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/// Trait-idiomatic *owned-input, [`std::rc::Rc<str>`] output* forward
1327/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1328/// closed-set fieldless typed enum — the single-threaded reference-
1329/// counted peer of the paired owned-input
1330/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl (bca2ec8) on
1331/// the sibling atomically-reference-counted [`std::sync::Arc<str>`] axis.
1332/// Routes byte-for-byte through the substrate-primitive
1333/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1334/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`.
1335///
1336/// Rust's standard library carries `impl From<&str> for std::rc::Rc<str>`
1337/// and `impl From<String> for std::rc::Rc<str>` but no blanket
1338/// `impl<T: AsRef<str>> From<T> for std::rc::Rc<str>` (nor a `From<&T>`
1339/// blanket), and the [`std::sync::Arc<str>`] and [`std::rc::Rc<str>`]
1340/// trait tables are disjoint — so a single-threaded caixa-operator
1341/// reconciliation pass that shares the `:supervisor :estrategia` wire
1342/// byte-string across intra-reconcile-loop tree nodes through the cheaper
1343/// non-atomic [`std::rc::Rc<str>`] refcount (the atomically-reference-
1344/// counted [`std::sync::Arc<str>`] return-shape cannot provide within a
1345/// single-threaded reconciliation pass without paying the atomic-fence
1346/// cost the [`std::rc::Rc<str>`] axis skips by construction) reaches
1347/// the substrate primitive through this impl and no other.
1348///
1349/// Extends the trait-idiomatic [`std::rc::Rc<str>`] forward-projection
1350/// axis onto the first M2 OTP-shape closed-set fieldless typed enum peer
1351/// on the caixa surface (`:supervisor :estrategia`), matching the
1352/// trajectory the M3-mesh-primitive-defining
1353/// [`crate::aplicacao::PlacementStrategy`],
1354/// [`crate::aplicacao::RateLimitUnit`], and
1355/// [`crate::aplicacao::WitShape`] (1afb5f4) peers established, and the
1356/// eighth in-caixa-core closed-set fieldless typed-enum peer to pick up
1357/// the axis (after [`crate::CaixaKind`],
1358/// [`crate::dialeto::CaixaDialeto`], [`crate::dep::DepList`],
1359/// [`crate::version::CaixaVersion`], [`crate::render::PathShapeViolation`],
1360/// and the three M3-mesh-primitive-defining peers above).
1361///
1362/// Pinned load-bearing by
1363/// [`tests::restart_strategy_from_into_rc_str_routes_through_as_str_accessor`]
1364/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1365/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1366/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1367/// axis byte-parity pins against the sibling owned-input `{&'static
1368/// str, String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
1369/// return-shape axes).
1370impl From<RestartStrategy> for std::rc::Rc<str> {
1371 fn from(strategy: RestartStrategy) -> std::rc::Rc<str> {
1372 std::rc::Rc::<str>::from(strategy.as_str())
1373 }
1374}
1375
1376/// Trait-idiomatic *borrowed-input, [`std::rc::Rc<str>`] output* forward
1377/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1378/// closed-set fieldless typed enum — the borrowed-input companion to the
1379/// paired owned-input [`From<RestartStrategy> for std::rc::Rc<str>`]
1380/// impl immediately above, closing the `{Self, &Self}` input-shape
1381/// corner of the [`std::rc::Rc<str>`] axis on the first M2 OTP-shape
1382/// closed-set fieldless typed enum peer on the caixa surface. Routes
1383/// byte-for-byte through the substrate-primitive
1384/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1385/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`, so a
1386/// `RestartStrategy::ALL.iter().map(std::rc::Rc::<str>::from)`-shaped
1387/// pipe (whose iterator over `&'static [RestartStrategy]` yields
1388/// `&RestartStrategy` by construction) reaches the same four-arm lifted
1389/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1390/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1391/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1392/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1393/// roster the paired owned-input axis and the sibling `{Self, &Self} ×
1394/// {&'static str, String, Cow<'static, str>, Box<str>,
1395/// std::sync::Arc<str>}` forward-projection corner already return.
1396///
1397/// Rust's standard library carries no blanket
1398/// `impl<T: AsRef<str>> From<&T> for std::rc::Rc<str>` (nor a `Copy`-
1399/// based `impl<T: Copy, U: From<T>> From<&T> for U`), so this borrowed-
1400/// input axis is a distinct trait-idiomatic surface — without it, the
1401/// `.iter().map(std::rc::Rc::<str>::from)` pipe would force a spurious
1402/// [`Copy`] deref or a `.copied()` restatement whose type bounds have
1403/// no compile-time link back to the substrate primitive.
1404///
1405/// Pinned load-bearing by
1406/// [`tests::restart_strategy_from_borrowed_into_rc_str_routes_through_as_str_accessor`]
1407/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1408/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1409/// surface, plus a blanket-derived [`Into`] shape witness, a cross-axis
1410/// partition pin against the paired owned-input
1411/// [`From<RestartStrategy> for std::rc::Rc<str>`] and the sibling
1412/// borrowed-input `{&'static str, String, Cow<'static, str>, Box<str>,
1413/// std::sync::Arc<str>}` return-shape axes, and a
1414/// `.iter().map(std::rc::Rc::<str>::from)` pipe witness over
1415/// [`RestartStrategy::ALL`] that resolves through the borrowed-input
1416/// axis without a spurious [`Copy`] deref).
1417impl From<&RestartStrategy> for std::rc::Rc<str> {
1418 fn from(strategy: &RestartStrategy) -> std::rc::Rc<str> {
1419 std::rc::Rc::<str>::from(strategy.as_str())
1420 }
1421}
1422
1423/// Substrate-canonical [`AsRef<[u8]>`] byte-view projection on the M2
1424/// OTP-shape sibling-restart [`RestartStrategy`] closed-set fieldless
1425/// typed enum — routes byte-for-byte through the substrate-primitive
1426/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1427/// [`str::as_bytes`] on the returned `&'static str`, so any future
1428/// consumer that binds a [`RestartStrategy`] through a standard-library
1429/// `<T: AsRef<[u8]>>` trait bound reaches the same four-arm lifted
1430/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1431/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1432/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1433/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
1434/// `PascalCase` wire byte-string emit-set the paired sibling
1435/// [`AsRef<str>`] (5b828ed) / [`std::fmt::Display`] /
1436/// [`RestartStrategy::as_str`] str-view surfaces and every
1437/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>,
1438/// std::sync::Arc<str>}` reverse-projection corner already return —
1439/// through the byte-view axis, which the str-view axes cannot express.
1440///
1441/// Rust's standard library carries `impl AsRef<[u8]> for str` and
1442/// `impl AsRef<[u8]> for String`, so the two-hop composition
1443/// `strategy.as_str().as_bytes()` (or, equivalently,
1444/// `AsRef::<str>::as_ref(&strategy).as_bytes()`) is reachable through
1445/// the pre-existing str-view axis alone. But that two-hop shape has no
1446/// compile-time link back to the byte-projection axis, forces every
1447/// downstream `<T: AsRef<[u8]>>`-bound consumer to open-code the
1448/// two-hop composition at every call site, and admits a silent split
1449/// whenever a future call site takes a sibling reverse-projection axis
1450/// whose `.as_bytes()` byte-tail carries no compile-time byte-view
1451/// surface (`Display` returns a formatter, `String` / `Box<str>` /
1452/// `Arc<str>` allocate). The lifted single-hop impl closes the
1453/// byte-view axis so every future `<T: AsRef<[u8]>>`-bound consumer
1454/// reaches the substrate primitive through one trait dispatch, and
1455/// every future arm addition (an OTP-`rest_for_all` fifth arm the
1456/// theory
1457/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1458/// might reach for once the four canonical OTP strategies stop covering
1459/// the substrate's discovered load-shape) grows the byte-view axis
1460/// through one edit on the substrate-primitive `as_str` accessor, not a
1461/// coordinated rewrite across every future `<T: AsRef<[u8]>>`-bound
1462/// consumer's arm-set.
1463///
1464/// The primary compounding target is the same `caixa-lacre` BLAKE3
1465/// content-address closure the peer [`crate::CaixaKind`] (69d8d86),
1466/// [`crate::dialeto::CaixaDialeto`] (8151347),
1467/// [`crate::dep::DepList`] (05ffaca),
1468/// [`crate::aplicacao::PlacementStrategy`] (daa8705), and
1469/// [`crate::aplicacao::RateLimitUnit`] (4867e0f) `AsRef<[u8]>` impls
1470/// open onto: [`blake3::hash`] and [`blake3::Hasher::update`] both bind
1471/// their input through `impl AsRef<[u8]>`, so any future per-supervisor
1472/// content-address tag that folds an `:estrategia` discriminator
1473/// byte-tag into the [`crate::Lacre`] closure (a hypothetical
1474/// `hasher.update(estrategia);`-shape composition partitioning the
1475/// four OTP restart-topology closures at content-address time so
1476/// downstream `Lacre` consumers key per-strategy reconciliation caches
1477/// off the typed discriminator rather than the sibling `&'static str`
1478/// wire scalar) reaches the substrate-primitive `as_str` accessor
1479/// through this impl and no other.
1480///
1481/// Opens the trait-idiomatic byte-view axis on the first M2 OTP-shape
1482/// closed-set fieldless typed enum peer on the caixa surface
1483/// (`:supervisor :estrategia`), extending the substrate-wide byte-view
1484/// campaign the sibling [`crate::CaixaKind`] first-mover (69d8d86)
1485/// opened onto the fifth in-caixa-core enum peer. The remaining
1486/// in-caixa-core closed-set fieldless typed-enum peers
1487/// ([`RestartPolicy`], [`crate::aplicacao::WitShape`],
1488/// [`crate::upgrade::UpgradeInstruction`],
1489/// [`crate::render::PathShapeViolation`]) each carry the same
1490/// [`AsRef<str>`] + `pub const fn as_str` substrate-primitive accessor
1491/// discipline, so a future extension of the byte-view axis onto each
1492/// peer reaches through one impl per enum keyed to that peer's
1493/// substrate-primitive accessor.
1494///
1495/// Pinned load-bearing by
1496/// [`tests::restart_strategy_as_ref_bytes_routes_through_as_str_accessor`]
1497/// (fail-before-pass-after byte-parity pin against
1498/// [`RestartStrategy::as_str`] `.as_bytes()` across the four-arm
1499/// [`RestartStrategy::ALL`] emit-set, cross-axis witness against the
1500/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
1501/// [`RestartStrategy::as_str`] axes' `.as_bytes()` byte-tails,
1502/// cross-axis witness against the paired reverse-projection
1503/// `{&'static str, String, Cow<'static, str>, Box<str>,
1504/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
1505/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
1506/// byte-input function accepts a [`RestartStrategy`] directly through
1507/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
1508/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
1509/// consumer axis to reach the caixa-lacre compounding target). Any
1510/// future silent detour that routes the byte-view impl off the
1511/// substrate-primitive [`RestartStrategy::as_str`] accessor (a per-arm
1512/// inline `b"OneForOne".as_slice()`-shaped re-inlining that opens a
1513/// compile-time link to the un-lifted arm-literal, a swap onto the
1514/// kebab-case [`gen_platform::Discriminant`] catalog identity that
1515/// would collide the wire axis with the dispatcher-catalog axis) trips
1516/// at caixa-core test time rather than at a downstream byte-consumer's
1517/// silent split.
1518impl AsRef<[u8]> for RestartStrategy {
1519 fn as_ref(&self) -> &[u8] {
1520 self.as_str().as_bytes()
1521 }
1522}
1523
1524/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
1525/// reverse projection on the first M2 OTP-shape closed-set fieldless
1526/// typed enum peer on the caixa surface ([`RestartStrategy`]) — the
1527/// byte-mirror of the [`From<RestartStrategy> for String`] str-owned
1528/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
1529/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
1530/// (cd4c4e0) lifted on this same enum. Routes byte-for-byte through
1531/// the substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1532/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
1533/// consumer that binds a [`RestartStrategy`] through the standard-
1534/// library `impl From<RestartStrategy> for Vec<u8>` axis
1535/// (equivalently `<T: Into<Vec<u8>>>`) — a future
1536/// [`std::io::Write::write_all`]-shape per-supervisor audit-log byte-
1537/// sink whose input parameter is an owned [`Vec<u8>`] payload, a
1538/// future `bytes::Bytes::from(Vec::<u8>::from(strategy))` composer
1539/// folding the per-arm sibling-restart-topology byte-tag into the
1540/// [`bytes::Bytes`] framing surface, a future
1541/// `hasher.update(&Vec::<u8>::from(strategy))`-shape BLAKE3 content-
1542/// address closure that needs the owned byte-tail buffered before
1543/// folding into the [`crate::Lacre`] closure body, a future per-
1544/// strategy protobuf/CBOR/msgpack payload composer whose framer takes
1545/// an owned [`Vec<u8>`] rather than a borrowed byte-slice — reaches
1546/// the substrate primitive through one trait dispatch rather than an
1547/// open-coded per-call-site `strategy.as_str().as_bytes().to_vec()`
1548/// composition whose type bounds have no compile-time link back to
1549/// the substrate primitive.
1550///
1551/// Extends the substrate-wide trait-idiomatic byte-owned reverse-
1552/// projection axis onto the first M2-OTP-shape closed-set fieldless
1553/// typed-enum peer, matching the trajectory the first-mover
1554/// [`crate::CaixaKind`] `From<{Self, &Self}> for Vec<u8>` lift
1555/// (b245fd6), the second-mover [`crate::dialeto::CaixaDialeto`] lift
1556/// (4cceaf5), and the third-mover [`crate::dep::DepList`] lift
1557/// (e974ca2) established across the caixa-core-internal tier. Every
1558/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
1559/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1560/// might reach for once the four canonical OTP strategies stop
1561/// covering the substrate's discovered load-shape) grows the byte-
1562/// owned axis through one edit on the substrate-primitive
1563/// [`RestartStrategy::as_str`] accessor, mirroring the discipline the
1564/// paired [`AsRef<[u8]>`] borrowed byte-view axis campaign already
1565/// tracked across every closed-set fieldless typed enum peer on the
1566/// substrate.
1567///
1568/// Pinned load-bearing by
1569/// [`tests::restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
1570/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1571/// four-arm [`RestartStrategy::ALL`] emit-set binding the byte-owned
1572/// reverse-projection axis against the paired [`AsRef<[u8]>`]
1573/// borrowed byte-view axis and the str-owned reverse-projection
1574/// family (`String`, `Cow<'static, str>`, `Box<str>`,
1575/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
1576/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
1577/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
1578/// witness on both owned and borrowed input shapes).
1579impl From<RestartStrategy> for Vec<u8> {
1580 fn from(strategy: RestartStrategy) -> Vec<u8> {
1581 strategy.as_str().as_bytes().to_vec()
1582 }
1583}
1584
1585/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
1586/// owned reverse projection on the first M2 OTP-shape closed-set
1587/// fieldless typed enum peer on the caixa surface
1588/// ([`RestartStrategy`]) — the borrowed-input peer of
1589/// [`From<RestartStrategy> for Vec<u8>`], closing the
1590/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
1591/// axis in one lift. Routes byte-for-byte through the substrate-
1592/// primitive [`RestartStrategy::as_str`] `pub const fn` accessor so
1593/// every consumer that holds a borrowed [`&RestartStrategy`] and
1594/// needs an owned [`Vec<u8>`] — a future
1595/// `.iter().map(Vec::<u8>::from).collect()` pipe over
1596/// `&[RestartStrategy]` (whose iterator yields `&RestartStrategy`,
1597/// not `RestartStrategy`, so the owned-input axis alone forces every
1598/// call site through an explicit `.copied()` / spurious [`Copy`]
1599/// deref restatement rather than the direct trait-idiomatic
1600/// projection), a future admission-webhook rejection body composer
1601/// that walks [`RestartStrategy::ALL`] through an `Into<Vec<u8>>`-
1602/// bound per-arm byte-writer to surface the accepted `:estrategia`
1603/// set — reaches the substrate primitive through one trait dispatch
1604/// rather than a `Vec::<u8>::from(*strategy)` spurious-`Copy`-deref
1605/// restatement.
1606impl From<&RestartStrategy> for Vec<u8> {
1607 fn from(strategy: &RestartStrategy) -> Vec<u8> {
1608 strategy.as_str().as_bytes().to_vec()
1609 }
1610}
1611
1612/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, [u8]>`]
1613/// output* byte-owned reverse projection on the first M2 OTP-shape
1614/// closed-set fieldless typed enum peer on the caixa surface
1615/// ([`RestartStrategy`]) — the [`std::borrow::Cow<'static, [u8]>`] byte-
1616/// mirror of the paired [`From<RestartStrategy> for
1617/// std::borrow::Cow<'static, str>`] str-side impl (7dd28b3) and the
1618/// [`std::borrow::Cow<'static, [u8]>`] companion of the paired byte-
1619/// owned [`From<RestartStrategy> for Vec<u8>`] reverse-projection axis
1620/// immediately above. Routes byte-for-byte through the substrate-
1621/// primitive [`RestartStrategy::as_str`] `pub const fn` accessor via
1622/// [`std::borrow::Cow::Borrowed`]`(strategy.as_str().as_bytes())` — the
1623/// four `match` arms in [`Self::as_str`] resolve to
1624/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &'static str`
1625/// bodies, so `.as_bytes()` on each returns `&'static [u8]` by
1626/// construction, and the zero-alloc [`Cow::Borrowed`] arm is the
1627/// type-correct projection with no runtime allocation (mirroring the
1628/// paired [`Cow<'static, str>`] axis's own [`Cow::Borrowed`]
1629/// discipline on this same primitive; contrasts with the sibling
1630/// [`crate::CaixaVersion`] [`Cow<'static, [u8]>`] impl (baf7537), whose
1631/// wrapped [`String`] storage is a runtime heap allocation with no
1632/// `&'static [u8]` lifetime, forcing the [`Cow::Owned`] arm there).
1633///
1634/// Extends the substrate-wide trait-idiomatic byte-owned reverse-
1635/// projection matrix onto the first M2-OTP-shape closed-set fieldless
1636/// typed-enum peer at the second byte-owned axis, following the
1637/// trajectory the same axis walked on [`crate::CaixaVersion`]
1638/// (98d38ed on the `Vec<u8>` axis, baf7537 on the `Cow<'static, [u8]>`
1639/// axis).
1640impl From<RestartStrategy> for std::borrow::Cow<'static, [u8]> {
1641 fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, [u8]> {
1642 std::borrow::Cow::Borrowed(strategy.as_str().as_bytes())
1643 }
1644}
1645
1646/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, [u8]>`]
1647/// output* byte-owned reverse projection on the first M2 OTP-shape
1648/// closed-set fieldless typed enum peer on the caixa surface
1649/// ([`RestartStrategy`]) — the borrowed-input companion to the paired
1650/// owned-input [`From<RestartStrategy> for
1651/// std::borrow::Cow<'static, [u8]>`] impl immediately above, closing
1652/// the `{Self, &Self} → Cow<'static, [u8]>` byte-owned reverse-
1653/// projection family on this primitive at the borrowed-input corner.
1654/// Routes byte-for-byte through the same substrate-primitive
1655/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1656/// [`std::borrow::Cow::Borrowed`]`(strategy.as_str().as_bytes())` —
1657/// the [`Cow::Borrowed`] arm is reachable on both input axes because
1658/// [`Self::as_str`] returns `&'static str` regardless of the input
1659/// shape, so no runtime allocation is forced on either corner.
1660/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U
1661/// where U: From<T>` (nor an
1662/// `impl<T: AsRef<[u8]>> From<&T> for Cow<'static, [u8]>`), so every
1663/// closed-set fieldless typed enum peer that carries the paired
1664/// owned-input axis but not the borrowed-input axis forces every
1665/// borrowed call site through a spurious [`Copy`] deref
1666/// (`Cow::<'static, [u8]>::from(*strategy)`) or an open-coded
1667/// `Cow::Borrowed(strategy.as_str().as_bytes())` whose type bounds
1668/// have no compile-time link to the substrate primitive.
1669impl From<&RestartStrategy> for std::borrow::Cow<'static, [u8]> {
1670 fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, [u8]> {
1671 std::borrow::Cow::Borrowed(strategy.as_str().as_bytes())
1672 }
1673}
1674
1675/// Trait-idiomatic *owned-input, [`Box<[u8]>`] output* byte-owned reverse
1676/// projection on the first M2-OTP-shape closed-set fieldless typed enum peer
1677/// on the caixa surface ([`RestartStrategy`]) — the [`Box<[u8]>`] companion
1678/// to the paired owned-input [`From<RestartStrategy> for Vec<u8>`] (98d38ed)
1679/// and [`From<RestartStrategy> for std::borrow::Cow<'static, [u8]>`]
1680/// (7f81539) reverse-projection impls on this same primitive, mirroring the
1681/// paired string-side [`From<RestartStrategy> for Box<str>`] (69ef45c)
1682/// forward-projection axis onto the byte-family side of the reverse-
1683/// projection matrix, and tracking the trajectory the same axis walked on
1684/// the sibling [`crate::CaixaVersion`] String-wrapper newtype primitive
1685/// (703b2fd on the [`Box<[u8]>`] corner). Routes byte-for-byte through the
1686/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn` accessor
1687/// via [`Box::<[u8]>::from`] on the returned `&'static str`'s
1688/// [`str::as_bytes`] — the four `match` arms in [`Self::as_str`] resolve to
1689/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &'static str`
1690/// bodies, so `.as_bytes()` returns `&'static [u8]` by construction, and
1691/// the standard-library [`Box::<[u8]>::from(&[u8])`] impl allocates a fit-
1692/// to-length boxed byte slice in one heap allocation without an
1693/// intermediary [`Vec<u8>`].
1694///
1695/// A future consumer that wants a [`Box<[u8]>`]-typed handle on a
1696/// [`RestartStrategy`] — a per-supervisor struct field typed [`Box<[u8]>`]
1697/// rather than [`Vec<u8>`] to trim the twenty-four-byte pointer + length +
1698/// capacity header down to the sixteen-byte pointer + length pair (a shape
1699/// the substrate acknowledges as the natural fixed-length storage for
1700/// once-written-never-mutated wire-scalar byte-tails held across the whole
1701/// operator reconciliation cycle), a future
1702/// `HashMap::<Box<[u8]>, _>::from_iter([(estrategia.into(), _)])`
1703/// per-strategy lookup where the map's key type is [`Box<[u8]>`] rather than
1704/// owned [`Vec<u8>`] so the map's per-entry key-slot carries the sixteen-
1705/// byte [`Box<[u8]>`] header instead of the twenty-four-byte [`Vec<u8>`]
1706/// header, a future M4 admission-webhook rejection body whose per-arm
1707/// error-frame composer accepts a [`Box<[u8]>`] intermediate for the same
1708/// reason — reaches the wire byte-string through this one dispatch, without
1709/// the pre-lift `Vec::<u8>::from(strategy).into_boxed_slice()` double-hop
1710/// that would still allocate through the same [`Vec<u8>`] intermediary on
1711/// the way to the same [`Box<[u8]>`] slot but with one extra header-slot
1712/// round-trip.
1713///
1714/// Peer of the paired owned-input [`From<RestartStrategy> for Vec<u8>`]
1715/// (98d38ed) and [`From<RestartStrategy> for std::borrow::Cow<'static,
1716/// [u8]>`] (7f81539) impls on the same primitive — the sibling
1717/// [`Vec<u8>`] axis returns a fresh heap allocation via
1718/// [`str::as_bytes`]`.to_vec()`; the sibling [`Cow<'static, [u8]>`] axis
1719/// binds the zero-alloc [`Cow::Borrowed`] arm on the same `&'static [u8]`
1720/// byte-tail; this axis allocates a fit-to-length boxed byte slice via
1721/// [`Box::<[u8]>::from(&[u8])`], preserving the fixed-length-storage
1722/// discipline the substrate opens on its byte-family reverse-projection
1723/// matrix across every closed-set fieldless typed enum peer.
1724///
1725/// Extends the substrate-wide trait-idiomatic *owned-input* byte-family
1726/// reverse-projection matrix onto the first M2-OTP-shape closed-set
1727/// fieldless typed enum peer at the [`Box<[u8]>`] corner — mirroring the
1728/// trajectory the same axis walked on the sibling [`crate::CaixaVersion`]
1729/// String-wrapper newtype primitive (98d38ed on [`Vec<u8>`], baf7537 on
1730/// [`Cow<'static, [u8]>`], 703b2fd on [`Box<[u8]>`], 3d5fc43 on
1731/// [`std::sync::Arc<[u8]>`], 6034943 on [`std::rc::Rc<[u8]>`]) and the
1732/// paired string-family [`Box<str>`] axis (69ef45c on the string-side).
1733/// Rust's standard library does not derive `From<Self> for Box<[u8]>` from
1734/// `From<Self> for Vec<u8>` (nor from `From<Self> for Cow<'static, [u8]>`),
1735/// so every closed-set fieldless typed enum peer that carries the paired
1736/// reverse [`Vec<u8>`] axis but not the paired [`Box<[u8]>`] axis forces
1737/// every [`Box<[u8]>`]-typed call site through a
1738/// `Vec::<u8>::from(strategy).into_boxed_slice()` intermediary allocation
1739/// whose bounds carry no compile-time link back to the substrate primitive.
1740///
1741/// Pinned load-bearing by
1742/// [`tests::restart_strategy_from_into_owned_box_bytes_routes_through_as_str_accessor`]
1743/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()`
1744/// across the four-arm [`RestartStrategy::ALL`] accept-set on the owned-
1745/// input surface, plus a cross-axis witness against the paired owned-input
1746/// [`From<RestartStrategy> for Vec<u8>`] and
1747/// [`From<RestartStrategy> for Cow<'static, [u8]>`] byte-owned reverse-
1748/// projection axes and the paired string-side [`Box<str>`] axis on every
1749/// canonical `PascalCase` scalar, closing the "owned-input into `Vec<u8>`
1750/// vs. `Cow<'static, [u8]>` vs. `Box<[u8]>`" three-corner partition on the
1751/// same wire byte-string).
1752impl From<RestartStrategy> for Box<[u8]> {
1753 fn from(strategy: RestartStrategy) -> Box<[u8]> {
1754 Box::<[u8]>::from(strategy.as_str().as_bytes())
1755 }
1756}
1757
1758/// Trait-idiomatic *borrowed-input, [`Box<[u8]>`] output* byte-owned reverse
1759/// projection on the first M2-OTP-shape closed-set fieldless typed enum peer
1760/// on the caixa surface ([`RestartStrategy`]) — the borrowed-input companion
1761/// to the paired owned-input [`From<RestartStrategy> for Box<[u8]>`] impl
1762/// immediately above, closing the `{Self, &Self} → Box<[u8]>` byte-owned
1763/// reverse-projection family on this primitive at the borrowed-input corner.
1764/// Routes byte-for-byte through the same substrate-primitive
1765/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1766/// [`Box::<[u8]>::from`] on the returned `&'static str`'s [`str::as_bytes`]
1767/// — the [`Box<[u8]>`] allocation happens on both input axes because
1768/// [`Self::as_str`] returns `&'static str` regardless of the input shape,
1769/// so the borrowed-input peer reaches the same wire byte-string through the
1770/// same one-heap-allocation path the owned-input peer already carries.
1771///
1772/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U where
1773/// U: From<T>` (nor a `Copy`-based
1774/// `impl<T: Copy, U: From<T>> From<&T> for U`), so every closed-set
1775/// fieldless typed enum peer that carries the paired owned-input
1776/// [`Box<[u8]>`] axis but not the borrowed-input axis forces every borrowed
1777/// call site through a spurious [`Copy`] deref
1778/// (`Box::<[u8]>::from(*strategy)`) or an open-coded
1779/// `Box::<[u8]>::from(strategy.as_str().as_bytes())` whose type bounds have
1780/// no compile-time link to the substrate primitive.
1781///
1782/// Pinned load-bearing by
1783/// [`tests::restart_strategy_from_borrowed_into_owned_box_bytes_routes_through_as_str_accessor`]
1784/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()` via a
1785/// borrowed input across the four-arm [`RestartStrategy::ALL`] accept-set,
1786/// plus a source-survival witness against silent move-out and a cross-
1787/// corner partition pin between owned-input and borrowed-input on the same
1788/// wire byte-string through the [`Box<[u8]>`] axis).
1789impl From<&RestartStrategy> for Box<[u8]> {
1790 fn from(strategy: &RestartStrategy) -> Box<[u8]> {
1791 Box::<[u8]>::from(strategy.as_str().as_bytes())
1792 }
1793}
1794
1795/// Trait-idiomatic *owned-input, [`std::sync::Arc<[u8]>`] output* byte-owned
1796/// reverse projection on the first M2-OTP-shape closed-set fieldless typed
1797/// enum peer on the caixa surface ([`RestartStrategy`]) — the
1798/// atomically-refcounted byte-slice mirror of the paired owned-input
1799/// [`From<RestartStrategy> for std::sync::Arc<str>`] (1244+ str-side) impl on
1800/// the string-side reverse-projection matrix, and the fourth axis in the
1801/// byte-side reverse-projection matrix that already carries
1802/// [`From<RestartStrategy> for Vec<u8>`] (98d38ed-pair on this enum),
1803/// [`From<RestartStrategy> for std::borrow::Cow<'static, [u8]>`] (7f81539),
1804/// and [`From<RestartStrategy> for Box<[u8]>`] (e11150e). Routes byte-for-
1805/// byte through the substrate-primitive [`RestartStrategy::as_str`]
1806/// `pub const fn` accessor via [`std::sync::Arc::<[u8]>::from`] on the
1807/// returned `&'static str`'s [`str::as_bytes`] — the four `match` arms in
1808/// [`Self::as_str`] resolve to [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
1809/// `pub const &'static str` bodies, so `.as_bytes()` returns `&'static [u8]`
1810/// by construction, and the standard-library
1811/// [`std::sync::Arc::<[u8]>::from(&[u8])`] impl allocates a fresh
1812/// atomically-refcounted heap slab whose header carries the strong + weak
1813/// counters the [`std::sync::Arc<[u8]>`] layout requires in one heap
1814/// allocation without an intermediary [`Vec<u8>`] or [`Box<[u8]>`].
1815///
1816/// A future consumer that wants a [`std::sync::Arc<[u8]>`]-typed handle on
1817/// a [`RestartStrategy`] — a share-through-clone byte-tail held across a
1818/// per-supervisor `caixa-operator` reconcile task where every spawn point
1819/// wants a cheap `.clone()` on the strategy's byte view without each task
1820/// re-allocating its own [`Vec<u8>`] copy (the [`std::sync::Arc::clone`]
1821/// path bumps the atomic refcount in place and returns a pointer-width
1822/// handle), a future `HashMap::<std::sync::Arc<[u8]>, _>::from_iter`
1823/// per-strategy lookup keyed by the byte-tail across worker threads, a
1824/// future M4 admission-webhook decoder that materializes decoded
1825/// `spec.estrategia` byte-tails as [`std::sync::Arc<[u8]>`] slices so
1826/// downstream verdict-composer tasks share the immutable byte-tail without
1827/// a per-consumer [`Vec::<u8>::clone`] — reaches the wire byte-string
1828/// through this one dispatch, without the pre-lift
1829/// `Box::<[u8]>::from(strategy).into::<Arc<[u8]>>()` double-hop that would
1830/// still allocate the same [`Arc<[u8]>`] slab plus one intermediary
1831/// [`Box<[u8]>`] between the enum peer and the [`std::sync::Arc<[u8]>`]
1832/// slot.
1833///
1834/// Peer of the paired owned-input [`From<RestartStrategy> for Vec<u8>`],
1835/// [`From<RestartStrategy> for Cow<'static, [u8]>`], and
1836/// [`From<RestartStrategy> for Box<[u8]>`] impls on the same primitive —
1837/// the sibling [`Vec<u8>`] axis returns a fresh heap allocation via
1838/// [`str::as_bytes`]`.to_vec()`; the sibling [`Cow<'static, [u8]>`] axis
1839/// binds the zero-alloc [`Cow::Borrowed`] arm on the same `&'static [u8]`
1840/// byte-tail; the sibling [`Box<[u8]>`] axis allocates a fit-to-length
1841/// boxed byte slice via [`Box::<[u8]>::from(&[u8])`]; this axis allocates
1842/// an atomically-refcounted heap slab whose header carries the strong +
1843/// weak counters the [`std::sync::Arc<[u8]>`] layout requires. Rust's
1844/// standard library does not derive `From<Self> for Arc<[u8]>` from
1845/// `From<Self> for Box<[u8]>` (nor from `From<Self> for Vec<u8>`), so every
1846/// closed-set fieldless typed enum peer that carries the paired
1847/// [`Box<[u8]>`] axis but not the paired [`Arc<[u8]>`] axis forces every
1848/// [`Arc<[u8]>`]-typed call site through a
1849/// `Box::<[u8]>::from(strategy).into()` /
1850/// `Arc::<[u8]>::from(Vec::<u8>::from(strategy))` intermediary allocation
1851/// whose bounds carry no compile-time link back to the substrate primitive.
1852///
1853/// Extends the substrate-wide trait-idiomatic *owned-input* byte-family
1854/// reverse-projection matrix onto the first M2-OTP-shape closed-set
1855/// fieldless typed enum peer at the [`std::sync::Arc<[u8]>`] corner —
1856/// mirroring the trajectory the same axis walked on the sibling
1857/// [`crate::CaixaVersion`] String-wrapper newtype primitive (98d38ed on
1858/// [`Vec<u8>`], baf7537 on [`Cow<'static, [u8]>`], 703b2fd on [`Box<[u8]>`],
1859/// 3d5fc43 on [`std::sync::Arc<[u8]>`], 6034943 on [`std::rc::Rc<[u8]>`]).
1860///
1861/// Pinned load-bearing by
1862/// [`tests::restart_strategy_from_into_owned_arc_bytes_routes_through_as_str_accessor`]
1863/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()`
1864/// across the four-arm [`RestartStrategy::ALL`] accept-set on the owned-
1865/// input surface, plus a cross-axis witness against the paired owned-input
1866/// [`From<RestartStrategy> for Vec<u8>`],
1867/// [`From<RestartStrategy> for Cow<'static, [u8]>`], and
1868/// [`From<RestartStrategy> for Box<[u8]>`] byte-owned reverse-projection
1869/// axes on every canonical `PascalCase` scalar, closing the "owned-input
1870/// into `Vec<u8>` vs. `Cow<'static, [u8]>` vs. `Box<[u8]>` vs. `Arc<[u8]>`"
1871/// four-corner partition on the same wire byte-string).
1872impl From<RestartStrategy> for std::sync::Arc<[u8]> {
1873 fn from(strategy: RestartStrategy) -> std::sync::Arc<[u8]> {
1874 std::sync::Arc::<[u8]>::from(strategy.as_str().as_bytes())
1875 }
1876}
1877
1878/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<[u8]>`] output*
1879/// byte-owned reverse projection on the first M2-OTP-shape closed-set
1880/// fieldless typed enum peer on the caixa surface ([`RestartStrategy`]) —
1881/// the borrowed-input companion to the paired owned-input
1882/// [`From<RestartStrategy> for std::sync::Arc<[u8]>`] impl immediately
1883/// above, closing the `{Self, &Self} → std::sync::Arc<[u8]>` byte-owned
1884/// reverse-projection family on this primitive at the borrowed-input
1885/// corner. Routes byte-for-byte through the same substrate-primitive
1886/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1887/// [`std::sync::Arc::<[u8]>::from`] on the returned `&'static str`'s
1888/// [`str::as_bytes`] — the [`std::sync::Arc<[u8]>`] allocation happens on
1889/// both input axes because [`Self::as_str`] returns `&'static str`
1890/// regardless of the input shape, so the borrowed-input peer reaches the
1891/// same wire byte-string through the same one-heap-allocation path the
1892/// owned-input peer already carries.
1893///
1894/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U where
1895/// U: From<T>` (nor a `Copy`-based
1896/// `impl<T: Copy, U: From<T>> From<&T> for U`), so every closed-set
1897/// fieldless typed enum peer that carries the paired owned-input
1898/// [`std::sync::Arc<[u8]>`] axis but not the borrowed-input axis forces
1899/// every borrowed call site through a spurious [`Copy`] deref
1900/// (`std::sync::Arc::<[u8]>::from(*strategy)`) or an open-coded
1901/// `std::sync::Arc::<[u8]>::from(strategy.as_str().as_bytes())` whose type
1902/// bounds have no compile-time link to the substrate primitive.
1903///
1904/// Pinned load-bearing by
1905/// [`tests::restart_strategy_from_borrowed_into_owned_arc_bytes_routes_through_as_str_accessor`]
1906/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()` via a
1907/// borrowed input across the four-arm [`RestartStrategy::ALL`] accept-set,
1908/// plus a source-survival witness against silent move-out and a cross-
1909/// corner partition pin between owned-input and borrowed-input on the same
1910/// wire byte-string through the [`std::sync::Arc<[u8]>`] axis).
1911impl From<&RestartStrategy> for std::sync::Arc<[u8]> {
1912 fn from(strategy: &RestartStrategy) -> std::sync::Arc<[u8]> {
1913 std::sync::Arc::<[u8]>::from(strategy.as_str().as_bytes())
1914 }
1915}
1916
1917/// Trait-idiomatic *owned-input, [`std::rc::Rc<[u8]>`] output* byte-owned
1918/// reverse projection on the first M2-OTP-shape closed-set fieldless typed
1919/// enum peer on the caixa surface ([`RestartStrategy`]) — the
1920/// single-threaded-refcounted byte-slice mirror of the paired owned-input
1921/// [`From<RestartStrategy> for std::rc::Rc<str>`] (1370+ str-side) impl on
1922/// the string-side reverse-projection matrix, and the fifth (and final)
1923/// axis on the byte-side reverse-projection matrix that already carries
1924/// [`From<RestartStrategy> for Vec<u8>`], [`From<RestartStrategy> for
1925/// std::borrow::Cow<'static, [u8]>`] (7f81539), [`From<RestartStrategy>
1926/// for Box<[u8]>`] (e11150e), and [`From<RestartStrategy> for
1927/// std::sync::Arc<[u8]>`] (98da8f6). Routes byte-for-byte through the
1928/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn` accessor
1929/// via [`std::rc::Rc::<[u8]>::from`] on the returned `&'static str`'s
1930/// [`str::as_bytes`] — the four `match` arms in [`Self::as_str`] resolve
1931/// to [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &'static str`
1932/// bodies, so `.as_bytes()` returns `&'static [u8]` by construction, and
1933/// the standard-library [`std::rc::Rc::<[u8]>::from(&[u8])`] impl allocates
1934/// a fresh single-threaded-refcounted heap slab whose header carries the
1935/// non-atomic strong + weak counters the [`std::rc::Rc<[u8]>`] layout
1936/// requires in one heap allocation without an intermediary [`Vec<u8>`],
1937/// [`Box<[u8]>`], or [`std::sync::Arc<[u8]>`].
1938///
1939/// A future consumer that wants a [`std::rc::Rc<[u8]>`]-typed handle on
1940/// a [`RestartStrategy`] — a single-threaded `feira lint` per-caixa
1941/// diagnostic table whose per-column payload carries the strategy's
1942/// byte-view through a chain of Nord-themed emitters via the pointer-
1943/// width [`std::rc::Rc::clone`] handle (a non-atomic refcount bump,
1944/// cheaper than the paired atomic increment on the sibling
1945/// [`std::sync::Arc<[u8]>`] axis by a measurable margin on hot
1946/// single-threaded call sites), a future single-threaded
1947/// `HashMap::<std::rc::Rc<[u8]>, _>::from_iter` per-strategy lookup keyed
1948/// by the byte-tail across the `feira supervisor --estrategia …`
1949/// composer's per-arg cache, a future non-`Send` planner that
1950/// materializes decoded `spec.estrategia` byte-tails as
1951/// [`std::rc::Rc<[u8]>`] slices so downstream single-threaded verdict
1952/// composers share the immutable byte-tail without a per-consumer
1953/// [`Vec::<u8>::clone`] — reaches the wire byte-string through this one
1954/// dispatch, without the pre-lift
1955/// `Box::<[u8]>::from(strategy).into::<Rc<[u8]>>()` /
1956/// `Rc::<[u8]>::from(Vec::<u8>::from(strategy))` double-hop that would
1957/// still allocate the same [`Rc<[u8]>`] slab plus one intermediary
1958/// [`Box<[u8]>`] or [`Vec<u8>`] between the enum peer and the
1959/// [`std::rc::Rc<[u8]>`] slot.
1960///
1961/// Peer of the paired owned-input [`From<RestartStrategy> for Vec<u8>`],
1962/// [`From<RestartStrategy> for Cow<'static, [u8]>`],
1963/// [`From<RestartStrategy> for Box<[u8]>`], and
1964/// [`From<RestartStrategy> for std::sync::Arc<[u8]>`] impls on the same
1965/// primitive — the sibling [`Vec<u8>`] axis returns a fresh heap
1966/// allocation via [`str::as_bytes`]`.to_vec()`; the sibling
1967/// [`Cow<'static, [u8]>`] axis binds the zero-alloc [`Cow::Borrowed`]
1968/// arm on the same `&'static [u8]` byte-tail; the sibling [`Box<[u8]>`]
1969/// axis allocates a fit-to-length boxed byte slice via
1970/// [`Box::<[u8]>::from(&[u8])`]; the sibling [`std::sync::Arc<[u8]>`]
1971/// axis allocates an atomically-refcounted heap slab; this axis
1972/// allocates a single-threaded-refcounted heap slab whose header carries
1973/// the non-atomic strong + weak counters the [`std::rc::Rc<[u8]>`]
1974/// layout requires. Rust's standard library does not derive
1975/// `From<Self> for Rc<[u8]>` from `From<Self> for Arc<[u8]>` (the two
1976/// layouts share the same on-disk shape but the trait tables are
1977/// disjoint, and no blanket `impl<T> From<T> for Rc<[u8]> where
1978/// Arc<[u8]>: From<T>` exists in `core`), so every closed-set fieldless
1979/// typed enum peer that carries the paired [`Arc<[u8]>`] axis but not
1980/// the paired [`Rc<[u8]>`] axis forces every single-threaded
1981/// [`Rc<[u8]>`]-typed call site through a
1982/// `Arc::<[u8]>::from(strategy).into()` /
1983/// `Rc::<[u8]>::from(Vec::<u8>::from(strategy))` double-allocation
1984/// detour whose bounds carry no compile-time link back to the substrate
1985/// primitive.
1986///
1987/// Closes the trait-idiomatic *owned-input* byte-family reverse-
1988/// projection matrix on the first M2-OTP-shape closed-set fieldless
1989/// typed enum peer at the [`std::rc::Rc<[u8]>`] corner — completing the
1990/// full `{Vec<u8>, Cow<'static, [u8]>, Box<[u8]>, Arc<[u8]>, Rc<[u8]>}`
1991/// five-corner partition on [`RestartStrategy`], mirroring the trajectory
1992/// the same axis walked on the sibling [`crate::CaixaVersion`]
1993/// String-wrapper newtype primitive (98d38ed on [`Vec<u8>`], baf7537 on
1994/// [`Cow<'static, [u8]>`], 703b2fd on [`Box<[u8]>`], 3d5fc43 on
1995/// [`std::sync::Arc<[u8]>`], 6034943 on [`std::rc::Rc<[u8]>`]).
1996///
1997/// Pinned load-bearing by
1998/// [`tests::restart_strategy_from_into_owned_rc_bytes_routes_through_as_str_accessor`]
1999/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()`
2000/// across the four-arm [`RestartStrategy::ALL`] accept-set on the owned-
2001/// input surface, plus a cross-axis witness against the paired owned-
2002/// input [`From<RestartStrategy> for Vec<u8>`], [`From<RestartStrategy>
2003/// for Cow<'static, [u8]>`], [`From<RestartStrategy> for Box<[u8]>`],
2004/// and [`From<RestartStrategy> for std::sync::Arc<[u8]>`] byte-owned
2005/// reverse-projection axes on every canonical `PascalCase` scalar,
2006/// closing the "owned-input into `Vec<u8>` vs. `Cow<'static, [u8]>` vs.
2007/// `Box<[u8]>` vs. `Arc<[u8]>` vs. `Rc<[u8]>`" five-corner partition on
2008/// the same wire byte-string).
2009impl From<RestartStrategy> for std::rc::Rc<[u8]> {
2010 fn from(strategy: RestartStrategy) -> std::rc::Rc<[u8]> {
2011 std::rc::Rc::<[u8]>::from(strategy.as_str().as_bytes())
2012 }
2013}
2014
2015/// Trait-idiomatic *borrowed-input, [`std::rc::Rc<[u8]>`] output*
2016/// byte-owned reverse projection on the first M2-OTP-shape closed-set
2017/// fieldless typed enum peer on the caixa surface ([`RestartStrategy`]) —
2018/// the borrowed-input companion to the paired owned-input
2019/// [`From<RestartStrategy> for std::rc::Rc<[u8]>`] impl immediately
2020/// above, closing the `{Self, &Self} → std::rc::Rc<[u8]>` byte-owned
2021/// reverse-projection family on this primitive at the borrowed-input
2022/// corner. Routes byte-for-byte through the same substrate-primitive
2023/// [`RestartStrategy::as_str`] `pub const fn` accessor via
2024/// [`std::rc::Rc::<[u8]>::from`] on the returned `&'static str`'s
2025/// [`str::as_bytes`] — the [`std::rc::Rc<[u8]>`] allocation happens on
2026/// both input axes because [`Self::as_str`] returns `&'static str`
2027/// regardless of the input shape, so the borrowed-input peer reaches the
2028/// same wire byte-string through the same one-heap-allocation path the
2029/// owned-input peer already carries.
2030///
2031/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U where
2032/// U: From<T>` (nor a `Copy`-based
2033/// `impl<T: Copy, U: From<T>> From<&T> for U`), so every closed-set
2034/// fieldless typed enum peer that carries the paired owned-input
2035/// [`std::rc::Rc<[u8]>`] axis but not the borrowed-input axis forces
2036/// every borrowed call site through a spurious [`Copy`] deref
2037/// (`std::rc::Rc::<[u8]>::from(*strategy)`) or an open-coded
2038/// `std::rc::Rc::<[u8]>::from(strategy.as_str().as_bytes())` whose type
2039/// bounds have no compile-time link to the substrate primitive.
2040///
2041/// Pinned load-bearing by
2042/// [`tests::restart_strategy_from_borrowed_into_owned_rc_bytes_routes_through_as_str_accessor`]
2043/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()` via a
2044/// borrowed input across the four-arm [`RestartStrategy::ALL`] accept-set,
2045/// plus a source-survival witness against silent move-out and a cross-
2046/// corner partition pin between owned-input and borrowed-input on the same
2047/// wire byte-string through the [`std::rc::Rc<[u8]>`] axis).
2048impl From<&RestartStrategy> for std::rc::Rc<[u8]> {
2049 fn from(strategy: &RestartStrategy) -> std::rc::Rc<[u8]> {
2050 std::rc::Rc::<[u8]>::from(strategy.as_str().as_bytes())
2051 }
2052}
2053
2054/// Trait-idiomatic *borrowed byte-slice input* reverse projection on the
2055/// first M2-OTP-shape closed-set fieldless typed enum peer on the caixa
2056/// surface ([`RestartStrategy`]) — the byte-view mirror of the str-view
2057/// reverse-projection axis carried by the paired
2058/// [`TryFrom<&str> for RestartStrategy`] impl (which routes through the
2059/// substrate-primitive [`RestartStrategy::from_wire`] `Option<Self>`
2060/// accessor on the four-arm `PascalCase` accept-set the sibling
2061/// [`RestartStrategy::as_str`] emitter returns). Routes byte-for-byte
2062/// through the standard-library [`std::str::from_utf8`] UTF-8 validator
2063/// and then through [`RestartStrategy::from_wire`] so every consumer that
2064/// holds a borrowed [`&[u8]`] and needs to project it back into a typed
2065/// [`RestartStrategy`] — a future `bytes::Bytes::as_ref()`-fed reader
2066/// that parses a per-supervisor `:estrategia` `PascalCase` wire scalar
2067/// from an already-borrowed framing byte-tail (a
2068/// `tracing::field::valuable::Value::Bytes` recorder on the future
2069/// wasm-operator's per-supervisor sibling-restart-strategy diagnostic
2070/// emission path, a future audit-report re-loader binding a prior
2071/// [`RestartStrategy::as_str`] output from a mmap'd byte-slice back
2072/// through the typed enum for cross-run comparison), a future M4
2073/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook rejection
2074/// body that reads a `spec.estrategia` field off a raw HTTP body byte-
2075/// slice before UTF-8 validation commits allocation, a future generic
2076/// `<T: for<'a> TryFrom<&'a [u8]>>`-bound loader over any of the
2077/// substrate's closed-set typed enums — reaches the same four-arm
2078/// `PascalCase` wire accept-set the sibling method-named
2079/// [`RestartStrategy::from_wire`] resolver and the paired trait-idiomatic
2080/// [`TryFrom<&str>`] axis already resolve against, rather than an open-
2081/// coded per-call-site
2082/// `std::str::from_utf8(bytes).ok().and_then(RestartStrategy::from_wire)`
2083/// composition or a
2084/// `<RestartStrategy as TryFrom<&str>>::try_from(std::str::from_utf8(bytes)?)`
2085/// two-hop shape whose type bounds have no compile-time link to the
2086/// substrate primitive.
2087///
2088/// Extends the substrate-wide trait-idiomatic *byte-view reverse-
2089/// projection* family — opened on the structurally most fundamental
2090/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
2091/// 18d1940), extended onto the second caixa-core-internal peer
2092/// ([`crate::CaixaDialeto`], commit d102cb8) and the third
2093/// ([`crate::dep::DepList`], commit b8f25d5) — onto the first
2094/// M2-OTP-shape supervisor-slot closed-set fieldless typed enum peer,
2095/// tracking the "route through `from_wire` via `std::str::from_utf8`"
2096/// discipline the first-mover established. Rust's standard library
2097/// carries no blanket
2098/// `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a two-
2099/// hop composition through [`std::str::from_utf8`] + the paired
2100/// [`TryFrom<&str>`] axis is reachable at every call site but has no
2101/// compile-time link back to the byte-view reverse-projection axis.
2102/// Every remaining closed-set fieldless typed enum peer on the substrate
2103/// ([`RestartPolicy`], [`crate::aplicacao::PlacementStrategy`],
2104/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
2105/// and the outside-`caixa-core` peers `PathShapeViolation`,
2106/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2107/// `FerriteRuntime`) is a future target of the campaign, mirroring the
2108/// trajectory the closed byte-owned reverse-projection family walked
2109/// arm-by-arm onto each peer.
2110///
2111/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
2112/// `Option<Self>` return-shape's deliberate deferral of error typing and
2113/// the paired trait-idiomatic [`TryFrom<&str>`] axis's unit-error shape —
2114/// the caller picks the diagnostic form appropriate for its use site (a
2115/// future `feira supervisor --estrategia …` arg-parse composes its own
2116/// per-verb "unknown strategy: <arg> — accepted: {…}" message enumerating
2117/// [`RestartStrategy::WIRE_NAMES`]; a future admission-webhook rejection
2118/// body wraps the `Err(())` outcome with the accepted-set enumeration for
2119/// operator diagnostics; a `Result::map_err` at the call site lifts the
2120/// unit-error to a per-verb error type). Two rejection paths route
2121/// through the single unit-error: an invalid UTF-8 byte-sequence
2122/// ([`std::str::from_utf8`] returns `Err`) and a valid UTF-8 byte-string
2123/// that falls outside the four-arm `PascalCase` accept-set
2124/// ([`RestartStrategy::from_wire`] returns `None`) — both collapse onto
2125/// `Err(())` so the trait signature stays consistent with the sibling
2126/// str-view reverse axis, and a caller that needs to distinguish the two
2127/// failure modes composes [`std::str::from_utf8`] +
2128/// [`RestartStrategy::from_wire`] explicitly.
2129///
2130/// Pinned load-bearing by
2131/// [`tests::restart_strategy_try_from_bytes_routes_through_from_wire_accessor`]
2132/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
2133/// four-arm [`RestartStrategy::ALL`] accept-set on the borrowed byte-
2134/// slice surface, plus a cross-axis witness that the byte-view reverse
2135/// projection agrees with the paired [`TryFrom<&str>`] str-view reverse
2136/// axis on every accepted arm) and
2137/// [`tests::restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
2138/// (rejection witness against silent accept-set widening on both the
2139/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
2140/// rejection path — the latter includes the sibling kebab-case
2141/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
2142/// a caller that confuses the two axes trips here rather than at a
2143/// downstream K8s-CR round-trip miss).
2144impl TryFrom<&[u8]> for RestartStrategy {
2145 type Error = ();
2146
2147 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
2148 std::str::from_utf8(bytes)
2149 .ok()
2150 .and_then(Self::from_wire)
2151 .ok_or(())
2152 }
2153}
2154
2155/// Trait-idiomatic *owned byte-vec input* reverse projection on the first
2156/// M2-OTP-shape supervisor-slot closed-set fieldless typed enum peer on the
2157/// caixa surface ([`RestartStrategy`]) — the owned-input peer of
2158/// [`TryFrom<&[u8]> for RestartStrategy`], mirroring the closed
2159/// [`From<RestartStrategy> for Vec<u8>`] + [`From<&RestartStrategy> for
2160/// Vec<u8>`] byte-owned *forward*-projection pair on this same enum onto
2161/// the byte-owned *reverse*-projection axis. Routes byte-for-byte through
2162/// [`<Self as TryFrom<&[u8]>>::try_from`] on the [`Vec<u8>::as_slice`]
2163/// borrow, so the owned-input surface reaches the same
2164/// [`std::str::from_utf8`] + [`RestartStrategy::from_wire`] resolution
2165/// chain the borrowed-input peer already carries — one substrate-primitive
2166/// accessor, one trait dispatch, no per-consumer detour.
2167///
2168/// Rust's standard library carries no blanket
2169/// `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`, so a
2170/// consumer that holds an owned [`Vec<u8>`] and needs a typed
2171/// [`RestartStrategy`] otherwise picks between (a) an open-coded
2172/// `<RestartStrategy as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
2173/// every call site (whose type bounds have no compile-time link to the
2174/// byte-owned reverse-projection axis), (b) a two-hop
2175/// `String::from_utf8(bytes)` + [`RestartStrategy::from_wire`] composition
2176/// whose error surface leaks the standard-library
2177/// [`std::string::FromUtf8Error`] (widening the sibling [`TryFrom<&[u8]>`]
2178/// axis's unit-error) and silently allocates a [`String`] on inputs that
2179/// will never make it past the wire vocabulary, or (c) an intermediate
2180/// `<RestartStrategy as TryFrom<&str>>::try_from(std::str::from_utf8(&bytes)?)`
2181/// three-hop shape. This impl closes the owned-byte-vec reverse-projection
2182/// axis at the substrate-primitive [`RestartStrategy::from_wire`] accessor
2183/// so every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec consumer —
2184/// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
2185/// body reader that hands the `spec.estrategia` byte-tail off as a
2186/// [`Vec<u8>`] before UTF-8 validation commits allocation, a
2187/// `bytes::Bytes::to_vec()`-shape wire-body composer walking a prior
2188/// audit's per-supervisor rejection payload back to the typed enum, a
2189/// `std::io::Read::read_to_end`-shape audit-log source whose framing
2190/// yields an owned byte-vec per per-strategy scalar, an
2191/// `<T: TryFrom<Vec<u8>>>`-bound generic loader over any of the
2192/// substrate's closed-set typed enums — reaches the same four-arm
2193/// `PascalCase` wire accept-set through one trait dispatch.
2194///
2195/// Extends the substrate-wide trait-idiomatic *byte-owned reverse-
2196/// projection* family — opened on the structurally most fundamental
2197/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
2198/// 99c2849), extended onto the second caixa-core-internal peer
2199/// ([`crate::CaixaDialeto`], commit 83a1526) and the third
2200/// ([`crate::dep::DepList`], commit 42091cb) — onto the first M2-OTP-shape
2201/// supervisor-slot closed-set fieldless typed enum peer, tracking the
2202/// "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice` borrow"
2203/// discipline the first-mover established. Every remaining closed-set
2204/// fieldless typed enum peer on the substrate ([`RestartPolicy`],
2205/// [`crate::aplicacao::PlacementStrategy`],
2206/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
2207/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
2208/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
2209/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
2210/// mirroring the trajectory the closed byte-view reverse-projection
2211/// family (`TryFrom<&[u8]>`) and the closed byte-owned forward-projection
2212/// family (`From<{Self, &Self}> for Vec<u8>`) already walked.
2213///
2214/// `type Error = ()` matches the sibling [`TryFrom<&[u8]> for
2215/// RestartStrategy`] unit-error shape, preserving the trait-family
2216/// consistency across the borrowed-and-owned byte-view reverse-projection
2217/// pair. The owned [`Vec<u8>`] input is dropped on the error path (the
2218/// standard-library `String::from_utf8` convention of returning the input
2219/// in the error deliberately declined — a caller that needs the bytes
2220/// back holds a clone before the call, and the closed-set-enum use site
2221/// rarely wants the raw bytes back past a "did you mean" diagnostic that
2222/// operates on the wire vocabulary rather than the input).
2223///
2224/// Pinned load-bearing by
2225/// [`tests::restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
2226/// (byte-parity pin against the paired borrowed [`TryFrom<&[u8]>`] axis
2227/// across the four-arm [`RestartStrategy::ALL`] accept-set on the owned
2228/// byte-vec surface, cross-axis witness that the byte-owned reverse
2229/// projection agrees with the paired str-view reverse-projection axis
2230/// ([`TryFrom<&str>`]) on every accepted arm through the shared
2231/// substrate-primitive [`RestartStrategy::from_wire`] accessor, and a
2232/// four-corner {owned-input, borrowed-input} × {`From<Self>` → `Vec<u8>`,
2233/// `From<&Self>` → `Vec<u8>`} round-trip witness available on this enum
2234/// because [`RestartStrategy::as_str`] and [`RestartStrategy::from_wire`]
2235/// share one `PascalCase` byte-vocabulary — unlike the sibling
2236/// [`crate::CaixaKind`] which its peer test deliberately declines the
2237/// four-corner witness on because the wire/diagnostic split makes the
2238/// forward and reverse pairs speak different byte-strings) and
2239/// [`tests::restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
2240/// (rejection witness against silent accept-set widening on both the
2241/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
2242/// rejection path — the latter includes the sibling kebab-case
2243/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
2244/// a caller that confuses the two axes trips here rather than at a
2245/// downstream K8s-CR round-trip miss, plus a cross-axis witness that the
2246/// owned byte-vec reverse-projection axis agrees with the borrowed byte-
2247/// slice reverse-projection axis on every rejected input).
2248impl TryFrom<Vec<u8>> for RestartStrategy {
2249 type Error = ();
2250
2251 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
2252 <Self as TryFrom<&[u8]>>::try_from(bytes.as_slice())
2253 }
2254}
2255
2256/// Trait-idiomatic *owned-`String` input, `Result<Self, ()>` output*
2257/// string-owned reverse projection on the first M2-OTP-shape supervisor-slot
2258/// closed-set fieldless typed enum peer on the caixa surface
2259/// ([`RestartStrategy`]) — the owned-input peer of the paired
2260/// [`TryFrom<&str> for RestartStrategy`] str-view reverse-projection axis, and
2261/// the string-owned reverse companion of the pre-existing string-owned
2262/// *forward* pair ([`From<RestartStrategy> for String`],
2263/// [`From<&RestartStrategy> for String`]) already lifted on this same enum.
2264/// Routes owned [`String`] input through the paired borrowed-input
2265/// [`TryFrom<&str>`] axis via [`String::as_str`] so every consumer that holds
2266/// an owned `String` — a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2267/// admission-webhook body reader that hands the `spec.estrategia`
2268/// `PascalCase` scalar off as an owned [`String`] after UTF-8 validation, a
2269/// `serde_yaml::from_str` / `serde_json::from_str` de-serialize round-trip
2270/// whose composer surfaces the `:estrategia` scalar as an owned [`String`]
2271/// typed field, a `feira supervisor --estrategia <OneForOne|OneForAll|
2272/// RestForOne|SimpleOneForOne>` `clap`-derived arg-parse whose owned-`String`
2273/// positional lands the canonical arm at the typed dispatch, a
2274/// per-`:supervisor`-slot overlay resolver reading an owned [`String`] out of
2275/// a `ConfigMap` `data.supervisor-estrategia` scalar, an
2276/// `<T: TryFrom<String>>`-bound generic loader over any of the substrate's
2277/// closed-set typed enums — reaches the same four-arm `PascalCase` accept-set
2278/// through one trait dispatch.
2279///
2280/// Extends the substrate-wide trait-idiomatic *string-owned reverse-
2281/// projection* family — opened on the compound M3-mesh
2282/// `:politicas :rate-limit` primitive [`crate::aplicacao::RateLimit`]
2283/// (a2e6f02), lifted onto the first closed-set fieldless typed-enum peer
2284/// [`crate::aplicacao::WitShape`] (e6aac29), extended onto the second closed-
2285/// set fieldless typed-enum peer [`crate::aplicacao::RateLimitUnit`]
2286/// (94a9c5e), extended onto the third closed-set fieldless typed-enum peer
2287/// [`crate::aplicacao::PlacementStrategy`] (d81a70a) — onto the first
2288/// M2-OTP-shape supervisor-slot closed-set fieldless typed-enum peer, the
2289/// per-`:supervisor` sibling-restart-strategy discriminator. The peers
2290/// [`RestartPolicy`], [`crate::CaixaKind`], [`crate::CaixaDialeto`], and
2291/// [`crate::dep::DepList`] remain the next targets of the campaign, mirroring
2292/// the trajectory the closed byte-view / byte-owned reverse-projection
2293/// families already walked across the same closed-set peers.
2294///
2295/// Rust's standard library carries no blanket
2296/// `impl<T: for<'a> TryFrom<&'a str>> TryFrom<String> for T`, so a consumer
2297/// that holds an owned [`String`] and needs a typed [`RestartStrategy`]
2298/// otherwise picks between (a) an open-coded
2299/// `<RestartStrategy as TryFrom<&str>>::try_from(s.as_str())` at every call
2300/// site whose type bounds have no compile-time link back to the string-owned
2301/// reverse-projection axis, (b) a `let s: &str = &s;
2302/// RestartStrategy::try_from(s)` two-step whose borrow arithmetic leaks a
2303/// per-call-site lifetime dance rather than a single trait dispatch, or (c) a
2304/// `String::into_bytes` + [`TryFrom<Vec<u8>>`] detour that reaches the
2305/// substrate-primitive `from_wire` accessor through a UTF-8 re-validation hop
2306/// the owned-`String` axis already knows to skip. This impl closes the
2307/// string-owned reverse-projection axis at the substrate-primitive
2308/// [`RestartStrategy::from_wire`] accessor so every future
2309/// `<T: TryFrom<String>>`-bound owned-string consumer reaches the same
2310/// four-arm `PascalCase` accept-set through one trait dispatch.
2311///
2312/// `type Error = ()` matches the sibling [`TryFrom<&str> for
2313/// RestartStrategy`], [`TryFrom<&[u8]> for RestartStrategy`], and
2314/// [`TryFrom<Vec<u8>> for RestartStrategy`] unit-error shapes, preserving the
2315/// trait-family consistency across the {str-view, byte-view, byte-owned,
2316/// string-owned} reverse-projection square. The owned [`String`] input is
2317/// dropped on the error path (the standard-library `String::from_utf8`
2318/// convention of returning the input in the error deliberately declined — a
2319/// caller that needs the string back holds a clone before the call, and the
2320/// closed-set-enum use site rarely wants the raw string back past a "did you
2321/// mean" diagnostic that operates on the wire vocabulary rather than the
2322/// input).
2323///
2324/// Pinned load-bearing by
2325/// [`tests::restart_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
2326/// (byte-parity pin against the paired borrowed [`TryFrom<&str>`] axis across
2327/// the four-arm [`RestartStrategy::ALL`] accept-set on the owned-`String`
2328/// surface, cross-axis witness that the string-owned reverse projection
2329/// agrees with the sibling byte-view / byte-owned reverse-projection axes on
2330/// every accepted arm through the shared substrate-primitive
2331/// [`RestartStrategy::from_wire`] accessor, and a closed-cycle witness
2332/// against the paired string-owned forward-projection pair — `Self → String
2333/// → TryFrom<String> → Self` round-trips to the originating arm on every
2334/// canonical `PascalCase` scalar) and
2335/// [`tests::restart_strategy_try_from_owned_string_rejects_unknown_wire_strings`]
2336/// (rejection witness against silent accept-set widening — mirrors the
2337/// corpus the paired [`TryFrom<&str>`] rejection witness already pins,
2338/// including empty / whitespace-only inputs, the sibling kebab-case
2339/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so a
2340/// caller that confuses the two axes trips here rather than at a downstream
2341/// K8s-CR round-trip miss, case-fold rebrand candidates, whitespace-padded /
2342/// trailing-newline / quote-wrapped forms, and English-rebrand candidates,
2343/// with per-input cross-axis parity against the borrowed [`TryFrom<&str>`]
2344/// reverse-projection axis).
2345impl TryFrom<String> for RestartStrategy {
2346 type Error = ();
2347
2348 fn try_from(s: String) -> Result<Self, Self::Error> {
2349 <Self as TryFrom<&str>>::try_from(s.as_str())
2350 }
2351}
2352
2353/// Per-child restart policy.
2354///
2355/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
2356#[derive(
2357 Serialize,
2358 Deserialize,
2359 Debug,
2360 Clone,
2361 Copy,
2362 PartialEq,
2363 Eq,
2364 Hash,
2365 gen_platform::TypedDispatcher,
2366 gen_platform::Discriminant,
2367 gen_platform::IsVariant,
2368 gen_platform::FromStrKind,
2369)]
2370pub enum RestartPolicy {
2371 /// Always restart the child, regardless of how it died. Used for
2372 /// long-running services that must always be up.
2373 Permanent,
2374 /// Never restart. Used for one-shot work whose completion is
2375 /// itself the success signal (`oneShot` triggers map here).
2376 Temporary,
2377 /// Restart only when the child died *abnormally* (non-zero exit
2378 /// or unhandled exception). A clean exit completes the child.
2379 Transient,
2380}
2381
2382impl Default for RestartPolicy {
2383 fn default() -> Self {
2384 // Route the [`Default for RestartPolicy`] impl's return arm through
2385 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
2386 // `pub const` rather than a raw `Self::Permanent` arm — one source
2387 // of truth for the Erlang/OTP-canonical `permanent` worker-child
2388 // default across the two production consumers that currently
2389 // dispatch on it (this impl at the [`RestartPolicy::default`] call
2390 // and the serde-side `#[serde(default)]` on
2391 // [`ChildSpec::restart`] that resolves an author-omitted
2392 // `:children :restart` slot through `RestartPolicy::default()`).
2393 // Peer of the sibling per-`:supervisor` axis
2394 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2395 // route (95ffacc) — the two impls now share one substrate-primitive
2396 // lift discipline, so any future coherent rebrand of the OTP-shape
2397 // supervisor+child default set migrates through typed constants in
2398 // lockstep instead of splitting a lifted supervisor half against
2399 // an open-coded child half. Pinned by
2400 // `restart_policy_default_routes_through_lifted_default` +
2401 // `child_spec_serde_default_restart_routes_through_lifted_default`
2402 // in the tests module.
2403 SUPERVISOR_CHILD_RESTART_DEFAULT
2404 }
2405}
2406
2407impl RestartPolicy {
2408 /// Exhaustive iteration surface for every consumer that walks the
2409 /// closed three-arm [`RestartPolicy`] discriminator set (the future
2410 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2411 /// per-child admission-webhook rejection body naming the accepted-
2412 /// `:restart` list, a future `feira supervisor --restart …` CLI
2413 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
2414 /// over the slice, the future `feira app graph` per-child restart
2415 /// column, any future round-trip fuzz harness that sweeps every
2416 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
2417 /// theory
2418 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2419 /// might reach for once the three canonical OTP restart policies
2420 /// stop covering the substrate's discovered load-shape) extends
2421 /// this slice as one edit and every consumer picks up the new entry
2422 /// by construction; the compiler-checked exhaustiveness on the
2423 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
2424 /// is the build-time guarantee that no arm forgets to grow.
2425 ///
2426 /// Peer of the sibling closed-set typed enums'
2427 /// [`RestartStrategy::ALL`] (4eec29c) /
2428 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
2429 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
2430 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
2431 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
2432 /// surfaces — the sixth (and the third and final M2 OTP-shape)
2433 /// closed-set typed enum on the caixa surface to converge onto the
2434 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
2435 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
2436 /// sibling-restart-strategy axis; this closes the per-child
2437 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
2438 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
2439
2440 /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
2441 /// `PascalCase` wire byte-string axis — the closed three-arm roster
2442 /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
2443 /// through the paired
2444 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2445 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2446 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
2447 /// `pub const` roster the [`Self::as_str`] emitter (and the
2448 /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
2449 /// walks — and byte-for-byte the same three strings the un-`rename`d
2450 /// `Serialize` derive emits under the paired
2451 /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
2452 /// JSON / YAML CR round-trip.
2453 ///
2454 /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
2455 /// roster on the top-level typed-kind discriminator's `PascalCase`
2456 /// wire byte-string axis, the sibling
2457 /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
2458 /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
2459 /// closed-set typed enum to converge onto the paired-roster
2460 /// discipline), the sibling
2461 /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
2462 /// roster on the first M3 mesh-shape distribution-strategy closed-
2463 /// set typed enum, and the sibling
2464 /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
2465 /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
2466 /// rosters on the OTP-appup discriminator's two-axis roster split —
2467 /// the same closed-set exhaustive-accept-set roster discipline
2468 /// extended here onto the second and final M2 OTP-shape sibling-
2469 /// enum on the caixa surface, closing the per-child restart-decision-
2470 /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
2471 /// per-supervisor sibling-restart-strategy axis on the same M2
2472 /// `:supervisor` slot.
2473 ///
2474 /// Downstream consumers of the closed accepted-wire-form set — a
2475 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
2476 /// webhook rejection body enumerating the accepted JSON `:restart`
2477 /// values verbatim (as distinct from the kebab-case dispatcher-
2478 /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
2479 /// form `"permanent"` / `"temporary"` / `"transient"` structurally
2480 /// disagrees with the wire byte-string these `PascalCase` entries
2481 /// carry — the split the sibling
2482 /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
2483 /// pin already makes load-bearing), a future `feira supervisor
2484 /// --restart …` CLI-side "did you mean" hint whose candidate-list
2485 /// must byte-match the wire form the operator's per-child dispatch
2486 /// keys off, a future `feira app graph` per-child `:restart`-
2487 /// histogram column that renders zero-count arms, a future
2488 /// `caixa-operator` per-reconcile-step diagnostic log line
2489 /// enumerating accepted wire forms on an unknown-policy rejection,
2490 /// a future
2491 /// `tracing::field::valuable::Value::List` structured-log accepted-
2492 /// wire-form emit — now reach for one lifted substrate-primitive
2493 /// roster rather than open-coding a three-string array-literal
2494 /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
2495 /// compile-time link back to the typed [`RestartPolicy`] enum. A
2496 /// future arm addition (an OTP-`intrinsic` fourth arm the theory
2497 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2498 /// might reach for once the three canonical OTP restart policies
2499 /// stop covering the substrate's discovered load-shape) extends
2500 /// this roster as a single edit — paired with the [`Self::as_str`]
2501 /// match's compiler-checked exhaustiveness on the new arm — and
2502 /// every consumer picks up the new wire form by construction rather
2503 /// than a coordinated array-literal rewrite across every downstream
2504 /// site.
2505 ///
2506 /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
2507 /// (three) by
2508 /// [`tests::restart_policy_wire_names_covers_every_arm`], every
2509 /// variant's [`Self::as_str`] projection is pinned to a member of
2510 /// the roster so a silent skew between the emitter's arm-set and
2511 /// this const's arm-set trips at caixa-core test time rather than at
2512 /// a downstream consumer's accepted-set enumeration miss, and every
2513 /// entry is further pinned to open with an ASCII uppercase byte so
2514 /// a silent collapse of the `PascalCase` wire-form axis with the
2515 /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
2516 /// to a sibling [`Self::discriminant`] kebab byte-string that would
2517 /// let a wire-axis consumer accept the dispatcher-catalog
2518 /// vocabulary) trips here rather than at a downstream K8s-CR round-
2519 /// trip miss.
2520 pub const WIRE_NAMES: &'static [&'static str] = &[
2521 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
2522 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
2523 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
2524 ];
2525
2526 /// Canonical PascalCase discriminator scalar this variant serializes
2527 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
2528 /// arms return the paired
2529 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2530 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2531 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
2532 /// constants so every substrate consumer that dispatches on the
2533 /// per-child restart-decision policy (the future wasm-operator's
2534 /// per-child post-exit restart-decision branch, the future M4
2535 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2536 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
2537 /// reconciliation scheduler's per-child-policy fan-out) reads the
2538 /// same byte-string the `Serialize` derive emits — the pin test in
2539 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2540 /// asserts the two paths agree, peer of the M2
2541 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
2542 /// sibling-restart-strategy axis and the M3
2543 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
2544 /// per-Aplicacao distribution-strategy axis — the third of three
2545 /// OTP-shaped closed-enum discriminator axes on the caixa typed
2546 /// surface to converge onto the same three-path-convergence
2547 /// (`Serialize` derive → `as_str` helper → lifted constant)
2548 /// drift-detection posture.
2549 #[must_use]
2550 pub const fn as_str(self) -> &'static str {
2551 match self {
2552 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
2553 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
2554 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
2555 }
2556 }
2557
2558 /// Substrate-canonical reverse projection on the `:children :restart`
2559 /// closed-set axis — parses the `PascalCase` discriminator scalar
2560 /// back to the typed variant, or `None` when `s` is outside the
2561 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
2562 /// the same lifted
2563 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2564 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2565 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
2566 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
2567 /// of the round-trip migrate through one caixa-core edit on any
2568 /// future arm addition.
2569 ///
2570 /// Prior to this lift the substrate carried only the forward
2571 /// `Self → &str` projection on the OTP per-child restart-policy
2572 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
2573 /// impl routed through it, the `Serialize` derive that emits the
2574 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
2575 /// plus the kebab-case dispatcher-catalog identity via
2576 /// [`Self::discriminant`] — every non-serde consumer that wanted to
2577 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
2578 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
2579 /// "Transient" => …, _ => … }` cascade that expressed no
2580 /// compile-time link back to the typed variant's canonical lifted
2581 /// constant. A future variant rename or per-arm serde-attribute
2582 /// drift would silently split the wire byte-string one non-serde
2583 /// consumer parsed from the one the emitter wrote, with the failure
2584 /// surfacing at the operator's reconcile posture (a `:temporary`
2585 /// `oneShot` child being restarted on clean exit, treating the
2586 /// successful-completion signal as failure and re-running the
2587 /// completion-terminal one-shot indefinitely; a `:transient` child
2588 /// that clean-exited being restarted, masking the clean-completion
2589 /// contract) far from the rebrand commit and with no field naming
2590 /// the drift.
2591 ///
2592 /// Distinct axis from the [`std::str::FromStr`] impl the
2593 /// [`gen_platform::FromStrKind`] derive already installs on this
2594 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
2595 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
2596 /// `"transient"` — the inverse of [`Self::discriminant`]), while
2597 /// this method inverts the `PascalCase` wire byte-string
2598 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
2599 /// catalog identity live in kebab-case (where every peer catalog
2600 /// identifier already lives) without forcing a wire-format rename
2601 /// on the tatara-lisp author surface (`:restart Permanent`,
2602 /// `PascalCase`) — the same two-axis distinction the sibling
2603 /// [`RestartStrategy::from_wire`] (4eec29c) /
2604 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
2605 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
2606 /// carry on their peer closed-set typed-enum wire round-trips.
2607 ///
2608 /// Same closed-set-reverse-projection discipline the sibling
2609 /// [`RestartStrategy::from_wire`] (4eec29c) /
2610 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
2611 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
2612 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
2613 /// carry on the peer wire-side `str → Self` axes — extended onto
2614 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
2615 /// sixth substrate-side closed-set typed enum (and the third and
2616 /// final OTP-shape closed-enum discriminator axis) to converge on
2617 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
2618 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
2619 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
2620 /// derive already installs on the sibling kebab-case axis. Returns
2621 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
2622 /// shapes: the caller picks the diagnostic form appropriate for
2623 /// its use site.
2624 #[must_use]
2625 pub fn from_wire(s: &str) -> Option<Self> {
2626 match s {
2627 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
2628 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
2629 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
2630 _ => None,
2631 }
2632 }
2633}
2634
2635/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
2636/// pretty-printed byte-string every consumer that formats the policy as
2637/// user-facing text lands on (the future wasm-operator's per-child
2638/// post-exit restart-decision diagnostic line, the future `feira app
2639/// graph` per-child restart column, the future M4
2640/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2641/// admission-webhook rejection body) reaches for the same lifted
2642/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2643/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2644/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2645/// wire-format `Serialize` derive already emits under
2646/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
2647/// [`RestartPolicy::as_str`] helper already returns.
2648///
2649/// Pre-convergence the two paths structurally disagreed — the
2650/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
2651/// route (now retired here) sent [`std::fmt::Display`] through the
2652/// gen-platform discriminant catalog string, which arrives kebab-case as
2653/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
2654/// (whose variant names each collapse to their own lowercase form under
2655/// the kebab-case transform), while the wire format ran as `PascalCase`
2656/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
2657/// serde derive. Every consumer that formatted the policy for a
2658/// diagnostic line, a graph column, or a rejection body under
2659/// `format!("{v}")` therefore landed under a different byte-string than
2660/// the wire format the operator's per-child-policy dispatch keyed off —
2661/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
2662/// diagnostic quoting `"permanent"` while the wire scalar the operator
2663/// probed was `"Permanent"`) surfaced as a confused correlate at
2664/// operator-log time far from the two-declaration site.
2665///
2666/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
2667/// path: every `format!("{v}")` call reaches the same lifted
2668/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
2669/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
2670/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
2671/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
2672/// byte-string per variant. A future variant rename or
2673/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
2674/// exactly one place, structurally.
2675///
2676/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
2677/// (from `#[derive(gen_platform::Discriminant)]`) still returns
2678/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
2679/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
2680/// registration keys the catalog off the same kebab identity. The two
2681/// naming worlds now live on separate typed methods (`Display` /
2682/// `as_str` for the wire byte-string, `discriminant` for the catalog
2683/// identity) rather than sharing one `Display` route that structurally
2684/// disagrees with the wire format.
2685///
2686/// Pin tests
2687/// [`tests::restart_policy_display_routes_through_as_str_helper`]
2688/// and
2689/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
2690/// assert the three paths agree byte-for-byte on every variant, so a
2691/// future variant rename or per-arm serde attribute drift is a build
2692/// error visible at caixa-core test time, not a silent per-consumer
2693/// dispatch miss at apply / reconcile time.
2694///
2695/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
2696/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
2697/// and the sibling [`RestartStrategy`] `Display` impl on the
2698/// per-supervisor sibling-restart-strategy axis — same three-path-
2699/// convergence discipline, extended to close the third and final of
2700/// three OTP-shaped closed-enum discriminator axes on the caixa typed
2701/// surface.
2702impl std::fmt::Display for RestartPolicy {
2703 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2704 f.write_str(self.as_str())
2705 }
2706}
2707
2708/// Substrate-canonical [`AsRef<str>`] projection on the M2
2709/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
2710/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
2711/// scalar accessor the paired [`std::fmt::Display`] impl and the
2712/// un-`rename`d [`serde::Serialize`] derive already key off, so any
2713/// future consumer that binds a [`RestartPolicy`] through the
2714/// standard-library `impl AsRef<str>` bound (a future
2715/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
2716/// composes the emitted `PascalCase` wire scalar into a
2717/// [`std::process::Command::arg`] shell-out of the future
2718/// wasm-operator's per-child admission gate, a per-child structured-
2719/// log recorder on the future `caixa-operator`'s hierarchical
2720/// reconciliation surface that accepts `impl AsRef<str>` at the
2721/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
2722/// lookup keyed on the restart-policy wire byte through
2723/// `map.get::<str>(policy.as_ref())` on a future per-policy
2724/// dispatch table) reaches the paired
2725/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2726/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2727/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
2728/// lifted-const through one substrate-primitive dispatch rather
2729/// than an open-coded `.as_str()` projection at every wire-up.
2730///
2731/// Peer of the sibling [`std::fmt::Display`] impl on the same
2732/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
2733/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
2734/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
2735/// byte-string per instance by construction. A future variant rename
2736/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
2737/// enum reaches every one of the three paths (plus the wire-format
2738/// `Serialize` derive that already routes through the same lifted
2739/// const) through exactly one caixa-core edit.
2740///
2741/// Same "route the trait impl through the substrate-primitive
2742/// accessor" discipline the sibling [`crate::CaixaVersion`]
2743/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
2744/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
2745/// the axis onto the paired per-child-restart-decision-policy
2746/// sibling on the same M2 `:supervisor` slot (the second M2
2747/// OTP-shape closed-set typed enum to converge onto the standard-
2748/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
2749/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
2750/// primitive so a caller who has one has both; before this lift,
2751/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
2752/// [`AsRef<str>`] impl the convention names.
2753///
2754/// Pinned load-bearing by
2755/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
2756/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2757/// three-arm closed set) and
2758/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
2759/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
2760/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
2761/// arm) — any future silent detour that routes the impl through a
2762/// divergent projection (a per-arm inline `match self { … }`
2763/// re-inlining that opens a compile-time link to the un-lifted
2764/// arm-literal, a swap onto the kebab-case
2765/// [`gen_platform::Discriminant`] catalog identity that would
2766/// collide the wire axis with the dispatcher-catalog axis) trips at
2767/// caixa-core test time under `assert_eq!` rather than at a
2768/// downstream `impl AsRef<str>`-bound consumer's silent split.
2769impl AsRef<str> for RestartPolicy {
2770 fn as_ref(&self) -> &str {
2771 self.as_str()
2772 }
2773}
2774
2775/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
2776/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2777/// byte-for-byte through the paired substrate-primitive
2778/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
2779/// consumer that binds a `PascalCase` `:children :restart` wire
2780/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
2781/// axis (a future [`caixa-feira`] `feira supervisor --restart
2782/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
2783/// `let restart: RestartPolicy = s.try_into()?`, a future
2784/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
2785/// `spec.children[*].restart: String` field through
2786/// `RestartPolicy::try_from(&s)?`, a generic
2787/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
2788/// set typed enums) reaches the same three-arm accept-set the sibling
2789/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
2790/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
2791/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
2792/// … }` cascade whose arm-set has no compile-time link back to the
2793/// substrate primitive.
2794///
2795/// Complements the pre-existing forward-projection triple
2796/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
2797/// with the paired trait-idiomatic reverse-projection axis: Rust-side
2798/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
2799/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
2800/// caller who can project *out to* a `&str` can also project *in from*
2801/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
2802/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
2803/// lint the sibling method-named [`RestartPolicy::from_wire`] would
2804/// trigger under a `FromStr` impl and to avoid colliding with the
2805/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
2806/// already installs on the paired *kebab-case dispatcher-catalog* axis
2807/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
2808/// inverse of [`Self::discriminant`]) — this impl closes the trait-
2809/// idiomatic reverse axis on the *`PascalCase` wire* half without
2810/// disturbing either the method-named `from_wire` shape every sibling
2811/// closed-set typed enum on the substrate already carries or the
2812/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
2813/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
2814///
2815/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
2816/// `Option<Self>` return-shape's deliberate deferral of error typing: the
2817/// caller picks the diagnostic form appropriate for its use site (a
2818/// future `feira supervisor --restart` arg-parse composes its own
2819/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
2820/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
2821/// wraps the `Err(())` outcome with the accepted-set enumeration for
2822/// operator diagnostics, a `Result::map_err` at the call site lifts the
2823/// unit-error to a per-verb error type). Same shape the peer
2824/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
2825/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
2826/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
2827/// their peer closed-set typed enums' reverse projections.
2828///
2829/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
2830/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
2831/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
2832/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2833/// might reach for once the three canonical OTP restart policies stop
2834/// covering the substrate's discovered load-shape) grows the trait-
2835/// idiomatic axis by construction — one caixa-core edit on
2836/// [`RestartPolicy::from_wire`] extends both the method-named reverse
2837/// projection every existing consumer keys off and the trait-idiomatic
2838/// reverse projection this impl exposes, without a coordinated rewrite
2839/// across every future `TryFrom<&str>`-bound consumer's arm-set.
2840///
2841/// Extends the substrate-wide closed-set-enum reverse-projection family
2842/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
2843/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
2844/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
2845/// closed-enum discriminator axis on the caixa surface — the paired
2846/// per-child `:children :restart` closed set the future wasm-operator's
2847/// hierarchical reconciliation scheduler's per-child post-exit
2848/// restart-decision branch keys off end-to-end.
2849///
2850/// Pinned load-bearing by
2851/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
2852/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
2853/// three-arm accept-set),
2854/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
2855/// (rejection witness against silent accept-set widening), and
2856/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
2857/// (cross-axis partition pin locking the trait and method-named
2858/// projections onto one accept-set).
2859impl TryFrom<&str> for RestartPolicy {
2860 type Error = ();
2861
2862 fn try_from(s: &str) -> Result<Self, Self::Error> {
2863 Self::from_wire(s).ok_or(())
2864 }
2865}
2866
2867/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
2868/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2869/// byte-for-byte through the paired substrate-primitive
2870/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
2871/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
2872/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
2873/// &str` with `'static` lifetime, so the trait's return-type promise is
2874/// upheld structurally without a [`String::leak`] cast or a per-arm inline
2875/// literal.
2876///
2877/// Every future consumer that specifically needs `&'static str` lifetime
2878/// bytes on the per-child restart-decision axis (a
2879/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
2880/// arm's typing demands `&'static str`, a
2881/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
2882/// on the future M4 admission-webhook rejection body where the
2883/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
2884/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
2885/// or error formatter that requires the `'static` bound) reaches the same
2886/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2887/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2888/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
2889/// primitive dispatch rather than an open-coded per-arm literal cascade
2890/// whose arm-set has no compile-time link back to the substrate primitive.
2891///
2892/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
2893/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
2894/// the second (and second-of-two-in-M2) closed-set typed enum on the
2895/// caixa surface to converge onto the paired trait-idiomatic forward-
2896/// projection axis. With this lift the paired per-child
2897/// `:children :restart` closed-set typed enum carries the full sibling
2898/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2899/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
2900/// lift) plus the round-trip witness through both the trait-idiomatic
2901/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
2902/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
2903/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
2904/// (an OTP-`intrinsic` fourth arm the theory
2905/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2906/// might reach for once the three canonical OTP restart policies stop
2907/// covering the substrate's discovered load-shape) grows the trait-
2908/// idiomatic forward axis by construction: one caixa-core edit on
2909/// [`RestartPolicy::as_str`] extends every one of the five sibling
2910/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
2911/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
2912/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
2913/// bytes) without a coordinated rewrite across every future
2914/// `Into<&'static str>`-bound consumer's arm-set.
2915///
2916/// Pinned load-bearing by
2917/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
2918/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2919/// three-arm emit-set, plus a `const`-context materialization witness for
2920/// the `&'static str` lifetime promise) and
2921/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
2922/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
2923/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
2924/// round-trip witness through the paired trait-idiomatic reverse-
2925/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
2926/// `policy.into::<&'static str>()` output re-parses back through
2927/// [`RestartPolicy::try_from`] to the original variant, closing the two-
2928/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
2929impl From<RestartPolicy> for &'static str {
2930 fn from(policy: RestartPolicy) -> &'static str {
2931 policy.as_str()
2932 }
2933}
2934
2935/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
2936/// *borrowed* input onto the `&'static str` axis — the borrowed-input
2937/// companion to the paired owned-input [`From<RestartPolicy> for
2938/// &'static str`] impl immediately above. Routes byte-for-byte through
2939/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
2940/// fn` accessor so every consumer that binds a `&RestartPolicy`
2941/// through the standard-library `.into()` / [`From<&Self> for &'static
2942/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
2943/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
2944/// whose iterator over `&'static [RestartPolicy]` yields
2945/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
2946/// [`From<RestartPolicy>`] axis alone forces every call site through
2947/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
2948/// rather than the direct trait-idiomatic projection; a future generic
2949/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
2950/// that walks the `iter().map(Into::into)` shape verbatim across every
2951/// substrate-wide closed-set typed enum; the future wasm-operator's
2952/// per-child post-exit restart-decision diagnostic line that composes
2953/// the accepted-set enumeration from an iterated
2954/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2955/// per-arm `match p { … }` cascade; a future
2956/// `HashMap::<&'static str, RestartPolicy>::from_iter(
2957/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
2958/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
2959/// cannot compose without this borrowed-input axis in place) reaches
2960/// the same three-arm lifted
2961/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2962/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2963/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2964/// paired owned-input [`From<RestartPolicy> for &'static str`], the
2965/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
2966/// [`RestartPolicy::as_str`] surfaces already return.
2967///
2968/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
2969/// forward-projection family opened on [`crate::dep::DepList`]
2970/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
2971/// [`crate::CaixaDialeto`] (807b0b5), and the paired
2972/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
2973/// (e941836). Rust's `From` trait does not auto-derive the
2974/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
2975/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
2976/// exist in `core`), so every closed-set typed enum that carries the
2977/// owned-input axis but not the borrowed-input axis forces every
2978/// borrowed-input call site through a `.copied()` /
2979/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
2980/// type bounds have no compile-time link to the substrate primitive.
2981/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
2982/// OTP-shape peer to converge onto this campaign — sibling of the
2983/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
2984/// with this lift both closed-set typed enums on the M2 `:supervisor`
2985/// slot now carry the full sibling quintet ([`std::fmt::Display`],
2986/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
2987/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
2988/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
2989/// forward-projection axis on the M2 OTP-shape slot as a unit.
2990///
2991/// Same three-path convergence discipline as the paired owned-input
2992/// impl (this borrowed-input axis, the paired owned-input
2993/// [`From<RestartPolicy> for &'static str`], and
2994/// [`RestartPolicy::as_str`] all route through the same lifted
2995/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
2996/// variant rename or per-arm serde-attribute drift reaches every one
2997/// of the six sibling forward-projection paths
2998/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2999/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
3000/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
3001/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
3002/// edit.
3003///
3004/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
3005/// parse share the same `PascalCase` vocabulary by construction, so
3006/// the borrowed-input forward axis and the reverse axis compose
3007/// directly — the round-trip witness pin below locks this direct
3008/// composition without the intermediate wire-vocab hop the peer
3009/// [`crate::CaixaKind`] axis pair requires.
3010///
3011/// Pinned load-bearing by
3012/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
3013/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3014/// three-arm emit-set via a borrowed input, plus a `const`-context
3015/// materialization witness for the `&'static str` lifetime promise,
3016/// plus a blanket `.into()` shape) and
3017/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
3018/// (cross-axis partition pin against the paired owned-input
3019/// [`From<RestartPolicy> for &'static str`] impl, plus a
3020/// `.iter().map(Into::into)` pipe witness over
3021/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
3022/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
3023/// Self` round-trip without the wire-vocab intermediate the peer
3024/// [`crate::CaixaKind`] axis pair requires).
3025impl From<&RestartPolicy> for &'static str {
3026 fn from(policy: &RestartPolicy) -> &'static str {
3027 policy.as_str()
3028 }
3029}
3030
3031/// Trait-idiomatic *owned-`String`* forward projection on the second
3032/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
3033/// owned-heap-string companion to the paired `&'static str`-returning
3034/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
3035/// for &'static str`] impls immediately above. Routes byte-for-byte
3036/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
3037/// const fn` accessor (via [`str::to_owned`]) so every consumer that
3038/// binds a [`RestartPolicy`] through the standard-library `.into()` /
3039/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
3040/// future `serde_json::Value::String(policy.into())` structured-payload
3041/// composer where the `Value::String` arm typing demands an owned
3042/// [`String`] and the sibling [`&'static str`]-returning axis forces
3043/// an explicit `.to_owned()` / `String::from` restatement at every
3044/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
3045/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
3046/// lookup where the map's key type is owned [`String`] rather than
3047/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
3048/// composer on the future M4 admission-webhook rejection body's
3049/// owned-arm, the future wasm-operator's per-child post-exit
3050/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
3051/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
3052/// — reaches the same three-arm lifted
3053/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3054/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3055/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3056/// paired [`std::fmt::Display`], [`AsRef<str>`],
3057/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
3058/// forward-projection impls already return.
3059///
3060/// Extends the trait-idiomatic *owned-`String`* forward-projection
3061/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
3062/// the caixa surface — mirror of the first-mover
3063/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
3064/// axis on the sibling supervisor-level strategy enum. Rust's standard
3065/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
3066/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
3067/// every closed-set typed enum that carries the paired `AsRef<str>` /
3068/// `Display` / `From<Self> for &'static str` triple but not the
3069/// owned-[`String`] axis forces every owned-string call site through a
3070/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
3071/// detour whose type bounds have no compile-time link to the
3072/// substrate primitive.
3073///
3074/// Deliberately routes through the human-readable
3075/// [`RestartPolicy::as_str`] axis — for this enum the wire format
3076/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
3077/// the diagnostic byte-string share the same vocabulary by
3078/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
3079/// two axes diverge), so the owned-[`String`] projection lands
3080/// byte-identically on both the wire vocabulary the paired
3081/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
3082/// [`RestartPolicy::as_str`] helper returns, and — because the paired
3083/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
3084/// axis parses the same `PascalCase` vocabulary — the direct two-way
3085/// `Self → String → Self` round-trip composes without the wire-vocab
3086/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
3087/// axis pair requires.
3088///
3089/// Pinned load-bearing by
3090/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
3091/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3092/// three-arm emit-set, plus a blanket `.into::<String>()` shape
3093/// witness) and
3094/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
3095/// (cross-axis partition pin against the paired owned-input
3096/// [`From<RestartPolicy> for &'static str`] impl and the sibling
3097/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
3098/// plus a `.iter().copied().map(String::from)` pipe witness over
3099/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
3100/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
3101/// borrow that closes the two-way `Self → String → Self` round-trip
3102/// on the trait-idiomatic owned-[`String`] forward + reverse axis
3103/// pair).
3104impl From<RestartPolicy> for String {
3105 fn from(policy: RestartPolicy) -> String {
3106 policy.as_str().to_owned()
3107 }
3108}
3109
3110/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
3111/// projection on the second-of-two M2 OTP-shape closed-set typed enum
3112/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
3113/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
3114/// projection family on this enum, mirror of the first-mover
3115/// [`From<&RestartStrategy> for String`] (579385f) that opened the
3116/// 2×2-completion corner on the sibling supervisor-level strategy
3117/// enum. Routes byte-for-byte through the substrate-primitive
3118/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
3119/// [`str::to_owned`]) so every consumer that holds a borrowed
3120/// [`&RestartPolicy`] and needs an owned [`String`] — a future
3121/// `serde_json::Value::String(String::from(&policy))` structured-payload
3122/// composer over a borrowed field, a future `Iterator::map` over
3123/// `&[RestartPolicy]` that projects to owned keys through
3124/// `.iter().map(String::from)`, a future `HashMap::<String,
3125/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
3126/// where dereferencing the policy would force an unnecessary `Copy` at
3127/// every step, the future wasm-operator's per-supervisor
3128/// `child_policies.iter().map(String::from).collect()` per-child post-
3129/// exit restart-decision diagnostic emit whose iteration axis is
3130/// borrowed by construction — reaches the same three-arm lifted
3131/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3132/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3133/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3134/// paired [`std::fmt::Display`], [`AsRef<str>`],
3135/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
3136/// forward-projection impls
3137/// ([`From<RestartPolicy> for &'static str`],
3138/// [`From<&RestartPolicy> for &'static str`],
3139/// [`From<RestartPolicy> for String`]) already return.
3140///
3141/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
3142/// owned-`String` output* forward-projection family opened on
3143/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
3144/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
3145/// both M2 OTP-shape sibling peers (the paired supervisor-level
3146/// sibling-restart-strategy axis and the per-child restart-decision-
3147/// policy axis), so the whole M2 OTP-shape axis pair now carries the
3148/// full four-corner family by construction. Rust's standard library
3149/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
3150/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
3151/// closed-set typed enum that carries the paired `AsRef<str>` /
3152/// `Display` / `From<Self> for &'static str` / `From<&Self> for
3153/// &'static str` / `From<Self> for String` quintuple but not the
3154/// borrowed-input owned-[`String`] axis forces every borrowed-input
3155/// owned-string call site through a `policy.as_str().to_owned()` /
3156/// `String::from(*policy)` (with a spurious `Copy`) /
3157/// `policy.to_string()` (through `Display`) detour whose type bounds
3158/// have no compile-time link to the substrate primitive.
3159///
3160/// Deliberately routes through the human-readable
3161/// [`RestartPolicy::as_str`] axis — for this enum the wire format
3162/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
3163/// the diagnostic byte-string share the same vocabulary by
3164/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
3165/// two axes diverge), so the borrowed-input owned-[`String`]
3166/// projection lands byte-identically on both the wire vocabulary the
3167/// paired [`serde::Serialize`] derive emits and the diagnostic
3168/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
3169/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
3170/// reverse-projection axis parses the same `PascalCase` vocabulary —
3171/// the direct two-way `&Self → String → Self` round-trip composes
3172/// without the wire-vocab intermediate hop the peer
3173/// [`crate::CaixaKind`] axis pair requires.
3174///
3175/// The remaining thirteen closed-set typed enums on the caixa
3176/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
3177/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
3178/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
3179/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
3180/// of this 2×2-completion campaign — each carries the same paired
3181/// quintuple that this borrowed-input owned-[`String`] axis extends
3182/// onto.
3183///
3184/// Pinned load-bearing by
3185/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
3186/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3187/// three-arm emit-set through the borrowed-input surface) and
3188/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
3189/// (cross-axis partition pin against the paired owned-input owned-
3190/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
3191/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
3192/// &'static str`] impl, and the sibling [`ToString::to_string`]
3193/// surface routed through [`std::fmt::Display`], plus a direct round-
3194/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
3195/// [`String::as_str`] borrow that closes the two-way
3196/// `&Self → String → Self` round-trip on the trait-idiomatic
3197/// borrowed-input owned-[`String`] forward + reverse axis pair).
3198impl From<&RestartPolicy> for String {
3199 fn from(policy: &RestartPolicy) -> String {
3200 policy.as_str().to_owned()
3201 }
3202}
3203
3204/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
3205/// output* forward projection on the M2 OTP-shape per-child-restart
3206/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
3207/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
3208/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
3209/// borrowed-input) and first extended off it onto the sibling M2
3210/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
3211/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
3212/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
3213/// surface (`:children :restart`). Routes byte-for-byte through the
3214/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3215/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
3216/// that binds a [`RestartPolicy`] through the trait-idiomatic
3217/// [`std::borrow::Cow<'static, str>`] axis — a future
3218/// `axum::response::IntoResponse` composer whose per-policy
3219/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
3220/// borrowed return, a future M4 admission-webhook rejection body
3221/// that composes the accepted-policy enumeration through the same
3222/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
3223/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
3224/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
3225/// emitter on a per-child-policy diagnostic column — reaches the same
3226/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
3227/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3228/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3229/// paired [`std::fmt::Display`], [`AsRef<str>`],
3230/// [`RestartPolicy::as_str`], and the four
3231/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
3232/// forward-projection corners already return.
3233///
3234/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
3235/// [`std::borrow::Cow::Owned`] — the substrate-primitive
3236/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
3237/// str` lifetime by construction (each `match` arm resolves to a
3238/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
3239/// with static lifetime), so the zero-alloc borrowed arm is the
3240/// type-correct projection with no runtime allocation.
3241///
3242/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
3243/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
3244/// From<T> for Cow<'static, str>`), so the paired sibling
3245/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
3246/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
3247/// [`std::fmt::Display`] surfaces do not implicitly extend to a
3248/// [`Cow<'static, str>`]-bound call site — every such site is forced
3249/// through a `Cow::Borrowed(policy.as_str())` /
3250/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
3251/// no compile-time link back to the substrate primitive until this
3252/// lift.
3253///
3254/// Second peer to extend the substrate-wide trait-idiomatic
3255/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
3256/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
3257/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
3258/// tier of the campaign (both sibling peers, `RestartStrategy` and
3259/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
3260/// forward projection) so the remaining eleven peers
3261/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
3262/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
3263/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
3264/// `FerriteRuntime`) are the future targets. Every future arm addition
3265/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
3266/// might reach for once the three canonical OTP restart policies stop
3267/// covering the substrate's discovered load-shape) grows the
3268/// Cow<'static, str> axis by construction through one caixa-core edit
3269/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
3270/// across every future Cow<'static, str>-bound consumer site.
3271///
3272/// Pinned load-bearing by
3273/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
3274/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
3275/// against [`RestartPolicy::as_str`] across the three-arm
3276/// [`RestartPolicy::ALL`]) and
3277/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
3278/// (cross-axis partition pin against the paired [`From<RestartPolicy>
3279/// for &'static str`], [`From<RestartPolicy> for String`], and
3280/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
3281/// `.iter().copied().map(Cow::from)` pipe witness over
3282/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
3283/// through the [`Cow<'static, str>`] axis alone and pins the
3284/// zero-alloc discipline on every element).
3285impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
3286 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
3287 std::borrow::Cow::Borrowed(policy.as_str())
3288 }
3289}
3290
3291/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
3292/// output* forward projection on the M2 OTP-shape per-child-restart
3293/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
3294/// companion to the paired owned-input
3295/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
3296/// immediately above (0612398). Routes byte-for-byte through the same
3297/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3298/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
3299/// that holds a `&RestartPolicy` and needs a
3300/// [`std::borrow::Cow<'static, str>`] — a
3301/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
3302/// per-arm accept-set materializer (whose iterator over
3303/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
3304/// `RestartPolicy`, so the paired owned-input
3305/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
3306/// alone forces every call site through an explicit `.copied()` /
3307/// dereference / [`Copy`]-bound restatement rather than the direct
3308/// trait-idiomatic projection), a future generic
3309/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
3310/// on a per-child-policy diagnostic column that walks the
3311/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
3312/// webhook rejection body that composes the accepted-policy
3313/// enumeration from an iterated
3314/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
3315/// per-arm `match p { … }` cascade — reaches the same three-arm
3316/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3317/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3318/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3319/// paired [`std::fmt::Display`], [`AsRef<str>`],
3320/// [`RestartPolicy::as_str`], the four
3321/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
3322/// forward-projection corners, and the paired owned-input
3323/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
3324/// already return.
3325///
3326/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
3327/// [`std::borrow::Cow::Owned`] — the substrate-primitive
3328/// [`RestartPolicy::as_str`] accessor's return carries the
3329/// `&'static str` lifetime by construction (each `match` arm resolves
3330/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
3331/// with static lifetime), so the zero-alloc borrowed arm is the
3332/// type-correct projection with no runtime allocation.
3333///
3334/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
3335/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
3336/// one commit prior (0612398) on the paired owned-input
3337/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
3338/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
3339/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
3340/// which carries both {Self, &Self} × Cow<'static, str> corners since
3341/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
3342/// closed it on the top-level [`crate::CaixaKind`] one commit after
3343/// the owning half (99c1735) landed. This lift closes the whole M2
3344/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
3345/// forward-projection campaign on both input-shape corners
3346/// ({Self, &Self}) of both M2 OTP-shape sibling peers
3347/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
3348/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
3349/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
3350/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
3351/// `FerriteRuntime`) become the future targets of the campaign. Rust's
3352/// standard library does not carry a blanket
3353/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
3354/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
3355/// closed-set fieldless typed enum peer on the substrate that carries
3356/// the paired owned-input [`Cow<'static, str>`] axis but not the
3357/// borrowed-input axis forces every borrowed-input
3358/// [`Cow<'static, str>`]-parameterized call site through a spurious
3359/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
3360/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
3361/// bounds have no compile-time link to the substrate primitive.
3362///
3363/// Pinned load-bearing by
3364/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
3365/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
3366/// against [`RestartPolicy::as_str`] across the three-arm
3367/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
3368/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
3369/// (cross-axis partition pin against the paired owned-input
3370/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
3371/// paired borrowed-input owned-`&'static str`
3372/// [`From<&RestartPolicy> for &'static str`], and the paired
3373/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
3374/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
3375/// over [`RestartPolicy::ALL`] — whose iterator yields
3376/// `&RestartPolicy` by construction, so the borrowed-input
3377/// [`Cow<'static, str>`] axis is what routes the pipe through the
3378/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
3379/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
3380/// spurious [`Copy`] deref).
3381impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
3382 fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
3383 std::borrow::Cow::Borrowed(policy.as_str())
3384 }
3385}
3386
3387/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
3388/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3389/// closed-set fieldless typed enum — extends the substrate-wide
3390/// `Box<str>` forward-projection campaign tier opened one commit prior
3391/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
3392/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
3393/// typed enum peer on the caixa surface (`:children :restart`),
3394/// immediately after the paired `Cow<'static, str>` axis (0612398 /
3395/// b4dc55c) closed the
3396/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
3397/// corner on this enum. Routes byte-for-byte through the
3398/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3399/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
3400/// so every consumer that binds a
3401/// `let key: Box<str> = policy.into();`-shaped call site — a
3402/// per-child metric-key materializer that stashes the policy
3403/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
3404/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
3405/// hierarchical reconciliation scheduler's per-child restart-decision
3406/// fan-out carries), a future admission-webhook rejection body whose
3407/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
3408/// handle — reaches the same three-arm lifted
3409/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3410/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3411/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3412/// sibling
3413/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
3414/// forward-projection corner already returns. Rust's standard library
3415/// carries `impl From<&str> for Box<str>` and
3416/// `impl From<String> for Box<str>` but no blanket
3417/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
3418/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
3419/// this axis is a distinct trait-idiomatic surface that a downstream
3420/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
3421/// no other — without a `Box::from(policy.as_str())` open-code whose
3422/// type bounds have no compile-time link back to the substrate
3423/// primitive.
3424///
3425/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
3426/// forward-projection family opened on the sibling-restart
3427/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
3428/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
3429/// projection campaign's owned-input corner on both M2 OTP-shape
3430/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
3431/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
3432/// and the remaining fieldless-enum peers on the M3 mesh-shape /
3433/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
3434/// are the future targets of the campaign.
3435///
3436/// Pinned load-bearing by
3437/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
3438/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3439/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
3440/// surface, plus a blanket-derived [`Into`] shape witness).
3441impl From<RestartPolicy> for Box<str> {
3442 fn from(policy: RestartPolicy) -> Box<str> {
3443 Box::<str>::from(policy.as_str())
3444 }
3445}
3446
3447/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
3448/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3449/// closed-set fieldless typed enum — the borrowed-input companion to
3450/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
3451/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
3452/// input-shape corner of the substrate-wide [`Box<str>`] forward-
3453/// projection axis on the second (and third-and-final) M2 OTP-shape
3454/// closed-set fieldless typed enum peer on the caixa surface
3455/// (`:children :restart`), routing byte-for-byte through the
3456/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3457/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
3458/// Every consumer that holds a `&RestartPolicy` and needs a
3459/// [`Box<str>`] — a
3460/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
3461/// per-arm accept-set materializer (whose iterator over
3462/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
3463/// `RestartPolicy`, so the paired owned-input
3464/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
3465/// call site through an explicit [`Copy`] deref or a
3466/// `.copied()` restatement rather than the direct trait-idiomatic
3467/// projection), a per-child metric-key materializer holding
3468/// `&RestartPolicy` through a `caixa-operator` hierarchical
3469/// reconciliation scheduler's borrow lifetime, a future admission-
3470/// webhook rejection body whose per-arm `Box<str>` field composes
3471/// from a borrowed `&RestartPolicy` handle — reaches the
3472/// substrate-primitive [`RestartPolicy::as_str`] accessor through
3473/// this impl and no other, without a
3474/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
3475/// have no compile-time link back to the substrate primitive.
3476///
3477/// Rust's standard library carries `impl From<&str> for Box<str>`
3478/// and `impl From<String> for Box<str>` but no blanket
3479/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
3480/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
3481/// set fieldless typed enum peer on the substrate that carries the
3482/// paired owned-input `Box<str>` axis but not the borrowed-input
3483/// axis forces every borrowed-input `Box<str>`-parameterized call
3484/// site through a spurious [`Copy`] deref
3485/// (`Box::<str>::from((*policy).as_str())`) or a
3486/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
3487/// have no compile-time link back to the substrate primitive.
3488///
3489/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
3490/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
3491/// — closes the whole `{Self, &Self}` input-shape corner of the
3492/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
3493/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
3494/// closed the paired [`Cow<'static, str>`] axis one commit after
3495/// its owning half (0612398) landed on this enum. The remaining
3496/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
3497/// core / render-side / outside-caixa-core tiers are the future
3498/// targets of the [`Box<str>`] campaign.
3499///
3500/// Pinned load-bearing by
3501/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
3502/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3503/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
3504/// surface, plus a blanket-derived [`Into`] shape witness, a
3505/// cross-axis partition pin against the paired owned-input
3506/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
3507/// input `{&'static str, String, Cow<'static, str>}` return-shape
3508/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
3509/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
3510/// by construction, so the borrowed-input [`Box<str>`] axis is
3511/// what routes the pipe through the substrate-primitive
3512/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
3513/// deref).
3514impl From<&RestartPolicy> for Box<str> {
3515 fn from(policy: &RestartPolicy) -> Box<str> {
3516 Box::<str>::from(policy.as_str())
3517 }
3518}
3519
3520/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
3521/// forward projection on the M2 OTP-shape per-child-restart
3522/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
3523/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
3524/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
3525/// returned `&'static str`, so every consumer that binds a
3526/// [`RestartPolicy`] through the standard-library `.into()` /
3527/// [`From<Self> for std::sync::Arc<str>`] (equivalently
3528/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
3529/// per-request `Sync` + `Send`-safe structured-log field composed
3530/// across an `.await` boundary through a
3531/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
3532/// a future wasm-operator's per-child post-exit restart-decision
3533/// pipeline holding a shared-ownership per-arm cache key, a
3534/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
3535/// collector recording a per-child-policy field onto the parent
3536/// span's shared-ownership context — reaches the same three-arm
3537/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3538/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3539/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3540/// sibling
3541/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
3542/// forward-projection corner already returns.
3543///
3544/// Second peer on the substrate-wide trait-idiomatic
3545/// [`std::sync::Arc<str>`] forward-projection family opened one
3546/// projection tier prior (bca2ec8) on the paired sibling-restart
3547/// [`RestartStrategy`] owned-input first-mover — extends the tier
3548/// onto the second (and third-and-final) M2 OTP-shape closed-set
3549/// fieldless typed enum peer on the caixa surface
3550/// (`:children :restart`), immediately after the paired [`Box<str>`]
3551/// axis (0a1b313 / cb1d068) closed the whole
3552/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
3553/// 2×4 corner on this enum. Rust's standard library carries
3554/// `impl From<&str> for std::sync::Arc<str>` and
3555/// `impl From<String> for std::sync::Arc<str>` but no blanket
3556/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
3557/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
3558/// axis is a distinct trait-idiomatic surface that a
3559/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
3560/// reaches through this impl and no other — a paired
3561/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
3562/// compile-time link back to the substrate primitive, and a two-step
3563/// `std::sync::Arc::<str>::from(String::from(policy))` composition
3564/// through the owned-`String` axis allocates twice (once into the
3565/// intermediate `String`, once into the [`Arc<str>`] on the
3566/// `From<String>` conversion) where the single-step trait impl
3567/// allocates once.
3568///
3569/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
3570/// same "extends the substrate-wide projection tier onto the next
3571/// M2 OTP-shape peer" discipline, extended onto the
3572/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
3573/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
3574/// owned-move return-shape cannot provide.
3575///
3576/// Pinned load-bearing by
3577/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
3578/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3579/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
3580/// surface, plus a blanket-derived [`Into`] shape witness and cross-
3581/// axis byte-parity pins against the sibling owned-input
3582/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
3583/// axes).
3584impl From<RestartPolicy> for std::sync::Arc<str> {
3585 fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
3586 std::sync::Arc::<str>::from(policy.as_str())
3587 }
3588}
3589
3590/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
3591/// forward projection on the M2 OTP-shape per-child-restart
3592/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
3593/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
3594/// forward-projection axis on the second (and third-and-final) M2
3595/// OTP-shape closed-set fieldless typed enum peer on the caixa
3596/// surface (`:children :restart`), companion to the paired
3597/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
3598/// one commit prior (b05724e). Routes byte-for-byte through the
3599/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3600/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
3601/// `&'static str`), so every consumer that binds a
3602/// [`&RestartPolicy`] through the standard-library `.into()` /
3603/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
3604/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
3605/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
3606/// `Sync` + `Send`-safe structured-log field across an `.await`
3607/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
3608/// diagnostic-column dispatch, a future wasm-operator's per-child
3609/// post-exit restart-decision pipeline whose
3610/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
3611/// into the shared-ownership per-arm key without a spurious [`Copy`]
3612/// deref (which would only be reachable through the owned-input
3613/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
3614/// calling `.copied()` on the iterator), a future
3615/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
3616/// collector recording a borrowed-`&RestartPolicy` per-arm field
3617/// onto the parent span's shared-ownership context — reaches the
3618/// same three-arm lifted
3619/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3620/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3621/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3622/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
3623/// impl and the sibling `{&'static str, String, Cow<'static, str>,
3624/// Box<str>}` forward-projection corner already return.
3625///
3626/// Closes the substrate-wide trait-idiomatic
3627/// [`std::sync::Arc<str>`] forward-projection family opened one
3628/// commit prior (b05724e) on the paired owned-input
3629/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
3630/// the `{Self, &Self}` input-shape corner of the
3631/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
3632/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
3633/// surface, exactly as b3e72d7 closed the paired
3634/// [`std::sync::Arc<str>`] corner on the sibling-restart
3635/// [`RestartStrategy`] first-mover one commit after its owning half
3636/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
3637/// corner on this enum one commit after its owning half (0a1b313)
3638/// landed. Rust's standard library carries `impl From<&str> for
3639/// std::sync::Arc<str>` and `impl From<String> for
3640/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
3641/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
3642/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
3643/// enum peer on the substrate that carries the paired owned-input
3644/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
3645/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
3646/// call site through a spurious [`Copy`] deref
3647/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
3648/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
3649/// type bounds have no compile-time link back to the substrate
3650/// primitive.
3651///
3652/// Pinned load-bearing by
3653/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
3654/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3655/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
3656/// surface, plus a blanket-derived [`Into`] shape witness, a
3657/// cross-axis pin against the paired owned-input
3658/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
3659/// borrowed-input `{&'static str, String, Cow<'static, str>,
3660/// Box<str>}` return-shape axes, and a
3661/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
3662/// [`RestartPolicy::ALL`]).
3663impl From<&RestartPolicy> for std::sync::Arc<str> {
3664 fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
3665 std::sync::Arc::<str>::from(policy.as_str())
3666 }
3667}
3668
3669/// Trait-idiomatic *owned-input, [`std::rc::Rc<str>`] output* forward
3670/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3671/// closed-set fieldless typed enum — the single-threaded reference-
3672/// counted peer of the paired owned-input
3673/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl (b05724e) on the
3674/// sibling atomically-reference-counted [`std::sync::Arc<str>`] axis.
3675/// Routes byte-for-byte through the substrate-primitive
3676/// [`RestartPolicy::as_str`] `pub const fn` accessor via
3677/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`.
3678///
3679/// Rust's standard library carries `impl From<&str> for std::rc::Rc<str>`
3680/// and `impl From<String> for std::rc::Rc<str>` but no blanket
3681/// `impl<T: AsRef<str>> From<T> for std::rc::Rc<str>` (nor a `From<&T>`
3682/// blanket), and the [`std::sync::Arc<str>`] and [`std::rc::Rc<str>`]
3683/// trait tables are disjoint — so a single-threaded caixa-operator
3684/// reconciliation pass that shares the `:children :restart` wire
3685/// byte-string across intra-reconcile-loop tree nodes through the cheaper
3686/// non-atomic [`std::rc::Rc<str>`] refcount (the atomically-reference-
3687/// counted [`std::sync::Arc<str>`] return-shape cannot provide within a
3688/// single-threaded reconciliation pass without paying the atomic-fence
3689/// cost the [`std::rc::Rc<str>`] axis skips by construction) reaches
3690/// the substrate primitive through this impl and no other.
3691///
3692/// Closes the substrate-wide trait-idiomatic [`std::rc::Rc<str>`]
3693/// forward-projection axis on the M2-OTP-shape `:supervisor
3694/// :estrategia` and `:children :restart` slot pair the sibling-restart
3695/// [`RestartStrategy`] first-mover (71ad8f4) opened one projection tier
3696/// prior on the paired sibling enum — closes the paired axis on the
3697/// second (and third-and-final) M2 OTP-shape closed-set fieldless typed
3698/// enum peer on the caixa surface, matching the discipline the paired
3699/// [`std::sync::Arc<str>`] forward-projection axis campaign already
3700/// carried across the same slot pair (bca2ec8 → b3e72d7 on
3701/// [`RestartStrategy`]; b05724e → borrowed-close on this enum).
3702///
3703/// Pinned load-bearing by
3704/// [`tests::restart_policy_from_into_rc_str_routes_through_as_str_accessor`]
3705/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3706/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
3707/// surface, plus a blanket-derived [`Into`] shape witness and cross-
3708/// axis byte-parity pins against the sibling owned-input `{&'static
3709/// str, String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
3710/// return-shape axes).
3711impl From<RestartPolicy> for std::rc::Rc<str> {
3712 fn from(policy: RestartPolicy) -> std::rc::Rc<str> {
3713 std::rc::Rc::<str>::from(policy.as_str())
3714 }
3715}
3716
3717/// Trait-idiomatic *borrowed-input, [`std::rc::Rc<str>`] output* forward
3718/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3719/// closed-set fieldless typed enum — the borrowed-input companion to
3720/// the paired owned-input [`From<RestartPolicy> for std::rc::Rc<str>`]
3721/// impl immediately above, closing the `{Self, &Self}` input-shape
3722/// corner of the [`std::rc::Rc<str>`] axis on the second (and third-
3723/// and-final) M2 OTP-shape closed-set fieldless typed enum peer on the
3724/// caixa surface. Routes byte-for-byte through the substrate-primitive
3725/// [`RestartPolicy::as_str`] `pub const fn` accessor via
3726/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`, so a
3727/// `RestartPolicy::ALL.iter().map(std::rc::Rc::<str>::from)`-shaped
3728/// pipe (whose iterator over `&'static [RestartPolicy]` yields
3729/// `&RestartPolicy` by construction) reaches the same three-arm lifted
3730/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3731/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3732/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const roster
3733/// the paired owned-input axis and the sibling `{Self, &Self} ×
3734/// {&'static str, String, Cow<'static, str>, Box<str>,
3735/// std::sync::Arc<str>}` forward-projection corner already return.
3736///
3737/// Rust's standard library carries no blanket
3738/// `impl<T: AsRef<str>> From<&T> for std::rc::Rc<str>` (nor a `Copy`-
3739/// based `impl<T: Copy, U: From<T>> From<&T> for U`), so this borrowed-
3740/// input axis is a distinct trait-idiomatic surface — without it, the
3741/// `.iter().map(std::rc::Rc::<str>::from)` pipe would force a spurious
3742/// [`Copy`] deref or a `.copied()` restatement whose type bounds have
3743/// no compile-time link back to the substrate primitive.
3744///
3745/// Closes the substrate-wide trait-idiomatic [`std::rc::Rc<str>`]
3746/// forward-projection family on the M2-OTP-shape `:supervisor
3747/// :estrategia` + `:children :restart` slot pair — the sibling
3748/// [`RestartStrategy`] first-mover (71ad8f4) opened + closed the pair
3749/// on the sibling `:supervisor :estrategia` half one projection tier
3750/// prior, and the paired owned-input [`From<RestartPolicy> for
3751/// std::rc::Rc<str>`] impl immediately above opens the same axis on
3752/// this half — this borrowed-input impl closes it.
3753///
3754/// Pinned load-bearing by
3755/// [`tests::restart_policy_from_borrowed_into_rc_str_routes_through_as_str_accessor`]
3756/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3757/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
3758/// surface, plus a blanket-derived [`Into`] shape witness, a cross-
3759/// axis partition pin against the paired owned-input
3760/// [`From<RestartPolicy> for std::rc::Rc<str>`] and the sibling
3761/// borrowed-input `{&'static str, String, Cow<'static, str>, Box<str>,
3762/// std::sync::Arc<str>}` return-shape axes, and a
3763/// `.iter().map(std::rc::Rc::<str>::from)` pipe witness over
3764/// [`RestartPolicy::ALL`] that resolves through the borrowed-input
3765/// axis without a spurious [`Copy`] deref).
3766impl From<&RestartPolicy> for std::rc::Rc<str> {
3767 fn from(policy: &RestartPolicy) -> std::rc::Rc<str> {
3768 std::rc::Rc::<str>::from(policy.as_str())
3769 }
3770}
3771
3772/// Trait-idiomatic byte-view surface on the per-child restart-decision
3773/// policy typed enum.
3774///
3775/// Every consumer that binds its input through the standard-library
3776/// [`AsRef<[u8]>`] trait bound — a byte-keyed
3777/// `HashMap<K: AsRef<[u8]>, V>` per-policy reconciliation-decision
3778/// table lookup on the future wasm-operator supervisor scheduler; a
3779/// `blake3::Hasher::update` / `ring::digest::Context::update` /
3780/// `sha2::Sha256::update` byte-input surface on any future per-child
3781/// content-address digest folded into the [`crate::Lacre`] closure so
3782/// downstream cache-keys partition on the three OTP restart policies
3783/// (`Permanent`, `Temporary`, `Transient`) at content-address time; an
3784/// `std::io::Write::write_all`-bound structured-log per-arm byte-sink —
3785/// reaches the substrate primitive through one trait dispatch rather
3786/// than open-coding the two-hop `restart.as_str().as_bytes()`
3787/// composition at every call site. Routed byte-for-byte through the
3788/// [`RestartPolicy::as_str`] `pub const fn` accessor the paired
3789/// str-view ([`AsRef<str>`], [`std::fmt::Display`],
3790/// [`RestartPolicy::as_str`]) and the five reverse-projection
3791/// (`&'static str`, `String`, `Cow<'static, str>`, `Box<str>`,
3792/// `std::sync::Arc<str>`) return-shape axes already resolve through,
3793/// so any future divergence between the byte-view and str-view axes
3794/// trips at caixa-core test time rather than at a downstream byte-
3795/// consumer's silent split.
3796///
3797/// Peer of the sibling per-supervisor-restart-strategy axis
3798/// [`AsRef<[u8]> for RestartStrategy`] (cd4c4e0, the first M2-OTP-
3799/// shape supervisor slot enum to open this axis) — the sixth
3800/// closed-set fieldless typed enum on the caixa surface to converge
3801/// onto the trait-idiomatic byte-view discipline, and the second (and
3802/// final) M2-OTP-shape sibling to pick it up, closing the byte-view
3803/// axis across the paired `:supervisor :estrategia` +
3804/// `:children :restart` M2 slot pair. Pin load-bearing by the paired
3805/// [`tests::restart_policy_as_ref_bytes_routes_through_as_str_accessor`]
3806/// (fail-before-pass-after byte-parity pin against
3807/// [`RestartPolicy::as_str`] `.as_bytes()` across the three-arm
3808/// [`RestartPolicy::ALL`] emit-set, cross-axis witness against the
3809/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
3810/// [`RestartPolicy::as_str`] axes' `.as_bytes()` byte-tails,
3811/// cross-axis witness against the paired reverse-projection
3812/// `{&'static str, String, Cow<'static, str>, Box<str>,
3813/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
3814/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
3815/// byte-input function accepts a [`RestartPolicy`] directly through
3816/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
3817/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
3818/// consumer axis to reach the caixa-lacre compounding target). Any
3819/// future silent detour that routes the byte-view impl off the
3820/// substrate-primitive [`RestartPolicy::as_str`] accessor (a per-arm
3821/// inline `b"Permanent".as_slice()`-shaped re-inlining that opens a
3822/// compile-time link to the un-lifted arm-literal, a swap onto the
3823/// kebab-case [`gen_platform::Discriminant`] catalog identity that
3824/// would collide the wire axis with the dispatcher-catalog axis) trips
3825/// at caixa-core test time rather than at a downstream byte-consumer's
3826/// silent split.
3827impl AsRef<[u8]> for RestartPolicy {
3828 fn as_ref(&self) -> &[u8] {
3829 self.as_str().as_bytes()
3830 }
3831}
3832
3833/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
3834/// reverse projection on the second (and final) M2 OTP-shape closed-set
3835/// fieldless typed enum peer on the caixa surface ([`RestartPolicy`]) —
3836/// the byte-mirror of the [`From<RestartPolicy> for String`] str-owned
3837/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
3838/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
3839/// (98b08fa) lifted on this same enum. Routes byte-for-byte through
3840/// the substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3841/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
3842/// consumer that binds a [`RestartPolicy`] through the standard-
3843/// library `impl From<RestartPolicy> for Vec<u8>` axis
3844/// (equivalently `<T: Into<Vec<u8>>>`) — a future
3845/// [`std::io::Write::write_all`]-shape per-child audit-log byte-sink
3846/// whose input parameter is an owned [`Vec<u8>`] payload, a future
3847/// `bytes::Bytes::from(Vec::<u8>::from(restart))` composer folding
3848/// the per-arm restart-decision-policy byte-tag into the
3849/// [`bytes::Bytes`] framing surface, a future
3850/// `hasher.update(&Vec::<u8>::from(restart))`-shape BLAKE3 content-
3851/// address closure that needs the owned byte-tail buffered before
3852/// folding into the [`crate::Lacre`] closure body, a future per-child
3853/// protobuf/CBOR/msgpack payload composer whose framer takes an owned
3854/// [`Vec<u8>`] rather than a borrowed byte-slice — reaches the
3855/// substrate primitive through one trait dispatch rather than an
3856/// open-coded per-call-site `restart.as_str().as_bytes().to_vec()`
3857/// composition whose type bounds have no compile-time link back to
3858/// the substrate primitive.
3859///
3860/// Closes the substrate-wide trait-idiomatic byte-owned reverse-
3861/// projection axis on the M2-OTP-shape `:supervisor :estrategia` +
3862/// `:children :restart` slot pair the sibling
3863/// [`RestartStrategy`] first-mover (63e5dd0) opened one commit prior,
3864/// matching the discipline the paired [`AsRef<[u8]>`] borrowed byte-
3865/// view axis campaign already carried across the same slot pair
3866/// (cd4c4e0 → 98b08fa). Every future arm addition (an OTP-
3867/// `intrinsic` fourth arm the theory
3868/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3869/// might reach for once the three canonical OTP restart policies
3870/// stop covering the substrate's discovered load-shape) grows the
3871/// byte-owned axis through one edit on the substrate-primitive
3872/// [`RestartPolicy::as_str`] accessor.
3873///
3874/// Pinned load-bearing by
3875/// [`tests::restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
3876/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3877/// three-arm [`RestartPolicy::ALL`] emit-set binding the byte-owned
3878/// reverse-projection axis against the paired [`AsRef<[u8]>`]
3879/// borrowed byte-view axis and the str-owned reverse-projection
3880/// family (`String`, `Cow<'static, str>`, `Box<str>`,
3881/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
3882/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
3883/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
3884/// witness on both owned and borrowed input shapes).
3885impl From<RestartPolicy> for Vec<u8> {
3886 fn from(policy: RestartPolicy) -> Vec<u8> {
3887 policy.as_str().as_bytes().to_vec()
3888 }
3889}
3890
3891/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
3892/// owned reverse projection on the second (and final) M2 OTP-shape
3893/// closed-set fieldless typed enum peer on the caixa surface
3894/// ([`RestartPolicy`]) — the borrowed-input peer of
3895/// [`From<RestartPolicy> for Vec<u8>`], closing the
3896/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
3897/// axis in one lift. Routes byte-for-byte through the substrate-
3898/// primitive [`RestartPolicy::as_str`] `pub const fn` accessor so
3899/// every consumer that holds a borrowed [`&RestartPolicy`] and needs
3900/// an owned [`Vec<u8>`] — a future
3901/// `.iter().map(Vec::<u8>::from).collect()` pipe over
3902/// `&[RestartPolicy]` (whose iterator yields `&RestartPolicy`,
3903/// not `RestartPolicy`, so the owned-input axis alone forces every
3904/// call site through an explicit `.copied()` / spurious [`Copy`]
3905/// deref restatement rather than the direct trait-idiomatic
3906/// projection), a future admission-webhook rejection body composer
3907/// that walks [`RestartPolicy::ALL`] through an `Into<Vec<u8>>`-
3908/// bound per-arm byte-writer to surface the accepted `:children
3909/// :restart` set — reaches the substrate primitive through one
3910/// trait dispatch rather than a `Vec::<u8>::from(*policy)` spurious-
3911/// [`Copy`]-deref restatement.
3912impl From<&RestartPolicy> for Vec<u8> {
3913 fn from(policy: &RestartPolicy) -> Vec<u8> {
3914 policy.as_str().as_bytes().to_vec()
3915 }
3916}
3917
3918/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, [u8]>`]
3919/// output* byte-owned reverse projection on the second (and final) M2
3920/// OTP-shape closed-set fieldless typed enum peer on the caixa surface
3921/// ([`RestartPolicy`]) — the [`std::borrow::Cow<'static, [u8]>`] byte-
3922/// mirror of the paired [`From<RestartPolicy> for
3923/// std::borrow::Cow<'static, str>`] str-side impl and the
3924/// [`std::borrow::Cow<'static, [u8]>`] companion of the paired byte-
3925/// owned [`From<RestartPolicy> for Vec<u8>`] reverse-projection axis
3926/// immediately above. Routes byte-for-byte through the substrate-
3927/// primitive [`RestartPolicy::as_str`] `pub const fn` accessor via
3928/// [`std::borrow::Cow::Borrowed`]`(policy.as_str().as_bytes())` — the
3929/// three `match` arms in [`Self::as_str`] resolve to
3930/// [`crate::render::SUPERVISOR_RESTART_*`] `pub const &'static str`
3931/// bodies, so `.as_bytes()` on each returns `&'static [u8]` by
3932/// construction, and the zero-alloc [`Cow::Borrowed`] arm is the
3933/// type-correct projection with no runtime allocation (mirroring the
3934/// paired [`Cow<'static, str>`] axis's own [`Cow::Borrowed`] discipline
3935/// on this same primitive; contrasts with the sibling
3936/// [`crate::CaixaVersion`] [`Cow<'static, [u8]>`] impl, whose wrapped
3937/// [`String`] storage is a runtime heap allocation with no
3938/// `&'static [u8]` lifetime, forcing the [`Cow::Owned`] arm there).
3939///
3940/// Extends the substrate-wide trait-idiomatic byte-owned reverse-
3941/// projection matrix onto the second (and final) M2-OTP-shape closed-
3942/// set fieldless typed-enum peer at the [`Cow<'static, [u8]>`] corner,
3943/// following the trajectory the sibling [`RestartStrategy`] first-mover
3944/// (7f81539) opened one axis prior on the paired M2-OTP-shape enum, and
3945/// mirroring the discipline the paired byte-owned [`Vec<u8>`] axis
3946/// campaign already tracked onto this primitive one commit sequence
3947/// prior.
3948impl From<RestartPolicy> for std::borrow::Cow<'static, [u8]> {
3949 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, [u8]> {
3950 std::borrow::Cow::Borrowed(policy.as_str().as_bytes())
3951 }
3952}
3953
3954/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, [u8]>`]
3955/// output* byte-owned reverse projection on the second (and final) M2
3956/// OTP-shape closed-set fieldless typed enum peer on the caixa surface
3957/// ([`RestartPolicy`]) — the borrowed-input companion to the paired
3958/// owned-input [`From<RestartPolicy> for std::borrow::Cow<'static, [u8]>`]
3959/// impl immediately above, closing the `{Self, &Self} → Cow<'static, [u8]>`
3960/// byte-owned reverse-projection family on this primitive at the
3961/// borrowed-input corner. Routes byte-for-byte through the same
3962/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn` accessor
3963/// via [`std::borrow::Cow::Borrowed`]`(policy.as_str().as_bytes())` —
3964/// the [`Cow::Borrowed`] arm is reachable on both input axes because
3965/// [`Self::as_str`] returns `&'static str` regardless of the input shape,
3966/// so no runtime allocation is forced on either corner. Rust's `From`
3967/// trait carries no blanket `impl<T> From<&T> for U where U: From<T>`
3968/// (nor an `impl<T: AsRef<[u8]>> From<&T> for Cow<'static, [u8]>`), so
3969/// every closed-set fieldless typed enum peer that carries the paired
3970/// owned-input axis but not the borrowed-input axis forces every
3971/// borrowed call site through a spurious [`Copy`] deref
3972/// (`Cow::<'static, [u8]>::from(*policy)`) or an open-coded
3973/// `Cow::Borrowed(policy.as_str().as_bytes())` whose type bounds have no
3974/// compile-time link to the substrate primitive.
3975impl From<&RestartPolicy> for std::borrow::Cow<'static, [u8]> {
3976 fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, [u8]> {
3977 std::borrow::Cow::Borrowed(policy.as_str().as_bytes())
3978 }
3979}
3980
3981/// Trait-idiomatic *owned-input, [`Box<[u8]>`] output* byte-owned reverse
3982/// projection on the second (and final) M2-OTP-shape closed-set fieldless
3983/// typed enum peer on the caixa surface ([`RestartPolicy`]) — the
3984/// [`Box<[u8]>`] companion to the paired owned-input
3985/// [`From<RestartPolicy> for Vec<u8>`] and
3986/// [`From<RestartPolicy> for std::borrow::Cow<'static, [u8]>`] reverse-
3987/// projection impls on this same primitive, mirroring the paired string-
3988/// side [`From<RestartPolicy> for Box<str>`] forward-projection axis onto
3989/// the byte-family side of the reverse-projection matrix and tracking the
3990/// trajectory the sibling [`RestartStrategy`] first-mover (e11150e) opened
3991/// one axis prior on the paired M2-OTP-shape enum. Routes byte-for-byte
3992/// through the substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3993/// accessor via [`Box::<[u8]>::from`] on the returned `&'static str`'s
3994/// [`str::as_bytes`] — the three `match` arms in [`Self::as_str`] resolve
3995/// to [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &'static str`
3996/// bodies, so `.as_bytes()` returns `&'static [u8]` by construction, and
3997/// the standard-library [`Box::<[u8]>::from(&[u8])`] impl allocates a fit-
3998/// to-length boxed byte slice in one heap allocation without an
3999/// intermediary [`Vec<u8>`].
4000///
4001/// Extends the substrate-wide trait-idiomatic *owned-input* byte-family
4002/// reverse-projection matrix onto the second (and final) M2-OTP-shape
4003/// closed-set fieldless typed enum peer at the [`Box<[u8]>`] corner,
4004/// closing the `{Vec<u8>, Cow<'static, [u8]>, Box<[u8]>}` three-corner
4005/// partition on the same wire byte-string this primitive already carries
4006/// on the paired [`Vec<u8>`] and [`Cow<'static, [u8]>`] axes. Rust's
4007/// standard library does not derive `From<Self> for Box<[u8]>` from
4008/// `From<Self> for Vec<u8>` (nor from `From<Self> for Cow<'static, [u8]>`),
4009/// so every closed-set fieldless typed enum peer that carries the paired
4010/// reverse [`Vec<u8>`] axis but not the paired [`Box<[u8]>`] axis forces
4011/// every [`Box<[u8]>`]-typed call site through a
4012/// `Vec::<u8>::from(policy).into_boxed_slice()` intermediary allocation
4013/// whose bounds carry no compile-time link back to the substrate primitive.
4014impl From<RestartPolicy> for Box<[u8]> {
4015 fn from(policy: RestartPolicy) -> Box<[u8]> {
4016 Box::<[u8]>::from(policy.as_str().as_bytes())
4017 }
4018}
4019
4020/// Trait-idiomatic *borrowed-input, [`Box<[u8]>`] output* byte-owned
4021/// reverse projection on the second (and final) M2-OTP-shape closed-set
4022/// fieldless typed enum peer on the caixa surface ([`RestartPolicy`]) —
4023/// the borrowed-input companion to the paired owned-input
4024/// [`From<RestartPolicy> for Box<[u8]>`] impl immediately above, closing
4025/// the `{Self, &Self} → Box<[u8]>` byte-owned reverse-projection family on
4026/// this primitive at the borrowed-input corner. Routes byte-for-byte
4027/// through the same substrate-primitive [`RestartPolicy::as_str`]
4028/// `pub const fn` accessor via [`Box::<[u8]>::from`] on the returned
4029/// `&'static str`'s [`str::as_bytes`] — the [`Box<[u8]>`] allocation
4030/// happens on both input axes because [`Self::as_str`] returns
4031/// `&'static str` regardless of the input shape, so the borrowed-input
4032/// peer reaches the same wire byte-string through the same one-heap-
4033/// allocation path the owned-input peer already carries.
4034///
4035/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U where
4036/// U: From<T>` (nor a `Copy`-based
4037/// `impl<T: Copy, U: From<T>> From<&T> for U`), so every closed-set
4038/// fieldless typed enum peer that carries the paired owned-input
4039/// [`Box<[u8]>`] axis but not the borrowed-input axis forces every
4040/// borrowed call site through a spurious [`Copy`] deref
4041/// (`Box::<[u8]>::from(*policy)`) or an open-coded
4042/// `Box::<[u8]>::from(policy.as_str().as_bytes())` whose type bounds
4043/// have no compile-time link to the substrate primitive.
4044impl From<&RestartPolicy> for Box<[u8]> {
4045 fn from(policy: &RestartPolicy) -> Box<[u8]> {
4046 Box::<[u8]>::from(policy.as_str().as_bytes())
4047 }
4048}
4049
4050/// Trait-idiomatic *owned-input, [`std::sync::Arc<[u8]>`] output* byte-owned
4051/// reverse projection on the second (and final) M2-OTP-shape closed-set
4052/// fieldless typed enum peer on the caixa surface ([`RestartPolicy`]) — the
4053/// atomically-refcounted byte-slice mirror of the paired owned-input
4054/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl on the string-side
4055/// reverse-projection matrix, and the fourth axis on the byte-side reverse-
4056/// projection matrix that already carries
4057/// [`From<RestartPolicy> for Vec<u8>`],
4058/// [`From<RestartPolicy> for std::borrow::Cow<'static, [u8]>`] (65f381b),
4059/// and [`From<RestartPolicy> for Box<[u8]>`] (6bc74c9). Routes byte-for-
4060/// byte through the substrate-primitive [`RestartPolicy::as_str`]
4061/// `pub const fn` accessor via [`std::sync::Arc::<[u8]>::from`] on the
4062/// returned `&'static str`'s [`str::as_bytes`] — the three `match` arms in
4063/// [`Self::as_str`] resolve to [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
4064/// `pub const &'static str` bodies, so `.as_bytes()` returns `&'static [u8]`
4065/// by construction, and the standard-library
4066/// [`std::sync::Arc::<[u8]>::from(&[u8])`] impl allocates an atomically-
4067/// refcounted heap slab in one heap allocation without an intermediary
4068/// [`Vec<u8>`] or [`Box<[u8]>`].
4069///
4070/// Rust's standard library does not derive `From<Self> for Arc<[u8]>` from
4071/// `From<Self> for Vec<u8>` (nor from `From<Self> for Box<[u8]>`), so every
4072/// closed-set fieldless typed enum peer that carries the paired reverse
4073/// [`Vec<u8>`] or [`Box<[u8]>`] axis but not the paired [`Arc<[u8]>`] axis
4074/// forces every [`Arc<[u8]>`]-typed call site through a
4075/// `Vec::<u8>::from(policy).into()` / `Box::<[u8]>::from(policy).into()`
4076/// double-allocation detour whose bounds carry no compile-time link back
4077/// to the substrate primitive.
4078///
4079/// Extends the substrate-wide trait-idiomatic *owned-input* byte-family
4080/// reverse-projection matrix onto the second (and final) M2-OTP-shape
4081/// closed-set fieldless typed enum peer at the [`std::sync::Arc<[u8]>`]
4082/// corner, tracking the trajectory the sibling [`RestartStrategy`] first-
4083/// mover (98da8f6) walked one axis prior on the paired M2-OTP-shape enum.
4084impl From<RestartPolicy> for std::sync::Arc<[u8]> {
4085 fn from(policy: RestartPolicy) -> std::sync::Arc<[u8]> {
4086 std::sync::Arc::<[u8]>::from(policy.as_str().as_bytes())
4087 }
4088}
4089
4090/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<[u8]>`] output*
4091/// byte-owned reverse projection on the second (and final) M2-OTP-shape
4092/// closed-set fieldless typed enum peer on the caixa surface
4093/// ([`RestartPolicy`]) — the borrowed-input companion to the paired owned-
4094/// input [`From<RestartPolicy> for std::sync::Arc<[u8]>`] impl immediately
4095/// above, closing the `{Self, &Self} → std::sync::Arc<[u8]>` byte-owned
4096/// reverse-projection family on this primitive at the borrowed-input
4097/// corner. Routes byte-for-byte through the same substrate-primitive
4098/// [`RestartPolicy::as_str`] `pub const fn` accessor via
4099/// [`std::sync::Arc::<[u8]>::from`] on the returned `&'static str`'s
4100/// [`str::as_bytes`] — the [`std::sync::Arc<[u8]>`] allocation happens on
4101/// both input axes because [`Self::as_str`] returns `&'static str`
4102/// regardless of the input shape, so the borrowed-input peer reaches the
4103/// same wire byte-string through the same one-heap-allocation path the
4104/// owned-input peer already carries.
4105///
4106/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U where
4107/// U: From<T>` (nor a `Copy`-based
4108/// `impl<T: Copy, U: From<T>> From<&T> for U`), so every closed-set
4109/// fieldless typed enum peer that carries the paired owned-input
4110/// [`std::sync::Arc<[u8]>`] axis but not the borrowed-input axis forces
4111/// every borrowed call site through a spurious [`Copy`] deref
4112/// (`std::sync::Arc::<[u8]>::from(*policy)`) or an open-coded
4113/// `std::sync::Arc::<[u8]>::from(policy.as_str().as_bytes())` whose type
4114/// bounds have no compile-time link to the substrate primitive.
4115impl From<&RestartPolicy> for std::sync::Arc<[u8]> {
4116 fn from(policy: &RestartPolicy) -> std::sync::Arc<[u8]> {
4117 std::sync::Arc::<[u8]>::from(policy.as_str().as_bytes())
4118 }
4119}
4120
4121/// Trait-idiomatic *borrowed byte-slice input* reverse projection on the
4122/// second (and final) M2-OTP-shape closed-set fieldless typed enum peer on
4123/// the caixa surface ([`RestartPolicy`]) — the byte-view mirror of the
4124/// str-view reverse-projection axis carried by the paired
4125/// [`TryFrom<&str> for RestartPolicy`] impl (which routes through the
4126/// substrate-primitive [`RestartPolicy::from_wire`] `Option<Self>` accessor
4127/// on the three-arm `PascalCase` accept-set the sibling
4128/// [`RestartPolicy::as_str`] emitter returns). Routes byte-for-byte through
4129/// the standard-library [`std::str::from_utf8`] UTF-8 validator and then
4130/// through [`RestartPolicy::from_wire`] so every consumer that holds a
4131/// borrowed [`&[u8]`] and needs to project it back into a typed
4132/// [`RestartPolicy`] — a future `bytes::Bytes::as_ref()`-fed reader that
4133/// parses a per-child `:restart` `PascalCase` wire scalar from an
4134/// already-borrowed framing byte-tail (a
4135/// `tracing::field::valuable::Value::Bytes` recorder on the future
4136/// wasm-operator's per-child restart-decision diagnostic emission path, a
4137/// future audit-report re-loader binding a prior
4138/// [`RestartPolicy::as_str`] output from a mmap'd byte-slice back through
4139/// the typed enum for cross-run comparison), a future M4
4140/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook rejection body
4141/// that reads a `spec.children[].restart` field off a raw HTTP body
4142/// byte-slice before UTF-8 validation commits allocation, a future generic
4143/// `<T: for<'a> TryFrom<&'a [u8]>>`-bound loader over any of the
4144/// substrate's closed-set typed enums — reaches the same three-arm
4145/// `PascalCase` wire accept-set the sibling method-named
4146/// [`RestartPolicy::from_wire`] resolver and the paired trait-idiomatic
4147/// [`TryFrom<&str>`] axis already resolve against, rather than an open-
4148/// coded per-call-site
4149/// `std::str::from_utf8(bytes).ok().and_then(RestartPolicy::from_wire)`
4150/// composition or a
4151/// `<RestartPolicy as TryFrom<&str>>::try_from(std::str::from_utf8(bytes)?)`
4152/// two-hop shape whose type bounds have no compile-time link to the
4153/// substrate primitive.
4154///
4155/// Closes the substrate-wide trait-idiomatic *byte-view reverse-projection*
4156/// family on the M2-OTP-shape `:supervisor :estrategia` + `:children
4157/// :restart` slot pair the sibling [`RestartStrategy`] first-mover
4158/// (c699a83) opened one commit prior — extends the family from
4159/// [`crate::CaixaKind`] (18d1940), [`crate::CaixaDialeto`] (d102cb8),
4160/// [`crate::dep::DepList`] (b8f25d5), and [`RestartStrategy`] (c699a83)
4161/// onto the second (and final) M2-OTP-shape closed-set fieldless typed
4162/// enum peer on the caixa surface, matching the trajectory the paired
4163/// byte-owned reverse-projection axis campaign already walked across the
4164/// same slot pair (63e5dd0 → 96a522a). Rust's standard library carries no
4165/// blanket `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a
4166/// two-hop composition through [`std::str::from_utf8`] + the paired
4167/// [`TryFrom<&str>`] axis is reachable at every call site but has no
4168/// compile-time link back to the byte-view reverse-projection axis. Every
4169/// remaining closed-set fieldless typed enum peer on the substrate
4170/// ([`crate::aplicacao::PlacementStrategy`],
4171/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
4172/// and the outside-`caixa-core` peers `PathShapeViolation`,
4173/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
4174/// `FerriteRuntime`) is a future target of the campaign.
4175///
4176/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
4177/// `Option<Self>` return-shape's deliberate deferral of error typing and
4178/// the paired trait-idiomatic [`TryFrom<&str>`] axis's unit-error shape —
4179/// the caller picks the diagnostic form appropriate for its use site (a
4180/// future `feira supervisor --restart …` arg-parse composes its own
4181/// per-verb "unknown restart policy: <arg> — accepted: {…}" message
4182/// enumerating [`RestartPolicy::WIRE_NAMES`]; a future admission-webhook
4183/// rejection body wraps the `Err(())` outcome with the accepted-set
4184/// enumeration for operator diagnostics; a `Result::map_err` at the call
4185/// site lifts the unit-error to a per-verb error type). Two rejection
4186/// paths route through the single unit-error: an invalid UTF-8
4187/// byte-sequence ([`std::str::from_utf8`] returns `Err`) and a valid UTF-8
4188/// byte-string that falls outside the three-arm `PascalCase` accept-set
4189/// ([`RestartPolicy::from_wire`] returns `None`) — both collapse onto
4190/// `Err(())` so the trait signature stays consistent with the sibling
4191/// str-view reverse axis, and a caller that needs to distinguish the two
4192/// failure modes composes [`std::str::from_utf8`] +
4193/// [`RestartPolicy::from_wire`] explicitly.
4194///
4195/// Pinned load-bearing by
4196/// [`tests::restart_policy_try_from_bytes_routes_through_from_wire_accessor`]
4197/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
4198/// three-arm [`RestartPolicy::ALL`] accept-set on the borrowed byte-slice
4199/// surface, plus a cross-axis witness that the byte-view reverse
4200/// projection agrees with the paired [`TryFrom<&str>`] str-view reverse
4201/// axis on every accepted arm, and a forward/reverse byte-view cross-axis
4202/// witness that feeding the paired [`AsRef<[u8]>`] byte-tail back through
4203/// the new impl round-trips to the originating arm) and
4204/// [`tests::restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
4205/// (rejection witness against silent accept-set widening on both the
4206/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
4207/// rejection path — the latter includes the sibling kebab-case
4208/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
4209/// a caller that confuses the two axes trips here rather than at a
4210/// downstream K8s-CR round-trip miss).
4211impl TryFrom<&[u8]> for RestartPolicy {
4212 type Error = ();
4213
4214 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
4215 std::str::from_utf8(bytes)
4216 .ok()
4217 .and_then(Self::from_wire)
4218 .ok_or(())
4219 }
4220}
4221
4222/// Trait-idiomatic *owned byte-vec input* reverse projection on the second
4223/// (and final) M2-OTP-shape supervisor-slot closed-set fieldless typed enum
4224/// peer on the caixa surface ([`RestartPolicy`]) — the owned-input peer of
4225/// [`TryFrom<&[u8]> for RestartPolicy`], closing the byte-view reverse-
4226/// projection *square* ({owned-input, borrowed-input} × {owned-output
4227/// byte-vec, borrowed-output byte-slice}) on the M2-OTP-shape
4228/// `:supervisor :estrategia` + `:children :restart` slot pair the sibling
4229/// [`RestartStrategy`] first-mover (34951fe) opened on the byte-owned
4230/// reverse-input axis one commit-window prior. Routes byte-for-byte through
4231/// [`<Self as TryFrom<&[u8]>>::try_from`] on the [`Vec<u8>::as_slice`]
4232/// borrow so the owned-input surface reaches the same
4233/// [`std::str::from_utf8`] + [`RestartPolicy::from_wire`] resolution chain
4234/// the borrowed-input peer already carries — one substrate-primitive
4235/// accessor, one trait dispatch, no per-consumer detour.
4236///
4237/// Rust's standard library carries no blanket
4238/// `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`, so a
4239/// consumer that holds an owned [`Vec<u8>`] and needs a typed
4240/// [`RestartPolicy`] otherwise picks between (a) an open-coded
4241/// `<RestartPolicy as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at every
4242/// call site (whose type bounds have no compile-time link to the byte-
4243/// owned reverse-projection axis), (b) a two-hop
4244/// `String::from_utf8(bytes)` + [`RestartPolicy::from_wire`] composition
4245/// whose error surface leaks the standard-library
4246/// [`std::string::FromUtf8Error`] (widening the sibling [`TryFrom<&[u8]>`]
4247/// axis's unit-error) and silently allocates a [`String`] on inputs that
4248/// will never make it past the wire vocabulary, or (c) an intermediate
4249/// `<RestartPolicy as TryFrom<&str>>::try_from(std::str::from_utf8(&bytes)?)`
4250/// three-hop shape. This impl closes the owned-byte-vec reverse-projection
4251/// axis at the substrate-primitive [`RestartPolicy::from_wire`] accessor so
4252/// every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec consumer — a
4253/// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook body
4254/// reader that hands the `spec.children[].restart` byte-tail off as a
4255/// [`Vec<u8>`] before UTF-8 validation commits allocation, a
4256/// `bytes::Bytes::to_vec()`-shape wire-body composer walking a prior
4257/// audit's per-child rejection payload back to the typed enum, a
4258/// `std::io::Read::read_to_end`-shape audit-log source whose framing yields
4259/// an owned byte-vec per per-policy scalar, an
4260/// `<T: TryFrom<Vec<u8>>>`-bound generic loader over any of the
4261/// substrate's closed-set typed enums — reaches the same three-arm
4262/// `PascalCase` wire accept-set through one trait dispatch.
4263///
4264/// Extends the substrate-wide trait-idiomatic *byte-owned reverse-
4265/// projection* family — opened on the structurally most fundamental
4266/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
4267/// 99c2849), extended onto the second caixa-core-internal peer
4268/// ([`crate::CaixaDialeto`], commit 83a1526), the third
4269/// ([`crate::dep::DepList`], commit 42091cb), and the first M2-OTP-shape
4270/// supervisor-slot peer ([`RestartStrategy`], commit 34951fe) — onto the
4271/// second (and final) M2-OTP-shape supervisor-slot closed-set fieldless
4272/// typed enum peer, tracking the "delegate through `TryFrom<&[u8]>` on the
4273/// `Vec<u8>::as_slice` borrow" discipline the first-mover established.
4274/// Every remaining closed-set fieldless typed enum peer on the substrate
4275/// ([`crate::aplicacao::PlacementStrategy`],
4276/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
4277/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
4278/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
4279/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
4280/// mirroring the trajectory the closed byte-view reverse-projection
4281/// family (`TryFrom<&[u8]>`) and the closed byte-owned forward-projection
4282/// family (`From<{Self, &Self}> for Vec<u8>`) already walked across the
4283/// same slot pair.
4284///
4285/// `type Error = ()` matches the sibling [`TryFrom<&[u8]> for
4286/// RestartPolicy`] unit-error shape, preserving the trait-family
4287/// consistency across the borrowed-and-owned byte-view reverse-projection
4288/// pair. The owned [`Vec<u8>`] input is dropped on the error path (the
4289/// standard-library `String::from_utf8` convention of returning the input
4290/// in the error deliberately declined — a caller that needs the bytes back
4291/// holds a clone before the call, and the closed-set-enum use site rarely
4292/// wants the raw bytes back past a "did you mean" diagnostic that operates
4293/// on the wire vocabulary rather than the input).
4294///
4295/// Pinned load-bearing by
4296/// [`tests::restart_policy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
4297/// (byte-parity pin against the paired borrowed [`TryFrom<&[u8]>`] axis
4298/// across the three-arm [`RestartPolicy::ALL`] accept-set on the owned
4299/// byte-vec surface, cross-axis witness that the byte-owned reverse
4300/// projection agrees with the paired str-view reverse-projection axis
4301/// ([`TryFrom<&str>`]) on every accepted arm through the shared substrate-
4302/// primitive [`RestartPolicy::from_wire`] accessor, and a four-corner
4303/// {owned-input, borrowed-input} × {`From<Self>` → `Vec<u8>`,
4304/// `From<&Self>` → `Vec<u8>`} round-trip witness available on this enum
4305/// because [`RestartPolicy::as_str`] and [`RestartPolicy::from_wire`]
4306/// share one `PascalCase` byte-vocabulary — like the sibling
4307/// [`RestartStrategy`] and unlike the sibling [`crate::CaixaKind`] which
4308/// its peer test deliberately declines the four-corner witness on because
4309/// the wire/diagnostic split makes the forward and reverse pairs speak
4310/// different byte-strings) and
4311/// [`tests::restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
4312/// (rejection witness against silent accept-set widening on both the
4313/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
4314/// rejection path — the latter includes the sibling kebab-case
4315/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
4316/// a caller that confuses the two axes trips here rather than at a
4317/// downstream K8s-CR round-trip miss, plus a cross-axis witness that the
4318/// owned byte-vec reverse-projection axis agrees with the borrowed byte-
4319/// slice reverse-projection axis on every rejected input).
4320impl TryFrom<Vec<u8>> for RestartPolicy {
4321 type Error = ();
4322
4323 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
4324 <Self as TryFrom<&[u8]>>::try_from(bytes.as_slice())
4325 }
4326}
4327
4328/// Trait-idiomatic *owned-`String` input, `Result<Self, ()>` output*
4329/// string-owned reverse projection on the second (and final) M2-OTP-shape
4330/// supervisor-slot closed-set fieldless typed enum peer on the caixa
4331/// surface ([`RestartPolicy`]) — the owned-input peer of the paired
4332/// [`TryFrom<&str> for RestartPolicy`] str-view reverse-projection axis,
4333/// and the string-owned reverse companion of the pre-existing string-owned
4334/// *forward* pair ([`From<RestartPolicy> for String`],
4335/// [`From<&RestartPolicy> for String`]) already lifted on this same enum.
4336/// Routes owned [`String`] input through the paired borrowed-input
4337/// [`TryFrom<&str>`] axis via [`String::as_str`] so every consumer that
4338/// holds an owned `String` — a future M4 `mesh.pleme.io/v1alpha1/Supervisor`
4339/// CR admission-webhook body reader that hands the
4340/// `spec.children[].restart` `PascalCase` scalar off as an owned [`String`]
4341/// after UTF-8 validation, a `serde_yaml::from_str` / `serde_json::from_str`
4342/// de-serialize round-trip whose composer surfaces the `:children :restart`
4343/// scalar as an owned [`String`] typed field, a
4344/// `feira supervisor --restart <Permanent|Temporary|Transient>`
4345/// `clap`-derived arg-parse whose owned-`String` positional lands the
4346/// canonical arm at the typed dispatch, a per-`:children`-slot overlay
4347/// resolver reading an owned [`String`] out of a `ConfigMap`
4348/// `data.children-restart` scalar, an `<T: TryFrom<String>>`-bound generic
4349/// loader over any of the substrate's closed-set typed enums — reaches the
4350/// same three-arm `PascalCase` accept-set through one trait dispatch.
4351///
4352/// Extends the substrate-wide trait-idiomatic *string-owned reverse-
4353/// projection* family — opened on the compound M3-mesh
4354/// `:politicas :rate-limit` primitive [`crate::aplicacao::RateLimit`]
4355/// (a2e6f02), lifted onto the first closed-set fieldless typed-enum peer
4356/// [`crate::aplicacao::WitShape`] (e6aac29), extended onto the second
4357/// closed-set fieldless typed-enum peer [`crate::aplicacao::RateLimitUnit`]
4358/// (94a9c5e), extended onto the third closed-set fieldless typed-enum peer
4359/// [`crate::aplicacao::PlacementStrategy`] (d81a70a), extended onto the
4360/// first M2-OTP-shape supervisor-slot closed-set fieldless typed-enum peer
4361/// [`RestartStrategy`] (78fe8c8) — onto the second (and final) M2-OTP-shape
4362/// supervisor-slot closed-set fieldless typed-enum peer, the per-`:children`
4363/// restart-decision-policy discriminator. This closes the string-owned
4364/// reverse-projection axis on the M2-OTP-shape `:supervisor :estrategia` +
4365/// `:children :restart` slot pair, mirroring the trajectory the byte-view
4366/// / byte-owned / str-view reverse-projection families already walked
4367/// across the same slot pair. The peers [`crate::CaixaKind`],
4368/// [`crate::CaixaDialeto`], and [`crate::dep::DepList`] remain the next
4369/// targets of the campaign.
4370///
4371/// Rust's standard library carries no blanket
4372/// `impl<T: for<'a> TryFrom<&'a str>> TryFrom<String> for T`, so a consumer
4373/// that holds an owned [`String`] and needs a typed [`RestartPolicy`]
4374/// otherwise picks between (a) an open-coded
4375/// `<RestartPolicy as TryFrom<&str>>::try_from(s.as_str())` at every call
4376/// site whose type bounds have no compile-time link back to the string-
4377/// owned reverse-projection axis, (b) a `let s: &str = &s;
4378/// RestartPolicy::try_from(s)` two-step whose borrow arithmetic leaks a
4379/// per-call-site lifetime dance rather than a single trait dispatch, or
4380/// (c) a `String::into_bytes` + [`TryFrom<Vec<u8>>`] detour that reaches
4381/// the substrate-primitive `from_wire` accessor through a UTF-8 re-
4382/// validation hop the owned-`String` axis already knows to skip. This
4383/// impl closes the string-owned reverse-projection axis at the substrate-
4384/// primitive [`RestartPolicy::from_wire`] accessor so every future
4385/// `<T: TryFrom<String>>`-bound owned-string consumer reaches the same
4386/// three-arm `PascalCase` accept-set through one trait dispatch.
4387///
4388/// `type Error = ()` matches the sibling [`TryFrom<&str> for
4389/// RestartPolicy`], [`TryFrom<&[u8]> for RestartPolicy`], and
4390/// [`TryFrom<Vec<u8>> for RestartPolicy`] unit-error shapes, preserving
4391/// the trait-family consistency across the {str-view, byte-view, byte-
4392/// owned, string-owned} reverse-projection square. The owned [`String`]
4393/// input is dropped on the error path (the standard-library
4394/// `String::from_utf8` convention of returning the input in the error
4395/// deliberately declined — a caller that needs the string back holds a
4396/// clone before the call, and the closed-set-enum use site rarely wants
4397/// the raw string back past a "did you mean" diagnostic that operates on
4398/// the wire vocabulary rather than the input).
4399///
4400/// Pinned load-bearing by
4401/// [`tests::restart_policy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
4402/// (byte-parity pin against the paired borrowed [`TryFrom<&str>`] axis
4403/// across the three-arm [`RestartPolicy::ALL`] accept-set on the owned-
4404/// `String` surface, cross-axis witness that the string-owned reverse
4405/// projection agrees with the sibling byte-view / byte-owned reverse-
4406/// projection axes on every accepted arm through the shared substrate-
4407/// primitive [`RestartPolicy::from_wire`] accessor, and a closed-cycle
4408/// witness against the paired string-owned forward-projection pair —
4409/// `Self → String → TryFrom<String> → Self` round-trips to the
4410/// originating arm on every canonical `PascalCase` scalar) and
4411/// [`tests::restart_policy_try_from_owned_string_rejects_unknown_wire_strings`]
4412/// (rejection witness against silent accept-set widening — mirrors the
4413/// corpus the paired [`TryFrom<&str>`] rejection witness already pins,
4414/// including empty / whitespace-only inputs, the sibling kebab-case
4415/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
4416/// a caller that confuses the two axes trips here rather than at a
4417/// downstream K8s-CR round-trip miss, case-fold rebrand candidates,
4418/// whitespace-padded / trailing-newline / quote-wrapped forms, and
4419/// English-rebrand candidates, with per-input cross-axis parity against
4420/// the borrowed [`TryFrom<&str>`] reverse-projection axis).
4421impl TryFrom<String> for RestartPolicy {
4422 type Error = ();
4423
4424 fn try_from(s: String) -> Result<Self, Self::Error> {
4425 <Self as TryFrom<&str>>::try_from(s.as_str())
4426 }
4427}
4428
4429// Fleet-wide dispatcher-catalog registrations for caixa's OTP
4430// supervisor surface — two more typed shadows over Erlang/OTP
4431// primitives the substrate now mechanically tracks (see
4432// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
4433// theory/TYPED-ABSORPTION.md for the absorption arc).
4434gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
4435gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
4436
4437/// One child entry in the supervisor's `:children` list.
4438///
4439/// Every child references another caixa by `:caixa <nome>` + version
4440/// constraint. The supervisor materializes one ComputeUnit per entry.
4441#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4442#[serde(rename_all = "camelCase")]
4443pub struct ChildSpec {
4444 /// The child caixa's `:nome`. Must resolve via the same dependency
4445 /// resolution path as `:deps` (caixa-resolver).
4446 pub caixa: String,
4447
4448 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
4449 /// [`crate::dep::Dep::versao`].
4450 pub versao: String,
4451
4452 /// Restart policy — an author-omitted slot degrades onto the
4453 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
4454 /// (`permanent`, the Erlang/OTP worker-child default) through the
4455 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
4456 /// to.
4457 #[serde(default)]
4458 pub restart: RestartPolicy,
4459}
4460
4461impl ChildSpec {
4462 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
4463 /// accessor every consumer that reads the OTP-shape supervised
4464 /// child's identity keys off — returns the author-declared
4465 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
4466 /// from the typed slot's own [`String`] storage.
4467 ///
4468 /// The `:children :caixa` slot carries the DNS-1123 label — the
4469 /// child caixa's `:nome` — that every emitted cluster artifact
4470 /// derives its `metadata.name` from verbatim: the rendered
4471 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
4472 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
4473 /// identity, and the per-child K8s Service `metadata.name` the
4474 /// future wasm-operator (M3) provisions for inter-child supervision-
4475 /// tree wiring. Every downstream consumer that fans on the child's
4476 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
4477 /// per-child DNS-1123 gate at
4478 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
4479 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
4480 /// [`validate_no_self_supervision`] cross-slot equality check
4481 /// against the parent's `:nome`, every `SupervisorError` variant
4482 /// carrying the offending child caixa verbatim for `feira lint`
4483 /// rendering, the future wasm-operator's hierarchical reconciliation
4484 /// scheduler's per-child ComputeUnit-name projection, the future M4
4485 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4486 /// admission webhook).
4487 ///
4488 /// Prior to this lift the `.caixa` byte-string was accessed inline
4489 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
4490 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
4491 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
4492 /// carriers' `child.caixa.clone()`, the dedup key's
4493 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
4494 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
4495 /// field-accesses that expressed no compile-time link back to the
4496 /// typed slot. A future extension of the `:children :caixa` axis to
4497 /// a richer author surface (a per-cluster alias table the operator
4498 /// pins through a future `:placement`-scoped slot on the supervisor
4499 /// tree, a namespace-qualified rewrite the M4 CR materializer
4500 /// applies per-CR, a per-child overlay from the future `:children
4501 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
4502 /// acknowledges) would have had to be threaded through every
4503 /// open-coded copy in lockstep or one consumer would silently
4504 /// disagree with the peers on which caixa a given child resolves to
4505 /// — a child-set lookup that treated the name as `"cart-worker"`
4506 /// while the peer duplicate-detector treated it as
4507 /// `"tenant-a/cart-worker"` would silently split the
4508 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
4509 /// self-supervision detector's parent-equality check, a two-consumer
4510 /// split at the validator far from the source `caixa.lisp` with no
4511 /// field naming the identity-drift root cause. Lifting the resolution
4512 /// rule to a typed method on the substrate primitive means every
4513 /// downstream consumer of the Supervisor's per-`:children` identity
4514 /// surface reaches for exactly one typed dispatch — the resolver's
4515 /// accept-set migrates as a unit on any future axis addition.
4516 ///
4517 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
4518 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
4519 /// mesh-slot surface — same "one typed dispatch on the substrate
4520 /// primitive, thin projections at each consumer" discipline extended
4521 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
4522 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
4523 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
4524 /// accessor discipline for the shared substrate concept "another
4525 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
4526 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
4527 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
4528 /// slot family's typed-accessor discipline now spans both the
4529 /// upgrade axis (`:upgrade-from`) and the supervision axis
4530 /// (`:children`), matching the closed M3 mesh-slot accessor family's
4531 /// shape. Named `nome()` to match the tatara-lisp author-surface
4532 /// term the field's docstring already reaches for ("The child
4533 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
4534 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
4535 /// discipline the substrate already carries — the accessor's name
4536 /// maps directly onto the canonical caixa-identity vocabulary rather
4537 /// than shadowing the field's storage-side `caixa` label.
4538 #[must_use]
4539 pub const fn nome(&self) -> &str {
4540 self.caixa.as_str()
4541 }
4542
4543 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
4544 /// requirement scalar accessor every consumer that reads the OTP-shape
4545 /// supervised child's version pin keys off — returns the author-declared
4546 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
4547 /// the typed slot's own [`String`] storage.
4548 ///
4549 /// The `:children :versao` slot carries the Cargo-shaped semver
4550 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
4551 /// which release of the supervised child caixa the OTP-shape supervisor
4552 /// tree materializes against — the same requirement grammar the peer
4553 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
4554 /// shared [`crate::render::require_valid_versao_requirement`] cascade
4555 /// and the shared [`crate::version::parse_requirement`] parser. Every
4556 /// downstream consumer that fans on the child's version pin keys off
4557 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
4558 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
4559 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
4560 /// for `feira lint` rendering, every future per-cluster version-lock
4561 /// overlay the caixa-operator's hierarchical reconciliation scheduler
4562 /// pins through a future `:placement`-scoped supervisor-tree slot, the
4563 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4564 /// per-child version resolver, the future wasm-operator's per-child
4565 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
4566 ///
4567 /// Prior to this lift the `.versao` byte-string was accessed inline at
4568 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
4569 /// [`SupervisorSpec::validate`] requirement-gate call
4570 /// `require_valid_versao_requirement(&child.versao, …)` and the
4571 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
4572 /// `versao: child.versao.clone()` — two open-coded field-accesses that
4573 /// expressed no compile-time link back to the typed slot. A future
4574 /// extension of the `:children :versao` axis to a richer author surface
4575 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
4576 /// flow, a lacre-projected concrete-version rewrite the operator
4577 /// materializes at CR-admission time, a future `:children :versao-lock`
4578 /// per-cluster override slot the wasm-operator's hierarchical
4579 /// reconciliation scheduler authors per-CR) would have had to be
4580 /// threaded through both open-coded copies in lockstep or one consumer
4581 /// would silently disagree with the peer on which release constraint a
4582 /// given child resolves to — the requirement-gate call reading
4583 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
4584 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
4585 /// the actual gate rejection input, a two-consumer split at the
4586 /// validator far from the source `caixa.lisp` with no field naming the
4587 /// version-pin drift root cause. Lifting the resolution rule to a typed
4588 /// method on the substrate primitive means every downstream
4589 /// requirement-facing consumer of the Supervisor's per-`:children`
4590 /// version-pin surface reaches for exactly one typed dispatch — the
4591 /// resolver's accept-set migrates as a unit on any future axis addition.
4592 ///
4593 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
4594 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
4595 /// surface — same "one typed dispatch on the substrate primitive, thin
4596 /// projections at each consumer" discipline extended onto the M2
4597 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
4598 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
4599 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
4600 /// one accessor discipline for the shared substrate concept "another
4601 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
4602 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
4603 /// `:nome` scalar accessor — the pair
4604 /// `(nome(), versao_requirement())` jointly projects the
4605 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
4606 /// that fans on per-child identity + version pin keys off, closing the
4607 /// last unlifted per-`:children` `String`-carry axis so every downstream
4608 /// per-`:children` reader now routes through a typed dispatch on the
4609 /// substrate primitive. Named `versao_requirement()` rather than
4610 /// `versao()` because the field's storage-side `.versao` label is
4611 /// already the author-surface term (`:versao`); the accessor's name
4612 /// carries the semantic role — the semver *requirement* string the
4613 /// shared [`crate::version::parse_requirement`] entry-point consumes —
4614 /// so a raw field access and a typed dispatch read differently at every
4615 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
4616 /// naming discipline verbatim.
4617 #[must_use]
4618 pub const fn versao_requirement(&self) -> &str {
4619 self.versao.as_str()
4620 }
4621
4622 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
4623 /// per-child post-exit restart-decision policy scalar accessor every
4624 /// consumer that dispatches on the supervised child's post-exit
4625 /// reconcile posture keys off — returns the author-declared
4626 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
4627 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
4628 /// storage.
4629 ///
4630 /// The `:children :restart` slot carries the closed-set OTP-shaped
4631 /// per-child restart-decision policy discriminator
4632 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
4633 /// worker-child default; [`RestartPolicy::Transient`] — restart only
4634 /// on abnormal exit, the OTP `transient` clean-completion-aware
4635 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
4636 /// `temporary` one-shot default) that every downstream consumer of
4637 /// the Supervisor's per-child post-exit reconcile branch keys off.
4638 /// Every future downstream consumer that fans on the per-child
4639 /// restart-decision keys off this scalar (the future `feira app
4640 /// graph` per-child restart column, the future wasm-operator's
4641 /// per-child post-exit restart-decision branch, the future M4
4642 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4643 /// admission webhook, the `caixa-operator`'s hierarchical
4644 /// reconciliation scheduler's per-child post-exit reconcile branch,
4645 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
4646 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
4647 /// pin threads through).
4648 ///
4649 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
4650 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
4651 /// scalar accessor and the M3 mesh-slot
4652 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
4653 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
4654 /// — same "one typed dispatch on the substrate primitive,
4655 /// `Copy`-projected closed-set enum-arm discriminator that partitions
4656 /// the downstream renderer's per-arm fan-out" discipline extended
4657 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
4658 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
4659 /// [`ChildSpec`] type — companion to the sibling per-`:children`
4660 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
4661 /// and the per-`:children` [`ChildSpec::versao_requirement`]
4662 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
4663 /// on the sibling `String`-carry axes. The triple
4664 /// `(nome(), versao_requirement(), restart())` jointly projects the
4665 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
4666 /// tree consumer that fans on per-child identity + version pin +
4667 /// restart-decision keys off, closing the last unlifted per-`:children`
4668 /// axis so every downstream per-`:children` reader now routes through
4669 /// a typed dispatch on the substrate primitive. Named `restart()` to
4670 /// match the storage field's name and the author-surface
4671 /// `:children :restart` slot term verbatim; the accessor's identity
4672 /// name maps onto the canonical OTP-shape per-child restart-decision-
4673 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
4674 /// carries.
4675 ///
4676 /// Declared `pub const fn` to close the last non-`const`
4677 /// `Copy`-return raw-field-getter posture on the M2
4678 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
4679 /// of the sibling M2 per-`:supervisor`
4680 /// [`SupervisorSpec::estrategia`] (converted in this commit)
4681 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
4682 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
4683 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
4684 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
4685 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
4686 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
4687 /// downstream substrate-side `const`-context consumer of the
4688 /// per-`:children` restart-decision-policy scalar (a future
4689 /// module-scope `const _:() = assert!(matches!(child.restart(),
4690 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
4691 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
4692 /// admission-webhook `const fn` per-child restart-decision floor
4693 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
4694 /// composer over the substrate primitive that fans on the per-child
4695 /// restart-decision policy at compile time) now reaches through the
4696 /// same typed dispatch on the substrate primitive at const-eval
4697 /// time as at runtime. A future non-`Copy`-return promotion of the
4698 /// scalar (an `Option<RestartPolicy>`-shape migration on the
4699 /// per-child restart-decision axis once heterogeneous per-cluster
4700 /// restart-policy overlays land, a per-tenant restart-policy-alias
4701 /// table the M4 CR materializer resolves per-CR) that would drop
4702 /// the `const` qualifier fails the fail-before-pass-after pin
4703 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
4704 /// build time rather than surfacing as a downstream consumer
4705 /// regression.
4706 #[must_use]
4707 pub const fn restart(&self) -> RestartPolicy {
4708 self.restart
4709 }
4710}
4711
4712/// Supervisor-typed slots that live alongside the standard Caixa
4713/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
4714/// the manifest stays a single typed form; this struct exists for
4715/// validation + conversion.
4716#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4717#[serde(rename_all = "camelCase")]
4718pub struct SupervisorSpec {
4719 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
4720 #[serde(default)]
4721 pub estrategia: RestartStrategy,
4722
4723 /// Max restarts within [`Self::restart_window`] before the
4724 /// supervisor itself terminates (and its parent supervisor decides
4725 /// what to do). Default 5.
4726 #[serde(default = "default_max_restarts")]
4727 pub max_restarts: u32,
4728
4729 /// Sliding window for `max_restarts`. Authored as a duration
4730 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
4731 /// is rejected by [`Self::validate`] — Erlang/OTP's
4732 /// `MaxIntensity / Period` invariant requires a positive window
4733 /// (a zero-period supervisor either trips on the first failure or
4734 /// never trips, depending on operator interpretation, neither of
4735 /// which is the author's intent). Omit the slot to express "no
4736 /// reset"; carry a positive duration to express the sliding window.
4737 #[serde(
4738 default,
4739 skip_serializing_if = "Option::is_none",
4740 with = "duration_codec"
4741 )]
4742 pub restart_window: Option<Duration>,
4743
4744 /// Static children. Empty for `SimpleOneForOne` (children added
4745 /// dynamically); required for the other three strategies.
4746 #[serde(default)]
4747 pub children: Vec<ChildSpec>,
4748}
4749
4750const fn default_max_restarts() -> u32 {
4751 // Route the private serde-`#[serde(default = "…")]` helper through
4752 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
4753 // `pub const` rather than the raw `5` literal — one source of truth
4754 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4755 // default across the two production consumers that currently
4756 // dispatch on it (this helper via `#[serde(default = "…")]` on
4757 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
4758 // impl at line 962). Pinned by
4759 // `default_max_restarts_helper_routes_through_lifted_default` +
4760 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
4761 // in the tests module; peer of the sibling caixa-core
4762 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
4763 // that now routes its author-omitted `:max-restarts` arm through
4764 // the same lifted constant.
4765 SUPERVISOR_MAX_RESTARTS_DEFAULT
4766}
4767
4768/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
4769/// count default for the `:supervisor :max-restarts` axis — the
4770/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
4771/// Erlang's worker-supervisor default, extracted as a typed `pub const`
4772/// so every substrate-side consumer that resolves "what
4773/// [`SupervisorSpec::max_restarts`] value does an author-omitted
4774/// `:max-restarts` slot degrade onto?" reaches for exactly one
4775/// substrate-primitive `u32`.
4776///
4777/// The `:max-restarts` default axis has two production consumers on the
4778/// substrate side today (both prior to this lift folded onto raw `5`
4779/// literals with no compile-time link back to a shared truth): the
4780/// serde-`#[serde(default = "default_max_restarts")]` helper on
4781/// [`SupervisorSpec::max_restarts`] that every author-omitted
4782/// `:supervisor :max-restarts` slot lands in past the derive-macro's
4783/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
4784/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
4785/// the composed [`SupervisorSpec`] altitude reaches through
4786/// (`feira app graph`, the future wasm-operator's per-supervisor
4787/// restart-intensity counter, the future M4
4788/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4789/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
4790/// A pair of open-coded `5`s across two files that expressed no
4791/// compile-time link back to the shared OTP-canonical default — a
4792/// future rebrand of the default (a tightening to Elixir's
4793/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
4794/// the operator pins through a future
4795/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
4796/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
4797/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
4798/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
4799/// per-child-cohort roadmap lands) would have had to be threaded
4800/// through both open-coded copies in lockstep or the wire-format
4801/// author-omitted arm and the view-construction author-omitted arm
4802/// would silently disagree on which restart-budget an omitted
4803/// `:max-restarts` resolves to (an author writing `:supervisor
4804/// (:max-restarts ())` would round-trip through serde with the new
4805/// default while `supervisor_view` silently continued to compose the
4806/// stale `5`, or vice versa), a two-consumer split at the composition
4807/// boundary far from the source `caixa.lisp` with no field naming the
4808/// default-drift root cause. Lifting the resolution rule to a typed
4809/// `pub const` on the substrate primitive means every downstream
4810/// consumer of the per-Supervisor default-restart-budget-count surface
4811/// reaches for exactly one substrate-primitive `u32` — the resolver's
4812/// accepted value migrates as a unit on any future axis change.
4813///
4814/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
4815/// worker-supervisor default (the closest canonical OTP-shape
4816/// production reference the substrate carries, matching the sibling
4817/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
4818/// this constant with on the paired sliding-window axis). Two orders of
4819/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
4820/// (the upper bracket on the same axis, sibling of this lower default;
4821/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
4822/// axis and now share one accessor discipline on the substrate) and
4823/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
4824/// restart floor — the "one restart, then escalate" default is
4825/// deliberately loose enough to absorb a short burst of transient
4826/// child failures without escalating past the supervisor's parent
4827/// while remaining tight enough to trip the `MaxIntensity / Period`
4828/// ratio's escalation on a genuinely-stuck child within the sibling
4829/// `60s` sliding window.
4830///
4831/// Lifted as a typed `pub const` so the bound has exactly one source
4832/// of truth — the serde-side wire-format author-omitted arm at
4833/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
4834/// struct-literal default field, and the caixa-core
4835/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
4836/// arm all read from one place. Same shape every other typed default
4837/// in this crate carries (the sibling
4838/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
4839/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
4840/// sibling `:restart-window` axis, and the peer
4841/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
4842/// per-renderer defaults on the caixa-flux / caixa-helm rendering
4843/// axes).
4844pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
4845
4846/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
4847/// validated [`SupervisorSpec::max_restarts`] past
4848/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
4849///
4850/// The typed field is `u32` (the zero-floor arm
4851/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
4852/// so a programmatic struct literal
4853/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
4854/// author-surface form (`:max-restarts 4294967295` or any
4855/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
4856/// cleanly through serde — a structurally unbounded `u32` ceiling. The
4857/// runtime substrate consuming the value (Erlang/OTP's
4858/// `MaxIntensity / Period` ratio, the future wasm-operator's
4859/// per-supervisor restart-intensity counter, the M4
4860/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
4861/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
4862/// escalation threshold is structurally so high that no realistic
4863/// restarts-per-`:restart-window` traffic shape can reach it, the
4864/// supervisor never escalates to its parent, and a bad child can loop
4865/// inside the window indefinitely with the parent supervisor structurally
4866/// never receiving the "this subtree has exceeded its restart budget"
4867/// signal the typed slot is meant to express — the canonical
4868/// "supervisor intensity declared, no escalation" footgun, exactly the
4869/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
4870/// on the `:politicas :circuit-breaker :max-failures` axis (both are
4871/// "trip the next-higher protection layer after N events in a rolling
4872/// window" counters with identical degenerate-at-the-high-end shape).
4873///
4874/// The `1000` ceiling matches the sibling
4875/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
4876/// peer — same "events-per-window trip threshold" semantics, same `u32`
4877/// type, same no-op-at-the-high-end failure mode) so the M4
4878/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
4879/// and the future wasm-operator's per-supervisor restart-intensity
4880/// counter reach for either field knowing the value is in `1..=1000`
4881/// without re-validating at the reconciler layer. The cap sits two
4882/// orders of magnitude above every documented Erlang/OTP production
4883/// playbook recommendation (Learn You Some Erlang's
4884/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
4885/// `max_restarts: 3` default, OTP's `supervisor` callback module
4886/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
4887/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
4888/// default) and below the clearly-pathological "effectively no
4889/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
4890/// author can plausibly want at hyperscale (a long-running supervisor
4891/// over a very-flaky pool tolerating thousands of transient restarts
4892/// before escalating), but a hard wall above which the typed policy is
4893/// structurally a no-op carried verbatim on every emitted child-restart
4894/// reconciliation contract.
4895///
4896/// Lifted as a typed `pub const` so the bound has exactly one source of
4897/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4898/// materializer's admission webhook and the wasm-operator-side
4899/// per-supervisor restart-intensity reconciler read from one place. Same
4900/// shape every other typed upper bound in this crate carries
4901/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
4902/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
4903/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
4904/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4905/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4906/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4907pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
4908
4909/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
4910/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
4911/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4912/// (inclusive on both ends, integer-millisecond magnitudes by the
4913/// canonical-form gate immediately preceding).
4914///
4915/// The typed field is `Option<Duration>` (the zero-floor arm
4916/// [`SupervisorError::RestartWindowZero`] already rejects
4917/// `Some(Duration::ZERO)`, and the canonical-form arm
4918/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
4919/// sub-millisecond residue), so a programmatic struct literal
4920/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
4921/// .. }` — 24h) and the equivalent author-surface form
4922/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
4923/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
4924/// cleanly through serde — a structurally unbounded `Duration` ceiling.
4925/// A `:restart-window` value far above the documented Erlang/OTP
4926/// `MaxIntensity / Period` production-playbook band (Learn You Some
4927/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
4928/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
4929/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
4930/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
4931/// degenerates the supervisor's restart-intensity counter into a
4932/// lifetime counter: the rolling failure-counting window is structurally
4933/// so long that transient restarts are never forgotten, so the
4934/// `MaxIntensity / Period` ratio degenerates from "trip the parent
4935/// supervisor when the child has exceeded its restart budget *within
4936/// the recent window*" to "trip the parent when the child has exceeded
4937/// its restart budget *over its lifetime*" — every transient restart
4938/// counts against the budget forever, the supervisor's reset semantic
4939/// never reaches the child, and the typed `:restart-window` slot
4940/// becomes a no-op rolling window carried on every emitted hierarchical
4941/// reconciliation contract. The canonical
4942/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
4943/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
4944/// `:politicas :circuit-breaker :window` axis with identical shape (both
4945/// are "rolling failure-counting window with a per-`Period` reset" Duration
4946/// axes whose lifetime-counter degenerate at the high end is the same
4947/// "the reset semantic never fires" CSE invariant violation).
4948///
4949/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
4950/// the shared duration codec emits (`"<n>h"` for any integer-hour
4951/// magnitude) — every value in the canonical authoring form's
4952/// `<integer><unit>` grammar at or below this cap renders to a clean
4953/// canonical string — and matches the three sibling typed-`Duration`
4954/// caps already lifted to this surface
4955/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
4956/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
4957/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
4958/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
4959/// per-supervisor `:supervisor :restart-window` — now share a single
4960/// uniform top edge at the codec's largest emitted unit so the next
4961/// typed-slot wiring (the future wasm-operator's per-supervisor
4962/// `MaxIntensity / Period` reconciler, the M4
4963/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4964/// webhook, the `caixa-operator`'s hierarchical reconciliation
4965/// scheduler) reaches for any of the four knowing the value is in
4966/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
4967/// two orders of magnitude above every documented Erlang/OTP / Elixir /
4968/// Riak Core / RabbitMQ production-playbook recommendation band
4969/// (`5s..=300s`) and below the clearly-pathological "rolling window
4970/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
4971/// a value the author can plausibly want for a very-low-traffic
4972/// long-tail failure-restart window over a hyperscale-flaky child pool,
4973/// but a hard wall above which the rolling-window contract is
4974/// structurally a lifetime-counter contract.
4975///
4976/// Lifted as a typed `pub const` so the bound has exactly one source
4977/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4978/// materializer's admission webhook, the wasm-operator-side
4979/// per-supervisor `MaxIntensity / Period` reconciler, and the
4980/// `caixa-operator`'s hierarchical reconciliation scheduler all read
4981/// from one place. Same shape every other typed upper bound in this
4982/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
4983/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
4984/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
4985/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
4986/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4987/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
4988/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
4989/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4990/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4991pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
4992
4993/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
4994/// default for the `:supervisor :restart-window` axis — the canonical
4995/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
4996/// worker-supervisor default, extracted as a typed `pub const` so every
4997/// substrate-side consumer that resolves "what
4998/// [`SupervisorSpec::restart_window`] value does an author-omitted
4999/// `:restart-window` slot degrade onto?" reaches for exactly one
5000/// substrate-primitive [`Duration`].
5001///
5002/// The `:restart-window` default axis has one production consumer on the
5003/// substrate side today: the [`Default for SupervisorSpec`] impl's
5004/// struct-literal `restart_window` field, which prior to this lift folded
5005/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
5006/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
5007/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
5008/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
5009/// *not* fall back to this default on the sibling `:restart-window` axis
5010/// — an author-omitted `:supervisor :restart-window` composes to
5011/// `restart_window: None` (the shared codec's soft-swallow shape),
5012/// keeping author-declared intent ("no reset — never escalate on rolling
5013/// window") distinct from the [`Default for SupervisorSpec`] "canonical
5014/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
5015/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
5016/// default was split across two files with no compile-time link between
5017/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
5018/// `MaxIntensity` half at the substrate primitive while the `Period`
5019/// half rode as an open-coded literal at the composition site, so a
5020/// future coherent rebrand of the paired canonical (a tightening to
5021/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
5022/// per-cluster overlay the operator pins through a future
5023/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
5024/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
5025/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
5026/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
5027/// roadmap lands) would have had to migrate the `MaxIntensity` half
5028/// through the lifted constant and the `Period` half through a raw
5029/// literal in lockstep or the two halves of the same OTP-canonical
5030/// default would silently drift out of pairing. Lifting the resolution
5031/// rule to a typed `pub const` on the substrate primitive means the
5032/// paired OTP-canonical default migrates as one unit on any future
5033/// axis change.
5034///
5035/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
5036/// worker-supervisor default (the closest canonical OTP-shape
5037/// production reference the substrate carries, matching the paired
5038/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
5039/// constant is the `Period` denominator of on the same
5040/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
5041/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
5042/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
5043/// this lower default; both are typed [`Duration`] const bounds on the
5044/// `:supervisor :restart-window` axis and now share one accessor
5045/// discipline on the substrate) and above the OTP-`supervisor`
5046/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
5047/// rolling window" default is deliberately loose enough to absorb a
5048/// short burst of transient child failures without escalating past the
5049/// supervisor's parent while remaining tight enough for the paired
5050/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
5051/// stuck child within a human-scale observation window.
5052///
5053/// Lifted as a typed `pub const` so the paired OTP-canonical default has
5054/// exactly one source of truth on each half — the sibling
5055/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
5056/// `Period` `60s` half now share the same substrate-primitive lift
5057/// discipline. Same shape every other typed default in this crate
5058/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
5059/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
5060/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
5061/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
5062/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
5063/// caixa-flux / caixa-helm rendering axes).
5064pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
5065
5066/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
5067/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
5068/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
5069/// worker-supervisor default, extracted as a typed `pub const` so every
5070/// substrate-side consumer that resolves "what
5071/// [`SupervisorSpec::estrategia`] variant does an author-omitted
5072/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
5073/// primitive [`RestartStrategy`].
5074///
5075/// The `:estrategia` default axis has three production consumers on the
5076/// substrate side today: the [`Default for RestartStrategy`] impl's
5077/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
5078/// `estrategia` field, and the
5079/// [`crate::manifest::Caixa::supervisor_view`] fold's
5080/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
5081/// collapse arm — three entry points onto the same OTP-canonical
5082/// `one_for_one` value that prior to this lift folded onto a raw
5083/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
5084/// implicit `RestartStrategy::default()` routes at the sibling consumers,
5085/// with no compile-time link back to the paired
5086/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
5087/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
5088/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
5089/// triple was split across three altitudes with no compile-time link
5090/// between the halves: the `MaxIntensity` half rode through the lifted
5091/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
5092/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5093/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
5094/// discriminator at the [`Default for RestartStrategy`] impl, so a future
5095/// coherent rebrand of the triple (Elixir's `{:one_for_one,
5096/// max_restarts: 3, max_seconds: 5}` — same strategy, different
5097/// intensity/period; an OTP `rest_for_one` widening once the substrate
5098/// discovers startup-order-coupled child cohorts as the more common
5099/// worker-supervisor default; a per-cluster overlay the operator pins
5100/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
5101/// §III.2 supervision-canary roadmap acknowledges) would have had to
5102/// migrate the `MaxIntensity` + `Period` halves through the lifted
5103/// constants and the `one_for_one` half through an open-coded arm in
5104/// lockstep or the three halves of the same OTP-canonical default would
5105/// silently drift out of pairing. Lifting the resolution rule to a typed
5106/// `pub const` on the substrate primitive means the paired OTP-canonical
5107/// worker-supervisor default migrates as one unit on any future axis
5108/// change.
5109///
5110/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
5111/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
5112/// closest canonical OTP-shape production reference the substrate
5113/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
5114/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5115/// `60s` `Period` half). The `one_for_one` strategy — restart only the
5116/// failed child, leaving siblings untouched — is the default for tree-of-
5117/// independent-workers use cases the substrate's [`RestartStrategy`]
5118/// discriminator's own docstring already carries as the default arm; it
5119/// composes with the `{5, 60}` restart-intensity ratio to name the same
5120/// substrate-canonical "canonical worker-supervisor" shape the paired
5121/// halves close on their respective axes.
5122///
5123/// Lifted as a typed `pub const` so the paired OTP-canonical default has
5124/// exactly one source of truth on each of its three halves — the sibling
5125/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
5126/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
5127/// this `one_for_one` strategy half now share the same substrate-
5128/// primitive lift discipline. Same shape every other typed default in
5129/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
5130/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
5131/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
5132/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
5133/// upper caps on the paired sibling axes, and the peer
5134/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
5135/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
5136pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
5137
5138/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
5139/// default for the `:children :restart` axis — the OTP `permanent`
5140/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
5141/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
5142/// `pub const` so every substrate-side consumer that resolves "what
5143/// [`ChildSpec::restart`] variant does an author-omitted `:children
5144/// :restart` slot degrade onto?" reaches for exactly one substrate-
5145/// primitive [`RestartPolicy`].
5146///
5147/// Completes the OTP-shape supervisor-tree default set at the substrate
5148/// primitive. The per-`:supervisor` axis already carries all three of its
5149/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
5150/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5151/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5152/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
5153/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
5154/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
5155/// the M2 `:supervisor` slot family. The split mattered because the two
5156/// axes resolve *together* on every author-omitted supervisor: a
5157/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
5158/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
5159/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
5160/// `permanent` through an open-coded enum arm, so a future coherent
5161/// rebrand of the OTP-shape default set (an Elixir-shaped
5162/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
5163/// per-cluster overlay the operator pins through the MESH-COMPOSITION
5164/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
5165/// once the substrate discovers clean-completion-aware children as the
5166/// more common child shape) would have had to migrate three halves
5167/// through typed constants and the fourth through a raw enum arm in
5168/// lockstep or the supervisor-level and child-level defaults would
5169/// silently drift apart.
5170///
5171/// The `:children :restart` default axis has two production consumers on
5172/// the substrate side today: the [`Default for RestartPolicy`] impl's
5173/// return arm, and the serde-side `#[serde(default)]` on
5174/// [`ChildSpec::restart`] that resolves an author-omitted `:children
5175/// :restart` slot through that same impl. Both now key off this one
5176/// substrate primitive, so the future wasm-operator's per-child post-exit
5177/// restart-decision branch, the future M4
5178/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
5179/// admission webhook, and the `caixa-operator`'s hierarchical
5180/// reconciliation scheduler's per-child fan-out all reach for one typed
5181/// identifier when they resolve an omitted per-child restart posture.
5182///
5183/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
5184/// worker-child restart type — always restart the child regardless of how
5185/// it died, the canonical posture for long-running services that must
5186/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
5187/// `one_for_one` tree-of-independent-workers strategy this constant pairs
5188/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
5189/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
5190/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
5191/// [`RestartPolicy::Temporary`] — never restart) express deliberate
5192/// one-shot / clean-completion-aware postures an author declares
5193/// explicitly, never a posture an omitted slot should silently assume.
5194pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
5195
5196/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
5197/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
5198/// `pub const fn` constructor rather than a struct-literal cascade over
5199/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5200/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5201/// lifted consts — one source of truth for the Erlang/OTP-canonical
5202/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
5203/// paths every downstream consumer already reaches through (the
5204/// hand-authored-until-now [`Default::default`] the
5205/// `..SupervisorSpec::default()` struct-update-syntax on every
5206/// one-axis-under-test fixture in this crate's test module rests on,
5207/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
5208/// every `const`-context consumer reaches through).
5209///
5210/// Extends the [`Default`]-through-const-ctor fold discipline the
5211/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5212/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
5213/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
5214/// and [`crate::BehaviorSpec`]
5215/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
5216/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
5217/// typed-slot spec family — extended here onto the M2 supervisor-slot
5218/// [`SupervisorSpec`] whose canonical baseline is not "everything
5219/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
5220/// supervisor triple. The `empty()` peer's naming did not fit
5221/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
5222/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
5223/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
5224/// the sibling `Option`-only slots fold to), so this peer is named
5225/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
5226/// existing per-arm pin tests
5227/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
5228/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
5229/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
5230/// already reach for. Pinned load-bearing by
5231/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
5232/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
5233/// [`PartialEq`], sharpening the sibling
5234/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
5235/// pins from a per-field lift into a whole-struct one-source-of-truth
5236/// pin — the derived-until-now [`Default::default`] and the
5237/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5238/// construction, not by coincidence).
5239impl Default for SupervisorSpec {
5240 #[inline]
5241 fn default() -> Self {
5242 Self::otp_canonical()
5243 }
5244}
5245
5246impl SupervisorSpec {
5247 /// `const`-context peer of the [`Default for SupervisorSpec`]
5248 /// impl (which routes through this constructor) — returns the
5249 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
5250 /// baseline this crate reaches for in every fixture-builder
5251 /// `..SupervisorSpec::default()` struct-update expression and
5252 /// every downstream `SupervisorSpec::default()` seed.
5253 ///
5254 /// Each field routes through the same substrate-canonical
5255 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
5256 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
5257 /// per-arm pin tests
5258 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
5259 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
5260 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
5261 /// already assert, so a future coherent rebrand of the OTP-canonical
5262 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
5263 /// cluster overlay via a future `:restart-window-overrides` slot, a
5264 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
5265 /// absorption roadmap acknowledges) migrates through three typed
5266 /// constants in lockstep, and the paired [`Default`] impl inherits
5267 /// every future extension by construction.
5268 ///
5269 /// `pub const fn` rather than the derived-style `Default::default`
5270 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
5271 /// [`Default::default`] is not `const` on stable Rust, and
5272 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
5273 /// every consumer through a [`Clone::clone`]. The `pub const fn`
5274 /// discipline lets `const`-context callers construct the OTP-
5275 /// canonical baseline at compile time without runtime dispatch on
5276 /// the derived [`Default::default`], the same posture the sibling
5277 /// [`crate::LimitsSpec::empty`] (9739971) /
5278 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
5279 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
5280 /// spec `pub const fn` constructors carry on the sibling
5281 /// "everything `None`" baseline axis.
5282 ///
5283 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
5284 /// of the derived-style [`Default`]" family — sibling of the
5285 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
5286 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
5287 /// baseline" trio, extended here onto the M2 supervisor-slot
5288 /// [`SupervisorSpec`] whose canonical baseline is not "everything
5289 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
5290 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
5291 /// than `empty()` to name the actual invariant the return value
5292 /// pins — the same phrasing already used in the per-arm pin tests
5293 /// on this file. Pinned load-bearing by
5294 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
5295 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
5296 #[must_use]
5297 pub const fn otp_canonical() -> Self {
5298 Self {
5299 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
5300 max_restarts: default_max_restarts(),
5301 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5302 children: Vec::new(),
5303 }
5304 }
5305
5306 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
5307 /// sibling-restart-strategy scalar accessor every consumer that
5308 /// dispatches on the supervisor's per-sibling restart-decision shape
5309 /// keys off — returns the author-declared `:supervisor :estrategia`
5310 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
5311 /// the typed slot's own [`RestartStrategy`] storage.
5312 ///
5313 /// The `:supervisor :estrategia` slot carries the closed-set
5314 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
5315 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
5316 /// [`RestartStrategy::OneForAll`] — restart every child on any child
5317 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
5318 /// [`RestartStrategy::RestForOne`] — restart the failed child and
5319 /// every child started after it, the Erlang/OTP `rest_for_one`
5320 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
5321 /// dynamic children of the same shape, the Erlang/OTP
5322 /// `simple_one_for_one` per-session default) that every downstream
5323 /// consumer of the Supervisor's per-sibling restart-decision fan-out
5324 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
5325 /// paired coherently with the sibling `:children` axis
5326 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
5327 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
5328 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
5329 /// downstream consumer that reads the strategy keys off this scalar
5330 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
5331 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
5332 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
5333 /// `estrategia:` field, the future `feira app graph` per-Supervisor
5334 /// strategy print line, the future wasm-operator's per-supervisor
5335 /// sibling-restart-strategy branch, the future M4
5336 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
5337 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
5338 /// reconciliation scheduler's per-strategy fan-out).
5339 ///
5340 /// Prior to this lift the `.estrategia` field was accessed inline at
5341 /// two production sites in `caixa-core/src/supervisor.rs` — the
5342 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
5343 /// `match self.estrategia { … }` partition dispatch, and the
5344 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
5345 /// carrier at `estrategia: self.estrategia` — two open-coded
5346 /// field-accesses that expressed no compile-time link back to the
5347 /// typed slot. A future extension of the `:supervisor :estrategia`
5348 /// axis to a richer author surface (a per-cluster strategy override
5349 /// the operator pins through a future `:supervisor :estrategia-overrides`
5350 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
5351 /// acknowledges, a per-tenant strategy-alias table the M4 CR
5352 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
5353 /// derivation the future adaptive-supervision engine computes from
5354 /// child-failure-history topology, a per-child-cohort strategy split
5355 /// the future `RestForCohort` extension acknowledged by the
5356 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
5357 /// would have had to be threaded through every open-coded copy in
5358 /// lockstep — one consumer reading the raw variant while a peer read
5359 /// the operator-resolved variant would silently split the
5360 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
5361 /// the actual partition-dispatch input the empty-children refusal
5362 /// arm reached under, a two-consumer split at the validator far from
5363 /// the source `caixa.lisp` with no field naming the strategy-drift
5364 /// root cause. Lifting the resolution rule to a typed method on the
5365 /// substrate primitive means every downstream consumer of the
5366 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
5367 /// reaches for exactly one typed dispatch — the resolver's accept-set
5368 /// migrates as a unit on any future axis addition.
5369 ///
5370 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
5371 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
5372 /// per-`:placement` distribution-strategy axis — same "one typed
5373 /// dispatch on the substrate primitive, thin projections at each
5374 /// consumer" discipline extended onto the M2 supervisor-slot
5375 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
5376 /// scalar axis. The two typed axes (`Placement::estrategia` on the
5377 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
5378 /// Supervisor side) now share one accessor discipline for the shared
5379 /// substrate concept "a `Copy`-projected closed-set enum-arm
5380 /// discriminator that partitions the downstream renderer's per-arm
5381 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
5382 /// `SupervisorSpec` type — companion to the sibling per-`:children`
5383 /// [`crate::ChildSpec::nome`] (57c61d0) /
5384 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
5385 /// scalar accessors on the sibling per-`:children` `String`-carry
5386 /// axes. Named `estrategia()` to match the storage field's name and
5387 /// the peer [`crate::Placement::estrategia`] method-name discipline
5388 /// verbatim; the accessor's identity name maps onto the canonical
5389 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
5390 /// docstring already carries.
5391 ///
5392 /// Declared `pub const fn` to close the M2 supervisor-slot
5393 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
5394 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
5395 /// (converted in this commit) `Copy`-composite-enum accessor, peer
5396 /// of the sibling M2 per-`:supervisor`
5397 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
5398 /// already lifted, and mirror of the peer M3 mesh-slot
5399 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
5400 /// `Copy`-return `pub const fn` scalar accessor whose method-name
5401 /// discipline this accessor was authored to match. Every downstream
5402 /// substrate-side `const`-context consumer of the per-`:supervisor`
5403 /// sibling-restart-strategy scalar (a future module-scope `const
5404 /// _:() = assert!(matches!(sup.estrategia(),
5405 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
5406 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
5407 /// admission-webhook `const fn` per-supervisor strategy-arm floor
5408 /// over a typed [`SupervisorSpec`], any future `const fn`
5409 /// supervisor-tree composer over the substrate primitive that fans
5410 /// on the sibling-restart-strategy at compile time) now reaches
5411 /// through the same typed dispatch on the substrate primitive at
5412 /// const-eval time as at runtime. A future non-`Copy`-return
5413 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
5414 /// migration once the substrate grows per-cluster strategy overlays
5415 /// the [`SupervisorSpec`] docstring already anticipates, a
5416 /// per-tenant strategy-alias table the M4 CR materializer resolves
5417 /// per-CR) that would drop the `const` qualifier fails the
5418 /// fail-before-pass-after pin
5419 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
5420 /// caixa-core build time rather than surfacing as a downstream
5421 /// consumer regression.
5422 #[must_use]
5423 pub const fn estrategia(&self) -> RestartStrategy {
5424 self.estrategia
5425 }
5426
5427 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
5428 /// `MaxIntensity` restart-budget scalar accessor every consumer that
5429 /// reads the supervisor's per-`:restart-window` restart-budget count
5430 /// keys off — returns the author-declared `:supervisor :max-restarts`
5431 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
5432 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
5433 /// borrow of `&self` past the call). Non-optional (the `u32` field
5434 /// carries the restart-budget count as a required axis with a
5435 /// [`default_max_restarts`]-supplied default; the zero-floor arm
5436 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
5437 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
5438 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
5439 ///
5440 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
5441 /// `MaxIntensity` restart-budget count that pairs with the sibling
5442 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
5443 /// restart-intensity ratio the supervisor trips its own escalation on
5444 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
5445 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
5446 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
5447 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
5448 /// upper-cap bracket at
5449 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
5450 /// wasm-operator's per-supervisor restart-intensity counter's
5451 /// budget-vs-count comparator, the future M4
5452 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
5453 /// webhook, the `caixa-operator`'s hierarchical reconciliation
5454 /// scheduler's per-supervisor escalation-decision branch, every
5455 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
5456 /// offending count verbatim for `feira lint` rendering).
5457 ///
5458 /// Prior to this lift the `.max_restarts` field was accessed inline at
5459 /// one production site in `caixa-core/src/supervisor.rs` — the
5460 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
5461 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
5462 /// that expressed no compile-time link back to the typed slot. A
5463 /// future extension of the `:max-restarts` axis to a richer author
5464 /// surface (a per-cluster restart-budget override the operator pins
5465 /// through a future `:supervisor :max-restarts-overrides` slot the
5466 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
5467 /// a per-tenant restart-budget-alias table the M4 CR materializer
5468 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
5469 /// the future adaptive-supervision engine computes from child-failure-
5470 /// history topology, a promotion of the plain `u32` count to a richer
5471 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
5472 /// budget-partition slot comes into scope) would have had to be
5473 /// threaded through every open-coded copy in lockstep or the validate
5474 /// gate and the future M4 emit path would silently disagree on which
5475 /// restart-budget count a given supervisor resolves to — an author's
5476 /// `:max-restarts 5` would satisfy validate while the emit path
5477 /// silently read a drifted other value (a `:max-restarts 10000`
5478 /// no-op supervisor at the emit boundary would carry the author's
5479 /// declared `5` verbatim in `feira lint` output while the future
5480 /// wasm-operator's restart-intensity counter operated under the
5481 /// drifted count), a two-consumer split at the validator far from the
5482 /// source `caixa.lisp` with no field naming the restart-budget-drift
5483 /// root cause. Lifting the resolution rule to a typed method on the
5484 /// substrate primitive means every downstream consumer of the
5485 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
5486 /// for exactly one typed dispatch — the resolver's accept-set migrates
5487 /// as a unit on any future axis addition.
5488 ///
5489 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
5490 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
5491 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
5492 /// outlier-detection trip-threshold axis — same "one typed dispatch on
5493 /// the substrate primitive, thin projections at each consumer"
5494 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
5495 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
5496 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
5497 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
5498 /// one accessor discipline for the shared substrate concept "a
5499 /// `Copy`-projected required `u32` count that trips the next-higher
5500 /// protection layer after N events in a rolling window" — both are
5501 /// counters with identical degenerate-at-the-high-end shape and share
5502 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
5503 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
5504 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
5505 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
5506 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
5507 /// the storage field's name verbatim and the peer
5508 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
5509 /// accessor's identity maps onto the canonical OTP-shape supervision
5510 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
5511 /// already carries.
5512 #[must_use]
5513 pub const fn max_restarts(&self) -> u32 {
5514 self.max_restarts
5515 }
5516
5517 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
5518 /// `Period` sliding-window scalar accessor every consumer of the
5519 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
5520 /// keys off — returns the author-declared `:supervisor :restart-window`
5521 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
5522 /// the typed slot's own `Option<Duration>` storage (`Duration` is
5523 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
5524 /// value; no borrow of `&self` past the call). `None` when the slot is
5525 /// absent (the canonical "never reset — every restart across the
5526 /// supervisor's lifetime counts against the sibling `:max-restarts`
5527 /// budget" sentinel the field's own docstring names and the peer
5528 /// `validate_accepts_none_restart_window` pin locks in on the
5529 /// [`SupervisorSpec::validate`] entry-side).
5530 ///
5531 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
5532 /// `Period` sliding-observation-interval that pairs with the sibling
5533 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
5534 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
5535 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
5536 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
5537 /// default). The typed slot's `Option<Duration>` accept-set —
5538 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
5539 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
5540 /// `Period > 0`; a zero period either trips on the first failure or
5541 /// never trips depending on operator interpretation, neither of which
5542 /// is the author's intent — omit the slot to express "no reset";
5543 /// carry a positive duration to express the sliding window),
5544 /// integer-millisecond canonical form enforced through
5545 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
5546 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
5547 /// future wasm-operator's per-supervisor restart-intensity counter
5548 /// quantizes at milliseconds), upper-bounded by
5549 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
5550 /// supervisor rolling window any operationally-reachable supervisor
5551 /// can honor without spanning multiple scheduler epochs the
5552 /// hierarchical-reconciliation scheduler treats as independent) —
5553 /// maps onto the future wasm-operator (M3) per-supervisor
5554 /// restart-intensity counter's rolling-observation-interval, the
5555 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5556 /// per-`spec.restartWindow` admission webhook, and the sibling
5557 /// `duration_codec`-serialized wire scalar every downstream consumer
5558 /// of the supervisor's per-`:supervisor` restart-intensity denominator
5559 /// keys off.
5560 ///
5561 /// Prior to this lift the `.restart_window` field was accessed inline
5562 /// at one production site in `caixa-core/src/supervisor.rs` — the
5563 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
5564 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
5565 /// open-coded field-access that expressed no compile-time link back to
5566 /// the typed slot. A future extension of the `:restart-window` axis to
5567 /// a richer author surface (a per-cluster restart-window override the
5568 /// operator pins through a future `:supervisor :restart-window-overrides`
5569 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
5570 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
5571 /// materializer resolves per-CR, a per-supervisor dynamic
5572 /// restart-window derivation the future adaptive-supervision engine
5573 /// computes from child-failure-history topology, a promotion of the
5574 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
5575 /// pair once Erlang/OTP's per-child-cohort observation-interval-
5576 /// partition slot comes into scope) would have had to be threaded
5577 /// through every open-coded copy in lockstep or the validate gate and
5578 /// the future M4 emit path would silently disagree on which
5579 /// restart-window a given supervisor resolves to — an author's
5580 /// `:restart-window "60s"` would satisfy validate while the emit path
5581 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
5582 /// authored slot at the emit boundary would carry the author's
5583 /// declared window verbatim in `feira lint` output while the future
5584 /// wasm-operator's restart-intensity counter operated under a
5585 /// drifted window, or vice versa: an author's `:restart-window ()`
5586 /// would carry the "never reset" sentinel through validate while the
5587 /// emit path silently substituted a default sliding window), a
5588 /// two-consumer split at the validator far from the source
5589 /// `caixa.lisp` with no field naming the restart-window-drift root
5590 /// cause. Lifting the resolution rule to a typed method on the
5591 /// substrate primitive means every downstream consumer of the
5592 /// Supervisor's per-`:supervisor` restart-intensity-denominator
5593 /// surface reaches for exactly one typed dispatch — the resolver's
5594 /// accept-set migrates as a unit on any future axis addition.
5595 ///
5596 /// Third `Copy`-return accessor on the M2 supervisor-slot
5597 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
5598 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
5599 /// payload rather than a `Copy`-scalar, and the per-`:children`
5600 /// [`crate::ChildSpec::nome`] (57c61d0) /
5601 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
5602 /// scalar accessors already close the per-element `String`-carry
5603 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
5604 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
5605 /// per-outermost-call wall-clock-deadline axis and the peer M3
5606 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
5607 /// accessor on the `:politicas` slot's per-call-deadline axis — all
5608 /// three share the shared substrate concept "a `Copy`-projected
5609 /// optional `Duration` that carries a positive integer-millisecond
5610 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
5611 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
5612 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
5613 /// bracket-helper the three axes each route through. Named
5614 /// `restart_window()` to match the storage field's name verbatim and
5615 /// the peer [`crate::LimitsSpec::wall_clock`] /
5616 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
5617 /// accessor's identity maps onto the canonical OTP-shape supervision
5618 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
5619 /// already carries.
5620 #[must_use]
5621 pub const fn restart_window(&self) -> Option<Duration> {
5622 self.restart_window
5623 }
5624
5625 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
5626 /// static-child-list slice accessor every consumer that walks the
5627 /// supervisor's declared child set keys off — returns the author-
5628 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
5629 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
5630 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
5631 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5632 /// through). Non-optional: an empty slice is the load-bearing
5633 /// "author declared `:children ()`" sentinel every consumer of the
5634 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
5635 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
5636 /// three strategies require a non-empty slice — the paired
5637 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
5638 /// [`SupervisorError::NoChildren`] refusal cascade pins the
5639 /// partition on both arms).
5640 ///
5641 /// The `:supervisor :children` slot carries the OTP-shaped static
5642 /// child list the supervisor materializes one ComputeUnit per
5643 /// entry from — the Erlang/OTP `supervisor:init/1`'s
5644 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
5645 /// through the tatara-lisp `:children` author surface onto a typed
5646 /// `Vec<ChildSpec>` whose per-element `(nome(),
5647 /// versao_requirement(), restart)` triple the per-child
5648 /// [`SupervisorSpec::validate`] loop already gates through the
5649 /// lifted [`ChildSpec::nome`] (57c61d0) /
5650 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
5651 /// Every downstream consumer that fans on the static child list
5652 /// keys off this slice (the [`SupervisorSpec::validate`]
5653 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
5654 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
5655 /// per-child DNS-1123 / semver-requirement / duplicate-detection
5656 /// fan-out loop, every future wasm-operator (M3) per-supervisor
5657 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
5658 /// materialization loop, the future M4
5659 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
5660 /// admission-webhook fan-out, the future `feira app graph`
5661 /// per-supervisor tree-print traversal).
5662 ///
5663 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
5664 /// inline at three production sites in `caixa-core/src/supervisor.rs`
5665 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
5666 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
5667 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
5668 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
5669 /// validate loop's `for child in &self.children` traversal head —
5670 /// three open-coded field-accesses that expressed no compile-time
5671 /// link back to the typed slot. A future extension of the
5672 /// `:supervisor :children` axis to a richer author surface (a
5673 /// per-cluster child-set overlay the operator pins through a future
5674 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
5675 /// supervision-canary roadmap acknowledges, a per-tenant
5676 /// child-set-alias table the M4 CR materializer resolves per-CR,
5677 /// a per-supervisor dynamic-child derivation the future adaptive-
5678 /// supervision engine computes from child-failure-history topology,
5679 /// a promotion of the plain `Vec<ChildSpec>` to a richer
5680 /// `{static, dynamic}` partition once Erlang/OTP's
5681 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
5682 /// would have had to be threaded through all three open-coded copies
5683 /// in lockstep or one consumer would silently disagree with the
5684 /// peers on which child-set a given supervisor resolves to — the
5685 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
5686 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
5687 /// would silently split the partition-dispatch's two-arm coherence
5688 /// (a supervisor that satisfies neither arm's precondition, or that
5689 /// satisfies both, at the cost of the paired
5690 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
5691 /// silently drifting from the per-child validate loop's actual
5692 /// traversal input), a three-consumer split at the validator far
5693 /// from the source `caixa.lisp` with no field naming the
5694 /// child-set-drift root cause. Lifting the resolution rule to a
5695 /// typed method on the substrate primitive means every downstream
5696 /// consumer of the Supervisor's per-`:supervisor` static-child-list
5697 /// surface reaches for exactly one typed dispatch — the resolver's
5698 /// accept-set migrates as a unit on any future axis addition.
5699 ///
5700 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5701 /// — the seed for the same "one typed dispatch on the substrate
5702 /// primitive, thin projections at each consumer" discipline the
5703 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
5704 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
5705 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
5706 /// onto the first `Vec`-carry axis on the substrate. The four peer
5707 /// `Vec`-carry axes still unlifted at the time of this seed —
5708 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
5709 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
5710 /// (`Vec<Membro>` per-Aplicacao member list),
5711 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
5712 /// per-Aplicacao WIT-typed edge list),
5713 /// [`crate::UpgradeFromEntry::instructions`]
5714 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5715 /// — inherit this accessor's discipline as future compounding runs
5716 /// migrate their consumers onto the shared slice-return shape.
5717 /// Fourth (and final) accessor on the M2 supervisor-slot
5718 /// `SupervisorSpec` type, sibling to the three `Copy`-return
5719 /// [`SupervisorSpec::estrategia`] (eafb619) /
5720 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
5721 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
5722 /// the last unlifted per-`:supervisor` field axis (the
5723 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
5724 /// per-`:supervisor` reader now routes through a typed dispatch on
5725 /// the substrate primitive. Named `children()` to match the storage
5726 /// field's name verbatim and the tatara-lisp author-surface term
5727 /// (`:children`) the field's own docstring already carries; the
5728 /// accessor's identity maps onto the canonical OTP-shape
5729 /// supervision vocabulary the [`SupervisorSpec::children`] field's
5730 /// docstring already reaches for ("Static children ..."). Returns
5731 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
5732 /// consumer of the child list treats it as a read-only sequence —
5733 /// the slice-view is the narrowest borrow that supports every
5734 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
5735 /// index, `.len()`) without leaking the backing `Vec`'s
5736 /// grow/push/reserve surface that no consumer of the typed view
5737 /// reaches for (the storage-side `Vec` remains reachable through
5738 /// the `pub children` field for the mutation-carrying
5739 /// `Caixa::supervisor_view` fold-in path in
5740 /// `manifest.rs:supervisor_view`).
5741 #[must_use]
5742 pub const fn children(&self) -> &[ChildSpec] {
5743 self.children.as_slice()
5744 }
5745
5746 /// Validate the supervisor's typed shape — strategy ↔ children
5747 /// invariants, max_restarts > 0, restart_window > 0 when set,
5748 /// per-child non-empty + duplicate-free names.
5749 ///
5750 /// Mirrors the value-shape discipline applied to every other
5751 /// typed slot:
5752 ///
5753 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
5754 /// same "0 means the opposite of what you think" footgun
5755 /// closed for `:politicas :timeout` (Envoy interprets a zero
5756 /// timeout as `infinite`), `:politicas :circuit-breaker
5757 /// :window`, and `:limits :wall-clock`. The
5758 /// `MaxIntensity / Period` ratio in Erlang/OTP's
5759 /// `supervisor` requires `Period > 0`; a zero period either
5760 /// trips on the first failure or never trips depending on
5761 /// operator interpretation, neither of which is the
5762 /// author's intent. Omit `:restart-window` to express "no
5763 /// reset"; carry a positive duration to express the window.
5764 /// - duplicate `:children` `:caixa` names are the same
5765 /// graph-node-set / multiset distinction closed for
5766 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
5767 /// and `:entrada :paths` (eb3456d). Two children with the
5768 /// same `:caixa` materialize as two ComputeUnits with the
5769 /// same name in the cluster's HelmRelease values, one
5770 /// silently overwriting the other. Erlang/OTP's
5771 /// `child_spec.id` is required-unique per supervisor;
5772 /// pleme-io enforces the same set-not-multiset shape on
5773 /// `:caixa` (the load-bearing identity in our renderer).
5774 pub fn validate(&self) -> Result<(), SupervisorError> {
5775 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
5776 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
5777 // error carrier's `estrategia:` field through the lifted
5778 // [`SupervisorSpec::estrategia`] accessor rather than the raw
5779 // `self.estrategia` field access — the two production consumers
5780 // of the per-`:supervisor` sibling-restart-strategy scalar now
5781 // key off exactly one typed dispatch on the substrate primitive,
5782 // so any future rebrand on the axis (a per-cluster strategy
5783 // override the operator pins through a future `:supervisor
5784 // :estrategia-overrides` slot, a per-tenant strategy-alias table
5785 // the M4 CR materializer resolves per-CR) migrates as a single
5786 // caixa-core edit rather than a coordinated rewrite of the two
5787 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
5788 // (921fe1b) four-consumer migration on the per-`:placement`
5789 // distribution-strategy axis.
5790 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
5791 // dispatch's paired `.is_empty()` cross-slot refusal probes
5792 // (the `SimpleOneForOne`-arm
5793 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
5794 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
5795 // refusal) through the lifted [`SupervisorSpec::children`]
5796 // slice-return accessor rather than the raw `self.children`
5797 // field access — the two paired production consumers of the
5798 // per-`:supervisor` static-child-list scalar-shape now key off
5799 // exactly one typed dispatch on the substrate primitive, so any
5800 // future rebrand on the axis (a per-cluster child-set overlay
5801 // the operator pins through a future `:supervisor
5802 // :children-overrides` slot, a per-tenant child-set-alias table
5803 // the M4 CR materializer resolves per-CR) migrates as a single
5804 // caixa-core edit rather than a coordinated rewrite of the
5805 // paired arms — first slice-return migration on any typed slot,
5806 // seed for the peer per-`:placement :clusters`,
5807 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
5808 // :instructions` `Vec`-carry axes.
5809 match self.estrategia() {
5810 RestartStrategy::SimpleOneForOne => {
5811 // SimpleOneForOne: children added at runtime. Static
5812 // list must be empty (one shape declared elsewhere).
5813 if !self.children().is_empty() {
5814 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
5815 }
5816 }
5817 _ => {
5818 if self.children().is_empty() {
5819 return Err(SupervisorError::no_children(self.estrategia()));
5820 }
5821 }
5822 }
5823 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
5824 // axis. See [`crate::render::require_positive_bounded_u32`] for
5825 // the ordering discipline (zero-floor arm strictly precedes cap
5826 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
5827 // diagnostic with its counter-axis remediation directly named,
5828 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
5829 // cap-arm miss). Until this bracket landed the top edge ran all
5830 // the way to `u32::MAX` and a struct-literal
5831 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
5832 // equivalent author-surface `:max-restarts 100000` /
5833 // `:max-restarts 4294967295` typo landing in the slot) silently
5834 // passed validate. The runtime substrate consuming the value
5835 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
5836 // wasm-operator's per-supervisor restart-intensity counter, the
5837 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5838 // admission webhook) then turned a typed `:max-restarts`
5839 // policy into a no-op supervisor: the escalation threshold is
5840 // structurally so high that no realistic
5841 // restarts-per-`:restart-window` traffic shape can reach it,
5842 // the supervisor never escalates to its parent, and a bad
5843 // child can loop inside the window indefinitely with the
5844 // parent supervisor structurally never receiving the "this
5845 // subtree has exceeded its restart budget" signal the typed
5846 // slot is meant to express. The bracket set is
5847 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
5848 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
5849 // the sibling `:politicas :circuit-breaker :max-failures` axis:
5850 // both are "trip the next-higher protection layer after N
5851 // events in a rolling window" counters with identical
5852 // degenerate-at-the-high-end shape and now share one canonical
5853 // bracket helper. The bracket precedes the sibling
5854 // `:restart-window` zero-floor / canonical-millisecond arms so
5855 // an over-cap `max_restarts` paired with a structurally invalid
5856 // window surfaces the bracket diagnostic first, mirroring the
5857 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
5858 // ordering on the peer `:politicas :circuit-breaker` slot.
5859 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
5860 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
5861 // accessor rather than the raw `self.max_restarts` field access —
5862 // the one production consumer of the per-`:supervisor`
5863 // restart-budget-count scalar now keys off exactly one typed
5864 // dispatch on the substrate primitive, so any future rebrand on
5865 // the axis (a per-cluster restart-budget override the operator
5866 // pins through a future `:supervisor :max-restarts-overrides`
5867 // slot, a per-tenant restart-budget-alias table the M4 CR
5868 // materializer resolves per-CR) migrates as a single caixa-core
5869 // edit rather than a coordinated rewrite — sibling of the peer M3
5870 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
5871 // the per-`:politicas :circuit-breaker :max-failures` axis.
5872 crate::render::require_positive_bounded_u32(
5873 self.max_restarts(),
5874 SUPERVISOR_MAX_RESTARTS_MAX,
5875 || SupervisorError::ZeroMaxRestarts,
5876 SupervisorError::max_restarts_exceeds_cap,
5877 )?;
5878 // Route the [`SupervisorSpec::validate`] `:restart-window`
5879 // zero-floor + integer-millisecond canonical-form + upper-cap
5880 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
5881 // accessor rather than the raw `self.restart_window` field access —
5882 // the one production consumer of the per-`:supervisor`
5883 // restart-intensity-denominator scalar now keys off exactly one
5884 // typed dispatch on the substrate primitive, so any future rebrand
5885 // on the axis (a per-cluster restart-window override the operator
5886 // pins through a future `:supervisor :restart-window-overrides`
5887 // slot, a per-tenant restart-window-alias table the M4 CR
5888 // materializer resolves per-CR) migrates as a single caixa-core
5889 // edit rather than a coordinated rewrite — sibling of the peer M2
5890 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
5891 // on the per-`:limits :wall-clock` axis and the peer M3
5892 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
5893 // per-`:politicas :timeout` axis.
5894 if let Some(w) = self.restart_window() {
5895 // Zero-floor + integer-millisecond canonical-form +
5896 // upper-cap bracket on the typed `:restart-window` axis.
5897 // See
5898 // [`crate::render::require_positive_canonical_bounded_duration`]
5899 // for the full three-arm ordering discipline (zero-floor
5900 // strictly precedes canonical-form so `Duration::ZERO`
5901 // surfaces the self-locating `RestartWindowZero`
5902 // diagnostic; canonical-form strictly precedes the cap arm
5903 // so a sub-millisecond above-cap value surfaces the more
5904 // fundamental round-trip-shape diagnostic first) and the
5905 // three peer typed-`Duration` sites that share this
5906 // canonical bracket ([`crate::MeshPolicy::timeout`],
5907 // [`crate::CircuitBreaker::window`],
5908 // [`crate::LimitsSpec::wall_clock`]). Every validated
5909 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
5910 // (1ms..=1h), integer-millisecond granularity.
5911 crate::render::require_positive_canonical_bounded_duration(
5912 w,
5913 SUPERVISOR_RESTART_WINDOW_MAX,
5914 || SupervisorError::RestartWindowZero,
5915 SupervisorError::restart_window_not_canonical,
5916 SupervisorError::restart_window_exceeds_cap,
5917 )?;
5918 }
5919 // Route the per-child DNS-1123 / semver-requirement / duplicate-
5920 // detection fan-out loop through the lifted named per-slot gate
5921 // [`SupervisorSpec::validate_children`] rather than an inline
5922 // three-per-child cascade — every future consumer that wants to
5923 // re-check only the `:children` slot's per-entry axes (the M4
5924 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5925 // admission webhook re-validating one added/renamed child, the
5926 // future wasm-operator's per-child dynamic-add re-validator on
5927 // the `SimpleOneForOne` runtime-add path once dynamic-children
5928 // graduate to a typed slot, a future partial re-validator on a
5929 // per-`:children`-entry patch) reaches every per-entry axis
5930 // through one dispatch rather than re-inlining the three-arm
5931 // cascade in lockstep with `validate` or paying the peer
5932 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
5933 // reach one entry check. Sibling of the peer M3 mesh-slot
5934 // per-slot gate family (`validate_membros` — the exact peer on
5935 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
5936 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
5937 // `validate_placement`; `validate_politicas` routing through
5938 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
5939 // per-slot gate discipline now spans both the M3 mesh-slot
5940 // family and the M2 `:children` per-child-cascade axis on one
5941 // shape: one named per-slot gate per typed per-entry loop.
5942 self.validate_children()?;
5943 Ok(())
5944 }
5945
5946 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
5947 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
5948 /// gate, and duplicate-`:caixa` dedup arm into one call every
5949 /// consumer that wants to re-validate one `:children` entry (or the
5950 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
5951 /// admits reaches through.
5952 ///
5953 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
5954 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
5955 /// three-per-entry shape (DNS-1123 name + semver-requirement +
5956 /// duplicate-`:caixa` dedup), lifted to one named substrate
5957 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
5958 /// materializer's admission webhook re-checking one added or renamed
5959 /// child, the future wasm-operator's per-child dynamic-add
5960 /// re-validator on the `SimpleOneForOne` runtime-add path once
5961 /// dynamic-children graduate to a typed slot, a future partial
5962 /// re-validator on a per-`:children`-entry patch — each reaches the
5963 /// three per-entry axes through this one dispatch rather than
5964 /// re-inlining the three-arm cascade in lockstep with `validate`
5965 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
5966 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
5967 /// reach one entry check.
5968 ///
5969 /// Self-contained on `&self` — resolves its own dedup `HashSet`
5970 /// through [`SupervisorSpec::children`] rather than borrowing one
5971 /// threaded down from `validate`, the same posture the peer M3
5972 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
5973 /// [`crate::AplicacaoSpec::validate_contratos`],
5974 /// [`crate::AplicacaoSpec::validate_entrada`],
5975 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
5976 /// consumer that reaches this gate directly (without first calling
5977 /// `validate`) still runs the full per-child cascade — pinned by
5978 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
5979 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
5980 /// + `validate_children_is_self_contained_on_children_slot`.
5981 ///
5982 /// The three per-entry arms run in the same canonical order the
5983 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
5984 /// the diagnostic every author-declared per-`:children` entry surfaces
5985 /// through `validate` is byte-equal to the diagnostic this gate
5986 /// surfaces when called directly — the equivalence-pin pair
5987 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
5988 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
5989 /// asserts the two altitudes discriminate the same set on every
5990 /// per-entry-covered input.
5991 pub fn validate_children(&self) -> Result<(), SupervisorError> {
5992 let mut seen = std::collections::HashSet::new();
5993 for child in self.children() {
5994 // Every emitted cluster artifact's `metadata.name` for a
5995 // supervised child derives from this `:children :caixa` value
5996 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
5997 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
5998 // label value on every child's pod identity, and the per-
5999 // child K8s [`Service`][svc] `metadata.name` the future
6000 // wasm-operator (M3) provisions for inter-child supervision
6001 // tree wiring. Each apiserver-side schema on each landing
6002 // site enforces the DNS-1123 label rule on admission; a
6003 // structurally invalid child name (`"Worker"`, `"my_worker"`,
6004 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
6005 // UUID-shaped mistaken-identity slug) silently passes the
6006 // prior empty-/duplicate-only gate and the failure surfaces
6007 // at `kubectl apply` time as a `metadata.name: Invalid value`
6008 // rejection, far from the source caixa.lisp, with no field
6009 // naming the offending `:children` entry. Lifting the gate
6010 // to caixa-build time mirrors the `:membros :caixa` value-
6011 // shape trajectory (3f9d7a0) and the `:placement :clusters`
6012 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
6013 // identifier axis — the supervisor tree's child names —
6014 // through the lifted
6015 // [`crate::render::require_valid_dns_1123_label`] gate the
6016 // seven peer name axes (`:membros :caixa`, `:placement
6017 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
6018 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
6019 // route through, so drift between the eight axes' accepted
6020 // DNS-1123-label sets is structurally impossible.
6021 //
6022 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
6023 crate::render::require_valid_dns_1123_label(
6024 child.nome(),
6025 || SupervisorError::EmptyChildName,
6026 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
6027 )?;
6028 // The author surface for `:children :versao` is the same
6029 // Cargo-shaped semver requirement string `:deps :versao` and
6030 // `:membros :versao` carry — and the lacre pipeline resolves
6031 // all three axes through the same
6032 // [`crate::version::parse_requirement`] entry-point. The
6033 // shared [`crate::render::require_valid_versao_requirement`]
6034 // helper brackets the empty-first + parse cascade both peer
6035 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6036 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
6037 // :versao`) route through, so drift between the three axes'
6038 // accepted requirement sets is structurally impossible and
6039 // the parse-side no-op the empty-first arm closes (semver's
6040 // empty parse yields an implicit `*`) lives in exactly one
6041 // predicate. Every `ChildSpec::versao` past validate is
6042 // round-trippable through [`crate::parse_requirement`]
6043 // without re-checking at the resolver layer, and the three
6044 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
6045 // are now structurally equivalent by construction.
6046 crate::render::require_valid_versao_requirement(
6047 child.versao_requirement(),
6048 || SupervisorError::empty_child_version(child.nome()),
6049 |reason| {
6050 SupervisorError::child_versao_invalid(
6051 child.nome(),
6052 child.versao_requirement(),
6053 reason,
6054 )
6055 },
6056 )?;
6057 crate::render::insert_first_seen(&mut seen, child.nome(), || {
6058 SupervisorError::duplicate_child_caixa(child.nome())
6059 })?;
6060 }
6061 Ok(())
6062 }
6063}
6064
6065/// Cross-slot coherence gate on the supervision tree: no
6066/// `:children :caixa` entry may name the supervisor's own `:nome`.
6067///
6068/// A supervisor that lists itself as a child is a degenerate self-parent
6069/// — the supervision tree is a DAG rooted at the supervisor (OTP child
6070/// specs reference *distinct* child processes; a supervisor is never its
6071/// own child), and the wasm-operator's hierarchical reconciliation would
6072/// otherwise be handed a node that is its own parent: a one-node cycle it
6073/// either rejects far from the source `caixa.lisp` or recurses on. Because
6074/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
6075/// lacre closure root), a child whose `:caixa` equals the supervisor's
6076/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
6077///
6078/// Lives outside [`SupervisorSpec::validate`] because the typed view
6079/// carries the children but not the parent `:nome`; mirrors the
6080/// cross-slot precedence gate `validate_upgrade_from_against_versao`
6081/// (which likewise reads one slot against another at the
6082/// [`crate::layout`] wire-up site) and the mesh self-edge gate
6083/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
6084/// node to itself is structurally not a tree/mesh edge" discipline, here
6085/// on the supervision-tree axis.
6086pub fn validate_no_self_supervision(
6087 children: &[ChildSpec],
6088 parent_nome: &str,
6089) -> Result<(), SupervisorError> {
6090 for child in children {
6091 if child.nome() == parent_nome {
6092 return Err(SupervisorError::child_supervises_self(parent_nome));
6093 }
6094 }
6095 Ok(())
6096}
6097
6098#[derive(Debug, Error, PartialEq, Eq)]
6099pub enum SupervisorError {
6100 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
6101 NoChildren { estrategia: RestartStrategy },
6102 #[error(
6103 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
6104 )]
6105 SimpleOneForOneWithStaticChildren,
6106 #[error(":max-restarts must be > 0")]
6107 ZeroMaxRestarts,
6108 #[error(
6109 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
6110 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
6111 restart-intensity policy into a no-op supervisor: the escalation threshold is \
6112 structurally so high that no realistic restarts-per-:restart-window traffic shape \
6113 can reach it, so the supervisor never escalates to its parent and a bad child can \
6114 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
6115 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
6116 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
6117 materializer's admission webhook) emits a `:max-restarts` declaration that is \
6118 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
6119 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
6120 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
6121 band) or restructure the supervision tree (split the flaky child into its own \
6122 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
6123 )]
6124 MaxRestartsExceedsCap { max_restarts: u32 },
6125 #[error(
6126 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
6127 requires Period > 0; a zero window either trips on the first failure or \
6128 never trips depending on operator interpretation. Omit :restart-window to \
6129 express `never reset`; carry a positive duration to express the window."
6130 )]
6131 RestartWindowZero,
6132 #[error(
6133 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
6134 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
6135 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
6136 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
6137 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
6138 )]
6139 RestartWindowNotCanonical { window: Duration },
6140 #[error(
6141 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
6142 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
6143 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
6144 failure-counting window is structurally so long that transient restarts are never \
6145 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
6146 when the child has exceeded its restart budget within the recent window` to `trip the \
6147 parent when the child has exceeded its restart budget over its lifetime`, and the \
6148 supervisor's reset semantic never reaches the child — every typed-slot consumer \
6149 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
6150 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
6151 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
6152 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
6153 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
6154 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
6155 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
6156 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
6157 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
6158 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
6159 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
6160 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
6161 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
6162 hiding it behind a rolling-window declaration the cap arm rejects)"
6163 )]
6164 RestartWindowExceedsCap { window: Duration },
6165 #[error("child entry has empty :caixa name")]
6166 EmptyChildName,
6167 #[error(
6168 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
6169 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
6170 name / label value the child name lands in — the per-child \
6171 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
6172 label value, and the future wasm-operator per-child Service `metadata.name` \
6173 — each apiserver-side schema rejects names that don't match; use a \
6174 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
6175 )]
6176 ChildCaixaInvalid { caixa: String, reason: String },
6177 #[error("child {caixa:?} has empty :versao constraint")]
6178 EmptyChildVersion { caixa: String },
6179 #[error(
6180 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
6181 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
6182 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
6183 `:membros :versao` carry; the lacre pipeline resolves all three \
6184 through the same parser)"
6185 )]
6186 ChildVersaoInvalid {
6187 caixa: String,
6188 versao: String,
6189 reason: String,
6190 },
6191 #[error(
6192 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
6193 child_spec.id per supervisor; duplicate children materialize as duplicate \
6194 ComputeUnits in the rendered chart, one silently overwriting the other)"
6195 )]
6196 DuplicateChildCaixa { caixa: String },
6197 #[error(
6198 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
6199 never its own child (the supervision tree is a DAG rooted at the supervisor; \
6200 OTP child specs reference distinct child processes). Since every :nome is a \
6201 globally-unique substrate identity, a child naming the supervisor's own :nome \
6202 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
6203 self-referential :children entry or rename it to the actual child caixa."
6204 )]
6205 ChildSupervisesSelf { caixa: String },
6206}
6207
6208// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
6209// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
6210// and [`validate_no_self_supervision`] onto one substrate primitive per
6211// typed variant — the sibling on `SupervisorError` of the four uniform-shape
6212// `LayoutError`-envelope constructor families the peer
6213// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
6214// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
6215// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
6216// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
6217// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
6218// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
6219// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
6220// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
6221// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
6222// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
6223// variants on `{ de, para }`) already at that discipline on the peer
6224// `AplicacaoError` envelopes.
6225//
6226// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
6227// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
6228// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
6229// self-supervision arm) opened the identical
6230// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
6231// the exact "same block re-inlined at every consumer" shape the PRIME
6232// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
6233// `AplicacaoError` families each closed on their sibling envelopes. The
6234// three variants share one `{ caixa: String }` shape, so the fold routes
6235// each wire-up site through one dispatch per typed variant.
6236//
6237// The macro below generates one static constructor per variant of shape
6238// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
6239// collapses onto one dispatch:
6240// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
6241// struct-literal on the same `&str` fixture. The uniform one-field
6242// construction (`caixa: caixa.to_string()`) is spelled once — inside the
6243// macro — rather than at every wire-up site. Every constructor is
6244// `#[must_use]` so a caller who mistakenly discards the constructed error
6245// trips a compile warning at the wire-up site.
6246//
6247// Every future consumer that wants to construct one of these three
6248// variants outside `SupervisorSpec::validate_children` /
6249// `validate_no_self_supervision` — a deferred
6250// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
6251// webhook re-checking one added/renamed child, a future
6252// `feira validate --supervisor` per-caixa admission verb, a per-child
6253// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
6254// once dynamic-children graduate to a typed slot, a per-Supervisor
6255// overlay resolver rejecting a duplicate/self-supervising child against
6256// a cluster-local snapshot — now reaches each variant through one call
6257// rather than re-inlining the three-line struct-literal in lockstep
6258// with the three in-crate wire-up sites.
6259macro_rules! supervisor_caixa_only_ctors {
6260 ($($ctor:ident => $variant:ident),* $(,)?) => {
6261 impl SupervisorError {
6262 $(
6263 #[doc = concat!(
6264 "Construct a [`SupervisorError::",
6265 stringify!($variant),
6266 "`] naming the offending `:children :caixa` (or ",
6267 "supervisor `:nome`, on the self-supervision arm). ",
6268 "Folds the uniform `Self::",
6269 stringify!($variant),
6270 " { caixa: caixa.to_string() }` one-field ",
6271 "struct-literal onto one substrate primitive so ",
6272 "every [`SupervisorSpec::validate_children`] / ",
6273 "[`validate_no_self_supervision`] wire-up on this ",
6274 "variant reads through one dispatch rather than the ",
6275 "pre-lift open-coded struct-literal block."
6276 )]
6277 #[must_use]
6278 pub fn $ctor(caixa: &str) -> Self {
6279 Self::$variant { caixa: caixa.to_string() }
6280 }
6281 )*
6282 }
6283 };
6284}
6285
6286supervisor_caixa_only_ctors! {
6287 empty_child_version => EmptyChildVersion,
6288 duplicate_child_caixa => DuplicateChildCaixa,
6289 child_supervises_self => ChildSupervisesSelf,
6290}
6291
6292// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
6293// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
6294// one substrate primitive per typed variant — the M2 supervisor-side siblings
6295// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
6296// already lifted through the sibling
6297// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
6298// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
6299// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
6300// String }` two-slot shape the peer seven-variant
6301// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
6302// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
6303// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
6304// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
6305// variant carries the `{ caixa: String, versao: String, reason: String }`
6306// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
6307// carries on the same `:versao` value-shape.
6308//
6309// Each of the two wire-up sites opened the same closure-shaped
6310// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
6311// [versao: child.versao_requirement().to_string(),] reason }` block inside
6312// the paired [`crate::render::require_valid_dns_1123_label`] and
6313// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
6314// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
6315// as a bug, on the same altitude the peer `AplicacaoError` /
6316// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
6317// families already closed on their sibling envelopes.
6318//
6319// The two `#[must_use]` inherent constructors below fold each wire-up onto
6320// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
6321// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
6322// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
6323// The uniform per-field `.to_string()` / `.into()` construction is spelled
6324// once — inside each ctor body — rather than at every wire-up site. The
6325// `reason: impl Into<String>` bound accepts both `&str` literals and
6326// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
6327// diagnostic shape at the lift, matching the peer
6328// [`aplicacao_field_reason_ctors!`] and
6329// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
6330// sibling envelopes.
6331//
6332// Every future consumer that wants to construct one of these two variants
6333// outside `SupervisorSpec::validate_children` — a deferred
6334// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
6335// re-checking one added/renamed child's `:caixa` or `:versao`, a future
6336// `feira validate --supervisor` per-caixa admission verb, a per-child
6337// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
6338// dynamic-children graduate to a typed slot, a per-Supervisor overlay
6339// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
6340// cluster-local snapshot — now reaches each variant through one call rather
6341// than re-inlining the per-shape struct-literal block in lockstep with the
6342// two in-crate wire-up sites.
6343impl SupervisorError {
6344 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
6345 /// offending `:children :caixa` value under the given `reason`. Folds
6346 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
6347 /// reason: reason.into() }` two-slot struct-literal onto one substrate
6348 /// primitive so every wire-up on this variant reads through one
6349 /// dispatch, matching the peer
6350 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
6351 /// sibling `AplicacaoError { caixa: String, reason: String }`
6352 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
6353 /// outputs through the `impl Into<String>` bound.
6354 #[must_use]
6355 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
6356 Self::ChildCaixaInvalid {
6357 caixa: caixa.to_string(),
6358 reason: reason.into(),
6359 }
6360 }
6361
6362 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
6363 /// offending `:children :caixa` and its `:versao` requirement under
6364 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
6365 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
6366 /// reason.into() }` three-slot struct-literal onto one substrate
6367 /// primitive so every wire-up on this variant reads through one
6368 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
6369 /// { caixa, versao, reason }` three-slot axis on the peer
6370 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
6371 /// and `format!(…)` outputs through the `impl Into<String>` bound.
6372 #[must_use]
6373 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
6374 Self::ChildVersaoInvalid {
6375 caixa: caixa.to_string(),
6376 versao: versao.to_string(),
6377 reason: reason.into(),
6378 }
6379 }
6380}
6381
6382// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
6383// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
6384// three bracket-arms — one struct-literal at the `:children`-empty
6385// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
6386// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
6387// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
6388// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
6389// [`crate::render::require_positive_canonical_bounded_duration`]
6390// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
6391// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
6392// primitive per typed variant, matching the sibling
6393// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
6394// variants on the same `{ <field>: Duration | u32 }` shape) at that
6395// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
6396// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
6397// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
6398// wire-up site through one dispatch per typed variant without a runtime-
6399// work delta.
6400//
6401// Each of the four wire-up sites opened the identical
6402// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
6403// exact "same block re-inlined at every consumer" shape the PRIME
6404// DIRECTIVE names as a bug, on the same altitude the peer
6405// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
6406// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
6407// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
6408// the fold routes each wire-up site through one dispatch per typed
6409// variant.
6410//
6411// The macro below generates one static constructor per variant of shape
6412// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
6413// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
6414// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
6415// fixture — as a direct call at the [`SupervisorSpec::validate`]
6416// `:children`-empty refusal, or as a bare function pointer in the
6417// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
6418// [`crate::render::require_positive_bounded_u32`] /
6419// [`crate::render::require_positive_canonical_bounded_duration`] gate
6420// carries — rather than the pre-lift open-coded one-line closure over
6421// the same one-field struct-literal. `const fn` preserves the `Copy`-
6422// pass-through's zero-runtime-work property verbatim. Every constructor
6423// is `#[must_use]` so a caller who mistakenly discards the constructed
6424// error trips a compile warning at the wire-up site.
6425//
6426// Every future consumer that wants to construct one of these four
6427// variants outside `SupervisorSpec::validate` — a deferred
6428// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
6429// webhook re-checking one edited `:estrategia` / `:max-restarts` /
6430// `:restart-window` slot against the cap + canonical-form cascade, a
6431// future `feira validate --supervisor` per-caixa admission verb re-
6432// running the shape gates on demand, a per-Supervisor overlay resolver
6433// rejecting an author-supplied slot against a cluster-local snapshot —
6434// now reaches each variant through one call rather than re-inlining the
6435// per-shape struct-literal block in lockstep with the four in-crate
6436// wire-up sites.
6437macro_rules! supervisor_scalar_ctors {
6438 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
6439 impl SupervisorError {
6440 $(
6441 #[doc = concat!(
6442 "Construct a [`SupervisorError::",
6443 stringify!($variant),
6444 "`] naming the offending per-`:supervisor` `",
6445 stringify!($field),
6446 "` scalar. Folds the uniform `Self::",
6447 stringify!($variant),
6448 " { ",
6449 stringify!($field),
6450 " }` one-field `Copy`-pass-through struct-literal onto ",
6451 "one substrate primitive so every per-axis wire-up on ",
6452 "this variant reads through one dispatch — as a direct ",
6453 "call (`SupervisorError::",
6454 stringify!($ctor),
6455 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
6456 "the same `Copy`-`",
6457 stringify!($ty),
6458 "` fixture) or as a bare function pointer in the ",
6459 "`impl FnOnce(",
6460 stringify!($ty),
6461 ") -> SupervisorError` bracket-closure slot every ",
6462 "`crate::render::require_positive_bounded_*` / ",
6463 "`crate::render::require_positive_canonical_bounded_*` ",
6464 "gate carries — rather than the pre-lift open-coded ",
6465 "one-line closure over the same one-field struct-",
6466 "literal. `const fn` preserves the `Copy`-pass-through's ",
6467 "zero-runtime-work property verbatim."
6468 )]
6469 #[must_use]
6470 pub const fn $ctor($field: $ty) -> Self {
6471 Self::$variant { $field }
6472 }
6473 )*
6474 }
6475 };
6476}
6477
6478supervisor_scalar_ctors! {
6479 no_children => NoChildren { estrategia: RestartStrategy },
6480 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
6481 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
6482 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
6483}
6484
6485/// Shared duration string codec for the typed slots that take a
6486/// duration (`restart_window`, `MeshPolicy::timeout`,
6487/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
6488/// reuse it without duplicating the parser.
6489pub mod duration_codec {
6490 use super::Duration;
6491 use serde::{Deserializer, Serializer};
6492
6493 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
6494 // Route through the canonical [`crate::render::serialize_option_via_str`]
6495 // — the substrate-side single-owner primitive for the forward
6496 // arm of the typed-magnitude codec family. See its docstring
6497 // for the full sibling roster.
6498 crate::render::serialize_option_via_str(v, s, render)
6499 }
6500
6501 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
6502 // Route through the canonical [`crate::render::deserialize_option_via_str`]
6503 // — the substrate-side single-owner primitive for the reverse
6504 // arm of the typed-magnitude codec family. See its docstring
6505 // for the full sibling roster.
6506 crate::render::deserialize_option_via_str(d, parse)
6507 }
6508
6509 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
6510 // Paired whitespace-rejection arm — same canonical-form
6511 // render-determinism discipline as the peer
6512 // `limits::parse_byte_size` / `limits::parse_duration` /
6513 // `limits::parse_millicores` /
6514 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
6515 // byte-scan closes the WhatWG-conformant whitespace bytes
6516 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
6517 // `char::is_whitespace` scan closes the strictly-complementary
6518 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
6519 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
6520 // codepoints) that `str::trim` at parse entry silently strips.
6521 // Either drift class would round-trip through `render` to a
6522 // *different* canonical form on next emit — breaking the
6523 // THEORY.md Part V render-determinism contract on three typed-
6524 // duration slots at once (`:supervisor :restart-window`,
6525 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
6526 // via the shared codec.
6527 //
6528 // Routed through the lifted [`crate::render::reject_whitespace`]
6529 // primitive — the substrate-side single-owner paired-arm gate
6530 // every typed-magnitude codec in caixa-core shares.
6531 crate::render::reject_whitespace::<String, _, _>(
6532 s,
6533 |b| {
6534 format!(
6535 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
6536 authoring form for the typed duration slots routed through this shared codec \
6537 (`:supervisor :restart-window`, `:politicas :timeout`, \
6538 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
6539 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
6540 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
6541 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
6542 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
6543 Part V render-determinism contract every typed slot carries. Strip every \
6544 whitespace byte (write `\"30s\"` verbatim)"
6545 )
6546 },
6547 |ch| {
6548 format!(
6549 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
6550 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
6551 duration slots routed through this shared codec (`:supervisor \
6552 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
6553 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
6554 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
6555 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
6556 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
6557 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
6558 `White_Space` property, strictly wider than the ASCII byte set) silently \
6559 strips it at parse entry, and the value round-trips through `render` to \
6560 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
6561 the THEORY.md Part V render-determinism contract every typed slot \
6562 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
6563 verbatim with only ASCII bytes)",
6564 cp = ch as u32
6565 )
6566 },
6567 )?;
6568 let s = s.trim();
6569 // Routed through the lifted
6570 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
6571 // the single-owner split every ASCII-alphabetic-unit typed-
6572 // magnitude codec in caixa-core (`limits::parse_byte_size` /
6573 // `limits::parse_duration` / this shared duration codec) shares.
6574 // See its docstring for the full sibling roster on the same
6575 // primitive altitude.
6576 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
6577 let num_trim = num_part.trim();
6578 // The canonical authoring form for every typed slot routed
6579 // through this shared codec — `:supervisor :restart-window`,
6580 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
6581 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
6582 // non-negative integer with no decimal point and no leading
6583 // sign, so the parser's accepted set must match for
6584 // serialize/deserialize to round-trip without canonical-form
6585 // drift. Until this gate landed the parser accepted any
6586 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
6587 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
6588 // tripped the value to a *different* canonical string on the
6589 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
6590 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
6591 // — breaking the THEORY.md Part V render-determinism contract
6592 // on three typed slots at once. Same canonical-form discipline
6593 // `crate::limits::parse_duration` (818dd38, the immediate
6594 // predecessor on the peer `:limits :wall-clock` codec) applies;
6595 // this gate lifts the discipline onto the shared codec that
6596 // backs the remaining three typed-duration slots in caixa-core.
6597 //
6598 // Strict canonical form: every byte of the magnitude is an
6599 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
6600 // inputs the gate distinguishes "non-canonical-but-numeric"
6601 // (parses as f64 or i64 — surfaced with a self-locating
6602 // diagnostic naming the canonical authoring form, the
6603 // round-trip drift each rejected shape would produce on first
6604 // serialize, and the canonical-form remediation) from
6605 // "garbage" (parses as neither — surfaced with the existing
6606 // narrower "bad duration magnitude" wording so its diagnostic
6607 // shape remains stable for the parser-shape footgun case).
6608 // The pre-existing `num < 0.0` arm is now unreachable — the
6609 // digit-only gate strictly precedes magnitude parsing, and a
6610 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
6611 // non-canonical-but-numeric branch with the `-30` named
6612 // verbatim in the diagnostic rather than the prior
6613 // value-laundered "negative duration in \"-30s\"" wording.
6614 //
6615 // Routed through the lifted
6616 // [`crate::render::is_digit_only_magnitude`] predicate — the
6617 // same source of truth the four peer typed-magnitude codec
6618 // sites share.
6619 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
6620 if !digit_only {
6621 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
6622 if numeric {
6623 return Err(format!(
6624 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
6625 canonical authoring form for the typed duration slots routed through \
6626 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
6627 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
6628 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
6629 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
6630 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
6631 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
6632 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
6633 THEORY.md Part V render-determinism contract every typed slot carries. \
6634 Pick an integer magnitude in the unit that divides cleanly (write \
6635 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
6636 ));
6637 }
6638 return Err(format!("bad duration magnitude in {s:?}"));
6639 }
6640 // Leading-zero arm — peer with the `rate_limit_codec` leading-
6641 // zero arm (4f46830) on the same canonical-form render-
6642 // determinism axis. The digit-only gate accepts `"030s"`,
6643 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
6644 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
6645 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
6646 // *different* canonical string on the next emit, breaking the
6647 // THEORY.md Part V render-determinism contract the same way
6648 // `"+30s"` did before the leading-`+` arm landed. The single-
6649 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
6650 // losslessly through `render` (`render(Duration::ZERO)` emits
6651 // `"0s"`) — the downstream semantic-zero gates (e.g.
6652 // `SupervisorError::ZeroRestartWindow` on
6653 // `:supervisor :restart-window`,
6654 // `AplicacaoError::PolicyTimeoutZero` /
6655 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
6656 // duration slots) refuse zero-magnitude authoring at the typed-
6657 // validate layer above, so the single-byte `"0"` stays in the
6658 // accepted set at this codec layer and the diagnostic
6659 // partitioning between canonical-form drift (this arm) and
6660 // semantic-zero (the downstream gates) remains stable.
6661 // Peer with the future leading-zero arms on the two remaining
6662 // typed-magnitude codecs the trajectory acknowledges:
6663 // `limits::parse_duration` backing `:limits :wall-clock`,
6664 // `limits::parse_byte_size` backing `:limits :memory` — each
6665 // carries the same canonical-form-drift class today; this
6666 // gate lands the discipline on the shared duration codec
6667 // first because the `rate_limit_codec` predecessor on the
6668 // same canonical-form-drift axis is the closest peer on the
6669 // trajectory.
6670 //
6671 // Routed through the lifted
6672 // [`crate::render::is_leading_zero_padded_magnitude`]
6673 // predicate — the same source of truth the four peer
6674 // typed-magnitude codec sites share.
6675 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
6676 return Err(format!(
6677 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
6678 canonical authoring form for the typed duration slots routed through \
6679 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
6680 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
6681 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
6682 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
6683 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
6684 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
6685 serialize — breaking the THEORY.md Part V render-determinism contract \
6686 every typed slot carries. Strip the leading zeros (write \
6687 `\"30s\"` instead of `\"030s\"`)"
6688 ));
6689 }
6690 // The digit-only gate guarantees every byte is `[0-9]`, and
6691 // the leading-zero arm above guarantees the magnitude is
6692 // either the single byte `"0"` or starts with `[1-9]`, so
6693 // the only way `u64::from_str` can fail here is overflow (the
6694 // magnitude exceeds `u64::MAX`). Surface that with an
6695 // overflow-shaped wording so the diagnostic names the offending
6696 // magnitude verbatim rather than collapsing onto the
6697 // non-canonical arm. The codec now operates on `u64` end-to-end
6698 // — every accepted magnitude is integer-exact; no f64 mantissa
6699 // drift between author-supplied magnitude and the consumer's
6700 // `Duration` value. Same shape `crate::limits::parse_duration`
6701 // (818dd38) carries on the peer `:limits :wall-clock` axis.
6702 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
6703 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
6704 })?;
6705 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
6706 // unit-arm dispatch through the canonical
6707 // [`crate::render::duration_from_integer_magnitude_and_unit`]
6708 // primitive — the substrate-side single-owner unit-dispatch
6709 // table every typed-duration codec in caixa-core routes
6710 // through (peer: `crate::limits::parse_duration` backing
6711 // `:limits :wall-clock`). Every unit conversion is integer-
6712 // exact for an integer magnitude; overflow surfaces via the
6713 // typed `DurationUnitError::Overflow { multiplier }`
6714 // discriminant so this arm reconstructs the pre-lift
6715 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
6716 // wording verbatim from `num` / `unit_trim` / the returned
6717 // `multiplier`, and the unknown-unit arm reconstructs the
6718 // pre-lift `"unknown duration unit \"<other>\""` wording from
6719 // the caller-scoped `unit_trim`. Load-bearing pinned by
6720 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
6721 let unit_trim = unit.trim();
6722 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
6723 |e| match e {
6724 crate::render::DurationUnitError::Overflow { multiplier } => format!(
6725 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
6726 ),
6727 crate::render::DurationUnitError::UnknownUnit => {
6728 format!("unknown duration unit {unit_trim:?}")
6729 }
6730 },
6731 )?;
6732 Ok(dur)
6733 }
6734
6735 /// Render a [`Duration`] in the canonical pleme-io duration string
6736 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
6737 /// caixa typed-duration slot serializes to and the same form K8s
6738 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
6739 /// EnvoyConfig per-route timeouts both expect (an integer
6740 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
6741 /// `+`). Lifted to `pub` so caixa-side renderers
6742 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
6743 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
6744 /// emitter, the future caixa-otel collector pipeline emitter) can
6745 /// consume the same canonical formatter without re-inlining the
6746 /// magnitude/unit decision tree (and inheriting the same drift
6747 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
6748 /// downstream apply-time parsing in non-obvious ways).
6749 pub fn render(d: Duration) -> String {
6750 let total_ms = d.as_millis();
6751 if total_ms == 0 {
6752 return "0s".into();
6753 }
6754 if total_ms.is_multiple_of(3600 * 1000) {
6755 return format!("{}h", total_ms / (3600 * 1000));
6756 }
6757 if total_ms.is_multiple_of(60 * 1000) {
6758 return format!("{}m", total_ms / (60 * 1000));
6759 }
6760 if total_ms.is_multiple_of(1000) {
6761 return format!("{}s", total_ms / 1000);
6762 }
6763 format!("{total_ms}ms")
6764 }
6765
6766 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
6767 ///
6768 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
6769 /// largest divisor unit, so any sub-millisecond residue
6770 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
6771 /// §V.2.7 render-determinism contract:
6772 ///
6773 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
6774 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
6775 /// `1_000_000` ns ≠ original `1_500_000` ns;
6776 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
6777 /// renders the literal `"0s"`, which the per-axis zero-floor gate
6778 /// on every typed-`Duration` slot then rejects on re-validate.
6779 ///
6780 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
6781 /// the codec's round-trippable accepted set lives in exactly one place —
6782 /// every typed-`Duration` slot that routes through this shared codec
6783 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
6784 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
6785 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
6786 /// every typed-`Duration` slot whose own codec shares the same
6787 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
6788 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
6789 /// pair) calls this predicate from its `validate()` to bracket the
6790 /// accepted set against the codec's accepted set, structurally. Drift
6791 /// between the codec's granularity and any typed slot's accepted set is
6792 /// then a single-source-of-truth edit at this predicate rather than a
6793 /// silent round-trip break the next consumer discovers at apply time.
6794 ///
6795 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
6796 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
6797 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
6798 /// family — same "typed-slot's valid set matches its codec's accepted
6799 /// set, structurally" discipline carried at the codec layer.
6800 #[must_use]
6801 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
6802 d.subsec_nanos().is_multiple_of(1_000_000)
6803 }
6804}
6805
6806/// Required-Duration variant for fields that aren't Option<Duration>.
6807pub mod duration_codec_required {
6808 use super::Duration;
6809 use serde::{Deserialize, Deserializer, Serializer};
6810
6811 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
6812 s.serialize_str(&super::duration_codec::render(*v))
6813 }
6814
6815 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
6816 let s = String::deserialize(d)?;
6817 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
6818 }
6819}
6820
6821#[cfg(test)]
6822mod tests {
6823 use super::*;
6824
6825 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
6826 ChildSpec {
6827 caixa: name.into(),
6828 versao: ver.into(),
6829 restart,
6830 }
6831 }
6832
6833 #[test]
6834 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
6835 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
6836 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
6837 // posture. Each accessor projects the per-`:children :caixa`
6838 // / per-`:children :versao` [`String`] storage through the
6839 // `pub const fn` [`String::as_str`] (const-stable since Rust
6840 // 1.87, well within the workspace MSRV) — any future
6841 // accidental downgrade to non-`const` fails the corresponding
6842 // `<name>_via_const_fn` wrapper at caixa-core build time with
6843 // E0015 (`cannot call non-const method`), strictly stronger
6844 // than a runtime `assert!`. Sibling of the peer
6845 // per-M2/M3/universal-axis `String → &str` scalar-accessor
6846 // family pins on the sibling `const`-eval-surface passes
6847 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
6848 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
6849 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
6850 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
6851 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
6852 // [`crate::aplicacao::Entrada::destination`] at the M3
6853 // ingress axis,
6854 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
6855 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
6856 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
6857 // axis, and the per-`:contratos`
6858 // [`crate::aplicacao::WitContract::source`] /
6859 // [`crate::aplicacao::WitContract::destination`] /
6860 // [`crate::aplicacao::WitContract::world_ref`] trio the
6861 // sibling pin at 279823b already anchors).
6862 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
6863 c.nome()
6864 }
6865 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
6866 c.versao_requirement()
6867 }
6868 for (caixa, versao) in [
6869 ("worker-a", "^0.1"),
6870 ("worker-b", "~0.2.3"),
6871 ("collector", "*"),
6872 ] {
6873 let c = child(caixa, versao, RestartPolicy::Permanent);
6874 assert_eq!(nome_via_const_fn(&c), c.nome());
6875 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
6876 assert_eq!(c.nome(), caixa);
6877 assert_eq!(c.versao_requirement(), versao);
6878 }
6879 }
6880
6881 #[test]
6882 fn supervisor_children_slice_return_accessor_is_const_fn() {
6883 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
6884 // `const`-eval-surface posture. The accessor destructures the
6885 // per-`:children` `Vec<ChildSpec>` storage through the
6886 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
6887 // 1.66, well within the workspace MSRV) — any future
6888 // accidental downgrade to non-`const` fails
6889 // `children_via_const_fn` at caixa-core build time with E0015
6890 // (`cannot call non-const method`), strictly stronger than a
6891 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
6892 // `Vec → &[T]` slice-return accessor family pin
6893 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
6894 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
6895 // per-`:membros` / per-`:contratos` slice-return axes, and of
6896 // the peer M2 upgrade-appup axis pin
6897 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
6898 // on the per-`:upgrade-from :instructions` slice-return axis.
6899 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
6900 s.children()
6901 }
6902 // Sweep both the empty-children (leaf-supervisor with no
6903 // static children — the `SimpleOneForOne` dynamic-child
6904 // arm's canonical shape) and the populated-children
6905 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
6906 // arm's canonical shape) axes so the accessor carries a
6907 // const-dispatch pin on both arms.
6908 let s_empty = SupervisorSpec {
6909 estrategia: RestartStrategy::SimpleOneForOne,
6910 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
6911 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6912 children: vec![],
6913 };
6914 assert!(children_via_const_fn(&s_empty).is_empty());
6915 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
6916 let s_full = SupervisorSpec {
6917 estrategia: RestartStrategy::OneForOne,
6918 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
6919 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6920 children: vec![
6921 child("worker-a", "^0.1", RestartPolicy::Permanent),
6922 child("worker-b", "~0.2.3", RestartPolicy::Transient),
6923 child("collector", "*", RestartPolicy::Temporary),
6924 ],
6925 };
6926 assert_eq!(children_via_const_fn(&s_full).len(), 3);
6927 assert_eq!(children_via_const_fn(&s_full), s_full.children());
6928 }
6929
6930 #[test]
6931 fn default_has_one_for_one_and_5_restarts_in_60s() {
6932 let s = SupervisorSpec::default();
6933 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
6934 assert_eq!(s.max_restarts, 5);
6935 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
6936 assert!(s.children.is_empty());
6937 }
6938
6939 #[test]
6940 fn validate_one_for_one_requires_children() {
6941 // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
6942 // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
6943 // struct-update to name the axis under test at construction, and this shape matches
6944 // it. Also keeps the "empty children is the axis under test" intent visible at the
6945 // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
6946 let mut s = SupervisorSpec {
6947 children: vec![],
6948 ..SupervisorSpec::default()
6949 };
6950 assert!(matches!(
6951 s.validate().unwrap_err(),
6952 SupervisorError::NoChildren { .. }
6953 ));
6954 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
6955 s.validate().unwrap();
6956 }
6957
6958 #[test]
6959 fn validate_simple_one_for_one_forbids_static_children() {
6960 let mut s = SupervisorSpec {
6961 estrategia: RestartStrategy::SimpleOneForOne,
6962 ..SupervisorSpec::default()
6963 };
6964 s.children
6965 .push(child("w", "^0.1", RestartPolicy::Permanent));
6966 assert_eq!(
6967 s.validate().unwrap_err(),
6968 SupervisorError::SimpleOneForOneWithStaticChildren
6969 );
6970 s.children.clear();
6971 s.validate().unwrap();
6972 }
6973
6974 #[test]
6975 fn validate_rejects_zero_max_restarts() {
6976 let s = SupervisorSpec {
6977 max_restarts: 0,
6978 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6979 ..SupervisorSpec::default()
6980 };
6981 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6982 }
6983
6984 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
6985 //
6986 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
6987 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
6988 // `:supervisor :max-restarts` axis — both fields are "trip the
6989 // next-higher protection layer after N events in a rolling window"
6990 // counters with identical degenerate-at-the-high-end shape, so the
6991 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
6992 // exactly as it lies in `1..=1000` on the breaker side.
6993
6994 #[test]
6995 fn validate_rejects_max_restarts_above_cap() {
6996 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
6997 // 1` is structurally one past the cap and silently passed
6998 // validate on every pre-gate codebase because the typed slot's
6999 // only check was the zero-floor arm. The no-op-supervisor vector
7000 // only surfaced at the runtime substrate (Erlang/OTP
7001 // MaxIntensity/Period ratio, the future wasm-operator's
7002 // per-supervisor restart-intensity counter) far from the source
7003 // caixa.lisp with no field naming the offending supervisor.
7004 let s = SupervisorSpec {
7005 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7006 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7007 ..SupervisorSpec::default()
7008 };
7009 assert_eq!(
7010 s.validate().unwrap_err(),
7011 SupervisorError::MaxRestartsExceedsCap {
7012 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7013 }
7014 );
7015 }
7016
7017 #[test]
7018 fn validate_rejects_max_restarts_far_above_cap() {
7019 // The `u32::MAX` worst case — the four-billion-restart
7020 // threshold a typo (`:max-restarts 4294967295`) or a
7021 // struct-literal copy-paste lands in the slot. Pin the cap
7022 // arm's coverage explicitly across the full `u32` overflow so
7023 // a future relaxation that drops the upper bound surfaces
7024 // here. Same shape every other typed-cap arm on this surface
7025 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
7026 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
7027 let s = SupervisorSpec {
7028 max_restarts: u32::MAX,
7029 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7030 ..SupervisorSpec::default()
7031 };
7032 assert_eq!(
7033 s.validate().unwrap_err(),
7034 SupervisorError::MaxRestartsExceedsCap {
7035 max_restarts: u32::MAX,
7036 }
7037 );
7038 }
7039
7040 #[test]
7041 fn validate_accepts_max_restarts_at_cap() {
7042 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
7043 // must validate. The cap is inclusive on the top edge,
7044 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
7045 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
7046 // discipline on the sibling capped axes. Pin the boundary
7047 // explicitly so a future off-by-one tightening
7048 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
7049 // here as a test failure rather than a silent contract
7050 // narrowing.
7051 let s = SupervisorSpec {
7052 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
7053 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7054 ..SupervisorSpec::default()
7055 };
7056 s.validate()
7057 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
7058 }
7059
7060 #[test]
7061 fn validate_accepts_max_restarts_typical_values() {
7062 // The documented production-playbook band positive-control
7063 // sweep — every value Erlang/OTP / Elixir / Riak Core /
7064 // RabbitMQ recommend (1..=100) must pass, plus a sweep
7065 // through the hyperscale band (200, 500, 1000) the cap
7066 // accepts. Pin the inclusive validated set explicitly so a
7067 // future tightening of the ceiling surfaces here.
7068 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
7069 let s = SupervisorSpec {
7070 max_restarts: n,
7071 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7072 ..SupervisorSpec::default()
7073 };
7074 s.validate()
7075 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
7076 }
7077 }
7078
7079 #[test]
7080 fn zero_max_restarts_takes_precedence_over_cap() {
7081 // The cross-arm ordering pin: `0` is structurally outside
7082 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
7083 // (cap), but the zero-floor diagnostic is the more
7084 // self-locating one (it directly names the counter-axis
7085 // remediation), so the validate gate must fire on zero first.
7086 // Same shape every other zero-then-shape ordering on this
7087 // surface uses (PolicyRetriesZero then
7088 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
7089 // PolicyBreakerMaxFailuresExceedsCap).
7090 let s = SupervisorSpec {
7091 max_restarts: 0,
7092 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7093 ..SupervisorSpec::default()
7094 };
7095 assert_eq!(
7096 s.validate().unwrap_err(),
7097 SupervisorError::ZeroMaxRestarts,
7098 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
7099 );
7100 }
7101
7102 #[test]
7103 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
7104 // The cross-arm ordering pin between the cap and the sibling
7105 // `:restart-window` gates (zero-window, canonical-window). A
7106 // supervisor carrying both an over-cap `max_restarts` AND a
7107 // structurally invalid window (zero, sub-ms) must surface the
7108 // cap diagnostic first — the cap arm is wired immediately
7109 // after the zero-restart arm and strictly before the window
7110 // arms, so the offending value the diagnostic names matches
7111 // the order the author would discover the gates by reading
7112 // top-to-bottom through `SupervisorSpec::validate`. Pin the
7113 // order so a future refactor that reorders the arms surfaces
7114 // here as a test failure rather than a silent diagnostic
7115 // regression. Peer of
7116 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
7117 // on the sibling `:politicas :circuit-breaker` slot.
7118 let s = SupervisorSpec {
7119 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7120 restart_window: Some(Duration::ZERO),
7121 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7122 ..SupervisorSpec::default()
7123 };
7124 assert_eq!(
7125 s.validate().unwrap_err(),
7126 SupervisorError::MaxRestartsExceedsCap {
7127 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7128 },
7129 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
7130 );
7131 }
7132
7133 #[test]
7134 fn max_restarts_cap_diagnostic_carries_offending_value() {
7135 // The diagnostic-shape pin: the offending `u32` is carried
7136 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
7137 // variant so the surfaced error message names the value the
7138 // author wrote (`":supervisor :max-restarts (50000) exceeds the
7139 // supervisor-policy ceiling …"`), not just the cap. Same
7140 // self-locating diagnostic shape every other typed-cap arm on
7141 // this surface carries
7142 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
7143 // the offending failure count verbatim,
7144 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
7145 // retries count verbatim).
7146 let s = SupervisorSpec {
7147 max_restarts: 50_000,
7148 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7149 ..SupervisorSpec::default()
7150 };
7151 let err = s.validate().unwrap_err();
7152 assert!(
7153 matches!(
7154 err,
7155 SupervisorError::MaxRestartsExceedsCap {
7156 max_restarts: 50_000
7157 }
7158 ),
7159 "got {err:?}"
7160 );
7161 let msg = err.to_string();
7162 assert!(
7163 msg.contains("50000"),
7164 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
7165 );
7166 }
7167
7168 #[test]
7169 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
7170 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
7171 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
7172 // half of Learn You Some Erlang's worker-supervisor default,
7173 // sibling of the `60s` `Period` half that the paired
7174 // [`Default for SupervisorSpec`] impl already pins on the
7175 // sibling `restart_window` axis. Pinning the literal here
7176 // surfaces a future rebrand (a tightening to Elixir's `3`,
7177 // a widening to a per-cluster overlay the operator pins
7178 // through a future `:max-restarts-overrides` slot) as a
7179 // deliberate test edit, not a silent contract migration.
7180 // Peer of the sibling
7181 // [`supervisor_max_restarts_cap_pins_canonical_value`]
7182 // upper-bracket pin on the same axis.
7183 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
7184 }
7185
7186 #[test]
7187 fn default_max_restarts_helper_routes_through_lifted_default() {
7188 // Composition pin: the private `default_max_restarts()`
7189 // serde-`#[serde(default = "…")]` helper on
7190 // [`SupervisorSpec::max_restarts`] must route through the
7191 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
7192 // typed `pub const` rather than a raw `5` literal. Prior to
7193 // the lift the helper carried an inline `5` with no compile-
7194 // time link back to the shared default, so the wire-format
7195 // author-omitted arm and the caixa-core
7196 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
7197 // arm could silently split on any future default rebrand.
7198 // Byte-parity against the lifted constant closes the split.
7199 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
7200 }
7201
7202 #[test]
7203 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
7204 // Composition pin: the [`Default for SupervisorSpec`] impl's
7205 // struct-literal `max_restarts` field must route through the
7206 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
7207 // typed `pub const` (via the private helper this test's
7208 // sibling `default_max_restarts_helper_routes_through_lifted_default`
7209 // already pins onto the constant). Structurally: every
7210 // `SupervisorSpec::default()` call must yield a
7211 // `max_restarts` field byte-equal to the lifted constant
7212 // (the two paired defaults — the serde-side wire-format arm
7213 // and the struct-literal default arm — cannot silently split
7214 // on any future default rebrand). Peer of the sibling
7215 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
7216 // — this pin closes the byte-parity arm on the two paired
7217 // altitude entry points onto the shared substrate constant.
7218 assert_eq!(
7219 SupervisorSpec::default().max_restarts(),
7220 SUPERVISOR_MAX_RESTARTS_DEFAULT,
7221 );
7222 }
7223
7224 #[test]
7225 fn supervisor_restart_window_default_pins_otp_canonical_value() {
7226 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
7227 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
7228 // Learn You Some Erlang's worker-supervisor default, paired
7229 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
7230 // `MaxIntensity` half this constant is the sliding-window
7231 // denominator of on the same `MaxIntensity / Period`
7232 // restart-intensity ratio. Pinning the literal here surfaces a
7233 // future coherent rebrand of the paired default (Elixir's
7234 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
7235 // the operator pins through a future
7236 // `:restart-window-overrides` slot) as a deliberate test edit,
7237 // not a silent contract migration. Peer of the sibling
7238 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
7239 // paired-half pin on the same OTP-canonical default and the
7240 // [`supervisor_restart_window_cap_pins_canonical_value`]
7241 // upper-bracket pin on the same axis.
7242 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
7243 }
7244
7245 #[test]
7246 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
7247 // Composition pin: the [`Default for SupervisorSpec`] impl's
7248 // struct-literal `restart_window` field must route through the
7249 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
7250 // typed `pub const` rather than a raw
7251 // `Duration::from_secs(60)` literal. Prior to this lift the
7252 // paired `{intensity, 5, 60}` OTP-canonical default was split
7253 // across two altitudes with no compile-time link between the
7254 // halves — the `MaxIntensity` half rode through the lifted
7255 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
7256 // `Period` half rode as an open-coded literal at the
7257 // composition site, so a future coherent rebrand of the paired
7258 // canonical would have had to migrate one half through the
7259 // constant and the other through a raw literal in lockstep.
7260 // Byte-parity against the lifted constant on the `Period` half
7261 // closes the split — the paired OTP-canonical default now
7262 // migrates as one unit on any future axis change. Peer of the
7263 // sibling
7264 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
7265 // byte-parity pin on the paired `MaxIntensity` half.
7266 assert_eq!(
7267 SupervisorSpec::default().restart_window(),
7268 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
7269 );
7270 }
7271
7272 #[test]
7273 fn supervisor_estrategia_default_pins_otp_canonical_value() {
7274 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
7275 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
7276 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
7277 // canonical default, paired with the sibling
7278 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
7279 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
7280 // this constant is the strategy discriminator of on the same
7281 // OTP-canonical worker-supervisor default. Pinning the arm here
7282 // surfaces a future coherent rebrand of the paired triple (Elixir's
7283 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
7284 // intensity/period axes leaving this strategy arm untouched, an OTP
7285 // `rest_for_one` widening once the substrate discovers startup-
7286 // order-coupled child cohorts as the more common worker-supervisor
7287 // shape, a per-cluster overlay the operator pins through a future
7288 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
7289 // supervision-canary roadmap acknowledges) as a deliberate test
7290 // edit, not a silent contract migration. Peer of the sibling
7291 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
7292 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
7293 // paired-half pins on the same OTP-canonical default.
7294 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
7295 }
7296
7297 #[test]
7298 fn restart_strategy_default_routes_through_lifted_default() {
7299 // Composition pin: the [`Default for RestartStrategy`] impl's
7300 // return arm must route through the substrate-canonical
7301 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
7302 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
7303 // an inline `Self::OneForOne` with no compile-time link back to
7304 // the shared OTP-canonical `one_for_one` strategy the paired
7305 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
7306 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
7307 // `.unwrap_or_default()` (now
7308 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
7309 // so a future rebrand of the OTP-canonical strategy default (an
7310 // OTP `rest_for_one` widening once the substrate discovers
7311 // startup-order-coupled child cohorts as the more common worker-
7312 // supervisor shape, a per-cluster overlay the operator pins
7313 // through a future `:estrategia-overrides` slot) would have had to
7314 // be threaded through the `Default` impl and the two peer routes
7315 // in lockstep or the three consumers would silently split. Byte-
7316 // parity against the lifted constant closes the split. Peer of
7317 // the sibling
7318 // [`default_max_restarts_helper_routes_through_lifted_default`] +
7319 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
7320 // composition pins on the paired `MaxIntensity` + `Period` halves.
7321 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
7322 }
7323
7324 #[test]
7325 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
7326 // Composition pin: the [`Default for SupervisorSpec`] impl's
7327 // struct-literal `estrategia` field must route through the
7328 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
7329 // `pub const` (either directly, or via the
7330 // [`RestartStrategy::default`] impl that the sibling
7331 // `restart_strategy_default_routes_through_lifted_default` pin
7332 // already routes onto the constant). Structurally: every
7333 // `SupervisorSpec::default()` call must yield an `estrategia`
7334 // field byte-equal to the lifted constant (the three paired
7335 // defaults — the [`Default for RestartStrategy`] impl arm, the
7336 // struct-literal default arm here, and the
7337 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
7338 // silently split on any future default rebrand). Peer of the
7339 // sibling
7340 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
7341 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
7342 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
7343 // of the same `SupervisorSpec::default()` composed altitude.
7344 assert_eq!(
7345 SupervisorSpec::default().estrategia(),
7346 SUPERVISOR_ESTRATEGIA_DEFAULT,
7347 );
7348 }
7349
7350 #[test]
7351 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
7352 // Composition pin: the [`Default for SupervisorSpec`] impl must
7353 // route through the substrate-canonical
7354 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
7355 // rather than a re-hand-authored struct-literal cascade. Sharpens
7356 // the sibling per-arm
7357 // `supervisor_spec_default_*_routes_through_lifted_default` pins
7358 // from a per-field lift into a whole-struct one-source-of-truth
7359 // pin — the derived-until-now [`Default::default`] and the
7360 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
7361 // construction, not by coincidence.
7362 //
7363 // A future extension of the OTP-canonical baseline (a fifth
7364 // `restart_intensity` field the Erlang/OTP `#supervisor` record
7365 // grows, a per-child-cohort split of the `restart_window` /
7366 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
7367 // CR materializer's admission-time overlay pass) reaches both
7368 // paths through exactly one edit on
7369 // [`SupervisorSpec::otp_canonical`] — the derived path could
7370 // silently disagree with the constructor's shape on any new
7371 // field whose [`Default::default`] resolves to a different arm
7372 // than the OTP-canonical baseline the constructor names, while
7373 // this delegated impl reaches the constructor directly and
7374 // picks up every future extension by construction.
7375 //
7376 // Fourth peer on the M2 / M3 typed-slot-spec
7377 // [`Default`]-through-const-ctor fold family — sibling of the
7378 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
7379 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
7380 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
7381 // (91641a4), and [`crate::BehaviorSpec`]
7382 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
7383 // per-`Option`-only-typed-slot folds — extended here onto the
7384 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
7385 // is not "everything `None`" but the Erlang/OTP-canonical
7386 // `{one_for_one, 5, 60}` worker-supervisor triple.
7387 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
7388 }
7389
7390 #[test]
7391 fn supervisor_spec_otp_canonical_byte_equals_default() {
7392 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
7393 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
7394 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
7395 // pin already asserts against the [`Default::default`] path.
7396 // Sharpens the pair-invariant into a per-constructor pin so a
7397 // future extension of [`SupervisorSpec`] with a fifth field
7398 // whose OTP-canonical shape is non-`Default::default`-equivalent
7399 // trips at caixa-core test time rather than at a downstream
7400 // consumer that composed [`SupervisorSpec::otp_canonical`] with
7401 // [`SupervisorSpec::validate`] as its "canonical baseline
7402 // seed".
7403 let canonical = SupervisorSpec::otp_canonical();
7404 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
7405 assert_eq!(canonical.max_restarts, 5);
7406 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
7407 assert!(canonical.children.is_empty());
7408 }
7409
7410 #[test]
7411 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
7412 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
7413 // remain callable from a `const`-bound position so downstream
7414 // `const`-context callers wanting a canonical OTP-baseline seed
7415 // can construct one at compile time without runtime dispatch on
7416 // the derived [`Default::default`]. Peer of the sibling
7417 // `pub const fn` [`crate::LimitsSpec::empty`] /
7418 // [`crate::aplicacao::MeshPolicy::empty`] /
7419 // [`crate::BehaviorSpec::empty`] constructors on the sibling
7420 // typed-slot-spec `pub const fn` axis. If a future edit breaks
7421 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
7422 // (a non-`const` field-default helper, a non-`const`-stable
7423 // container type promotion), this evaluation fails at
7424 // build time on this file rather than at a downstream
7425 // `const`-context call site.
7426 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
7427 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
7428 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
7429 assert_eq!(
7430 CANONICAL.restart_window,
7431 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
7432 );
7433 assert!(CANONICAL.children.is_empty());
7434 }
7435
7436 #[test]
7437 fn supervisor_child_restart_default_pins_otp_canonical_value() {
7438 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
7439 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
7440 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
7441 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
7442 // half of the same OTP-shape supervisor-tree default set whose
7443 // per-`:supervisor` halves the sibling
7444 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
7445 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
7446 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
7447 // arm here surfaces a future rebrand of the per-child default (an
7448 // OTP-`transient` widening once the substrate discovers clean-
7449 // completion-aware children as the more common child shape, a
7450 // per-cluster overlay the operator pins through a future
7451 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
7452 // supervision-canary roadmap acknowledges) as a deliberate test
7453 // edit, not a silent contract migration. Peer of the sibling
7454 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
7455 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
7456 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
7457 // value pins on the per-`:supervisor` halves.
7458 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
7459 }
7460
7461 #[test]
7462 fn restart_policy_default_routes_through_lifted_default() {
7463 // Composition pin: the [`Default for RestartPolicy`] impl's return
7464 // arm must route through the substrate-canonical
7465 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
7466 // than a raw `Self::Permanent` arm. Prior to the lift the impl
7467 // carried an inline `Self::Permanent` with no compile-time link
7468 // back to the OTP-shape supervisor-tree default set whose three
7469 // per-`:supervisor` halves already rode through lifted constants
7470 // — so a future coherent rebrand of the set would have had to
7471 // migrate three halves through typed constants and this fourth
7472 // through a raw enum arm in lockstep or the supervisor-level and
7473 // child-level defaults would silently drift apart. Byte-parity
7474 // against the lifted constant closes the split. Peer of the
7475 // sibling
7476 // [`restart_strategy_default_routes_through_lifted_default`]
7477 // composition pin on the per-`:supervisor` `:estrategia` axis.
7478 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
7479 }
7480
7481 #[test]
7482 fn child_spec_serde_default_restart_routes_through_lifted_default() {
7483 // Composition pin: the serde-side `#[serde(default)]` on
7484 // [`ChildSpec::restart`] — the wire-format author-omitted
7485 // `:children :restart` arm — must resolve onto the substrate-
7486 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
7487 // (via the [`Default for RestartPolicy`] impl the sibling
7488 // `restart_policy_default_routes_through_lifted_default` pin
7489 // already routes onto the constant). Structurally: a `ChildSpec`
7490 // deserialized from a payload that omits the `restart` key must
7491 // yield a `restart` field byte-equal to the lifted constant, so
7492 // the wire-format author-omitted arm and the
7493 // [`RestartPolicy::default`] impl arm cannot silently split on any
7494 // future default rebrand. Peer of the sibling
7495 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
7496 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
7497 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
7498 // byte-parity pins on the per-`:supervisor` halves of the same
7499 // author-omitted-slot resolution surface.
7500 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
7501 .expect("ChildSpec must deserialize with the restart key omitted");
7502 assert_eq!(
7503 omitted.restart(),
7504 SUPERVISOR_CHILD_RESTART_DEFAULT,
7505 "an author-omitted :children :restart slot must degrade onto \
7506 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
7507 {:?}, expected {:?})",
7508 omitted.restart(),
7509 SUPERVISOR_CHILD_RESTART_DEFAULT,
7510 );
7511 }
7512
7513 #[test]
7514 fn supervisor_max_restarts_cap_pins_canonical_value() {
7515 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
7516 // 1000 — the same ceiling the peer
7517 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
7518 // `:politicas :circuit-breaker :max-failures` axis (both are
7519 // "trip the next-higher protection layer after N events in a
7520 // rolling window" counters with identical
7521 // degenerate-at-the-high-end shape; uniform top edge so the
7522 // M4 CR materializers and the wasm-operator reconciler reach
7523 // for either field knowing the value is in `1..=1000`). Two
7524 // orders of magnitude above every documented Erlang/OTP /
7525 // Elixir / Riak Core / RabbitMQ production-playbook
7526 // recommendation band and below the clearly-pathological
7527 // "effectively no escalation" floor (10_000, 100_000,
7528 // u32::MAX). Pinning the literal value here surfaces a future
7529 // drift (a relaxation to 10_000, a tightening to 100) as a
7530 // deliberate test edit, not a silent contract narrowing.
7531 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
7532 }
7533
7534 #[test]
7535 fn validate_rejects_empty_child_name() {
7536 let s = SupervisorSpec {
7537 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
7538 ..SupervisorSpec::default()
7539 };
7540 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
7541 }
7542
7543 #[test]
7544 fn validate_rejects_empty_child_version() {
7545 let s = SupervisorSpec {
7546 children: vec![child("w", "", RestartPolicy::Permanent)],
7547 ..SupervisorSpec::default()
7548 };
7549 assert!(matches!(
7550 s.validate().unwrap_err(),
7551 SupervisorError::EmptyChildVersion { .. }
7552 ));
7553 }
7554
7555 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
7556
7557 #[test]
7558 fn validate_rejects_invalid_child_versao_requirement() {
7559 // The fail-before-pass-after pin: a non-empty but malformed
7560 // semver requirement (`"^bad-version"`) silently passed
7561 // `validate()` on every pre-gate codebase because the prior
7562 // shape only refused the empty string. The parse failure
7563 // surfaced far downstream at lacre-resolve time with a
7564 // `semver::Error` that didn't name which `:children` entry
7565 // carried the typo. The new gate moves the check to caixa-build
7566 // time at the source caixa.lisp — the third `:versao` typed
7567 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
7568 // structural parity.
7569 let s = SupervisorSpec {
7570 children: vec![
7571 child("worker", "^0.1", RestartPolicy::Permanent),
7572 child("cache", "^bad-version", RestartPolicy::Transient),
7573 ],
7574 ..SupervisorSpec::default()
7575 };
7576 let err = s.validate().unwrap_err();
7577 assert!(
7578 matches!(
7579 err,
7580 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
7581 if caixa == "cache" && versao == "^bad-version"
7582 ),
7583 "got {err:?}"
7584 );
7585 }
7586
7587 #[test]
7588 fn validate_rejects_child_versao_with_double_caret_typo() {
7589 // `"^^0.1"` is the canonical doubled-caret typo — looks
7590 // Cargo-shaped on first glance but fails the parser because
7591 // semver doesn't accept stacked operators. Pin this
7592 // adjacent-shape footgun explicitly so a future relaxation that
7593 // accepts "looks-canonical-but-isn't" forms surfaces here.
7594 let s = SupervisorSpec {
7595 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
7596 ..SupervisorSpec::default()
7597 };
7598 let err = s.validate().unwrap_err();
7599 assert!(
7600 matches!(
7601 err,
7602 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
7603 if caixa == "worker" && versao == "^^0.1"
7604 ),
7605 "got {err:?}"
7606 );
7607 }
7608
7609 #[test]
7610 fn validate_rejects_child_versao_with_v_prefixed_tag() {
7611 // `"v0.1"` is the canonical "git-tag-shape leaking into the
7612 // semver requirement slot" typo — an author copies the
7613 // publish-side git-tag string verbatim into `:versao`, but
7614 // Cargo's semver parser rejects the leading `v`. Same
7615 // adjacent-shape footgun pinned for `:membros :versao`
7616 // (9888b13).
7617 let s = SupervisorSpec {
7618 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
7619 ..SupervisorSpec::default()
7620 };
7621 let err = s.validate().unwrap_err();
7622 assert!(
7623 matches!(
7624 err,
7625 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
7626 if caixa == "worker" && versao == "v0.1"
7627 ),
7628 "got {err:?}"
7629 );
7630 }
7631
7632 #[test]
7633 fn validate_accepts_canonical_child_versao_forms() {
7634 // The Cargo-shaped requirement forms `:deps :versao` and
7635 // `:membros :versao` already accept via
7636 // `crate::parse_requirement` must pass the children gate
7637 // without re-validating at the resolver layer. Pin every leg so
7638 // a future tightening of the canonical set surfaces here as a
7639 // test failure.
7640 for form in [
7641 "^0.1", // caret — minor-range pin (the most common shape)
7642 "~0.1.2", // tilde — patch-range pin
7643 "0.1.0", // exact — single-version pin
7644 "*", // wildcard — any version (semver::VersionReq::STAR)
7645 ">=0.1, <2", // multi-range — comma-separated comparators
7646 ] {
7647 let s = SupervisorSpec {
7648 children: vec![child("worker", form, RestartPolicy::Permanent)],
7649 ..SupervisorSpec::default()
7650 };
7651 s.validate()
7652 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7653 }
7654 }
7655
7656 #[test]
7657 fn child_versao_empty_takes_precedence_over_invalid() {
7658 // Order pin: the existing `EmptyChildVersion` diagnostic (which
7659 // doesn't try to parse) fires before the new
7660 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
7661 // `:versao` keeps its narrower error message —
7662 // `parse_requirement` would also reject `""`, but the
7663 // empty-string arm is the more self-locating diagnostic for the
7664 // author. Same ordering discipline as
7665 // `membro_versao_empty_takes_precedence_over_invalid` in
7666 // aplicacao.rs.
7667 let s = SupervisorSpec {
7668 children: vec![child("worker", "", RestartPolicy::Permanent)],
7669 ..SupervisorSpec::default()
7670 };
7671 let err = s.validate().unwrap_err();
7672 assert!(
7673 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
7674 "got {err:?}"
7675 );
7676 }
7677
7678 #[test]
7679 fn child_versao_invalid_fires_before_duplicate_check() {
7680 // Order pin: a malformed requirement on a non-duplicate entry
7681 // surfaces *its own* diagnostic (which names the offending
7682 // `:versao` string), even when a later entry would otherwise
7683 // collapse onto an earlier name. The per-entry shape gate runs
7684 // inline before the duplicate-key insert — parallel to
7685 // `membro_versao_invalid_fires_before_duplicate_check` in
7686 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
7687 let s = SupervisorSpec {
7688 children: vec![
7689 child("worker", "^bad", RestartPolicy::Permanent),
7690 child("cache", "^0.1", RestartPolicy::Transient),
7691 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
7692 ],
7693 ..SupervisorSpec::default()
7694 };
7695 let err = s.validate().unwrap_err();
7696 assert!(
7697 matches!(
7698 err,
7699 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
7700 ),
7701 "got {err:?}"
7702 );
7703 }
7704
7705 #[test]
7706 fn child_versao_invalid_diagnostic_carries_offending_versao() {
7707 // The diagnostic-shape pin: the error names the offending
7708 // `:versao` value verbatim so the author can grep their
7709 // caixa.lisp without re-running the build, and carries a
7710 // non-empty `reason` from `semver::VersionReq::parse` so the
7711 // parser's own wording flows through to the diagnostic.
7712 let s = SupervisorSpec {
7713 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
7714 ..SupervisorSpec::default()
7715 };
7716 let err = s.validate().unwrap_err();
7717 let SupervisorError::ChildVersaoInvalid {
7718 caixa,
7719 versao,
7720 reason,
7721 } = err
7722 else {
7723 panic!("expected ChildVersaoInvalid, got other variant");
7724 };
7725 assert_eq!(caixa, "worker");
7726 assert_eq!(versao, "not-a-req");
7727 assert!(
7728 !reason.is_empty(),
7729 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
7730 );
7731 }
7732
7733 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
7734
7735 #[test]
7736 fn validate_rejects_child_caixa_with_uppercase() {
7737 // The canonical "I copied the Servico's display name verbatim"
7738 // typo — child caixa names are lowercase per K8s DNS-1123 label
7739 // rule. The diagnostic names the offending name and suggests the
7740 // lower-cased fix in one edit, mirroring the
7741 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
7742 let s = SupervisorSpec {
7743 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
7744 ..SupervisorSpec::default()
7745 };
7746 let err = s.validate().unwrap_err();
7747 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
7748 panic!("expected ChildCaixaInvalid, got other variant");
7749 };
7750 assert_eq!(caixa, "Worker");
7751 assert!(
7752 reason.contains("uppercase"),
7753 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7754 );
7755 assert!(
7756 reason.contains("\"worker\""),
7757 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7758 );
7759 }
7760
7761 #[test]
7762 fn validate_rejects_child_caixa_with_underscore() {
7763 // The canonical "I'm thinking of a Python module / Postgres
7764 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7765 // label schema. K8s rejects `metadata.name: my_worker` at
7766 // admission time with an opaque `field is invalid` (no source-
7767 // citing diagnostic). The gate moves it to caixa-build time.
7768 let s = SupervisorSpec {
7769 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
7770 ..SupervisorSpec::default()
7771 };
7772 let err = s.validate().unwrap_err();
7773 assert!(
7774 matches!(
7775 err,
7776 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
7777 if caixa == "my_worker" && reason.contains('_')
7778 ),
7779 "got {err:?}"
7780 );
7781 }
7782
7783 #[test]
7784 fn validate_rejects_child_caixa_with_dot() {
7785 // A `:children :caixa` entry is a single DNS-1123 label, not a
7786 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
7787 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
7788 // (3f9d7a0) on the peer name axis.
7789 let s = SupervisorSpec {
7790 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
7791 ..SupervisorSpec::default()
7792 };
7793 let err = s.validate().unwrap_err();
7794 assert!(
7795 matches!(
7796 err,
7797 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
7798 if caixa == "team.worker" && reason.contains('.')
7799 ),
7800 "got {err:?}"
7801 );
7802 }
7803
7804 #[test]
7805 fn validate_rejects_child_caixa_with_leading_hyphen() {
7806 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7807 // with an alphanumeric. The K8s apiserver rejects `-worker`
7808 // outright; the renderer would emit a `metadata.name: "-worker"`
7809 // that fails admission far from the source caixa.lisp.
7810 let s = SupervisorSpec {
7811 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
7812 ..SupervisorSpec::default()
7813 };
7814 let err = s.validate().unwrap_err();
7815 assert!(
7816 matches!(
7817 err,
7818 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
7819 if caixa == "-worker" && reason.contains("start and end")
7820 ),
7821 "got {err:?}"
7822 );
7823 }
7824
7825 #[test]
7826 fn validate_rejects_child_caixa_with_trailing_hyphen() {
7827 // The symmetric arm of the boundary rule. Pin separately so
7828 // both ends of the label are covered against a future relaxation
7829 // that only checks one boundary.
7830 let s = SupervisorSpec {
7831 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
7832 ..SupervisorSpec::default()
7833 };
7834 let err = s.validate().unwrap_err();
7835 assert!(
7836 matches!(
7837 err,
7838 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
7839 if caixa == "worker-"
7840 ),
7841 "got {err:?}"
7842 );
7843 }
7844
7845 #[test]
7846 fn validate_rejects_child_caixa_with_unicode() {
7847 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7848 // (`xn--…`) by the author before it reaches K8s. The byte-by-
7849 // byte ASCII validity check rejects multi-byte UTF-8 sequences
7850 // by the first byte that fails the `[a-z0-9-]` predicate.
7851 let s = SupervisorSpec {
7852 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
7853 ..SupervisorSpec::default()
7854 };
7855 let err = s.validate().unwrap_err();
7856 assert!(
7857 matches!(
7858 err,
7859 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
7860 if caixa == "café"
7861 ),
7862 "got {err:?}"
7863 );
7864 }
7865
7866 #[test]
7867 fn validate_rejects_child_caixa_with_whitespace() {
7868 // Whitespace is the canonical "I pasted from a sketch / doc"
7869 // footgun. The apiserver rejects every `metadata.name` value
7870 // carrying whitespace; pin the gate fires at the right boundary.
7871 let s = SupervisorSpec {
7872 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
7873 ..SupervisorSpec::default()
7874 };
7875 let err = s.validate().unwrap_err();
7876 assert!(
7877 matches!(
7878 err,
7879 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
7880 if caixa == "my worker"
7881 ),
7882 "got {err:?}"
7883 );
7884 }
7885
7886 #[test]
7887 fn validate_rejects_child_caixa_too_long() {
7888 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
7889 // 63 bytes; the K8s apiserver rejects every `metadata.name`
7890 // axis over the limit at admission time. The diagnostic names
7891 // both the cap and the actual length so the author can shorten
7892 // in one edit, mirroring `rejects_membro_caixa_too_long`
7893 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
7894 let too_long = "a".repeat(64);
7895 let s = SupervisorSpec {
7896 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
7897 ..SupervisorSpec::default()
7898 };
7899 let err = s.validate().unwrap_err();
7900 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
7901 panic!("expected ChildCaixaInvalid, got other variant");
7902 };
7903 assert_eq!(caixa, too_long);
7904 assert!(
7905 reason.contains("63"),
7906 "diagnostic must name the 63-byte cap (got: {reason:?})"
7907 );
7908 assert!(
7909 reason.contains("64"),
7910 "diagnostic must name the actual length (got: {reason:?})"
7911 );
7912 }
7913
7914 #[test]
7915 fn child_caixa_max_length_validates() {
7916 // The 63-byte boundary control pin — exactly-at-the-cap is
7917 // accepted, mirroring `membro_caixa_max_length_validates`
7918 // (3f9d7a0) and `placement_cluster_max_length_validates`
7919 // (6cbb900). Pinned separately so a future off-by-one tightening
7920 // surfaces here.
7921 let max_label = "a".repeat(63);
7922 let s = SupervisorSpec {
7923 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
7924 ..SupervisorSpec::default()
7925 };
7926 s.validate().unwrap();
7927 }
7928
7929 #[test]
7930 fn validate_accepts_canonical_child_caixa_forms() {
7931 // The realistic shapes a supervised child's `:caixa` carries —
7932 // single-word `worker`, version-suffixed `cache-v2`, single-char
7933 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
7934 // `payment-retry`, all-digit `0`. Pin every leg so a future
7935 // tightening (e.g. requiring a leading lowercase letter) surfaces
7936 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
7937 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
7938 // (6cbb900).
7939 for form in [
7940 "worker",
7941 "cache-v2",
7942 "a",
7943 "db",
7944 "2-pool",
7945 "payment-retry",
7946 "0",
7947 ] {
7948 let s = SupervisorSpec {
7949 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
7950 ..SupervisorSpec::default()
7951 };
7952 s.validate()
7953 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7954 }
7955 }
7956
7957 #[test]
7958 fn child_caixa_empty_takes_precedence_over_invalid() {
7959 // Order pin: the existing `EmptyChildName` diagnostic (which
7960 // doesn't try to parse the DNS-1123 shape) fires before the new
7961 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
7962 // its narrower error message — `is_dns_1123_label` would reject
7963 // the empty string too (boundary check on the first byte), but
7964 // the empty-string arm is the more self-locating diagnostic for
7965 // the author. Same ordering discipline as
7966 // `membro_caixa_empty_takes_precedence_over_invalid` in
7967 // aplicacao.rs.
7968 let s = SupervisorSpec {
7969 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
7970 ..SupervisorSpec::default()
7971 };
7972 let err = s.validate().unwrap_err();
7973 assert_eq!(err, SupervisorError::EmptyChildName);
7974 }
7975
7976 #[test]
7977 fn child_caixa_invalid_fires_before_versao_check() {
7978 // Order pin: the per-axis shape gate runs inline before the
7979 // per-entry versao check, so a malformed `:caixa` on an entry
7980 // whose `:versao` would also fail surfaces the more self-
7981 // locating name-axis diagnostic first. Parallel to
7982 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
7983 // and `placement_cluster_invalid_fires_before_duplicate_check`
7984 // (6cbb900).
7985 let s = SupervisorSpec {
7986 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
7987 ..SupervisorSpec::default()
7988 };
7989 let err = s.validate().unwrap_err();
7990 assert!(
7991 matches!(
7992 err,
7993 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
7994 ),
7995 "got {err:?}"
7996 );
7997 }
7998
7999 #[test]
8000 fn child_caixa_invalid_fires_before_duplicate_check() {
8001 // Order pin: a malformed name on a non-duplicate entry surfaces
8002 // its own diagnostic, even when a later entry would otherwise
8003 // collapse onto an earlier name. The per-entry shape gate runs
8004 // inline before the duplicate-key HashSet insert, mirroring
8005 // `placement_cluster_invalid_fires_before_duplicate_check`
8006 // (6cbb900).
8007 let s = SupervisorSpec {
8008 children: vec![
8009 child("Worker", "^0.1", RestartPolicy::Permanent),
8010 child("cache", "^0.1", RestartPolicy::Transient),
8011 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
8012 ],
8013 ..SupervisorSpec::default()
8014 };
8015 let err = s.validate().unwrap_err();
8016 assert!(
8017 matches!(
8018 err,
8019 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
8020 ),
8021 "got {err:?}"
8022 );
8023 }
8024
8025 #[test]
8026 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
8027 // The diagnostic-shape pin: the error names the offending
8028 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
8029 // the author can grep their caixa.lisp without re-running the
8030 // build. Mirrors the diagnostic-shape sweep on every prior
8031 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
8032 let s = SupervisorSpec {
8033 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
8034 ..SupervisorSpec::default()
8035 };
8036 let err = s.validate().unwrap_err();
8037 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
8038 panic!("expected ChildCaixaInvalid, got other variant");
8039 };
8040 assert_eq!(caixa, "My_Worker");
8041 assert!(
8042 !reason.is_empty(),
8043 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
8044 );
8045 }
8046
8047 // ── value-shape: zero restart_window + duplicate child names ──────────
8048
8049 #[test]
8050 fn validate_accepts_none_restart_window() {
8051 // Omitted `:restart-window` is the "never reset" sentinel —
8052 // valid by design. Mirrors :limits axes where None = unbounded.
8053 let s = SupervisorSpec {
8054 restart_window: None,
8055 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8056 ..SupervisorSpec::default()
8057 };
8058 s.validate().unwrap();
8059 }
8060
8061 #[test]
8062 fn validate_rejects_zero_restart_window() {
8063 // Same "0 means the opposite of what you think" footgun closed
8064 // for :politicas :timeout (Envoy treats 0s as infinite) and
8065 // :limits :wall-clock (wasmtime traps before the call starts).
8066 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
8067 let s = SupervisorSpec {
8068 restart_window: Some(Duration::ZERO),
8069 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8070 ..SupervisorSpec::default()
8071 };
8072 assert_eq!(
8073 s.validate().unwrap_err(),
8074 SupervisorError::RestartWindowZero
8075 );
8076 }
8077
8078 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
8079 //
8080 // The fourth (and last) typed-`Duration` axis in caixa-core to get
8081 // the integer-millisecond canonical-form gate — peer with
8082 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
8083 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
8084 // path is already gated at the shared codec layer (see
8085 // `restart_window_serde_rejects_fractional_seconds`); this arm
8086 // closes the programmatic-struct-literal path the codec gate can't
8087 // see.
8088
8089 #[test]
8090 fn validate_rejects_sub_millisecond_restart_window() {
8091 // The fail-before-pass-after pin: a programmatic
8092 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
8093 // `validate` on every pre-gate codebase, then truncated to
8094 // `as_millis() == 1` on first serialize — the shared codec
8095 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
8096 // 1_000_000 ns, the typed `restart_window` no longer matches
8097 // its rendered form.
8098 let s = SupervisorSpec {
8099 restart_window: Some(Duration::from_micros(1500)),
8100 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8101 ..SupervisorSpec::default()
8102 };
8103 match s.validate().unwrap_err() {
8104 SupervisorError::RestartWindowNotCanonical { window } => {
8105 assert_eq!(window, Duration::from_micros(1500));
8106 }
8107 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
8108 }
8109 }
8110
8111 #[test]
8112 fn validate_rejects_one_nanosecond_restart_window() {
8113 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
8114 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
8115 // so the shared codec emits the literal `"0s"` — the next
8116 // serde round-trip would parse back to `Duration::ZERO`, which
8117 // the `RestartWindowZero` arm then rejects on re-validate. The
8118 // canonical-form gate at this layer surfaces a self-locating
8119 // diagnostic naming the offending Duration verbatim rather
8120 // than a downstream `RestartWindowZero` whose remediation
8121 // points at omitting the slot.
8122 let s = SupervisorSpec {
8123 restart_window: Some(Duration::from_nanos(1)),
8124 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8125 ..SupervisorSpec::default()
8126 };
8127 match s.validate().unwrap_err() {
8128 SupervisorError::RestartWindowNotCanonical { window } => {
8129 assert_eq!(window, Duration::from_nanos(1));
8130 }
8131 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
8132 }
8133 }
8134
8135 #[test]
8136 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
8137 // The 1-ns-past-1ms boundary case: a `Duration` carrying
8138 // 1_000_001 ns is structurally past the integer-ms granularity
8139 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
8140 // trip would truncate to `1ms` and the consumer would observe
8141 // a 1-ns drift on every emit. Same boundary the peer
8142 // `validate_rejects_nanosecond_past_canonical_boundary` test
8143 // in limits.rs pins for the `:limits :wall-clock` axis.
8144 let w = Duration::from_nanos(1_000_001);
8145 let s = SupervisorSpec {
8146 restart_window: Some(w),
8147 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8148 ..SupervisorSpec::default()
8149 };
8150 assert_eq!(
8151 s.validate().unwrap_err(),
8152 SupervisorError::RestartWindowNotCanonical { window: w }
8153 );
8154 }
8155
8156 #[test]
8157 fn validate_accepts_integer_millisecond_restart_window_values() {
8158 // The positive-control sweep: every `Duration` the shared
8159 // codec can round-trip losslessly — the canonical
8160 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
8161 // pair emits and accepts — passes `validate` without
8162 // surfacing the new canonical-form arm. Mirrors
8163 // `validate_accepts_integer_millisecond_wall_clock_values` on
8164 // the sibling `:limits :wall-clock` axis.
8165 for w in [
8166 Duration::from_millis(1),
8167 Duration::from_millis(500),
8168 Duration::from_millis(1500),
8169 Duration::from_secs(1),
8170 Duration::from_secs(30),
8171 Duration::from_secs(60),
8172 Duration::from_secs(120),
8173 Duration::from_secs(3600),
8174 ] {
8175 let s = SupervisorSpec {
8176 restart_window: Some(w),
8177 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8178 ..SupervisorSpec::default()
8179 };
8180 s.validate()
8181 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
8182 }
8183 }
8184
8185 #[test]
8186 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
8187 // Cross-arm ordering pin: `Duration::ZERO` has
8188 // `subsec_nanos() == 0` and would otherwise pass the
8189 // canonical-form arm — the zero-floor arm must fire first so
8190 // the more self-locating `RestartWindowZero` diagnostic (with
8191 // its omit-axis remediation directly named) leads. Same
8192 // posture every peer zero-then-shape gate uses
8193 // (`WallClockZero` → `WallClockNotCanonical`,
8194 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
8195 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
8196 let s = SupervisorSpec {
8197 restart_window: Some(Duration::ZERO),
8198 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8199 ..SupervisorSpec::default()
8200 };
8201 assert_eq!(
8202 s.validate().unwrap_err(),
8203 SupervisorError::RestartWindowZero
8204 );
8205 }
8206
8207 #[test]
8208 fn restart_window_canonical_diagnostic_carries_offending_duration() {
8209 // Diagnostic-shape pin: the canonical-form arm names the
8210 // offending `Duration` verbatim so the author's grep lands on
8211 // the field's value, not a generic "duration not canonical"
8212 // message. Same shape every other typed-canonical-form arm
8213 // on this surface carries (`WallClockNotCanonical` carries
8214 // the offending `Duration` verbatim,
8215 // `PolicyTimeoutNotCanonical` carries the offending
8216 // `Duration` verbatim).
8217 let w = Duration::from_micros(500);
8218 let s = SupervisorSpec {
8219 restart_window: Some(w),
8220 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8221 ..SupervisorSpec::default()
8222 };
8223 let err = s.validate().unwrap_err();
8224 let msg = err.to_string();
8225 assert!(
8226 msg.contains("500"),
8227 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
8228 );
8229 assert!(
8230 msg.contains("sub-millisecond"),
8231 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
8232 );
8233 }
8234
8235 #[test]
8236 fn restart_window_validated_value_round_trips_through_codec() {
8237 // The structural property the canonical-ms gate enforces:
8238 // every `SupervisorSpec::restart_window` past
8239 // `SupervisorSpec::validate` round-trips losslessly through
8240 // the shared duration codec (serialize → string →
8241 // deserialize → equal value). Pin this end-to-end so a future
8242 // change to either side (the validate gate's accepted
8243 // granularity, the codec's parse/render unit set) that breaks
8244 // the alignment surfaces here. Peer of
8245 // `wall_clock_validated_value_round_trips_through_codec` on
8246 // the sibling `:limits :wall-clock` axis.
8247 for w in [
8248 Duration::from_millis(1),
8249 Duration::from_millis(1500),
8250 Duration::from_secs(30),
8251 Duration::from_secs(3600),
8252 ] {
8253 let s = SupervisorSpec {
8254 restart_window: Some(w),
8255 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8256 ..SupervisorSpec::default()
8257 };
8258 s.validate().unwrap();
8259 let json = serde_json::to_string(&s).unwrap();
8260 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8261 assert_eq!(back.restart_window, Some(w));
8262 }
8263 }
8264
8265 // ── value-shape: upper cap on :restart-window ─────────────────────────
8266 //
8267 // The fourth (and last) typed-`Duration` axis in caixa-core to get
8268 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
8269 // `:politicas :timeout` (2e8ee7e), and `:politicas
8270 // :circuit-breaker :window` (379a814). Brackets the typed
8271 // `:restart-window` axis structurally: every validated value lies
8272 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
8273 // granularity, closing the
8274 // rolling-window-degenerates-to-lifetime-counter footgun the prior
8275 // zero-floor-and-canonical-form-only checks left open.
8276
8277 #[test]
8278 fn validate_rejects_restart_window_above_cap() {
8279 // The fail-before-pass-after pin: 3601s = 1h + 1s is
8280 // structurally one canonical-tick past the
8281 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
8282 // integer-millisecond magnitude the canonical-form arm above
8283 // accepts cleanly, that the shared duration codec round-trips
8284 // losslessly as `"3601s"`, and that silently passed validate on
8285 // every pre-gate codebase because the typed slot's only checks
8286 // were the zero-floor and canonical-form arms. The runtime
8287 // substrate consuming the value (Erlang/OTP's MaxIntensity/
8288 // Period reconciler, the future wasm-operator's per-supervisor
8289 // restart-intensity counter) reaches for a `Duration` so long
8290 // no realistic restart-recovery pattern resets the counter,
8291 // far from the source caixa.lisp.
8292 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
8293 let s = SupervisorSpec {
8294 restart_window: Some(w),
8295 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8296 ..SupervisorSpec::default()
8297 };
8298 assert_eq!(
8299 s.validate().unwrap_err(),
8300 SupervisorError::RestartWindowExceedsCap { window: w }
8301 );
8302 }
8303
8304 #[test]
8305 fn validate_rejects_restart_window_one_millisecond_above_cap() {
8306 // Boundary case: exactly 1ms past the cap (the granularity the
8307 // canonical-form gate enforces). Catches a future "strictly
8308 // less than" half-measure and pins the diagnostic to name the
8309 // offending `Duration` verbatim. Peer of
8310 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
8311 // `rejects_policy_timeout_one_millisecond_above_cap` /
8312 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
8313 // on the sibling typed-`Duration` axes' top edges.
8314 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8315 let s = SupervisorSpec {
8316 restart_window: Some(w),
8317 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8318 ..SupervisorSpec::default()
8319 };
8320 assert_eq!(
8321 s.validate().unwrap_err(),
8322 SupervisorError::RestartWindowExceedsCap { window: w }
8323 );
8324 }
8325
8326 #[test]
8327 fn validate_rejects_restart_window_far_above_cap() {
8328 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
8329 // `(:restart-window "7d")`, or any "I want a lifetime counter
8330 // but wrote a `<integer>h` magnitude anyway" typo — values the
8331 // canonical-form arm accepts as integer-millisecond magnitudes,
8332 // the codec round-trips losslessly through serde, but the
8333 // operator's `MaxIntensity / Period` reconciler cannot honor
8334 // as a meaningful rolling window. Until this gate landed
8335 // validate accepted them. Pin the common above-cap values (24h,
8336 // 7d, ~11.5d) so a future relaxation that drops the upper bound
8337 // surfaces here.
8338 for w in [
8339 Duration::from_secs(86_400), // 24h
8340 Duration::from_secs(604_800), // 7d
8341 Duration::from_secs(1_000_000), // ~11.5 days
8342 ] {
8343 let s = SupervisorSpec {
8344 restart_window: Some(w),
8345 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8346 ..SupervisorSpec::default()
8347 };
8348 assert_eq!(
8349 s.validate().unwrap_err(),
8350 SupervisorError::RestartWindowExceedsCap { window: w }
8351 );
8352 }
8353 }
8354
8355 #[test]
8356 fn validate_accepts_restart_window_at_cap() {
8357 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
8358 // (1h) — must validate. The cap is inclusive on the top edge,
8359 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
8360 // [`crate::POLICY_TIMEOUT_MAX`] /
8361 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
8362 // capped axes. Pin the boundary explicitly so a future
8363 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
8364 // instead of `>`) surfaces here as a test failure rather than a
8365 // silent contract narrowing.
8366 let s = SupervisorSpec {
8367 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
8368 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8369 ..SupervisorSpec::default()
8370 };
8371 s.validate()
8372 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
8373 }
8374
8375 #[test]
8376 fn validate_accepts_restart_window_typical_values() {
8377 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
8378 // per-supervisor production-playbook band positive-control
8379 // sweep — every value Learn You Some Erlang's `{intensity, 5,
8380 // 60}` worker-supervisor `Period = 60s` default, Elixir's
8381 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
8382 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
8383 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
8384 // default recommend (5s..=300s) must pass, plus a sweep
8385 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
8386 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
8387 // on the sibling `:limits :wall-clock` axis.
8388 for w in [
8389 Duration::from_millis(1),
8390 Duration::from_millis(500),
8391 Duration::from_secs(1),
8392 Duration::from_secs(5), // RabbitMQ broker-supervisor default
8393 Duration::from_secs(10), // Riak Core lower
8394 Duration::from_secs(30),
8395 Duration::from_secs(60), // Learn You Some Erlang default
8396 Duration::from_secs(120), // OTP supervisor MaxT typical
8397 Duration::from_secs(300), // Riak Core upper
8398 Duration::from_secs(900), // 15m
8399 Duration::from_secs(1800),
8400 Duration::from_secs(3600), // exactly 1h, the cap
8401 ] {
8402 let s = SupervisorSpec {
8403 restart_window: Some(w),
8404 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8405 ..SupervisorSpec::default()
8406 };
8407 s.validate()
8408 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
8409 }
8410 }
8411
8412 #[test]
8413 fn restart_window_zero_takes_precedence_over_cap() {
8414 // The cross-arm ordering pin: `Duration::ZERO` is structurally
8415 // outside both `>= 1ms` (zero-floor) and `<=
8416 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
8417 // diagnostic is the more self-locating one (it directly names
8418 // the omit-axis remediation), so the validate gate must fire
8419 // on zero first. Same shape every other zero-then-cap ordering
8420 // on this surface uses (`WallClockZero` then
8421 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
8422 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
8423 // `PolicyBreakerWindowExceedsCap`).
8424 let s = SupervisorSpec {
8425 restart_window: Some(Duration::ZERO),
8426 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8427 ..SupervisorSpec::default()
8428 };
8429 assert_eq!(
8430 s.validate().unwrap_err(),
8431 SupervisorError::RestartWindowZero,
8432 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
8433 );
8434 }
8435
8436 #[test]
8437 fn restart_window_canonical_takes_precedence_over_cap() {
8438 // The cross-arm ordering pin: a `Duration` that is *both*
8439 // sub-millisecond (non-canonical-form) and structurally above
8440 // the cap surfaces the canonical-form diagnostic first,
8441 // because the round-trip-shape break is the more fundamental
8442 // issue (the value can't even round-trip through the codec,
8443 // so the cap diagnostic naming `1ms..=1h` would be misleading
8444 // — there's no integer-ms form of the offending value). Pin
8445 // the order so a future refactor that reorders the arms
8446 // surfaces here as a test failure rather than a silent
8447 // diagnostic regression. Peer of
8448 // `wall_clock_canonical_takes_precedence_over_cap` /
8449 // `policy_timeout_canonical_takes_precedence_over_cap`.
8450 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
8451 let s = SupervisorSpec {
8452 restart_window: Some(w),
8453 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8454 ..SupervisorSpec::default()
8455 };
8456 assert_eq!(
8457 s.validate().unwrap_err(),
8458 SupervisorError::RestartWindowNotCanonical { window: w },
8459 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
8460 );
8461 }
8462
8463 #[test]
8464 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
8465 // The cross-arm ordering pin between the `:max-restarts` cap
8466 // and the sibling `:restart-window` cap. A supervisor carrying
8467 // both an over-cap `max_restarts` AND an over-cap window must
8468 // surface the `MaxRestartsExceedsCap` diagnostic first — the
8469 // cap arm is wired immediately after the zero-restart arm and
8470 // strictly before every window-axis arm (zero / canonical /
8471 // cap), so the offending value the diagnostic names matches
8472 // the order the author would discover the gates by reading
8473 // top-to-bottom through `SupervisorSpec::validate`. Pin the
8474 // order so a future refactor that reorders the arms surfaces
8475 // here as a test failure rather than a silent diagnostic
8476 // regression. Peer of
8477 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
8478 // on the sibling zero / canonical window arms.
8479 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
8480 let s = SupervisorSpec {
8481 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8482 restart_window: Some(w),
8483 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8484 ..SupervisorSpec::default()
8485 };
8486 assert_eq!(
8487 s.validate().unwrap_err(),
8488 SupervisorError::MaxRestartsExceedsCap {
8489 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8490 },
8491 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
8492 );
8493 }
8494
8495 #[test]
8496 fn restart_window_cap_diagnostic_carries_offending_value() {
8497 // The diagnostic-shape pin: the offending `Duration` is
8498 // carried verbatim into the
8499 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
8500 // surfaced error message names the value the author wrote,
8501 // not just the cap. Same self-locating diagnostic shape every
8502 // other typed-cap arm on this surface carries
8503 // (`WallClockExceedsCap` carries the offending `Duration`
8504 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
8505 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
8506 // the offending `Duration` verbatim).
8507 let w = Duration::from_secs(7200); // 2h
8508 let s = SupervisorSpec {
8509 restart_window: Some(w),
8510 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8511 ..SupervisorSpec::default()
8512 };
8513 let err = s.validate().unwrap_err();
8514 assert!(
8515 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
8516 "got {err:?}"
8517 );
8518 let msg = err.to_string();
8519 assert!(
8520 msg.contains("7200"),
8521 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
8522 );
8523 }
8524
8525 #[test]
8526 fn supervisor_restart_window_cap_pins_canonical_value() {
8527 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
8528 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
8529 // shared duration codec emits as a clean canonical string
8530 // (`"<n>h"`). Pinning the literal value here surfaces a future
8531 // drift (a relaxation to 24h, a tightening to 5m) as a
8532 // deliberate test edit, not a silent contract narrowing.
8533 //
8534 // The four typed-`Duration` caps on the validation surface
8535 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
8536 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
8537 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
8538 // single uniform top edge at the codec's largest emitted unit
8539 // — a structural-property invariant the equality assertions
8540 // here enshrine, so a future drift on any of the four
8541 // surfaces as a deliberate test edit. Same shape every other
8542 // typed-cap value pin uses
8543 // (`wall_clock_cap_pins_canonical_value`,
8544 // `policy_timeout_cap_pins_canonical_value`,
8545 // `circuit_breaker_window_cap_pins_canonical_value`).
8546 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
8547 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
8548 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
8549 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
8550 assert_eq!(
8551 SUPERVISOR_RESTART_WINDOW_MAX,
8552 crate::POLICY_BREAKER_WINDOW_MAX
8553 );
8554 }
8555
8556 #[test]
8557 fn restart_window_cap_value_round_trips_through_codec() {
8558 // The codec round-trip property the cap arm preserves: the
8559 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
8560 // through the shared duration codec — every value at the cap
8561 // serializes to the canonical `"1h"` form and parses back
8562 // identically. Pin the round-trip so a future change to the
8563 // codec's unit set or to the cap's magnitude that breaks the
8564 // round-trip property surfaces here. Peer of
8565 // `wall_clock_cap_value_round_trips_through_codec` on the
8566 // sibling `:limits :wall-clock` axis.
8567 let s = SupervisorSpec {
8568 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
8569 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8570 ..SupervisorSpec::default()
8571 };
8572 s.validate().unwrap();
8573 let json = serde_json::to_string(&s).unwrap();
8574 assert!(
8575 json.contains("\"1h\""),
8576 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
8577 );
8578 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8579 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
8580 }
8581
8582 #[test]
8583 fn validate_rejects_duplicate_child_caixa() {
8584 // Two children with the same :caixa render to two ComputeUnits
8585 // with the same name in the cluster's HelmRelease values —
8586 // one silently overwrites the other. Erlang/OTP's child_spec.id
8587 // is required-unique per supervisor; same set-not-multiset
8588 // discipline applied here as for :membros / :placement
8589 // :clusters / :entrada :paths.
8590 let s = SupervisorSpec {
8591 children: vec![
8592 child("worker", "^0.1", RestartPolicy::Permanent),
8593 child("cache", "^0.1", RestartPolicy::Transient),
8594 child("worker", "^0.2", RestartPolicy::Permanent),
8595 ],
8596 ..SupervisorSpec::default()
8597 };
8598 let err = s.validate().unwrap_err();
8599 assert!(
8600 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
8601 "got {err:?}"
8602 );
8603 }
8604
8605 #[test]
8606 fn validate_duplicate_child_diagnostic_names_first_collision() {
8607 // Iteration walks the :children list in declaration order —
8608 // the diagnostic names the first repeat, deterministically,
8609 // even when multiple names duplicate.
8610 let s = SupervisorSpec {
8611 children: vec![
8612 child("a", "^0.1", RestartPolicy::Permanent),
8613 child("b", "^0.1", RestartPolicy::Permanent),
8614 child("a", "^0.1", RestartPolicy::Permanent),
8615 child("b", "^0.1", RestartPolicy::Permanent),
8616 ],
8617 ..SupervisorSpec::default()
8618 };
8619 let err = s.validate().unwrap_err();
8620 assert!(
8621 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
8622 "got {err:?}"
8623 );
8624 }
8625
8626 // ── self-supervision cross-slot gate ──────────────────────────
8627
8628 #[test]
8629 fn validate_no_self_supervision_rejects_self_referential_child() {
8630 // A supervisor whose `:children` lists its own `:nome` is a
8631 // one-node reconciliation cycle — rejected, naming the parent.
8632 let children = vec![
8633 child("worker", "^0.1", RestartPolicy::Permanent),
8634 child("orquestra", "^0.1", RestartPolicy::Permanent),
8635 ];
8636 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
8637 assert!(
8638 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
8639 "got {err:?}"
8640 );
8641 }
8642
8643 #[test]
8644 fn validate_no_self_supervision_accepts_distinct_children() {
8645 // Positive control: distinct child names (including a child that
8646 // is itself a supervisor — nested trees are valid OTP) pass.
8647 let children = vec![
8648 child("worker", "^0.1", RestartPolicy::Permanent),
8649 child("sub-tree", "^0.1", RestartPolicy::Permanent),
8650 ];
8651 validate_no_self_supervision(&children, "orquestra").unwrap();
8652 }
8653
8654 #[test]
8655 fn validate_no_self_supervision_empty_children_is_ok() {
8656 // SimpleOneForOne / no-static-children supervisors have nothing
8657 // to self-reference — the gate is vacuously satisfied.
8658 validate_no_self_supervision(&[], "orquestra").unwrap();
8659 }
8660
8661 #[test]
8662 fn validate_simple_one_for_one_skips_uniqueness_check() {
8663 // SimpleOneForOne supervisors carry no static children — the
8664 // duplicate-child loop never runs. A zero-window declaration
8665 // on a SimpleOneForOne supervisor still trips the window check
8666 // (window applies to dynamic children too).
8667 let s = SupervisorSpec {
8668 estrategia: RestartStrategy::SimpleOneForOne,
8669 restart_window: None,
8670 children: vec![],
8671 ..SupervisorSpec::default()
8672 };
8673 s.validate().unwrap();
8674 let s_zero = SupervisorSpec {
8675 estrategia: RestartStrategy::SimpleOneForOne,
8676 restart_window: Some(Duration::ZERO),
8677 children: vec![],
8678 ..SupervisorSpec::default()
8679 };
8680 assert_eq!(
8681 s_zero.validate().unwrap_err(),
8682 SupervisorError::RestartWindowZero
8683 );
8684 }
8685
8686 #[test]
8687 fn validate_zero_window_runs_after_max_restarts_check() {
8688 // Pin the order: max_restarts == 0 fires before
8689 // restart_window == 0s, so an author with both wrong sees the
8690 // counter-axis diagnostic first (matches the order in the
8691 // struct and in the doc comment).
8692 let s = SupervisorSpec {
8693 max_restarts: 0,
8694 restart_window: Some(Duration::ZERO),
8695 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8696 ..SupervisorSpec::default()
8697 };
8698 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
8699 }
8700
8701 #[test]
8702 fn round_trip_all_strategies() {
8703 for &strat in RestartStrategy::ALL {
8704 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
8705 // shape partition through the [`gen_platform::IsVariant`]
8706 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
8707 // predicate rather than the raw
8708 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
8709 // open-coded pattern-match — same closed-set-typed-enum
8710 // arm-discriminator dispatch discipline the sibling
8711 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
8712 // (915a934) extended onto its two paired positive / negated
8713 // `matches!` filter sites, and the sibling
8714 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
8715 // predicate convergence (766ec63) extended onto the M3 mesh-
8716 // slot per-`:placement` distribution-strategy `matches!`
8717 // discriminator axis. See the sibling
8718 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8719 // fixture and the peer `manifest::tests::
8720 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
8721 // fixture — all three sites (the last unlifted
8722 // `matches!`-based arm-discriminator axis on the OTP-shape
8723 // supervisor sibling-restart-strategy closed-set typed enum,
8724 // acknowledged in 915a934's Prior-commits footnote as the
8725 // outstanding follow-up) now consult one typed dispatch on
8726 // the substrate primitive.
8727 let s = SupervisorSpec {
8728 estrategia: strat,
8729 children: if strat.is_simple_one_for_one() {
8730 vec![]
8731 } else {
8732 vec![child("w", "^0.1", RestartPolicy::Permanent)]
8733 },
8734 ..SupervisorSpec::default()
8735 };
8736 let json = serde_json::to_string(&s).unwrap();
8737 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8738 assert_eq!(s, back);
8739 }
8740 }
8741
8742 #[test]
8743 fn round_trip_all_restart_policies() {
8744 for policy in [
8745 RestartPolicy::Permanent,
8746 RestartPolicy::Temporary,
8747 RestartPolicy::Transient,
8748 ] {
8749 let c = child("w", "^0.1", policy);
8750 let json = serde_json::to_string(&c).unwrap();
8751 let back: ChildSpec = serde_json::from_str(&json).unwrap();
8752 assert_eq!(c, back);
8753 }
8754 }
8755
8756 #[test]
8757 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
8758 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
8759 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
8760 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
8761 // is the only variant that satisfies `.is_simple_one_for_one()`;
8762 // every static-children-bearing arm (`OneForOne` / `OneForAll`
8763 // / `RestForOne`) returns `false`. This pin makes the partition
8764 // invariant load-bearing at caixa-core test time so a future
8765 // derive regression (a hole that returns `false` for
8766 // `SimpleOneForOne` too, or a byte-collision that flips a second
8767 // variant to `true`) trips here rather than laundering the arm
8768 // at the three test-fixture builder sites (a hole flips the
8769 // `SimpleOneForOne` fixture to carry a non-empty children list
8770 // and the subsequent `SupervisorSpec::validate` would refuse the
8771 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
8772 // a collision flips a peer strategy's fixture to carry an empty
8773 // children list and the subsequent `validate` would refuse with
8774 // [`SupervisorError::NoChildren`] — either way, the pin fires
8775 // here, at the derive site, rather than at the fixture-refusal
8776 // site far away). Peer of the sibling
8777 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
8778 // (915a934) pin on the M2 OTP-appup axis and the sibling
8779 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
8780 // pin on the M0 `:kind` axis.
8781 let cases: &[(RestartStrategy, bool)] = &[
8782 (RestartStrategy::OneForOne, false),
8783 (RestartStrategy::OneForAll, false),
8784 (RestartStrategy::RestForOne, false),
8785 (RestartStrategy::SimpleOneForOne, true),
8786 ];
8787 for (variant, expected) in cases {
8788 assert_eq!(
8789 variant.is_simple_one_for_one(),
8790 *expected,
8791 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
8792 return {expected} (partition invariant on the \
8793 IsVariant-derived arm-discriminator predicate — every \
8794 test-fixture site that partitions the `:children` slot \
8795 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
8796 off this typed dispatch, so a derive regression must \
8797 surface here rather than at the fixture-refusal site)"
8798 );
8799 }
8800 }
8801
8802 #[test]
8803 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
8804 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
8805 // fixture-shape partition against the pre-lift
8806 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
8807 // pattern-match every test-fixture builder site previously
8808 // coupled to inline. Asserts the two projections agree byte-for-
8809 // byte on every arm of the enum, so a future derive regression
8810 // that flipped either predicate's arm-set would surface here at
8811 // caixa-core test time rather than at the three fixture-builder
8812 // sites (`supervisor::tests::round_trip_all_strategies`,
8813 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
8814 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
8815 // far from the derive site. Same peer-shape byte-identity pin
8816 // every sibling `IsVariant`-derive-routed convergence carries on
8817 // the substrate's closed-set typed-enum surface (peer of
8818 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
8819 // on the M2 OTP-appup axis).
8820 for &strat in RestartStrategy::ALL {
8821 let via_predicate = strat.is_simple_one_for_one();
8822 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
8823 assert_eq!(
8824 via_predicate, via_matches,
8825 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
8826 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
8827 the pre-lift open-coded pattern and the \
8828 IsVariant-derived predicate are the same axis, \
8829 one typed dispatch"
8830 );
8831 }
8832 }
8833
8834 #[test]
8835 fn duration_codec_round_trip_canonical_units() {
8836 // Note the canonical-form rule: durations serialize to the
8837 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
8838 // "60s" — but the round-trip preserves the underlying Duration.
8839 let cases = [
8840 ("30s", Duration::from_secs(30)),
8841 ("5m", Duration::from_secs(300)),
8842 ("1h", Duration::from_secs(3600)),
8843 ("500ms", Duration::from_millis(500)),
8844 ];
8845 for (lit, dur) in cases {
8846 let s = SupervisorSpec {
8847 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8848 restart_window: Some(dur),
8849 ..SupervisorSpec::default()
8850 };
8851 let json = serde_json::to_string(&s).unwrap();
8852 assert!(
8853 json.contains(&format!("\"{lit}\"")),
8854 "expected \"{lit}\" in {json}"
8855 );
8856 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8857 assert_eq!(back.restart_window, Some(dur));
8858 }
8859 }
8860
8861 #[test]
8862 fn duration_canonicalizes_to_largest_unit() {
8863 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
8864 // typed Duration still equals 60s on the way back.
8865 let s = SupervisorSpec {
8866 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8867 restart_window: Some(Duration::from_secs(60)),
8868 ..SupervisorSpec::default()
8869 };
8870 let json = serde_json::to_string(&s).unwrap();
8871 assert!(json.contains("\"1m\""), "{json}");
8872 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8873 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
8874 }
8875
8876 #[test]
8877 fn three_child_one_for_one_validates() {
8878 let s = SupervisorSpec {
8879 estrategia: RestartStrategy::OneForOne,
8880 max_restarts: 5,
8881 restart_window: Some(Duration::from_secs(60)),
8882 children: vec![
8883 child("worker", "^0.1", RestartPolicy::Permanent),
8884 child("cache", "^0.1", RestartPolicy::Transient),
8885 child("scratch", "^0.1", RestartPolicy::Temporary),
8886 ],
8887 };
8888 s.validate().unwrap();
8889 }
8890
8891 #[test]
8892 fn json_uses_pascal_case_for_strategy_and_policy() {
8893 // Variant names are PascalCase by default in serde, matching
8894 // tatara-lisp's enum convention (`:estrategia OneForOne`).
8895 let c = child("w", "^0.1", RestartPolicy::Permanent);
8896 let json = serde_json::to_string(&c).unwrap();
8897 assert!(json.contains("\"Permanent\""));
8898 assert!(!json.contains("\"permanent\""));
8899
8900 let s = SupervisorSpec {
8901 estrategia: RestartStrategy::OneForOne,
8902 children: vec![c],
8903 ..SupervisorSpec::default()
8904 };
8905 let json = serde_json::to_string(&s).unwrap();
8906 assert!(json.contains("\"estrategia\":\"OneForOne\""));
8907 }
8908
8909 // ── shared duration codec: integer-magnitude canonical-form gate ──
8910 //
8911 // The gate lifts the discipline `crate::limits::parse_duration`
8912 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
8913 // the shared codec backing the remaining three typed-duration
8914 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
8915 // `:politicas :circuit-breaker :window`. Every magnitude `render`
8916 // emits is a non-negative integer with no decimal point and no
8917 // leading sign, so the codec's accepted set must match for
8918 // serialize/deserialize to round-trip without canonical-form
8919 // drift.
8920
8921 #[test]
8922 fn parse_accepts_integer_canonical_units() {
8923 // Pin the happy-path: every canonical author shape `render`
8924 // ever emits parses to the same `Duration` value, so the
8925 // codec's accepted set is at least a superset of its emitted
8926 // set on the canonical-unit axis.
8927 for (lit, dur) in [
8928 ("30s", Duration::from_secs(30)),
8929 ("500ms", Duration::from_millis(500)),
8930 ("2m", Duration::from_secs(120)),
8931 ("1h", Duration::from_secs(3600)),
8932 ("0s", Duration::ZERO),
8933 ] {
8934 assert_eq!(
8935 duration_codec::parse(lit).unwrap(),
8936 dur,
8937 "parse({lit:?}) should be {dur:?}"
8938 );
8939 }
8940 }
8941
8942 #[test]
8943 fn parse_accepts_bare_integer_as_seconds() {
8944 // The `"s" | ""` arm: a bare integer with no unit is read as
8945 // seconds. Pin this so the unit-empty form keeps parsing (it
8946 // renders to `"<n>s"` on serialize — that's a unit-choice
8947 // drift the integer-magnitude gate does NOT close, matching
8948 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
8949 // the peer `:limits :memory` codec).
8950 assert_eq!(
8951 duration_codec::parse("30").unwrap(),
8952 Duration::from_secs(30)
8953 );
8954 }
8955
8956 #[test]
8957 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
8958 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
8959 // on first serialize — DRIFT. The integer-magnitude gate names
8960 // the offending `"1.5"` verbatim and points at the canonical
8961 // remediation `"1500ms"`.
8962 let err = duration_codec::parse("1.5s").unwrap_err();
8963 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
8964 assert!(
8965 err.contains("not a non-negative integer"),
8966 "missing canonical-form reason in {err:?}"
8967 );
8968 assert!(
8969 err.contains("\"1500ms\""),
8970 "missing canonical-form remediation in {err:?}"
8971 );
8972 }
8973
8974 #[test]
8975 fn parse_rejects_decimal_shaped_integer_seconds() {
8976 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
8977 // `1s` exactly, so the round-trip looks correct — but the
8978 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
8979 // decimal-shape-with-integer-value form so author intent is
8980 // never silently rewritten.
8981 let err = duration_codec::parse("1.0s").unwrap_err();
8982 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
8983 assert!(
8984 err.contains("not a non-negative integer"),
8985 "missing canonical-form reason in {err:?}"
8986 );
8987 }
8988
8989 #[test]
8990 fn parse_rejects_half_unit_minute() {
8991 // `"0.5m"` is the unit-fraction footgun — author writes a
8992 // human-readable half-minute, serde silently rewrites to
8993 // `"30s"` on next emit. The gate names the offending
8994 // magnitude `"0.5"` and points at the integer-in-smaller-unit
8995 // form.
8996 let err = duration_codec::parse("0.5m").unwrap_err();
8997 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
8998 assert!(
8999 err.contains("\"30s\""),
9000 "missing canonical-form remediation in {err:?}"
9001 );
9002 }
9003
9004 #[test]
9005 fn parse_rejects_leading_plus_sign() {
9006 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
9007 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
9008 // cleanly to 30s and round-tripped to `"30s"` on next emit
9009 // (DRIFT). The digit-only gate closes the leading-sign class
9010 // first; the diagnostic names `"+30"` verbatim.
9011 let err = duration_codec::parse("+30s").unwrap_err();
9012 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
9013 assert!(
9014 err.contains("not a non-negative integer"),
9015 "missing canonical-form reason in {err:?}"
9016 );
9017 }
9018
9019 #[test]
9020 fn parse_rejects_leading_minus_sign() {
9021 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
9022 // rejected with `"negative duration in \"-30s\""`. Under the
9023 // integer-magnitude gate the diagnostic is unified — `-30` is
9024 // non-digit-only, f64-numeric, and surfaces with the canonical-
9025 // form reason (no leading `+` / `-` sign) naming the offending
9026 // `"-30"` verbatim. Same diagnostic shape as every other
9027 // rejected non-integer magnitude.
9028 let err = duration_codec::parse("-30s").unwrap_err();
9029 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
9030 assert!(
9031 err.contains("not a non-negative integer"),
9032 "missing canonical-form reason in {err:?}"
9033 );
9034 }
9035
9036 #[test]
9037 fn parse_garbage_still_falls_through_to_bad_magnitude() {
9038 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
9039 // through to the narrower "bad duration magnitude" arm — the
9040 // canonical-form diagnostic is reserved for the parser-shape
9041 // footgun case, not the "not a number at all" case. Same
9042 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
9043 // the peer `:limits :memory` codec.
9044 let err = duration_codec::parse("--1s").unwrap_err();
9045 assert!(
9046 err.contains("bad duration magnitude"),
9047 "expected bad-magnitude wording in {err:?}"
9048 );
9049 }
9050
9051 #[test]
9052 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
9053 // The accepted set is now closed under `u64`-exact integer
9054 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
9055 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
9056 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
9057 // possible. Pin the integer-exact arms across the four unit
9058 // suffixes so a future refactor that reaches back for f64
9059 // (`from_secs_f64`, `mul_f64`) surfaces here.
9060 assert_eq!(
9061 duration_codec::parse("3600s").unwrap(),
9062 Duration::from_secs(3600)
9063 );
9064 assert_eq!(
9065 duration_codec::parse("60m").unwrap(),
9066 Duration::from_secs(3600)
9067 );
9068 assert_eq!(
9069 duration_codec::parse("1h").unwrap(),
9070 Duration::from_secs(3600)
9071 );
9072 assert_eq!(
9073 duration_codec::parse("999ms").unwrap(),
9074 Duration::from_millis(999)
9075 );
9076 }
9077
9078 #[test]
9079 fn restart_window_serde_rejects_fractional_seconds() {
9080 // The shared codec backs `SupervisorSpec::restart_window`
9081 // (`with = "duration_codec"`) — so the gate applies on serde
9082 // deserialize for the typed Supervisor slot. A
9083 // `{"restartWindow":"1.5s"}` payload that previously round-
9084 // tripped to a different canonical string on next serialize
9085 // is now refused at deserialize with the integer-magnitude
9086 // diagnostic.
9087 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
9088 "restartWindow":"1.5s",
9089 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
9090 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
9091 let msg = err.to_string();
9092 assert!(
9093 msg.contains("not a non-negative integer"),
9094 "expected integer-magnitude diagnostic in {msg:?}"
9095 );
9096 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
9097 }
9098
9099 #[test]
9100 fn restart_window_serde_rejects_leading_plus() {
9101 // The `u64::from_str` leading-`+` permissiveness gap that
9102 // motivated the digit-only gate (the `f64`-side accepted
9103 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
9104 // is now closed on the shared codec — surfaces as a structured
9105 // diagnostic at the serde layer for every typed-duration slot.
9106 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
9107 "restartWindow":"+30s",
9108 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
9109 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
9110 let msg = err.to_string();
9111 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
9112 assert!(
9113 msg.contains("not a non-negative integer"),
9114 "missing canonical-form reason in {msg:?}"
9115 );
9116 }
9117
9118 #[test]
9119 fn parse_rejects_leading_zero_magnitude() {
9120 // `"030s"` is digit-only, so the existing non-digit-only / sign
9121 // / fractional arm doesn't catch it — `u64::from_str("030")`
9122 // returns `Ok(30)`, so before this gate `"030s"` parsed to
9123 // `Duration::from_secs(30)` and round-tripped through `render`
9124 // to `"30s"` — a *different* canonical string on the next emit,
9125 // breaking the THEORY.md Part V render-determinism contract
9126 // exactly the way `"+30s"` did before the leading-`+` arm
9127 // landed. Peer with the `rate_limit_codec` leading-zero arm
9128 // (4f46830) on the same canonical-form-drift axis.
9129 let err = duration_codec::parse("030s").unwrap_err();
9130 assert!(
9131 err.contains("non-canonical leading zero"),
9132 "expected leading-zero diagnostic in {err:?}"
9133 );
9134 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
9135 assert!(
9136 err.contains("\"30s\""),
9137 "missing canonical-form remediation in {err:?}"
9138 );
9139 assert!(
9140 err.contains("THEORY.md"),
9141 "missing render-determinism citation in {err:?}"
9142 );
9143 }
9144
9145 #[test]
9146 fn parse_rejects_multi_digit_zero_magnitude() {
9147 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
9148 // digit-only, parse losslessly to `Duration::ZERO`, but render
9149 // back to `"0s"` (the single-byte canonical form) on the next
9150 // emit. The leading-zero arm refuses the drift class at the
9151 // codec layer; the semantic-zero gate downstream
9152 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
9153 // the single-byte canonical form `"0s"` separately on the
9154 // typed-validate layer.
9155 let err = duration_codec::parse("00s").unwrap_err();
9156 assert!(
9157 err.contains("non-canonical leading zero"),
9158 "expected leading-zero diagnostic in {err:?}"
9159 );
9160 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
9161 }
9162
9163 #[test]
9164 fn parse_rejects_leading_zero_per_hour_window() {
9165 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
9166 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
9167 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
9168 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
9169 // `h` / bare-integer-as-seconds) inherits the same gate.
9170 let err = duration_codec::parse("01h").unwrap_err();
9171 assert!(
9172 err.contains("non-canonical leading zero"),
9173 "expected leading-zero diagnostic in {err:?}"
9174 );
9175 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
9176 }
9177
9178 #[test]
9179 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
9180 // The `parse_accepts_bare_integer_as_seconds` happy-path
9181 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
9182 // multi-byte starts-with-`0`, parses losslessly to
9183 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
9184 // bare-integer surface accepts permissive unit-empty
9185 // shorthand but still must reject leading-zero padding.
9186 let err = duration_codec::parse("030").unwrap_err();
9187 assert!(
9188 err.contains("non-canonical leading zero"),
9189 "expected leading-zero diagnostic in {err:?}"
9190 );
9191 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
9192 }
9193
9194 #[test]
9195 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
9196 // The codec-layer / typed-validate-layer boundary: `"0s"` /
9197 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
9198 // each round-trips losslessly through `render`
9199 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
9200 // accepts them. The downstream semantic-zero gates
9201 // (`SupervisorError::ZeroRestartWindow`,
9202 // `AplicacaoError::PolicyTimeoutZero`,
9203 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
9204 // zero-magnitude authoring at the typed-validate layer above,
9205 // peer with the `rate_limit_codec` codec-layer / typed-
9206 // validate-layer partition for `"0/s"`.
9207 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
9208 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
9209 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
9210 }
9211
9212 #[test]
9213 fn parse_accepts_canonical_magnitude_with_leading_one() {
9214 // The complementary boundary: a future tightening cannot
9215 // drift into rejecting valid canonical magnitudes that
9216 // happen to start with `1` (or any digit `[1-9]`). Pin
9217 // every canonical-unit suffix so the leading-zero arm
9218 // remains strictly narrower than the digit-only arm.
9219 assert_eq!(
9220 duration_codec::parse("100ms").unwrap(),
9221 Duration::from_millis(100)
9222 );
9223 assert_eq!(
9224 duration_codec::parse("100s").unwrap(),
9225 Duration::from_secs(100)
9226 );
9227 assert_eq!(
9228 duration_codec::parse("10m").unwrap(),
9229 Duration::from_secs(600)
9230 );
9231 assert_eq!(
9232 duration_codec::parse("10h").unwrap(),
9233 Duration::from_secs(36_000)
9234 );
9235 }
9236
9237 #[test]
9238 fn restart_window_serde_rejects_leading_zero() {
9239 // The shared codec backs `SupervisorSpec::restart_window`
9240 // (`with = "duration_codec"`) — so the leading-zero arm
9241 // applies on serde deserialize for the typed Supervisor slot.
9242 // A `{"restartWindow":"030s"}` payload that previously round-
9243 // tripped to a different canonical string on next serialize
9244 // is now refused at deserialize with the leading-zero
9245 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
9246 // / `restart_window_serde_rejects_fractional_seconds` on the
9247 // same canonical-form-drift axis.
9248 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
9249 "restartWindow":"030s",
9250 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
9251 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
9252 let msg = err.to_string();
9253 assert!(
9254 msg.contains("non-canonical leading zero"),
9255 "expected leading-zero diagnostic in {msg:?}"
9256 );
9257 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
9258 }
9259
9260 #[test]
9261 fn parse_rejects_leading_whitespace() {
9262 // `" 30s"` — the canonical paste-from-aligned-doc /
9263 // paste-from-YAML-quoted-plain-scalar footgun. Before this
9264 // gate the top-level `s.trim()` at parse entry silently ate
9265 // the leading space and parsed the value to
9266 // `Duration::from_secs(30)`, which then round-tripped through
9267 // `render` to `"30s"` (a *different* canonical string on the
9268 // next emit) — the exact canonical-form-drift class the
9269 // leading-`+` / leading-zero arms already close, extended
9270 // to the whitespace-byte class. Peer with the sibling
9271 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
9272 // the M3 `:politicas` axis.
9273 let err = duration_codec::parse(" 30s").unwrap_err();
9274 assert!(
9275 err.contains("contains whitespace byte"),
9276 "expected whitespace diagnostic in {err:?}"
9277 );
9278 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
9279 assert!(
9280 err.contains("THEORY.md"),
9281 "missing render-determinism contract citation in {err:?}"
9282 );
9283 }
9284
9285 #[test]
9286 fn parse_rejects_trailing_whitespace() {
9287 // `"30s "` — the canonical shell-history / trailing-space
9288 // paste footgun. Before this gate the top-level `s.trim()`
9289 // silently ate the trailing space and parsed to
9290 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
9291 // next emit — same canonical-form drift as the leading-space
9292 // sibling, closed on the same whitespace-byte arm.
9293 let err = duration_codec::parse("30s ").unwrap_err();
9294 assert!(
9295 err.contains("contains whitespace byte"),
9296 "expected whitespace diagnostic in {err:?}"
9297 );
9298 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
9299 }
9300
9301 #[test]
9302 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
9303 // `"30 s"` — the canonical typographically-spaced author
9304 // shape (the same idiom every prose reference to a duration
9305 // renders as, mistakenly retained when the value is pasted
9306 // into a codec-shaped slot). Before this gate the per-part
9307 // `num_part.trim()` / `unit.trim()` calls silently ate the
9308 // whitespace between the magnitude and the unit and parsed
9309 // the value to `Duration::from_secs(30)`, round-tripping to
9310 // `"30s"` — the codec's *internal* whitespace-tolerance
9311 // vector, orthogonal to the leading / trailing surface but
9312 // the same canonical-form-drift class. Pins the arm as
9313 // strictly stronger than the pre-existing top-level
9314 // `s.trim()` behavior: it fires on whitespace anywhere in
9315 // the value, not just at the string boundary.
9316 let err = duration_codec::parse("30 s").unwrap_err();
9317 assert!(
9318 err.contains("contains whitespace byte"),
9319 "expected whitespace diagnostic in {err:?}"
9320 );
9321 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
9322 }
9323
9324 #[test]
9325 fn parse_rejects_tab_byte() {
9326 // `"\t30s"` — the canonical paste-from-indented-doc /
9327 // paste-from-YAML-block-scalar footgun where a tab byte leads
9328 // the magnitude. Pins that the gate covers tab (`0x09`) as
9329 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
9330 // members and both would be silently swallowed by `s.trim()`
9331 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
9332 // space alone to the full ASCII-whitespace set (space `0x20`,
9333 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
9334 // the tab arm as a representative of the non-space members.
9335 let err = duration_codec::parse("\t30s").unwrap_err();
9336 assert!(
9337 err.contains("contains whitespace byte"),
9338 "expected whitespace diagnostic in {err:?}"
9339 );
9340 assert!(
9341 err.contains("0x09"),
9342 "missing offending tab byte in {err:?}"
9343 );
9344 }
9345
9346 #[test]
9347 fn restart_window_serde_rejects_whitespace() {
9348 // The shared codec backs `SupervisorSpec::restart_window`
9349 // (`with = "duration_codec"`) — so the whitespace arm
9350 // applies on serde deserialize for the typed Supervisor slot.
9351 // A `{"restartWindow":" 30s"}` payload that previously round-
9352 // tripped to a different canonical string on next serialize
9353 // is now refused at deserialize with the whitespace-byte
9354 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
9355 // / `restart_window_serde_rejects_leading_plus` /
9356 // `restart_window_serde_rejects_fractional_seconds` on the
9357 // same canonical-form-drift axis.
9358 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
9359 "restartWindow":" 30s",
9360 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
9361 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
9362 let msg = err.to_string();
9363 assert!(
9364 msg.contains("contains whitespace byte"),
9365 "expected whitespace diagnostic in {msg:?}"
9366 );
9367 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
9368 }
9369
9370 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
9371 //
9372 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
9373 // duration codec — closes the strictly-complementary class the
9374 // byte-scan cannot see, through the lifted
9375 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
9376 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
9377 // and `:politicas :circuit-breaker :window` simultaneously via
9378 // this shared codec.
9379
9380 #[test]
9381 fn duration_codec_parse_rejects_leading_nbsp() {
9382 // NBSP prefix — the strictly-complementary drift class the
9383 // ASCII byte-scan cannot see. `str::trim` strips it silently
9384 // and the value drifts to `"30s"` on next serialize.
9385 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
9386 assert!(
9387 err.contains("non-ASCII Unicode whitespace character"),
9388 "expected non-ASCII whitespace diagnostic in {err:?}"
9389 );
9390 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
9391 }
9392
9393 #[test]
9394 fn duration_codec_parse_rejects_trailing_line_separator() {
9395 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
9396 // footgun.
9397 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
9398 assert!(
9399 err.contains("non-ASCII Unicode whitespace character"),
9400 "expected non-ASCII whitespace diagnostic in {err:?}"
9401 );
9402 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
9403 }
9404
9405 #[test]
9406 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
9407 // Positive-control pin: every ASCII-only canonical form the
9408 // renderer emits stays accepted through the new arm.
9409 assert_eq!(
9410 duration_codec::parse("30s").unwrap(),
9411 Duration::from_secs(30)
9412 );
9413 assert_eq!(
9414 duration_codec::parse("500ms").unwrap(),
9415 Duration::from_millis(500)
9416 );
9417 assert_eq!(
9418 duration_codec::parse("1h").unwrap(),
9419 Duration::from_secs(3600)
9420 );
9421 }
9422
9423 #[test]
9424 fn restart_window_serde_rejects_non_ascii_whitespace() {
9425 // The shared codec backs `SupervisorSpec::restart_window` — so
9426 // the new non-ASCII Unicode whitespace arm applies on serde
9427 // deserialize for the typed Supervisor slot. A
9428 // `{"restartWindow":" 30s"}` payload that previously
9429 // survived the ASCII byte-scan (only ASCII whitespace was
9430 // refused) is now refused at deserialize with the
9431 // non-ASCII-whitespace-and-codepoint diagnostic.
9432 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
9433 \"restartWindow\":\"\u{00A0}30s\",\
9434 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
9435 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
9436 let msg = err.to_string();
9437 assert!(
9438 msg.contains("non-ASCII Unicode whitespace character"),
9439 "expected non-ASCII whitespace diagnostic in {msg:?}"
9440 );
9441 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
9442 }
9443
9444 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
9445
9446 #[test]
9447 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
9448 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
9449 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
9450 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
9451 // name the exact camelCase JSON keys the
9452 // `#[serde(rename_all = "camelCase")]` attribute on
9453 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
9454 // field carries `Some(_)` / non-empty) and pin that each canonical
9455 // byte-sequence appears verbatim in the JSON — a future accidental
9456 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
9457 // name flip at the derive attribute (any of which would silently
9458 // break every downstream JSON consumer that reaches for one of the
9459 // four consts via `Value::get(...)`) surfaces here as a build-time
9460 // test failure at `supervisor.rs`, not as an apply-time
9461 // `.get(<stale-canonical-const>)` returning `None` far from the
9462 // derive-attr drift's commit. Peer with the sibling
9463 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
9464 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
9465 // M2 typed-slot family established, extended here to close the
9466 // top-level Supervisor axis.
9467 let spec = SupervisorSpec {
9468 estrategia: RestartStrategy::OneForOne,
9469 max_restarts: 5,
9470 restart_window: Some(Duration::from_secs(60)),
9471 children: vec![ChildSpec {
9472 caixa: "w".into(),
9473 versao: "^0.1".into(),
9474 restart: RestartPolicy::Permanent,
9475 }],
9476 };
9477 let json = serde_json::to_string(&spec).unwrap();
9478 for key in [
9479 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9480 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9481 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9482 crate::render::SUPERVISOR_KEY_CHILDREN,
9483 ] {
9484 let quoted = format!("\"{key}\"");
9485 assert!(
9486 json.contains("ed),
9487 "serialized SupervisorSpec must carry the lifted \
9488 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
9489 the JSON emission (got: {json})",
9490 );
9491 }
9492 }
9493
9494 #[test]
9495 fn supervisor_key_consts_are_pairwise_distinct() {
9496 // Cross-axis drift-detection pin: a future collapse of two
9497 // canonical top-level byte-strings onto the same value (e.g. an
9498 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
9499 // also read `"estrategia"`) would silently reroute every
9500 // downstream probe on one axis onto the sibling axis's overlay
9501 // entry and pass every propagation-probe test that expected only
9502 // the stale axis's value. Peer of the sibling four-way distinct
9503 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
9504 let all = [
9505 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9506 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9507 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9508 crate::render::SUPERVISOR_KEY_CHILDREN,
9509 ];
9510 for (i, a) in all.iter().enumerate() {
9511 for b in all.iter().skip(i + 1) {
9512 assert_ne!(
9513 a, b,
9514 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
9515 canonical byte-sequences — got `{a}` == `{b}`",
9516 );
9517 }
9518 }
9519 }
9520
9521 #[test]
9522 fn supervisor_key_consts_are_lower_camel_case_shape() {
9523 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
9524 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
9525 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
9526 // capital, no whitespace / dots) — the canonical shape the
9527 // `#[serde(rename_all = "camelCase")]` derive produces on
9528 // `SupervisorSpec`. A future flip to a non-camelCase attribute
9529 // at the derive surfaces both here (this test fails on the
9530 // stale-constant shape) and at
9531 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
9532 // (that test fails on the mismatch between const and derive).
9533 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
9534 // (d8b8b4f) on the sibling M2 `:limits` axis.
9535 for key in [
9536 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9537 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9538 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9539 crate::render::SUPERVISOR_KEY_CHILDREN,
9540 ] {
9541 assert!(
9542 !key.is_empty(),
9543 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
9544 );
9545 let first = key.chars().next().unwrap();
9546 assert!(
9547 first.is_ascii_lowercase(),
9548 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
9549 (got {key:?}, leads with {first:?})",
9550 );
9551 assert!(
9552 key.chars().all(|c| c.is_ascii_alphanumeric()),
9553 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
9554 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
9555 );
9556 }
9557 }
9558
9559 #[test]
9560 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
9561 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
9562 // (camelCase JSON keys, no leading colon) must never collide
9563 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
9564 // consts (kebab-case author-facing labels with leading colon)
9565 // that sit next to them at `caixa_core::render`. Both families
9566 // cover the same four typed Supervisor slots on two distinct
9567 // axes (author-side kebab vs renderer-side camelCase);
9568 // collapsing either family onto the other's byte-shape would
9569 // silently reroute the render-side probe onto the author-facing
9570 // surface, or vice versa. Peer of the byte-distinctness
9571 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
9572 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
9573 let pairs = [
9574 (
9575 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9576 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
9577 ),
9578 (
9579 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9580 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
9581 ),
9582 (
9583 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9584 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
9585 ),
9586 (
9587 crate::render::SUPERVISOR_KEY_CHILDREN,
9588 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
9589 ),
9590 ];
9591 for (json_key, author_key) in pairs {
9592 assert_ne!(
9593 json_key, author_key,
9594 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
9595 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
9596 got JSON `{json_key}` == author `{author_key}`",
9597 );
9598 }
9599 }
9600
9601 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
9602
9603 #[test]
9604 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
9605 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
9606 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
9607 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
9608 // keys the `#[serde(rename_all = "camelCase")]` attribute on
9609 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
9610 // pin that each canonical byte-sequence appears verbatim in the
9611 // JSON — a future accidental `rename_all = "snake_case"` /
9612 // `"kebab-case"` / verbatim-field-name flip at the derive
9613 // attribute (any of which would silently break every downstream
9614 // JSON consumer that reaches for one of the three consts via
9615 // `Value::get(...)`) surfaces here as a build-time test failure at
9616 // `supervisor.rs`, not as an apply-time
9617 // `.get(<stale-canonical-const>)` returning `None` far from the
9618 // derive-attr drift's commit. Peer with the enclosing
9619 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
9620 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
9621 // discipline the SupervisorSpec top-level lift established,
9622 // extended here to the sibling per-`:children` entry `ChildSpec`
9623 // derive so the last M2 typed-struct sub-block
9624 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
9625 // surface without a lifted serde-key peer joins the substrate's
9626 // "one canonical byte-string per typed serialized-key axis"
9627 // discipline.
9628 let c = ChildSpec {
9629 caixa: "worker".into(),
9630 versao: "^0.1".into(),
9631 restart: RestartPolicy::Permanent,
9632 };
9633 let json = serde_json::to_string(&c).unwrap();
9634 for key in [
9635 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
9636 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
9637 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
9638 ] {
9639 let quoted = format!("\"{key}\"");
9640 assert!(
9641 json.contains("ed),
9642 "serialized ChildSpec must carry the lifted \
9643 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
9644 in the JSON emission (got: {json})",
9645 );
9646 }
9647 }
9648
9649 #[test]
9650 fn supervisor_child_key_consts_are_pairwise_distinct() {
9651 // Cross-axis drift-detection pin: a future collapse of two
9652 // canonical `ChildSpec` per-entry byte-strings onto the same
9653 // value (e.g. an accidental copy-paste flip of
9654 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
9655 // silently reroute every downstream probe on one axis onto the
9656 // sibling axis's overlay entry and pass every propagation-probe
9657 // test that expected only the stale axis's value. Peer of the
9658 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
9659 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
9660 // pair (ce80ca0).
9661 let all = [
9662 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
9663 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
9664 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
9665 ];
9666 for (i, a) in all.iter().enumerate() {
9667 for b in all.iter().skip(i + 1) {
9668 assert_ne!(
9669 a, b,
9670 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
9671 distinct canonical byte-sequences — got `{a}` == `{b}`",
9672 );
9673 }
9674 }
9675 }
9676
9677 #[test]
9678 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
9679 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
9680 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
9681 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
9682 // capital, no whitespace / dots) — the canonical shape the
9683 // `#[serde(rename_all = "camelCase")]` derive produces on
9684 // `ChildSpec`. A future flip to a non-camelCase attribute at the
9685 // derive surfaces both here (this test fails on the
9686 // stale-constant shape) and at
9687 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
9688 // (that test fails on the mismatch between const and derive).
9689 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
9690 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
9691 for key in [
9692 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
9693 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
9694 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
9695 ] {
9696 assert!(
9697 !key.is_empty(),
9698 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
9699 );
9700 let first = key.chars().next().unwrap();
9701 assert!(
9702 first.is_ascii_lowercase(),
9703 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
9704 byte (got {key:?}, leads with {first:?})",
9705 );
9706 assert!(
9707 key.chars().all(|c| c.is_ascii_alphanumeric()),
9708 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
9709 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
9710 );
9711 }
9712 }
9713
9714 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
9715
9716 #[test]
9717 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
9718 // The fail-before-pass-after pin: pre-lift there was no
9719 // single-source binding between the [`RestartStrategy`] variant
9720 // name the un-`rename`d `Serialize` derive emits under
9721 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
9722 // every downstream cluster-side dispatcher (the future
9723 // wasm-operator's per-supervisor sibling-restart branch, the
9724 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
9725 // admission-time enum-arm bind, the `caixa-operator`'s
9726 // hierarchical reconciliation scheduler's per-strategy fan-out)
9727 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
9728 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
9729 // override, or a variant rename in the source — would silently
9730 // rebrand the emitted scalar under one spelling while every
9731 // downstream dispatcher still probed the other, with the failure
9732 // surfacing at the operator's reconcile posture (subtrees coming
9733 // up under the `default()` `OneForOne` arm rather than the typed
9734 // slot's declared strategy — a bad child would then only take
9735 // itself down instead of the sibling set the author intended, so
9736 // shared-state children fall out of sync) far from the source
9737 // rebrand commit and with no field naming the drift. Pinning the
9738 // two paths (the `Serialize` derive's serialized string AND the
9739 // [`RestartStrategy::as_str`] helper) to the same four lifted
9740 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
9741 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
9742 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
9743 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
9744 // byte-strings makes any future drift on either endpoint fail
9745 // here at caixa-core build time. Peer of the M3
9746 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
9747 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
9748 // three-path-convergence discipline, extended to close the
9749 // OTP-shaped per-supervisor sibling-restart axis.
9750 for (variant, expected) in [
9751 (
9752 RestartStrategy::OneForOne,
9753 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9754 ),
9755 (
9756 RestartStrategy::OneForAll,
9757 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9758 ),
9759 (
9760 RestartStrategy::RestForOne,
9761 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9762 ),
9763 (
9764 RestartStrategy::SimpleOneForOne,
9765 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9766 ),
9767 ] {
9768 let json = serde_json::to_string(&variant).unwrap();
9769 assert_eq!(
9770 json,
9771 format!("\"{expected}\""),
9772 "RestartStrategy::{variant:?} must serialize to {expected:?}"
9773 );
9774 assert_eq!(
9775 variant.as_str(),
9776 expected,
9777 "RestartStrategy::{variant:?}.as_str() must return the lifted \
9778 SUPERVISOR_ESTRATEGIA_* constant"
9779 );
9780 }
9781 }
9782
9783 #[test]
9784 fn supervisor_estrategia_consts_are_pairwise_distinct() {
9785 // Cross-arm drift-detection pin: a future collapse of two
9786 // canonical variant byte-strings onto the same value (e.g. an
9787 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
9788 // to also read `"OneForOne"`) would silently reroute every
9789 // downstream operator's per-strategy dispatch onto the sibling
9790 // arm's reconcile branch and pass every propagation-probe test
9791 // that expected only the stale arm's value — the mis-strategied
9792 // subtree would come up with the wrong sibling-restart posture
9793 // on every subsequent failure. Peer of the sibling four-way
9794 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
9795 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
9796 let all = [
9797 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9798 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9799 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9800 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9801 ];
9802 for (i, a) in all.iter().enumerate() {
9803 for (j, b) in all.iter().enumerate() {
9804 if i != j {
9805 assert_ne!(
9806 a, b,
9807 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
9808 — got duplicate {a:?} at indices {i} and {j}",
9809 );
9810 }
9811 }
9812 }
9813 }
9814
9815 #[test]
9816 fn restart_strategy_display_routes_through_as_str_helper() {
9817 // The fail-before-pass-after pin on the first half of the
9818 // three-path convergence: pre-convergence the sibling
9819 // OTP-shape typed enum [`RestartStrategy`] carried a
9820 // [`std::fmt::Display`] surface via its
9821 // `#[discriminant(also_display)]` gen-platform derive route,
9822 // which arrived kebab-case as `"one-for-one"` /
9823 // `"one-for-all"` / `"rest-for-one"` /
9824 // `"simple-one-for-one"` while the wire format ran as
9825 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
9826 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
9827 // Every consumer reaching for a strategy byte-string past the
9828 // wire format had to pick between three paths
9829 // ([`RestartStrategy::as_str`], the `Serialize` derive's
9830 // serialized string, or `format!("{v}")` on the
9831 // discriminant-Display route), any two of which a future
9832 // variant rename or `#[serde(rename_all = "kebab-case")]`
9833 // attribute would silently desynchronize. Wiring
9834 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
9835 // closes the third path: every `format!("{v}")` call reaches
9836 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9837 // const the wire format and the [`RestartStrategy::as_str`]
9838 // helper already route through, so a future variant rename
9839 // lands at exactly one place. Pin the routing here so a future
9840 // `impl std::fmt::Display for RestartStrategy`
9841 // reimplementation that hand-rolls the arms instead of
9842 // delegating to [`RestartStrategy::as_str`] fails at
9843 // caixa-core build time. Peer of the M3
9844 // `placement_strategy_display_routes_through_as_str_helper`
9845 // (cc8f749) which the M3 axis converged first.
9846 for &variant in RestartStrategy::ALL {
9847 assert_eq!(
9848 variant.to_string(),
9849 variant.as_str(),
9850 "RestartStrategy::{variant:?} Display must route through \
9851 RestartStrategy::as_str (single source of truth: the lifted \
9852 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
9853 );
9854 }
9855 }
9856
9857 #[test]
9858 fn restart_strategy_display_matches_serialized_wire_byte_string() {
9859 // The fail-before-pass-after pin on the second half of the
9860 // three-path convergence: `Display` (user-facing text) agrees
9861 // byte-for-byte with the `Serialize` derive's wire format
9862 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
9863 // scalar) on every variant. Pre-convergence the two paths
9864 // were structurally independent — a future
9865 // `#[serde(rename_all = "kebab-case")]` attribute on the
9866 // enum would silently rebrand the emitted wire scalar
9867 // (`one-for-one`, `one-for-all`, `rest-for-one`,
9868 // `simple-one-for-one`) while every consumer that
9869 // pretty-prints the strategy (the future wasm-operator's
9870 // per-supervisor sibling-restart-strategy diagnostic line,
9871 // the future `feira app graph` per-supervisor strategy line,
9872 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
9873 // materializer's admission-webhook rejection body) would
9874 // still emit the PascalCase form the `as_str` / `Display`
9875 // route returns, with the mismatch surfacing at consumer
9876 // parse time / operator dispatch time far from the source
9877 // rebrand commit. Pin the two paths byte-for-byte here so any
9878 // future serde-attribute or variant-rename drift is a
9879 // caixa-core-build-time test failure at this call, not a
9880 // silent per-consumer dispatch miss. Peer of the M3
9881 // `placement_strategy_display_matches_serialized_wire_byte_string`
9882 // (cc8f749) which the M3 axis converged first.
9883 for &variant in RestartStrategy::ALL {
9884 let wire = serde_json::to_string(&variant).unwrap();
9885 let unquoted = wire
9886 .strip_prefix('"')
9887 .and_then(|s| s.strip_suffix('"'))
9888 .expect("serialized RestartStrategy is a JSON string");
9889 assert_eq!(
9890 variant.to_string(),
9891 unquoted,
9892 "RestartStrategy::{variant:?} Display byte-string must match the \
9893 Serialize derive's wire byte-string (three-path convergence: \
9894 Display + as_str + Serialize all resolve to the same \
9895 SUPERVISOR_ESTRATEGIA_* const)"
9896 );
9897 }
9898 }
9899
9900 #[test]
9901 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
9902 // Fail-before-pass-after byte-parity pin on the lifted
9903 // `impl AsRef<str> for RestartStrategy` — asserts the
9904 // standard-library trait impl and the substrate-primitive
9905 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
9906 // to the same `&str` per instance across the four-arm
9907 // closed set, so any future silent detour that routes the
9908 // impl through a divergent projection (a per-arm inline
9909 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
9910 // re-inlining that opens a compile-time link to the un-lifted
9911 // arm-literal, a swap onto the kebab-case
9912 // [`gen_platform::Discriminant`] catalog identity that would
9913 // collide the wire axis with the dispatcher-catalog axis) trips
9914 // at caixa-core test time under `PartialEq` rather than at a
9915 // downstream `impl AsRef<str>`-bound consumer's silent split.
9916 // Sweeps every one of the four arms
9917 // [`RestartStrategy::ALL`] carries so no arm's projection is
9918 // covered only by the sibling wire-format `Serialize` derive
9919 // path. Peer of the sibling
9920 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
9921 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
9922 // top-level `:versao` typed newtype — the two pins together
9923 // cover the substrate primitive's `AsRef<str>` projection axis
9924 // on the paired newtype + closed-set-typed-enum surface.
9925 for &variant in RestartStrategy::ALL {
9926 assert_eq!(
9927 <RestartStrategy as AsRef<str>>::as_ref(&variant),
9928 variant.as_str(),
9929 "AsRef<str> impl on RestartStrategy::{variant:?} must \
9930 byte-equal RestartStrategy::as_str on the same instance \
9931 — divergence signals a silent detour off the substrate-\
9932 primitive accessor"
9933 );
9934 }
9935 }
9936
9937 #[test]
9938 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
9939 // Fail-before-pass-after byte-parity pin on the three-path
9940 // convergence discipline the M2 sibling-restart primitive now
9941 // carries on the `&str`-projection axis:
9942 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
9943 // lifted impl), `format!("{s}")` (the pre-existing
9944 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
9945 // primitive `pub const fn` accessor both trait impls delegate
9946 // through) must resolve to the same byte-string on every
9947 // instance across the four-arm closed set. Refuses any future
9948 // divergence between the two trait impls (a stray
9949 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
9950 // rather than delegating through the shared accessor; a
9951 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
9952 // literal cascade) that would silently split the two
9953 // projection paths of the same closed-set typed enum. Mirrors
9954 // the sibling three-path-convergence discipline the peer
9955 // [`crate::CaixaVersion`] typed newtype carries on its
9956 // `AsRef<str>` / `Display` / `as_str` triple
9957 // (version.rs pin
9958 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
9959 // 16d5c7e).
9960 for &variant in RestartStrategy::ALL {
9961 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
9962 let via_display: String = format!("{variant}");
9963 let via_accessor: &str = variant.as_str();
9964 assert_eq!(via_as_ref, via_accessor);
9965 assert_eq!(via_display, via_accessor);
9966 assert_eq!(via_as_ref, via_display.as_str());
9967 }
9968 }
9969
9970 #[test]
9971 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
9972 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
9973 // exhaustive-iteration surface: every variant appears exactly
9974 // once, and the slice length matches the arm count of the
9975 // closed set. Every consumer that walks the accepted-strategy
9976 // set (a future `feira supervisor --estrategia …` CLI-side
9977 // arg-parse's "did you mean" hint, a future M4 admission-
9978 // webhook's rejection body naming the accepted-`:estrategia`
9979 // list, the [`RestartStrategy::from_wire`] reverse-projection
9980 // consumers that iterate the accept-set for diagnostic
9981 // rendering) reads through this slice, so a future arm addition
9982 // that grows the enum but forgets to grow [`Self::ALL`]
9983 // silently truncates every downstream consumer's accept-set at
9984 // the same pre-addition boundary — this pin fails at caixa-core
9985 // build time on the pairwise-distinct + arm-count invariants.
9986 //
9987 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
9988 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
9989 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
9990 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
9991 // pins on the peer closed-set typed-enum axes.
9992 let all: &[RestartStrategy] = RestartStrategy::ALL;
9993 assert_eq!(
9994 all.len(),
9995 4,
9996 "RestartStrategy::ALL must enumerate every variant of the \
9997 four-arm closed set (OneForOne, OneForAll, RestForOne, \
9998 SimpleOneForOne); got {all:?}"
9999 );
10000 for (i, a) in all.iter().enumerate() {
10001 for (j, b) in all.iter().enumerate() {
10002 if i != j {
10003 assert_ne!(
10004 a, b,
10005 "RestartStrategy::ALL must carry every variant exactly \
10006 once — got duplicate {a:?} at indices {i} and {j}"
10007 );
10008 }
10009 }
10010 }
10011 for variant in [
10012 RestartStrategy::OneForOne,
10013 RestartStrategy::OneForAll,
10014 RestartStrategy::RestForOne,
10015 RestartStrategy::SimpleOneForOne,
10016 ] {
10017 assert!(
10018 all.contains(&variant),
10019 "RestartStrategy::ALL must contain {variant:?} — a future arm \
10020 addition that grows the enum but forgets to grow the ALL slice \
10021 silently truncates every downstream consumer's accept-set at \
10022 the pre-addition boundary"
10023 );
10024 }
10025 }
10026
10027 #[test]
10028 fn restart_strategy_wire_names_covers_every_arm() {
10029 // Load-bearing pin on the substrate-canonical
10030 // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
10031 // on the `PascalCase` wire byte-string axis: every variant of
10032 // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
10033 // surface must project through [`RestartStrategy::as_str`] onto
10034 // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
10035 // and the roster's length must byte-equal
10036 // `RestartStrategy::ALL.len()` so a silent skew between the
10037 // [`RestartStrategy::as_str`] match's arm-set and the roster's
10038 // arm-set trips here at caixa-core test time rather than at a
10039 // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
10040 // admission-webhook rejection body's wire-form `:estrategia`
10041 // accepted-set enumeration miss / a `feira supervisor
10042 // --estrategia …` "did you mean" hint drift / a future
10043 // wasm-operator per-reconcile-step diagnostic log line's
10044 // accepted-wire-form enumeration miss. A future arm addition
10045 // (an OTP-`rest_for_all` arm the theory
10046 // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
10047 // might reach for once the four canonical OTP strategies stop
10048 // covering the substrate's discovered load-shape) extends
10049 // [`RestartStrategy::ALL`] as a single edit and this pin
10050 // sweeps the new arm by iteration; the paired
10051 // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
10052 // or this assertion trips. Every entry is further pinned to
10053 // open with an ASCII uppercase byte so a silent collapse of
10054 // the wire-form axis with the peer kebab-case
10055 // dispatcher-catalog axis (an entry byte-identical to a
10056 // sibling [`Self::discriminant`] kebab byte-string that would
10057 // let a wire-axis consumer accept the dispatcher-catalog
10058 // vocabulary) trips here rather than at a downstream K8s-CR
10059 // round-trip miss.
10060 //
10061 // Peer of the sibling
10062 // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
10063 // (bd708bd) pin on the top-level typed-kind discriminator's
10064 // `PascalCase` wire byte-string axis, and of the sibling
10065 // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
10066 // (cc42c0e) /
10067 // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
10068 // (1898d77) pins on the OTP-appup discriminator's two-axis
10069 // roster split — the same closed-set exhaustive-roster
10070 // coverage discipline extended here onto the first M2
10071 // OTP-shape sibling-restart closed-set typed enum.
10072 //
10073 // Fail-before-pass-after locally verified by mutating one arm
10074 // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
10075 // const family (e.g. dropping the trailing `e` from
10076 // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
10077 // but the `contains` check fires on the mutated arm; and by
10078 // shortening the roster to three entries — the length pin
10079 // fires first.
10080 assert_eq!(
10081 RestartStrategy::WIRE_NAMES.len(),
10082 RestartStrategy::ALL.len(),
10083 "RestartStrategy::WIRE_NAMES.len() must byte-equal \
10084 RestartStrategy::ALL.len() — a mismatch means the roster \
10085 and the enum's arm-set have drifted; downstream consumers \
10086 that fan through both will silently disagree on the \
10087 accepted arm-set"
10088 );
10089 for &variant in RestartStrategy::ALL {
10090 let wire = variant.as_str();
10091 assert!(
10092 RestartStrategy::WIRE_NAMES.contains(&wire),
10093 "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
10094 be a member of RestartStrategy::WIRE_NAMES — the \
10095 emitter and the roster have drifted out of lockstep"
10096 );
10097 }
10098 for tag in RestartStrategy::WIRE_NAMES {
10099 let first = tag.chars().next().unwrap_or_else(|| {
10100 panic!(
10101 "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
10102 a non-empty PascalCase byte-string"
10103 )
10104 });
10105 assert!(
10106 first.is_ascii_uppercase(),
10107 "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
10108 with an ASCII uppercase byte (PascalCase wire form) — \
10109 a lowercase entry would collide the wire-form axis \
10110 with the peer kebab-case dispatcher-catalog axis \
10111 [`RestartStrategy::discriminant`] serves"
10112 );
10113 }
10114 }
10115
10116 #[test]
10117 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
10118 // Fail-before-pass-after pin on the forward accept-set of the
10119 // [`RestartStrategy::from_wire`] reverse projection: every
10120 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
10121 // constant the [`RestartStrategy::as_str`] emitter walks parses
10122 // back to its paired variant. Any future arm addition that
10123 // grows the emitter's `as_str` match but forgets to grow the
10124 // parser's `from_wire` match silently splits the two halves of
10125 // the round-trip — the wire byte-string one non-serde consumer
10126 // parses from the one the emitter wrote — with the failure
10127 // surfacing at parse time far from the rebrand commit. Pinning
10128 // the four-arm accept-set here catches the drift at caixa-core
10129 // build time.
10130 //
10131 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
10132 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
10133 // accept-set pins on the peer closed-set typed-enum `str → Self`
10134 // axes.
10135 for (wire, expected) in [
10136 (
10137 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
10138 RestartStrategy::OneForOne,
10139 ),
10140 (
10141 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
10142 RestartStrategy::OneForAll,
10143 ),
10144 (
10145 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
10146 RestartStrategy::RestForOne,
10147 ),
10148 (
10149 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
10150 RestartStrategy::SimpleOneForOne,
10151 ),
10152 ] {
10153 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
10154 panic!(
10155 "RestartStrategy::from_wire({wire:?}) must accept every \
10156 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
10157 lifted canonical byte-string that RestartStrategy::{expected:?} \
10158 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
10159 )
10160 });
10161 assert_eq!(
10162 parsed, expected,
10163 "RestartStrategy::from_wire({wire:?}) must return \
10164 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
10165 );
10166 }
10167 }
10168
10169 #[test]
10170 fn restart_strategy_from_wire_round_trips_through_as_str() {
10171 // Fail-before-pass-after pin on the closed round-trip between
10172 // the forward [`RestartStrategy::as_str`] emitter and the
10173 // reverse [`RestartStrategy::from_wire`] parser: for every
10174 // variant in [`RestartStrategy::ALL`], parsing the emitter's
10175 // output must return exactly the same variant. Any per-arm
10176 // divergence — a future arm added to `as_str` but not
10177 // `from_wire`, an accidental copy-paste flip in one but not
10178 // the other — silently splits the emit and parse halves and
10179 // the failure surfaces at consumer parse time far from the
10180 // drift site. The `ALL`-iterating shape means a future arm
10181 // addition picks up the coverage by construction.
10182 //
10183 // Peer of the sibling
10184 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
10185 // (18c7342) round-trip pin on
10186 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
10187 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
10188 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
10189 for &variant in RestartStrategy::ALL {
10190 let wire = variant.as_str();
10191 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
10192 panic!(
10193 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
10194 must be Some({variant:?}) — the two halves of the round-trip \
10195 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
10196 got None on wire byte-string {wire:?}"
10197 )
10198 });
10199 assert_eq!(
10200 parsed, variant,
10201 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
10202 must round-trip to the same variant; got {parsed:?}"
10203 );
10204 }
10205 }
10206
10207 #[test]
10208 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
10209 // Fail-before-pass-after pin on the closed-set refusal
10210 // discipline of [`RestartStrategy::from_wire`]: every
10211 // byte-string outside the four-arm accept-set returns `None`
10212 // rather than silently collapsing onto the [`Default`]
10213 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
10214 // exercised here sweeps the load-bearing drift shapes: the
10215 // empty string (a stripped serde-attribute drift), all-
10216 // whitespace strings (the canonical text-editor accidental
10217 // padding shape), the kebab-case dispatcher-catalog identities
10218 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
10219 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
10220 // derived [`std::str::FromStr`] accept-set, which parses the
10221 // *other* axis of this enum's two-axis split and must not leak
10222 // into the `from_wire` PascalCase-wire accept-set), the
10223 // lowercased single-word forms (`"oneforone"`), the padded
10224 // canonical scalar (`" OneForOne "`), the trailing-newline
10225 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
10226 // (`"AllForOne"` — the canonical typo direction).
10227 //
10228 // Peer of the sibling
10229 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
10230 // (2aa6d23) +
10231 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
10232 // (18c7342) refusal pins on the peer closed-set typed-enum
10233 // axes.
10234 for bad in [
10235 "",
10236 " ",
10237 "\n",
10238 "\t",
10239 "one-for-one",
10240 "one-for-all",
10241 "rest-for-one",
10242 "simple-one-for-one",
10243 "oneforone",
10244 "OneForOnes",
10245 "one_for_one",
10246 "one for one",
10247 "ONEFORONE",
10248 "OneForOne ",
10249 " OneForOne",
10250 " SimpleOneForOne ",
10251 "OneForOne\n",
10252 "restforone",
10253 "REST_FOR_ONE",
10254 "AllForOne",
10255 "Simple",
10256 "?",
10257 ] {
10258 assert!(
10259 RestartStrategy::from_wire(bad).is_none(),
10260 "RestartStrategy::from_wire({bad:?}) must return None — the \
10261 parser's accept-set is exactly the four RestartStrategy::as_str \
10262 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
10263 and this byte-string is outside that closed set"
10264 );
10265 }
10266 }
10267
10268 #[test]
10269 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
10270 // Fail-before-pass-after pin on the fourth path of the four-path
10271 // convergence: `from_wire` (the reverse projection) inverts the
10272 // `Serialize` derive's wire byte-string on every variant.
10273 // Together with the pre-existing three-path convergence
10274 // (`Display` + `as_str` + `Serialize` all resolve to the same
10275 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
10276 // pinned by
10277 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
10278 // this closes the round-trip: the wire byte-string the
10279 // `Serialize` derive emits parses back to the same variant
10280 // through `from_wire`, so any future serde-attribute or variant-
10281 // rename drift on the emit half now surfaces as a matched drift
10282 // on the parse half at caixa-core build time — the two halves
10283 // migrate as a unit through the lifted consts on any future
10284 // rename, and the round-trip cannot silently split.
10285 //
10286 // Peer of the sibling
10287 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10288 // (18c7342) wire-format pin on
10289 // [`crate::aplicacao::PlacementStrategy::from_wire`].
10290 for &variant in RestartStrategy::ALL {
10291 let wire = serde_json::to_string(&variant).unwrap();
10292 let unquoted = wire
10293 .strip_prefix('"')
10294 .and_then(|s| s.strip_suffix('"'))
10295 .expect("serialized RestartStrategy is a JSON string");
10296 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
10297 panic!(
10298 "RestartStrategy::from_wire({unquoted:?}) must accept the \
10299 Serialize derive's wire byte-string for \
10300 RestartStrategy::{variant:?} — the four-path convergence \
10301 (Display + as_str + Serialize + from_wire) resolves through \
10302 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
10303 )
10304 });
10305 assert_eq!(
10306 parsed, variant,
10307 "RestartStrategy::from_wire of the Serialize derive's wire \
10308 byte-string for RestartStrategy::{variant:?} must round-trip \
10309 to the same variant; got {parsed:?}"
10310 );
10311 }
10312 }
10313
10314 #[test]
10315 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
10316 // Fail-before-pass-after byte-parity pin on the newly lifted
10317 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
10318 // library trait impl and the substrate-primitive
10319 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
10320 // the same four-arm accept-set across every arm the exhaustive
10321 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
10322 // detour that routes the trait impl through a divergent projection
10323 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
10324 // … }` re-inlining that opens a compile-time link to the un-
10325 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
10326 // attribute drift that silently splits the wire byte-string from
10327 // every consumer that reaches for this typed dispatch, an
10328 // accidental swap onto the kebab-case dispatcher-catalog axis the
10329 // pre-existing [`std::str::FromStr`] impl parses through and which
10330 // would collide the two-axis wire/catalog split the sibling
10331 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
10332 // trips at caixa-core test time under `assert_eq!` rather than at
10333 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
10334 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
10335 // carries so no arm's projection is covered only by the sibling
10336 // method-named `from_wire` path. Peer of the sibling
10337 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
10338 // (3c83606),
10339 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
10340 // (bf33136), and the M3
10341 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
10342 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
10343 // onto the first M2-OTP-shape closed-set typed enum on the caixa
10344 // surface.
10345 for &variant in RestartStrategy::ALL {
10346 let wire = variant.as_str();
10347 assert_eq!(
10348 <RestartStrategy as TryFrom<&str>>::try_from(wire),
10349 Ok(variant),
10350 "TryFrom<&str> impl on RestartStrategy must round-trip \
10351 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
10352 Ok(RestartStrategy::{variant:?}) — divergence from \
10353 RestartStrategy::from_wire signals a silent detour off \
10354 the substrate-primitive accessor"
10355 );
10356 assert_eq!(
10357 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
10358 RestartStrategy::from_wire(wire),
10359 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
10360 RestartStrategy::from_wire on the same input"
10361 );
10362 }
10363 }
10364
10365 #[test]
10366 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
10367 // Rejection witness on the `impl TryFrom<&str> for
10368 // RestartStrategy` — sweeps a candidate set of byte-strings
10369 // outside the four-arm PascalCase wire accept-set the sibling
10370 // [`RestartStrategy::as_str`] emits and asserts every one lands on
10371 // `Err(())`, so a future accidental widening of the trait impl's
10372 // accept-set (a stray additional
10373 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
10374 // path, a silent inclusion of the kebab-case dispatcher-catalog
10375 // byte-string the pre-existing [`std::str::FromStr`] impl the
10376 // [`gen_platform::FromStrKind`] derive installs parses onto the
10377 // wire axis — which would collide the two-axis
10378 // wire/dispatcher-catalog split the sibling
10379 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
10380 // an English-rebrand or plural-arm silent alias that would
10381 // widen the wire accept-set past the OTP-canonical four) trips at
10382 // caixa-core test time. The candidate set includes the empty
10383 // string, whitespace-only padding, the kebab-case dispatcher-
10384 // catalog byte-strings on the sibling axis (a caller who confuses
10385 // the two axes trips here rather than at a downstream consumer's
10386 // silent reject), a lowercase / uppercase / mixed-case fold of
10387 // each PascalCase arm (a caller who assumes case-fold acceptance
10388 // trips here), leading/trailing whitespace padding, the trailing-
10389 // newline shape, quote-wrapped candidates, and a residual set of
10390 // plausible-but-wrong English rebrand candidates. Peer of the
10391 // sibling
10392 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
10393 // (3c83606) and
10394 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
10395 // (6fd00cd) rejection witnesses.
10396 let rejected: &[&str] = &[
10397 "",
10398 " ",
10399 "\n",
10400 "\t",
10401 "one-for-one",
10402 "one-for-all",
10403 "rest-for-one",
10404 "simple-one-for-one",
10405 "oneforone",
10406 "one_for_one",
10407 "OneForOnes",
10408 "ONEFORONE",
10409 "oneforall",
10410 "restforone",
10411 "simpleoneforone",
10412 "OneForOne ",
10413 " OneForOne",
10414 " OneForAll ",
10415 "OneForOne\n",
10416 "RestForOne\t",
10417 "OneForEach",
10418 "AllForOne",
10419 "one for one",
10420 "\"OneForOne\"",
10421 "?",
10422 ];
10423 for &input in rejected {
10424 assert_eq!(
10425 <RestartStrategy as TryFrom<&str>>::try_from(input),
10426 Err(()),
10427 "TryFrom<&str> impl on RestartStrategy must reject the \
10428 non-wire byte-string {input:?} — silent acceptance signals \
10429 an accept-set widening off the paired \
10430 RestartStrategy::from_wire resolver"
10431 );
10432 }
10433 }
10434
10435 #[test]
10436 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
10437 // Cross-axis partition pin: the paired `TryFrom<&str>` and
10438 // `from_wire` reverse projections must resolve identically on
10439 // *every* input, not just the ones [`RestartStrategy::ALL`]
10440 // enumerates. Sweeps a mixed candidate set spanning accepted
10441 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
10442 // dispatcher-catalog byte-strings, empty, whitespace-padded,
10443 // quoted, English-rebrand candidates) inputs and asserts the
10444 // trait's `Result::ok()` projection byte-equals the method-named
10445 // resolver's `Option<Self>` return-shape on each, locking the two
10446 // paths together by construction so any future detour (a stray
10447 // `try_from` special-case that widens or narrows the accept-set
10448 // outside the paired `from_wire` resolver, an accidental swap
10449 // onto the kebab-case [`std::str::FromStr`] impl the
10450 // [`gen_platform::FromStrKind`] derive installs on the sibling
10451 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
10452 // the sibling
10453 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
10454 // pin — extends the round-trip discipline onto the M2-OTP-shape
10455 // sibling-restart axis.
10456 let candidates: &[&str] = &[
10457 "OneForOne",
10458 "OneForAll",
10459 "RestForOne",
10460 "SimpleOneForOne",
10461 "",
10462 "one-for-one",
10463 "one-for-all",
10464 "rest-for-one",
10465 "simple-one-for-one",
10466 "oneforone",
10467 "unknown",
10468 "OneForOne ",
10469 " OneForOne",
10470 "\"OneForOne\"",
10471 "OneForEach",
10472 "?",
10473 ];
10474 for &input in candidates {
10475 let via_trait: Option<RestartStrategy> =
10476 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
10477 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
10478 assert_eq!(
10479 via_trait, via_method,
10480 "TryFrom<&str> and from_wire must resolve identically on \
10481 input {input:?} — divergence signals the two reverse-\
10482 projection paths have drifted onto different accept-sets"
10483 );
10484 }
10485 }
10486
10487 #[test]
10488 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
10489 // Fail-before-pass-after byte-parity pin on the newly lifted
10490 // `impl From<RestartStrategy> for &'static str` — asserts the
10491 // standard-library trait impl and the substrate-primitive
10492 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
10493 // the same four-arm emit-set across every arm the exhaustive
10494 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
10495 // detour that routes the trait impl through a divergent
10496 // projection (a per-arm inline `match strategy { OneForOne =>
10497 // "OneForOne", … }` re-inlining that opens a compile-time link to
10498 // the un-lifted arm-literal, an accidental swap onto the sibling
10499 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
10500 // would collide the two-axis wire/catalog split the sibling
10501 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
10502 // at caixa-core test time under `assert_eq!` rather than at a
10503 // downstream `impl Into<&'static str>`-bound consumer's silent
10504 // split. Sweeps every one of the four arms
10505 // [`RestartStrategy::ALL`] carries so no arm's projection is
10506 // covered only by the sibling method-named `as_str` /
10507 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
10508 // `<&'static str as From<RestartStrategy>>::from` output in a
10509 // `const`-shape binding to make the `'static` lifetime promise a
10510 // build-time invariant — a future accidental downgrade of any of
10511 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
10512 // constants to a non-`&'static str` (a `String::leak()`-produced
10513 // return, a `Box::leak`-cast) trips at caixa-core build time
10514 // rather than at a downstream `'static`-bound consumer.
10515 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
10516 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
10517 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
10518 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
10519 for &variant in RestartStrategy::ALL {
10520 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10521 let via_method: &'static str = variant.as_str();
10522 assert_eq!(
10523 via_trait, via_method,
10524 "From<RestartStrategy> for &'static str impl must round-trip \
10525 RestartStrategy::{variant:?} to the same lifted \
10526 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
10527 divergence signals a silent detour off the substrate-primitive \
10528 accessor"
10529 );
10530 let via_into: &'static str = variant.into();
10531 assert_eq!(
10532 via_into, via_method,
10533 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
10534 byte-equal RestartStrategy::as_str on the same input — the \
10535 blanket-derived Into shape must resolve to the same as_str \
10536 dispatch as the explicit From impl"
10537 );
10538 }
10539 assert_eq!(
10540 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
10541 [
10542 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
10543 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
10544 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
10545 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
10546 ],
10547 "const-context RestartStrategy::as_str must resolve to the four \
10548 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
10549 downgrade of any arm to a non-const or non-static byte-string \
10550 breaks the `&'static str`-lifetime promise the paired \
10551 From<RestartStrategy> for &'static str impl carries by \
10552 construction"
10553 );
10554 }
10555
10556 #[test]
10557 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
10558 // Cross-axis partition pin: the paired trait-idiomatic
10559 // `From<RestartStrategy> for &'static str` forward projection and
10560 // the method-named [`RestartStrategy::as_str`] forward projection
10561 // must resolve identically on *every* arm, not just the ones
10562 // named in the primary byte-parity pin above. Sweeps every
10563 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
10564 // output byte-equals the method-named accessor's return-value on
10565 // each, locking the two forward-projection paths together by
10566 // construction so any future detour (a stray `From` special-case
10567 // that lands on a divergent per-arm literal outside the paired
10568 // `as_str` dispatch, a hypothetical rebrand touching one axis
10569 // without the other) trips at caixa-core test time. Peer of the
10570 // sibling reverse-projection partition pin
10571 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
10572 // — extends the round-trip discipline onto the trait-idiomatic
10573 // *forward* axis, closing the two-way `Self ↔ &'static str`
10574 // round-trip on the trait-idiomatic pair
10575 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
10576 // well as the pre-existing method-named pair
10577 // (`as_str` + `from_wire`).
10578 for &variant in RestartStrategy::ALL {
10579 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10580 let via_method: &'static str = variant.as_str();
10581 assert_eq!(
10582 via_trait, via_method,
10583 "From<RestartStrategy> for &'static str and \
10584 RestartStrategy::as_str must resolve identically on \
10585 RestartStrategy::{variant:?} — divergence signals the \
10586 two forward-projection paths have drifted onto different \
10587 emit-sets"
10588 );
10589 }
10590 // Round-trip witness: every arm's forward `From` output re-parses
10591 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10592 // to the original variant. Closes the two-way `RestartStrategy ↔
10593 // &'static str` round-trip on the trait-idiomatic axis pair,
10594 // mirroring the pre-existing method-named `as_str` + `from_wire`
10595 // round-trip on the substrate-primitive axis pair.
10596 for &variant in RestartStrategy::ALL {
10597 let emitted: &'static str = variant.into();
10598 let re_parsed: Result<RestartStrategy, ()> =
10599 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
10600 assert_eq!(
10601 re_parsed,
10602 Ok(variant),
10603 "trait-idiomatic axis pair must round-trip \
10604 RestartStrategy::{variant:?} through `.into::<&'static \
10605 str>()` and back through `TryFrom<&str>` — a break signals \
10606 the forward-emit and reverse-parse axes have drifted onto \
10607 different vocabularies"
10608 );
10609 }
10610 }
10611
10612 #[test]
10613 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10614 // Fail-before-pass-after byte-parity pin on the newly lifted
10615 // `impl From<&RestartStrategy> for &'static str` — asserts the
10616 // borrowed-input standard-library trait impl and the substrate-
10617 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
10618 // resolve to the same four-arm emit-set across every arm the
10619 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
10620 // `From` trait does not auto-derive the borrowed-input sibling
10621 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10622 // where T: Copy, U: From<T>` blanket in `core`), so the
10623 // borrowed-input axis is a distinct trait-idiomatic surface
10624 // that a `.iter().map(Into::into)` shape over
10625 // [`RestartStrategy::ALL`] (whose iterator yields
10626 // `&RestartStrategy`, not `RestartStrategy`) reaches through
10627 // this impl and no other — the paired owned-input
10628 // [`From<RestartStrategy>`] impl requires an explicit
10629 // `.copied()` / dereference before the trait fires.
10630 // Materializes the `<&'static str as
10631 // From<&RestartStrategy>>::from` output in a `const`-shape
10632 // binding to make the `'static` lifetime promise a build-time
10633 // invariant.
10634 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
10635 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
10636 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
10637 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
10638 for variant in RestartStrategy::ALL {
10639 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
10640 let via_method: &'static str = variant.as_str();
10641 assert_eq!(
10642 via_trait, via_method,
10643 "From<&RestartStrategy> for &'static str impl must \
10644 round-trip &RestartStrategy::{variant:?} to the same \
10645 lifted SUPERVISOR_ESTRATEGIA_* const \
10646 RestartStrategy::as_str returns — divergence signals a \
10647 silent detour off the substrate-primitive accessor"
10648 );
10649 let via_into: &'static str = variant.into();
10650 assert_eq!(
10651 via_into, via_method,
10652 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
10653 must byte-equal RestartStrategy::as_str on the same input — \
10654 the blanket-derived Into shape must resolve to the same \
10655 as_str dispatch as the explicit From impl"
10656 );
10657 }
10658 assert_eq!(
10659 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
10660 [
10661 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
10662 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
10663 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
10664 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
10665 ],
10666 "const-context RestartStrategy::as_str must resolve to the \
10667 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
10668 input From<&RestartStrategy> for &'static str impl inherits \
10669 its `'static` lifetime promise from the same accessor the \
10670 owned-input sibling routes through"
10671 );
10672 }
10673
10674 #[test]
10675 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10676 // Cross-axis partition pin: the paired trait-idiomatic
10677 // owned-input `From<RestartStrategy> for &'static str` (523157d
10678 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
10679 // &'static str` (this lift) forward projections must resolve
10680 // identically on every arm, locking the two input-shape paths
10681 // together so any future detour trips at caixa-core test time.
10682 // Then a witness that a `.iter().map(Into::into)` pipe over
10683 // [`RestartStrategy::ALL`] (whose iterator yields
10684 // `&RestartStrategy`) materializes the four-arm accept-set
10685 // through the borrowed-input axis alone — the exact shape a
10686 // future wasm-operator per-supervisor sibling-restart-strategy
10687 // diagnostic line, a future substrate-wide per-arm diagnostic
10688 // column, or a
10689 // `HashMap::<&'static str, RestartStrategy>::from_iter(
10690 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
10691 // per-strategy lookup reaches through — closing the two-way
10692 // owned/borrowed input-shape symmetry on the forward-projection
10693 // trait-idiomatic axis. Peer of the sibling
10694 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10695 // (64aa742) /
10696 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10697 // (5ab993a) /
10698 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10699 // (807b0b5) partition pins on the sibling closed-set typed-enum
10700 // discriminator axes — extends the borrowed-input axis
10701 // discipline onto the first M2 OTP-shape sibling-restart
10702 // closed-set typed enum on the caixa surface. Also closes the
10703 // direct two-way `&Self → &'static str → Self` round-trip via
10704 // the paired [`TryFrom<&str>`] axis — unlike the peer
10705 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
10706 // lowercase Portuguese diagnostic bytes while the reverse
10707 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
10708 // trip through an intermediate wire-vocab hop), the
10709 // [`RestartStrategy::as_str`] emit and
10710 // [`RestartStrategy::from_wire`] parse share the same
10711 // `PascalCase` vocabulary by construction, so the borrowed-
10712 // input forward axis and the reverse axis compose directly.
10713 for &variant in RestartStrategy::ALL {
10714 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10715 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
10716 assert_eq!(
10717 owned, borrowed,
10718 "From<RestartStrategy> and From<&RestartStrategy> for \
10719 &'static str must resolve identically on \
10720 RestartStrategy::{variant:?} — divergence signals the \
10721 owned-input and borrowed-input forward-projection paths \
10722 have drifted onto different emit-sets"
10723 );
10724 }
10725 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
10726 let via_method: Vec<&'static str> =
10727 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
10728 assert_eq!(
10729 via_iter, via_method,
10730 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
10731 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
10732 borrowed-input `From<&RestartStrategy> for &'static str` \
10733 axis is what makes the `.iter().map(Into::into)` shape route \
10734 through the substrate-primitive `RestartStrategy::as_str` \
10735 accessor rather than through a per-call-site `.copied()` / \
10736 dereference detour"
10737 );
10738 for variant in RestartStrategy::ALL {
10739 let emitted: &'static str = variant.into();
10740 let re_parsed: Result<RestartStrategy, ()> =
10741 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
10742 assert_eq!(
10743 re_parsed,
10744 Ok(*variant),
10745 "trait-idiomatic borrowed-input forward-projection + \
10746 reverse-projection axis pair must round-trip \
10747 &RestartStrategy::{variant:?} through `.into::<&'static \
10748 str>()` (via the borrowed-input axis) and back through \
10749 `TryFrom<&str>` — a break signals the borrowed-input \
10750 forward-emit and reverse-parse axes have drifted onto \
10751 different vocabularies"
10752 );
10753 }
10754 }
10755
10756 #[test]
10757 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
10758 // Fail-before-pass-after byte-parity pin on the newly lifted
10759 // `impl From<RestartStrategy> for String` — asserts the
10760 // owned-`String`-returning standard-library trait impl and the
10761 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
10762 // accessor resolve to the same four-arm emit-set across every
10763 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
10764 // Rust's standard library does not carry a blanket
10765 // `impl<T: AsRef<str>> From<T> for String` (nor an
10766 // `impl<T: fmt::Display> From<T> for String`), so the
10767 // owned-`String` forward-projection axis is a distinct
10768 // trait-idiomatic surface that a
10769 // `let key: String = strategy.into();`-shaped call site
10770 // reaches through this impl and no other — the paired sibling
10771 // `From<RestartStrategy> for &'static str` impl forces every
10772 // owned-`String` call site through an explicit
10773 // `.to_owned()` / `String::from` restatement.
10774 for &variant in RestartStrategy::ALL {
10775 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
10776 let via_method: &'static str = variant.as_str();
10777 assert_eq!(
10778 via_trait.as_str(),
10779 via_method,
10780 "From<RestartStrategy> for String impl must round-trip \
10781 RestartStrategy::{variant:?} to the same lifted \
10782 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10783 returns — divergence signals a silent detour off the \
10784 substrate-primitive accessor"
10785 );
10786 let via_into: String = variant.into();
10787 assert_eq!(
10788 via_into.as_str(),
10789 via_method,
10790 "Into<String>::into on RestartStrategy::{variant:?} must \
10791 byte-equal RestartStrategy::as_str on the same input — the \
10792 blanket-derived Into shape must resolve to the same as_str \
10793 dispatch as the explicit From impl"
10794 );
10795 }
10796 }
10797
10798 #[test]
10799 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10800 // Cross-axis partition pin: the paired trait-idiomatic
10801 // owned-`String` `From<RestartStrategy> for String` (this lift)
10802 // and owned-`&'static str` `From<RestartStrategy> for &'static
10803 // str` (523157d) forward projections must resolve identically
10804 // on every arm, locking the two return-type-shape paths
10805 // together so any future detour trips at caixa-core test time.
10806 // Also byte-parity witness against the sibling
10807 // [`ToString::to_string`] surface routed through
10808 // [`std::fmt::Display`] — the three owned-heap-string paths
10809 // (`.into::<String>()`, `String::from`, `.to_string()`) must
10810 // resolve identically on every arm so a future consumer that
10811 // picks any of the three lands on the same lifted
10812 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
10813 // witness through the paired trait-idiomatic reverse
10814 // [`TryFrom<&str>`] axis on the owned-`String`'s
10815 // [`String::as_str`] borrow that closes the two-way
10816 // `Self → String → Self` round-trip on the trait-idiomatic
10817 // owned-`String` forward + reverse axis pair.
10818 for &variant in RestartStrategy::ALL {
10819 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10820 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10821 assert_eq!(
10822 owned_string.as_str(),
10823 owned_static,
10824 "From<RestartStrategy> for String and From<RestartStrategy> \
10825 for &'static str must resolve identically on \
10826 RestartStrategy::{variant:?} — divergence signals the \
10827 owned-`String` and owned-`&'static str` forward-projection \
10828 return-type-shape paths have drifted onto different \
10829 emit-sets"
10830 );
10831 let via_to_string: String = variant.to_string();
10832 assert_eq!(
10833 owned_string, via_to_string,
10834 "From<RestartStrategy> for String must byte-equal \
10835 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
10836 divergence signals the trait-idiomatic owned-`String` \
10837 forward-projection axis and the ToString-through-Display \
10838 axis have drifted onto different emit-sets"
10839 );
10840 }
10841 let via_iter: Vec<String> = RestartStrategy::ALL
10842 .iter()
10843 .copied()
10844 .map(String::from)
10845 .collect();
10846 let via_method: Vec<String> = RestartStrategy::ALL
10847 .iter()
10848 .map(|s| s.as_str().to_owned())
10849 .collect();
10850 assert_eq!(
10851 via_iter, via_method,
10852 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
10853 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
10854 every arm — the owned-`String` `From<RestartStrategy> for \
10855 String` axis is what makes the `String::from` composition \
10856 route through the substrate-primitive `RestartStrategy::as_str` \
10857 accessor rather than through a per-call-site `.to_owned()` / \
10858 `String::from(strategy.as_str())` detour"
10859 );
10860 for &variant in RestartStrategy::ALL {
10861 let emitted: String = variant.into();
10862 let re_parsed: Result<RestartStrategy, ()> =
10863 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
10864 assert_eq!(
10865 re_parsed,
10866 Ok(variant),
10867 "trait-idiomatic owned-`String` forward-projection + \
10868 reverse-projection axis pair must round-trip \
10869 RestartStrategy::{variant:?} through `.into::<String>()` \
10870 and back through `TryFrom<&str>` on the owned-`String`'s \
10871 String::as_str borrow — a break signals the owned-`String` \
10872 forward-emit and reverse-parse axes have drifted onto \
10873 different vocabularies"
10874 );
10875 }
10876 }
10877
10878 #[test]
10879 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10880 // Fail-before-pass-after byte-parity pin on the newly lifted
10881 // `impl From<&RestartStrategy> for String` — asserts the
10882 // borrowed-input owned-`String`-returning standard-library trait
10883 // impl and the substrate-primitive [`RestartStrategy::as_str`]
10884 // `pub const fn` accessor resolve to the same four-arm emit-set
10885 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
10886 // enumerates. Rust's standard library does not carry a blanket
10887 // `impl<T: AsRef<str>> From<&T> for String` (nor an
10888 // `impl<T: fmt::Display> From<&T> for String`), so the
10889 // borrowed-input owned-`String` forward-projection axis is a
10890 // distinct trait-idiomatic surface that a
10891 // `let key: String = (&strategy).into();`-shaped call site
10892 // reaches through this impl and no other — the paired sibling
10893 // `From<RestartStrategy> for String` impl forces every
10894 // borrowed-input call site through an explicit `Copy` deref
10895 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
10896 // `.to_string()` detour.
10897 for &variant in RestartStrategy::ALL {
10898 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
10899 let via_method: &'static str = variant.as_str();
10900 assert_eq!(
10901 via_trait.as_str(),
10902 via_method,
10903 "From<&RestartStrategy> for String impl must round-trip \
10904 &RestartStrategy::{variant:?} to the same lifted \
10905 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10906 returns — divergence signals a silent detour off the \
10907 substrate-primitive accessor"
10908 );
10909 let via_into: String = (&variant).into();
10910 assert_eq!(
10911 via_into.as_str(),
10912 via_method,
10913 "Into<String>::into on &RestartStrategy::{variant:?} must \
10914 byte-equal RestartStrategy::as_str on the same input — the \
10915 blanket-derived Into shape must resolve to the same as_str \
10916 dispatch as the explicit From impl"
10917 );
10918 }
10919 }
10920
10921 #[test]
10922 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10923 // Cross-axis partition pin: the newly lifted trait-idiomatic
10924 // borrowed-input owned-`String` `From<&RestartStrategy> for
10925 // String` (this lift), the paired owned-input owned-`String`
10926 // `From<RestartStrategy> for String` (7baa18a), the paired
10927 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
10928 // for &'static str` (e941836), and the paired owned-input
10929 // owned-`&'static str` `From<RestartStrategy> for &'static str`
10930 // (523157d) — every corner of the `{Self, &Self} × {&'static
10931 // str, String}` 2×2 trait-idiomatic projection family — must
10932 // resolve identically on every arm, locking the four
10933 // return-shape × input-shape paths together so any future
10934 // detour trips at caixa-core test time. Also byte-parity
10935 // witness against the sibling [`ToString::to_string`] surface
10936 // routed through [`std::fmt::Display`] and a direct round-trip
10937 // witness through the paired trait-idiomatic reverse
10938 // [`TryFrom<&str>`] axis on the owned-`String`'s
10939 // [`String::as_str`] borrow that closes the two-way
10940 // `&Self → String → Self` round-trip on the trait-idiomatic
10941 // borrowed-input owned-`String` forward + reverse axis pair.
10942 for &variant in RestartStrategy::ALL {
10943 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10944 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10945 let borrowed_static: &'static str =
10946 <&'static str as From<&RestartStrategy>>::from(&variant);
10947 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10948 assert_eq!(
10949 borrowed_string, owned_string,
10950 "From<&RestartStrategy> for String and From<RestartStrategy> \
10951 for String must resolve identically on \
10952 RestartStrategy::{variant:?} — divergence signals the \
10953 borrowed-input and owned-input owned-`String` \
10954 forward-projection input-shape paths have drifted onto \
10955 different emit-sets"
10956 );
10957 assert_eq!(
10958 borrowed_string.as_str(),
10959 borrowed_static,
10960 "From<&RestartStrategy> for String and From<&RestartStrategy> \
10961 for &'static str must resolve identically on \
10962 RestartStrategy::{variant:?} — divergence signals the \
10963 borrowed-input `&'static str` and owned-`String` \
10964 return-shape paths have drifted onto different emit-sets"
10965 );
10966 assert_eq!(
10967 borrowed_string.as_str(),
10968 owned_static,
10969 "From<&RestartStrategy> for String and From<RestartStrategy> \
10970 for &'static str must resolve identically on \
10971 RestartStrategy::{variant:?} — divergence signals a break \
10972 in the diagonal corner of the {{Self, &Self}} × \
10973 {{&'static str, String}} 2×2 trait-idiomatic \
10974 projection family"
10975 );
10976 let via_to_string: String = variant.to_string();
10977 assert_eq!(
10978 borrowed_string, via_to_string,
10979 "From<&RestartStrategy> for String must byte-equal \
10980 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
10981 divergence signals the trait-idiomatic borrowed-input \
10982 owned-`String` forward-projection axis and the \
10983 ToString-through-Display axis have drifted onto different \
10984 emit-sets"
10985 );
10986 }
10987 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
10988 let via_method: Vec<String> = RestartStrategy::ALL
10989 .iter()
10990 .map(|s| s.as_str().to_owned())
10991 .collect();
10992 assert_eq!(
10993 via_iter, via_method,
10994 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
10995 call site whose iteration axis holds `&RestartStrategy` by \
10996 construction — must byte-equal `.iter().map(|s| \
10997 s.as_str().to_owned())` on every arm — the borrowed-input \
10998 owned-`String` `From<&RestartStrategy> for String` axis is \
10999 what makes the `String::from` composition route through the \
11000 substrate-primitive `RestartStrategy::as_str` accessor \
11001 without a spurious `Copy` deref (which would only be \
11002 reachable through the owned-input `From<RestartStrategy> for \
11003 String` axis by first calling `.copied()` on the iterator)"
11004 );
11005 for &variant in RestartStrategy::ALL {
11006 let emitted: String = (&variant).into();
11007 let re_parsed: Result<RestartStrategy, ()> =
11008 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
11009 assert_eq!(
11010 re_parsed,
11011 Ok(variant),
11012 "trait-idiomatic borrowed-input owned-`String` \
11013 forward-projection + reverse-projection axis pair must \
11014 round-trip &RestartStrategy::{variant:?} through \
11015 `.into::<String>()` on the borrowed-input surface and \
11016 back through `TryFrom<&str>` on the owned-`String`'s \
11017 String::as_str borrow — a break signals the \
11018 borrowed-input owned-`String` forward-emit and \
11019 reverse-parse axes have drifted onto different \
11020 vocabularies"
11021 );
11022 }
11023 }
11024
11025 #[test]
11026 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
11027 // Fail-before-pass-after byte-parity pin on the newly lifted
11028 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
11029 // asserts the standard-library trait impl and the substrate-
11030 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
11031 // accessor resolve to the same four-arm emit-set across every
11032 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
11033 // enumerates. Rust's standard library does not carry a blanket
11034 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
11035 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
11036 // the `Cow<'static, str>` forward-projection axis is a
11037 // distinct trait-idiomatic surface that a
11038 // `let key: Cow<'static, str> = strategy.into();`-shaped call
11039 // site reaches through this impl and no other — the paired
11040 // sibling `From<RestartStrategy> for &'static str` and
11041 // `From<RestartStrategy> for String` impls force every
11042 // `Cow<'static, str>`-parameterized call site through a
11043 // `Cow::Borrowed(strategy.as_str())` /
11044 // `Cow::Owned(strategy.to_string())` composition whose type
11045 // bounds have no compile-time link back to the substrate
11046 // primitive.
11047 //
11048 // Also asserts the projection lands on the zero-alloc
11049 // [`std::borrow::Cow::Borrowed`] arm (not the
11050 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11051 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
11052 // return lifetime by construction makes the borrowed arm the
11053 // type-correct projection with no runtime allocation. Any
11054 // future silent detour that routes the impl through the owned
11055 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
11056 // that would allocate on every call site where the
11057 // `&'static str` return of [`super::RestartStrategy::as_str`]
11058 // makes the zero-alloc borrowed projection type-correct) trips
11059 // at caixa-core test time under the
11060 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
11061 // than at a downstream `Cow<'static, str>`-bound consumer's
11062 // silent allocation.
11063 //
11064 // First peer on the substrate-wide trait-idiomatic
11065 // [`std::borrow::Cow<'static, str>`] forward-projection family
11066 // to extend the axis off the top-level [`super::CaixaKind`]
11067 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
11068 // first M2 OTP-shape closed-set fieldless typed enum on the
11069 // caixa surface.
11070 for &variant in RestartStrategy::ALL {
11071 let via_trait: std::borrow::Cow<'static, str> =
11072 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11073 let via_method: &'static str = variant.as_str();
11074 assert_eq!(
11075 via_trait.as_ref(),
11076 via_method,
11077 "From<RestartStrategy> for Cow<'static, str> impl must \
11078 round-trip RestartStrategy::{variant:?} to the same \
11079 lifted SUPERVISOR_ESTRATEGIA_* const \
11080 RestartStrategy::as_str returns — divergence signals a \
11081 silent detour off the substrate-primitive accessor"
11082 );
11083 assert!(
11084 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11085 "From<RestartStrategy> for Cow<'static, str> impl must \
11086 land on the zero-alloc Cow::Borrowed arm on \
11087 RestartStrategy::{variant:?} — a Cow::Owned outcome \
11088 signals the projection has silently allocated where \
11089 the substrate-primitive RestartStrategy::as_str \
11090 `&'static str` return makes the borrowed arm the \
11091 type-correct projection"
11092 );
11093 let via_into: std::borrow::Cow<'static, str> = variant.into();
11094 assert_eq!(
11095 via_into.as_ref(),
11096 via_method,
11097 "Into<Cow<'static, str>>::into on \
11098 RestartStrategy::{variant:?} must byte-equal \
11099 RestartStrategy::as_str on the same input — the \
11100 blanket-derived Into shape must resolve to the same \
11101 as_str dispatch as the explicit From impl"
11102 );
11103 assert!(
11104 matches!(via_into, std::borrow::Cow::Borrowed(_)),
11105 "Into<Cow<'static, str>>::into on \
11106 RestartStrategy::{variant:?} must land on the \
11107 zero-alloc Cow::Borrowed arm — the blanket-derived \
11108 Into shape must resolve to the same Cow::Borrowed \
11109 dispatch as the explicit From impl"
11110 );
11111 }
11112 }
11113
11114 #[test]
11115 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11116 // Cross-axis partition pin: the newly lifted trait-idiomatic
11117 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
11118 // (this lift), the paired owned-input `From<RestartStrategy>
11119 // for &'static str` (523157d), and the paired owned-input
11120 // `From<RestartStrategy> for String` (7baa18a) forward
11121 // projections must resolve identically on every arm, locking
11122 // the three return-shape paths together by construction so any
11123 // future detour trips at caixa-core test time. Also byte-parity
11124 // witness against the sibling [`ToString::to_string`] surface
11125 // routed through [`std::fmt::Display`] — every owned-heap-
11126 // string path (the `Cow::Owned` promotion of this axis's
11127 // `.into_owned()`, `From<RestartStrategy> for String`, and
11128 // `.to_string()`) resolves to the same lifted
11129 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
11130 //
11131 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
11132 // witness over [`super::RestartStrategy::ALL`] that
11133 // materializes the four-arm accept-set through the
11134 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
11135 // shape a future `axum::response::IntoResponse` per-strategy
11136 // rejection-body composer, a future M4 admission-webhook
11137 // per-strategy rejection-reason emitter whose typing rules out
11138 // the sibling [`AsRef<str>`] borrowed return, or a future
11139 // substrate-wide per-strategy diagnostic surface that binds
11140 // through a [`Cow<'static, str>`] boundary reaches through.
11141 // The pipe witness also pins the zero-alloc discipline: every
11142 // element in the collected vector satisfies the
11143 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
11144 // accidental silent-allocation regression on the pipe's
11145 // iteration axis is a caixa-core-test-time failure.
11146 for &variant in RestartStrategy::ALL {
11147 let via_cow: std::borrow::Cow<'static, str> =
11148 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11149 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
11150 let via_string: String = <String as From<RestartStrategy>>::from(variant);
11151 assert_eq!(
11152 via_cow.as_ref(),
11153 via_static,
11154 "From<RestartStrategy> for Cow<'static, str> and \
11155 From<RestartStrategy> for &'static str must resolve \
11156 identically on RestartStrategy::{variant:?} — \
11157 divergence signals the Cow<'static, str> and \
11158 &'static str return-shape paths have drifted onto \
11159 different emit-sets"
11160 );
11161 assert_eq!(
11162 via_cow.as_ref(),
11163 via_string.as_str(),
11164 "From<RestartStrategy> for Cow<'static, str> and \
11165 From<RestartStrategy> for String must resolve \
11166 identically on RestartStrategy::{variant:?} — \
11167 divergence signals the Cow<'static, str> and String \
11168 return-shape paths have drifted onto different \
11169 emit-sets"
11170 );
11171 let via_to_string: String = variant.to_string();
11172 assert_eq!(
11173 via_cow.as_ref(),
11174 via_to_string.as_str(),
11175 "From<RestartStrategy> for Cow<'static, str> must \
11176 byte-equal RestartStrategy::to_string on \
11177 RestartStrategy::{variant:?} — divergence signals the \
11178 trait-idiomatic Cow<'static, str> forward-projection \
11179 axis and the ToString-through-Display axis have \
11180 drifted onto different emit-sets"
11181 );
11182 }
11183 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
11184 .iter()
11185 .copied()
11186 .map(std::borrow::Cow::from)
11187 .collect();
11188 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
11189 .iter()
11190 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
11191 .collect();
11192 assert_eq!(
11193 via_iter, via_method,
11194 "`.iter().copied().map(Cow::from)` over \
11195 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
11196 Cow::Borrowed(s.as_str()))` on every arm — the \
11197 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
11198 str>` axis is what makes the `Cow::from` composition \
11199 route through the substrate-primitive \
11200 `RestartStrategy::as_str` accessor with the zero-alloc \
11201 Cow::Borrowed arm by construction, rather than a \
11202 per-call-site `Cow::Owned(strategy.to_string())` \
11203 allocation"
11204 );
11205 for cow in &via_iter {
11206 assert!(
11207 matches!(cow, std::borrow::Cow::Borrowed(_)),
11208 "every element of the \
11209 .iter().copied().map(Cow::from) pipe over \
11210 RestartStrategy::ALL must land on the zero-alloc \
11211 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
11212 signals the pipe's iteration axis has silently \
11213 allocated where the substrate-primitive \
11214 RestartStrategy::as_str `&'static str` return makes \
11215 the borrowed arm the type-correct projection"
11216 );
11217 }
11218 }
11219
11220 #[test]
11221 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
11222 // Fail-before-pass-after byte-parity pin on the newly lifted
11223 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
11224 // asserts the borrowed-input standard-library trait impl and
11225 // the substrate-primitive [`super::RestartStrategy::as_str`]
11226 // `pub const fn` accessor resolve to the same four-arm emit-
11227 // set across every arm the exhaustive
11228 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
11229 // standard library does not carry a blanket
11230 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
11231 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
11232 // the borrowed-input `Cow<'static, str>` forward-projection
11233 // axis is a distinct trait-idiomatic surface that a
11234 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
11235 // call site or a
11236 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
11237 // reaches through this impl and no other — the paired owned-
11238 // input `From<RestartStrategy> for Cow<'static, str>` impl
11239 // (7dd28b3) forces every borrowed-input call site through an
11240 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
11241 // `Cow::Borrowed(strategy.as_str())` open-code whose type
11242 // bounds have no compile-time link back to the substrate
11243 // primitive.
11244 //
11245 // Also asserts the projection lands on the zero-alloc
11246 // [`std::borrow::Cow::Borrowed`] arm (not the
11247 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11248 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
11249 // return lifetime by construction makes the borrowed arm the
11250 // type-correct projection with no runtime allocation on the
11251 // borrowed-input surface just as on the paired owned-input
11252 // surface.
11253 //
11254 // Second peer on the substrate-wide trait-idiomatic
11255 // [`std::borrow::Cow<'static, str>`] forward-projection family
11256 // on this enum — closes the `{Self, &Self}` input-shape
11257 // corner of the [`Cow<'static, str>`] axis on the first M2
11258 // OTP-shape closed-set fieldless typed enum peer on the caixa
11259 // surface (`:supervisor :estrategia`), exactly as d45c409
11260 // closed it on the top-level [`super::CaixaKind`] one commit
11261 // after the owning half (99c1735) landed. Every future
11262 // closed-set fieldless typed enum peer on the substrate is a
11263 // future target of the campaign.
11264 for &variant in RestartStrategy::ALL {
11265 let via_trait: std::borrow::Cow<'static, str> =
11266 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
11267 let via_method: &'static str = variant.as_str();
11268 assert_eq!(
11269 via_trait.as_ref(),
11270 via_method,
11271 "From<&RestartStrategy> for Cow<'static, str> impl must \
11272 round-trip &RestartStrategy::{variant:?} to the same \
11273 lifted SUPERVISOR_ESTRATEGIA_* const \
11274 RestartStrategy::as_str returns — divergence signals a \
11275 silent detour off the substrate-primitive accessor"
11276 );
11277 assert!(
11278 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11279 "From<&RestartStrategy> for Cow<'static, str> impl must \
11280 land on the zero-alloc Cow::Borrowed arm on \
11281 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
11282 signals the projection has silently allocated where \
11283 the substrate-primitive RestartStrategy::as_str \
11284 `&'static str` return makes the borrowed arm the \
11285 type-correct projection"
11286 );
11287 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
11288 assert_eq!(
11289 via_into.as_ref(),
11290 via_method,
11291 "Into<Cow<'static, str>>::into on \
11292 &RestartStrategy::{variant:?} must byte-equal \
11293 RestartStrategy::as_str on the same input — the \
11294 blanket-derived Into shape must resolve to the same \
11295 as_str dispatch as the explicit From impl"
11296 );
11297 assert!(
11298 matches!(via_into, std::borrow::Cow::Borrowed(_)),
11299 "Into<Cow<'static, str>>::into on \
11300 &RestartStrategy::{variant:?} must land on the \
11301 zero-alloc Cow::Borrowed arm — the blanket-derived \
11302 Into shape must resolve to the same Cow::Borrowed \
11303 dispatch as the explicit From impl"
11304 );
11305 }
11306 }
11307
11308 #[test]
11309 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11310 // Cross-axis partition pin: the newly lifted trait-idiomatic
11311 // borrowed-input `From<&RestartStrategy> for
11312 // std::borrow::Cow<'static, str>` (this lift), the paired
11313 // owned-input `From<RestartStrategy> for
11314 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
11315 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
11316 // for &'static str`, and the paired borrowed-input owned-
11317 // `String` `From<&RestartStrategy> for String` must resolve
11318 // identically on every arm, locking the four
11319 // return-shape × input-shape paths together by construction so
11320 // any future detour trips at caixa-core test time. Also byte-
11321 // parity witness against the sibling [`ToString::to_string`]
11322 // surface routed through [`std::fmt::Display`] — every owned-
11323 // heap-string path (this axis's `.into_owned()` promotion, the
11324 // paired [`From<&RestartStrategy> for String`], and
11325 // `.to_string()`) resolves to the same lifted
11326 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
11327 //
11328 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
11329 // over [`super::RestartStrategy::ALL`] — whose iterator yields
11330 // `&RestartStrategy` by construction, so the borrowed-input
11331 // [`Cow<'static, str>`] axis is what routes the pipe through
11332 // the substrate-primitive [`super::RestartStrategy::as_str`]
11333 // accessor without a spurious [`Copy`] deref (which would only
11334 // be reachable through the owned-input
11335 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
11336 // first calling `.copied()` on the iterator). The pipe witness
11337 // also pins the zero-alloc discipline: every element in the
11338 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
11339 // arm predicate, so a future accidental silent-allocation
11340 // regression on the pipe's iteration axis is a caixa-core-
11341 // test-time failure.
11342 for &strategy in RestartStrategy::ALL {
11343 let borrowed_cow: std::borrow::Cow<'static, str> =
11344 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
11345 let owned_cow: std::borrow::Cow<'static, str> =
11346 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
11347 let borrowed_static: &'static str =
11348 <&'static str as From<&RestartStrategy>>::from(&strategy);
11349 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
11350 assert_eq!(
11351 borrowed_cow, owned_cow,
11352 "From<&RestartStrategy> for Cow<'static, str> and \
11353 From<RestartStrategy> for Cow<'static, str> must \
11354 resolve identically on RestartStrategy::{strategy:?} — \
11355 divergence signals the borrowed-input and owned-input \
11356 Cow<'static, str> forward-projection input-shape \
11357 paths have drifted onto different emit-sets"
11358 );
11359 assert_eq!(
11360 borrowed_cow.as_ref(),
11361 borrowed_static,
11362 "From<&RestartStrategy> for Cow<'static, str> and \
11363 From<&RestartStrategy> for &'static str must resolve \
11364 identically on RestartStrategy::{strategy:?} — \
11365 divergence signals the borrowed-input Cow<'static, \
11366 str> and &'static str return-shape paths have drifted \
11367 onto different emit-sets"
11368 );
11369 assert_eq!(
11370 borrowed_cow.as_ref(),
11371 borrowed_string.as_str(),
11372 "From<&RestartStrategy> for Cow<'static, str> and \
11373 From<&RestartStrategy> for String must resolve \
11374 identically on RestartStrategy::{strategy:?} — \
11375 divergence signals the borrowed-input Cow<'static, \
11376 str> and owned-`String` return-shape paths have \
11377 drifted onto different emit-sets"
11378 );
11379 let via_to_string: String = strategy.to_string();
11380 assert_eq!(
11381 borrowed_cow.as_ref(),
11382 via_to_string.as_str(),
11383 "From<&RestartStrategy> for Cow<'static, str> must \
11384 byte-equal RestartStrategy::to_string on \
11385 RestartStrategy::{strategy:?} — divergence signals \
11386 the trait-idiomatic borrowed-input Cow<'static, str> \
11387 forward-projection axis and the ToString-through-\
11388 Display axis have drifted onto different emit-sets"
11389 );
11390 }
11391 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
11392 .iter()
11393 .map(std::borrow::Cow::from)
11394 .collect();
11395 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
11396 .iter()
11397 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
11398 .collect();
11399 assert_eq!(
11400 via_iter, via_method,
11401 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
11402 call site whose iteration axis holds `&RestartStrategy` \
11403 by construction — must byte-equal `.iter().map(|s| \
11404 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
11405 input Cow<'static, str> `From<&RestartStrategy> for \
11406 Cow<'static, str>` axis is what makes the `Cow::from` \
11407 composition route through the substrate-primitive \
11408 `RestartStrategy::as_str` accessor with the zero-alloc \
11409 Cow::Borrowed arm by construction and without a spurious \
11410 `Copy` deref (which would only be reachable through the \
11411 owned-input `From<RestartStrategy> for Cow<'static, str>` \
11412 axis by first calling `.copied()` on the iterator)"
11413 );
11414 for cow in &via_iter {
11415 assert!(
11416 matches!(cow, std::borrow::Cow::Borrowed(_)),
11417 "every element of the .iter().map(Cow::from) pipe \
11418 over RestartStrategy::ALL must land on the zero-\
11419 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
11420 any arm signals the pipe's iteration axis has \
11421 silently allocated where the substrate-primitive \
11422 RestartStrategy::as_str `&'static str` return makes \
11423 the borrowed arm the type-correct projection"
11424 );
11425 }
11426 }
11427
11428 #[test]
11429 fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
11430 // Fail-before-pass-after byte-parity pin on the newly lifted
11431 // `impl From<RestartStrategy> for Box<str>` — asserts the
11432 // owned-input standard-library trait impl and the
11433 // substrate-primitive [`super::RestartStrategy::as_str`]
11434 // `pub const fn` accessor resolve to the same four-arm emit-
11435 // set across every arm the exhaustive
11436 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
11437 // substrate-wide `Box<str>` forward-projection campaign tier
11438 // on the first M2 OTP-shape closed-set fieldless typed enum
11439 // peer on the caixa surface (`:supervisor :estrategia`),
11440 // immediately after the paired `Cow<'static, str>` axis
11441 // (7dd28b3 / ee577fd) closed the
11442 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
11443 // 2×3 corner on this enum. Rust's standard library carries
11444 // `impl From<&str> for Box<str>` and
11445 // `impl From<String> for Box<str>` but no blanket
11446 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
11447 // a distinct trait-idiomatic surface that a
11448 // `let key: Box<str> = strategy.into();`-shaped call site
11449 // reaches through this impl and no other — a paired
11450 // `Box::from(strategy.as_str())` open-code has no compile-
11451 // time link back to the substrate primitive.
11452 for &variant in RestartStrategy::ALL {
11453 let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11454 let via_method: &'static str = variant.as_str();
11455 assert_eq!(
11456 via_trait.as_ref(),
11457 via_method,
11458 "From<RestartStrategy> for Box<str> impl must round-\
11459 trip RestartStrategy::{variant:?} to the same lifted \
11460 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
11461 returns — divergence signals a silent detour off the \
11462 substrate-primitive accessor"
11463 );
11464 let via_into: Box<str> = variant.into();
11465 assert_eq!(
11466 via_into.as_ref(),
11467 via_method,
11468 "Into<Box<str>>::into on RestartStrategy::{variant:?} \
11469 must byte-equal RestartStrategy::as_str on the same \
11470 input — the blanket-derived Into shape must resolve \
11471 to the same as_str dispatch as the explicit From impl"
11472 );
11473 }
11474 }
11475
11476 #[test]
11477 fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
11478 // Fail-before-pass-after byte-parity pin on the newly lifted
11479 // `impl From<&RestartStrategy> for Box<str>` — asserts the
11480 // borrowed-input standard-library trait impl and the
11481 // substrate-primitive [`super::RestartStrategy::as_str`]
11482 // `pub const fn` accessor resolve to the same four-arm emit-
11483 // set across every arm the exhaustive
11484 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
11485 // standard library does not carry a blanket
11486 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
11487 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11488 // so the borrowed-input `Box<str>` forward-projection axis
11489 // is a distinct trait-idiomatic surface that a
11490 // `let key: Box<str> = (&strategy).into();`-shaped call site
11491 // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
11492 // shaped pipe reaches through this impl and no other — the
11493 // paired owned-input `From<RestartStrategy> for Box<str>`
11494 // impl (69ef45c) forces every borrowed-input call site
11495 // through an explicit `Copy` deref
11496 // (`Box::<str>::from((*strategy).as_str())`) or a
11497 // `Box::<str>::from(strategy.as_str())` open-code whose
11498 // type bounds have no compile-time link back to the
11499 // substrate primitive.
11500 //
11501 // Second peer on the substrate-wide trait-idiomatic
11502 // [`Box<str>`] forward-projection family on this enum —
11503 // closes the `{Self, &Self}` input-shape corner of the
11504 // [`Box<str>`] axis on the first M2 OTP-shape closed-set
11505 // fieldless typed enum peer on the caixa surface
11506 // (`:supervisor :estrategia`), exactly as ee577fd closed
11507 // the paired [`Cow<'static, str>`] axis one commit after
11508 // its owning half (7dd28b3) landed. Every future closed-
11509 // set fieldless typed enum peer on the substrate is a
11510 // future target of the campaign.
11511 //
11512 // Also byte-parity witness against the paired owned-input
11513 // [`From<RestartStrategy> for Box<str>`] and the sibling
11514 // borrowed-input [`From<&RestartStrategy> for &'static str`],
11515 // [`From<&RestartStrategy> for String`], and
11516 // [`From<&RestartStrategy> for Cow<'static, str>`]
11517 // return-shape axes — locking the four
11518 // return-shape × input-shape paths together by construction
11519 // so any future detour trips at caixa-core test time. Then a
11520 // `.iter().map(Box::<str>::from)` pipe witness over
11521 // [`super::RestartStrategy::ALL`] — whose iterator yields
11522 // `&RestartStrategy` by construction, so the borrowed-input
11523 // [`Box<str>`] axis is what routes the pipe through the
11524 // substrate-primitive [`super::RestartStrategy::as_str`]
11525 // accessor without a spurious [`Copy`] deref (which would
11526 // only be reachable through the owned-input
11527 // [`From<RestartStrategy> for Box<str>`] axis by first
11528 // calling `.copied()` on the iterator).
11529 for &variant in RestartStrategy::ALL {
11530 let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
11531 let via_method: &'static str = variant.as_str();
11532 assert_eq!(
11533 via_trait.as_ref(),
11534 via_method,
11535 "From<&RestartStrategy> for Box<str> impl must \
11536 round-trip &RestartStrategy::{variant:?} to the same \
11537 lifted SUPERVISOR_ESTRATEGIA_* const \
11538 RestartStrategy::as_str returns — divergence signals \
11539 a silent detour off the substrate-primitive accessor"
11540 );
11541 let via_into: Box<str> = (&variant).into();
11542 assert_eq!(
11543 via_into.as_ref(),
11544 via_method,
11545 "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
11546 must byte-equal RestartStrategy::as_str on the same \
11547 input — the blanket-derived Into shape must resolve \
11548 to the same as_str dispatch as the explicit From impl"
11549 );
11550 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11551 assert_eq!(
11552 via_trait, owned_box,
11553 "From<&RestartStrategy> for Box<str> and \
11554 From<RestartStrategy> for Box<str> must resolve \
11555 identically on RestartStrategy::{variant:?} — \
11556 divergence signals the borrowed-input and owned-input \
11557 Box<str> forward-projection input-shape paths have \
11558 drifted onto different emit-sets"
11559 );
11560 let borrowed_static: &'static str =
11561 <&'static str as From<&RestartStrategy>>::from(&variant);
11562 assert_eq!(
11563 via_trait.as_ref(),
11564 borrowed_static,
11565 "From<&RestartStrategy> for Box<str> and \
11566 From<&RestartStrategy> for &'static str must resolve \
11567 identically on RestartStrategy::{variant:?} — \
11568 divergence signals the borrowed-input Box<str> and \
11569 &'static str return-shape paths have drifted onto \
11570 different emit-sets"
11571 );
11572 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
11573 assert_eq!(
11574 via_trait.as_ref(),
11575 borrowed_string.as_str(),
11576 "From<&RestartStrategy> for Box<str> and \
11577 From<&RestartStrategy> for String must resolve \
11578 identically on RestartStrategy::{variant:?} — \
11579 divergence signals the borrowed-input Box<str> and \
11580 owned-`String` return-shape paths have drifted onto \
11581 different emit-sets"
11582 );
11583 let borrowed_cow: std::borrow::Cow<'static, str> =
11584 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
11585 assert_eq!(
11586 via_trait.as_ref(),
11587 borrowed_cow.as_ref(),
11588 "From<&RestartStrategy> for Box<str> and \
11589 From<&RestartStrategy> for Cow<'static, str> must \
11590 resolve identically on RestartStrategy::{variant:?} — \
11591 divergence signals the borrowed-input Box<str> and \
11592 Cow<'static, str> return-shape paths have drifted \
11593 onto different emit-sets"
11594 );
11595 }
11596 let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
11597 let via_method: Vec<Box<str>> = RestartStrategy::ALL
11598 .iter()
11599 .map(|s| Box::<str>::from(s.as_str()))
11600 .collect();
11601 assert_eq!(
11602 via_iter, via_method,
11603 "`.iter().map(Box::<str>::from)` over \
11604 RestartStrategy::ALL — a call site whose iteration axis \
11605 holds `&RestartStrategy` by construction — must byte-\
11606 equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
11607 on every arm — the borrowed-input Box<str> \
11608 `From<&RestartStrategy> for Box<str>` axis is what \
11609 makes the `Box::<str>::from` composition route through \
11610 the substrate-primitive `RestartStrategy::as_str` \
11611 accessor without a spurious `Copy` deref (which would \
11612 only be reachable through the owned-input \
11613 `From<RestartStrategy> for Box<str>` axis by first \
11614 calling `.copied()` on the iterator)"
11615 );
11616 }
11617
11618 #[test]
11619 fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
11620 // Fail-before-pass-after byte-parity pin on the newly lifted
11621 // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
11622 // the owned-input standard-library trait impl and the
11623 // substrate-primitive [`super::RestartStrategy::as_str`]
11624 // `pub const fn` accessor resolve to the same four-arm emit-
11625 // set across every arm the exhaustive
11626 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
11627 // substrate-wide [`std::sync::Arc<str>`] forward-projection
11628 // campaign tier on the first M2 OTP-shape closed-set fieldless
11629 // typed enum peer on the caixa surface
11630 // (`:supervisor :estrategia`), immediately after the paired
11631 // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
11632 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11633 // Box<str>}` 2×4 corner on this enum. Rust's standard library
11634 // carries `impl From<&str> for std::sync::Arc<str>` and
11635 // `impl From<String> for std::sync::Arc<str>` but no blanket
11636 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11637 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11638 // so this axis is a distinct trait-idiomatic surface that a
11639 // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
11640 // site reaches through this impl and no other — a paired
11641 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
11642 // has no compile-time link back to the substrate primitive,
11643 // and a two-step `std::sync::Arc::<str>::from(String::from(
11644 // strategy))` composition through the owned-`String` axis
11645 // allocates twice (once into the intermediate `String`, once
11646 // into the [`Arc<str>`] on the `From<String>` conversion)
11647 // where the single-step trait impl allocates once.
11648 //
11649 // Cross-axis byte-parity witness against the sibling owned-
11650 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11651 // return-shape axes — locking the five return-shape paths on
11652 // the owned-input surface together by construction so any
11653 // future detour off the substrate-primitive
11654 // [`super::RestartStrategy::as_str`] accessor trips at caixa-
11655 // core test time.
11656 for &variant in RestartStrategy::ALL {
11657 let via_trait: std::sync::Arc<str> =
11658 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11659 let via_method: &'static str = variant.as_str();
11660 assert_eq!(
11661 via_trait.as_ref(),
11662 via_method,
11663 "From<RestartStrategy> for std::sync::Arc<str> impl \
11664 must round-trip RestartStrategy::{variant:?} to the \
11665 same lifted SUPERVISOR_ESTRATEGIA_* const \
11666 RestartStrategy::as_str returns — divergence signals \
11667 a silent detour off the substrate-primitive accessor"
11668 );
11669 let via_into: std::sync::Arc<str> = variant.into();
11670 assert_eq!(
11671 via_into.as_ref(),
11672 via_method,
11673 "Into<std::sync::Arc<str>>::into on \
11674 RestartStrategy::{variant:?} must byte-equal \
11675 RestartStrategy::as_str on the same input — the \
11676 blanket-derived Into shape must resolve to the same \
11677 as_str dispatch as the explicit From impl"
11678 );
11679 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
11680 assert_eq!(
11681 via_trait.as_ref(),
11682 owned_static,
11683 "From<RestartStrategy> for std::sync::Arc<str> and \
11684 From<RestartStrategy> for &'static str must resolve \
11685 identically on RestartStrategy::{variant:?} — \
11686 divergence signals the owned-input std::sync::Arc<str> \
11687 and &'static str return-shape paths have drifted onto \
11688 different emit-sets"
11689 );
11690 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
11691 assert_eq!(
11692 via_trait.as_ref(),
11693 owned_string.as_str(),
11694 "From<RestartStrategy> for std::sync::Arc<str> and \
11695 From<RestartStrategy> for String must resolve \
11696 identically on RestartStrategy::{variant:?} — \
11697 divergence signals the owned-input std::sync::Arc<str> \
11698 and owned-`String` return-shape paths have drifted \
11699 onto different emit-sets"
11700 );
11701 let owned_cow: std::borrow::Cow<'static, str> =
11702 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11703 assert_eq!(
11704 via_trait.as_ref(),
11705 owned_cow.as_ref(),
11706 "From<RestartStrategy> for std::sync::Arc<str> and \
11707 From<RestartStrategy> for Cow<'static, str> must \
11708 resolve identically on RestartStrategy::{variant:?} — \
11709 divergence signals the owned-input std::sync::Arc<str> \
11710 and Cow<'static, str> return-shape paths have drifted \
11711 onto different emit-sets"
11712 );
11713 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11714 assert_eq!(
11715 via_trait.as_ref(),
11716 owned_box.as_ref(),
11717 "From<RestartStrategy> for std::sync::Arc<str> and \
11718 From<RestartStrategy> for Box<str> must resolve \
11719 identically on RestartStrategy::{variant:?} — \
11720 divergence signals the owned-input std::sync::Arc<str> \
11721 and Box<str> return-shape paths have drifted onto \
11722 different emit-sets"
11723 );
11724 }
11725 }
11726
11727 #[test]
11728 fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
11729 // Fail-before-pass-after byte-parity pin on the newly lifted
11730 // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
11731 // asserts the borrowed-input standard-library trait impl and
11732 // the substrate-primitive [`super::RestartStrategy::as_str`]
11733 // `pub const fn` accessor resolve to the same four-arm emit-
11734 // set across every arm the exhaustive
11735 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
11736 // standard library does not carry a blanket
11737 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
11738 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11739 // so the borrowed-input [`std::sync::Arc<str>`] forward-
11740 // projection axis is a distinct trait-idiomatic surface that a
11741 // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
11742 // call site or a
11743 // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
11744 // shaped pipe reaches through this impl and no other — the
11745 // paired owned-input
11746 // `From<RestartStrategy> for std::sync::Arc<str>` impl
11747 // (bca2ec8) forces every borrowed-input call site through an
11748 // explicit `Copy` deref
11749 // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
11750 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
11751 // whose type bounds have no compile-time link back to the
11752 // substrate primitive.
11753 //
11754 // Second peer on the substrate-wide trait-idiomatic
11755 // [`std::sync::Arc<str>`] forward-projection family on this
11756 // enum — closes the `{Self, &Self}` input-shape corner of
11757 // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
11758 // closed-set fieldless typed enum peer on the caixa surface
11759 // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
11760 // paired [`Box<str>`] axis one commit after its owning half
11761 // (69ef45c) landed. Every future closed-set fieldless typed
11762 // enum peer on the substrate is a future target of the
11763 // campaign.
11764 //
11765 // Also byte-parity witness against the paired owned-input
11766 // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
11767 // sibling borrowed-input
11768 // [`From<&RestartStrategy> for &'static str`],
11769 // [`From<&RestartStrategy> for String`],
11770 // [`From<&RestartStrategy> for Cow<'static, str>`], and
11771 // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
11772 // locking the five return-shape × input-shape paths together
11773 // by construction so any future detour trips at caixa-core
11774 // test time. Then a
11775 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
11776 // [`super::RestartStrategy::ALL`] — whose iterator yields
11777 // `&RestartStrategy` by construction, so the borrowed-input
11778 // [`std::sync::Arc<str>`] axis is what routes the pipe
11779 // through the substrate-primitive
11780 // [`super::RestartStrategy::as_str`] accessor without a
11781 // spurious [`Copy`] deref (which would only be reachable
11782 // through the owned-input
11783 // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
11784 // first calling `.copied()` on the iterator).
11785 for &variant in RestartStrategy::ALL {
11786 let via_trait: std::sync::Arc<str> =
11787 <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
11788 let via_method: &'static str = variant.as_str();
11789 assert_eq!(
11790 via_trait.as_ref(),
11791 via_method,
11792 "From<&RestartStrategy> for std::sync::Arc<str> impl \
11793 must round-trip &RestartStrategy::{variant:?} to the \
11794 same lifted SUPERVISOR_ESTRATEGIA_* const \
11795 RestartStrategy::as_str returns — divergence signals \
11796 a silent detour off the substrate-primitive accessor"
11797 );
11798 let via_into: std::sync::Arc<str> = (&variant).into();
11799 assert_eq!(
11800 via_into.as_ref(),
11801 via_method,
11802 "Into<std::sync::Arc<str>>::into on \
11803 &RestartStrategy::{variant:?} must byte-equal \
11804 RestartStrategy::as_str on the same input — the \
11805 blanket-derived Into shape must resolve to the same \
11806 as_str dispatch as the explicit From impl"
11807 );
11808 let owned_arc: std::sync::Arc<str> =
11809 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11810 assert_eq!(
11811 via_trait, owned_arc,
11812 "From<&RestartStrategy> for std::sync::Arc<str> and \
11813 From<RestartStrategy> for std::sync::Arc<str> must \
11814 resolve identically on RestartStrategy::{variant:?} — \
11815 divergence signals the borrowed-input and owned-input \
11816 std::sync::Arc<str> forward-projection input-shape \
11817 paths have drifted onto different emit-sets"
11818 );
11819 let borrowed_static: &'static str =
11820 <&'static str as From<&RestartStrategy>>::from(&variant);
11821 assert_eq!(
11822 via_trait.as_ref(),
11823 borrowed_static,
11824 "From<&RestartStrategy> for std::sync::Arc<str> and \
11825 From<&RestartStrategy> for &'static str must resolve \
11826 identically on RestartStrategy::{variant:?} — \
11827 divergence signals the borrowed-input \
11828 std::sync::Arc<str> and &'static str return-shape \
11829 paths have drifted onto different emit-sets"
11830 );
11831 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
11832 assert_eq!(
11833 via_trait.as_ref(),
11834 borrowed_string.as_str(),
11835 "From<&RestartStrategy> for std::sync::Arc<str> and \
11836 From<&RestartStrategy> for String must resolve \
11837 identically on RestartStrategy::{variant:?} — \
11838 divergence signals the borrowed-input \
11839 std::sync::Arc<str> and owned-`String` return-shape \
11840 paths have drifted onto different emit-sets"
11841 );
11842 let borrowed_cow: std::borrow::Cow<'static, str> =
11843 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
11844 assert_eq!(
11845 via_trait.as_ref(),
11846 borrowed_cow.as_ref(),
11847 "From<&RestartStrategy> for std::sync::Arc<str> and \
11848 From<&RestartStrategy> for Cow<'static, str> must \
11849 resolve identically on RestartStrategy::{variant:?} — \
11850 divergence signals the borrowed-input \
11851 std::sync::Arc<str> and Cow<'static, str> return-shape \
11852 paths have drifted onto different emit-sets"
11853 );
11854 let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
11855 assert_eq!(
11856 via_trait.as_ref(),
11857 borrowed_box.as_ref(),
11858 "From<&RestartStrategy> for std::sync::Arc<str> and \
11859 From<&RestartStrategy> for Box<str> must resolve \
11860 identically on RestartStrategy::{variant:?} — \
11861 divergence signals the borrowed-input \
11862 std::sync::Arc<str> and Box<str> return-shape paths \
11863 have drifted onto different emit-sets"
11864 );
11865 }
11866 let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
11867 .iter()
11868 .map(std::sync::Arc::<str>::from)
11869 .collect();
11870 let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
11871 .iter()
11872 .map(|s| std::sync::Arc::<str>::from(s.as_str()))
11873 .collect();
11874 assert_eq!(
11875 via_iter, via_method,
11876 "`.iter().map(std::sync::Arc::<str>::from)` over \
11877 RestartStrategy::ALL — a call site whose iteration axis \
11878 holds `&RestartStrategy` by construction — must byte-\
11879 equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
11880 on every arm — the borrowed-input std::sync::Arc<str> \
11881 `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
11882 what makes the `std::sync::Arc::<str>::from` composition \
11883 route through the substrate-primitive \
11884 `RestartStrategy::as_str` accessor without a spurious \
11885 `Copy` deref (which would only be reachable through the \
11886 owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
11887 axis by first calling `.copied()` on the iterator)"
11888 );
11889 }
11890
11891 #[test]
11892 fn restart_strategy_from_into_rc_str_routes_through_as_str_accessor() {
11893 // Fail-before-pass-after byte-parity pin on the newly lifted
11894 // `impl From<RestartStrategy> for std::rc::Rc<str>` — asserts
11895 // the owned-input standard-library trait impl and the
11896 // substrate-primitive [`super::RestartStrategy::as_str`]
11897 // `pub const fn` accessor resolve to the same four-arm emit-
11898 // set across every arm the exhaustive
11899 // [`super::RestartStrategy::ALL`] slice enumerates, and cross-
11900 // witnesses against every sibling owned-input `{&'static str,
11901 // String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
11902 // return-shape axis so the six return-shape paths on the
11903 // owned-input surface lock together by construction. Extends
11904 // the substrate-wide [`std::rc::Rc<str>`] forward-projection
11905 // campaign onto the first M2 OTP-shape closed-set fieldless
11906 // typed enum peer on the caixa surface
11907 // (`:supervisor :estrategia`).
11908 for &variant in RestartStrategy::ALL {
11909 let via_trait: std::rc::Rc<str> =
11910 <std::rc::Rc<str> as From<RestartStrategy>>::from(variant);
11911 let via_method: &'static str = variant.as_str();
11912 assert_eq!(
11913 via_trait.as_ref(),
11914 via_method,
11915 "From<RestartStrategy> for std::rc::Rc<str> impl must \
11916 round-trip RestartStrategy::{variant:?} to the same \
11917 lifted SUPERVISOR_ESTRATEGIA_* const \
11918 RestartStrategy::as_str returns — divergence signals \
11919 a silent detour off the substrate-primitive accessor"
11920 );
11921 let via_into: std::rc::Rc<str> = variant.into();
11922 assert_eq!(
11923 via_into.as_ref(),
11924 via_method,
11925 "Into<std::rc::Rc<str>>::into on \
11926 RestartStrategy::{variant:?} must byte-equal \
11927 RestartStrategy::as_str on the same input — the \
11928 blanket-derived Into shape must resolve to the same \
11929 as_str dispatch as the explicit From impl"
11930 );
11931 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
11932 assert_eq!(
11933 via_trait.as_ref(),
11934 owned_static,
11935 "From<RestartStrategy> for std::rc::Rc<str> and \
11936 From<RestartStrategy> for &'static str must resolve \
11937 identically on RestartStrategy::{variant:?}"
11938 );
11939 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
11940 assert_eq!(
11941 via_trait.as_ref(),
11942 owned_string.as_str(),
11943 "From<RestartStrategy> for std::rc::Rc<str> and \
11944 From<RestartStrategy> for String must resolve \
11945 identically on RestartStrategy::{variant:?}"
11946 );
11947 let owned_cow: std::borrow::Cow<'static, str> =
11948 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11949 assert_eq!(
11950 via_trait.as_ref(),
11951 owned_cow.as_ref(),
11952 "From<RestartStrategy> for std::rc::Rc<str> and \
11953 From<RestartStrategy> for Cow<'static, str> must \
11954 resolve identically on RestartStrategy::{variant:?}"
11955 );
11956 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11957 assert_eq!(
11958 via_trait.as_ref(),
11959 owned_box.as_ref(),
11960 "From<RestartStrategy> for std::rc::Rc<str> and \
11961 From<RestartStrategy> for Box<str> must resolve \
11962 identically on RestartStrategy::{variant:?}"
11963 );
11964 let owned_arc: std::sync::Arc<str> =
11965 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11966 assert_eq!(
11967 via_trait.as_ref(),
11968 owned_arc.as_ref(),
11969 "From<RestartStrategy> for std::rc::Rc<str> and \
11970 From<RestartStrategy> for std::sync::Arc<str> must \
11971 resolve identically on RestartStrategy::{variant:?}"
11972 );
11973 }
11974 }
11975
11976 #[test]
11977 fn restart_strategy_from_borrowed_into_rc_str_routes_through_as_str_accessor() {
11978 // Fail-before-pass-after byte-parity pin on the newly lifted
11979 // `impl From<&RestartStrategy> for std::rc::Rc<str>` — asserts
11980 // the borrowed-input standard-library trait impl and the
11981 // substrate-primitive [`super::RestartStrategy::as_str`]
11982 // `pub const fn` accessor resolve to the same four-arm emit-
11983 // set across every arm the exhaustive
11984 // [`super::RestartStrategy::ALL`] slice enumerates. Closes the
11985 // `{Self, &Self}` input-shape corner of the
11986 // [`std::rc::Rc<str>`] axis on this enum, cross-witnesses
11987 // against the paired owned-input axis and every sibling
11988 // borrowed-input return-shape axis, and locks the
11989 // `.iter().map(std::rc::Rc::<str>::from)` pipe over
11990 // [`super::RestartStrategy::ALL`] to the substrate-primitive
11991 // accessor without a spurious [`Copy`] deref (which would only
11992 // be reachable through the owned-input axis by first calling
11993 // `.copied()` on the iterator).
11994 for &variant in RestartStrategy::ALL {
11995 let via_trait: std::rc::Rc<str> =
11996 <std::rc::Rc<str> as From<&RestartStrategy>>::from(&variant);
11997 let via_method: &'static str = variant.as_str();
11998 assert_eq!(
11999 via_trait.as_ref(),
12000 via_method,
12001 "From<&RestartStrategy> for std::rc::Rc<str> impl must \
12002 round-trip &RestartStrategy::{variant:?} to the same \
12003 lifted SUPERVISOR_ESTRATEGIA_* const \
12004 RestartStrategy::as_str returns"
12005 );
12006 let via_into: std::rc::Rc<str> = (&variant).into();
12007 assert_eq!(
12008 via_into.as_ref(),
12009 via_method,
12010 "Into<std::rc::Rc<str>>::into on \
12011 &RestartStrategy::{variant:?} must byte-equal \
12012 RestartStrategy::as_str on the same input"
12013 );
12014 let owned_rc: std::rc::Rc<str> =
12015 <std::rc::Rc<str> as From<RestartStrategy>>::from(variant);
12016 assert_eq!(
12017 via_trait, owned_rc,
12018 "From<&RestartStrategy> for std::rc::Rc<str> and \
12019 From<RestartStrategy> for std::rc::Rc<str> must \
12020 resolve identically on RestartStrategy::{variant:?}"
12021 );
12022 let borrowed_static: &'static str =
12023 <&'static str as From<&RestartStrategy>>::from(&variant);
12024 assert_eq!(
12025 via_trait.as_ref(),
12026 borrowed_static,
12027 "From<&RestartStrategy> for std::rc::Rc<str> and \
12028 From<&RestartStrategy> for &'static str must resolve \
12029 identically on RestartStrategy::{variant:?}"
12030 );
12031 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
12032 assert_eq!(
12033 via_trait.as_ref(),
12034 borrowed_string.as_str(),
12035 "From<&RestartStrategy> for std::rc::Rc<str> and \
12036 From<&RestartStrategy> for String must resolve \
12037 identically on RestartStrategy::{variant:?}"
12038 );
12039 let borrowed_cow: std::borrow::Cow<'static, str> =
12040 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
12041 assert_eq!(
12042 via_trait.as_ref(),
12043 borrowed_cow.as_ref(),
12044 "From<&RestartStrategy> for std::rc::Rc<str> and \
12045 From<&RestartStrategy> for Cow<'static, str> must \
12046 resolve identically on RestartStrategy::{variant:?}"
12047 );
12048 let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
12049 assert_eq!(
12050 via_trait.as_ref(),
12051 borrowed_box.as_ref(),
12052 "From<&RestartStrategy> for std::rc::Rc<str> and \
12053 From<&RestartStrategy> for Box<str> must resolve \
12054 identically on RestartStrategy::{variant:?}"
12055 );
12056 let borrowed_arc: std::sync::Arc<str> =
12057 <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
12058 assert_eq!(
12059 via_trait.as_ref(),
12060 borrowed_arc.as_ref(),
12061 "From<&RestartStrategy> for std::rc::Rc<str> and \
12062 From<&RestartStrategy> for std::sync::Arc<str> must \
12063 resolve identically on RestartStrategy::{variant:?}"
12064 );
12065 }
12066 let via_iter: Vec<std::rc::Rc<str>> = RestartStrategy::ALL
12067 .iter()
12068 .map(std::rc::Rc::<str>::from)
12069 .collect();
12070 let via_method: Vec<std::rc::Rc<str>> = RestartStrategy::ALL
12071 .iter()
12072 .map(|s| std::rc::Rc::<str>::from(s.as_str()))
12073 .collect();
12074 assert_eq!(
12075 via_iter, via_method,
12076 "`.iter().map(std::rc::Rc::<str>::from)` over \
12077 RestartStrategy::ALL — a call site whose iteration axis \
12078 holds `&RestartStrategy` by construction — must byte-\
12079 equal `.iter().map(|s| std::rc::Rc::<str>::from(s.as_str()))` \
12080 on every arm — the borrowed-input std::rc::Rc<str> \
12081 `From<&RestartStrategy> for std::rc::Rc<str>` axis is \
12082 what makes the `std::rc::Rc::<str>::from` composition \
12083 route through the substrate-primitive \
12084 `RestartStrategy::as_str` accessor without a spurious \
12085 `Copy` deref (which would only be reachable through the \
12086 owned-input `From<RestartStrategy> for std::rc::Rc<str>` \
12087 axis by first calling `.copied()` on the iterator)"
12088 );
12089 }
12090
12091 #[test]
12092 #[allow(
12093 clippy::too_many_lines,
12094 reason = "cross-axis partition pin folds the substrate-primitive \
12095 as_str accessor's `.as_bytes()` byte-tail plus the \
12096 paired str-view (AsRef<str>, Display, as_str) and \
12097 reverse-projection ({&'static str, String, Cow<'static, \
12098 str>, Box<str>, std::sync::Arc<str>}) return-shape \
12099 axes' `.as_bytes()` byte-tails plus a <T: AsRef<[u8]>>\
12100 -bound-consumer witness plus a blake3::Hasher::update-\
12101 shape byte-input surface witness into one exhaustive \
12102 round-trip over RestartStrategy::ALL — the accepted \
12103 line-count cost of opening the byte-view axis keyed \
12104 to the substrate-primitive as_str accessor at the \
12105 same test-site"
12106 )]
12107 #[allow(
12108 clippy::needless_borrows_for_generic_args,
12109 reason = "the borrowed-input surface (&variant) is exercised \
12110 deliberately: the `<T: AsRef<[u8]>>`-bound consumer \
12111 and the `blake3::Hasher::update`-shape byte-input \
12112 surface both accept either owned or borrowed input \
12113 through the standard-library blanket \
12114 `impl<T: ?Sized + AsRef<[u8]>> AsRef<[u8]> for &T`, \
12115 and this pin round-trips both input shapes to lock \
12116 the borrowed-input path load-bearing against a \
12117 future silent regression"
12118 )]
12119 fn restart_strategy_as_ref_bytes_routes_through_as_str_accessor() {
12120 // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
12121 // function that binds its argument through the standard-library
12122 // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartStrategy`]
12123 // directly, without the caller open-coding the two-hop
12124 // `estrategia.as_str().as_bytes()` composition. Lifted to the top
12125 // of the function per `clippy::items_after_statements`.
12126 fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
12127 t.as_ref().to_vec()
12128 }
12129 // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
12130 // `blake3::Hasher::update` / `ring::digest::Context::update` /
12131 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
12132 // signature so a per-supervisor BLAKE3 content-address closure
12133 // that composes `hasher.update(estrategia)` on the
12134 // [`crate::Lacre`] closure builder reaches the substrate-primitive
12135 // `as_str` accessor through the [`super::RestartStrategy`]
12136 // `AsRef<[u8]>` axis and no other. Lifted to the top of the
12137 // function per `clippy::items_after_statements`.
12138 struct MockHasher(Vec<u8>);
12139 impl MockHasher {
12140 fn new() -> Self {
12141 Self(Vec::new())
12142 }
12143 fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
12144 self.0.extend_from_slice(bytes.as_ref());
12145 self
12146 }
12147 fn finalize(self) -> Vec<u8> {
12148 self.0
12149 }
12150 }
12151
12152 // Fail-before-pass-after byte-parity pin on the newly lifted
12153 // `impl AsRef<[u8]> for RestartStrategy` — asserts the trait-
12154 // idiomatic byte-view standard-library impl and the substrate-
12155 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
12156 // accessor's `.as_bytes()` byte-tail resolve to the same four-arm
12157 // `PascalCase` wire byte-string emit-set across every arm the
12158 // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
12159 // Opens the trait-idiomatic byte-view axis onto the first M2
12160 // OTP-shape closed-set fieldless typed enum peer on the caixa
12161 // surface (`:supervisor :estrategia`), extending the substrate-
12162 // wide byte-view campaign the sibling
12163 // [`super::crate::CaixaKind`] first-mover (69d8d86) opened.
12164 //
12165 // Rust's standard library carries `impl AsRef<[u8]> for str` and
12166 // `impl AsRef<[u8]> for String`, so a two-hop composition
12167 // `estrategia.as_str().as_bytes()` (or the equally two-hop
12168 // `AsRef::<str>::as_ref(&estrategia).as_bytes()`) is reachable
12169 // through the pre-existing str-view axis alone. But that two-hop
12170 // shape has no compile-time link back to the byte-projection
12171 // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
12172 // consumer to open-code the two-hop composition at every call
12173 // site, and admits a silent split whenever a future call site
12174 // takes a sibling reverse-projection axis whose `.as_bytes()`
12175 // byte-tail carries no compile-time byte-view surface. This
12176 // impl closes the byte-view axis at the substrate-primitive
12177 // [`super::RestartStrategy::as_str`] accessor so every future
12178 // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
12179 // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const roster
12180 // the paired str-view axes already return through — through one
12181 // trait dispatch.
12182 for &variant in RestartStrategy::ALL {
12183 let via_trait: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
12184 let via_method_bytes: &[u8] = variant.as_str().as_bytes();
12185 assert_eq!(
12186 via_trait, via_method_bytes,
12187 "AsRef<[u8]> for RestartStrategy impl must byte-equal \
12188 RestartStrategy::as_str().as_bytes() on \
12189 RestartStrategy::{variant:?} — divergence signals a \
12190 silent detour off the substrate-primitive accessor"
12191 );
12192 // Cross-axis witness against the paired str-view axes'
12193 // `.as_bytes()` byte-tails: [`AsRef<str>`] /
12194 // [`std::fmt::Display`] / [`super::RestartStrategy::as_str`]
12195 // all resolve to the same lifted
12196 // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const
12197 // roster, and the byte-view axis must byte-equal each of
12198 // their `.as_bytes()` byte-tails by construction — locking
12199 // the str-view and byte-view axes together at the
12200 // substrate-primitive accessor.
12201 let str_view_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
12202 assert_eq!(
12203 via_trait,
12204 str_view_ref.as_bytes(),
12205 "AsRef<[u8]> for RestartStrategy and AsRef<str> for \
12206 RestartStrategy must resolve to byte-equal byte-tails \
12207 on RestartStrategy::{variant:?} — divergence signals \
12208 the byte-view and str-view axes have drifted off the \
12209 same substrate-primitive as_str accessor"
12210 );
12211 let display_bytes = variant.to_string();
12212 assert_eq!(
12213 via_trait,
12214 display_bytes.as_bytes(),
12215 "AsRef<[u8]> for RestartStrategy and \
12216 <RestartStrategy as std::fmt::Display>::to_string must \
12217 resolve to byte-equal byte-tails on \
12218 RestartStrategy::{variant:?} — divergence signals the \
12219 byte-view axis and the Display formatter axis have \
12220 drifted off the same substrate-primitive as_str \
12221 accessor"
12222 );
12223 // Cross-axis witness against the paired reverse-projection
12224 // axes' `.as_bytes()` byte-tails: every one of `{&'static
12225 // str, String, Cow<'static, str>, Box<str>,
12226 // std::sync::Arc<str>}` allocates (or borrows) the same
12227 // `PascalCase` wire byte-string the substrate-primitive
12228 // accessor emits, so the byte-view axis must byte-equal
12229 // each of their `.as_bytes()` byte-tails by construction.
12230 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
12231 assert_eq!(
12232 via_trait,
12233 owned_static.as_bytes(),
12234 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
12235 for &'static str must resolve to byte-equal byte-tails \
12236 on RestartStrategy::{variant:?}"
12237 );
12238 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
12239 assert_eq!(
12240 via_trait,
12241 owned_string.as_bytes(),
12242 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
12243 for String must resolve to byte-equal byte-tails on \
12244 RestartStrategy::{variant:?}"
12245 );
12246 let owned_cow: std::borrow::Cow<'static, str> =
12247 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
12248 assert_eq!(
12249 via_trait,
12250 owned_cow.as_bytes(),
12251 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
12252 for Cow<'static, str> must resolve to byte-equal byte-\
12253 tails on RestartStrategy::{variant:?}"
12254 );
12255 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
12256 assert_eq!(
12257 via_trait,
12258 owned_box.as_bytes(),
12259 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
12260 for Box<str> must resolve to byte-equal byte-tails on \
12261 RestartStrategy::{variant:?}"
12262 );
12263 let owned_arc: std::sync::Arc<str> =
12264 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
12265 assert_eq!(
12266 via_trait,
12267 owned_arc.as_bytes(),
12268 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
12269 for std::sync::Arc<str> must resolve to byte-equal byte-\
12270 tails on RestartStrategy::{variant:?}"
12271 );
12272 }
12273 // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
12274 // input function `generic_bytes_sink` (lifted above per
12275 // `clippy::items_after_statements`) accepts a
12276 // [`super::RestartStrategy`] directly through the trait bound,
12277 // without the caller open-coding the two-hop
12278 // `estrategia.as_str().as_bytes()` composition. This is the
12279 // shape that reaches the caixa-lacre BLAKE3 content-address
12280 // closure's `blake3::Hasher::update(impl AsRef<[u8]>)` byte-
12281 // input surface through this impl and no other.
12282 for &variant in RestartStrategy::ALL {
12283 let via_generic = generic_bytes_sink(variant);
12284 let via_borrowed_generic = generic_bytes_sink(&variant);
12285 let via_method_bytes = variant.as_str().as_bytes().to_vec();
12286 assert_eq!(
12287 via_generic, via_method_bytes,
12288 "generic `<T: AsRef<[u8]>>`-bound consumer on \
12289 RestartStrategy::{variant:?} must yield the same byte-\
12290 tail RestartStrategy::as_str().as_bytes() returns — \
12291 divergence signals the byte-view axis fails to bridge \
12292 a generic byte-input trait bound to the substrate-\
12293 primitive accessor"
12294 );
12295 assert_eq!(
12296 via_borrowed_generic, via_method_bytes,
12297 "generic `<T: AsRef<[u8]>>`-bound consumer on \
12298 &RestartStrategy::{variant:?} must yield the same byte-\
12299 tail RestartStrategy::as_str().as_bytes() returns — \
12300 the borrowed-input surface must resolve to the same \
12301 as_str dispatch"
12302 );
12303 }
12304 // `blake3::Hasher::update`-shape byte-input surface witness on
12305 // the caixa-lacre compounding target: the `MockHasher` (lifted
12306 // above per `clippy::items_after_statements`) mirrors
12307 // `blake3::Hasher::update` / `ring::digest::Context::update` /
12308 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
12309 // signature and accepts a [`super::RestartStrategy`] directly,
12310 // routing its byte-tail through the substrate-primitive
12311 // `as_str` accessor — the shape a future per-supervisor BLAKE3
12312 // content-address closure composes to fold an `:estrategia`
12313 // discriminator byte-tag into the [`crate::Lacre`] closure
12314 // body.
12315 for &variant in RestartStrategy::ALL {
12316 let mut owned_hasher = MockHasher::new();
12317 owned_hasher.update(variant);
12318 let owned_folded = owned_hasher.finalize();
12319 assert_eq!(
12320 owned_folded,
12321 variant.as_str().as_bytes(),
12322 "`hasher.update(estrategia)`-shape composition on \
12323 RestartStrategy::{variant:?} must fold the same byte-\
12324 tail RestartStrategy::as_str().as_bytes() returns — \
12325 the shape a future per-supervisor BLAKE3 content-\
12326 address closure composes to fold an `:estrategia` \
12327 discriminator byte-tag into the Lacre closure body"
12328 );
12329 let mut borrowed_hasher = MockHasher::new();
12330 borrowed_hasher.update(&variant);
12331 let borrowed_folded = borrowed_hasher.finalize();
12332 assert_eq!(
12333 borrowed_folded,
12334 variant.as_str().as_bytes(),
12335 "`hasher.update(&estrategia)`-shape composition on \
12336 &RestartStrategy::{variant:?} must fold the same byte-\
12337 tail RestartStrategy::as_str().as_bytes() returns — \
12338 the borrowed-input surface must resolve to the same \
12339 as_str dispatch"
12340 );
12341 }
12342 }
12343
12344 #[test]
12345 #[expect(
12346 clippy::too_many_lines,
12347 reason = "the byte-owned reverse-projection axis is extended \
12348 here onto the first M2-OTP-shape closed-set fieldless \
12349 typed-enum peer, so the pin binds the new impl against \
12350 every paired byte-view and str-owned axis on the same \
12351 enum plus a generic <T: Into<Vec<u8>>>-bound consumer \
12352 witness and a std::io::Write::write_all-shape owned-\
12353 byte-sink surface witness on both owned and borrowed \
12354 input shapes to lock the whole family against a future \
12355 silent regression"
12356 )]
12357 fn restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
12358 // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
12359 // owned-byte-input function accepts a [`super::RestartStrategy`]
12360 // directly through the trait bound, without the caller open-
12361 // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
12362 // composition. Lifted to the top of the function per
12363 // `clippy::items_after_statements`.
12364 fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
12365 t.into()
12366 }
12367 // `std::io::Write::write_all`-shape owned-byte-sink surface
12368 // mock: mirrors `std::io::Write::write_all` /
12369 // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
12370 // byte-sink that consumes a `Vec<u8>` payload via
12371 // `Into<Vec<u8>>`, so a future per-supervisor per-`:estrategia`
12372 // audit-log emit reaches the substrate-primitive `as_str`
12373 // accessor through the byte-owned reverse-projection axis and
12374 // no other. Lifted to the top of the function per
12375 // `clippy::items_after_statements`.
12376 struct MockOwnedByteSink(Vec<u8>);
12377 impl MockOwnedByteSink {
12378 fn new() -> Self {
12379 Self(Vec::new())
12380 }
12381 fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
12382 self.0.extend_from_slice(&bytes.into());
12383 self
12384 }
12385 fn finalize(self) -> Vec<u8> {
12386 self.0
12387 }
12388 }
12389
12390 // Fail-before-pass-after byte-parity pin on the newly lifted
12391 // `impl From<RestartStrategy> for Vec<u8>` and
12392 // `impl From<&RestartStrategy> for Vec<u8>` — asserts the trait-
12393 // idiomatic byte-owned reverse-projection standard-library
12394 // impls and the substrate-primitive
12395 // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
12396 // `.as_bytes().to_vec()` byte-tail resolve to the same four-arm
12397 // PascalCase wire byte-string emit-set across every arm the
12398 // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
12399 // Extends the substrate-wide trait-idiomatic byte-owned
12400 // reverse-projection axis onto the first M2-OTP-shape closed-
12401 // set fieldless typed-enum peer on the caixa surface
12402 // (`:supervisor :estrategia`), matching the trajectory the
12403 // first-mover [`super::crate::CaixaKind`] lift (b245fd6), the
12404 // second-mover [`super::crate::dialeto::CaixaDialeto`] lift
12405 // (4cceaf5), and the third-mover
12406 // [`super::crate::dep::DepList`] lift (e974ca2) established
12407 // across the caixa-core-internal tier.
12408 for &variant in RestartStrategy::ALL {
12409 let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
12410 let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
12411 let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
12412 assert_eq!(
12413 via_owned_from, via_method_bytes,
12414 "From<RestartStrategy> for Vec<u8> impl must byte-equal \
12415 RestartStrategy::as_str().as_bytes().to_vec() on \
12416 RestartStrategy::{variant:?} — divergence signals a \
12417 silent detour off the substrate-primitive accessor"
12418 );
12419 assert_eq!(
12420 via_borrowed_from, via_method_bytes,
12421 "From<&RestartStrategy> for Vec<u8> impl must byte-\
12422 equal RestartStrategy::as_str().as_bytes().to_vec() \
12423 on RestartStrategy::{variant:?} — divergence signals \
12424 a silent detour off the substrate-primitive accessor"
12425 );
12426 assert_eq!(
12427 via_owned_from, via_borrowed_from,
12428 "From<RestartStrategy> for Vec<u8> and \
12429 From<&RestartStrategy> for Vec<u8> must byte-equal \
12430 each other on RestartStrategy::{variant:?} — \
12431 divergence signals the owned-input and borrowed-input \
12432 paths have drifted off the same substrate-primitive \
12433 as_str accessor"
12434 );
12435 // Cross-axis witness against the paired [`AsRef<[u8]>`]
12436 // borrowed byte-view axis (cd4c4e0): the byte-owned
12437 // reverse-projection axis must byte-equal the paired
12438 // borrowed byte-view axis by construction — locking the
12439 // byte-view and byte-owned axes together at the substrate-
12440 // primitive accessor.
12441 let borrowed_bytes: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
12442 assert_eq!(
12443 via_owned_from,
12444 borrowed_bytes.to_vec(),
12445 "From<RestartStrategy> for Vec<u8> and AsRef<[u8]> \
12446 for RestartStrategy must resolve to byte-equal byte-\
12447 tails on RestartStrategy::{variant:?} — divergence \
12448 signals the byte-owned and byte-view axes have \
12449 drifted off the same substrate-primitive as_str \
12450 accessor"
12451 );
12452 // Cross-axis witness against the str-owned reverse-
12453 // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
12454 // byte-tails: every one of `{String, Cow<'static, str>,
12455 // Box<str>, std::sync::Arc<str>, std::rc::Rc<str>}`
12456 // allocates (or borrows) the same PascalCase wire byte-
12457 // string the substrate-primitive accessor emits, so the
12458 // byte-owned axis must byte-equal each of their owned
12459 // byte-tails by construction.
12460 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
12461 assert_eq!(
12462 via_owned_from,
12463 owned_string.into_bytes(),
12464 "From<RestartStrategy> for Vec<u8> and \
12465 String::from(strategy).into_bytes() must resolve to \
12466 byte-equal byte-tails on RestartStrategy::{variant:?}"
12467 );
12468 let owned_cow: std::borrow::Cow<'static, str> =
12469 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
12470 assert_eq!(
12471 via_owned_from,
12472 owned_cow.as_bytes().to_vec(),
12473 "From<RestartStrategy> for Vec<u8> and \
12474 From<RestartStrategy> for Cow<'static, str> must \
12475 resolve to byte-equal byte-tails on \
12476 RestartStrategy::{variant:?}"
12477 );
12478 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
12479 assert_eq!(
12480 via_owned_from,
12481 owned_box.as_bytes().to_vec(),
12482 "From<RestartStrategy> for Vec<u8> and \
12483 From<RestartStrategy> for Box<str> must resolve to \
12484 byte-equal byte-tails on RestartStrategy::{variant:?}"
12485 );
12486 let owned_arc: std::sync::Arc<str> =
12487 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
12488 assert_eq!(
12489 via_owned_from,
12490 owned_arc.as_bytes().to_vec(),
12491 "From<RestartStrategy> for Vec<u8> and \
12492 From<RestartStrategy> for std::sync::Arc<str> must \
12493 resolve to byte-equal byte-tails on \
12494 RestartStrategy::{variant:?}"
12495 );
12496 }
12497 // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
12498 // and borrowed input shapes: the generic owned-byte-input
12499 // function `generic_owned_bytes_sink` (lifted above per
12500 // `clippy::items_after_statements`) accepts a
12501 // [`super::RestartStrategy`] and a `&RestartStrategy`
12502 // directly through the trait bound, without the caller open-
12503 // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
12504 // composition.
12505 for &variant in RestartStrategy::ALL {
12506 let via_generic_owned = generic_owned_bytes_sink(variant);
12507 // Bind the borrowed-input path through an explicit
12508 // `&RestartStrategy` local so the generic-consumer witness
12509 // routes through `From<&RestartStrategy> for Vec<u8>` (T
12510 // binds to `&RestartStrategy`) rather than clippy-collapsing
12511 // the borrow onto the owned-input peer.
12512 let variant_ref: &RestartStrategy = &variant;
12513 let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
12514 let via_method_bytes = variant.as_str().as_bytes().to_vec();
12515 assert_eq!(
12516 via_generic_owned, via_method_bytes,
12517 "generic `<T: Into<Vec<u8>>>`-bound consumer on \
12518 RestartStrategy::{variant:?} must yield the same byte-\
12519 tail RestartStrategy::as_str().as_bytes() returns — \
12520 divergence signals the byte-owned axis fails to bridge \
12521 a generic owned-byte-input trait bound to the \
12522 substrate-primitive accessor"
12523 );
12524 assert_eq!(
12525 via_generic_borrowed, via_method_bytes,
12526 "generic `<T: Into<Vec<u8>>>`-bound consumer on \
12527 &RestartStrategy::{variant:?} must yield the same byte-\
12528 tail RestartStrategy::as_str().as_bytes() returns — \
12529 the borrowed-input surface must resolve to the same \
12530 as_str dispatch"
12531 );
12532 }
12533 // `std::io::Write::write_all`-shape owned-byte-sink surface
12534 // witness: the `MockOwnedByteSink` (lifted above per
12535 // `clippy::items_after_statements`) mirrors
12536 // `std::io::Write::write_all` /
12537 // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
12538 // bound owned-byte input signature and accepts a
12539 // [`super::RestartStrategy`] directly on both owned and
12540 // borrowed input shapes, routing its byte-tail through the
12541 // substrate-primitive `as_str` accessor — the shape a future
12542 // per-supervisor per-`:estrategia` audit-log emit composes to
12543 // fold an `:estrategia` discriminator byte-tag into a
12544 // downstream owned-byte-sink surface.
12545 for &variant in RestartStrategy::ALL {
12546 let mut owned_sink = MockOwnedByteSink::new();
12547 owned_sink.write_all(variant);
12548 let owned_folded = owned_sink.finalize();
12549 assert_eq!(
12550 owned_folded,
12551 variant.as_str().as_bytes(),
12552 "`sink.write_all(strategy)`-shape composition on \
12553 RestartStrategy::{variant:?} must fold the same byte-\
12554 tail RestartStrategy::as_str().as_bytes() returns"
12555 );
12556 let mut borrowed_sink = MockOwnedByteSink::new();
12557 let variant_ref: &RestartStrategy = &variant;
12558 borrowed_sink.write_all(variant_ref);
12559 let borrowed_folded = borrowed_sink.finalize();
12560 assert_eq!(
12561 borrowed_folded,
12562 variant.as_str().as_bytes(),
12563 "`sink.write_all(&strategy)`-shape composition on \
12564 &RestartStrategy::{variant:?} must fold the same byte-\
12565 tail RestartStrategy::as_str().as_bytes() returns — \
12566 the borrowed-input surface must resolve to the same \
12567 as_str dispatch"
12568 );
12569 }
12570 }
12571
12572 #[test]
12573 fn restart_strategy_from_into_owned_cow_bytes_routes_through_as_str_accessor() {
12574 // Fail-before-pass-after byte-parity pin on the newly lifted
12575 // `impl From<RestartStrategy> for std::borrow::Cow<'static, [u8]>`
12576 // and `impl From<&RestartStrategy> for std::borrow::Cow<'static, [u8]>` —
12577 // asserts the trait-idiomatic byte-owned reverse-projection standard-
12578 // library impls and the substrate-primitive
12579 // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
12580 // `.as_bytes()` byte-view resolve to the same four-arm PascalCase
12581 // wire byte-string emit-set across every arm the exhaustive
12582 // [`super::RestartStrategy::ALL`] slice enumerates. Additionally
12583 // asserts the returned `Cow<'static, [u8]>` binds the zero-alloc
12584 // `Cow::Borrowed` arm on both input shapes, because
12585 // `Self::as_str` returns `&'static str` and `.as_bytes()` on it
12586 // preserves the `&'static [u8]` lifetime by construction.
12587 //
12588 // Generic `<T: Into<Cow<'static, [u8]>>>`-bound consumer witness
12589 // helper: a future per-supervisor byte-writer that accepts a
12590 // `Cow<'static, [u8]>` composes on both owned and borrowed input
12591 // shapes without an open-coded three-hop
12592 // `Cow::Borrowed(strategy.as_str().as_bytes())` at every call
12593 // site. Lifted to the top of the function per
12594 // `clippy::items_after_statements`.
12595 fn generic_cow_bytes_sink<T: Into<std::borrow::Cow<'static, [u8]>>>(
12596 t: T,
12597 ) -> std::borrow::Cow<'static, [u8]> {
12598 t.into()
12599 }
12600 for &variant in RestartStrategy::ALL {
12601 let via_owned_from: std::borrow::Cow<'static, [u8]> =
12602 <std::borrow::Cow<'static, [u8]> as From<RestartStrategy>>::from(variant);
12603 let via_borrowed_from: std::borrow::Cow<'static, [u8]> =
12604 <std::borrow::Cow<'static, [u8]> as From<&RestartStrategy>>::from(&variant);
12605 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
12606 assert_eq!(
12607 via_owned_from.as_ref(),
12608 via_method_bytes,
12609 "From<RestartStrategy> for Cow<'static, [u8]> impl must \
12610 byte-equal RestartStrategy::as_str().as_bytes() on \
12611 RestartStrategy::{variant:?} — divergence signals a \
12612 silent detour off the substrate-primitive accessor"
12613 );
12614 assert_eq!(
12615 via_borrowed_from.as_ref(),
12616 via_method_bytes,
12617 "From<&RestartStrategy> for Cow<'static, [u8]> impl must \
12618 byte-equal RestartStrategy::as_str().as_bytes() on \
12619 RestartStrategy::{variant:?} — divergence signals a \
12620 silent detour off the substrate-primitive accessor"
12621 );
12622 assert!(
12623 matches!(via_owned_from, std::borrow::Cow::Borrowed(_)),
12624 "From<RestartStrategy> for Cow<'static, [u8]> must bind \
12625 the zero-alloc Cow::Borrowed arm on \
12626 RestartStrategy::{variant:?} — Self::as_str returns \
12627 &'static str, so a Cow::Owned arm signals a silent \
12628 allocation off the substrate primitive"
12629 );
12630 assert!(
12631 matches!(via_borrowed_from, std::borrow::Cow::Borrowed(_)),
12632 "From<&RestartStrategy> for Cow<'static, [u8]> must bind \
12633 the zero-alloc Cow::Borrowed arm on \
12634 &RestartStrategy::{variant:?} — Self::as_str returns \
12635 &'static str, so a Cow::Owned arm signals a silent \
12636 allocation off the substrate primitive"
12637 );
12638 // Cross-axis partition against the paired byte-owned
12639 // `Vec<u8>` reverse-projection axis (7cc10eb line 1579) on
12640 // the same enum — the two byte-owned reverse-projection
12641 // axes must byte-agree on every arm.
12642 let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
12643 assert_eq!(
12644 via_owned_from.as_ref(),
12645 via_vec_bytes.as_slice(),
12646 "From<RestartStrategy> for Cow<'static, [u8]> and \
12647 From<RestartStrategy> for Vec<u8> must byte-agree on \
12648 RestartStrategy::{variant:?} — divergence signals the \
12649 two byte-owned reverse-projection axes have drifted \
12650 off the same substrate-primitive as_str accessor"
12651 );
12652 // Cross-axis partition against the paired str-side
12653 // `Cow<'static, str>` reverse-projection axis (7dd28b3) on
12654 // the same enum — the byte-side and str-side Cow<'static, _>
12655 // axes must both bind the Cow::Borrowed arm on every arm
12656 // (both route through Self::as_str's &'static return).
12657 let via_cow_str: std::borrow::Cow<'static, str> =
12658 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
12659 assert_eq!(
12660 via_owned_from.as_ref(),
12661 via_cow_str.as_bytes(),
12662 "From<RestartStrategy> for Cow<'static, [u8]> and \
12663 From<RestartStrategy> for Cow<'static, str> must \
12664 byte-agree on RestartStrategy::{variant:?} — \
12665 divergence signals a silent detour off the shared \
12666 substrate-primitive as_str accessor"
12667 );
12668 }
12669 for &variant in RestartStrategy::ALL {
12670 let owned_via_generic = generic_cow_bytes_sink(variant);
12671 let variant_ref: &RestartStrategy = &variant;
12672 let borrowed_via_generic = generic_cow_bytes_sink(variant_ref);
12673 assert_eq!(
12674 owned_via_generic.as_ref(),
12675 variant.as_str().as_bytes(),
12676 "<T: Into<Cow<'static, [u8]>>>-bound composition on \
12677 RestartStrategy::{variant:?} must fold the same byte-\
12678 tail RestartStrategy::as_str().as_bytes() returns"
12679 );
12680 assert_eq!(
12681 borrowed_via_generic.as_ref(),
12682 variant.as_str().as_bytes(),
12683 "<T: Into<Cow<'static, [u8]>>>-bound composition on \
12684 &RestartStrategy::{variant:?} must fold the same byte-\
12685 tail RestartStrategy::as_str().as_bytes() returns"
12686 );
12687 }
12688 }
12689
12690 #[test]
12691 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
12692 // Fail-before-pass-after byte-parity pin on the newly lifted
12693 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
12694 // library trait impl and the substrate-primitive
12695 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
12696 // the same three-arm accept-set across every arm the exhaustive
12697 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
12698 // detour that routes the trait impl through a divergent
12699 // projection (a per-arm inline `match s { "Permanent" =>
12700 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
12701 // link to the un-lifted arm-literal, a hypothetical
12702 // `#[serde(rename_all = "…")]` attribute drift that silently
12703 // splits the wire byte-string from every consumer that reaches
12704 // for this typed dispatch, an accidental swap onto the kebab-case
12705 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
12706 // impl parses through and which would collide the two-axis
12707 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
12708 // doc block makes load-bearing) trips at caixa-core test time
12709 // under `assert_eq!` rather than at a downstream
12710 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
12711 // every one of the three arms [`RestartPolicy::ALL`] carries so
12712 // no arm's projection is covered only by the sibling method-
12713 // named `from_wire` path. Peer of the sibling
12714 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
12715 // (5b828ed) — extends the trait-idiomatic reverse-projection
12716 // axis onto the third and final M2-OTP-shape closed-set typed
12717 // enum on the caixa surface (the paired per-child restart-
12718 // decision-policy sibling on the same M2 `:supervisor` slot).
12719 for &variant in RestartPolicy::ALL {
12720 let wire = variant.as_str();
12721 assert_eq!(
12722 <RestartPolicy as TryFrom<&str>>::try_from(wire),
12723 Ok(variant),
12724 "TryFrom<&str> impl on RestartPolicy must round-trip \
12725 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
12726 Ok(RestartPolicy::{variant:?}) — divergence from \
12727 RestartPolicy::from_wire signals a silent detour off \
12728 the substrate-primitive accessor"
12729 );
12730 assert_eq!(
12731 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
12732 RestartPolicy::from_wire(wire),
12733 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
12734 equal RestartPolicy::from_wire on the same input"
12735 );
12736 }
12737 }
12738
12739 #[test]
12740 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
12741 // Rejection witness on the `impl TryFrom<&str> for
12742 // RestartPolicy` — sweeps a candidate set of byte-strings
12743 // outside the three-arm PascalCase wire accept-set the sibling
12744 // [`RestartPolicy::as_str`] emits and asserts every one lands on
12745 // `Err(())`, so a future accidental widening of the trait impl's
12746 // accept-set (a stray additional
12747 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
12748 // path, a silent inclusion of the kebab-case dispatcher-catalog
12749 // byte-string the pre-existing [`std::str::FromStr`] impl the
12750 // [`gen_platform::FromStrKind`] derive installs parses onto the
12751 // wire axis — which would collide the two-axis
12752 // wire/dispatcher-catalog split the sibling
12753 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
12754 // an English-rebrand or plural-arm silent alias that would widen
12755 // the wire accept-set past the OTP-canonical three) trips at
12756 // caixa-core test time. The candidate set includes the empty
12757 // string, whitespace-only padding, the kebab-case dispatcher-
12758 // catalog byte-strings on the sibling axis (a caller who
12759 // confuses the two axes trips here rather than at a downstream
12760 // consumer's silent reject), a lowercase / uppercase / mixed-case
12761 // fold of each PascalCase arm (a caller who assumes case-fold
12762 // acceptance trips here), leading/trailing whitespace padding,
12763 // the trailing-newline shape, quote-wrapped candidates, and a
12764 // residual set of plausible-but-wrong English rebrand
12765 // candidates. Peer of the sibling
12766 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
12767 // (5b828ed) rejection witness.
12768 let rejected: &[&str] = &[
12769 "",
12770 " ",
12771 "\n",
12772 "\t",
12773 "permanent",
12774 "temporary",
12775 "transient",
12776 "PERMANENT",
12777 "TEMPORARY",
12778 "TRANSIENT",
12779 "Permanents",
12780 "Permanent ",
12781 " Permanent",
12782 " Temporary ",
12783 "Permanent\n",
12784 "Transient\t",
12785 "\"Permanent\"",
12786 "Ephemeral",
12787 "Always",
12788 "Never",
12789 "OnAbnormalExit",
12790 "intrinsic",
12791 "?",
12792 ];
12793 for &input in rejected {
12794 assert_eq!(
12795 <RestartPolicy as TryFrom<&str>>::try_from(input),
12796 Err(()),
12797 "TryFrom<&str> impl on RestartPolicy must reject the \
12798 non-wire byte-string {input:?} — silent acceptance \
12799 signals an accept-set widening off the paired \
12800 RestartPolicy::from_wire resolver"
12801 );
12802 }
12803 }
12804
12805 #[test]
12806 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
12807 // Cross-axis partition pin: the paired `TryFrom<&str>` and
12808 // `from_wire` reverse projections must resolve identically on
12809 // *every* input, not just the ones [`RestartPolicy::ALL`]
12810 // enumerates. Sweeps a mixed candidate set spanning accepted
12811 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
12812 // case dispatcher-catalog byte-strings, empty, whitespace-
12813 // padded, quoted, English-rebrand candidates) inputs and asserts
12814 // the trait's `Result::ok()` projection byte-equals the method-
12815 // named resolver's `Option<Self>` return-shape on each, locking
12816 // the two paths together by construction so any future detour
12817 // (a stray `try_from` special-case that widens or narrows the
12818 // accept-set outside the paired `from_wire` resolver, an
12819 // accidental swap onto the kebab-case [`std::str::FromStr`]
12820 // impl the [`gen_platform::FromStrKind`] derive installs on the
12821 // sibling dispatcher-catalog axis) trips at caixa-core test
12822 // time. Peer of the sibling
12823 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
12824 // pin — extends the round-trip discipline onto the M2-OTP-shape
12825 // per-child restart-policy axis.
12826 let candidates: &[&str] = &[
12827 "Permanent",
12828 "Temporary",
12829 "Transient",
12830 "",
12831 "permanent",
12832 "temporary",
12833 "transient",
12834 "PERMANENT",
12835 "unknown",
12836 "Permanent ",
12837 " Permanent",
12838 "\"Permanent\"",
12839 "Ephemeral",
12840 "OnAbnormalExit",
12841 "?",
12842 ];
12843 for &input in candidates {
12844 let via_trait: Option<RestartPolicy> =
12845 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
12846 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
12847 assert_eq!(
12848 via_trait, via_method,
12849 "TryFrom<&str> and from_wire must resolve identically on \
12850 input {input:?} — divergence signals the two reverse-\
12851 projection paths have drifted onto different accept-sets"
12852 );
12853 }
12854 }
12855
12856 #[test]
12857 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
12858 // Fail-before-pass-after byte-parity pin on the newly lifted
12859 // `impl From<RestartPolicy> for &'static str` — asserts the
12860 // standard-library trait impl and the substrate-primitive
12861 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
12862 // the same three-arm emit-set across every arm the exhaustive
12863 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
12864 // detour that routes the trait impl through a divergent
12865 // projection (a per-arm inline `match policy { Permanent =>
12866 // "Permanent", … }` re-inlining that opens a compile-time link
12867 // to the un-lifted arm-literal, an accidental swap onto the
12868 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
12869 // axis that would collide the two-axis wire/catalog split the
12870 // sibling [`RestartPolicy::from_wire`] doc block makes
12871 // load-bearing) trips at caixa-core test time under
12872 // `assert_eq!` rather than at a downstream
12873 // `impl Into<&'static str>`-bound consumer's silent split.
12874 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
12875 // carries so no arm's projection is covered only by the sibling
12876 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
12877 // paths. Materializes the `<&'static str as
12878 // From<RestartPolicy>>::from` output in a `const`-shape binding
12879 // to make the `'static` lifetime promise a build-time invariant
12880 // — a future accidental downgrade of any of the three arms'
12881 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
12882 // non-`&'static str` (a `String::leak()`-produced return, a
12883 // `Box::leak`-cast) trips at caixa-core build time rather than
12884 // at a downstream `'static`-bound consumer. Peer of the sibling
12885 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
12886 // (523157d) — extends the trait-idiomatic forward-projection
12887 // axis onto the second (and second-of-two-in-M2) closed-set
12888 // typed enum on the caixa surface (the paired per-child
12889 // restart-decision-policy sibling on the same M2 `:supervisor`
12890 // slot).
12891 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
12892 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
12893 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
12894 for &variant in RestartPolicy::ALL {
12895 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12896 let via_method: &'static str = variant.as_str();
12897 assert_eq!(
12898 via_trait, via_method,
12899 "From<RestartPolicy> for &'static str impl must round-trip \
12900 RestartPolicy::{variant:?} to the same lifted \
12901 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
12902 divergence signals a silent detour off the substrate-primitive \
12903 accessor"
12904 );
12905 let via_into: &'static str = variant.into();
12906 assert_eq!(
12907 via_into, via_method,
12908 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
12909 byte-equal RestartPolicy::as_str on the same input — the \
12910 blanket-derived Into shape must resolve to the same as_str \
12911 dispatch as the explicit From impl"
12912 );
12913 }
12914 assert_eq!(
12915 [PERMANENT, TEMPORARY, TRANSIENT],
12916 [
12917 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12918 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12919 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12920 ],
12921 "const-context RestartPolicy::as_str must resolve to the three \
12922 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
12923 downgrade of any arm to a non-const or non-static byte-string \
12924 breaks the `&'static str`-lifetime promise the paired \
12925 From<RestartPolicy> for &'static str impl carries by \
12926 construction"
12927 );
12928 }
12929
12930 #[test]
12931 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
12932 // Cross-axis partition pin: the paired trait-idiomatic
12933 // `From<RestartPolicy> for &'static str` forward projection and
12934 // the method-named [`RestartPolicy::as_str`] forward projection
12935 // must resolve identically on *every* arm, not just the ones
12936 // named in the primary byte-parity pin above. Sweeps every
12937 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
12938 // output byte-equals the method-named accessor's return-value on
12939 // each, locking the two forward-projection paths together by
12940 // construction so any future detour (a stray `From` special-case
12941 // that lands on a divergent per-arm literal outside the paired
12942 // `as_str` dispatch, a hypothetical rebrand touching one axis
12943 // without the other) trips at caixa-core test time. Peer of the
12944 // sibling forward-projection partition pin
12945 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
12946 // (523157d) — extends the round-trip discipline onto the
12947 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
12948 // surface, closing the two-way `Self ↔ &'static str` round-trip
12949 // on the trait-idiomatic pair (`From<Self> for &'static str` +
12950 // `TryFrom<&str> for Self`) as well as the pre-existing method-
12951 // named pair (`as_str` + `from_wire`).
12952 for &variant in RestartPolicy::ALL {
12953 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12954 let via_method: &'static str = variant.as_str();
12955 assert_eq!(
12956 via_trait, via_method,
12957 "From<RestartPolicy> for &'static str and \
12958 RestartPolicy::as_str must resolve identically on \
12959 RestartPolicy::{variant:?} — divergence signals the \
12960 two forward-projection paths have drifted onto different \
12961 emit-sets"
12962 );
12963 }
12964 // Round-trip witness: every arm's forward `From` output re-parses
12965 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
12966 // to the original variant. Closes the two-way `RestartPolicy ↔
12967 // &'static str` round-trip on the trait-idiomatic axis pair,
12968 // mirroring the pre-existing method-named `as_str` + `from_wire`
12969 // round-trip on the substrate-primitive axis pair.
12970 for &variant in RestartPolicy::ALL {
12971 let emitted: &'static str = variant.into();
12972 let re_parsed: Result<RestartPolicy, ()> =
12973 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
12974 assert_eq!(
12975 re_parsed,
12976 Ok(variant),
12977 "trait-idiomatic axis pair must round-trip \
12978 RestartPolicy::{variant:?} through `.into::<&'static \
12979 str>()` and back through `TryFrom<&str>` — a break signals \
12980 the forward-emit and reverse-parse axes have drifted onto \
12981 different vocabularies"
12982 );
12983 }
12984 }
12985
12986 #[test]
12987 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
12988 // Fail-before-pass-after byte-parity pin on the newly lifted
12989 // `impl From<&RestartPolicy> for &'static str` — asserts the
12990 // borrowed-input standard-library trait impl and the substrate-
12991 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
12992 // resolve to the same three-arm emit-set across every arm the
12993 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
12994 // `From` trait does not auto-derive the borrowed-input sibling
12995 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
12996 // where T: Copy, U: From<T>` blanket in `core`), so the
12997 // borrowed-input axis is a distinct trait-idiomatic surface
12998 // that a `.iter().map(Into::into)` shape over
12999 // [`RestartPolicy::ALL`] (whose iterator yields
13000 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
13001 // impl and no other — the paired owned-input
13002 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
13003 // / dereference before the trait fires. Materializes the
13004 // `<&'static str as From<&RestartPolicy>>::from` output in a
13005 // `const`-shape binding to make the `'static` lifetime promise
13006 // a build-time invariant.
13007 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
13008 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
13009 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
13010 for variant in RestartPolicy::ALL {
13011 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
13012 let via_method: &'static str = variant.as_str();
13013 assert_eq!(
13014 via_trait, via_method,
13015 "From<&RestartPolicy> for &'static str impl must round-trip \
13016 &RestartPolicy::{variant:?} to the same lifted \
13017 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
13018 returns — divergence signals a silent detour off the \
13019 substrate-primitive accessor"
13020 );
13021 let via_into: &'static str = variant.into();
13022 assert_eq!(
13023 via_into, via_method,
13024 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
13025 must byte-equal RestartPolicy::as_str on the same input — \
13026 the blanket-derived Into shape must resolve to the same \
13027 as_str dispatch as the explicit From impl"
13028 );
13029 }
13030 assert_eq!(
13031 [PERMANENT, TEMPORARY, TRANSIENT],
13032 [
13033 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
13034 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
13035 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
13036 ],
13037 "const-context RestartPolicy::as_str must resolve to the three \
13038 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
13039 From<&RestartPolicy> for &'static str impl inherits its \
13040 `'static` lifetime promise from the same accessor the \
13041 owned-input sibling routes through"
13042 );
13043 }
13044
13045 #[test]
13046 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
13047 // Cross-axis partition pin: the paired trait-idiomatic
13048 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
13049 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
13050 // &'static str` (this lift) forward projections must resolve
13051 // identically on every arm, locking the two input-shape paths
13052 // together so any future detour trips at caixa-core test time.
13053 // Then a witness that a `.iter().map(Into::into)` pipe over
13054 // [`RestartPolicy::ALL`] (whose iterator yields
13055 // `&RestartPolicy`) materializes the three-arm accept-set
13056 // through the borrowed-input axis alone — the exact shape a
13057 // future wasm-operator per-child post-exit restart-decision
13058 // diagnostic line, a future substrate-wide per-arm diagnostic
13059 // column, or a
13060 // `HashMap::<&'static str, RestartPolicy>::from_iter(
13061 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
13062 // per-policy lookup reaches through — closing the two-way
13063 // owned/borrowed input-shape symmetry on the forward-projection
13064 // trait-idiomatic axis. Peer of the sibling
13065 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
13066 // (64aa742) /
13067 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
13068 // (5ab993a) /
13069 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
13070 // (807b0b5) /
13071 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
13072 // (e941836) partition pins on the sibling closed-set typed-enum
13073 // discriminator axes — extends the borrowed-input axis
13074 // discipline onto the second-of-two M2 OTP-shape closed-set
13075 // typed enum on the caixa surface (per-child restart-decision
13076 // policy). Also closes the direct two-way `&Self → &'static
13077 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
13078 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
13079 // forward `From` emits lowercase Portuguese diagnostic bytes
13080 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
13081 // forcing the round-trip through an intermediate wire-vocab
13082 // hop), the [`RestartPolicy::as_str`] emit and
13083 // [`RestartPolicy::from_wire`] parse share the same
13084 // `PascalCase` vocabulary by construction, so the borrowed-
13085 // input forward axis and the reverse axis compose directly.
13086 for &variant in RestartPolicy::ALL {
13087 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13088 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
13089 assert_eq!(
13090 owned, borrowed,
13091 "From<RestartPolicy> and From<&RestartPolicy> for \
13092 &'static str must resolve identically on \
13093 RestartPolicy::{variant:?} — divergence signals the \
13094 owned-input and borrowed-input forward-projection paths \
13095 have drifted onto different emit-sets"
13096 );
13097 }
13098 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
13099 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
13100 assert_eq!(
13101 via_iter, via_method,
13102 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
13103 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
13104 borrowed-input `From<&RestartPolicy> for &'static str` axis \
13105 is what makes the `.iter().map(Into::into)` shape route \
13106 through the substrate-primitive `RestartPolicy::as_str` \
13107 accessor rather than through a per-call-site `.copied()` / \
13108 dereference detour"
13109 );
13110 for variant in RestartPolicy::ALL {
13111 let emitted: &'static str = variant.into();
13112 let re_parsed: Result<RestartPolicy, ()> =
13113 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
13114 assert_eq!(
13115 re_parsed,
13116 Ok(*variant),
13117 "trait-idiomatic borrowed-input forward-projection + \
13118 reverse-projection axis pair must round-trip \
13119 &RestartPolicy::{variant:?} through `.into::<&'static \
13120 str>()` (via the borrowed-input axis) and back through \
13121 `TryFrom<&str>` — a break signals the borrowed-input \
13122 forward-emit and reverse-parse axes have drifted onto \
13123 different vocabularies"
13124 );
13125 }
13126 }
13127
13128 #[test]
13129 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
13130 // Fail-before-pass-after byte-parity pin on the newly lifted
13131 // `impl From<RestartPolicy> for String` — asserts the
13132 // owned-`String`-returning standard-library trait impl and the
13133 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
13134 // accessor resolve to the same three-arm emit-set across every
13135 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
13136 // Rust's standard library does not carry a blanket
13137 // `impl<T: AsRef<str>> From<T> for String` (nor an
13138 // `impl<T: fmt::Display> From<T> for String`), so the
13139 // owned-`String` forward-projection axis is a distinct
13140 // trait-idiomatic surface that a `let key: String =
13141 // policy.into();`-shaped call site reaches through this impl
13142 // and no other — the paired sibling `From<RestartPolicy> for
13143 // &'static str` impl forces every owned-`String` call site
13144 // through an explicit `.to_owned()` / `String::from`
13145 // restatement. Peer of the first-mover
13146 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
13147 // (7baa18a) — extends the trait-idiomatic owned-`String`
13148 // forward-projection axis onto the second-of-two M2 OTP-shape
13149 // closed-set typed enums on the caixa surface (per-child
13150 // restart-decision-policy sibling on the same M2 `:supervisor`
13151 // slot).
13152 for &variant in RestartPolicy::ALL {
13153 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
13154 let via_method: &'static str = variant.as_str();
13155 assert_eq!(
13156 via_trait.as_str(),
13157 via_method,
13158 "From<RestartPolicy> for String impl must round-trip \
13159 RestartPolicy::{variant:?} to the same lifted \
13160 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
13161 returns — divergence signals a silent detour off the \
13162 substrate-primitive accessor"
13163 );
13164 let via_into: String = variant.into();
13165 assert_eq!(
13166 via_into.as_str(),
13167 via_method,
13168 "Into<String>::into on RestartPolicy::{variant:?} must \
13169 byte-equal RestartPolicy::as_str on the same input — the \
13170 blanket-derived Into shape must resolve to the same as_str \
13171 dispatch as the explicit From impl"
13172 );
13173 }
13174 }
13175
13176 #[test]
13177 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
13178 // Cross-axis partition pin: the paired trait-idiomatic
13179 // owned-`String` `From<RestartPolicy> for String` (this lift)
13180 // and owned-`&'static str` `From<RestartPolicy> for &'static
13181 // str` (9fb37d0) forward projections must resolve identically
13182 // on every arm, locking the two return-type-shape paths
13183 // together so any future detour trips at caixa-core test time.
13184 // Also byte-parity witness against the sibling
13185 // [`ToString::to_string`] surface routed through
13186 // [`std::fmt::Display`] — the three owned-heap-string paths
13187 // (`.into::<String>()`, `String::from`, `.to_string()`) must
13188 // resolve identically on every arm so a future consumer that
13189 // picks any of the three lands on the same lifted
13190 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
13191 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
13192 // that materializes the three-arm accept-set through the
13193 // owned-`String` axis alone — the exact shape a future
13194 // wasm-operator per-child post-exit restart-decision
13195 // diagnostic line composer or a
13196 // `HashMap::<String, RestartPolicy>::from_iter(
13197 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
13198 // owned-key per-policy lookup reaches through — closing the
13199 // owned-`String` forward-projection axis's iterator-pipe
13200 // shape. Then a direct round-trip witness through the paired
13201 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
13202 // owned-`String`'s [`String::as_str`] borrow that closes the
13203 // two-way `Self → String → Self` round-trip on the trait-
13204 // idiomatic owned-`String` forward + reverse axis pair —
13205 // unlike the peer [`crate::CaixaKind`] axis pair (whose
13206 // forward `From` emits lowercase Portuguese diagnostic bytes
13207 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
13208 // forcing the round-trip through an intermediate wire-vocab
13209 // hop), the [`RestartPolicy::as_str`] emit and
13210 // [`RestartPolicy::from_wire`] parse share the same
13211 // `PascalCase` vocabulary by construction, so the owned-
13212 // `String` forward axis and the reverse axis compose directly.
13213 for &variant in RestartPolicy::ALL {
13214 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13215 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13216 assert_eq!(
13217 owned_string.as_str(),
13218 owned_static,
13219 "From<RestartPolicy> for String and From<RestartPolicy> \
13220 for &'static str must resolve identically on \
13221 RestartPolicy::{variant:?} — divergence signals the \
13222 owned-`String` and owned-`&'static str` forward-projection \
13223 return-type-shape paths have drifted onto different \
13224 emit-sets"
13225 );
13226 let via_to_string: String = variant.to_string();
13227 assert_eq!(
13228 owned_string, via_to_string,
13229 "From<RestartPolicy> for String must byte-equal \
13230 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
13231 divergence signals the trait-idiomatic owned-`String` \
13232 forward-projection axis and the ToString-through-Display \
13233 axis have drifted onto different emit-sets"
13234 );
13235 }
13236 let via_iter: Vec<String> = RestartPolicy::ALL
13237 .iter()
13238 .copied()
13239 .map(String::from)
13240 .collect();
13241 let via_method: Vec<String> = RestartPolicy::ALL
13242 .iter()
13243 .map(|p| p.as_str().to_owned())
13244 .collect();
13245 assert_eq!(
13246 via_iter, via_method,
13247 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
13248 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
13249 every arm — the owned-`String` `From<RestartPolicy> for \
13250 String` axis is what makes the `String::from` composition \
13251 route through the substrate-primitive `RestartPolicy::as_str` \
13252 accessor rather than through a per-call-site `.to_owned()` / \
13253 `String::from(policy.as_str())` detour"
13254 );
13255 for &variant in RestartPolicy::ALL {
13256 let emitted: String = variant.into();
13257 let re_parsed: Result<RestartPolicy, ()> =
13258 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
13259 assert_eq!(
13260 re_parsed,
13261 Ok(variant),
13262 "trait-idiomatic owned-`String` forward-projection + \
13263 reverse-projection axis pair must round-trip \
13264 RestartPolicy::{variant:?} through `.into::<String>()` \
13265 and back through `TryFrom<&str>` on the owned-`String`'s \
13266 String::as_str borrow — a break signals the owned-`String` \
13267 forward-emit and reverse-parse axes have drifted onto \
13268 different vocabularies"
13269 );
13270 }
13271 }
13272
13273 #[test]
13274 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
13275 // Fail-before-pass-after byte-parity pin on the newly lifted
13276 // `impl From<&RestartPolicy> for String` — asserts the
13277 // borrowed-input owned-`String`-returning standard-library
13278 // trait impl and the substrate-primitive
13279 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
13280 // the same three-arm emit-set across every arm the exhaustive
13281 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
13282 // library does not carry a blanket `impl<T: AsRef<str>>
13283 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
13284 // for String`), so the borrowed-input owned-`String` forward-
13285 // projection axis is a distinct trait-idiomatic surface that a
13286 // `let key: String = (&policy).into();`-shaped call site
13287 // reaches through this impl and no other — the paired sibling
13288 // `From<RestartPolicy> for String` impl forces every borrowed-
13289 // input call site through an explicit `Copy` deref
13290 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
13291 // `.to_string()` detour. Peer of the first-mover
13292 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
13293 // (579385f) — extends the trait-idiomatic borrowed-input
13294 // owned-`String` forward-projection axis onto the second-of-
13295 // two M2 OTP-shape closed-set typed enums on the caixa surface
13296 // (per-child restart-decision-policy sibling on the same M2
13297 // `:supervisor` slot).
13298 for &variant in RestartPolicy::ALL {
13299 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
13300 let via_method: &'static str = variant.as_str();
13301 assert_eq!(
13302 via_trait.as_str(),
13303 via_method,
13304 "From<&RestartPolicy> for String impl must round-trip \
13305 &RestartPolicy::{variant:?} to the same lifted \
13306 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
13307 returns — divergence signals a silent detour off the \
13308 substrate-primitive accessor"
13309 );
13310 let via_into: String = (&variant).into();
13311 assert_eq!(
13312 via_into.as_str(),
13313 via_method,
13314 "Into<String>::into on &RestartPolicy::{variant:?} must \
13315 byte-equal RestartPolicy::as_str on the same input — \
13316 the blanket-derived Into shape must resolve to the \
13317 same as_str dispatch as the explicit From impl"
13318 );
13319 }
13320 }
13321
13322 #[test]
13323 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
13324 // Cross-axis partition pin: the newly lifted trait-idiomatic
13325 // borrowed-input owned-`String` `From<&RestartPolicy> for
13326 // String` (this lift), the paired owned-input owned-`String`
13327 // `From<RestartPolicy> for String` (7851725), the paired
13328 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
13329 // for &'static str` (842c7f3), and the paired owned-input
13330 // owned-`&'static str` `From<RestartPolicy> for &'static str`
13331 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
13332 // str, String}` 2×2 trait-idiomatic projection family — must
13333 // resolve identically on every arm, locking the four
13334 // return-shape × input-shape paths together so any future
13335 // detour trips at caixa-core test time. Also byte-parity
13336 // witness against the sibling [`ToString::to_string`] surface
13337 // routed through [`std::fmt::Display`] and a direct round-trip
13338 // witness through the paired trait-idiomatic reverse
13339 // [`TryFrom<&str>`] axis on the owned-`String`'s
13340 // [`String::as_str`] borrow that closes the two-way
13341 // `&Self → String → Self` round-trip on the trait-idiomatic
13342 // borrowed-input owned-`String` forward + reverse axis pair.
13343 // Peer of the first-mover
13344 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
13345 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
13346 // String}` 2×2 projection corner on both M2 OTP-shape sibling
13347 // peers.
13348 for &variant in RestartPolicy::ALL {
13349 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
13350 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13351 let borrowed_static: &'static str =
13352 <&'static str as From<&RestartPolicy>>::from(&variant);
13353 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13354 assert_eq!(
13355 borrowed_string, owned_string,
13356 "From<&RestartPolicy> for String and From<RestartPolicy> \
13357 for String must resolve identically on \
13358 RestartPolicy::{variant:?} — divergence signals the \
13359 borrowed-input and owned-input owned-`String` \
13360 forward-projection input-shape paths have drifted onto \
13361 different emit-sets"
13362 );
13363 assert_eq!(
13364 borrowed_string.as_str(),
13365 borrowed_static,
13366 "From<&RestartPolicy> for String and From<&RestartPolicy> \
13367 for &'static str must resolve identically on \
13368 RestartPolicy::{variant:?} — divergence signals the \
13369 borrowed-input `&'static str` and owned-`String` \
13370 return-shape paths have drifted onto different \
13371 emit-sets"
13372 );
13373 assert_eq!(
13374 borrowed_string.as_str(),
13375 owned_static,
13376 "From<&RestartPolicy> for String and From<RestartPolicy> \
13377 for &'static str must resolve identically on \
13378 RestartPolicy::{variant:?} — divergence signals a \
13379 break in the diagonal corner of the {{Self, &Self}} × \
13380 {{&'static str, String}} 2×2 trait-idiomatic \
13381 projection family"
13382 );
13383 let via_to_string: String = variant.to_string();
13384 assert_eq!(
13385 borrowed_string, via_to_string,
13386 "From<&RestartPolicy> for String must byte-equal \
13387 RestartPolicy::to_string on RestartPolicy::{variant:?} \
13388 — divergence signals the trait-idiomatic borrowed-input \
13389 owned-`String` forward-projection axis and the \
13390 ToString-through-Display axis have drifted onto \
13391 different emit-sets"
13392 );
13393 }
13394 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
13395 let via_method: Vec<String> = RestartPolicy::ALL
13396 .iter()
13397 .map(|p| p.as_str().to_owned())
13398 .collect();
13399 assert_eq!(
13400 via_iter, via_method,
13401 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
13402 call site whose iteration axis holds `&RestartPolicy` by \
13403 construction — must byte-equal `.iter().map(|p| \
13404 p.as_str().to_owned())` on every arm — the borrowed-input \
13405 owned-`String` `From<&RestartPolicy> for String` axis is \
13406 what makes the `String::from` composition route through \
13407 the substrate-primitive `RestartPolicy::as_str` accessor \
13408 without a spurious `Copy` deref (which would only be \
13409 reachable through the owned-input `From<RestartPolicy> \
13410 for String` axis by first calling `.copied()` on the \
13411 iterator)"
13412 );
13413 for &variant in RestartPolicy::ALL {
13414 let emitted: String = (&variant).into();
13415 let re_parsed: Result<RestartPolicy, ()> =
13416 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
13417 assert_eq!(
13418 re_parsed,
13419 Ok(variant),
13420 "trait-idiomatic borrowed-input owned-`String` \
13421 forward-projection + reverse-projection axis pair must \
13422 round-trip &RestartPolicy::{variant:?} through \
13423 `.into::<String>()` on the borrowed-input surface and \
13424 back through `TryFrom<&str>` on the owned-`String`'s \
13425 String::as_str borrow — a break signals the \
13426 borrowed-input owned-`String` forward-emit and \
13427 reverse-parse axes have drifted onto different \
13428 vocabularies"
13429 );
13430 }
13431 }
13432
13433 #[test]
13434 fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
13435 // Fail-before-pass-after byte-parity pin on the newly lifted
13436 // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
13437 // asserts the standard-library trait impl and the substrate-
13438 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
13439 // accessor resolve to the same three-arm emit-set across every
13440 // arm the exhaustive [`super::RestartPolicy::ALL`] slice
13441 // enumerates. Rust's standard library does not carry a blanket
13442 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
13443 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
13444 // the `Cow<'static, str>` forward-projection axis is a
13445 // distinct trait-idiomatic surface that a
13446 // `let key: Cow<'static, str> = policy.into();`-shaped call
13447 // site reaches through this impl and no other — the paired
13448 // sibling `From<RestartPolicy> for &'static str` and
13449 // `From<RestartPolicy> for String` impls force every
13450 // `Cow<'static, str>`-parameterized call site through a
13451 // `Cow::Borrowed(policy.as_str())` /
13452 // `Cow::Owned(policy.to_string())` composition whose type
13453 // bounds have no compile-time link back to the substrate
13454 // primitive.
13455 //
13456 // Also asserts the projection lands on the zero-alloc
13457 // [`std::borrow::Cow::Borrowed`] arm (not the
13458 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
13459 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
13460 // return lifetime by construction makes the borrowed arm the
13461 // type-correct projection with no runtime allocation. Any
13462 // future silent detour that routes the impl through the owned
13463 // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
13464 // that would allocate on every call site where the
13465 // `&'static str` return of [`super::RestartPolicy::as_str`]
13466 // makes the zero-alloc borrowed projection type-correct) trips
13467 // at caixa-core test time under the
13468 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
13469 // than at a downstream `Cow<'static, str>`-bound consumer's
13470 // silent allocation.
13471 //
13472 // Second peer on the substrate-wide trait-idiomatic
13473 // [`std::borrow::Cow<'static, str>`] forward-projection family
13474 // to extend the axis off the top-level [`super::CaixaKind`]
13475 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
13476 // second (and second-of-two-in-M2) M2 OTP-shape closed-set
13477 // fieldless typed enum peer on the caixa surface — closes the
13478 // M2 OTP-shape tier of the campaign on the owned-input axis
13479 // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
13480 // now carry the owned-input Cow<'static, str> forward
13481 // projection).
13482 for &variant in RestartPolicy::ALL {
13483 let via_trait: std::borrow::Cow<'static, str> =
13484 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13485 let via_method: &'static str = variant.as_str();
13486 assert_eq!(
13487 via_trait.as_ref(),
13488 via_method,
13489 "From<RestartPolicy> for Cow<'static, str> impl must \
13490 round-trip RestartPolicy::{variant:?} to the same \
13491 lifted SUPERVISOR_CHILD_RESTART_* const \
13492 RestartPolicy::as_str returns — divergence signals a \
13493 silent detour off the substrate-primitive accessor"
13494 );
13495 assert!(
13496 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
13497 "From<RestartPolicy> for Cow<'static, str> impl must \
13498 land on the zero-alloc Cow::Borrowed arm on \
13499 RestartPolicy::{variant:?} — a Cow::Owned outcome \
13500 signals the projection has silently allocated where \
13501 the substrate-primitive RestartPolicy::as_str \
13502 `&'static str` return makes the borrowed arm the \
13503 type-correct projection"
13504 );
13505 let via_into: std::borrow::Cow<'static, str> = variant.into();
13506 assert_eq!(
13507 via_into.as_ref(),
13508 via_method,
13509 "Into<Cow<'static, str>>::into on \
13510 RestartPolicy::{variant:?} must byte-equal \
13511 RestartPolicy::as_str on the same input — the \
13512 blanket-derived Into shape must resolve to the same \
13513 as_str dispatch as the explicit From impl"
13514 );
13515 assert!(
13516 matches!(via_into, std::borrow::Cow::Borrowed(_)),
13517 "Into<Cow<'static, str>>::into on \
13518 RestartPolicy::{variant:?} must land on the \
13519 zero-alloc Cow::Borrowed arm — the blanket-derived \
13520 Into shape must resolve to the same Cow::Borrowed \
13521 dispatch as the explicit From impl"
13522 );
13523 }
13524 }
13525
13526 #[test]
13527 fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
13528 // Cross-axis partition pin: the newly lifted trait-idiomatic
13529 // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
13530 // (this lift), the paired owned-input `From<RestartPolicy>
13531 // for &'static str` (9fb37d0), and the paired owned-input
13532 // `From<RestartPolicy> for String` (7851725) forward
13533 // projections must resolve identically on every arm, locking
13534 // the three return-shape paths together by construction so any
13535 // future detour trips at caixa-core test time. Also byte-parity
13536 // witness against the sibling [`ToString::to_string`] surface
13537 // routed through [`std::fmt::Display`] — every owned-heap-
13538 // string path (the `Cow::Owned` promotion of this axis's
13539 // `.into_owned()`, `From<RestartPolicy> for String`, and
13540 // `.to_string()`) resolves to the same lifted
13541 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
13542 //
13543 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
13544 // witness over [`super::RestartPolicy::ALL`] that
13545 // materializes the three-arm accept-set through the
13546 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
13547 // shape a future `axum::response::IntoResponse` per-policy
13548 // rejection-body composer, a future M4 admission-webhook
13549 // per-policy rejection-reason emitter whose typing rules out
13550 // the sibling [`AsRef<str>`] borrowed return, or a future
13551 // substrate-wide per-policy diagnostic surface that binds
13552 // through a [`Cow<'static, str>`] boundary reaches through.
13553 // The pipe witness also pins the zero-alloc discipline: every
13554 // element in the collected vector satisfies the
13555 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
13556 // accidental silent-allocation regression on the pipe's
13557 // iteration axis is a caixa-core-test-time failure. Peer of
13558 // the first-mover
13559 // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
13560 // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
13561 // — closes the whole owned-input `Cow<'static, str>` +
13562 // paired `{&'static str, String}` cross-axis-parity corner on
13563 // both M2 OTP-shape sibling peers.
13564 for &variant in RestartPolicy::ALL {
13565 let via_cow: std::borrow::Cow<'static, str> =
13566 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13567 let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13568 let via_string: String = <String as From<RestartPolicy>>::from(variant);
13569 assert_eq!(
13570 via_cow.as_ref(),
13571 via_static,
13572 "From<RestartPolicy> for Cow<'static, str> and \
13573 From<RestartPolicy> for &'static str must resolve \
13574 identically on RestartPolicy::{variant:?} — \
13575 divergence signals the Cow<'static, str> and \
13576 &'static str return-shape paths have drifted onto \
13577 different emit-sets"
13578 );
13579 assert_eq!(
13580 via_cow.as_ref(),
13581 via_string.as_str(),
13582 "From<RestartPolicy> for Cow<'static, str> and \
13583 From<RestartPolicy> for String must resolve \
13584 identically on RestartPolicy::{variant:?} — \
13585 divergence signals the Cow<'static, str> and String \
13586 return-shape paths have drifted onto different \
13587 emit-sets"
13588 );
13589 let via_to_string: String = variant.to_string();
13590 assert_eq!(
13591 via_cow.as_ref(),
13592 via_to_string.as_str(),
13593 "From<RestartPolicy> for Cow<'static, str> must \
13594 byte-equal RestartPolicy::to_string on \
13595 RestartPolicy::{variant:?} — divergence signals the \
13596 trait-idiomatic Cow<'static, str> forward-projection \
13597 axis and the ToString-through-Display axis have \
13598 drifted onto different emit-sets"
13599 );
13600 }
13601 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13602 .iter()
13603 .copied()
13604 .map(std::borrow::Cow::from)
13605 .collect();
13606 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13607 .iter()
13608 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
13609 .collect();
13610 assert_eq!(
13611 via_iter, via_method,
13612 "`.iter().copied().map(Cow::from)` over \
13613 RestartPolicy::ALL must byte-equal `.iter().map(|p| \
13614 Cow::Borrowed(p.as_str()))` on every arm — the \
13615 trait-idiomatic `From<RestartPolicy> for Cow<'static, \
13616 str>` axis is what makes the `Cow::from` composition \
13617 route through the substrate-primitive \
13618 `RestartPolicy::as_str` accessor with the zero-alloc \
13619 Cow::Borrowed arm by construction, rather than a \
13620 per-call-site `Cow::Owned(policy.to_string())` \
13621 allocation"
13622 );
13623 for cow in &via_iter {
13624 assert!(
13625 matches!(cow, std::borrow::Cow::Borrowed(_)),
13626 "every element of the \
13627 .iter().copied().map(Cow::from) pipe over \
13628 RestartPolicy::ALL must land on the zero-alloc \
13629 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
13630 signals the pipe's iteration axis has silently \
13631 allocated where the substrate-primitive \
13632 RestartPolicy::as_str `&'static str` return makes \
13633 the borrowed arm the type-correct projection"
13634 );
13635 }
13636 }
13637
13638 #[test]
13639 fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
13640 // Fail-before-pass-after byte-parity pin on the newly lifted
13641 // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
13642 // asserts the borrowed-input standard-library trait impl and
13643 // the substrate-primitive [`super::RestartPolicy::as_str`]
13644 // `pub const fn` accessor resolve to the same three-arm emit-
13645 // set across every arm the exhaustive
13646 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
13647 // standard library does not carry a blanket
13648 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
13649 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
13650 // the borrowed-input `Cow<'static, str>` forward-projection
13651 // axis is a distinct trait-idiomatic surface that a
13652 // `let key: Cow<'static, str> = (&policy).into();`-shaped
13653 // call site or a
13654 // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
13655 // reaches through this impl and no other — the paired owned-
13656 // input `From<RestartPolicy> for Cow<'static, str>` impl
13657 // (0612398) forces every borrowed-input call site through an
13658 // explicit `Copy` deref (`Cow::from(*policy)`) or a
13659 // `Cow::Borrowed(policy.as_str())` open-code whose type
13660 // bounds have no compile-time link back to the substrate
13661 // primitive.
13662 //
13663 // Also asserts the projection lands on the zero-alloc
13664 // [`std::borrow::Cow::Borrowed`] arm (not the
13665 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
13666 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
13667 // return lifetime by construction makes the borrowed arm the
13668 // type-correct projection with no runtime allocation on the
13669 // borrowed-input surface just as on the paired owned-input
13670 // surface.
13671 //
13672 // Closes the `{Self, &Self}` input-shape corner on the M2
13673 // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
13674 // the second-of-two-in-M2 closed-set fieldless typed enum peer
13675 // on the caixa surface (`:supervisor :children :restart`),
13676 // exactly as d45c409 closed it on the top-level
13677 // [`super::CaixaKind`] one commit after the owning half
13678 // (99c1735) landed and as 9b3e4b3 closed it on the sibling
13679 // M2 OTP-shape [`super::RestartStrategy`] one commit after
13680 // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
13681 // tier of the substrate-wide Cow<'static, str> forward-
13682 // projection campaign on both input-shape corners
13683 // ({Self, &Self}) of both M2 OTP-shape sibling peers.
13684 for &variant in RestartPolicy::ALL {
13685 let via_trait: std::borrow::Cow<'static, str> =
13686 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
13687 let via_method: &'static str = variant.as_str();
13688 assert_eq!(
13689 via_trait.as_ref(),
13690 via_method,
13691 "From<&RestartPolicy> for Cow<'static, str> impl must \
13692 round-trip &RestartPolicy::{variant:?} to the same \
13693 lifted SUPERVISOR_CHILD_RESTART_* const \
13694 RestartPolicy::as_str returns — divergence signals a \
13695 silent detour off the substrate-primitive accessor"
13696 );
13697 assert!(
13698 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
13699 "From<&RestartPolicy> for Cow<'static, str> impl must \
13700 land on the zero-alloc Cow::Borrowed arm on \
13701 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
13702 signals the projection has silently allocated where \
13703 the substrate-primitive RestartPolicy::as_str \
13704 `&'static str` return makes the borrowed arm the \
13705 type-correct projection"
13706 );
13707 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
13708 assert_eq!(
13709 via_into.as_ref(),
13710 via_method,
13711 "Into<Cow<'static, str>>::into on \
13712 &RestartPolicy::{variant:?} must byte-equal \
13713 RestartPolicy::as_str on the same input — the \
13714 blanket-derived Into shape must resolve to the same \
13715 as_str dispatch as the explicit From impl"
13716 );
13717 assert!(
13718 matches!(via_into, std::borrow::Cow::Borrowed(_)),
13719 "Into<Cow<'static, str>>::into on \
13720 &RestartPolicy::{variant:?} must land on the \
13721 zero-alloc Cow::Borrowed arm — the blanket-derived \
13722 Into shape must resolve to the same Cow::Borrowed \
13723 dispatch as the explicit From impl"
13724 );
13725 }
13726 }
13727
13728 #[test]
13729 fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
13730 // Cross-axis partition pin: the newly lifted trait-idiomatic
13731 // borrowed-input `From<&RestartPolicy> for
13732 // std::borrow::Cow<'static, str>` (this lift), the paired
13733 // owned-input `From<RestartPolicy> for
13734 // std::borrow::Cow<'static, str>` (0612398), the paired
13735 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
13736 // for &'static str`, and the paired borrowed-input owned-
13737 // `String` `From<&RestartPolicy> for String` must resolve
13738 // identically on every arm, locking the four
13739 // return-shape × input-shape paths together by construction so
13740 // any future detour trips at caixa-core test time. Also byte-
13741 // parity witness against the sibling [`ToString::to_string`]
13742 // surface routed through [`std::fmt::Display`] — every owned-
13743 // heap-string path (this axis's `.into_owned()` promotion, the
13744 // paired [`From<&RestartPolicy> for String`], and
13745 // `.to_string()`) resolves to the same lifted
13746 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
13747 //
13748 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
13749 // over [`super::RestartPolicy::ALL`] — whose iterator yields
13750 // `&RestartPolicy` by construction, so the borrowed-input
13751 // [`Cow<'static, str>`] axis is what routes the pipe through
13752 // the substrate-primitive [`super::RestartPolicy::as_str`]
13753 // accessor without a spurious [`Copy`] deref (which would only
13754 // be reachable through the owned-input
13755 // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
13756 // calling `.copied()` on the iterator). The pipe witness also
13757 // pins the zero-alloc discipline: every element in the
13758 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
13759 // arm predicate, so a future accidental silent-allocation
13760 // regression on the pipe's iteration axis is a caixa-core-
13761 // test-time failure. Peer of the sibling
13762 // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
13763 // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
13764 // the whole borrowed-input `Cow<'static, str>` +
13765 // paired `{&'static str, String}` cross-axis-parity corner on
13766 // both M2 OTP-shape sibling peers.
13767 for &policy in RestartPolicy::ALL {
13768 let borrowed_cow: std::borrow::Cow<'static, str> =
13769 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
13770 let owned_cow: std::borrow::Cow<'static, str> =
13771 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
13772 let borrowed_static: &'static str =
13773 <&'static str as From<&RestartPolicy>>::from(&policy);
13774 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
13775 assert_eq!(
13776 borrowed_cow, owned_cow,
13777 "From<&RestartPolicy> for Cow<'static, str> and \
13778 From<RestartPolicy> for Cow<'static, str> must \
13779 resolve identically on RestartPolicy::{policy:?} — \
13780 divergence signals the borrowed-input and owned-input \
13781 Cow<'static, str> forward-projection input-shape \
13782 paths have drifted onto different emit-sets"
13783 );
13784 assert_eq!(
13785 borrowed_cow.as_ref(),
13786 borrowed_static,
13787 "From<&RestartPolicy> for Cow<'static, str> and \
13788 From<&RestartPolicy> for &'static str must resolve \
13789 identically on RestartPolicy::{policy:?} — \
13790 divergence signals the borrowed-input Cow<'static, \
13791 str> and &'static str return-shape paths have drifted \
13792 onto different emit-sets"
13793 );
13794 assert_eq!(
13795 borrowed_cow.as_ref(),
13796 borrowed_string.as_str(),
13797 "From<&RestartPolicy> for Cow<'static, str> and \
13798 From<&RestartPolicy> for String must resolve \
13799 identically on RestartPolicy::{policy:?} — \
13800 divergence signals the borrowed-input Cow<'static, \
13801 str> and owned-`String` return-shape paths have \
13802 drifted onto different emit-sets"
13803 );
13804 let via_to_string: String = policy.to_string();
13805 assert_eq!(
13806 borrowed_cow.as_ref(),
13807 via_to_string.as_str(),
13808 "From<&RestartPolicy> for Cow<'static, str> must \
13809 byte-equal RestartPolicy::to_string on \
13810 RestartPolicy::{policy:?} — divergence signals \
13811 the trait-idiomatic borrowed-input Cow<'static, str> \
13812 forward-projection axis and the ToString-through-\
13813 Display axis have drifted onto different emit-sets"
13814 );
13815 }
13816 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13817 .iter()
13818 .map(std::borrow::Cow::from)
13819 .collect();
13820 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13821 .iter()
13822 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
13823 .collect();
13824 assert_eq!(
13825 via_iter, via_method,
13826 "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
13827 call site whose iteration axis holds `&RestartPolicy` \
13828 by construction — must byte-equal `.iter().map(|p| \
13829 Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
13830 input Cow<'static, str> `From<&RestartPolicy> for \
13831 Cow<'static, str>` axis is what makes the `Cow::from` \
13832 composition route through the substrate-primitive \
13833 `RestartPolicy::as_str` accessor with the zero-alloc \
13834 Cow::Borrowed arm by construction and without a spurious \
13835 `Copy` deref (which would only be reachable through the \
13836 owned-input `From<RestartPolicy> for Cow<'static, str>` \
13837 axis by first calling `.copied()` on the iterator)"
13838 );
13839 for cow in &via_iter {
13840 assert!(
13841 matches!(cow, std::borrow::Cow::Borrowed(_)),
13842 "every element of the .iter().map(Cow::from) pipe \
13843 over RestartPolicy::ALL must land on the zero-\
13844 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
13845 any arm signals the pipe's iteration axis has \
13846 silently allocated where the substrate-primitive \
13847 RestartPolicy::as_str `&'static str` return makes \
13848 the borrowed arm the type-correct projection"
13849 );
13850 }
13851 }
13852
13853 #[test]
13854 fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
13855 // Fail-before-pass-after byte-parity pin on the newly lifted
13856 // `impl From<RestartPolicy> for Box<str>` — asserts the
13857 // owned-input standard-library trait impl and the
13858 // substrate-primitive [`super::RestartPolicy::as_str`]
13859 // `pub const fn` accessor resolve to the same three-arm emit-
13860 // set across every arm the exhaustive
13861 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
13862 // substrate-wide `Box<str>` forward-projection campaign tier
13863 // opened one commit prior (69ef45c) on the paired sibling-
13864 // restart [`RestartStrategy`] onto the second (and third-and-
13865 // final) M2 OTP-shape closed-set fieldless typed enum peer on
13866 // the caixa surface (`:children :restart`), immediately after
13867 // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
13868 // closed the
13869 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
13870 // 2×3 corner on this enum. Rust's standard library carries
13871 // `impl From<&str> for Box<str>` and
13872 // `impl From<String> for Box<str>` but no blanket
13873 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
13874 // a distinct trait-idiomatic surface that a
13875 // `let key: Box<str> = policy.into();`-shaped call site
13876 // reaches through this impl and no other — a paired
13877 // `Box::from(policy.as_str())` open-code has no compile-time
13878 // link back to the substrate primitive. Peer of the sibling
13879 // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
13880 // (69ef45c) — extends the trait-idiomatic owned-input
13881 // [`Box<str>`] forward-projection axis onto the third and
13882 // final M2-OTP-shape closed-set typed enum on the caixa
13883 // surface.
13884 for &variant in RestartPolicy::ALL {
13885 let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13886 let via_method: &'static str = variant.as_str();
13887 assert_eq!(
13888 via_trait.as_ref(),
13889 via_method,
13890 "From<RestartPolicy> for Box<str> impl must round-\
13891 trip RestartPolicy::{variant:?} to the same lifted \
13892 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
13893 returns — divergence signals a silent detour off the \
13894 substrate-primitive accessor"
13895 );
13896 let via_into: Box<str> = variant.into();
13897 assert_eq!(
13898 via_into.as_ref(),
13899 via_method,
13900 "Into<Box<str>>::into on RestartPolicy::{variant:?} \
13901 must byte-equal RestartPolicy::as_str on the same \
13902 input — the blanket-derived Into shape must resolve \
13903 to the same as_str dispatch as the explicit From impl"
13904 );
13905 }
13906 }
13907
13908 #[test]
13909 fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
13910 // Fail-before-pass-after byte-parity pin on the newly lifted
13911 // `impl From<&RestartPolicy> for Box<str>` — asserts the
13912 // borrowed-input standard-library trait impl and the
13913 // substrate-primitive [`super::RestartPolicy::as_str`]
13914 // `pub const fn` accessor resolve to the same three-arm emit-
13915 // set across every arm the exhaustive
13916 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
13917 // standard library does not carry a blanket
13918 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
13919 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
13920 // so the borrowed-input `Box<str>` forward-projection axis
13921 // is a distinct trait-idiomatic surface that a
13922 // `let key: Box<str> = (&policy).into();`-shaped call site
13923 // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
13924 // shaped pipe reaches through this impl and no other — the
13925 // paired owned-input `From<RestartPolicy> for Box<str>`
13926 // impl (0a1b313) forces every borrowed-input call site
13927 // through an explicit `Copy` deref
13928 // (`Box::<str>::from((*policy).as_str())`) or a
13929 // `Box::<str>::from(policy.as_str())` open-code whose
13930 // type bounds have no compile-time link back to the
13931 // substrate primitive.
13932 //
13933 // Fourth (and closing) peer on the substrate-wide trait-
13934 // idiomatic [`Box<str>`] forward-projection family on the
13935 // M2 OTP-shape tier — closes the `{Self, &Self}` input-
13936 // shape corner of the [`Box<str>`] axis on the second (and
13937 // third-and-final) M2 OTP-shape closed-set fieldless typed
13938 // enum peer on the caixa surface (`:children :restart`),
13939 // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
13940 // axis one commit after its owning half (0612398) landed
13941 // on this enum. Every remaining closed-set fieldless typed
13942 // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
13943 // render-side / outside-caixa-core tiers is a future
13944 // target of the campaign.
13945 //
13946 // Also byte-parity witness against the paired owned-input
13947 // [`From<RestartPolicy> for Box<str>`] and the sibling
13948 // borrowed-input [`From<&RestartPolicy> for &'static str`],
13949 // [`From<&RestartPolicy> for String`], and
13950 // [`From<&RestartPolicy> for Cow<'static, str>`]
13951 // return-shape axes — locking the four
13952 // return-shape × input-shape paths together by construction
13953 // so any future detour trips at caixa-core test time. Then a
13954 // `.iter().map(Box::<str>::from)` pipe witness over
13955 // [`super::RestartPolicy::ALL`] — whose iterator yields
13956 // `&RestartPolicy` by construction, so the borrowed-input
13957 // [`Box<str>`] axis is what routes the pipe through the
13958 // substrate-primitive [`super::RestartPolicy::as_str`]
13959 // accessor without a spurious [`Copy`] deref (which would
13960 // only be reachable through the owned-input
13961 // [`From<RestartPolicy> for Box<str>`] axis by first
13962 // calling `.copied()` on the iterator).
13963 for &variant in RestartPolicy::ALL {
13964 let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
13965 let via_method: &'static str = variant.as_str();
13966 assert_eq!(
13967 via_trait.as_ref(),
13968 via_method,
13969 "From<&RestartPolicy> for Box<str> impl must round-\
13970 trip &RestartPolicy::{variant:?} to the same lifted \
13971 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
13972 returns — divergence signals a silent detour off the \
13973 substrate-primitive accessor"
13974 );
13975 let via_into: Box<str> = (&variant).into();
13976 assert_eq!(
13977 via_into.as_ref(),
13978 via_method,
13979 "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
13980 must byte-equal RestartPolicy::as_str on the same \
13981 input — the blanket-derived Into shape must resolve \
13982 to the same as_str dispatch as the explicit From impl"
13983 );
13984 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13985 assert_eq!(
13986 via_trait, owned_box,
13987 "From<&RestartPolicy> for Box<str> and \
13988 From<RestartPolicy> for Box<str> must resolve \
13989 identically on RestartPolicy::{variant:?} — \
13990 divergence signals the borrowed-input and owned-input \
13991 Box<str> forward-projection input-shape paths have \
13992 drifted onto different emit-sets"
13993 );
13994 let borrowed_static: &'static str =
13995 <&'static str as From<&RestartPolicy>>::from(&variant);
13996 assert_eq!(
13997 via_trait.as_ref(),
13998 borrowed_static,
13999 "From<&RestartPolicy> for Box<str> and \
14000 From<&RestartPolicy> for &'static str must resolve \
14001 identically on RestartPolicy::{variant:?} — \
14002 divergence signals the borrowed-input Box<str> and \
14003 &'static str return-shape paths have drifted onto \
14004 different emit-sets"
14005 );
14006 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
14007 assert_eq!(
14008 via_trait.as_ref(),
14009 borrowed_string.as_str(),
14010 "From<&RestartPolicy> for Box<str> and \
14011 From<&RestartPolicy> for String must resolve \
14012 identically on RestartPolicy::{variant:?} — \
14013 divergence signals the borrowed-input Box<str> and \
14014 owned-`String` return-shape paths have drifted onto \
14015 different emit-sets"
14016 );
14017 let borrowed_cow: std::borrow::Cow<'static, str> =
14018 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
14019 assert_eq!(
14020 via_trait.as_ref(),
14021 borrowed_cow.as_ref(),
14022 "From<&RestartPolicy> for Box<str> and \
14023 From<&RestartPolicy> for Cow<'static, str> must \
14024 resolve identically on RestartPolicy::{variant:?} — \
14025 divergence signals the borrowed-input Box<str> and \
14026 Cow<'static, str> return-shape paths have drifted \
14027 onto different emit-sets"
14028 );
14029 }
14030 let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
14031 let via_method: Vec<Box<str>> = RestartPolicy::ALL
14032 .iter()
14033 .map(|p| Box::<str>::from(p.as_str()))
14034 .collect();
14035 assert_eq!(
14036 via_iter, via_method,
14037 "`.iter().map(Box::<str>::from)` over \
14038 RestartPolicy::ALL — a call site whose iteration axis \
14039 holds `&RestartPolicy` by construction — must byte-\
14040 equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
14041 on every arm — the borrowed-input Box<str> \
14042 `From<&RestartPolicy> for Box<str>` axis is what \
14043 makes the `Box::<str>::from` composition route through \
14044 the substrate-primitive `RestartPolicy::as_str` \
14045 accessor without a spurious `Copy` deref (which would \
14046 only be reachable through the owned-input \
14047 `From<RestartPolicy> for Box<str>` axis by first \
14048 calling `.copied()` on the iterator)"
14049 );
14050 }
14051
14052 #[test]
14053 fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
14054 // Fail-before-pass-after byte-parity pin on the newly lifted
14055 // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
14056 // the owned-input standard-library trait impl and the
14057 // substrate-primitive [`super::RestartPolicy::as_str`]
14058 // `pub const fn` accessor resolve to the same three-arm emit-
14059 // set across every arm the exhaustive
14060 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
14061 // substrate-wide [`std::sync::Arc<str>`] forward-projection
14062 // campaign tier opened one projection tier prior (bca2ec8) on
14063 // the paired sibling-restart [`RestartStrategy`] owned-input
14064 // first-mover onto the second (and third-and-final) M2 OTP-
14065 // shape closed-set fieldless typed enum peer on the caixa
14066 // surface (`:children :restart`), immediately after the paired
14067 // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
14068 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
14069 // Box<str>}` 2×4 corner on this enum. Rust's standard library
14070 // carries `impl From<&str> for std::sync::Arc<str>` and
14071 // `impl From<String> for std::sync::Arc<str>` but no blanket
14072 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
14073 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
14074 // so this axis is a distinct trait-idiomatic surface that a
14075 // `let key: std::sync::Arc<str> = policy.into();`-shaped call
14076 // site reaches through this impl and no other — a paired
14077 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
14078 // has no compile-time link back to the substrate primitive,
14079 // and a two-step `std::sync::Arc::<str>::from(String::from(
14080 // policy))` composition through the owned-`String` axis
14081 // allocates twice (once into the intermediate `String`, once
14082 // into the [`Arc<str>`] on the `From<String>` conversion)
14083 // where the single-step trait impl allocates once.
14084 //
14085 // Cross-axis byte-parity witness against the sibling owned-
14086 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
14087 // return-shape axes — locking the five return-shape paths on
14088 // the owned-input surface together by construction so any
14089 // future detour off the substrate-primitive
14090 // [`super::RestartPolicy::as_str`] accessor trips at caixa-
14091 // core test time.
14092 for &variant in RestartPolicy::ALL {
14093 let via_trait: std::sync::Arc<str> =
14094 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
14095 let via_method: &'static str = variant.as_str();
14096 assert_eq!(
14097 via_trait.as_ref(),
14098 via_method,
14099 "From<RestartPolicy> for std::sync::Arc<str> impl \
14100 must round-trip RestartPolicy::{variant:?} to the \
14101 same lifted SUPERVISOR_CHILD_RESTART_* const \
14102 RestartPolicy::as_str returns — divergence signals \
14103 a silent detour off the substrate-primitive accessor"
14104 );
14105 let via_into: std::sync::Arc<str> = variant.into();
14106 assert_eq!(
14107 via_into.as_ref(),
14108 via_method,
14109 "Into<std::sync::Arc<str>>::into on \
14110 RestartPolicy::{variant:?} must byte-equal \
14111 RestartPolicy::as_str on the same input — the \
14112 blanket-derived Into shape must resolve to the same \
14113 as_str dispatch as the explicit From impl"
14114 );
14115 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
14116 assert_eq!(
14117 via_trait.as_ref(),
14118 owned_static,
14119 "From<RestartPolicy> for std::sync::Arc<str> and \
14120 From<RestartPolicy> for &'static str must resolve \
14121 identically on RestartPolicy::{variant:?} — \
14122 divergence signals the owned-input std::sync::Arc<str> \
14123 and &'static str return-shape paths have drifted onto \
14124 different emit-sets"
14125 );
14126 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
14127 assert_eq!(
14128 via_trait.as_ref(),
14129 owned_string.as_str(),
14130 "From<RestartPolicy> for std::sync::Arc<str> and \
14131 From<RestartPolicy> for String must resolve \
14132 identically on RestartPolicy::{variant:?} — \
14133 divergence signals the owned-input std::sync::Arc<str> \
14134 and owned-`String` return-shape paths have drifted \
14135 onto different emit-sets"
14136 );
14137 let owned_cow: std::borrow::Cow<'static, str> =
14138 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
14139 assert_eq!(
14140 via_trait.as_ref(),
14141 owned_cow.as_ref(),
14142 "From<RestartPolicy> for std::sync::Arc<str> and \
14143 From<RestartPolicy> for Cow<'static, str> must \
14144 resolve identically on RestartPolicy::{variant:?} — \
14145 divergence signals the owned-input std::sync::Arc<str> \
14146 and Cow<'static, str> return-shape paths have drifted \
14147 onto different emit-sets"
14148 );
14149 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
14150 assert_eq!(
14151 via_trait.as_ref(),
14152 owned_box.as_ref(),
14153 "From<RestartPolicy> for std::sync::Arc<str> and \
14154 From<RestartPolicy> for Box<str> must resolve \
14155 identically on RestartPolicy::{variant:?} — \
14156 divergence signals the owned-input std::sync::Arc<str> \
14157 and Box<str> return-shape paths have drifted onto \
14158 different emit-sets"
14159 );
14160 }
14161 }
14162
14163 #[test]
14164 fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
14165 // Fail-before-pass-after byte-parity pin on the newly lifted
14166 // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
14167 // asserts the borrowed-input standard-library trait impl and
14168 // the substrate-primitive [`super::RestartPolicy::as_str`]
14169 // `pub const fn` accessor resolve to the same three-arm
14170 // emit-set across every arm the exhaustive
14171 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
14172 // standard library carries `impl From<&str> for
14173 // std::sync::Arc<str>` and `impl From<String> for
14174 // std::sync::Arc<str>` but no blanket
14175 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
14176 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
14177 // so the borrowed-input [`std::sync::Arc<str>`] forward-
14178 // projection axis is a distinct trait-idiomatic surface that
14179 // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
14180 // call site or a
14181 // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
14182 // shaped pipe reaches through this impl and no other — the
14183 // paired owned-input [`From<RestartPolicy> for
14184 // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
14185 // input call site through an explicit [`Copy`] deref
14186 // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
14187 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
14188 // whose type bounds have no compile-time link back to the
14189 // substrate primitive.
14190 //
14191 // Closes the `{Self, &Self}` input-shape corner of the
14192 // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
14193 // forward-projection family on the second (and third-and-
14194 // final) M2 OTP-shape closed-set fieldless typed enum peer
14195 // on the caixa surface (`:children :restart`), one commit
14196 // after b05724e opened the owned-input half — exactly as
14197 // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
14198 // the sibling-restart [`RestartStrategy`] first-mover one
14199 // commit after its owning half (bca2ec8) landed, and as
14200 // cb1d068 closed the paired [`Box<str>`] corner on this
14201 // enum one commit after its owning half (0a1b313) landed.
14202 //
14203 // Also byte-parity witness against the paired owned-input
14204 // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
14205 // sibling borrowed-input [`From<&RestartPolicy> for
14206 // &'static str`], [`From<&RestartPolicy> for String`],
14207 // [`From<&RestartPolicy> for Cow<'static, str>`], and
14208 // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
14209 // locking the five return-shape × input-shape paths together
14210 // by construction so any future detour off the substrate-
14211 // primitive [`super::RestartPolicy::as_str`] accessor trips
14212 // at caixa-core test time. Then a
14213 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
14214 // over [`super::RestartPolicy::ALL`] — whose iterator yields
14215 // `&RestartPolicy` by construction, so the borrowed-input
14216 // [`std::sync::Arc<str>`] axis is what routes the pipe
14217 // through the substrate-primitive
14218 // [`super::RestartPolicy::as_str`] accessor without a
14219 // spurious [`Copy`] deref (which would only be reachable
14220 // through the owned-input
14221 // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
14222 // first calling `.copied()` on the iterator).
14223 for &variant in RestartPolicy::ALL {
14224 let via_trait: std::sync::Arc<str> =
14225 <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
14226 let via_method: &'static str = variant.as_str();
14227 assert_eq!(
14228 via_trait.as_ref(),
14229 via_method,
14230 "From<&RestartPolicy> for std::sync::Arc<str> impl \
14231 must round-trip &RestartPolicy::{variant:?} to the \
14232 same lifted SUPERVISOR_CHILD_RESTART_* const \
14233 RestartPolicy::as_str returns — divergence signals \
14234 a silent detour off the substrate-primitive accessor"
14235 );
14236 let via_into: std::sync::Arc<str> = (&variant).into();
14237 assert_eq!(
14238 via_into.as_ref(),
14239 via_method,
14240 "Into<std::sync::Arc<str>>::into on \
14241 &RestartPolicy::{variant:?} must byte-equal \
14242 RestartPolicy::as_str on the same input — the \
14243 blanket-derived Into shape must resolve to the same \
14244 as_str dispatch as the explicit From impl"
14245 );
14246 let owned_arc: std::sync::Arc<str> =
14247 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
14248 assert_eq!(
14249 via_trait, owned_arc,
14250 "From<&RestartPolicy> for std::sync::Arc<str> and \
14251 From<RestartPolicy> for std::sync::Arc<str> must \
14252 resolve identically on RestartPolicy::{variant:?} — \
14253 divergence signals the borrowed-input and owned-input \
14254 std::sync::Arc<str> forward-projection input-shape \
14255 paths have drifted onto different emit-sets"
14256 );
14257 let borrowed_static: &'static str =
14258 <&'static str as From<&RestartPolicy>>::from(&variant);
14259 assert_eq!(
14260 via_trait.as_ref(),
14261 borrowed_static,
14262 "From<&RestartPolicy> for std::sync::Arc<str> and \
14263 From<&RestartPolicy> for &'static str must resolve \
14264 identically on RestartPolicy::{variant:?} — \
14265 divergence signals the borrowed-input std::sync::Arc<str> \
14266 and &'static str return-shape paths have drifted onto \
14267 different emit-sets"
14268 );
14269 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
14270 assert_eq!(
14271 via_trait.as_ref(),
14272 borrowed_string.as_str(),
14273 "From<&RestartPolicy> for std::sync::Arc<str> and \
14274 From<&RestartPolicy> for String must resolve \
14275 identically on RestartPolicy::{variant:?} — \
14276 divergence signals the borrowed-input std::sync::Arc<str> \
14277 and owned-`String` return-shape paths have drifted \
14278 onto different emit-sets"
14279 );
14280 let borrowed_cow: std::borrow::Cow<'static, str> =
14281 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
14282 assert_eq!(
14283 via_trait.as_ref(),
14284 borrowed_cow.as_ref(),
14285 "From<&RestartPolicy> for std::sync::Arc<str> and \
14286 From<&RestartPolicy> for Cow<'static, str> must \
14287 resolve identically on RestartPolicy::{variant:?} — \
14288 divergence signals the borrowed-input std::sync::Arc<str> \
14289 and Cow<'static, str> return-shape paths have drifted \
14290 onto different emit-sets"
14291 );
14292 let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
14293 assert_eq!(
14294 via_trait.as_ref(),
14295 borrowed_box.as_ref(),
14296 "From<&RestartPolicy> for std::sync::Arc<str> and \
14297 From<&RestartPolicy> for Box<str> must resolve \
14298 identically on RestartPolicy::{variant:?} — \
14299 divergence signals the borrowed-input std::sync::Arc<str> \
14300 and Box<str> return-shape paths have drifted onto \
14301 different emit-sets"
14302 );
14303 }
14304 let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
14305 .iter()
14306 .map(std::sync::Arc::<str>::from)
14307 .collect();
14308 let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
14309 .iter()
14310 .map(|p| std::sync::Arc::<str>::from(p.as_str()))
14311 .collect();
14312 assert_eq!(
14313 via_iter, via_method,
14314 "`.iter().map(std::sync::Arc::<str>::from)` over \
14315 RestartPolicy::ALL — a call site whose iteration axis \
14316 holds `&RestartPolicy` by construction — must byte-\
14317 equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
14318 on every arm — the borrowed-input std::sync::Arc<str> \
14319 `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
14320 what makes the `std::sync::Arc::<str>::from` composition \
14321 route through the substrate-primitive \
14322 `RestartPolicy::as_str` accessor without a spurious \
14323 `Copy` deref (which would only be reachable through the \
14324 owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
14325 axis by first calling `.copied()` on the iterator)"
14326 );
14327 }
14328
14329 #[test]
14330 fn restart_policy_from_into_rc_str_routes_through_as_str_accessor() {
14331 // Fail-before-pass-after byte-parity pin on the newly lifted
14332 // `impl From<RestartPolicy> for std::rc::Rc<str>` — asserts
14333 // the owned-input standard-library trait impl and the
14334 // substrate-primitive [`super::RestartPolicy::as_str`]
14335 // `pub const fn` accessor resolve to the same three-arm emit-
14336 // set across every arm the exhaustive
14337 // [`super::RestartPolicy::ALL`] slice enumerates, and cross-
14338 // witnesses against every sibling owned-input `{&'static str,
14339 // String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
14340 // return-shape axis so the six return-shape paths on the
14341 // owned-input surface lock together by construction. Closes
14342 // the substrate-wide [`std::rc::Rc<str>`] forward-projection
14343 // campaign on the M2-OTP-shape `:supervisor :estrategia` +
14344 // `:children :restart` slot pair the sibling-restart
14345 // [`RestartStrategy`] first-mover (71ad8f4) opened one
14346 // projection tier prior on the paired sibling enum.
14347 for &variant in RestartPolicy::ALL {
14348 let via_trait: std::rc::Rc<str> =
14349 <std::rc::Rc<str> as From<RestartPolicy>>::from(variant);
14350 let via_method: &'static str = variant.as_str();
14351 assert_eq!(
14352 via_trait.as_ref(),
14353 via_method,
14354 "From<RestartPolicy> for std::rc::Rc<str> impl must \
14355 round-trip RestartPolicy::{variant:?} to the same \
14356 lifted SUPERVISOR_CHILD_RESTART_* const \
14357 RestartPolicy::as_str returns — divergence signals \
14358 a silent detour off the substrate-primitive accessor"
14359 );
14360 let via_into: std::rc::Rc<str> = variant.into();
14361 assert_eq!(
14362 via_into.as_ref(),
14363 via_method,
14364 "Into<std::rc::Rc<str>>::into on \
14365 RestartPolicy::{variant:?} must byte-equal \
14366 RestartPolicy::as_str on the same input — the \
14367 blanket-derived Into shape must resolve to the same \
14368 as_str dispatch as the explicit From impl"
14369 );
14370 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
14371 assert_eq!(
14372 via_trait.as_ref(),
14373 owned_static,
14374 "From<RestartPolicy> for std::rc::Rc<str> and \
14375 From<RestartPolicy> for &'static str must resolve \
14376 identically on RestartPolicy::{variant:?}"
14377 );
14378 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
14379 assert_eq!(
14380 via_trait.as_ref(),
14381 owned_string.as_str(),
14382 "From<RestartPolicy> for std::rc::Rc<str> and \
14383 From<RestartPolicy> for String must resolve \
14384 identically on RestartPolicy::{variant:?}"
14385 );
14386 let owned_cow: std::borrow::Cow<'static, str> =
14387 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
14388 assert_eq!(
14389 via_trait.as_ref(),
14390 owned_cow.as_ref(),
14391 "From<RestartPolicy> for std::rc::Rc<str> and \
14392 From<RestartPolicy> for Cow<'static, str> must \
14393 resolve identically on RestartPolicy::{variant:?}"
14394 );
14395 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
14396 assert_eq!(
14397 via_trait.as_ref(),
14398 owned_box.as_ref(),
14399 "From<RestartPolicy> for std::rc::Rc<str> and \
14400 From<RestartPolicy> for Box<str> must resolve \
14401 identically on RestartPolicy::{variant:?}"
14402 );
14403 let owned_arc: std::sync::Arc<str> =
14404 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
14405 assert_eq!(
14406 via_trait.as_ref(),
14407 owned_arc.as_ref(),
14408 "From<RestartPolicy> for std::rc::Rc<str> and \
14409 From<RestartPolicy> for std::sync::Arc<str> must \
14410 resolve identically on RestartPolicy::{variant:?}"
14411 );
14412 }
14413 }
14414
14415 #[test]
14416 fn restart_policy_from_borrowed_into_rc_str_routes_through_as_str_accessor() {
14417 // Fail-before-pass-after byte-parity pin on the newly lifted
14418 // `impl From<&RestartPolicy> for std::rc::Rc<str>` — asserts
14419 // the borrowed-input standard-library trait impl and the
14420 // substrate-primitive [`super::RestartPolicy::as_str`]
14421 // `pub const fn` accessor resolve to the same three-arm emit-
14422 // set across every arm the exhaustive
14423 // [`super::RestartPolicy::ALL`] slice enumerates. Closes the
14424 // `{Self, &Self}` input-shape corner of the
14425 // [`std::rc::Rc<str>`] axis on this enum, cross-witnesses
14426 // against the paired owned-input axis and every sibling
14427 // borrowed-input return-shape axis, and locks the
14428 // `.iter().map(std::rc::Rc::<str>::from)` pipe over
14429 // [`super::RestartPolicy::ALL`] to the substrate-primitive
14430 // accessor without a spurious [`Copy`] deref (which would only
14431 // be reachable through the owned-input axis by first calling
14432 // `.copied()` on the iterator).
14433 for &variant in RestartPolicy::ALL {
14434 let via_trait: std::rc::Rc<str> =
14435 <std::rc::Rc<str> as From<&RestartPolicy>>::from(&variant);
14436 let via_method: &'static str = variant.as_str();
14437 assert_eq!(
14438 via_trait.as_ref(),
14439 via_method,
14440 "From<&RestartPolicy> for std::rc::Rc<str> impl must \
14441 round-trip &RestartPolicy::{variant:?} to the same \
14442 lifted SUPERVISOR_CHILD_RESTART_* const \
14443 RestartPolicy::as_str returns"
14444 );
14445 let via_into: std::rc::Rc<str> = (&variant).into();
14446 assert_eq!(
14447 via_into.as_ref(),
14448 via_method,
14449 "Into<std::rc::Rc<str>>::into on \
14450 &RestartPolicy::{variant:?} must byte-equal \
14451 RestartPolicy::as_str on the same input"
14452 );
14453 let owned_rc: std::rc::Rc<str> =
14454 <std::rc::Rc<str> as From<RestartPolicy>>::from(variant);
14455 assert_eq!(
14456 via_trait, owned_rc,
14457 "From<&RestartPolicy> for std::rc::Rc<str> and \
14458 From<RestartPolicy> for std::rc::Rc<str> must \
14459 resolve identically on RestartPolicy::{variant:?}"
14460 );
14461 let borrowed_static: &'static str =
14462 <&'static str as From<&RestartPolicy>>::from(&variant);
14463 assert_eq!(
14464 via_trait.as_ref(),
14465 borrowed_static,
14466 "From<&RestartPolicy> for std::rc::Rc<str> and \
14467 From<&RestartPolicy> for &'static str must resolve \
14468 identically on RestartPolicy::{variant:?}"
14469 );
14470 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
14471 assert_eq!(
14472 via_trait.as_ref(),
14473 borrowed_string.as_str(),
14474 "From<&RestartPolicy> for std::rc::Rc<str> and \
14475 From<&RestartPolicy> for String must resolve \
14476 identically on RestartPolicy::{variant:?}"
14477 );
14478 let borrowed_cow: std::borrow::Cow<'static, str> =
14479 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
14480 assert_eq!(
14481 via_trait.as_ref(),
14482 borrowed_cow.as_ref(),
14483 "From<&RestartPolicy> for std::rc::Rc<str> and \
14484 From<&RestartPolicy> for Cow<'static, str> must \
14485 resolve identically on RestartPolicy::{variant:?}"
14486 );
14487 let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
14488 assert_eq!(
14489 via_trait.as_ref(),
14490 borrowed_box.as_ref(),
14491 "From<&RestartPolicy> for std::rc::Rc<str> and \
14492 From<&RestartPolicy> for Box<str> must resolve \
14493 identically on RestartPolicy::{variant:?}"
14494 );
14495 let borrowed_arc: std::sync::Arc<str> =
14496 <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
14497 assert_eq!(
14498 via_trait.as_ref(),
14499 borrowed_arc.as_ref(),
14500 "From<&RestartPolicy> for std::rc::Rc<str> and \
14501 From<&RestartPolicy> for std::sync::Arc<str> must \
14502 resolve identically on RestartPolicy::{variant:?}"
14503 );
14504 }
14505 let via_iter: Vec<std::rc::Rc<str>> = RestartPolicy::ALL
14506 .iter()
14507 .map(std::rc::Rc::<str>::from)
14508 .collect();
14509 let via_method: Vec<std::rc::Rc<str>> = RestartPolicy::ALL
14510 .iter()
14511 .map(|p| std::rc::Rc::<str>::from(p.as_str()))
14512 .collect();
14513 assert_eq!(
14514 via_iter, via_method,
14515 "`.iter().map(std::rc::Rc::<str>::from)` over \
14516 RestartPolicy::ALL — a call site whose iteration axis \
14517 holds `&RestartPolicy` by construction — must byte-\
14518 equal `.iter().map(|p| std::rc::Rc::<str>::from(p.as_str()))` \
14519 on every arm — the borrowed-input std::rc::Rc<str> \
14520 `From<&RestartPolicy> for std::rc::Rc<str>` axis is \
14521 what makes the `std::rc::Rc::<str>::from` composition \
14522 route through the substrate-primitive \
14523 `RestartPolicy::as_str` accessor without a spurious \
14524 `Copy` deref (which would only be reachable through the \
14525 owned-input `From<RestartPolicy> for std::rc::Rc<str>` \
14526 axis by first calling `.copied()` on the iterator)"
14527 );
14528 }
14529
14530 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
14531
14532 #[test]
14533 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
14534 // The fail-before-pass-after pin: pre-lift there was no
14535 // single-source binding between the [`RestartPolicy`] variant
14536 // name the un-`rename`d `Serialize` derive emits under
14537 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
14538 // byte-string every downstream cluster-side dispatcher (the
14539 // future wasm-operator's per-child post-exit restart-decision
14540 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
14541 // materializer's admission-time enum-arm bind, the
14542 // `caixa-operator`'s hierarchical reconciliation scheduler's
14543 // per-child-policy fan-out) probes verbatim. A future
14544 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
14545 // or a per-variant `#[serde(rename = "…")]` override, or a
14546 // variant rename in the source — would silently rebrand the
14547 // emitted scalar under one spelling while every downstream
14548 // dispatcher still probed the other, with the failure surfacing
14549 // at the operator's reconcile posture (children coming up under
14550 // the `default()` `Permanent` arm rather than the typed slot's
14551 // declared policy — a `:temporary` `oneShot` child would be
14552 // restarted on clean exit, treating the successful-completion
14553 // signal as failure and re-running the completion-terminal
14554 // one-shot indefinitely; a `:transient` child that clean-exited
14555 // would be restarted, masking the clean-completion contract)
14556 // far from the source rebrand commit and with no field naming
14557 // the drift. Pinning the two paths (the `Serialize` derive's
14558 // serialized string AND the [`RestartPolicy::as_str`] helper)
14559 // to the same three lifted
14560 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
14561 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
14562 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
14563 // byte-strings makes any future drift on either endpoint fail
14564 // here at caixa-core build time. Peer of the sibling
14565 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
14566 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
14567 // and the M3
14568 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
14569 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
14570 // same three-path-convergence discipline, extended to close the
14571 // third OTP-shaped closed-enum discriminator axis on the caixa
14572 // typed surface (per-child restart-decision policy).
14573 for (variant, expected) in [
14574 (
14575 RestartPolicy::Permanent,
14576 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
14577 ),
14578 (
14579 RestartPolicy::Temporary,
14580 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
14581 ),
14582 (
14583 RestartPolicy::Transient,
14584 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
14585 ),
14586 ] {
14587 let json = serde_json::to_string(&variant).unwrap();
14588 assert_eq!(
14589 json,
14590 format!("\"{expected}\""),
14591 "RestartPolicy::{variant:?} must serialize to {expected:?}"
14592 );
14593 assert_eq!(
14594 variant.as_str(),
14595 expected,
14596 "RestartPolicy::{variant:?}.as_str() must return the lifted \
14597 SUPERVISOR_CHILD_RESTART_* constant"
14598 );
14599 }
14600 }
14601
14602 #[test]
14603 fn supervisor_child_restart_consts_are_pairwise_distinct() {
14604 // Cross-arm drift-detection pin: a future collapse of two
14605 // canonical variant byte-strings onto the same value (e.g. an
14606 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
14607 // to also read `"Permanent"`) would silently reroute every
14608 // downstream operator's per-child-policy dispatch onto the
14609 // sibling arm's reconcile branch and pass every propagation-probe
14610 // test that expected only the stale arm's value — a `:transient`
14611 // child would come up under the `:permanent` restart-decision
14612 // posture on every subsequent clean exit, so a completion-terminal
14613 // child would be restarted indefinitely against its declared
14614 // policy. Peer of the sibling
14615 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
14616 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
14617 // and the four-way distinct pin
14618 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
14619 // top-level `SUPERVISOR_KEY_*` axis.
14620 let all = [
14621 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
14622 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
14623 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
14624 ];
14625 for (i, a) in all.iter().enumerate() {
14626 for (j, b) in all.iter().enumerate() {
14627 if i != j {
14628 assert_ne!(
14629 a, b,
14630 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
14631 — got duplicate {a:?} at indices {i} and {j}",
14632 );
14633 }
14634 }
14635 }
14636 }
14637
14638 #[test]
14639 fn restart_policy_display_routes_through_as_str_helper() {
14640 // The fail-before-pass-after pin on the first half of the
14641 // three-path convergence: pre-convergence [`RestartPolicy`]
14642 // carried a [`std::fmt::Display`] surface via its
14643 // `#[discriminant(also_display)]` gen-platform derive route,
14644 // which arrived kebab-case as `"permanent"` / `"temporary"`
14645 // / `"transient"` on this three-arm enum (whose variant
14646 // names each collapse to their own lowercase form under the
14647 // kebab-case transform) while the wire format ran as
14648 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
14649 // through the un-`rename`d serde derive. Every consumer
14650 // reaching for a policy byte-string past the wire format had
14651 // to pick between three paths ([`RestartPolicy::as_str`],
14652 // the `Serialize` derive's serialized string, or
14653 // `format!("{v}")` on the discriminant-Display route), any
14654 // two of which a future variant rename or
14655 // `#[serde(rename_all = "kebab-case")]` attribute would
14656 // silently desynchronize. Wiring [`std::fmt::Display`]
14657 // through [`RestartPolicy::as_str`] closes the third path:
14658 // every `format!("{v}")` call reaches the same lifted
14659 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
14660 // wire format and the [`RestartPolicy::as_str`] helper
14661 // already route through, so a future variant rename lands at
14662 // exactly one place. Pin the routing here so a future
14663 // `impl std::fmt::Display for RestartPolicy`
14664 // reimplementation that hand-rolls the arms instead of
14665 // delegating to [`RestartPolicy::as_str`] fails at
14666 // caixa-core build time. Peer of the sibling
14667 // [`restart_strategy_display_routes_through_as_str_helper`]
14668 // on the per-supervisor sibling-restart-strategy axis and
14669 // the M3
14670 // `placement_strategy_display_routes_through_as_str_helper`
14671 // (cc8f749) — the third of three OTP-shape closed-enum
14672 // discriminator axes on the caixa typed surface now
14673 // converged onto the same three-path
14674 // (Display → as_str → lifted const) discipline.
14675 for variant in [
14676 RestartPolicy::Permanent,
14677 RestartPolicy::Temporary,
14678 RestartPolicy::Transient,
14679 ] {
14680 assert_eq!(
14681 variant.to_string(),
14682 variant.as_str(),
14683 "RestartPolicy::{variant:?} Display must route through \
14684 RestartPolicy::as_str (single source of truth: the lifted \
14685 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
14686 );
14687 }
14688 }
14689
14690 #[test]
14691 fn restart_policy_display_matches_serialized_wire_byte_string() {
14692 // The fail-before-pass-after pin on the second half of the
14693 // three-path convergence: `Display` (user-facing text) agrees
14694 // byte-for-byte with the `Serialize` derive's wire format
14695 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
14696 // scalar) on every variant. Pre-convergence the two paths
14697 // were structurally independent — a future
14698 // `#[serde(rename_all = "kebab-case")]` attribute on the
14699 // enum would silently rebrand the emitted wire scalar
14700 // (`permanent`, `temporary`, `transient`) while every
14701 // consumer that pretty-prints the policy (the future
14702 // wasm-operator's per-child post-exit restart-decision
14703 // diagnostic line, the future `feira app graph` per-child
14704 // restart column, the future M4
14705 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
14706 // per-child admission-webhook rejection body) would still
14707 // emit the PascalCase form the `as_str` / `Display` route
14708 // returns, with the mismatch surfacing at consumer parse
14709 // time / operator dispatch time far from the source rebrand
14710 // commit. Pin the two paths byte-for-byte here so any future
14711 // serde-attribute or variant-rename drift is a
14712 // caixa-core-build-time test failure at this call, not a
14713 // silent per-consumer dispatch miss. Peer of the sibling
14714 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
14715 // on the per-supervisor sibling-restart-strategy axis and
14716 // the M3
14717 // `placement_strategy_display_matches_serialized_wire_byte_string`
14718 // (cc8f749).
14719 for variant in [
14720 RestartPolicy::Permanent,
14721 RestartPolicy::Temporary,
14722 RestartPolicy::Transient,
14723 ] {
14724 let wire = serde_json::to_string(&variant).unwrap();
14725 let unquoted = wire
14726 .strip_prefix('"')
14727 .and_then(|s| s.strip_suffix('"'))
14728 .expect("serialized RestartPolicy is a JSON string");
14729 assert_eq!(
14730 variant.to_string(),
14731 unquoted,
14732 "RestartPolicy::{variant:?} Display byte-string must match the \
14733 Serialize derive's wire byte-string (three-path convergence: \
14734 Display + as_str + Serialize all resolve to the same \
14735 SUPERVISOR_CHILD_RESTART_* const)"
14736 );
14737 }
14738 }
14739
14740 #[test]
14741 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
14742 // Fail-before-pass-after byte-parity pin on the lifted
14743 // `impl AsRef<str> for RestartPolicy` — asserts the
14744 // standard-library trait impl and the substrate-primitive
14745 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
14746 // to the same `&str` per instance across the three-arm
14747 // closed set, so any future silent detour that routes the
14748 // impl through a divergent projection (a per-arm inline
14749 // `match self { RestartPolicy::Permanent => "Permanent", … }`
14750 // re-inlining that opens a compile-time link to the un-lifted
14751 // arm-literal, a swap onto the kebab-case
14752 // [`gen_platform::Discriminant`] catalog identity that would
14753 // collide the wire axis with the dispatcher-catalog axis) trips
14754 // at caixa-core test time under `PartialEq` rather than at a
14755 // downstream `impl AsRef<str>`-bound consumer's silent split.
14756 // Sweeps every one of the three arms
14757 // [`RestartPolicy::ALL`] carries so no arm's projection is
14758 // covered only by the sibling wire-format `Serialize` derive
14759 // path. Peer of the sibling
14760 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
14761 // (63eb1a4) on the paired per-supervisor sibling-restart-
14762 // strategy axis and the [`crate::CaixaVersion`]
14763 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
14764 // top-level `:versao` typed newtype — the three pins together
14765 // cover the substrate primitive's `AsRef<str>` projection axis
14766 // on the paired newtype + M2 closed-set-typed-enum surface.
14767 for &variant in RestartPolicy::ALL {
14768 assert_eq!(
14769 <RestartPolicy as AsRef<str>>::as_ref(&variant),
14770 variant.as_str(),
14771 "AsRef<str> impl on RestartPolicy::{variant:?} must \
14772 byte-equal RestartPolicy::as_str on the same instance \
14773 — divergence signals a silent detour off the substrate-\
14774 primitive accessor"
14775 );
14776 }
14777 }
14778
14779 #[test]
14780 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
14781 // Fail-before-pass-after byte-parity pin on the three-path
14782 // convergence discipline the M2 per-child-restart-policy
14783 // primitive now carries on the `&str`-projection axis:
14784 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
14785 // lifted impl), `format!("{v}")` (the pre-existing
14786 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
14787 // primitive `pub const fn` accessor both trait impls delegate
14788 // through) must resolve to the same byte-string on every
14789 // instance across the three-arm closed set. Refuses any future
14790 // divergence between the two trait impls (a stray
14791 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
14792 // rather than delegating through the shared accessor; a
14793 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
14794 // literal cascade) that would silently split the two
14795 // projection paths of the same closed-set typed enum. Mirrors
14796 // the sibling three-path-convergence discipline the peer
14797 // [`RestartStrategy`] typed enum carries on its
14798 // `AsRef<str>` / `Display` / `as_str` triple
14799 // (supervisor.rs pin
14800 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
14801 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
14802 // carries on the same triple (version.rs pin
14803 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
14804 // 16d5c7e).
14805 for &variant in RestartPolicy::ALL {
14806 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
14807 let via_display: String = format!("{variant}");
14808 let via_accessor: &str = variant.as_str();
14809 assert_eq!(via_as_ref, via_accessor);
14810 assert_eq!(via_display, via_accessor);
14811 assert_eq!(via_as_ref, via_display.as_str());
14812 }
14813 }
14814
14815 // The `generic_bytes_sink(&variant)` and `borrowed_hasher.update(&variant)`
14816 // shapes below are the borrowed-input witness half of the by-value +
14817 // by-reference partition the paired witness pair carries: the pair proves
14818 // the trait bound accepts both owned (`variant`) and borrowed (`&variant`)
14819 // shapes through the same substrate-primitive `as_str` accessor, which is
14820 // the shape the caixa-lacre BLAKE3 content-address closure composes.
14821 // `clippy::needless_borrows_for_generic_args` would fold the borrowed half
14822 // into the owned half and collapse the by-value/by-reference partition
14823 // this test load-bears; the `#[allow]` documents that the partition is
14824 // deliberate, not an oversight.
14825 #[allow(clippy::needless_borrows_for_generic_args)]
14826 #[test]
14827 fn restart_policy_as_ref_bytes_routes_through_as_str_accessor() {
14828 // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
14829 // function that binds its argument through the standard-library
14830 // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartPolicy`]
14831 // directly, without the caller open-coding the two-hop
14832 // `restart.as_str().as_bytes()` composition. Lifted to the top
14833 // of the function per `clippy::items_after_statements`.
14834 fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
14835 t.as_ref().to_vec()
14836 }
14837 // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
14838 // `blake3::Hasher::update` / `ring::digest::Context::update` /
14839 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
14840 // signature so a per-child BLAKE3 content-address closure that
14841 // composes `hasher.update(restart)` on the [`crate::Lacre`]
14842 // closure builder reaches the substrate-primitive `as_str`
14843 // accessor through the [`super::RestartPolicy`] `AsRef<[u8]>`
14844 // axis and no other. Lifted to the top of the function per
14845 // `clippy::items_after_statements`.
14846 struct MockHasher(Vec<u8>);
14847 impl MockHasher {
14848 fn new() -> Self {
14849 Self(Vec::new())
14850 }
14851 fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
14852 self.0.extend_from_slice(bytes.as_ref());
14853 self
14854 }
14855 fn finalize(self) -> Vec<u8> {
14856 self.0
14857 }
14858 }
14859
14860 // Fail-before-pass-after byte-parity pin on the newly lifted
14861 // `impl AsRef<[u8]> for RestartPolicy` — asserts the trait-
14862 // idiomatic byte-view standard-library impl and the substrate-
14863 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
14864 // accessor's `.as_bytes()` byte-tail resolve to the same three-
14865 // arm `PascalCase` wire byte-string emit-set across every arm
14866 // the exhaustive [`super::RestartPolicy::ALL`] slice enumerates.
14867 // Extends the trait-idiomatic byte-view axis onto the second
14868 // (and final) M2 OTP-shape closed-set fieldless typed enum peer
14869 // on the caixa surface (the paired per-child restart-decision
14870 // policy sibling on the same M2 `:supervisor` slot), closing
14871 // the byte-view axis across the `:supervisor :estrategia` +
14872 // `:children :restart` M2 slot pair the sibling
14873 // [`super::RestartStrategy`] first-mover (cd4c4e0) opened.
14874 //
14875 // Rust's standard library carries `impl AsRef<[u8]> for str` and
14876 // `impl AsRef<[u8]> for String`, so a two-hop composition
14877 // `restart.as_str().as_bytes()` (or the equally two-hop
14878 // `AsRef::<str>::as_ref(&restart).as_bytes()`) is reachable
14879 // through the pre-existing str-view axis alone. But that two-hop
14880 // shape has no compile-time link back to the byte-projection
14881 // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
14882 // consumer to open-code the two-hop composition at every call
14883 // site, and admits a silent split whenever a future call site
14884 // takes a sibling reverse-projection axis whose `.as_bytes()`
14885 // byte-tail carries no compile-time byte-view surface. This
14886 // impl closes the byte-view axis at the substrate-primitive
14887 // [`super::RestartPolicy::as_str`] accessor so every future
14888 // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
14889 // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
14890 // roster the paired str-view axes already return through —
14891 // through one trait dispatch.
14892 for &variant in RestartPolicy::ALL {
14893 let via_trait: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
14894 let via_method_bytes: &[u8] = variant.as_str().as_bytes();
14895 assert_eq!(
14896 via_trait, via_method_bytes,
14897 "AsRef<[u8]> for RestartPolicy impl must byte-equal \
14898 RestartPolicy::as_str().as_bytes() on \
14899 RestartPolicy::{variant:?} — divergence signals a \
14900 silent detour off the substrate-primitive accessor"
14901 );
14902 // Cross-axis witness against the paired str-view axes'
14903 // `.as_bytes()` byte-tails: [`AsRef<str>`] /
14904 // [`std::fmt::Display`] / [`super::RestartPolicy::as_str`]
14905 // all resolve to the same lifted
14906 // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
14907 // roster, and the byte-view axis must byte-equal each of
14908 // their `.as_bytes()` byte-tails by construction — locking
14909 // the str-view and byte-view axes together at the
14910 // substrate-primitive accessor.
14911 let str_view_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
14912 assert_eq!(
14913 via_trait,
14914 str_view_ref.as_bytes(),
14915 "AsRef<[u8]> for RestartPolicy and AsRef<str> for \
14916 RestartPolicy must resolve to byte-equal byte-tails \
14917 on RestartPolicy::{variant:?} — divergence signals \
14918 the byte-view and str-view axes have drifted off the \
14919 same substrate-primitive as_str accessor"
14920 );
14921 let display_bytes = variant.to_string();
14922 assert_eq!(
14923 via_trait,
14924 display_bytes.as_bytes(),
14925 "AsRef<[u8]> for RestartPolicy and \
14926 <RestartPolicy as std::fmt::Display>::to_string must \
14927 resolve to byte-equal byte-tails on \
14928 RestartPolicy::{variant:?} — divergence signals the \
14929 byte-view axis and the Display formatter axis have \
14930 drifted off the same substrate-primitive as_str \
14931 accessor"
14932 );
14933 // Cross-axis witness against the paired reverse-projection
14934 // axes' `.as_bytes()` byte-tails: every one of `{&'static
14935 // str, String, Cow<'static, str>, Box<str>,
14936 // std::sync::Arc<str>}` allocates (or borrows) the same
14937 // `PascalCase` wire byte-string the substrate-primitive
14938 // accessor emits, so the byte-view axis must byte-equal
14939 // each of their `.as_bytes()` byte-tails by construction.
14940 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
14941 assert_eq!(
14942 via_trait,
14943 owned_static.as_bytes(),
14944 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14945 for &'static str must resolve to byte-equal byte-tails \
14946 on RestartPolicy::{variant:?}"
14947 );
14948 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
14949 assert_eq!(
14950 via_trait,
14951 owned_string.as_bytes(),
14952 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14953 for String must resolve to byte-equal byte-tails on \
14954 RestartPolicy::{variant:?}"
14955 );
14956 let owned_cow: std::borrow::Cow<'static, str> =
14957 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
14958 assert_eq!(
14959 via_trait,
14960 owned_cow.as_bytes(),
14961 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14962 for Cow<'static, str> must resolve to byte-equal byte-\
14963 tails on RestartPolicy::{variant:?}"
14964 );
14965 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
14966 assert_eq!(
14967 via_trait,
14968 owned_box.as_bytes(),
14969 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14970 for Box<str> must resolve to byte-equal byte-tails on \
14971 RestartPolicy::{variant:?}"
14972 );
14973 let owned_arc: std::sync::Arc<str> =
14974 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
14975 assert_eq!(
14976 via_trait,
14977 owned_arc.as_bytes(),
14978 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14979 for std::sync::Arc<str> must resolve to byte-equal \
14980 byte-tails on RestartPolicy::{variant:?}"
14981 );
14982 }
14983 // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
14984 // input function `generic_bytes_sink` (lifted above per
14985 // `clippy::items_after_statements`) accepts a
14986 // [`super::RestartPolicy`] directly through the trait bound,
14987 // without the caller open-coding the two-hop
14988 // `restart.as_str().as_bytes()` composition. This is the shape
14989 // that reaches the caixa-lacre BLAKE3 content-address closure's
14990 // `blake3::Hasher::update(impl AsRef<[u8]>)` byte-input surface
14991 // through this impl and no other.
14992 for &variant in RestartPolicy::ALL {
14993 let via_generic = generic_bytes_sink(variant);
14994 let via_borrowed_generic = generic_bytes_sink(&variant);
14995 let via_method_bytes = variant.as_str().as_bytes().to_vec();
14996 assert_eq!(
14997 via_generic, via_method_bytes,
14998 "generic `<T: AsRef<[u8]>>`-bound consumer on \
14999 RestartPolicy::{variant:?} must yield the same byte-\
15000 tail RestartPolicy::as_str().as_bytes() returns — \
15001 divergence signals the byte-view axis fails to bridge \
15002 a generic byte-input trait bound to the substrate-\
15003 primitive accessor"
15004 );
15005 assert_eq!(
15006 via_borrowed_generic, via_method_bytes,
15007 "generic `<T: AsRef<[u8]>>`-bound consumer on \
15008 &RestartPolicy::{variant:?} must yield the same byte-\
15009 tail RestartPolicy::as_str().as_bytes() returns — the \
15010 borrowed-input surface must resolve to the same as_str \
15011 dispatch"
15012 );
15013 }
15014 // `blake3::Hasher::update`-shape byte-input surface witness on
15015 // the caixa-lacre compounding target: the `MockHasher` (lifted
15016 // above per `clippy::items_after_statements`) mirrors
15017 // `blake3::Hasher::update` / `ring::digest::Context::update` /
15018 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
15019 // signature and accepts a [`super::RestartPolicy`] directly,
15020 // routing its byte-tail through the substrate-primitive
15021 // `as_str` accessor — the shape a future per-child BLAKE3
15022 // content-address closure composes to fold a `:restart`
15023 // discriminator byte-tag into the [`crate::Lacre`] closure
15024 // body.
15025 for &variant in RestartPolicy::ALL {
15026 let mut owned_hasher = MockHasher::new();
15027 owned_hasher.update(variant);
15028 let owned_folded = owned_hasher.finalize();
15029 assert_eq!(
15030 owned_folded,
15031 variant.as_str().as_bytes(),
15032 "`hasher.update(restart)`-shape composition on \
15033 RestartPolicy::{variant:?} must fold the same byte-\
15034 tail RestartPolicy::as_str().as_bytes() returns — the \
15035 shape a future per-child BLAKE3 content-address \
15036 closure composes to fold a `:restart` discriminator \
15037 byte-tag into the Lacre closure body"
15038 );
15039 let mut borrowed_hasher = MockHasher::new();
15040 borrowed_hasher.update(&variant);
15041 let borrowed_folded = borrowed_hasher.finalize();
15042 assert_eq!(
15043 borrowed_folded,
15044 variant.as_str().as_bytes(),
15045 "`hasher.update(&restart)`-shape composition on \
15046 &RestartPolicy::{variant:?} must fold the same byte-\
15047 tail RestartPolicy::as_str().as_bytes() returns — the \
15048 borrowed-input surface must resolve to the same as_str \
15049 dispatch"
15050 );
15051 }
15052 }
15053
15054 #[test]
15055 #[expect(
15056 clippy::too_many_lines,
15057 reason = "the byte-owned reverse-projection axis is closed \
15058 here across the M2-OTP-shape :supervisor slot pair by \
15059 extending onto the second and final M2-OTP-shape \
15060 closed-set fieldless typed-enum peer, so the pin \
15061 binds the new impl against every paired byte-view \
15062 and str-owned axis on the same enum plus a generic \
15063 <T: Into<Vec<u8>>>-bound consumer witness and a \
15064 std::io::Write::write_all-shape owned-byte-sink \
15065 surface witness on both owned and borrowed input \
15066 shapes to lock the whole family against a future \
15067 silent regression"
15068 )]
15069 fn restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
15070 // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
15071 // owned-byte-input function accepts a [`super::RestartPolicy`]
15072 // directly through the trait bound, without the caller open-
15073 // coding the three-hop `restart.as_str().as_bytes().to_vec()`
15074 // composition. Lifted to the top of the function per
15075 // `clippy::items_after_statements`.
15076 fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
15077 t.into()
15078 }
15079 // `std::io::Write::write_all`-shape owned-byte-sink surface
15080 // mock: mirrors `std::io::Write::write_all` /
15081 // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
15082 // byte-sink that consumes a `Vec<u8>` payload via
15083 // `Into<Vec<u8>>`, so a future per-child per-`:restart` audit-
15084 // log emit reaches the substrate-primitive `as_str` accessor
15085 // through the byte-owned reverse-projection axis and no
15086 // other. Lifted to the top of the function per
15087 // `clippy::items_after_statements`.
15088 struct MockOwnedByteSink(Vec<u8>);
15089 impl MockOwnedByteSink {
15090 fn new() -> Self {
15091 Self(Vec::new())
15092 }
15093 fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
15094 self.0.extend(bytes.into());
15095 self
15096 }
15097 fn finalize(self) -> Vec<u8> {
15098 self.0
15099 }
15100 }
15101
15102 // Fail-before-pass-after byte-parity pin on the newly lifted
15103 // `impl From<RestartPolicy> for Vec<u8>` and
15104 // `impl From<&RestartPolicy> for Vec<u8>` — asserts the trait-
15105 // idiomatic byte-owned reverse-projection standard-library
15106 // impls and the substrate-primitive
15107 // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
15108 // `.as_bytes().to_vec()` byte-tail resolve to the same three-
15109 // arm PascalCase wire byte-string emit-set across every arm
15110 // the exhaustive [`super::RestartPolicy::ALL`] slice
15111 // enumerates. Closes the substrate-wide trait-idiomatic byte-
15112 // owned reverse-projection axis on the M2-OTP-shape closed-
15113 // set typed-enum pair the sibling first-mover
15114 // [`super::RestartStrategy`] `From<{Self, &Self}> for Vec<u8>`
15115 // lift (63e5dd0) opened one commit prior, matching the
15116 // trajectory the paired [`AsRef<[u8]>`] borrowed byte-view
15117 // axis campaign already tracked across the same slot pair
15118 // (cd4c4e0 → 98b08fa).
15119 for &variant in RestartPolicy::ALL {
15120 let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
15121 let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
15122 let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
15123 assert_eq!(
15124 via_owned_from, via_method_bytes,
15125 "From<RestartPolicy> for Vec<u8> impl must byte-equal \
15126 RestartPolicy::as_str().as_bytes().to_vec() on \
15127 RestartPolicy::{variant:?} — divergence signals a \
15128 silent detour off the substrate-primitive accessor"
15129 );
15130 assert_eq!(
15131 via_borrowed_from, via_method_bytes,
15132 "From<&RestartPolicy> for Vec<u8> impl must byte-\
15133 equal RestartPolicy::as_str().as_bytes().to_vec() \
15134 on RestartPolicy::{variant:?} — divergence signals \
15135 a silent detour off the substrate-primitive accessor"
15136 );
15137 assert_eq!(
15138 via_owned_from, via_borrowed_from,
15139 "From<RestartPolicy> for Vec<u8> and \
15140 From<&RestartPolicy> for Vec<u8> must byte-equal \
15141 each other on RestartPolicy::{variant:?} — \
15142 divergence signals the owned-input and borrowed-input \
15143 paths have drifted off the same substrate-primitive \
15144 as_str accessor"
15145 );
15146 // Cross-axis witness against the paired [`AsRef<[u8]>`]
15147 // borrowed byte-view axis (98b08fa): the byte-owned
15148 // reverse-projection axis must byte-equal the paired
15149 // borrowed byte-view axis by construction — locking the
15150 // byte-view and byte-owned axes together at the substrate-
15151 // primitive accessor.
15152 let borrowed_bytes: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
15153 assert_eq!(
15154 via_owned_from,
15155 borrowed_bytes.to_vec(),
15156 "From<RestartPolicy> for Vec<u8> and AsRef<[u8]> for \
15157 RestartPolicy must resolve to byte-equal byte-tails \
15158 on RestartPolicy::{variant:?} — divergence signals \
15159 the byte-owned and byte-view axes have drifted off \
15160 the same substrate-primitive as_str accessor"
15161 );
15162 // Cross-axis witness against the str-owned reverse-
15163 // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
15164 // byte-tails: every one of `{String, Cow<'static, str>,
15165 // Box<str>, std::sync::Arc<str>}` allocates (or borrows)
15166 // the same PascalCase wire byte-string the substrate-
15167 // primitive accessor emits, so the byte-owned axis must
15168 // byte-equal each of their owned byte-tails by
15169 // construction.
15170 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
15171 assert_eq!(
15172 via_owned_from,
15173 owned_string.into_bytes(),
15174 "From<RestartPolicy> for Vec<u8> and \
15175 String::from(policy).into_bytes() must resolve to \
15176 byte-equal byte-tails on RestartPolicy::{variant:?}"
15177 );
15178 let owned_cow: std::borrow::Cow<'static, str> =
15179 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
15180 assert_eq!(
15181 via_owned_from,
15182 owned_cow.as_bytes().to_vec(),
15183 "From<RestartPolicy> for Vec<u8> and \
15184 From<RestartPolicy> for Cow<'static, str> must \
15185 resolve to byte-equal byte-tails on \
15186 RestartPolicy::{variant:?}"
15187 );
15188 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
15189 assert_eq!(
15190 via_owned_from,
15191 owned_box.as_bytes().to_vec(),
15192 "From<RestartPolicy> for Vec<u8> and \
15193 From<RestartPolicy> for Box<str> must resolve to \
15194 byte-equal byte-tails on RestartPolicy::{variant:?}"
15195 );
15196 let owned_arc: std::sync::Arc<str> =
15197 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
15198 assert_eq!(
15199 via_owned_from,
15200 owned_arc.as_bytes().to_vec(),
15201 "From<RestartPolicy> for Vec<u8> and \
15202 From<RestartPolicy> for std::sync::Arc<str> must \
15203 resolve to byte-equal byte-tails on \
15204 RestartPolicy::{variant:?}"
15205 );
15206 }
15207 // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
15208 // and borrowed input shapes: the generic owned-byte-input
15209 // function `generic_owned_bytes_sink` (lifted above per
15210 // `clippy::items_after_statements`) accepts a
15211 // [`super::RestartPolicy`] and a `&RestartPolicy` directly
15212 // through the trait bound, without the caller open-coding
15213 // the three-hop `restart.as_str().as_bytes().to_vec()`
15214 // composition.
15215 for &variant in RestartPolicy::ALL {
15216 let via_generic_owned = generic_owned_bytes_sink(variant);
15217 // Bind the borrowed-input path through an explicit
15218 // `&RestartPolicy` local so the generic-consumer witness
15219 // routes through `From<&RestartPolicy> for Vec<u8>` (T
15220 // binds to `&RestartPolicy`) rather than clippy-collapsing
15221 // the borrow onto the owned-input peer.
15222 let variant_ref: &RestartPolicy = &variant;
15223 let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
15224 let via_method_bytes = variant.as_str().as_bytes().to_vec();
15225 assert_eq!(
15226 via_generic_owned, via_method_bytes,
15227 "generic `<T: Into<Vec<u8>>>`-bound consumer on \
15228 RestartPolicy::{variant:?} must yield the same byte-\
15229 tail RestartPolicy::as_str().as_bytes() returns — \
15230 divergence signals the byte-owned axis fails to bridge \
15231 a generic owned-byte-input trait bound to the \
15232 substrate-primitive accessor"
15233 );
15234 assert_eq!(
15235 via_generic_borrowed, via_method_bytes,
15236 "generic `<T: Into<Vec<u8>>>`-bound consumer on \
15237 &RestartPolicy::{variant:?} must yield the same byte-\
15238 tail RestartPolicy::as_str().as_bytes() returns — \
15239 the borrowed-input surface must resolve to the same \
15240 as_str dispatch"
15241 );
15242 }
15243 // `std::io::Write::write_all`-shape owned-byte-sink surface
15244 // witness: the `MockOwnedByteSink` (lifted above per
15245 // `clippy::items_after_statements`) mirrors
15246 // `std::io::Write::write_all` /
15247 // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
15248 // bound owned-byte input signature and accepts a
15249 // [`super::RestartPolicy`] directly on both owned and
15250 // borrowed input shapes, routing its byte-tail through the
15251 // substrate-primitive `as_str` accessor — the shape a future
15252 // per-child per-`:restart` audit-log emit composes to fold a
15253 // `:restart` discriminator byte-tag into a downstream owned-
15254 // byte-sink surface.
15255 for &variant in RestartPolicy::ALL {
15256 let mut owned_sink = MockOwnedByteSink::new();
15257 owned_sink.write_all(variant);
15258 let owned_folded = owned_sink.finalize();
15259 assert_eq!(
15260 owned_folded,
15261 variant.as_str().as_bytes(),
15262 "`sink.write_all(restart)`-shape composition on \
15263 RestartPolicy::{variant:?} must fold the same byte-\
15264 tail RestartPolicy::as_str().as_bytes() returns"
15265 );
15266 let mut borrowed_sink = MockOwnedByteSink::new();
15267 let variant_ref: &RestartPolicy = &variant;
15268 borrowed_sink.write_all(variant_ref);
15269 let borrowed_folded = borrowed_sink.finalize();
15270 assert_eq!(
15271 borrowed_folded,
15272 variant.as_str().as_bytes(),
15273 "`sink.write_all(&restart)`-shape composition on \
15274 &RestartPolicy::{variant:?} must fold the same byte-\
15275 tail RestartPolicy::as_str().as_bytes() returns — \
15276 the borrowed-input surface must resolve to the same \
15277 as_str dispatch"
15278 );
15279 }
15280 }
15281
15282 #[test]
15283 fn restart_policy_from_into_owned_cow_bytes_routes_through_as_str_accessor() {
15284 // Fail-before-pass-after byte-parity pin on the newly lifted
15285 // `impl From<RestartPolicy> for std::borrow::Cow<'static, [u8]>`
15286 // and `impl From<&RestartPolicy> for std::borrow::Cow<'static, [u8]>` —
15287 // asserts the trait-idiomatic byte-owned reverse-projection standard-
15288 // library impls and the substrate-primitive
15289 // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
15290 // `.as_bytes()` byte-view resolve to the same three-arm PascalCase
15291 // wire byte-string emit-set across every arm the exhaustive
15292 // [`super::RestartPolicy::ALL`] slice enumerates. Additionally
15293 // asserts the returned `Cow<'static, [u8]>` binds the zero-alloc
15294 // `Cow::Borrowed` arm on both input shapes, because
15295 // `Self::as_str` returns `&'static str` and `.as_bytes()` on it
15296 // preserves the `&'static [u8]` lifetime by construction.
15297 //
15298 // Generic `<T: Into<Cow<'static, [u8]>>>`-bound consumer witness
15299 // helper: a future per-child byte-writer that accepts a
15300 // `Cow<'static, [u8]>` composes on both owned and borrowed input
15301 // shapes without an open-coded three-hop
15302 // `Cow::Borrowed(policy.as_str().as_bytes())` at every call
15303 // site. Lifted to the top of the function per
15304 // `clippy::items_after_statements`.
15305 fn generic_cow_bytes_sink<T: Into<std::borrow::Cow<'static, [u8]>>>(
15306 t: T,
15307 ) -> std::borrow::Cow<'static, [u8]> {
15308 t.into()
15309 }
15310 for &variant in RestartPolicy::ALL {
15311 let via_owned_from: std::borrow::Cow<'static, [u8]> =
15312 <std::borrow::Cow<'static, [u8]> as From<RestartPolicy>>::from(variant);
15313 let via_borrowed_from: std::borrow::Cow<'static, [u8]> =
15314 <std::borrow::Cow<'static, [u8]> as From<&RestartPolicy>>::from(&variant);
15315 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
15316 assert_eq!(
15317 via_owned_from.as_ref(),
15318 via_method_bytes,
15319 "From<RestartPolicy> for Cow<'static, [u8]> impl must \
15320 byte-equal RestartPolicy::as_str().as_bytes() on \
15321 RestartPolicy::{variant:?} — divergence signals a \
15322 silent detour off the substrate-primitive accessor"
15323 );
15324 assert_eq!(
15325 via_borrowed_from.as_ref(),
15326 via_method_bytes,
15327 "From<&RestartPolicy> for Cow<'static, [u8]> impl must \
15328 byte-equal RestartPolicy::as_str().as_bytes() on \
15329 RestartPolicy::{variant:?} — divergence signals a \
15330 silent detour off the substrate-primitive accessor"
15331 );
15332 assert!(
15333 matches!(via_owned_from, std::borrow::Cow::Borrowed(_)),
15334 "From<RestartPolicy> for Cow<'static, [u8]> must bind \
15335 the zero-alloc Cow::Borrowed arm on \
15336 RestartPolicy::{variant:?} — Self::as_str returns \
15337 &'static str, so a Cow::Owned arm signals a silent \
15338 allocation off the substrate primitive"
15339 );
15340 assert!(
15341 matches!(via_borrowed_from, std::borrow::Cow::Borrowed(_)),
15342 "From<&RestartPolicy> for Cow<'static, [u8]> must bind \
15343 the zero-alloc Cow::Borrowed arm on \
15344 &RestartPolicy::{variant:?} — Self::as_str returns \
15345 &'static str, so a Cow::Owned arm signals a silent \
15346 allocation off the substrate primitive"
15347 );
15348 // Cross-axis partition against the paired byte-owned
15349 // `Vec<u8>` reverse-projection axis on the same enum — the
15350 // two byte-owned reverse-projection axes must byte-agree on
15351 // every arm.
15352 let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
15353 assert_eq!(
15354 via_owned_from.as_ref(),
15355 via_vec_bytes.as_slice(),
15356 "From<RestartPolicy> for Cow<'static, [u8]> and \
15357 From<RestartPolicy> for Vec<u8> must byte-agree on \
15358 RestartPolicy::{variant:?} — divergence signals the \
15359 two byte-owned reverse-projection axes have drifted \
15360 off the same substrate-primitive as_str accessor"
15361 );
15362 // Cross-axis partition against the paired str-side
15363 // `Cow<'static, str>` reverse-projection axis on the same
15364 // enum — the byte-side and str-side Cow<'static, _> axes
15365 // must both bind the Cow::Borrowed arm on every arm (both
15366 // route through Self::as_str's &'static return).
15367 let via_cow_str: std::borrow::Cow<'static, str> =
15368 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
15369 assert_eq!(
15370 via_owned_from.as_ref(),
15371 via_cow_str.as_bytes(),
15372 "From<RestartPolicy> for Cow<'static, [u8]> and \
15373 From<RestartPolicy> for Cow<'static, str> must \
15374 byte-agree on RestartPolicy::{variant:?} — \
15375 divergence signals a silent detour off the shared \
15376 substrate-primitive as_str accessor"
15377 );
15378 }
15379 for &variant in RestartPolicy::ALL {
15380 let owned_via_generic = generic_cow_bytes_sink(variant);
15381 let variant_ref: &RestartPolicy = &variant;
15382 let borrowed_via_generic = generic_cow_bytes_sink(variant_ref);
15383 assert_eq!(
15384 owned_via_generic.as_ref(),
15385 variant.as_str().as_bytes(),
15386 "<T: Into<Cow<'static, [u8]>>>-bound composition on \
15387 RestartPolicy::{variant:?} must fold the same byte-\
15388 tail RestartPolicy::as_str().as_bytes() returns"
15389 );
15390 assert_eq!(
15391 borrowed_via_generic.as_ref(),
15392 variant.as_str().as_bytes(),
15393 "<T: Into<Cow<'static, [u8]>>>-bound composition on \
15394 &RestartPolicy::{variant:?} must fold the same byte-\
15395 tail RestartPolicy::as_str().as_bytes() returns"
15396 );
15397 }
15398 }
15399
15400 #[test]
15401 fn restart_policy_from_into_owned_box_bytes_routes_through_as_str_accessor() {
15402 // Fail-before-pass-after byte-parity pin on the newly lifted
15403 // `impl From<RestartPolicy> for Box<[u8]>` — asserts the owned-
15404 // input byte-owned reverse projection routes through the
15405 // substrate-primitive [`super::RestartPolicy::as_str`]
15406 // `pub const fn` accessor's `.as_bytes()` byte-view via
15407 // [`Box::<[u8]>::from`] on the returned `&'static [u8]` and
15408 // resolves to the same three-arm PascalCase wire byte-string
15409 // emit-set across every arm the exhaustive
15410 // [`super::RestartPolicy::ALL`] slice enumerates. Refuses any
15411 // future silent detour that would swap
15412 // `Box::<[u8]>::from(policy.as_str().as_bytes())` for a
15413 // `Vec::<u8>::from(policy).into_boxed_slice()` double-hop, a
15414 // routing through the sibling `fmt::Display` emitter, or a stray
15415 // normalization step that would drop or rebrand a canonical
15416 // PascalCase arm ahead of the boxed byte-emit. Cross-axis
15417 // partition against the paired owned-input byte-owned reverse-
15418 // projection axes ([`Vec<u8>`], [`Cow<'static, [u8]>`]) and the
15419 // paired string-side [`Box<str>`] forward-projection axis on the
15420 // same primitive — all four routes must byte-agree on every arm,
15421 // otherwise the byte-owned reverse-projection matrix has drifted
15422 // off the shared substrate-primitive `as_str` accessor.
15423 for &variant in RestartPolicy::ALL {
15424 let via_owned_from: Box<[u8]> = <Box<[u8]> as From<RestartPolicy>>::from(variant);
15425 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
15426 assert_eq!(
15427 via_owned_from.as_ref(),
15428 via_method_bytes,
15429 "From<RestartPolicy> for Box<[u8]> impl must byte-\
15430 equal RestartPolicy::as_str().as_bytes() on \
15431 RestartPolicy::{variant:?} — divergence signals a \
15432 silent detour off the substrate-primitive accessor"
15433 );
15434 // Cross-axis partition against the paired owned-input
15435 // `Vec<u8>` and `Cow<'static, [u8]>` byte-owned reverse-
15436 // projection axes on the same enum — all three axes must
15437 // byte-agree on every arm.
15438 let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
15439 let via_cow_bytes: std::borrow::Cow<'static, [u8]> =
15440 <std::borrow::Cow<'static, [u8]> as From<RestartPolicy>>::from(variant);
15441 assert_eq!(
15442 via_owned_from.as_ref(),
15443 via_vec_bytes.as_slice(),
15444 "From<RestartPolicy> for Box<[u8]> and \
15445 From<RestartPolicy> for Vec<u8> must byte-agree on \
15446 RestartPolicy::{variant:?} — divergence signals the \
15447 owned-input byte-owned reverse-projection axes have \
15448 drifted off the same substrate-primitive as_str \
15449 accessor"
15450 );
15451 assert_eq!(
15452 via_owned_from.as_ref(),
15453 via_cow_bytes.as_ref(),
15454 "From<RestartPolicy> for Box<[u8]> and \
15455 From<RestartPolicy> for Cow<'static, [u8]> must \
15456 byte-agree on RestartPolicy::{variant:?} — \
15457 divergence signals the owned-input byte-owned reverse-\
15458 projection axes have drifted off the same substrate-\
15459 primitive as_str accessor"
15460 );
15461 // Cross-axis partition against the paired string-side
15462 // `Box<str>` forward-projection axis on the same enum — the
15463 // byte-side and str-side `Box<_>` axes must byte-agree on
15464 // every arm (both route through Self::as_str's `&'static str`
15465 // return).
15466 let via_box_str: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
15467 assert_eq!(
15468 via_owned_from.as_ref(),
15469 via_box_str.as_bytes(),
15470 "From<RestartPolicy> for Box<[u8]> and \
15471 From<RestartPolicy> for Box<str> must byte-agree on \
15472 RestartPolicy::{variant:?} — divergence signals a \
15473 silent detour off the shared substrate-primitive \
15474 as_str accessor"
15475 );
15476 }
15477 }
15478
15479 #[test]
15480 fn restart_policy_from_borrowed_into_owned_box_bytes_routes_through_as_str_accessor() {
15481 // Fail-before-pass-after byte-parity pin on the newly lifted
15482 // `impl From<&RestartPolicy> for Box<[u8]>` — asserts the
15483 // borrowed-input byte-owned reverse projection routes byte-for-
15484 // byte through the substrate-primitive
15485 // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
15486 // `.as_bytes()` byte-view via [`Box::<[u8]>::from`] on the
15487 // returned `&'static [u8]` on every arm the exhaustive
15488 // [`super::RestartPolicy::ALL`] slice enumerates, preserving
15489 // the source [`super::RestartPolicy`] intact (no move-out).
15490 // Additionally asserts the paired owned-input and borrowed-input
15491 // corners byte-agree on the same arm, closing the
15492 // `{Self, &Self} → Box<[u8]>` byte-owned reverse-projection
15493 // family on this primitive.
15494 //
15495 // Generic `<T: Into<Box<[u8]>>>`-bound consumer witness helper:
15496 // a future per-child byte-writer that accepts a [`Box<[u8]>`]
15497 // composes on both owned and borrowed input shapes without an
15498 // open-coded `Box::<[u8]>::from(policy.as_str().as_bytes())` at
15499 // every call site. Lifted to the top of the function per
15500 // `clippy::items_after_statements`.
15501 fn generic_box_bytes_sink<T: Into<Box<[u8]>>>(t: T) -> Box<[u8]> {
15502 t.into()
15503 }
15504 for &variant in RestartPolicy::ALL {
15505 let via_borrowed_from: Box<[u8]> = <Box<[u8]> as From<&RestartPolicy>>::from(&variant);
15506 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
15507 assert_eq!(
15508 via_borrowed_from.as_ref(),
15509 via_method_bytes,
15510 "From<&RestartPolicy> for Box<[u8]> impl must byte-\
15511 equal RestartPolicy::as_str().as_bytes() on \
15512 &RestartPolicy::{variant:?} — divergence signals a \
15513 silent detour off the substrate-primitive accessor"
15514 );
15515 // The borrowed-input impl must not move out of the source —
15516 // the source RestartPolicy must survive the projection.
15517 let survivor: &'static str = variant.as_str();
15518 assert_eq!(
15519 survivor.as_bytes(),
15520 via_method_bytes,
15521 "source &RestartPolicy::{variant:?} must survive \
15522 borrowed-input projection — a move-out here signals \
15523 the impl silently dereferences past the borrowed \
15524 handle"
15525 );
15526 // Cross-corner partition against the paired owned-input
15527 // `Box<[u8]>` axis on the same enum — the two corners must
15528 // byte-agree on every arm, closing the "owned-input move
15529 // vs. borrowed-input clone" bifurcation on the same wire
15530 // byte-string through the `Box<[u8]>` axis.
15531 let via_owned_from: Box<[u8]> = <Box<[u8]> as From<RestartPolicy>>::from(variant);
15532 assert_eq!(
15533 via_borrowed_from.as_ref(),
15534 via_owned_from.as_ref(),
15535 "From<&RestartPolicy> for Box<[u8]> and \
15536 From<RestartPolicy> for Box<[u8]> must byte-agree on \
15537 RestartPolicy::{variant:?} — divergence signals the \
15538 paired owned-input and borrowed-input corners have \
15539 drifted off the same substrate-primitive as_str \
15540 accessor"
15541 );
15542 let owned_via_generic = generic_box_bytes_sink(variant);
15543 let variant_ref: &RestartPolicy = &variant;
15544 let borrowed_via_generic = generic_box_bytes_sink(variant_ref);
15545 assert_eq!(
15546 owned_via_generic.as_ref(),
15547 via_method_bytes,
15548 "<T: Into<Box<[u8]>>>-bound composition on \
15549 RestartPolicy::{variant:?} must fold the same byte-\
15550 tail RestartPolicy::as_str().as_bytes() returns"
15551 );
15552 assert_eq!(
15553 borrowed_via_generic.as_ref(),
15554 via_method_bytes,
15555 "<T: Into<Box<[u8]>>>-bound composition on \
15556 &RestartPolicy::{variant:?} must fold the same byte-\
15557 tail RestartPolicy::as_str().as_bytes() returns"
15558 );
15559 }
15560 }
15561
15562 #[test]
15563 fn restart_policy_from_into_owned_arc_bytes_routes_through_as_str_accessor() {
15564 // Fail-before-pass-after byte-parity pin on the newly lifted
15565 // `impl From<RestartPolicy> for std::sync::Arc<[u8]>` — asserts the
15566 // owned-input byte-owned reverse projection routes through the
15567 // substrate-primitive [`super::RestartPolicy::as_str`]
15568 // `pub const fn` accessor's `.as_bytes()` byte-view via
15569 // [`std::sync::Arc::<[u8]>::from`] on the returned `&'static [u8]`
15570 // and resolves to the same three-arm PascalCase wire byte-string
15571 // emit-set across every arm the exhaustive
15572 // [`super::RestartPolicy::ALL`] slice enumerates. Refuses any
15573 // future silent detour that would swap
15574 // `std::sync::Arc::<[u8]>::from(policy.as_str().as_bytes())` for a
15575 // `Box::<[u8]>::from(policy).into()` double-hop, a routing through
15576 // the sibling `fmt::Display` emitter, or a stray normalization step
15577 // that would drop or rebrand a canonical PascalCase arm ahead of
15578 // the atomic-refcounted byte-emit. Cross-axis partition against
15579 // the paired owned-input byte-owned reverse-projection axes
15580 // ([`Vec<u8>`], [`Cow<'static, [u8]>`], [`Box<[u8]>`]) on the same
15581 // primitive — all four routes must byte-agree on every arm.
15582 for &variant in RestartPolicy::ALL {
15583 let via_owned_from: std::sync::Arc<[u8]> =
15584 <std::sync::Arc<[u8]> as From<RestartPolicy>>::from(variant);
15585 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
15586 assert_eq!(
15587 via_owned_from.as_ref(),
15588 via_method_bytes,
15589 "From<RestartPolicy> for Arc<[u8]> impl must byte-\
15590 equal RestartPolicy::as_str().as_bytes() on \
15591 RestartPolicy::{variant:?} — divergence signals a \
15592 silent detour off the substrate-primitive accessor"
15593 );
15594 let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
15595 let via_cow_bytes: std::borrow::Cow<'static, [u8]> =
15596 <std::borrow::Cow<'static, [u8]> as From<RestartPolicy>>::from(variant);
15597 let via_box_bytes: Box<[u8]> = <Box<[u8]> as From<RestartPolicy>>::from(variant);
15598 assert_eq!(
15599 via_owned_from.as_ref(),
15600 via_vec_bytes.as_slice(),
15601 "From<RestartPolicy> for Arc<[u8]> and \
15602 From<RestartPolicy> for Vec<u8> must byte-agree on \
15603 RestartPolicy::{variant:?} — divergence signals the \
15604 owned-input byte-owned reverse-projection axes have \
15605 drifted off the same substrate-primitive as_str \
15606 accessor"
15607 );
15608 assert_eq!(
15609 via_owned_from.as_ref(),
15610 via_cow_bytes.as_ref(),
15611 "From<RestartPolicy> for Arc<[u8]> and \
15612 From<RestartPolicy> for Cow<'static, [u8]> must byte-\
15613 agree on RestartPolicy::{variant:?} — divergence \
15614 signals the owned-input byte-owned reverse-projection \
15615 axes have drifted off the same substrate-primitive \
15616 as_str accessor"
15617 );
15618 assert_eq!(
15619 via_owned_from.as_ref(),
15620 via_box_bytes.as_ref(),
15621 "From<RestartPolicy> for Arc<[u8]> and \
15622 From<RestartPolicy> for Box<[u8]> must byte-agree on \
15623 RestartPolicy::{variant:?} — divergence signals the \
15624 owned-input byte-owned reverse-projection axes have \
15625 drifted off the same substrate-primitive as_str \
15626 accessor"
15627 );
15628 }
15629 }
15630
15631 #[test]
15632 fn restart_policy_from_borrowed_into_owned_arc_bytes_routes_through_as_str_accessor() {
15633 // Fail-before-pass-after byte-parity pin on the newly lifted
15634 // `impl From<&RestartPolicy> for std::sync::Arc<[u8]>` — asserts
15635 // the borrowed-input byte-owned reverse projection routes byte-
15636 // for-byte through the substrate-primitive
15637 // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
15638 // `.as_bytes()` byte-view via [`std::sync::Arc::<[u8]>::from`] on
15639 // the returned `&'static [u8]` on every arm the exhaustive
15640 // [`super::RestartPolicy::ALL`] slice enumerates, preserving the
15641 // source [`super::RestartPolicy`] intact (no move-out).
15642 // Additionally asserts the paired owned-input and borrowed-input
15643 // corners byte-agree on the same arm, closing the
15644 // `{Self, &Self} → std::sync::Arc<[u8]>` byte-owned reverse-
15645 // projection family on this primitive.
15646 fn generic_arc_bytes_sink<T: Into<std::sync::Arc<[u8]>>>(t: T) -> std::sync::Arc<[u8]> {
15647 t.into()
15648 }
15649 for &variant in RestartPolicy::ALL {
15650 let via_borrowed_from: std::sync::Arc<[u8]> =
15651 <std::sync::Arc<[u8]> as From<&RestartPolicy>>::from(&variant);
15652 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
15653 assert_eq!(
15654 via_borrowed_from.as_ref(),
15655 via_method_bytes,
15656 "From<&RestartPolicy> for Arc<[u8]> impl must byte-\
15657 equal RestartPolicy::as_str().as_bytes() on \
15658 &RestartPolicy::{variant:?} — divergence signals a \
15659 silent detour off the substrate-primitive accessor"
15660 );
15661 let survivor: &'static str = variant.as_str();
15662 assert_eq!(
15663 survivor.as_bytes(),
15664 via_method_bytes,
15665 "source &RestartPolicy::{variant:?} must survive \
15666 borrowed-input projection — a move-out here signals \
15667 the impl silently dereferences past the borrowed \
15668 handle"
15669 );
15670 let via_owned_from: std::sync::Arc<[u8]> =
15671 <std::sync::Arc<[u8]> as From<RestartPolicy>>::from(variant);
15672 assert_eq!(
15673 via_borrowed_from.as_ref(),
15674 via_owned_from.as_ref(),
15675 "From<&RestartPolicy> for Arc<[u8]> and \
15676 From<RestartPolicy> for Arc<[u8]> must byte-agree on \
15677 RestartPolicy::{variant:?} — divergence signals the \
15678 paired owned-input and borrowed-input corners have \
15679 drifted off the same substrate-primitive as_str \
15680 accessor"
15681 );
15682 let owned_via_generic = generic_arc_bytes_sink(variant);
15683 let variant_ref: &RestartPolicy = &variant;
15684 let borrowed_via_generic = generic_arc_bytes_sink(variant_ref);
15685 assert_eq!(
15686 owned_via_generic.as_ref(),
15687 via_method_bytes,
15688 "<T: Into<Arc<[u8]>>>-bound composition on \
15689 RestartPolicy::{variant:?} must fold the same byte-\
15690 tail RestartPolicy::as_str().as_bytes() returns"
15691 );
15692 assert_eq!(
15693 borrowed_via_generic.as_ref(),
15694 via_method_bytes,
15695 "<T: Into<Arc<[u8]>>>-bound composition on \
15696 &RestartPolicy::{variant:?} must fold the same byte-\
15697 tail RestartPolicy::as_str().as_bytes() returns"
15698 );
15699 }
15700 }
15701
15702 #[test]
15703 fn restart_policy_all_enumerates_every_variant_exactly_once() {
15704 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
15705 // exhaustive-iteration surface: every variant appears exactly
15706 // once, and the slice length matches the arm count of the
15707 // closed set. Every consumer that walks the accepted-policy
15708 // set (a future `feira supervisor --restart …` CLI-side
15709 // arg-parse's "did you mean" hint, a future M4 admission-
15710 // webhook's per-child rejection body naming the accepted-
15711 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
15712 // projection consumers that iterate the accept-set for
15713 // diagnostic rendering) reads through this slice, so a future
15714 // arm addition that grows the enum but forgets to grow
15715 // [`Self::ALL`] silently truncates every downstream consumer's
15716 // accept-set at the same pre-addition boundary — this pin
15717 // fails at caixa-core build time on the pairwise-distinct +
15718 // arm-count invariants.
15719 //
15720 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
15721 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
15722 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
15723 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
15724 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
15725 // pins on the peer closed-set typed-enum axes.
15726 let all: &[RestartPolicy] = RestartPolicy::ALL;
15727 assert_eq!(
15728 all.len(),
15729 3,
15730 "RestartPolicy::ALL must enumerate every variant of the \
15731 three-arm closed set (Permanent, Temporary, Transient); \
15732 got {all:?}"
15733 );
15734 for (i, a) in all.iter().enumerate() {
15735 for (j, b) in all.iter().enumerate() {
15736 if i != j {
15737 assert_ne!(
15738 a, b,
15739 "RestartPolicy::ALL must carry every variant exactly \
15740 once — got duplicate {a:?} at indices {i} and {j}"
15741 );
15742 }
15743 }
15744 }
15745 for variant in [
15746 RestartPolicy::Permanent,
15747 RestartPolicy::Temporary,
15748 RestartPolicy::Transient,
15749 ] {
15750 assert!(
15751 all.contains(&variant),
15752 "RestartPolicy::ALL must contain {variant:?} — a future arm \
15753 addition that grows the enum but forgets to grow the ALL slice \
15754 silently truncates every downstream consumer's accept-set at \
15755 the pre-addition boundary"
15756 );
15757 }
15758 }
15759
15760 #[test]
15761 fn restart_policy_wire_names_covers_every_arm() {
15762 // Load-bearing pin on the substrate-canonical
15763 // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
15764 // the `PascalCase` wire byte-string axis: every variant of the
15765 // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
15766 // must project through [`RestartPolicy::as_str`] onto an entry
15767 // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
15768 // roster's length must byte-equal `RestartPolicy::ALL.len()` so
15769 // a silent skew between the [`RestartPolicy::as_str`] match's
15770 // arm-set and the roster's arm-set trips here at caixa-core
15771 // test time rather than at a downstream M4
15772 // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
15773 // rejection body's wire-form `:restart` accepted-set
15774 // enumeration miss / a `feira supervisor --restart …` "did you
15775 // mean" hint drift / a future wasm-operator per-reconcile-step
15776 // diagnostic log line's accepted-wire-form enumeration miss.
15777 // A future arm addition (an OTP-`intrinsic` fourth arm the
15778 // theory
15779 // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
15780 // might reach for once the three canonical OTP restart policies
15781 // stop covering the substrate's discovered load-shape) extends
15782 // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
15783 // the new arm by iteration; the paired
15784 // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
15785 // this assertion trips. Every entry is further pinned to open
15786 // with an ASCII uppercase byte so a silent collapse of the
15787 // wire-form axis with the peer kebab-case dispatcher-catalog
15788 // axis (an entry byte-identical to a sibling
15789 // [`RestartPolicy::discriminant`] kebab byte-string that would
15790 // let a wire-axis consumer accept the dispatcher-catalog
15791 // vocabulary) trips here rather than at a downstream K8s-CR
15792 // round-trip miss.
15793 //
15794 // Peer of the sibling
15795 // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
15796 // pin on the first M2 OTP-shape sibling-restart closed-set
15797 // typed enum, the sibling
15798 // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
15799 // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
15800 // closed-set typed enum, the sibling
15801 // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
15802 // (bd708bd) pin on the top-level typed-kind discriminator's
15803 // `PascalCase` wire byte-string axis, and the sibling
15804 // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
15805 // (cc42c0e) /
15806 // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
15807 // (1898d77) pins on the OTP-appup discriminator's two-axis
15808 // roster split — the same closed-set exhaustive-roster coverage
15809 // discipline extended here onto the second and final M2
15810 // OTP-shape sibling-enum on the caixa surface, closing the
15811 // per-child restart-decision-policy axis paired with the peer
15812 // per-supervisor sibling-restart-strategy axis on the same M2
15813 // `:supervisor` slot.
15814 //
15815 // Fail-before-pass-after locally verified by mutating one arm
15816 // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
15817 // const family (e.g. dropping the trailing `t` from
15818 // `"Permanent"` → `"Permanen"`) — the length pin still passes
15819 // but the `contains` check fires on the mutated arm; and by
15820 // shortening the roster to two entries — the length pin fires
15821 // first.
15822 assert_eq!(
15823 RestartPolicy::WIRE_NAMES.len(),
15824 RestartPolicy::ALL.len(),
15825 "RestartPolicy::WIRE_NAMES.len() must byte-equal \
15826 RestartPolicy::ALL.len() — a mismatch means the roster \
15827 and the enum's arm-set have drifted; downstream consumers \
15828 that fan through both will silently disagree on the \
15829 accepted arm-set"
15830 );
15831 for &variant in RestartPolicy::ALL {
15832 let wire = variant.as_str();
15833 assert!(
15834 RestartPolicy::WIRE_NAMES.contains(&wire),
15835 "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
15836 be a member of RestartPolicy::WIRE_NAMES — the \
15837 emitter and the roster have drifted out of lockstep"
15838 );
15839 }
15840 for tag in RestartPolicy::WIRE_NAMES {
15841 let first = tag.chars().next().unwrap_or_else(|| {
15842 panic!(
15843 "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
15844 a non-empty PascalCase byte-string"
15845 )
15846 });
15847 assert!(
15848 first.is_ascii_uppercase(),
15849 "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
15850 with an ASCII uppercase byte (PascalCase wire form) — \
15851 a lowercase entry would collide the wire-form axis \
15852 with the peer kebab-case dispatcher-catalog axis \
15853 [`RestartPolicy::discriminant`] serves"
15854 );
15855 }
15856 }
15857
15858 #[test]
15859 fn restart_policy_from_wire_accepts_every_lifted_constant() {
15860 // Fail-before-pass-after pin on the forward accept-set of the
15861 // [`RestartPolicy::from_wire`] reverse projection: every
15862 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
15863 // constant the [`RestartPolicy::as_str`] emitter walks parses
15864 // back to its paired variant. Any future arm addition that
15865 // grows the emitter's `as_str` match but forgets to grow the
15866 // parser's `from_wire` match silently splits the two halves of
15867 // the round-trip — the wire byte-string one non-serde consumer
15868 // parses from the one the emitter wrote — with the failure
15869 // surfacing at the operator's reconcile posture (a `:temporary`
15870 // `oneShot` child restarted on clean exit, a `:transient` child
15871 // restarted after clean completion) far from the rebrand
15872 // commit. Pinning the three-arm accept-set here catches the
15873 // drift at caixa-core build time.
15874 //
15875 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
15876 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
15877 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
15878 // accept-set pins on the peer closed-set typed-enum `str → Self`
15879 // axes.
15880 for (wire, expected) in [
15881 (
15882 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
15883 RestartPolicy::Permanent,
15884 ),
15885 (
15886 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
15887 RestartPolicy::Temporary,
15888 ),
15889 (
15890 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
15891 RestartPolicy::Transient,
15892 ),
15893 ] {
15894 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
15895 panic!(
15896 "RestartPolicy::from_wire({wire:?}) must accept every \
15897 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
15898 lifted canonical byte-string that RestartPolicy::{expected:?} \
15899 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
15900 )
15901 });
15902 assert_eq!(
15903 parsed, expected,
15904 "RestartPolicy::from_wire({wire:?}) must return \
15905 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
15906 );
15907 }
15908 }
15909
15910 #[test]
15911 fn restart_policy_from_wire_round_trips_through_as_str() {
15912 // Fail-before-pass-after pin on the closed round-trip between
15913 // the forward [`RestartPolicy::as_str`] emitter and the
15914 // reverse [`RestartPolicy::from_wire`] parser: for every
15915 // variant in [`RestartPolicy::ALL`], parsing the emitter's
15916 // output must return exactly the same variant. Any per-arm
15917 // divergence — a future arm added to `as_str` but not
15918 // `from_wire`, an accidental copy-paste flip in one but not
15919 // the other — silently splits the emit and parse halves and
15920 // the failure surfaces at consumer parse time far from the
15921 // drift site. The `ALL`-iterating shape means a future arm
15922 // addition picks up the coverage by construction.
15923 //
15924 // Peer of the sibling
15925 // [`restart_strategy_from_wire_round_trips_through_as_str`]
15926 // (4eec29c) round-trip pin on
15927 // [`RestartStrategy::from_wire`] and the M3
15928 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
15929 // (18c7342) round-trip pin on
15930 // [`crate::aplicacao::PlacementStrategy::from_wire`].
15931 for &variant in RestartPolicy::ALL {
15932 let wire = variant.as_str();
15933 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
15934 panic!(
15935 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
15936 must be Some({variant:?}) — the two halves of the round-trip \
15937 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
15938 got None on wire byte-string {wire:?}"
15939 )
15940 });
15941 assert_eq!(
15942 parsed, variant,
15943 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
15944 must round-trip to the same variant; got {parsed:?}"
15945 );
15946 }
15947 }
15948
15949 #[test]
15950 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
15951 // Fail-before-pass-after pin on the closed-set refusal
15952 // discipline of [`RestartPolicy::from_wire`]: every
15953 // byte-string outside the three-arm accept-set returns `None`
15954 // rather than silently collapsing onto the [`Default`]
15955 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
15956 // exercised here sweeps the load-bearing drift shapes: the
15957 // empty string (a stripped serde-attribute drift), all-
15958 // whitespace strings (the canonical text-editor accidental
15959 // padding shape), the kebab-case dispatcher-catalog identities
15960 // (`"permanent"` / `"temporary"` / `"transient"` — the
15961 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
15962 // accept-set, which parses the *other* axis of this enum's
15963 // two-axis split and must not leak into the `from_wire`
15964 // PascalCase-wire accept-set — a lowercase leak here would
15965 // silently accept the operator's kebab-case
15966 // dispatcher-catalog probe under the wire-axis parser and mis-
15967 // route a `:permanent` intent), the padded canonical scalar
15968 // (`" Permanent "`), the trailing-newline shapes
15969 // (`"Permanent\n"`), the uppercase-single-word forms
15970 // (`"PERMANENT"`), and neighboring-but-unknown arms
15971 // (`"Restart"` — the canonical typo direction toward the
15972 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
15973 //
15974 // Peer of the sibling
15975 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
15976 // (4eec29c) +
15977 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
15978 // (2aa6d23) +
15979 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
15980 // (18c7342) refusal pins on the peer closed-set typed-enum
15981 // axes.
15982 for bad in [
15983 "",
15984 " ",
15985 "\n",
15986 "\t",
15987 "permanent",
15988 "temporary",
15989 "transient",
15990 "PERMANENT",
15991 "TEMPORARY",
15992 "TRANSIENT",
15993 "Permanents",
15994 "Permanent ",
15995 " Permanent",
15996 " Transient ",
15997 "Permanent\n",
15998 "perma",
15999 "Trans",
16000 "OneForOne",
16001 "Restart",
16002 "?",
16003 ] {
16004 assert!(
16005 RestartPolicy::from_wire(bad).is_none(),
16006 "RestartPolicy::from_wire({bad:?}) must return None — the \
16007 parser's accept-set is exactly the three RestartPolicy::as_str \
16008 outputs (Permanent, Temporary, Transient), and this \
16009 byte-string is outside that closed set"
16010 );
16011 }
16012 }
16013
16014 #[test]
16015 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
16016 // Fail-before-pass-after pin on the fourth path of the four-path
16017 // convergence: `from_wire` (the reverse projection) inverts the
16018 // `Serialize` derive's wire byte-string on every variant.
16019 // Together with the pre-existing three-path convergence
16020 // (`Display` + `as_str` + `Serialize` all resolve to the same
16021 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
16022 // pinned by
16023 // [`restart_policy_display_matches_serialized_wire_byte_string`])
16024 // this closes the round-trip: the wire byte-string the
16025 // `Serialize` derive emits parses back to the same variant
16026 // through `from_wire`, so any future serde-attribute or variant-
16027 // rename drift on the emit half now surfaces as a matched drift
16028 // on the parse half at caixa-core build time — the two halves
16029 // migrate as a unit through the lifted consts on any future
16030 // rename, and the round-trip cannot silently split.
16031 //
16032 // Peer of the sibling
16033 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
16034 // (4eec29c) wire-format pin on
16035 // [`RestartStrategy::from_wire`] and the M3
16036 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
16037 // (18c7342) wire-format pin on
16038 // [`crate::aplicacao::PlacementStrategy::from_wire`].
16039 for &variant in RestartPolicy::ALL {
16040 let wire = serde_json::to_string(&variant).unwrap();
16041 let unquoted = wire
16042 .strip_prefix('"')
16043 .and_then(|s| s.strip_suffix('"'))
16044 .expect("serialized RestartPolicy is a JSON string");
16045 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
16046 panic!(
16047 "RestartPolicy::from_wire({unquoted:?}) must accept the \
16048 Serialize derive's wire byte-string for \
16049 RestartPolicy::{variant:?} — the four-path convergence \
16050 (Display + as_str + Serialize + from_wire) resolves through \
16051 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
16052 )
16053 });
16054 assert_eq!(
16055 parsed, variant,
16056 "RestartPolicy::from_wire of the Serialize derive's wire \
16057 byte-string for RestartPolicy::{variant:?} must round-trip \
16058 to the same variant; got {parsed:?}"
16059 );
16060 }
16061 }
16062
16063 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
16064 //
16065 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
16066 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
16067 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
16068 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
16069 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
16070 // the peer per-`:upgrade-from :from` axis. The three pins jointly
16071 // brace the accessor against every future silent detour that would
16072 // desynchronize it from the raw `.caixa` field access every consumer
16073 // previously open-coded.
16074
16075 #[test]
16076 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
16077 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
16078 // [`ChildSpec::nome`] must return the `:children :caixa` field
16079 // byte-for-byte across every DNS-1123-label value the upstream
16080 // [`crate::render::require_valid_dns_1123_label`] gate at
16081 // `SupervisorSpec::validate` admits. Peer of the sibling
16082 // `membro_nome_returns_caixa_byte_equal_across_permutations`
16083 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
16084 // substrate-primitive accessor must byte-equal the raw field
16085 // access verbatim across every author-declared value" discipline
16086 // extended to the M2 supervisor-tree per-`:children` arm. Pins
16087 // against a future silent detour that re-normalized the child
16088 // identity (an accidental `.to_lowercase()` — every `:children
16089 // :caixa` is validated as a DNS-1123 label upstream, so any
16090 // re-normalization is redundant + a drift surface between the
16091 // validator and the accessor), a namespace-prefix rewrite (an
16092 // accidental `format!("{namespace}/{caixa}")` per-CR
16093 // fully-qualified rewrite that didn't land on the peer axes), or
16094 // a per-cluster alias stamp the future wasm-operator's
16095 // hierarchical reconciliation scheduler authors on one consumer
16096 // without the others. Five values sweep the accept-set the
16097 // DNS-1123 gate upstream admits (short single-word / dashed /
16098 // v-suffixed / mixed-digit child names).
16099 for name in [
16100 "worker",
16101 "cache-server",
16102 "scratch-job",
16103 "orders-v2",
16104 "session-8080",
16105 ] {
16106 let c = ChildSpec {
16107 caixa: name.into(),
16108 versao: "^0.1".into(),
16109 restart: RestartPolicy::Permanent,
16110 };
16111 assert_eq!(
16112 c.nome(),
16113 name,
16114 "ChildSpec::nome must return :children :caixa verbatim \
16115 (got {:?}, expected {name:?})",
16116 c.nome(),
16117 );
16118 assert_eq!(
16119 c.nome(),
16120 c.caixa.as_str(),
16121 "ChildSpec::nome must byte-equal the .caixa field access",
16122 );
16123 }
16124 }
16125
16126 #[test]
16127 fn child_spec_nome_borrows_from_caixa_storage() {
16128 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
16129 // `&str` slice that borrows from the typed slot's own [`String`]
16130 // storage — same-address invariant with `c.caixa.as_str()`. Pins
16131 // against a future silent detour that allocated a fresh `String`
16132 // (`self.caixa.clone()` in the body would type-check but silently
16133 // drop the borrow, and every downstream consumer that assumed
16134 // the returned slice outlives `&self` would break on a stale-
16135 // reference use-after-free — the [`crate::render::insert_first_seen`]
16136 // dedup key at [`SupervisorSpec::validate`], the
16137 // [`validate_no_self_supervision`] equality check against the
16138 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
16139 // borrow — each would silently misbehave if this accessor
16140 // produced a detached copy). Peer of the sibling
16141 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
16142 // M3 per-`:membros` axis and the
16143 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
16144 // first M2 slot scalar accessor.
16145 let c = ChildSpec {
16146 caixa: "worker".into(),
16147 versao: "^0.1".into(),
16148 restart: RestartPolicy::Permanent,
16149 };
16150 let name = c.nome();
16151 let caixa_slice = c.caixa.as_str();
16152 assert_eq!(
16153 name.as_ptr(),
16154 caixa_slice.as_ptr(),
16155 "ChildSpec::nome must borrow from the .caixa String's backing \
16156 storage — a fresh allocation here means the accessor no \
16157 longer names the substrate-primitive typed dispatch and \
16158 every downstream consumer would silently carry a detached \
16159 copy",
16160 );
16161 assert_eq!(
16162 name.len(),
16163 caixa_slice.len(),
16164 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
16165 as well as in address",
16166 );
16167 }
16168
16169 #[test]
16170 fn validate_gates_child_nome_through_lifted_accessor() {
16171 // Bilateral coherence pin: every `:children :caixa` that
16172 // [`SupervisorSpec::validate`] accepts is one
16173 // [`crate::render::require_valid_dns_1123_label`] accepts on the
16174 // accessor-projected value, and vice versa on the reject side.
16175 // This closes the "the validator reads through the accessor"
16176 // contract structurally — a future silent detour that made the
16177 // accessor return a different byte-string than the validator
16178 // gates against would surface here as a coverage mismatch, not
16179 // as an apply-time DNS-1123 rejection at
16180 // `metadata.name: Invalid value` far from the caixa.lisp source.
16181 // Peer of the M2 sibling
16182 // `validate_parses_prior_versao_through_lifted_accessor`
16183 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
16184 // `validate_membros` peer discipline.
16185 //
16186 // Accept-set sweep: five DNS-1123-label values the upstream gate
16187 // admits.
16188 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
16189 let s = SupervisorSpec {
16190 children: vec![ChildSpec {
16191 caixa: ok_name.into(),
16192 versao: "^0.1".into(),
16193 restart: RestartPolicy::Permanent,
16194 }],
16195 ..SupervisorSpec::default()
16196 };
16197 s.validate().unwrap_or_else(|e| {
16198 panic!(
16199 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
16200 (upstream DNS-1123 gate accepts it): got {e:?}",
16201 );
16202 });
16203 let c = ChildSpec {
16204 caixa: ok_name.into(),
16205 versao: "^0.1".into(),
16206 restart: RestartPolicy::Permanent,
16207 };
16208 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
16209 .unwrap_or_else(|()| {
16210 panic!(
16211 "require_valid_dns_1123_label must accept the accessor-projected \
16212 :children :caixa {ok_name:?}",
16213 );
16214 });
16215 }
16216 // Reject-set sweep: five DNS-1123-label-violating shapes the
16217 // upstream gate refuses (empty / uppercase / underscore / dot /
16218 // leading-hyphen). Every rejection at the validator must
16219 // correspond to a rejection when the accessor's projected value
16220 // is fed back through the shared gate.
16221 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
16222 let s = SupervisorSpec {
16223 children: vec![ChildSpec {
16224 caixa: bad_name.into(),
16225 versao: "^0.1".into(),
16226 restart: RestartPolicy::Permanent,
16227 }],
16228 ..SupervisorSpec::default()
16229 };
16230 let err = s.validate().unwrap_err();
16231 assert!(
16232 matches!(
16233 err,
16234 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
16235 ),
16236 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
16237 via the DNS-1123 gate: got {err:?}",
16238 );
16239 let c = ChildSpec {
16240 caixa: bad_name.into(),
16241 versao: "^0.1".into(),
16242 restart: RestartPolicy::Permanent,
16243 };
16244 assert!(
16245 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
16246 .is_err(),
16247 "require_valid_dns_1123_label must reject the accessor-projected \
16248 :children :caixa {bad_name:?}",
16249 );
16250 }
16251 }
16252
16253 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
16254 //
16255 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
16256 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
16257 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
16258 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
16259 // trio on the peer per-`:children` `String`-carry axis. The three pins
16260 // jointly brace the accessor against every future silent detour that
16261 // would desynchronize it from the raw `.versao` field access the
16262 // requirement gate + error carrier previously open-coded.
16263 //
16264 // Closes the last unlifted per-`:children` `String`-carry axis: the
16265 // pair (`nome`, `versao_requirement`) now jointly projects the
16266 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
16267 // consumer that fans on per-child identity + version pin reads,
16268 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
16269 // pair discipline verbatim.
16270 #[test]
16271 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
16272 // The canonical per-`:children` child-`:versao`-scalar pin:
16273 // [`ChildSpec::versao_requirement`] must return the `:children
16274 // :versao` field byte-for-byte across every Cargo-shaped semver
16275 // requirement value the upstream
16276 // [`crate::render::require_valid_versao_requirement`] gate admits.
16277 // Peer of the sibling
16278 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
16279 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
16280 // substrate-primitive accessor must byte-equal the raw field
16281 // access verbatim across every author-declared value" discipline
16282 // extended to the M2 supervisor-tree per-`:children` arm. Pins
16283 // against a future silent detour that re-canonicalized the
16284 // requirement (an accidental `.to_string()` via
16285 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
16286 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
16287 // silently drifted the error carrier's quoted requirement away
16288 // from the source `caixa.lisp`, an accidental whitespace trim on
16289 // `"^ 0.1"` that no consumer ever produced from the field-access
16290 // side, an accidental per-cluster lacre-projected concrete-version
16291 // rewrite that didn't land on the peer requirement-gate call).
16292 // Five values sweep the accept-set the shared
16293 // [`crate::render::require_valid_versao_requirement`] gate admits
16294 // (caret / tilde / exact / wildcard / bare-major).
16295 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
16296 let c = ChildSpec {
16297 caixa: "worker".into(),
16298 versao: req.into(),
16299 restart: RestartPolicy::Permanent,
16300 };
16301 assert_eq!(
16302 c.versao_requirement(),
16303 req,
16304 "ChildSpec::versao_requirement must return :children :versao \
16305 verbatim (got {:?}, expected {req:?})",
16306 c.versao_requirement(),
16307 );
16308 assert_eq!(
16309 c.versao_requirement(),
16310 c.versao.as_str(),
16311 "ChildSpec::versao_requirement must byte-equal the .versao \
16312 field access",
16313 );
16314 }
16315 }
16316
16317 #[test]
16318 fn child_spec_versao_requirement_borrows_from_versao_storage() {
16319 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
16320 // return a `&str` slice that borrows from the typed slot's own
16321 // [`String`] storage — same-address invariant with
16322 // `c.versao.as_str()`. Pins against a future silent detour that
16323 // allocated a fresh `String` (`self.versao.clone()` in the body
16324 // would type-check but silently drop the borrow, and every
16325 // downstream consumer that assumed the returned slice outlives
16326 // `&self` — the [`crate::render::require_valid_versao_requirement`]
16327 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
16328 // `.to_string()` carrier's byte-length assumption — would silently
16329 // misbehave if this accessor produced a detached copy). Peer of
16330 // the sibling `child_spec_nome_borrows_from_caixa_storage`
16331 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
16332 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
16333 // pin on the peer per-`:membros` `:versao` axis.
16334 let c = ChildSpec {
16335 caixa: "worker".into(),
16336 versao: "^0.1".into(),
16337 restart: RestartPolicy::Permanent,
16338 };
16339 let req = c.versao_requirement();
16340 let versao_slice = c.versao.as_str();
16341 assert_eq!(
16342 req.as_ptr(),
16343 versao_slice.as_ptr(),
16344 "ChildSpec::versao_requirement must borrow from the .versao \
16345 String's backing storage — a fresh allocation here means the \
16346 accessor no longer names the substrate-primitive typed \
16347 dispatch and every downstream consumer would silently carry \
16348 a detached copy",
16349 );
16350 assert_eq!(
16351 req.len(),
16352 versao_slice.len(),
16353 "ChildSpec::versao_requirement and .versao.as_str() must \
16354 byte-equal in length as well as in address",
16355 );
16356 }
16357
16358 #[test]
16359 fn validate_gates_child_versao_through_lifted_accessor() {
16360 // Bilateral coherence pin: every `:children :versao` that
16361 // [`SupervisorSpec::validate`] accepts is one
16362 // [`crate::render::require_valid_versao_requirement`] accepts on
16363 // the accessor-projected value, and vice versa on the reject side.
16364 // This closes the "the validator reads through the accessor"
16365 // contract structurally — a future silent detour that made the
16366 // accessor return a different byte-string than the validator gates
16367 // against would surface here as a coverage mismatch, not as a
16368 // resolver-time semver-parse rejection at lacre-closure time far
16369 // from the caixa.lisp source. Peer of the sibling
16370 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
16371 // the per-`:children :caixa` axis and the M2
16372 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
16373 // on the peer per-`:upgrade-from :from` axis.
16374 //
16375 // Accept-set sweep: five Cargo-shaped semver requirement values
16376 // the upstream gate admits (caret / tilde / exact / wildcard /
16377 // bare-major).
16378 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
16379 let s = SupervisorSpec {
16380 children: vec![ChildSpec {
16381 caixa: "worker".into(),
16382 versao: ok_req.into(),
16383 restart: RestartPolicy::Permanent,
16384 }],
16385 ..SupervisorSpec::default()
16386 };
16387 s.validate().unwrap_or_else(|e| {
16388 panic!(
16389 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
16390 (upstream versao-requirement gate accepts it): got {e:?}",
16391 );
16392 });
16393 let c = ChildSpec {
16394 caixa: "worker".into(),
16395 versao: ok_req.into(),
16396 restart: RestartPolicy::Permanent,
16397 };
16398 crate::render::require_valid_versao_requirement(
16399 c.versao_requirement(),
16400 || (),
16401 |_reason| (),
16402 )
16403 .unwrap_or_else(|()| {
16404 panic!(
16405 "require_valid_versao_requirement must accept the accessor-projected \
16406 :children :versao {ok_req:?}",
16407 );
16408 });
16409 }
16410 // Reject-set sweep: five requirement-violating shapes the upstream
16411 // gate refuses. The empty string closes the empty-first arm of the
16412 // shared [`crate::render::require_valid_versao_requirement`]
16413 // cascade; the four non-empty arms exercise distinct semver-parse
16414 // failure modes the M3 peer per-`:membros` reject-set already pins
16415 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
16416 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
16417 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
16418 // shared parser routing means the same reject-set must fail
16419 // identically at the M2 supervisor-tree per-`:children` accessor
16420 // arm here. Every rejection at the validator must correspond to a
16421 // rejection when the accessor's projected value is fed back
16422 // through the shared gate.
16423 //
16424 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
16425 // `"not-a-semver"` are intentionally *not* in the reject-set: the
16426 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
16427 // and the identifier-tail arm's grammar admits some non-canonical
16428 // shapes — matching what the M3 peer test suite already documents
16429 // as the shared parser's accept-set edges.)
16430 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
16431 let s = SupervisorSpec {
16432 children: vec![ChildSpec {
16433 caixa: "worker".into(),
16434 versao: bad_req.into(),
16435 restart: RestartPolicy::Permanent,
16436 }],
16437 ..SupervisorSpec::default()
16438 };
16439 let err = s.validate().unwrap_err();
16440 assert!(
16441 matches!(
16442 err,
16443 SupervisorError::EmptyChildVersion { .. }
16444 | SupervisorError::ChildVersaoInvalid { .. }
16445 ),
16446 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
16447 via the versao-requirement gate: got {err:?}",
16448 );
16449 let c = ChildSpec {
16450 caixa: "worker".into(),
16451 versao: bad_req.into(),
16452 restart: RestartPolicy::Permanent,
16453 };
16454 assert!(
16455 crate::render::require_valid_versao_requirement(
16456 c.versao_requirement(),
16457 || (),
16458 |_reason| (),
16459 )
16460 .is_err(),
16461 "require_valid_versao_requirement must reject the accessor-projected \
16462 :children :versao {bad_req:?}",
16463 );
16464 }
16465 }
16466
16467 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
16468 //
16469 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
16470 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
16471 // already project the `String`-carry `(caixa, versao)` fields; the
16472 // `Copy`-composite-enum `restart` field is the third and final axis).
16473 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
16474 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
16475 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
16476 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
16477 // strategy scalar accessor — same "one typed dispatch on the substrate
16478 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
16479 // extended onto the M2 supervisor-slot per-`:children` restart-decision
16480 // axis. The pin below covers the accessor's byte-equal projection
16481 // against the raw field access across every variant in the closed
16482 // accept-set (`Permanent`, `Transient`, `Temporary`).
16483
16484 #[test]
16485 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
16486 // The canonical per-`:children` restart-decision-policy-scalar
16487 // pin: [`ChildSpec::restart`] must return the `:children :restart`
16488 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
16489 // typed slot's own [`RestartPolicy`] storage across every variant
16490 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
16491 // Pins against a future silent detour that re-derived the policy
16492 // from a peer axis (an accidental fallback to
16493 // `if is_supervisor_child { Permanent } else { Temporary }` that
16494 // collapsed the child's kind axis into the restart discriminator),
16495 // a variant remap the operator authors on one consumer without the
16496 // other, or a stale-derive detour that substituted
16497 // [`RestartPolicy::default`] when the field held any explicit
16498 // variant (which would silently collapse the distinction between
16499 // "author explicitly declared `:restart Permanent`" and "author
16500 // omitted the slot and inherited the default" the future
16501 // per-cluster restart-decision override slot depends on).
16502 //
16503 // Peer of the sibling per-`:supervisor`
16504 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
16505 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
16506 // axis and the M3
16507 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
16508 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
16509 // — same "the substrate-primitive accessor must byte-equal the raw
16510 // field access verbatim across every author-declared value"
16511 // discipline extended onto the M2 supervisor-slot per-`:children`
16512 // restart-decision-policy axis, closing the last unlifted axis on
16513 // the per-`:children` [`ChildSpec`] type.
16514 for restart in [
16515 RestartPolicy::Permanent,
16516 RestartPolicy::Transient,
16517 RestartPolicy::Temporary,
16518 ] {
16519 let c = ChildSpec {
16520 caixa: "worker".into(),
16521 versao: "^0.1".into(),
16522 restart,
16523 };
16524 assert_eq!(
16525 c.restart(),
16526 restart,
16527 "ChildSpec::restart must return :children :restart \
16528 verbatim (got {:?}, expected {restart:?})",
16529 c.restart(),
16530 );
16531 assert_eq!(
16532 c.restart(),
16533 c.restart,
16534 "ChildSpec::restart accessor and .restart field access \
16535 must byte-equal — the accessor is the substrate-primitive \
16536 typed dispatch every downstream per-child restart-\
16537 decision consumer must route through",
16538 );
16539 }
16540 }
16541
16542 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
16543 //
16544 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
16545 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
16546 // distribution-strategy accessor discipline onto the M2 supervisor-slot
16547 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
16548 // scalar axis. The two pins below cover (1) the accessor's byte-equal
16549 // projection against the raw field access across every variant in the
16550 // closed accept-set, and (2) the two-consumer coherence between the
16551 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
16552 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
16553 // carrier's `estrategia:` field — peer of the sibling M3
16554 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
16555 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
16556 // pair on the per-`:placement` distribution-strategy axis.
16557
16558 #[test]
16559 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
16560 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
16561 // pin: [`SupervisorSpec::estrategia`] must return the
16562 // `:supervisor :estrategia` field verbatim as a
16563 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
16564 // [`RestartStrategy`] storage across every variant in the closed
16565 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
16566 // `SimpleOneForOne`). Pins against a future silent detour that
16567 // re-derived the strategy from a peer axis (an accidental
16568 // fallback to `if children.is_empty() { SimpleOneForOne } else {
16569 // OneForOne }` collapse that read the children-count axis into
16570 // the strategy discriminator), a variant remap the operator
16571 // authors on one consumer without the other, or a stale-derive
16572 // detour that substituted [`RestartStrategy::default`] when the
16573 // field held any explicit variant (which would silently collapse
16574 // the distinction between "author explicitly declared
16575 // `:estrategia OneForOne`" and "author omitted the slot and
16576 // inherited the default" the future per-cluster strategy override
16577 // slot depends on). Peer of the sibling M3
16578 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
16579 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
16580 // axis — same "the substrate-primitive accessor must byte-equal
16581 // the raw field access verbatim across every author-declared
16582 // value" discipline extended onto the M2 supervisor-slot
16583 // per-`:supervisor` sibling-restart-strategy axis.
16584 for &estrategia in RestartStrategy::ALL {
16585 // `SimpleOneForOne` requires `children.is_empty()`; the peer
16586 // three strategies require a non-empty static children list.
16587 // Build each shape coherently so the pin's fixture would
16588 // itself pass [`SupervisorSpec::validate`] once fed through
16589 // the sibling coherence pin below — the byte-equal projection
16590 // asserted here is a strictly weaker property (a `Copy` field
16591 // read) that does not depend on `validate` running, but
16592 // keeping the fixture validate-clean means a future extension
16593 // of the pin to exercise `validate` end-to-end does not have
16594 // to re-author the children shape.
16595 //
16596 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
16597 // shape partition through the [`gen_platform::IsVariant`]
16598 // derive-generated
16599 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
16600 // than the raw `matches!(estrategia, RestartStrategy::
16601 // SimpleOneForOne)` open-coded pattern-match — same closed-
16602 // set-typed-enum arm-discriminator dispatch discipline the
16603 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
16604 // convergence (915a934) extended onto its two paired positive
16605 // / negated `matches!` sites and the peer
16606 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
16607 // predicate convergence (766ec63) extended onto the M3 mesh-
16608 // slot per-`:placement` distribution-strategy discriminator
16609 // axis. See the sibling `round_trip_all_strategies` and the
16610 // peer `manifest::tests::
16611 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
16612 // fixture for the two peer sites the same lift closes on.
16613 let children = if estrategia.is_simple_one_for_one() {
16614 Vec::new()
16615 } else {
16616 vec![ChildSpec {
16617 caixa: "worker".into(),
16618 versao: "^0.1".into(),
16619 restart: RestartPolicy::Permanent,
16620 }]
16621 };
16622 let s = SupervisorSpec {
16623 estrategia,
16624 children,
16625 ..SupervisorSpec::default()
16626 };
16627 assert_eq!(
16628 s.estrategia(),
16629 estrategia,
16630 "SupervisorSpec::estrategia must return :supervisor :estrategia \
16631 verbatim (got {:?}, expected {estrategia:?})",
16632 s.estrategia(),
16633 );
16634 assert_eq!(
16635 s.estrategia(),
16636 s.estrategia,
16637 "SupervisorSpec::estrategia accessor and .estrategia field \
16638 access must byte-equal — the accessor is the substrate-\
16639 primitive typed dispatch every downstream sibling-restart-\
16640 strategy consumer must route through",
16641 );
16642 }
16643 }
16644
16645 #[test]
16646 fn validate_reads_through_lifted_estrategia_accessor() {
16647 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
16648 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
16649 // dispatch (which reads through [`SupervisorSpec::estrategia`]
16650 // to fan across the strategy-arm shape-gate cascades) and the
16651 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
16652 // error carrier's `estrategia:` field (which reads through
16653 // [`SupervisorSpec::estrategia`] to name the strategy the empty
16654 // `:children` list was declared against) must both key off the
16655 // lifted accessor, so any future rebrand on the typed slot's
16656 // reader shape lands at exactly one place. Pins the two-site
16657 // coherence by exercising the `NoChildren` error surface end-to-
16658 // end across every non-`SimpleOneForOne` variant and asserting
16659 // the surfaced `estrategia:` field byte-equals the accessor's
16660 // return. Peer of the sibling M3
16661 // `validate_placement_reads_through_lifted_estrategia_accessor`
16662 // (921fe1b) three-consumer coherence pin on the per-`:placement`
16663 // distribution-strategy axis.
16664 for estrategia in [
16665 RestartStrategy::OneForOne,
16666 RestartStrategy::OneForAll,
16667 RestartStrategy::RestForOne,
16668 ] {
16669 let s = SupervisorSpec {
16670 estrategia,
16671 children: Vec::new(),
16672 ..SupervisorSpec::default()
16673 };
16674 let err = s.validate().unwrap_err();
16675 match err {
16676 SupervisorError::NoChildren { estrategia: e } => {
16677 assert_eq!(
16678 e,
16679 s.estrategia(),
16680 "NoChildren.estrategia must byte-equal \
16681 SupervisorSpec::estrategia() — the empty-`:children` \
16682 refusal reads through the lifted accessor",
16683 );
16684 assert_eq!(
16685 e, estrategia,
16686 "NoChildren.estrategia must carry the author-declared \
16687 :supervisor :estrategia variant verbatim (got {e:?}, \
16688 expected {estrategia:?})",
16689 );
16690 }
16691 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
16692 }
16693 }
16694 }
16695
16696 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
16697 //
16698 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
16699 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
16700 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
16701 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
16702 // The two pins below cover (1) the accessor's byte-equal projection
16703 // against the raw field access across every representative value in
16704 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
16705 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
16706 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
16707 // zero-floor / cap composition — the validate gate and the accessor
16708 // must route through the same substrate-primitive typed dispatch, so
16709 // any future silent detour that had the accessor perform a
16710 // bounds-collapsing clamp would fail here at caixa-core build time.
16711 // Peer of the sibling M3
16712 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
16713 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
16714
16715 #[test]
16716 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
16717 // The canonical per-`:supervisor` restart-budget-count scalar pin:
16718 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
16719 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
16720 // typed slot's own `u32` storage, byte-equal to the raw field
16721 // access across every representative value in the accept-set —
16722 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
16723 // accept-set the surrounding [`SupervisorSpec::validate`] gate
16724 // carves out on the sibling `ZeroMaxRestarts` refusal),
16725 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
16726 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
16727 // (a past-the-guard sentinel that pins the accessor doesn't
16728 // perform a silent bounds-collapse into `1` on the zero arm —
16729 // validate rejects zero but the accessor must ship the raw slot
16730 // verbatim so a validate-time gate regression surfaces at the
16731 // emit boundary rather than being silently absorbed), `u32::MAX`
16732 // (a past-the-guard sentinel that pins the accessor doesn't
16733 // perform a silent bounds-collapse through
16734 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
16735 //
16736 // Peer of the sibling M3
16737 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
16738 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
16739 // required-scalar axis — same "the substrate-primitive accessor
16740 // must byte-equal the raw field access verbatim across every
16741 // value in the `u32` accept-set" discipline extended onto the M2
16742 // supervisor-slot per-`:supervisor` restart-budget-count axis.
16743 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
16744 let s = SupervisorSpec {
16745 max_restarts,
16746 ..SupervisorSpec::default()
16747 };
16748 assert_eq!(
16749 s.max_restarts(),
16750 max_restarts,
16751 "SupervisorSpec::max_restarts must return :supervisor \
16752 :max-restarts verbatim (got {}, expected {max_restarts})",
16753 s.max_restarts(),
16754 );
16755 assert_eq!(
16756 s.max_restarts(),
16757 s.max_restarts,
16758 "SupervisorSpec::max_restarts accessor and .max_restarts \
16759 field access must byte-equal — the accessor is the \
16760 substrate-primitive typed dispatch every downstream \
16761 restart-budget-count consumer must route through",
16762 );
16763 }
16764 }
16765
16766 #[test]
16767 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
16768 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
16769 // zero-floor + upper-cap bracket must key off
16770 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
16771 // field access. Structurally: a `SupervisorSpec { max_restarts:
16772 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
16773 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
16774 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
16775 // (with the offending count carried verbatim from the accessor
16776 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
16777 // lower boundary of the accept-set) plus a `SupervisorSpec {
16778 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
16779 // boundary) must pass validate. The four together jointly pin the
16780 // accessor + validate-gate composition: any future silent detour
16781 // that had the accessor return a fresh `1` on the zero arm (a
16782 // `.max_restarts().max(1)` collapse) would silently absorb the
16783 // `ZeroMaxRestarts` refusal at the accessor boundary and the
16784 // validate gate would accept a struct-literal `SupervisorSpec {
16785 // max_restarts: 0, .. }` — the composition pin catches that at
16786 // caixa-core build time.
16787 //
16788 // Peer of the sibling M3
16789 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
16790 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
16791 // composition axis — same "the validate / shape-gate predicate
16792 // must route through the substrate-primitive typed dispatch"
16793 // discipline extended onto the peer M2 supervisor-slot
16794 // required-`u32` composition axis.
16795 let child = ChildSpec {
16796 caixa: "worker".into(),
16797 versao: "^0.1".into(),
16798 restart: RestartPolicy::Permanent,
16799 };
16800 // Zero-floor arm.
16801 let s = SupervisorSpec {
16802 max_restarts: 0,
16803 children: vec![child.clone()],
16804 ..SupervisorSpec::default()
16805 };
16806 assert_eq!(
16807 s.validate().unwrap_err(),
16808 SupervisorError::ZeroMaxRestarts,
16809 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
16810 — the accessor and the validate gate must route through the \
16811 same substrate-primitive typed dispatch on the zero-floor arm",
16812 );
16813 // Cap arm — the surfaced `max_restarts:` field must byte-equal
16814 // the accessor's return so a future rebrand on the accessor
16815 // lands in the diagnostic without a coordinated rewrite.
16816 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
16817 let s = SupervisorSpec {
16818 max_restarts: over_cap,
16819 children: vec![child.clone()],
16820 ..SupervisorSpec::default()
16821 };
16822 match s.validate().unwrap_err() {
16823 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
16824 assert_eq!(
16825 max_restarts,
16826 s.max_restarts(),
16827 "MaxRestartsExceedsCap.max_restarts must byte-equal \
16828 SupervisorSpec::max_restarts() — the cap-arm refusal \
16829 reads through the lifted accessor",
16830 );
16831 assert_eq!(
16832 max_restarts, over_cap,
16833 "MaxRestartsExceedsCap.max_restarts must carry the \
16834 author-declared :supervisor :max-restarts value \
16835 verbatim (got {max_restarts}, expected {over_cap})",
16836 );
16837 }
16838 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
16839 }
16840 // Lower + upper accept-set boundaries.
16841 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
16842 let s = SupervisorSpec {
16843 max_restarts,
16844 children: vec![child.clone()],
16845 ..SupervisorSpec::default()
16846 };
16847 assert!(
16848 s.validate().is_ok(),
16849 "validate must accept max_restarts == {max_restarts} \
16850 (an accept-set boundary of \
16851 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
16852 );
16853 }
16854 }
16855
16856 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
16857 //
16858 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
16859 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
16860 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
16861 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
16862 // supervisor-slot per-`:supervisor` restart-intensity-denominator
16863 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
16864 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
16865 // per-`:supervisor` scalar-value axis. The three pins below cover
16866 // (1) the accessor's byte-equal projection against the raw field
16867 // access across every representative value in the `Option<Duration>`
16868 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
16869 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
16870 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
16871 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
16872 // `if let Some(w) = self.restart_window() { … }` bracket-arm
16873 // composition — the validate gate and the accessor must route through
16874 // the same substrate-primitive typed dispatch, so any future silent
16875 // detour that had the accessor perform a bounds-collapsing clamp
16876 // would fail here at caixa-core build time, and (3) the accessor's
16877 // by-copy idempotence pin — the returned `Option<Duration>` must
16878 // outlive `&self` and two successive calls must return byte-equal
16879 // values. Peer of the sibling M2
16880 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
16881 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
16882 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
16883 // (7073d0f) pin on the per-`:politicas :timeout` axis.
16884
16885 #[test]
16886 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
16887 // The canonical per-`:supervisor` restart-intensity-denominator
16888 // scalar pin: [`SupervisorSpec::restart_window`] must return the
16889 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
16890 // `Option<Duration>`, `Copy`-projected from the typed slot's own
16891 // `Option<Duration>` storage, byte-equal to the raw field access
16892 // across every representative value in the accept-set — `None`
16893 // (the "never reset — every restart across the supervisor's
16894 // lifetime counts against the sibling `:max-restarts` budget"
16895 // sentinel the field's own docstring names and the peer
16896 // `validate_accepts_none_restart_window` pin locks in on the
16897 // [`SupervisorSpec::validate`] entry-side),
16898 // `Some(Duration::from_millis(1))` (the structural minimum a
16899 // validated `:restart-window` may carry, the integer-millisecond
16900 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
16901 // everything sub-ms; `Duration::ZERO` is separately rejected by
16902 // [`SupervisorError::RestartWindowZero`]),
16903 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
16904 // surrounding [`SupervisorSpec::validate`] gate carves out on the
16905 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
16906 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
16907 // accessor doesn't perform a silent bounds-collapse into `None` on
16908 // the zero-Duration arm — validate rejects zero but the accessor
16909 // must ship the raw slot verbatim so a validate-time gate
16910 // regression surfaces at the emit boundary rather than being
16911 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
16912 // sentinel that pins the accessor doesn't perform a silent
16913 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
16914 // return path).
16915 //
16916 // Peer of the sibling M2
16917 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
16918 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
16919 // sibling M3
16920 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
16921 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
16922 // substrate-primitive accessor must byte-equal the raw field
16923 // access verbatim across every value in the `Option<Duration>`
16924 // accept-set" discipline extended onto the M2 supervisor-slot
16925 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
16926 // silent detour that re-derived the restart-window from a peer
16927 // axis (an accidental `.max_restarts.into()` collapse that read
16928 // the restart-budget-count as a duration — the two axes serve
16929 // different halves of the `MaxIntensity / Period` restart-
16930 // intensity ratio, and confusing them silently inverts the
16931 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
16932 // "zero means never reset" collapse (the canonical
16933 // `Option<Duration>` → `Duration` collapse footgun the
16934 // [`SupervisorError::RestartWindowZero`] validate arm guards on
16935 // the peer zero-floor axis; a zero period either trips on the
16936 // first failure or never trips depending on operator
16937 // interpretation, neither of which is the author's "never reset"
16938 // intent that `None` expresses structurally), or a per-arm
16939 // variant swap that landed on one consumer without the other.
16940 for restart_window in [
16941 None,
16942 Some(Duration::from_millis(1)),
16943 Some(SUPERVISOR_RESTART_WINDOW_MAX),
16944 Some(Duration::ZERO),
16945 Some(Duration::MAX),
16946 ] {
16947 let s = SupervisorSpec {
16948 restart_window,
16949 ..SupervisorSpec::default()
16950 };
16951 assert_eq!(
16952 s.restart_window(),
16953 restart_window,
16954 "SupervisorSpec::restart_window must return :supervisor \
16955 :restart-window verbatim (got {:?}, expected {restart_window:?})",
16956 s.restart_window(),
16957 );
16958 assert_eq!(
16959 s.restart_window(),
16960 s.restart_window,
16961 "SupervisorSpec::restart_window accessor and \
16962 .restart_window field access must byte-equal — the \
16963 accessor is the substrate-primitive typed dispatch every \
16964 downstream restart-intensity-denominator consumer must \
16965 route through",
16966 );
16967 }
16968 }
16969
16970 #[test]
16971 fn validate_restart_window_bracket_arm_routes_through_accessor() {
16972 // Composition pin: [`SupervisorSpec::validate`]'s
16973 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
16974 // zero-floor + integer-millisecond canonical-form + upper-cap
16975 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
16976 // the raw `.restart_window` field access. Structurally: a
16977 // `SupervisorSpec { restart_window: None, .. }` must pass the
16978 // arm gate structurally (the `if let Some(_)` shape returns
16979 // early on the `None` arm — the accessor and the validate gate
16980 // must agree on `None → skip the bracket cascade` so an authored
16981 // `:restart-window ()` structurally routes through the "never
16982 // reset" sentinel path), a `SupervisorSpec { restart_window:
16983 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
16984 // refusal exactly, a `SupervisorSpec { restart_window:
16985 // Some(Duration::from_micros(1500)), .. }` must surface the
16986 // `RestartWindowNotCanonical` refusal exactly (with the offending
16987 // duration carried verbatim from the accessor return), a
16988 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
16989 // + Duration::from_millis(1)), .. }` must surface the
16990 // `RestartWindowExceedsCap` refusal exactly (with the offending
16991 // duration carried verbatim from the accessor return), and a
16992 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
16993 // .. }` (the lower boundary of the accept-set) plus a
16994 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
16995 // .. }` (the upper boundary) must pass validate. The six together
16996 // jointly pin the accessor + validate-gate composition: any future
16997 // silent detour that had the accessor return a fresh `None` on any
16998 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
16999 // collapse) would silently absorb the `RestartWindowZero` refusal
17000 // at the accessor boundary and the validate gate would accept a
17001 // struct-literal `SupervisorSpec { restart_window:
17002 // Some(Duration::ZERO), .. }` — the composition pin catches that
17003 // at caixa-core build time.
17004 //
17005 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
17006 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
17007 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
17008 // accessor-composition pin on the per-`:politicas :timeout` axis —
17009 // same "the validate / shape-gate predicate must route through
17010 // the substrate-primitive typed dispatch" discipline extended
17011 // onto the peer M2 supervisor-slot optional-`Duration` axis.
17012 let child = ChildSpec {
17013 caixa: "worker".into(),
17014 versao: "^0.1".into(),
17015 restart: RestartPolicy::Permanent,
17016 };
17017 // None arm — must not surface any :restart-window-shaped refusal;
17018 // the `if let Some(_)` bracket returns early on `None` structurally.
17019 let s = SupervisorSpec {
17020 restart_window: None,
17021 children: vec![child.clone()],
17022 ..SupervisorSpec::default()
17023 };
17024 assert!(
17025 s.validate().is_ok(),
17026 "validate must accept restart_window: None (the never-reset \
17027 sentinel) — the `if let Some(_)` bracket returns early on \
17028 the None arm and the accessor must agree",
17029 );
17030 // Zero-floor arm.
17031 let s = SupervisorSpec {
17032 restart_window: Some(Duration::ZERO),
17033 children: vec![child.clone()],
17034 ..SupervisorSpec::default()
17035 };
17036 assert_eq!(
17037 s.validate().unwrap_err(),
17038 SupervisorError::RestartWindowZero,
17039 "validate must reject restart_window == Some(Duration::ZERO) \
17040 with RestartWindowZero — the accessor and the validate gate \
17041 must route through the same substrate-primitive typed \
17042 dispatch on the zero-floor arm",
17043 );
17044 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
17045 // byte-equal the accessor's return so a future rebrand on the
17046 // accessor lands in the diagnostic without a coordinated rewrite.
17047 let sub_ms = Duration::from_micros(1500);
17048 let s = SupervisorSpec {
17049 restart_window: Some(sub_ms),
17050 children: vec![child.clone()],
17051 ..SupervisorSpec::default()
17052 };
17053 match s.validate().unwrap_err() {
17054 SupervisorError::RestartWindowNotCanonical { window } => {
17055 assert_eq!(
17056 Some(window),
17057 s.restart_window(),
17058 "RestartWindowNotCanonical.window must byte-equal \
17059 SupervisorSpec::restart_window().unwrap() — the \
17060 non-canonical-arm refusal reads through the lifted \
17061 accessor",
17062 );
17063 assert_eq!(
17064 window, sub_ms,
17065 "RestartWindowNotCanonical.window must carry the \
17066 author-declared :supervisor :restart-window value \
17067 verbatim (got {window:?}, expected {sub_ms:?})",
17068 );
17069 }
17070 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
17071 }
17072 // Cap arm — the surfaced `window:` field must byte-equal the
17073 // accessor's return.
17074 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
17075 let s = SupervisorSpec {
17076 restart_window: Some(over_cap),
17077 children: vec![child.clone()],
17078 ..SupervisorSpec::default()
17079 };
17080 match s.validate().unwrap_err() {
17081 SupervisorError::RestartWindowExceedsCap { window } => {
17082 assert_eq!(
17083 Some(window),
17084 s.restart_window(),
17085 "RestartWindowExceedsCap.window must byte-equal \
17086 SupervisorSpec::restart_window().unwrap() — the \
17087 cap-arm refusal reads through the lifted accessor",
17088 );
17089 assert_eq!(
17090 window, over_cap,
17091 "RestartWindowExceedsCap.window must carry the \
17092 author-declared :supervisor :restart-window value \
17093 verbatim (got {window:?}, expected {over_cap:?})",
17094 );
17095 }
17096 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
17097 }
17098 // Lower + upper accept-set boundaries.
17099 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
17100 let s = SupervisorSpec {
17101 restart_window: Some(restart_window),
17102 children: vec![child.clone()],
17103 ..SupervisorSpec::default()
17104 };
17105 assert!(
17106 s.validate().is_ok(),
17107 "validate must accept restart_window == Some({restart_window:?}) \
17108 (an accept-set boundary of \
17109 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
17110 );
17111 }
17112 }
17113
17114 #[test]
17115 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
17116 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
17117 // `Option<Duration>` by copy — `Duration` is `Copy` (so
17118 // `Option<Duration>` is `Copy`) and the accessor must return by
17119 // value, not by reference. Peer of the sibling M2
17120 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
17121 // per-`:limits :wall-clock` axis and the sibling M3
17122 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
17123 // per-`:politicas :timeout` axis, extended onto the peer M2
17124 // supervisor-slot `Option<Duration>` copy-invariant shape — the
17125 // accessor's returned `Option<Duration>` must outlive `&self`
17126 // (multiple calls must return equal values from a dropped-`&self`
17127 // copy, since the returned Option carries no borrow), and calling
17128 // the accessor twice on the same SupervisorSpec must yield the
17129 // same `Option<Duration>` verbatim (idempotent, no side effects
17130 // on `&self`).
17131 //
17132 // Pins against a future silent detour that returned
17133 // `Option<&Duration>` (which would type-check but silently break
17134 // every downstream caller — the future wasm-operator's
17135 // per-supervisor restart-intensity counter consumes `Duration` by
17136 // value and `&Duration` would fold to a detached copy at the call
17137 // site), an accidental `Option::as_ref()` projection
17138 // (`self.restart_window.as_ref()` would also type-check but
17139 // return `Option<&Duration>`), or a one-arm-only accessor that
17140 // reads `Some(*w)` in the Some arm but reads a fresh
17141 // `Default::default()` (which would collapse to `Duration::ZERO`,
17142 // not `None`) in the None arm — a footgun the
17143 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
17144 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
17145 // requires `Period > 0` and `None` structurally expresses "never
17146 // reset" instead.
17147 for restart_window in [
17148 None,
17149 Some(Duration::from_millis(1)),
17150 Some(Duration::from_secs(60)),
17151 Some(SUPERVISOR_RESTART_WINDOW_MAX),
17152 ] {
17153 let s = SupervisorSpec {
17154 restart_window,
17155 ..SupervisorSpec::default()
17156 };
17157 let first = s.restart_window();
17158 let second = s.restart_window();
17159 assert_eq!(
17160 first, second,
17161 "SupervisorSpec::restart_window must be idempotent — two \
17162 successive calls on the same &self must return the \
17163 same Option<Duration>",
17164 );
17165 assert_eq!(
17166 first, restart_window,
17167 "SupervisorSpec::restart_window must return :supervisor \
17168 :restart-window verbatim by copy — got {first:?}, \
17169 expected {restart_window:?}",
17170 );
17171 }
17172 }
17173
17174 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
17175 //
17176 // The [`SupervisorSpec::children`] accessor lift is the seed of the
17177 // slice-return (`&[T]`) accessor discipline on the substrate — the four
17178 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
17179 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
17180 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
17181 // access at the time of this seed, and inherit this pin family's
17182 // discipline as future compounding runs migrate their consumers. The
17183 // three pins below cover (1) the accessor's byte-equal projection
17184 // against the raw field access across the empty / singleton / cohort
17185 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
17186 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
17187 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
17188 // consumer routing through the accessor on both arms, and (3) the
17189 // per-child validate loop's traversal reading the same slice-view the
17190 // accessor projects. Peer of the sibling M2
17191 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
17192 // two-consumer coherence pin on the per-`:supervisor`
17193 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
17194 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
17195
17196 #[test]
17197 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
17198 // The canonical per-`:supervisor` static-child-list scalar-shape
17199 // pin: [`SupervisorSpec::children`] must return the `:supervisor
17200 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
17201 // slice-view over the same backing buffer the raw
17202 // `self.children.as_slice()` field access borrows from, byte-
17203 // equal across every representative fixture in the accept-set —
17204 // the empty slice (the `SimpleOneForOne`-arm sentinel),
17205 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
17206 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
17207 // with the peer three restart-policy variants in play).
17208 //
17209 // Pins against a future silent detour that returned
17210 // `&Vec<ChildSpec>` (which would type-check but leak the
17211 // storage-side `Vec`'s grow/push/reserve surface no consumer of
17212 // the typed view reaches for), a fresh-allocated
17213 // `Vec<ChildSpec>` copy (which would type-check via a coercion
17214 // but silently break every downstream caller that relied on the
17215 // slice sharing the backing buffer's identity), or an
17216 // out-of-order or length-drifted projection (which would silently
17217 // split the per-child validate loop's traversal input from the
17218 // paired partition-dispatch `.is_empty()` probe's input).
17219 //
17220 // Peer of the sibling
17221 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
17222 // (eafb619) `Copy`-composite-enum byte-equal pin on the
17223 // per-`:supervisor` sibling-restart-strategy axis, extended onto
17224 // the per-`:supervisor` static-child-list `Vec`-carry axis.
17225 let fixtures: Vec<Vec<ChildSpec>> = vec![
17226 Vec::new(),
17227 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
17228 vec![
17229 child("worker", "^0.1", RestartPolicy::Permanent),
17230 child("cache-server", "^0.1", RestartPolicy::Transient),
17231 ],
17232 vec![
17233 child("worker", "^0.1", RestartPolicy::Permanent),
17234 child("cache-server", "^0.1", RestartPolicy::Transient),
17235 child("scratch-job", "^0.1", RestartPolicy::Temporary),
17236 ],
17237 ];
17238 for children in fixtures {
17239 let s = SupervisorSpec {
17240 children: children.clone(),
17241 ..SupervisorSpec::default()
17242 };
17243 assert_eq!(
17244 s.children(),
17245 children.as_slice(),
17246 "SupervisorSpec::children must return :supervisor \
17247 :children verbatim (got {:?}, expected {:?})",
17248 s.children(),
17249 children.as_slice(),
17250 );
17251 assert_eq!(
17252 s.children(),
17253 s.children.as_slice(),
17254 "SupervisorSpec::children accessor and \
17255 .children.as_slice() field access must byte-equal — \
17256 the accessor is the substrate-primitive typed \
17257 dispatch every downstream static-child-list consumer \
17258 must route through",
17259 );
17260 assert_eq!(
17261 s.children().len(),
17262 s.children.len(),
17263 "SupervisorSpec::children().len() must byte-equal \
17264 self.children.len() — a length-drift would silently \
17265 split the paired partition-dispatch `.is_empty()` \
17266 probe input from the per-child validate loop's \
17267 traversal input",
17268 );
17269 }
17270 }
17271
17272 #[test]
17273 fn validate_reads_through_lifted_children_accessor() {
17274 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
17275 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
17276 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
17277 // when the accessor projects a non-empty slice under a
17278 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
17279 // `self.children().is_empty()` refusal probe (which must trip
17280 // [`SupervisorError::NoChildren`] when the accessor projects the
17281 // empty slice under any peer estrategia), and the per-child
17282 // validate loop's `for child in self.children()` traversal
17283 // (which must reach every entry in the same order the accessor
17284 // projects) must all key off the lifted accessor, so any future
17285 // rebrand on the typed slot's reader shape lands at exactly one
17286 // place. Pins the three-site coherence by exercising each
17287 // production consumer end-to-end: (1) the
17288 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
17289 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
17290 // refusal under the empty slice + non-`SimpleOneForOne`
17291 // estrategia across every peer variant, and (3) the per-child
17292 // duplicate-detection surface fires on the second entry of a
17293 // two-child cohort that shares a `:caixa` name (which requires
17294 // the loop to reach both entries — a first-entry-only projection
17295 // would silently pass since the dedup HashSet has room for the
17296 // first insert).
17297 //
17298 // Peer of the sibling M2
17299 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
17300 // two-consumer coherence pin on the per-`:supervisor`
17301 // sibling-restart-strategy axis, extended onto the
17302 // per-`:supervisor` static-child-list `Vec`-carry axis.
17303
17304 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
17305 // `SimpleOneForOne` estrategia must trip
17306 // `SimpleOneForOneWithStaticChildren`.
17307 let s = SupervisorSpec {
17308 estrategia: RestartStrategy::SimpleOneForOne,
17309 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
17310 ..SupervisorSpec::default()
17311 };
17312 assert_eq!(
17313 s.validate().unwrap_err(),
17314 SupervisorError::SimpleOneForOneWithStaticChildren,
17315 "SimpleOneForOne + non-empty children must trip \
17316 SimpleOneForOneWithStaticChildren — the accessor projects \
17317 a non-empty slice, and the SimpleOneForOne-arm refusal \
17318 probe reads through the lifted accessor",
17319 );
17320 assert!(
17321 !s.children().is_empty(),
17322 "the SimpleOneForOne-arm refusal input must be a non-empty \
17323 slice per the accessor's projection",
17324 );
17325
17326 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
17327 // under any peer estrategia must trip `NoChildren`.
17328 for estrategia in [
17329 RestartStrategy::OneForOne,
17330 RestartStrategy::OneForAll,
17331 RestartStrategy::RestForOne,
17332 ] {
17333 let s = SupervisorSpec {
17334 estrategia,
17335 children: Vec::new(),
17336 ..SupervisorSpec::default()
17337 };
17338 match s.validate().unwrap_err() {
17339 SupervisorError::NoChildren { estrategia: e } => {
17340 assert_eq!(
17341 e, estrategia,
17342 "NoChildren.estrategia must carry the author-\
17343 declared :supervisor :estrategia variant \
17344 verbatim (got {e:?}, expected {estrategia:?})",
17345 );
17346 }
17347 other => panic!(
17348 "expected NoChildren, got {other:?} for \
17349 estrategia={estrategia:?}"
17350 ),
17351 }
17352 assert!(
17353 s.children().is_empty(),
17354 "the non-SimpleOneForOne-arm refusal input must be the \
17355 empty slice per the accessor's projection",
17356 );
17357 }
17358
17359 // (3) Per-child validate loop: a two-child cohort that shares a
17360 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
17361 // reach both entries through the accessor.
17362 let s = SupervisorSpec {
17363 estrategia: RestartStrategy::OneForOne,
17364 children: vec![
17365 child("worker", "^0.1", RestartPolicy::Permanent),
17366 child("worker", "^0.2", RestartPolicy::Transient),
17367 ],
17368 ..SupervisorSpec::default()
17369 };
17370 match s.validate().unwrap_err() {
17371 SupervisorError::DuplicateChildCaixa { caixa } => {
17372 assert_eq!(
17373 caixa, "worker",
17374 "DuplicateChildCaixa.caixa must carry the shared \
17375 child `:caixa` name verbatim",
17376 );
17377 }
17378 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
17379 }
17380 assert_eq!(
17381 s.children().len(),
17382 2,
17383 "the per-child validate loop's traversal input must be a \
17384 two-element slice per the accessor's projection",
17385 );
17386 }
17387
17388 // Shared helper for the M2 per-`:children` per-slot-gate ≡
17389 // `validate` equivalence pins: builds an `OneForOne`-estrategia
17390 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
17391 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
17392 // bracket all pass cleanly so the sole failing surface is the
17393 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
17394 // pins the two-altitude equivalence on the paired probe.
17395 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
17396 let s = SupervisorSpec {
17397 estrategia: RestartStrategy::OneForOne,
17398 children,
17399 ..SupervisorSpec::default()
17400 };
17401 let via_gate = s.validate_children().unwrap_err();
17402 let via_validate = s.validate().unwrap_err();
17403 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
17404 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
17405 assert_eq!(
17406 via_gate, via_validate,
17407 "per-slot gate ≡ validate() must discriminate the same \
17408 refusal shape",
17409 );
17410 }
17411
17412 #[test]
17413 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
17414 // Fail-before-pass-after equivalence pin on the M2
17415 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
17416 // convergence — sibling of the M3 mesh-slot
17417 // `validate_membros_*` / `validate_contratos_*` /
17418 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
17419 // peer per-entry axes. Sweeps four of the five refusal shapes
17420 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
17421 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
17422 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
17423 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
17424 // duplicate-`:caixa` fan-out. Companion pin
17425 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
17426 // covers `ChildVersaoInvalid` (whose parser-owned reason string
17427 // needs pattern-matching, not equality) and the clean-pass
17428 // canonical fixture; together the two pins guarantee the
17429 // per-slot gate and `validate` discriminate the same set on
17430 // every per-child-covered input.
17431 assert_validate_children_matches_gate(
17432 vec![child("", "^0.1", RestartPolicy::Permanent)],
17433 &SupervisorError::EmptyChildName,
17434 );
17435 assert_validate_children_matches_gate(
17436 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
17437 &SupervisorError::ChildCaixaInvalid {
17438 caixa: "Worker".into(),
17439 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
17440 },
17441 );
17442 assert_validate_children_matches_gate(
17443 vec![child("worker", "", RestartPolicy::Permanent)],
17444 &SupervisorError::EmptyChildVersion {
17445 caixa: "worker".into(),
17446 },
17447 );
17448 assert_validate_children_matches_gate(
17449 vec![
17450 child("worker", "^0.1", RestartPolicy::Permanent),
17451 child("worker", "^0.2", RestartPolicy::Transient),
17452 ],
17453 &SupervisorError::DuplicateChildCaixa {
17454 caixa: "worker".into(),
17455 },
17456 );
17457 }
17458
17459 #[test]
17460 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
17461 // Second half of the two-altitude equivalence pin — covers the
17462 // one refusal shape whose reason string is parser-owned
17463 // (`ChildVersaoInvalid`, whose reason comes from the shared
17464 // [`crate::version::parse_requirement`] impl and may drift) and
17465 // the clean-pass canonical fixture. Sibling pin
17466 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
17467 // covers the four equality-comparable refusal shapes.
17468 let s_bad_versao = SupervisorSpec {
17469 estrategia: RestartStrategy::OneForOne,
17470 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
17471 ..SupervisorSpec::default()
17472 };
17473 let via_gate = s_bad_versao.validate_children().unwrap_err();
17474 let via_validate = s_bad_versao.validate().unwrap_err();
17475 match (&via_gate, &via_validate) {
17476 (
17477 SupervisorError::ChildVersaoInvalid {
17478 caixa: cg,
17479 versao: vg,
17480 ..
17481 },
17482 SupervisorError::ChildVersaoInvalid {
17483 caixa: cv,
17484 versao: vv,
17485 ..
17486 },
17487 ) => {
17488 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
17489 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
17490 assert_eq!(cv, "worker", "validate() :caixa carrier");
17491 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
17492 }
17493 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
17494 }
17495 assert_eq!(
17496 via_gate, via_validate,
17497 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
17498 );
17499
17500 let s_ok = SupervisorSpec {
17501 estrategia: RestartStrategy::OneForOne,
17502 children: vec![
17503 child("worker-a", "^0.1", RestartPolicy::Permanent),
17504 child("worker-b", "~0.2.3", RestartPolicy::Transient),
17505 child("collector", "*", RestartPolicy::Temporary),
17506 ],
17507 ..SupervisorSpec::default()
17508 };
17509 s_ok.validate_children()
17510 .expect("per-slot gate must accept the clean-pass fixture");
17511 s_ok.validate()
17512 .expect("validate() must accept the clean-pass fixture");
17513 }
17514
17515 #[test]
17516 fn validate_children_is_self_contained_on_children_slot() {
17517 // Self-containment pin: [`SupervisorSpec::validate_children`]
17518 // resolves the per-child cascade against `&self` alone, without
17519 // depending on the peer `:estrategia`/`:max-restarts`/
17520 // `:restart-window` gates having run first — same posture the M3
17521 // peer per-slot gates carry (`validate_membros`,
17522 // `validate_contratos`, `validate_entrada`, `validate_placement`,
17523 // routing through their own oracles rather than borrowing state
17524 // threaded down from `validate`). A future consumer that reaches
17525 // the per-slot gate directly on a spec whose peer slots would
17526 // fail `validate` still surfaces the per-child refusal, not the
17527 // peer refusal.
17528 //
17529 // Construct a spec whose `:max-restarts` is `0` (which would
17530 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
17531 // the partition-dispatch) and whose `:children` carries a
17532 // `DuplicateChildCaixa` shape: the per-slot gate called directly
17533 // must surface `DuplicateChildCaixa`, proving it does not depend
17534 // on the peer `:max-restarts` gate running first.
17535 let s = SupervisorSpec {
17536 estrategia: RestartStrategy::OneForOne,
17537 max_restarts: 0,
17538 restart_window: Some(Duration::from_secs(60)),
17539 children: vec![
17540 child("worker", "^0.1", RestartPolicy::Permanent),
17541 child("worker", "^0.2", RestartPolicy::Transient),
17542 ],
17543 };
17544 assert_eq!(
17545 s.validate_children().unwrap_err(),
17546 SupervisorError::DuplicateChildCaixa {
17547 caixa: "worker".into(),
17548 },
17549 "per-slot gate must resolve per-child refusal directly against \
17550 `&self` — a dependency on the peer `:max-restarts` gate \
17551 running first would surface ZeroMaxRestarts here instead",
17552 );
17553 // The peer gate is still the surface `validate` reaches — pin
17554 // the ordering to establish that `validate_children` truly runs
17555 // last in `validate`'s dispatch, so a direct call bypasses the
17556 // peer gates on any spec whose per-child cascade would fail.
17557 assert_eq!(
17558 s.validate().unwrap_err(),
17559 SupervisorError::ZeroMaxRestarts,
17560 "validate() must surface the peer `:max-restarts` gate before \
17561 reaching the per-child cascade — this pins the dispatch \
17562 ordering the per-slot gate's self-containment complements",
17563 );
17564 }
17565
17566 #[test]
17567 fn child_spec_restart_accessor_is_const_fn() {
17568 // The [`ChildSpec::restart`] per-`:children` restart-decision-
17569 // policy `Copy`-return scalar accessor is declared
17570 // `#[must_use] pub const fn` — matching the sibling M2
17571 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
17572 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
17573 // both converted in this commit), the sibling M2
17574 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
17575 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
17576 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
17577 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
17578 // `Copy`-return `pub const fn` scalar accessors on the sibling
17579 // M3 surface. Pin the `const`-eval posture here so a future
17580 // accidental downgrade to non-`const` (an added runtime helper
17581 // reachable only from a non-`const` context, an
17582 // `Option<RestartPolicy>`-shape migration on the per-child
17583 // restart-decision axis once heterogeneous per-cluster
17584 // restart-policy overlays land that would silently drop the
17585 // `const` qualifier, a manual hand-rolled shadow) trips at
17586 // caixa-core build time rather than surfacing as a downstream
17587 // `const`-context regression far from the declaration.
17588 //
17589 // Same shape as the sibling M3
17590 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
17591 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
17592 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
17593 // accessor axis — the load-bearing witness lives in the
17594 // module-scope `const fn` wrapper `restart_via_const_fn` below:
17595 // a body that calls [`ChildSpec::restart`] under a `const fn`
17596 // signature is well-formed only when the callee is itself
17597 // `const fn`, so any future accidental downgrade of
17598 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
17599 // build time (const-eval E0015 `cannot call non-const method`),
17600 // strictly stronger than a runtime `assert!(CONST)` and
17601 // side-stepping the destructor-in-const restriction that
17602 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
17603 // items on `ChildSpec`'s `String` carriers.
17604 //
17605 // The runtime body sweeps every closed-set [`RestartPolicy`]
17606 // arm and asserts the wrapped and direct dispatches agree.
17607 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
17608 c.restart()
17609 }
17610 for restart in [
17611 RestartPolicy::Permanent,
17612 RestartPolicy::Transient,
17613 RestartPolicy::Temporary,
17614 ] {
17615 let c = ChildSpec {
17616 caixa: "worker".into(),
17617 versao: "^0.1".into(),
17618 restart,
17619 };
17620 assert_eq!(
17621 restart_via_const_fn(&c),
17622 c.restart(),
17623 "const-fn-wrapped and direct dispatch on \
17624 ChildSpec::restart must agree for {restart:?}",
17625 );
17626 assert_eq!(
17627 c.restart(),
17628 restart,
17629 "ChildSpec::restart must return the storage-side \
17630 RestartPolicy verbatim for {restart:?} (a violation \
17631 means the accessor stopped being a raw field-return \
17632 copy)",
17633 );
17634 }
17635 }
17636
17637 #[test]
17638 fn supervisor_spec_estrategia_accessor_is_const_fn() {
17639 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
17640 // sibling-restart-strategy `Copy`-return scalar accessor is
17641 // declared `#[must_use] pub const fn` — matching the sibling M2
17642 // per-`:children` [`ChildSpec::restart`] (pinned by
17643 // [`child_spec_restart_accessor_is_const_fn`] above, both
17644 // converted in this commit), the sibling M2 per-`:supervisor`
17645 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
17646 // accessor already `pub const fn`, and mirroring the peer M3
17647 // mesh-slot per-`:placement`
17648 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
17649 // `pub const fn` scalar accessor whose method-name discipline
17650 // the [`SupervisorSpec::estrategia`] method was authored to
17651 // match. Pin the `const`-eval posture here so a future
17652 // accidental downgrade to non-`const` (an added runtime helper
17653 // reachable only from a non-`const` context, an
17654 // `Option<RestartStrategy>`-shape migration once the substrate
17655 // grows per-cluster strategy overlays that would silently drop
17656 // the `const` qualifier, a manual hand-rolled shadow) trips at
17657 // caixa-core build time rather than surfacing as a downstream
17658 // `const`-context regression far from the declaration.
17659 //
17660 // Same shape as the sibling
17661 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
17662 // load-bearing witness lives in the module-scope `const fn`
17663 // wrapper `estrategia_via_const_fn` below: a body that calls
17664 // [`SupervisorSpec::estrategia`] under a `const fn` signature
17665 // is well-formed only when the callee is itself `const fn`,
17666 // side-stepping the destructor-in-const restriction that would
17667 // otherwise block a direct
17668 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
17669 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
17670 // carriers.
17671 //
17672 // The runtime body sweeps every closed-set [`RestartStrategy`]
17673 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
17674 // direct dispatches agree.
17675 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
17676 s.estrategia()
17677 }
17678 for &estrategia in RestartStrategy::ALL {
17679 let s = SupervisorSpec {
17680 estrategia,
17681 max_restarts: 5,
17682 restart_window: Some(Duration::from_secs(60)),
17683 children: Vec::new(),
17684 };
17685 assert_eq!(
17686 estrategia_via_const_fn(&s),
17687 s.estrategia(),
17688 "const-fn-wrapped and direct dispatch on \
17689 SupervisorSpec::estrategia must agree for {estrategia:?}",
17690 );
17691 assert_eq!(
17692 s.estrategia(),
17693 estrategia,
17694 "SupervisorSpec::estrategia must return the storage-side \
17695 RestartStrategy verbatim for {estrategia:?} (a violation \
17696 means the accessor stopped being a raw field-return \
17697 copy)",
17698 );
17699 }
17700 }
17701
17702 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
17703 // macro definition (see the paired doc-block above the macro
17704 // definition) — every generated `<ctor>(caixa: &str) -> Self`
17705 // constructor folds the uniform `Self::<Variant> { caixa:
17706 // caixa.to_string() }` one-field struct-literal onto one substrate
17707 // primitive. The three per-variant equivalence pins below
17708 // (fail-before-pass-after by construction — a byte-mismatched macro
17709 // arm would trip its equivalence pin first) lock each generated
17710 // constructor to its struct-literal peer under `PartialEq`, so
17711 // every wire-up in [`SupervisorSpec::validate_children`] and
17712 // [`validate_no_self_supervision`] on that variant produces a
17713 // byte-equal `SupervisorError` to the pre-lift open-coded
17714 // struct-literal. The cross-axis pin that follows (non-default
17715 // caixa name) routes the sole constructor input axis through
17716 // `.to_string()`, so the fold does not silently collapse onto a
17717 // fixed name.
17718 //
17719 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
17720 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
17721 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
17722 // `missing_entry_ctor_matches_struct_literal_wrap` /
17723 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
17724 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
17725 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
17726 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
17727 // on the six sibling ctor families the recent trajectory closed
17728 // on the peer `LayoutError` / `AplicacaoError` envelopes.
17729
17730 #[test]
17731 fn empty_child_version_ctor_matches_struct_literal_wrap() {
17732 assert_eq!(
17733 SupervisorError::empty_child_version("worker"),
17734 SupervisorError::EmptyChildVersion {
17735 caixa: "worker".to_string(),
17736 },
17737 "generated empty_child_version ctor must produce byte-equal \
17738 SupervisorError to the open-coded struct-literal wrap on the \
17739 same &str fixture",
17740 );
17741 }
17742
17743 #[test]
17744 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
17745 assert_eq!(
17746 SupervisorError::duplicate_child_caixa("worker"),
17747 SupervisorError::DuplicateChildCaixa {
17748 caixa: "worker".to_string(),
17749 },
17750 "generated duplicate_child_caixa ctor must produce byte-equal \
17751 SupervisorError to the open-coded struct-literal wrap on the \
17752 same &str fixture",
17753 );
17754 }
17755
17756 #[test]
17757 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
17758 assert_eq!(
17759 SupervisorError::child_supervises_self("orquestra"),
17760 SupervisorError::ChildSupervisesSelf {
17761 caixa: "orquestra".to_string(),
17762 },
17763 "generated child_supervises_self ctor must produce byte-equal \
17764 SupervisorError to the open-coded struct-literal wrap on the \
17765 same &str fixture",
17766 );
17767 }
17768
17769 // Per-variant equivalence pins for the two lifted
17770 // [`SupervisorError::child_caixa_invalid`] /
17771 // [`SupervisorError::child_versao_invalid`] inherent constructors
17772 // (fail-before-pass-after by construction — a byte-mismatched ctor body
17773 // would trip its equivalence pin first). Each pins the ctor output to
17774 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
17775 // in [`SupervisorSpec::validate_children`] on the two variants
17776 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
17777 // struct-literal on the same scalar fixtures. Peers of the sibling
17778 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
17779 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
17780 // the peer `AplicacaoError` envelope's
17781 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
17782
17783 #[test]
17784 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
17785 let caixa = "Worker";
17786 let reason = "sample reason text";
17787 assert_eq!(
17788 SupervisorError::child_caixa_invalid(caixa, reason),
17789 SupervisorError::ChildCaixaInvalid {
17790 caixa: caixa.to_string(),
17791 reason: reason.to_string(),
17792 },
17793 "lifted child_caixa_invalid ctor must produce byte-equal \
17794 SupervisorError to the open-coded struct-literal wrap on the \
17795 same (&str, reason) fixture",
17796 );
17797 }
17798
17799 #[test]
17800 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
17801 let caixa = "worker";
17802 let versao = "not-a-req";
17803 let reason = "sample reason text";
17804 assert_eq!(
17805 SupervisorError::child_versao_invalid(caixa, versao, reason),
17806 SupervisorError::ChildVersaoInvalid {
17807 caixa: caixa.to_string(),
17808 versao: versao.to_string(),
17809 reason: reason.to_string(),
17810 },
17811 "lifted child_versao_invalid ctor must produce byte-equal \
17812 SupervisorError to the open-coded struct-literal wrap on the \
17813 same (&str, &str, reason) fixture",
17814 );
17815 }
17816
17817 #[test]
17818 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
17819 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
17820 // against a `&str`-literal vs. `format!(…)` reason input to pin
17821 // both constructors accept the `impl Into<String>` bound
17822 // uniformly, so neither wire-up site drifts under a per-arm
17823 // wrapper transformation on the caller-side `reason` axis. Peer
17824 // of the sibling
17825 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
17826 // sweep on the peer `AplicacaoError` envelope.
17827 let via_literal = "literal reason text";
17828 let via_format = format!("{} reason text", "literal");
17829 assert_eq!(
17830 SupervisorError::child_caixa_invalid("Worker", via_literal),
17831 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
17832 );
17833 assert_eq!(
17834 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
17835 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
17836 );
17837 }
17838
17839 #[test]
17840 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
17841 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
17842 // &str`) through a non-default fixture name against every
17843 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
17844 // so any wrapper-side lowercase / trim / truncate / re-order on
17845 // the `caixa.to_string()` sole-field construction surfaces
17846 // here rather than at a downstream diagnostic-shape mismatch.
17847 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
17848 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
17849 // through_to_string` / `contrato_target_ctors_route_edge_
17850 // triple_through_verbatim` / `contrato_empty_pair_ctors_
17851 // route_edge_pair_through_verbatim` cross-axis routing pins on
17852 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
17853 // here onto the `SupervisorError` `{ caixa: String }` envelope
17854 // so every substrate-primitive ctor family in caixa-core
17855 // guarantees the sole-field construction routes the caller's
17856 // `&str` through `.to_string()` verbatim.
17857 let name = "cache-v2";
17858 assert_eq!(
17859 SupervisorError::empty_child_version(name),
17860 SupervisorError::EmptyChildVersion {
17861 caixa: name.to_string(),
17862 },
17863 );
17864 assert_eq!(
17865 SupervisorError::duplicate_child_caixa(name),
17866 SupervisorError::DuplicateChildCaixa {
17867 caixa: name.to_string(),
17868 },
17869 );
17870 assert_eq!(
17871 SupervisorError::child_supervises_self(name),
17872 SupervisorError::ChildSupervisesSelf {
17873 caixa: name.to_string(),
17874 },
17875 );
17876 }
17877
17878 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
17879 //
17880 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
17881 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
17882 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
17883 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
17884 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
17885 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
17886 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
17887 // / silent constant-substitution on any one variant surfaces here rather
17888 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
17889 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
17890 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
17891 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
17892 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
17893 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
17894 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
17895 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
17896 #[test]
17897 fn no_children_ctor_matches_struct_literal_wrap() {
17898 let estrategia = RestartStrategy::OneForAll;
17899 assert_eq!(
17900 SupervisorError::no_children(estrategia),
17901 SupervisorError::NoChildren { estrategia },
17902 "generated no_children ctor must produce byte-equal \
17903 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
17904 on the same `Copy`-`RestartStrategy` fixture",
17905 );
17906 }
17907
17908 #[test]
17909 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
17910 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
17911 assert_eq!(
17912 SupervisorError::max_restarts_exceeds_cap(max_restarts),
17913 SupervisorError::MaxRestartsExceedsCap { max_restarts },
17914 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
17915 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
17916 struct-literal wrap on the same `Copy`-`u32` fixture",
17917 );
17918 }
17919
17920 #[test]
17921 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
17922 let window = Duration::from_micros(1_500);
17923 assert_eq!(
17924 SupervisorError::restart_window_not_canonical(window),
17925 SupervisorError::RestartWindowNotCanonical { window },
17926 "generated restart_window_not_canonical ctor must produce \
17927 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
17928 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
17929 );
17930 }
17931
17932 #[test]
17933 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
17934 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
17935 assert_eq!(
17936 SupervisorError::restart_window_exceeds_cap(window),
17937 SupervisorError::RestartWindowExceedsCap { window },
17938 "generated restart_window_exceeds_cap ctor must produce \
17939 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
17940 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
17941 );
17942 }
17943
17944 #[test]
17945 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
17946 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
17947 // constructor input axis through a non-default `Copy` fixture against
17948 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
17949 // side silent `.into()` / silent constant-substitution / silent field
17950 // re-name away from the canonical `estrategia | max_restarts | window`
17951 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
17952 // axis silently rerouted through some other `Copy` coercion, surfaces
17953 // here rather than at a downstream per-`:supervisor` diagnostic-shape
17954 // drift. Peer of the sibling
17955 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
17956 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
17957 // envelope's per-`:politicas` per-axis ctor family, extended here onto
17958 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
17959 // variant family folded onto a substrate primitive.
17960 //
17961 // Fixtures picked out of each variant's accept-set boundary rather
17962 // than the default value so a silent constant-substitution to a per-
17963 // variant sentinel surfaces here on the structural-equality assertion.
17964 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
17965 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
17966 // isn't the `SimpleOneForOne` arm the sibling
17967 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
17968 // `max_restarts` fixture picks an above-cap magnitude the cap arm
17969 // rejects; the two `Duration` fixtures pick the sub-millisecond and
17970 // above-cap ends of the `:restart-window` canonical-form + cap
17971 // bracket respectively.
17972 let estrategia = RestartStrategy::RestForOne;
17973 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
17974 let sub_ms = Duration::from_micros(1_500);
17975 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
17976 assert_eq!(
17977 SupervisorError::no_children(estrategia),
17978 SupervisorError::NoChildren { estrategia },
17979 );
17980 assert_eq!(
17981 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
17982 SupervisorError::MaxRestartsExceedsCap {
17983 max_restarts: above_cap_restarts,
17984 },
17985 );
17986 assert_eq!(
17987 SupervisorError::restart_window_not_canonical(sub_ms),
17988 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
17989 );
17990 assert_eq!(
17991 SupervisorError::restart_window_exceeds_cap(above_hour),
17992 SupervisorError::RestartWindowExceedsCap { window: above_hour },
17993 );
17994 }
17995
17996 #[test]
17997 fn restart_strategy_try_from_bytes_routes_through_from_wire_accessor() {
17998 // Fail-before-pass-after byte-parity pin on the newly lifted
17999 // `impl TryFrom<&[u8]> for RestartStrategy` — asserts the trait-
18000 // idiomatic byte-view reverse-projection standard-library impl
18001 // and the substrate-primitive [`RestartStrategy::from_wire`]
18002 // `Option<Self>` accessor resolve to the same four-arm
18003 // `PascalCase` wire accept-set across every arm the exhaustive
18004 // [`RestartStrategy::ALL`] slice enumerates. Extends the
18005 // substrate-wide trait-idiomatic byte-view reverse-projection
18006 // axis onto the first M2-OTP-shape supervisor-slot closed-set
18007 // fieldless typed enum peer — mirror of the paired
18008 // [`TryFrom<&str> for RestartStrategy`] str-view reverse-
18009 // projection axis on the same enum, and the byte-view companion
18010 // of the pre-existing byte-owned reverse-projection family
18011 // ([`AsRef<[u8]>`], [`From<RestartStrategy> for Vec<u8>`],
18012 // [`From<&RestartStrategy> for Vec<u8>`]) on this same enum.
18013 // Peer of the sibling
18014 // [`crate::kind::tests::caixa_kind_try_from_bytes_routes_through_from_wire_accessor`]
18015 // (18d1940),
18016 // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_routes_through_from_wire_accessor`]
18017 // (d102cb8), and
18018 // [`crate::dep::tests::dep_list_try_from_bytes_routes_through_from_wire_accessor`]
18019 // (b8f25d5) — tracks the "route through `from_wire` via
18020 // `std::str::from_utf8`" discipline the first-mover established.
18021 //
18022 // Rust's standard library carries no blanket
18023 // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so
18024 // a two-hop composition through [`std::str::from_utf8`] + the
18025 // paired [`TryFrom<&str>`] axis is reachable through the pre-
18026 // existing str-view reverse-projection axis alone. But that
18027 // two-hop shape has no compile-time link back to the byte-view
18028 // reverse-projection axis, forces every downstream
18029 // `<T: for<'a> TryFrom<&'a [u8]>>`-bound consumer to open-code
18030 // the composition at every call site, and admits a silent split
18031 // whenever a future call site takes a sibling byte-projection
18032 // axis whose parse arm-set carries no compile-time byte-view
18033 // surface. This impl closes the byte-view reverse-projection
18034 // axis at the substrate-primitive [`RestartStrategy::from_wire`]
18035 // accessor so every future `<T: for<'a> TryFrom<&'a [u8]>>`-
18036 // bound consumer reaches the same four-arm `PascalCase` wire
18037 // accept-set through one trait dispatch.
18038 for &variant in RestartStrategy::ALL {
18039 let wire_bytes: &[u8] = variant.as_str().as_bytes();
18040 assert_eq!(
18041 <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes),
18042 Ok(variant),
18043 "TryFrom<&[u8]> impl on RestartStrategy must round-trip \
18044 RestartStrategy::{variant:?}.as_str().as_bytes() back to \
18045 Ok(RestartStrategy::{variant:?}) — divergence from \
18046 RestartStrategy::from_wire signals a silent detour off \
18047 the substrate-primitive accessor"
18048 );
18049 assert_eq!(
18050 <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes).ok(),
18051 RestartStrategy::from_wire(variant.as_str()),
18052 "TryFrom<&[u8]> ok()-projection on \
18053 RestartStrategy::{variant:?}.as_str().as_bytes() must \
18054 byte-equal RestartStrategy::from_wire on the paired \
18055 &str input"
18056 );
18057 // Cross-axis witness: the byte-view reverse-projection axis
18058 // must agree with the paired str-view reverse-projection
18059 // axis ([`TryFrom<&str>`]) on every accepted arm — the two
18060 // reverse paths share one `PascalCase` accept-set through
18061 // the substrate-primitive `from_wire` accessor.
18062 let via_str: Result<RestartStrategy, ()> =
18063 <RestartStrategy as TryFrom<&str>>::try_from(variant.as_str());
18064 let via_bytes: Result<RestartStrategy, ()> =
18065 <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes);
18066 assert_eq!(
18067 via_bytes, via_str,
18068 "TryFrom<&[u8]> and TryFrom<&str> reverse-projection \
18069 axes on RestartStrategy must agree on \
18070 RestartStrategy::{variant:?} — divergence signals the \
18071 byte-view and str-view reverse paths have drifted off \
18072 the same substrate-primitive from_wire accessor"
18073 );
18074 // Forward/reverse byte-view cross-axis witness: feed the
18075 // paired [`AsRef<[u8]>`] byte-tail back through the new
18076 // impl and assert it round-trips to the originating arm.
18077 let via_asref: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
18078 assert_eq!(
18079 <RestartStrategy as TryFrom<&[u8]>>::try_from(via_asref),
18080 Ok(variant),
18081 "TryFrom<&[u8]> ∘ AsRef<[u8]> must round-trip \
18082 RestartStrategy::{variant:?} — divergence signals the \
18083 forward and reverse byte-view axes have drifted off \
18084 the same substrate-primitive as_str/from_wire pair"
18085 );
18086 }
18087 }
18088
18089 #[test]
18090 fn restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes() {
18091 // Rejection witness on the `impl TryFrom<&[u8]> for
18092 // RestartStrategy` — sweeps two rejection paths the byte-view
18093 // reverse-projection axis collapses onto the single unit-error
18094 // `Err(())` return: the invalid-UTF-8 rejection path
18095 // ([`std::str::from_utf8`] returns `Err` before
18096 // [`RestartStrategy::from_wire`] runs) and the valid-UTF-8-but-
18097 // unknown-wire rejection path ([`RestartStrategy::from_wire`]
18098 // returns `None` on a byte-string outside the four-arm
18099 // `PascalCase` accept-set). Both must reject, so a future
18100 // accidental widening of the trait impl's accept-set (a case-
18101 // fold path, a silent acceptance of the kebab-case dispatcher-
18102 // catalog byte-strings on this axis — which would collide the
18103 // two-axis wire/catalog split the sibling
18104 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
18105 // a `#[serde(rename_all = "…")]` attribute drift that widens
18106 // the parse arm-set silently, a stray fallback that maps
18107 // invalid UTF-8 onto a default arm rather than the trait-
18108 // idiomatic `Err(())`) trips at caixa-core test time. Peer of
18109 // the sibling
18110 // [`crate::kind::tests::caixa_kind_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18111 // (18d1940),
18112 // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18113 // (d102cb8), and
18114 // [`crate::dep::tests::dep_list_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18115 // (b8f25d5) rejection witnesses.
18116 //
18117 // Non-UTF-8 candidates:
18118 // - a lone 0xFF byte (never valid as a UTF-8 leading byte)
18119 // - a lone 0x80 continuation byte with no leading byte
18120 // - a truncated multi-byte sequence (0xC3 without its continuation)
18121 // - a UTF-16 BOM-style byte pair the UTF-8 validator rejects
18122 // - a UTF-16 surrogate half rejected by UTF-8
18123 let non_utf8_rejected: &[&[u8]] = &[
18124 &[0xFF],
18125 &[0x80],
18126 &[0xC3],
18127 &[0xFF, 0xFE],
18128 &[0xED, 0xA0, 0x80],
18129 ];
18130 for &input in non_utf8_rejected {
18131 assert_eq!(
18132 <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
18133 Err(()),
18134 "TryFrom<&[u8]> impl on RestartStrategy must reject the \
18135 non-UTF-8 byte-sequence {input:?} with Err(()) — \
18136 silent acceptance signals the UTF-8 validation path \
18137 collapsed onto a default arm rather than the trait-\
18138 idiomatic unit-error"
18139 );
18140 }
18141 // Valid-UTF-8-but-unknown-wire candidates mirror the corpus
18142 // the sibling `restart_strategy_try_from_str_rejects_unknown_byte_strings`
18143 // (5b828ed) str-view rejection witness already pins on the
18144 // paired [`TryFrom<&str>`] axis: the empty byte-string,
18145 // whitespace-only padding, the kebab-case dispatcher-catalog
18146 // byte-strings on the sibling axis the pre-existing
18147 // [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`]
18148 // derive installs parses onto (a caller who confuses the two
18149 // axes trips here rather than at a downstream K8s-CR round-
18150 // trip miss), lowercase / uppercase / mixed-case folds of each
18151 // `PascalCase` arm, whitespace-padded / trailing-newline /
18152 // quote-wrapped forms, and plausible-but-wrong English rebrand
18153 // candidates.
18154 let unknown_wire_rejected: &[&[u8]] = &[
18155 b"",
18156 b" ",
18157 b"\n",
18158 b"\t",
18159 b"one-for-one",
18160 b"one-for-all",
18161 b"rest-for-one",
18162 b"simple-one-for-one",
18163 b"oneforone",
18164 b"one_for_one",
18165 b"OneForOnes",
18166 b"ONEFORONE",
18167 b"oneforall",
18168 b"restforone",
18169 b"simpleoneforone",
18170 b"OneForOne ",
18171 b" OneForOne",
18172 b" OneForAll ",
18173 b"OneForOne\n",
18174 b"RestForOne\t",
18175 b"OneForEach",
18176 b"AllForOne",
18177 b"one for one",
18178 b"\"OneForOne\"",
18179 b"?",
18180 ];
18181 for &input in unknown_wire_rejected {
18182 assert_eq!(
18183 <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
18184 Err(()),
18185 "TryFrom<&[u8]> impl on RestartStrategy must reject the \
18186 valid-UTF-8-but-unknown-wire byte-string {input:?} \
18187 with Err(()) — silent acceptance signals an accept-\
18188 set widening off the paired RestartStrategy::from_wire \
18189 resolver"
18190 );
18191 // Cross-axis witness: on a byte-string that is valid UTF-8,
18192 // the byte-view reverse-projection axis must agree with the
18193 // paired str-view reverse-projection axis
18194 // ([`TryFrom<&str>`]) — both route through the same
18195 // [`RestartStrategy::from_wire`] resolver, so the two
18196 // rejection paths align by construction.
18197 if let Ok(s) = std::str::from_utf8(input) {
18198 assert_eq!(
18199 <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
18200 <RestartStrategy as TryFrom<&str>>::try_from(s),
18201 "TryFrom<&[u8]> and TryFrom<&str> reverse-\
18202 projection axes on RestartStrategy must agree on \
18203 the valid-UTF-8 input {input:?} — divergence \
18204 signals the two reverse paths have drifted off \
18205 the same substrate-primitive from_wire accessor"
18206 );
18207 }
18208 }
18209 }
18210
18211 #[test]
18212 fn restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis() {
18213 // Fail-before-pass-after byte-parity pin on the newly lifted
18214 // `impl TryFrom<Vec<u8>> for RestartStrategy` — asserts the trait-
18215 // idiomatic owned-byte-vec reverse-projection standard-library
18216 // impl and the sibling borrowed-input [`TryFrom<&[u8]>`] axis
18217 // resolve to the same four-arm `PascalCase` wire accept-set
18218 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
18219 // enumerates. Extends the substrate-wide trait-idiomatic byte-
18220 // owned reverse-projection axis onto the first M2-OTP-shape
18221 // supervisor-slot closed-set fieldless typed enum peer — owned-
18222 // input mirror of the paired [`TryFrom<&[u8]>`] byte-view
18223 // reverse-projection axis (c699a83), and byte-owned reverse
18224 // companion of the pre-existing byte-owned *forward*-projection
18225 // pair ([`From<RestartStrategy> for Vec<u8>`],
18226 // [`From<&RestartStrategy> for Vec<u8>`]) on this same enum.
18227 // Peer of the sibling first-mover
18228 // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18229 // (99c2849) on the [`crate::CaixaKind`] closed-set typed-enum
18230 // peer, the sibling second-mover
18231 // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18232 // (83a1526) on the [`crate::CaixaDialeto`] peer, and the sibling
18233 // third-mover
18234 // [`crate::dep::tests::dep_list_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18235 // (42091cb) on the [`crate::dep::DepList`] peer — tracks the
18236 // "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice`
18237 // borrow" discipline the first-mover established.
18238 //
18239 // Rust's standard library carries no blanket
18240 // `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`,
18241 // so an owned-byte-vec caller otherwise picks between an open-
18242 // coded `<T as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
18243 // every call site whose type bounds have no compile-time link
18244 // back to the byte-owned reverse-projection axis, or a
18245 // `String::from_utf8(bytes)` two-hop shape whose error surface
18246 // leaks the standard-library `FromUtf8Error` type. This impl
18247 // closes the byte-owned reverse-projection axis at the
18248 // substrate-primitive [`RestartStrategy::from_wire`] accessor so
18249 // every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec
18250 // consumer reaches the same four-arm `PascalCase` wire accept-
18251 // set through one trait dispatch.
18252 for &variant in RestartStrategy::ALL {
18253 let wire_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
18254 assert_eq!(
18255 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone()),
18256 Ok(variant),
18257 "TryFrom<Vec<u8>> impl on RestartStrategy must round-trip \
18258 RestartStrategy::{variant:?}.as_str().as_bytes().to_vec() \
18259 back to Ok(RestartStrategy::{variant:?}) — divergence \
18260 from the sibling TryFrom<&[u8]> axis signals a silent \
18261 detour off the substrate-primitive from_wire accessor"
18262 );
18263 // Cross-axis witness: the owned-byte-vec reverse-projection
18264 // axis must agree with the borrowed byte-slice reverse-
18265 // projection axis on every accepted arm — the two axes share
18266 // one `PascalCase` wire vocabulary through the substrate-
18267 // primitive `from_wire` accessor, and the owned-input axis
18268 // delegates to the borrowed peer by design.
18269 let via_owned: Result<RestartStrategy, ()> =
18270 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone());
18271 let via_borrowed: Result<RestartStrategy, ()> =
18272 <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes.as_slice());
18273 assert_eq!(
18274 via_owned, via_borrowed,
18275 "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18276 axes on RestartStrategy must agree on \
18277 RestartStrategy::{variant:?} — divergence signals the \
18278 owned-input and borrowed-input byte-view reverse paths \
18279 have drifted off the same substrate-primitive \
18280 from_wire accessor"
18281 );
18282 // Cross-axis witness against the paired str-view reverse
18283 // axis ([`TryFrom<&str>`]) — the three reverse paths (str-
18284 // view, byte-view borrowed, byte-view owned) share one
18285 // substrate primitive.
18286 let via_str: Result<RestartStrategy, ()> =
18287 <RestartStrategy as TryFrom<&str>>::try_from(variant.as_str());
18288 assert_eq!(
18289 via_owned, via_str,
18290 "TryFrom<Vec<u8>> and TryFrom<&str> reverse-projection \
18291 axes on RestartStrategy must agree on \
18292 RestartStrategy::{variant:?} — divergence signals the \
18293 byte-owned and str-view reverse paths have drifted off \
18294 the same substrate-primitive from_wire accessor"
18295 );
18296 // Four-corner witness: because [`RestartStrategy`] carries
18297 // no wire-vs-diagnostic split (as_str and from_wire share
18298 // one `PascalCase` byte-vocabulary — unlike the sibling
18299 // [`crate::CaixaKind`] whose peer test deliberately declines
18300 // this witness), the byte-owned reverse-projection axis on
18301 // this enum *does* round-trip against the paired byte-owned
18302 // forward-projection pair. Pin every corner of the {owned-
18303 // input, borrowed-input} × {From<Self> → Vec<u8>,
18304 // From<&Self> → Vec<u8>} square onto the same Ok(variant)
18305 // return so a future accident that drops one corner off the
18306 // substrate-primitive accessor trips here.
18307 let owned_forward: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
18308 let borrowed_forward: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
18309 assert_eq!(
18310 owned_forward, wire_bytes,
18311 "From<RestartStrategy> for Vec<u8> forward projection on \
18312 RestartStrategy::{variant:?} must byte-equal \
18313 variant.as_str().as_bytes().to_vec() — divergence \
18314 signals the paired forward pair drifted off the \
18315 substrate-primitive as_str accessor"
18316 );
18317 assert_eq!(
18318 borrowed_forward, wire_bytes,
18319 "From<&RestartStrategy> for Vec<u8> forward projection \
18320 on &RestartStrategy::{variant:?} must byte-equal \
18321 variant.as_str().as_bytes().to_vec() — divergence \
18322 signals the paired forward pair drifted off the \
18323 substrate-primitive as_str accessor"
18324 );
18325 assert_eq!(
18326 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned_forward.clone()),
18327 Ok(variant),
18328 "Four-corner round-trip on RestartStrategy::{variant:?} \
18329 through From<RestartStrategy> for Vec<u8> then \
18330 TryFrom<Vec<u8>> for RestartStrategy must return \
18331 Ok(variant) — divergence signals the byte-owned \
18332 forward pair and the byte-owned reverse axis have \
18333 drifted apart"
18334 );
18335 assert_eq!(
18336 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(borrowed_forward),
18337 Ok(variant),
18338 "Four-corner round-trip on RestartStrategy::{variant:?} \
18339 through From<&RestartStrategy> for Vec<u8> then \
18340 TryFrom<Vec<u8>> for RestartStrategy must return \
18341 Ok(variant) — divergence signals the borrowed-input \
18342 forward corner and the owned-input reverse corner have \
18343 drifted apart"
18344 );
18345 }
18346 }
18347
18348 #[test]
18349 fn restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes() {
18350 // Rejection witness on the `impl TryFrom<Vec<u8>> for
18351 // RestartStrategy` — sweeps the same two rejection paths the
18352 // sibling borrowed `TryFrom<&[u8]>` axis collapses onto the
18353 // single unit-error return: the invalid-UTF-8 rejection path
18354 // (`std::str::from_utf8` on the underlying byte-slice returns
18355 // `Err` before [`RestartStrategy::from_wire`] runs) and the
18356 // valid-UTF-8-but-unknown-wire rejection path
18357 // ([`RestartStrategy::from_wire`] returns `None` on a byte-
18358 // string outside the four-arm `PascalCase` accept-set). Both
18359 // must reject so a future accidental widening of the trait
18360 // impl's accept-set (a case-fold path, a silent acceptance of
18361 // the kebab-case dispatcher-catalog byte-strings on this axis —
18362 // which would collide the two-axis wire/catalog split the
18363 // sibling [`RestartStrategy::from_wire`] doc block makes load-
18364 // bearing — a `#[serde(rename_all = "…")]` attribute drift that
18365 // widens the parse arm-set silently, a stray
18366 // `String::from_utf8_lossy` detour that widens the input
18367 // surface with the U+FFFD replacement character, an
18368 // `Option::unwrap_or_default`-shape fallback that maps invalid
18369 // UTF-8 onto a default arm rather than the trait-idiomatic
18370 // `Err(())`) trips at caixa-core test time. Peer of the sibling
18371 // first-mover
18372 // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18373 // (99c2849) on the [`crate::CaixaKind`] peer, the sibling
18374 // second-mover
18375 // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18376 // (83a1526) on the [`crate::CaixaDialeto`] peer, and the
18377 // sibling third-mover
18378 // [`crate::dep::tests::dep_list_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18379 // (42091cb) on the [`crate::dep::DepList`] peer rejection
18380 // witnesses.
18381 let non_utf8_rejected: &[&[u8]] = &[
18382 &[0xFF],
18383 &[0x80],
18384 &[0xC3],
18385 &[0xFF, 0xFE],
18386 &[0xED, 0xA0, 0x80], // UTF-16 surrogate half — rejected by UTF-8
18387 ];
18388 for &input in non_utf8_rejected {
18389 let owned: Vec<u8> = input.to_vec();
18390 assert_eq!(
18391 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned),
18392 Err(()),
18393 "TryFrom<Vec<u8>> impl on RestartStrategy must reject \
18394 the non-UTF-8 byte-sequence {input:?} with Err(()) — \
18395 silent acceptance signals the UTF-8 validation path \
18396 collapsed onto a default arm rather than the trait-\
18397 idiomatic unit-error"
18398 );
18399 // Cross-axis witness: the owned-input axis must agree with
18400 // the borrowed-input axis on every rejected input.
18401 assert_eq!(
18402 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
18403 <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
18404 "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18405 axes on RestartStrategy must agree on the non-UTF-8 \
18406 input {input:?} — divergence signals the owned-input \
18407 and borrowed-input byte-view reverse paths have drifted \
18408 off the same substrate-primitive from_wire accessor"
18409 );
18410 }
18411 // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
18412 // sibling borrowed-input rejection witness
18413 // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18414 // (c699a83) already pins on the paired byte-view axis: the
18415 // empty byte-string, whitespace-only padding, the kebab-case
18416 // dispatcher-catalog byte-strings on the sibling axis the pre-
18417 // existing [`std::str::FromStr`] impl the
18418 // [`gen_platform::FromStrKind`] derive installs parses onto (a
18419 // caller who confuses the two axes trips here rather than at a
18420 // downstream K8s-CR round-trip miss), lowercase / uppercase /
18421 // mixed-case folds of each `PascalCase` arm, whitespace-padded
18422 // / trailing-newline / quote-wrapped forms, and plausible-but-
18423 // wrong English rebrand candidates.
18424 let unknown_wire_rejected: &[&[u8]] = &[
18425 b"",
18426 b" ",
18427 b"\n",
18428 b"\t",
18429 b"one-for-one",
18430 b"one-for-all",
18431 b"rest-for-one",
18432 b"simple-one-for-one",
18433 b"oneforone",
18434 b"one_for_one",
18435 b"OneForOnes",
18436 b"ONEFORONE",
18437 b"oneforall",
18438 b"restforone",
18439 b"simpleoneforone",
18440 b"OneForOne ",
18441 b" OneForOne",
18442 b" OneForAll ",
18443 b"OneForOne\n",
18444 b"RestForOne\t",
18445 b"OneForEach",
18446 b"AllForOne",
18447 b"one for one",
18448 b"\"OneForOne\"",
18449 b"?",
18450 ];
18451 for &input in unknown_wire_rejected {
18452 let owned: Vec<u8> = input.to_vec();
18453 assert_eq!(
18454 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned),
18455 Err(()),
18456 "TryFrom<Vec<u8>> impl on RestartStrategy must reject \
18457 the valid-UTF-8-but-unknown-wire byte-string {input:?} \
18458 with Err(()) — silent acceptance signals an accept-\
18459 set widening off the paired RestartStrategy::from_wire \
18460 resolver"
18461 );
18462 // Cross-axis witness against the borrowed byte-view axis:
18463 // the two paths must agree by construction, since the owned
18464 // axis delegates to the borrowed peer.
18465 assert_eq!(
18466 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
18467 <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
18468 "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18469 axes on RestartStrategy must agree on the valid-UTF-8-\
18470 but-unknown-wire input {input:?} — divergence signals \
18471 the owned-input and borrowed-input byte-view reverse \
18472 paths have drifted off the same substrate-primitive \
18473 from_wire accessor"
18474 );
18475 }
18476 }
18477
18478 #[test]
18479 fn restart_policy_try_from_bytes_routes_through_from_wire_accessor() {
18480 // Fail-before-pass-after byte-parity pin on the newly lifted
18481 // `impl TryFrom<&[u8]> for RestartPolicy` — asserts the trait-
18482 // idiomatic byte-view reverse-projection standard-library impl
18483 // and the substrate-primitive [`RestartPolicy::from_wire`]
18484 // `Option<Self>` accessor resolve to the same three-arm
18485 // `PascalCase` wire accept-set across every arm the exhaustive
18486 // [`RestartPolicy::ALL`] slice enumerates. Closes the substrate-
18487 // wide trait-idiomatic byte-view reverse-projection axis on the
18488 // M2-OTP-shape `:supervisor :estrategia` + `:children :restart`
18489 // slot pair the sibling [`RestartStrategy`] first-mover
18490 // (c699a83) opened one commit prior — mirror of the paired
18491 // [`TryFrom<&str> for RestartPolicy`] str-view reverse-
18492 // projection axis on the same enum, and the byte-view companion
18493 // of the pre-existing byte-owned reverse-projection family
18494 // ([`AsRef<[u8]>`], [`From<RestartPolicy> for Vec<u8>`],
18495 // [`From<&RestartPolicy> for Vec<u8>`]) on this same enum. Peer
18496 // of the sibling
18497 // [`restart_strategy_try_from_bytes_routes_through_from_wire_accessor`]
18498 // (c699a83),
18499 // [`crate::kind::tests::caixa_kind_try_from_bytes_routes_through_from_wire_accessor`]
18500 // (18d1940),
18501 // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_routes_through_from_wire_accessor`]
18502 // (d102cb8), and
18503 // [`crate::dep::tests::dep_list_try_from_bytes_routes_through_from_wire_accessor`]
18504 // (b8f25d5) — tracks the "route through `from_wire` via
18505 // `std::str::from_utf8`" discipline the first-mover established.
18506 //
18507 // Rust's standard library carries no blanket
18508 // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a
18509 // two-hop composition through [`std::str::from_utf8`] + the
18510 // paired [`TryFrom<&str>`] axis is reachable through the pre-
18511 // existing str-view reverse-projection axis alone. But that
18512 // two-hop shape has no compile-time link back to the byte-view
18513 // reverse-projection axis, forces every downstream
18514 // `<T: for<'a> TryFrom<&'a [u8]>>`-bound consumer to open-code
18515 // the composition at every call site, and admits a silent split
18516 // whenever a future call site takes a sibling byte-projection
18517 // axis whose parse arm-set carries no compile-time byte-view
18518 // surface. This impl closes the byte-view reverse-projection
18519 // axis at the substrate-primitive [`RestartPolicy::from_wire`]
18520 // accessor so every future `<T: for<'a> TryFrom<&'a [u8]>>`-
18521 // bound consumer reaches the same three-arm `PascalCase` wire
18522 // accept-set through one trait dispatch.
18523 for &variant in RestartPolicy::ALL {
18524 let wire_bytes: &[u8] = variant.as_str().as_bytes();
18525 assert_eq!(
18526 <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes),
18527 Ok(variant),
18528 "TryFrom<&[u8]> impl on RestartPolicy must round-trip \
18529 RestartPolicy::{variant:?}.as_str().as_bytes() back to \
18530 Ok(RestartPolicy::{variant:?}) — divergence from \
18531 RestartPolicy::from_wire signals a silent detour off \
18532 the substrate-primitive accessor"
18533 );
18534 assert_eq!(
18535 <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes).ok(),
18536 RestartPolicy::from_wire(variant.as_str()),
18537 "TryFrom<&[u8]> ok()-projection on \
18538 RestartPolicy::{variant:?}.as_str().as_bytes() must \
18539 byte-equal RestartPolicy::from_wire on the paired \
18540 &str input"
18541 );
18542 // Cross-axis witness: the byte-view reverse-projection axis
18543 // must agree with the paired str-view reverse-projection
18544 // axis ([`TryFrom<&str>`]) on every accepted arm — the two
18545 // reverse paths share one `PascalCase` accept-set through
18546 // the substrate-primitive `from_wire` accessor.
18547 let via_str: Result<RestartPolicy, ()> =
18548 <RestartPolicy as TryFrom<&str>>::try_from(variant.as_str());
18549 let via_bytes: Result<RestartPolicy, ()> =
18550 <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes);
18551 assert_eq!(
18552 via_bytes, via_str,
18553 "TryFrom<&[u8]> and TryFrom<&str> reverse-projection \
18554 axes on RestartPolicy must agree on \
18555 RestartPolicy::{variant:?} — divergence signals the \
18556 byte-view and str-view reverse paths have drifted off \
18557 the same substrate-primitive from_wire accessor"
18558 );
18559 // Forward/reverse byte-view cross-axis witness: feed the
18560 // paired [`AsRef<[u8]>`] byte-tail back through the new
18561 // impl and assert it round-trips to the originating arm.
18562 let via_asref: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
18563 assert_eq!(
18564 <RestartPolicy as TryFrom<&[u8]>>::try_from(via_asref),
18565 Ok(variant),
18566 "TryFrom<&[u8]> ∘ AsRef<[u8]> must round-trip \
18567 RestartPolicy::{variant:?} — divergence signals the \
18568 forward and reverse byte-view axes have drifted off \
18569 the same substrate-primitive as_str/from_wire pair"
18570 );
18571 }
18572 }
18573
18574 #[test]
18575 fn restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes() {
18576 // Rejection witness on the `impl TryFrom<&[u8]> for RestartPolicy`
18577 // — sweeps two rejection paths the byte-view reverse-projection
18578 // axis collapses onto the single unit-error `Err(())` return: the
18579 // invalid-UTF-8 rejection path ([`std::str::from_utf8`] returns
18580 // `Err` before [`RestartPolicy::from_wire`] runs) and the
18581 // valid-UTF-8-but-unknown-wire rejection path
18582 // ([`RestartPolicy::from_wire`] returns `None` on a byte-string
18583 // outside the three-arm `PascalCase` accept-set). Both must
18584 // reject, so a future accidental widening of the trait impl's
18585 // accept-set (a case-fold path, a silent acceptance of the
18586 // kebab-case dispatcher-catalog byte-strings on this axis — which
18587 // would collide the two-axis wire/catalog split the sibling
18588 // [`RestartPolicy::from_wire`] doc block makes load-bearing — a
18589 // `#[serde(rename_all = "…")]` attribute drift that widens the
18590 // parse arm-set silently, a stray fallback that maps invalid
18591 // UTF-8 onto a default arm rather than the trait-idiomatic
18592 // `Err(())`) trips at caixa-core test time. Peer of the sibling
18593 // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18594 // (c699a83),
18595 // [`crate::kind::tests::caixa_kind_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18596 // (18d1940),
18597 // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18598 // (d102cb8), and
18599 // [`crate::dep::tests::dep_list_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18600 // (b8f25d5) rejection witnesses.
18601 //
18602 // Non-UTF-8 candidates:
18603 // - a lone 0xFF byte (never valid as a UTF-8 leading byte)
18604 // - a lone 0x80 continuation byte with no leading byte
18605 // - a truncated multi-byte sequence (0xC3 without its continuation)
18606 // - a UTF-16 BOM-style byte pair the UTF-8 validator rejects
18607 // - a UTF-16 surrogate half rejected by UTF-8
18608 let non_utf8_rejected: &[&[u8]] = &[
18609 &[0xFF],
18610 &[0x80],
18611 &[0xC3],
18612 &[0xFF, 0xFE],
18613 &[0xED, 0xA0, 0x80],
18614 ];
18615 for &input in non_utf8_rejected {
18616 assert_eq!(
18617 <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
18618 Err(()),
18619 "TryFrom<&[u8]> impl on RestartPolicy must reject the \
18620 non-UTF-8 byte-sequence {input:?} with Err(()) — \
18621 silent acceptance signals the UTF-8 validation path \
18622 collapsed onto a default arm rather than the trait-\
18623 idiomatic unit-error"
18624 );
18625 }
18626 // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
18627 // sibling `restart_policy_try_from_str_rejects_unknown_byte_strings`
18628 // str-view rejection witness already pins on the paired
18629 // [`TryFrom<&str>`] axis: the empty byte-string, whitespace-only
18630 // padding, the kebab-case dispatcher-catalog byte-strings on the
18631 // sibling axis the pre-existing [`std::str::FromStr`] impl the
18632 // [`gen_platform::FromStrKind`] derive installs parses onto (a
18633 // caller who confuses the two axes trips here rather than at a
18634 // downstream K8s-CR round-trip miss), lowercase / uppercase /
18635 // mixed-case folds of each `PascalCase` arm, whitespace-padded /
18636 // trailing-newline / quote-wrapped forms, and plausible-but-wrong
18637 // English rebrand candidates (`Ephemeral`, `Always`, `Never`,
18638 // `OnAbnormalExit`, `intrinsic`).
18639 let unknown_wire_rejected: &[&[u8]] = &[
18640 b"",
18641 b" ",
18642 b"\n",
18643 b"\t",
18644 b"permanent",
18645 b"temporary",
18646 b"transient",
18647 b"PERMANENT",
18648 b"TEMPORARY",
18649 b"TRANSIENT",
18650 b"Permanents",
18651 b"Permanent ",
18652 b" Permanent",
18653 b" Temporary ",
18654 b"Permanent\n",
18655 b"Transient\t",
18656 b"\"Permanent\"",
18657 b"Ephemeral",
18658 b"Always",
18659 b"Never",
18660 b"OnAbnormalExit",
18661 b"intrinsic",
18662 b"?",
18663 ];
18664 for &input in unknown_wire_rejected {
18665 assert_eq!(
18666 <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
18667 Err(()),
18668 "TryFrom<&[u8]> impl on RestartPolicy must reject the \
18669 valid-UTF-8-but-unknown-wire byte-string {input:?} \
18670 with Err(()) — silent acceptance signals an accept-\
18671 set widening off the paired RestartPolicy::from_wire \
18672 resolver"
18673 );
18674 // Cross-axis witness: on a byte-string that is valid UTF-8,
18675 // the byte-view reverse-projection axis must agree with the
18676 // paired str-view reverse-projection axis
18677 // ([`TryFrom<&str>`]) — both route through the same
18678 // [`RestartPolicy::from_wire`] resolver, so the two
18679 // rejection paths align by construction.
18680 if let Ok(s) = std::str::from_utf8(input) {
18681 assert_eq!(
18682 <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
18683 <RestartPolicy as TryFrom<&str>>::try_from(s),
18684 "TryFrom<&[u8]> and TryFrom<&str> reverse-\
18685 projection axes on RestartPolicy must agree on \
18686 the valid-UTF-8 input {input:?} — divergence \
18687 signals the two reverse paths have drifted off \
18688 the same substrate-primitive from_wire accessor"
18689 );
18690 }
18691 }
18692 }
18693
18694 #[test]
18695 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
18696 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
18697 // generated ctor `const fn` so a caller can pin a `SupervisorError`
18698 // at compile time — the same zero-runtime-work property the pre-lift
18699 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
18700 // its `Copy`-pass-through construction path (no `.to_string()` /
18701 // `.into()` allocation, no branching). If any future edit silently
18702 // drops the `const` qualifier from the macro body the per-arm `const`
18703 // bindings below fail to compile, which surfaces the regression at
18704 // the substrate-primitive definition rather than at some downstream
18705 // consumer that had come to rely on the `const`-constructibility.
18706 // Peer of the sibling
18707 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
18708 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
18709 // per-`:politicas` per-axis ctor family.
18710 const NO_CHILDREN: SupervisorError =
18711 SupervisorError::no_children(RestartStrategy::OneForAll);
18712 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
18713 const WINDOW_NC: SupervisorError =
18714 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
18715 const WINDOW_CAP: SupervisorError =
18716 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
18717 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
18718 assert!(matches!(
18719 MAX_RESTARTS_CAP,
18720 SupervisorError::MaxRestartsExceedsCap { .. }
18721 ));
18722 assert!(matches!(
18723 WINDOW_NC,
18724 SupervisorError::RestartWindowNotCanonical { .. }
18725 ));
18726 assert!(matches!(
18727 WINDOW_CAP,
18728 SupervisorError::RestartWindowExceedsCap { .. }
18729 ));
18730 }
18731
18732 #[test]
18733 fn restart_policy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis() {
18734 // Fail-before-pass-after byte-parity pin on the newly lifted
18735 // `impl TryFrom<Vec<u8>> for RestartPolicy` — asserts the trait-
18736 // idiomatic owned-byte-vec reverse-projection standard-library
18737 // impl and the sibling borrowed-input [`TryFrom<&[u8]>`] axis
18738 // resolve to the same three-arm `PascalCase` wire accept-set
18739 // across every arm the exhaustive [`RestartPolicy::ALL`] slice
18740 // enumerates. Closes the substrate-wide trait-idiomatic byte-
18741 // owned reverse-projection axis on the M2-OTP-shape
18742 // `:supervisor :estrategia` + `:children :restart` slot pair the
18743 // sibling [`RestartStrategy`] first-mover
18744 // [`restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18745 // (34951fe) opened one commit-window prior — owned-input mirror
18746 // of the paired [`TryFrom<&[u8]>`] byte-view reverse-projection
18747 // axis on this same enum (d9ef5f0), and byte-owned reverse
18748 // companion of the pre-existing byte-owned *forward*-projection
18749 // pair ([`From<RestartPolicy> for Vec<u8>`],
18750 // [`From<&RestartPolicy> for Vec<u8>`]) on this same enum. Peer
18751 // of the sibling first-mover
18752 // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18753 // (99c2849) on the [`crate::CaixaKind`] closed-set typed-enum
18754 // peer, the sibling second-mover
18755 // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18756 // (83a1526) on the [`crate::CaixaDialeto`] peer, the sibling
18757 // third-mover
18758 // [`crate::dep::tests::dep_list_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18759 // (42091cb) on the [`crate::dep::DepList`] peer, and the sibling
18760 // fourth-mover
18761 // [`restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
18762 // (34951fe) on the [`RestartStrategy`] peer — tracks the
18763 // "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice`
18764 // borrow" discipline the first-mover established.
18765 //
18766 // Rust's standard library carries no blanket
18767 // `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`,
18768 // so an owned-byte-vec caller otherwise picks between an open-
18769 // coded `<T as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
18770 // every call site whose type bounds have no compile-time link
18771 // back to the byte-owned reverse-projection axis, or a
18772 // `String::from_utf8(bytes)` two-hop shape whose error surface
18773 // leaks the standard-library `FromUtf8Error` type. This impl
18774 // closes the byte-owned reverse-projection axis at the
18775 // substrate-primitive [`RestartPolicy::from_wire`] accessor so
18776 // every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec
18777 // consumer reaches the same three-arm `PascalCase` wire accept-
18778 // set through one trait dispatch.
18779 for &variant in RestartPolicy::ALL {
18780 let wire_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
18781 assert_eq!(
18782 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone()),
18783 Ok(variant),
18784 "TryFrom<Vec<u8>> impl on RestartPolicy must round-trip \
18785 RestartPolicy::{variant:?}.as_str().as_bytes().to_vec() \
18786 back to Ok(RestartPolicy::{variant:?}) — divergence \
18787 from the sibling TryFrom<&[u8]> axis signals a silent \
18788 detour off the substrate-primitive from_wire accessor"
18789 );
18790 // Cross-axis witness: the owned-byte-vec reverse-projection
18791 // axis must agree with the borrowed byte-slice reverse-
18792 // projection axis on every accepted arm — the two axes share
18793 // one `PascalCase` wire vocabulary through the substrate-
18794 // primitive `from_wire` accessor, and the owned-input axis
18795 // delegates to the borrowed peer by design.
18796 let via_owned: Result<RestartPolicy, ()> =
18797 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone());
18798 let via_borrowed: Result<RestartPolicy, ()> =
18799 <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes.as_slice());
18800 assert_eq!(
18801 via_owned, via_borrowed,
18802 "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18803 axes on RestartPolicy must agree on \
18804 RestartPolicy::{variant:?} — divergence signals the \
18805 owned-input and borrowed-input byte-view reverse paths \
18806 have drifted off the same substrate-primitive \
18807 from_wire accessor"
18808 );
18809 // Cross-axis witness against the paired str-view reverse
18810 // axis ([`TryFrom<&str>`]) — the three reverse paths (str-
18811 // view, byte-view borrowed, byte-view owned) share one
18812 // substrate primitive.
18813 let via_str: Result<RestartPolicy, ()> =
18814 <RestartPolicy as TryFrom<&str>>::try_from(variant.as_str());
18815 assert_eq!(
18816 via_owned, via_str,
18817 "TryFrom<Vec<u8>> and TryFrom<&str> reverse-projection \
18818 axes on RestartPolicy must agree on \
18819 RestartPolicy::{variant:?} — divergence signals the \
18820 byte-owned and str-view reverse paths have drifted off \
18821 the same substrate-primitive from_wire accessor"
18822 );
18823 // Four-corner witness: because [`RestartPolicy`] carries
18824 // no wire-vs-diagnostic split (as_str and from_wire share
18825 // one `PascalCase` byte-vocabulary — like the sibling
18826 // [`RestartStrategy`] and unlike the sibling
18827 // [`crate::CaixaKind`] whose peer test deliberately declines
18828 // this witness), the byte-owned reverse-projection axis on
18829 // this enum *does* round-trip against the paired byte-owned
18830 // forward-projection pair. Pin every corner of the {owned-
18831 // input, borrowed-input} × {From<Self> → Vec<u8>,
18832 // From<&Self> → Vec<u8>} square onto the same Ok(variant)
18833 // return so a future accident that drops one corner off the
18834 // substrate-primitive accessor trips here.
18835 let owned_forward: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
18836 let borrowed_forward: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
18837 assert_eq!(
18838 owned_forward, wire_bytes,
18839 "From<RestartPolicy> for Vec<u8> forward projection on \
18840 RestartPolicy::{variant:?} must byte-equal \
18841 variant.as_str().as_bytes().to_vec() — divergence \
18842 signals the paired forward pair drifted off the \
18843 substrate-primitive as_str accessor"
18844 );
18845 assert_eq!(
18846 borrowed_forward, wire_bytes,
18847 "From<&RestartPolicy> for Vec<u8> forward projection \
18848 on &RestartPolicy::{variant:?} must byte-equal \
18849 variant.as_str().as_bytes().to_vec() — divergence \
18850 signals the paired forward pair drifted off the \
18851 substrate-primitive as_str accessor"
18852 );
18853 assert_eq!(
18854 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned_forward.clone()),
18855 Ok(variant),
18856 "Four-corner round-trip on RestartPolicy::{variant:?} \
18857 through From<RestartPolicy> for Vec<u8> then \
18858 TryFrom<Vec<u8>> for RestartPolicy must return \
18859 Ok(variant) — divergence signals the byte-owned \
18860 forward pair and the byte-owned reverse axis have \
18861 drifted apart"
18862 );
18863 assert_eq!(
18864 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(borrowed_forward),
18865 Ok(variant),
18866 "Four-corner round-trip on RestartPolicy::{variant:?} \
18867 through From<&RestartPolicy> for Vec<u8> then \
18868 TryFrom<Vec<u8>> for RestartPolicy must return \
18869 Ok(variant) — divergence signals the borrowed-input \
18870 forward corner and the owned-input reverse corner have \
18871 drifted apart"
18872 );
18873 }
18874 }
18875
18876 #[test]
18877 fn restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes() {
18878 // Rejection witness on the `impl TryFrom<Vec<u8>> for
18879 // RestartPolicy` — sweeps the same two rejection paths the
18880 // sibling borrowed `TryFrom<&[u8]>` axis collapses onto the
18881 // single unit-error return: the invalid-UTF-8 rejection path
18882 // (`std::str::from_utf8` on the underlying byte-slice returns
18883 // `Err` before [`RestartPolicy::from_wire`] runs) and the
18884 // valid-UTF-8-but-unknown-wire rejection path
18885 // ([`RestartPolicy::from_wire`] returns `None` on a byte-
18886 // string outside the three-arm `PascalCase` accept-set). Both
18887 // must reject so a future accidental widening of the trait
18888 // impl's accept-set (a case-fold path, a silent acceptance of
18889 // the kebab-case dispatcher-catalog byte-strings on this axis —
18890 // which would collide the two-axis wire/catalog split the
18891 // sibling [`RestartPolicy::from_wire`] doc block makes load-
18892 // bearing — a `#[serde(rename_all = "…")]` attribute drift that
18893 // widens the parse arm-set silently, a stray
18894 // `String::from_utf8_lossy` detour that widens the input
18895 // surface with the U+FFFD replacement character, an
18896 // `Option::unwrap_or_default`-shape fallback that maps invalid
18897 // UTF-8 onto a default arm rather than the trait-idiomatic
18898 // `Err(())`) trips at caixa-core test time. Peer of the sibling
18899 // first-mover
18900 // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18901 // (99c2849) on the [`crate::CaixaKind`] peer, the sibling
18902 // second-mover
18903 // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18904 // (83a1526) on the [`crate::CaixaDialeto`] peer, the sibling
18905 // third-mover
18906 // [`crate::dep::tests::dep_list_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18907 // (42091cb) on the [`crate::dep::DepList`] peer, and the
18908 // sibling fourth-mover
18909 // [`restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18910 // (34951fe) on the [`RestartStrategy`] peer rejection
18911 // witnesses.
18912 let non_utf8_rejected: &[&[u8]] = &[
18913 &[0xFF],
18914 &[0x80],
18915 &[0xC3],
18916 &[0xFF, 0xFE],
18917 &[0xED, 0xA0, 0x80], // UTF-16 surrogate half — rejected by UTF-8
18918 ];
18919 for &input in non_utf8_rejected {
18920 let owned: Vec<u8> = input.to_vec();
18921 assert_eq!(
18922 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned),
18923 Err(()),
18924 "TryFrom<Vec<u8>> impl on RestartPolicy must reject \
18925 the non-UTF-8 byte-sequence {input:?} with Err(()) — \
18926 silent acceptance signals the UTF-8 validation path \
18927 collapsed onto a default arm rather than the trait-\
18928 idiomatic unit-error"
18929 );
18930 // Cross-axis witness: the owned-input axis must agree with
18931 // the borrowed-input axis on every rejected input.
18932 assert_eq!(
18933 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
18934 <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
18935 "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18936 axes on RestartPolicy must agree on the non-UTF-8 \
18937 input {input:?} — divergence signals the owned-input \
18938 and borrowed-input byte-view reverse paths have drifted \
18939 off the same substrate-primitive from_wire accessor"
18940 );
18941 }
18942 // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
18943 // sibling borrowed-input rejection witness
18944 // [`restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18945 // (d9ef5f0) already pins on the paired byte-view axis: the
18946 // empty byte-string, whitespace-only padding, the kebab-case
18947 // dispatcher-catalog byte-strings on the sibling axis the pre-
18948 // existing [`std::str::FromStr`] impl the
18949 // [`gen_platform::FromStrKind`] derive installs parses onto (a
18950 // caller who confuses the two axes trips here rather than at a
18951 // downstream K8s-CR round-trip miss), lowercase / uppercase /
18952 // mixed-case folds of each `PascalCase` arm, whitespace-padded /
18953 // trailing-newline / quote-wrapped forms, and plausible-but-
18954 // wrong English rebrand candidates (`Ephemeral`, `Always`,
18955 // `Never`, `OnAbnormalExit`, `intrinsic`).
18956 let unknown_wire_rejected: &[&[u8]] = &[
18957 b"",
18958 b" ",
18959 b"\n",
18960 b"\t",
18961 b"permanent",
18962 b"temporary",
18963 b"transient",
18964 b"PERMANENT",
18965 b"TEMPORARY",
18966 b"TRANSIENT",
18967 b"Permanents",
18968 b"Permanent ",
18969 b" Permanent",
18970 b" Temporary ",
18971 b"Permanent\n",
18972 b"Transient\t",
18973 b"\"Permanent\"",
18974 b"Ephemeral",
18975 b"Always",
18976 b"Never",
18977 b"OnAbnormalExit",
18978 b"intrinsic",
18979 b"?",
18980 ];
18981 for &input in unknown_wire_rejected {
18982 let owned: Vec<u8> = input.to_vec();
18983 assert_eq!(
18984 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned),
18985 Err(()),
18986 "TryFrom<Vec<u8>> impl on RestartPolicy must reject \
18987 the valid-UTF-8-but-unknown-wire byte-string {input:?} \
18988 with Err(()) — silent acceptance signals an accept-\
18989 set widening off the paired RestartPolicy::from_wire \
18990 resolver"
18991 );
18992 // Cross-axis witness against the borrowed byte-view axis:
18993 // the two paths must agree by construction, since the owned
18994 // axis delegates to the borrowed peer.
18995 assert_eq!(
18996 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
18997 <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
18998 "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18999 axes on RestartPolicy must agree on the valid-UTF-8-\
19000 but-unknown-wire input {input:?} — divergence signals \
19001 the owned-input and borrowed-input byte-view reverse \
19002 paths have drifted off the same substrate-primitive \
19003 from_wire accessor"
19004 );
19005 }
19006 }
19007
19008 #[test]
19009 fn restart_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis() {
19010 // Fail-before-pass-after byte-parity pin on the newly lifted
19011 // `impl TryFrom<String> for RestartStrategy` — asserts the
19012 // trait-idiomatic string-owned reverse-projection standard-
19013 // library impl and the sibling borrowed-input [`TryFrom<&str>`]
19014 // axis resolve to the same four-arm `PascalCase` wire accept-set
19015 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
19016 // enumerates. Extends the substrate-wide trait-idiomatic string-
19017 // owned reverse-projection axis onto the first M2-OTP-shape
19018 // supervisor-slot closed-set fieldless typed-enum peer — owned-
19019 // input mirror of the paired [`TryFrom<&str>`] str-view reverse-
19020 // projection axis, and string-owned reverse companion of the
19021 // pre-existing string-owned *forward*-projection pair
19022 // ([`From<RestartStrategy> for String`],
19023 // [`From<&RestartStrategy> for String`]) on this same enum. Peer
19024 // of the sibling opener
19025 // [`crate::aplicacao::tests::rate_limit_try_from_owned_string_routes_through_borrowed_str_view_axis`]
19026 // (a2e6f02) on the compound [`crate::aplicacao::RateLimit`]
19027 // primitive, the sibling first-mover
19028 // [`crate::aplicacao::tests::wit_shape_try_from_owned_string_routes_through_borrowed_str_view_axis`]
19029 // (e6aac29) on the [`crate::aplicacao::WitShape`] closed-set peer,
19030 // the sibling second-mover
19031 // [`crate::aplicacao::tests::rate_limit_unit_try_from_owned_string_routes_through_borrowed_str_view_axis`]
19032 // (94a9c5e) on the [`crate::aplicacao::RateLimitUnit`] peer, and
19033 // the sibling third-mover
19034 // [`crate::aplicacao::tests::placement_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
19035 // (d81a70a) on the [`crate::aplicacao::PlacementStrategy`] peer —
19036 // tracks the "delegate through `TryFrom<&str>` on the
19037 // `String::as_str` borrow" discipline the compound-primitive
19038 // opener and closed-set-peer first-mover established.
19039 //
19040 // Rust's standard library carries no blanket
19041 // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<String> for T`, so
19042 // an owned-`String` caller otherwise picks between an open-coded
19043 // `<T as TryFrom<&str>>::try_from(s.as_str())` at every call
19044 // site (whose type bounds have no compile-time link back to the
19045 // string-owned reverse-projection axis) or a `let s: &str = &s;
19046 // T::try_from(s)` two-step whose borrow arithmetic leaks a per-
19047 // call-site lifetime dance. This impl closes the string-owned
19048 // reverse-projection axis at the substrate-primitive
19049 // [`RestartStrategy::from_wire`] accessor so every future
19050 // `<T: TryFrom<String>>`-bound owned-string consumer reaches the
19051 // same four-arm `PascalCase` accept-set through one trait
19052 // dispatch.
19053 for &variant in RestartStrategy::ALL {
19054 let wire_string: String = variant.as_str().to_string();
19055 assert_eq!(
19056 <RestartStrategy as TryFrom<String>>::try_from(wire_string.clone()),
19057 Ok(variant),
19058 "TryFrom<String> impl on RestartStrategy must round-trip \
19059 RestartStrategy::{variant:?}.as_str().to_string() back \
19060 to Ok(RestartStrategy::{variant:?}) — divergence from \
19061 the sibling TryFrom<&str> axis signals a silent detour \
19062 off the substrate-primitive from_wire accessor"
19063 );
19064 // Cross-axis witness: the string-owned reverse-projection
19065 // axis must agree with the borrowed `&str` reverse-projection
19066 // axis on every accepted arm — the two axes share one
19067 // `PascalCase` wire vocabulary through the substrate-primitive
19068 // `from_wire` accessor, and the owned-input axis delegates to
19069 // the borrowed peer by design.
19070 let via_owned: Result<RestartStrategy, ()> =
19071 <RestartStrategy as TryFrom<String>>::try_from(wire_string.clone());
19072 let via_borrowed: Result<RestartStrategy, ()> =
19073 <RestartStrategy as TryFrom<&str>>::try_from(wire_string.as_str());
19074 assert_eq!(
19075 via_owned, via_borrowed,
19076 "TryFrom<String> and TryFrom<&str> reverse-projection \
19077 axes on RestartStrategy must agree on \
19078 RestartStrategy::{variant:?} — divergence signals the \
19079 owned-`String` and borrowed-`&str` reverse paths have \
19080 drifted off the same substrate-primitive from_wire \
19081 accessor"
19082 );
19083 // Cross-axis witness against the paired byte-view and byte-
19084 // owned reverse axes — the four reverse paths (str-view
19085 // borrowed, string-owned, byte-view borrowed, byte-owned)
19086 // share one substrate primitive.
19087 let via_bytes_borrowed: Result<RestartStrategy, ()> =
19088 <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_string.as_bytes());
19089 let via_bytes_owned: Result<RestartStrategy, ()> =
19090 <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_string.as_bytes().to_vec());
19091 assert_eq!(
19092 via_owned, via_bytes_borrowed,
19093 "TryFrom<String> and TryFrom<&[u8]> reverse-projection \
19094 axes on RestartStrategy must agree on \
19095 RestartStrategy::{variant:?} — divergence signals the \
19096 string-owned and byte-view reverse paths have drifted \
19097 off the same substrate-primitive from_wire accessor"
19098 );
19099 assert_eq!(
19100 via_owned, via_bytes_owned,
19101 "TryFrom<String> and TryFrom<Vec<u8>> reverse-projection \
19102 axes on RestartStrategy must agree on \
19103 RestartStrategy::{variant:?} — divergence signals the \
19104 string-owned and byte-owned reverse paths have drifted \
19105 off the same substrate-primitive from_wire accessor"
19106 );
19107 // Closed-cycle witness against the paired string-owned
19108 // forward-projection pair: `Self → String → TryFrom<String>
19109 // → Self` round-trips to the originating arm on every
19110 // canonical `PascalCase` scalar. Both the owned-input
19111 // `From<RestartStrategy> for String` and the borrowed-input
19112 // `From<&RestartStrategy> for String` corners must feed back
19113 // through the new impl to `Ok(variant)`.
19114 let owned_forward: String = <String as From<RestartStrategy>>::from(variant);
19115 let borrowed_forward: String = <String as From<&RestartStrategy>>::from(&variant);
19116 assert_eq!(
19117 owned_forward, wire_string,
19118 "From<RestartStrategy> for String forward projection on \
19119 RestartStrategy::{variant:?} must byte-equal \
19120 variant.as_str().to_string() — divergence signals the \
19121 paired forward pair drifted off the substrate-primitive \
19122 as_str accessor"
19123 );
19124 assert_eq!(
19125 borrowed_forward, wire_string,
19126 "From<&RestartStrategy> for String forward projection on \
19127 &RestartStrategy::{variant:?} must byte-equal \
19128 variant.as_str().to_string() — divergence signals the \
19129 paired forward pair drifted off the substrate-primitive \
19130 as_str accessor"
19131 );
19132 assert_eq!(
19133 <RestartStrategy as TryFrom<String>>::try_from(owned_forward.clone()),
19134 Ok(variant),
19135 "Closed-cycle round-trip on RestartStrategy::{variant:?} \
19136 through From<RestartStrategy> for String then \
19137 TryFrom<String> for RestartStrategy must return \
19138 Ok(variant) — divergence signals the string-owned \
19139 forward pair and the string-owned reverse axis have \
19140 drifted apart"
19141 );
19142 assert_eq!(
19143 <RestartStrategy as TryFrom<String>>::try_from(borrowed_forward),
19144 Ok(variant),
19145 "Closed-cycle round-trip on RestartStrategy::{variant:?} \
19146 through From<&RestartStrategy> for String then \
19147 TryFrom<String> for RestartStrategy must return \
19148 Ok(variant) — divergence signals the borrowed-input \
19149 forward corner and the owned-input string reverse \
19150 corner have drifted apart"
19151 );
19152 }
19153 }
19154
19155 #[test]
19156 fn restart_strategy_try_from_owned_string_rejects_unknown_wire_strings() {
19157 // Rejection witness on the `impl TryFrom<String> for
19158 // RestartStrategy` — sweeps the corpus of valid-UTF-8-but-
19159 // unknown-wire byte-strings the sibling borrowed [`TryFrom<&str>`]
19160 // axis already rejects and asserts every one lands on `Err(())`,
19161 // so a future accidental widening of the trait impl's accept-set
19162 // (a case-fold path, a silent inclusion of the kebab-case
19163 // dispatcher-catalog byte-strings on the sibling axis that would
19164 // collide the two-axis wire/catalog split the sibling
19165 // [`RestartStrategy::from_wire`] doc block makes load-bearing, a
19166 // stray fallback that maps whitespace-padded canonical scalars
19167 // onto their unpadded arm rather than the trait-idiomatic
19168 // `Err(())`) trips at caixa-core test time. Peer of the sibling
19169 // borrowed-input rejection witness
19170 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
19171 // on the same enum, and the sibling byte-view / byte-owned
19172 // rejection witnesses
19173 // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
19174 // (c699a83) /
19175 // [`restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
19176 // (34951fe) on the same enum.
19177 let unknown_wire_rejected: &[&str] = &[
19178 "",
19179 " ",
19180 "\n",
19181 "\t",
19182 "one-for-one",
19183 "one-for-all",
19184 "rest-for-one",
19185 "simple-one-for-one",
19186 "oneforone",
19187 "one_for_one",
19188 "OneForOnes",
19189 "ONEFORONE",
19190 "oneforall",
19191 "restforone",
19192 "simpleoneforone",
19193 "OneForOne ",
19194 " OneForOne",
19195 " OneForAll ",
19196 "OneForOne\n",
19197 "RestForOne\t",
19198 "OneForEach",
19199 "AllForOne",
19200 "one for one",
19201 "\"OneForOne\"",
19202 "?",
19203 ];
19204 for &input in unknown_wire_rejected {
19205 let owned: String = input.to_string();
19206 assert_eq!(
19207 <RestartStrategy as TryFrom<String>>::try_from(owned),
19208 Err(()),
19209 "TryFrom<String> impl on RestartStrategy must reject the \
19210 valid-UTF-8-but-unknown-wire byte-string {input:?} with \
19211 Err(()) — silent acceptance signals an accept-set \
19212 widening off the paired RestartStrategy::from_wire \
19213 resolver"
19214 );
19215 // Cross-axis witness against the borrowed str-view axis:
19216 // the two paths must agree by construction, since the owned
19217 // axis delegates to the borrowed peer.
19218 assert_eq!(
19219 <RestartStrategy as TryFrom<String>>::try_from(input.to_string()),
19220 <RestartStrategy as TryFrom<&str>>::try_from(input),
19221 "TryFrom<String> and TryFrom<&str> reverse-projection \
19222 axes on RestartStrategy must agree on the valid-UTF-8-\
19223 but-unknown-wire input {input:?} — divergence signals \
19224 the owned-`String` and borrowed-`&str` reverse paths \
19225 have drifted off the same substrate-primitive from_wire \
19226 accessor"
19227 );
19228 }
19229 }
19230
19231 #[test]
19232 fn restart_policy_try_from_owned_string_routes_through_borrowed_str_view_axis() {
19233 // Fail-before-pass-after byte-parity pin on the newly lifted
19234 // `impl TryFrom<String> for RestartPolicy` — asserts the trait-
19235 // idiomatic string-owned reverse-projection standard-library impl
19236 // and the sibling borrowed-input [`TryFrom<&str>`] axis resolve
19237 // to the same three-arm `PascalCase` wire accept-set across every
19238 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
19239 // Extends the substrate-wide trait-idiomatic string-owned reverse-
19240 // projection axis onto the second (and final) M2-OTP-shape
19241 // supervisor-slot closed-set fieldless typed-enum peer — owned-
19242 // input mirror of the paired [`TryFrom<&str>`] str-view reverse-
19243 // projection axis, and string-owned reverse companion of the
19244 // pre-existing string-owned *forward*-projection pair
19245 // ([`From<RestartPolicy> for String`],
19246 // [`From<&RestartPolicy> for String`]) on this same enum. Peer
19247 // of the sibling first-mover
19248 // [`crate::aplicacao::tests::rate_limit_try_from_owned_string_routes_through_borrowed_str_view_axis`]
19249 // (a2e6f02) on the compound [`crate::aplicacao::RateLimit`]
19250 // primitive, and the sibling
19251 // [`restart_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
19252 // (78fe8c8) on the sibling first M2-OTP-shape supervisor-slot
19253 // [`RestartStrategy`] peer — tracks the "delegate through
19254 // `TryFrom<&str>` on the `String::as_str` borrow" discipline the
19255 // compound-primitive opener and closed-set-peer first-mover
19256 // established. This closes the string-owned reverse-projection
19257 // axis on the M2-OTP-shape `:supervisor :estrategia` +
19258 // `:children :restart` slot pair.
19259 for &variant in RestartPolicy::ALL {
19260 let wire_string: String = variant.as_str().to_string();
19261 assert_eq!(
19262 <RestartPolicy as TryFrom<String>>::try_from(wire_string.clone()),
19263 Ok(variant),
19264 "TryFrom<String> impl on RestartPolicy must round-trip \
19265 RestartPolicy::{variant:?}.as_str().to_string() back \
19266 to Ok(RestartPolicy::{variant:?}) — divergence from \
19267 the sibling TryFrom<&str> axis signals a silent detour \
19268 off the substrate-primitive from_wire accessor"
19269 );
19270 // Cross-axis witness: the string-owned reverse-projection
19271 // axis must agree with the borrowed `&str` reverse-projection
19272 // axis on every accepted arm — the two axes share one
19273 // `PascalCase` wire vocabulary through the substrate-
19274 // primitive `from_wire` accessor, and the owned-input axis
19275 // delegates to the borrowed peer by design.
19276 let via_owned: Result<RestartPolicy, ()> =
19277 <RestartPolicy as TryFrom<String>>::try_from(wire_string.clone());
19278 let via_borrowed: Result<RestartPolicy, ()> =
19279 <RestartPolicy as TryFrom<&str>>::try_from(wire_string.as_str());
19280 assert_eq!(
19281 via_owned, via_borrowed,
19282 "TryFrom<String> and TryFrom<&str> reverse-projection \
19283 axes on RestartPolicy must agree on \
19284 RestartPolicy::{variant:?} — divergence signals the \
19285 owned-`String` and borrowed-`&str` reverse paths have \
19286 drifted off the same substrate-primitive from_wire \
19287 accessor"
19288 );
19289 // Cross-axis witness against the paired byte-view and byte-
19290 // owned reverse axes — the four reverse paths (str-view
19291 // borrowed, string-owned, byte-view borrowed, byte-owned)
19292 // share one substrate primitive.
19293 let via_bytes_borrowed: Result<RestartPolicy, ()> =
19294 <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_string.as_bytes());
19295 let via_bytes_owned: Result<RestartPolicy, ()> =
19296 <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_string.as_bytes().to_vec());
19297 assert_eq!(
19298 via_owned, via_bytes_borrowed,
19299 "TryFrom<String> and TryFrom<&[u8]> reverse-projection \
19300 axes on RestartPolicy must agree on \
19301 RestartPolicy::{variant:?} — divergence signals the \
19302 string-owned and byte-view reverse paths have drifted \
19303 off the same substrate-primitive from_wire accessor"
19304 );
19305 assert_eq!(
19306 via_owned, via_bytes_owned,
19307 "TryFrom<String> and TryFrom<Vec<u8>> reverse-projection \
19308 axes on RestartPolicy must agree on \
19309 RestartPolicy::{variant:?} — divergence signals the \
19310 string-owned and byte-owned reverse paths have drifted \
19311 off the same substrate-primitive from_wire accessor"
19312 );
19313 // Closed-cycle witness against the paired string-owned
19314 // forward-projection pair: `Self → String → TryFrom<String>
19315 // → Self` round-trips to the originating arm on every
19316 // canonical `PascalCase` scalar. Both the owned-input
19317 // `From<RestartPolicy> for String` and the borrowed-input
19318 // `From<&RestartPolicy> for String` corners must feed back
19319 // through the new impl to `Ok(variant)`.
19320 let owned_forward: String = <String as From<RestartPolicy>>::from(variant);
19321 let borrowed_forward: String = <String as From<&RestartPolicy>>::from(&variant);
19322 assert_eq!(
19323 owned_forward, wire_string,
19324 "From<RestartPolicy> for String forward projection on \
19325 RestartPolicy::{variant:?} must byte-equal \
19326 variant.as_str().to_string() — divergence signals the \
19327 paired forward pair drifted off the substrate-primitive \
19328 as_str accessor"
19329 );
19330 assert_eq!(
19331 borrowed_forward, wire_string,
19332 "From<&RestartPolicy> for String forward projection on \
19333 &RestartPolicy::{variant:?} must byte-equal \
19334 variant.as_str().to_string() — divergence signals the \
19335 paired forward pair drifted off the substrate-primitive \
19336 as_str accessor"
19337 );
19338 assert_eq!(
19339 <RestartPolicy as TryFrom<String>>::try_from(owned_forward.clone()),
19340 Ok(variant),
19341 "Closed-cycle round-trip on RestartPolicy::{variant:?} \
19342 through From<RestartPolicy> for String then \
19343 TryFrom<String> for RestartPolicy must return \
19344 Ok(variant) — divergence signals the string-owned \
19345 forward pair and the string-owned reverse axis have \
19346 drifted apart"
19347 );
19348 assert_eq!(
19349 <RestartPolicy as TryFrom<String>>::try_from(borrowed_forward),
19350 Ok(variant),
19351 "Closed-cycle round-trip on RestartPolicy::{variant:?} \
19352 through From<&RestartPolicy> for String then \
19353 TryFrom<String> for RestartPolicy must return \
19354 Ok(variant) — divergence signals the borrowed-input \
19355 forward corner and the owned-input string reverse \
19356 corner have drifted apart"
19357 );
19358 }
19359 }
19360
19361 #[test]
19362 fn restart_policy_try_from_owned_string_rejects_unknown_wire_strings() {
19363 // Rejection witness on the `impl TryFrom<String> for
19364 // RestartPolicy` — sweeps the corpus of valid-UTF-8-but-
19365 // unknown-wire byte-strings the sibling borrowed [`TryFrom<&str>`]
19366 // axis already rejects and asserts every one lands on `Err(())`,
19367 // so a future accidental widening of the trait impl's accept-set
19368 // (a case-fold path, a silent inclusion of the kebab-case
19369 // dispatcher-catalog byte-strings on the sibling axis that would
19370 // collide the two-axis wire/catalog split the sibling
19371 // [`RestartPolicy::from_wire`] doc block makes load-bearing, a
19372 // stray fallback that maps whitespace-padded canonical scalars
19373 // onto their unpadded arm rather than the trait-idiomatic
19374 // `Err(())`) trips at caixa-core test time. Peer of the sibling
19375 // borrowed-input rejection witness
19376 // [`restart_policy_try_from_str_rejects_unknown_byte_strings`]
19377 // on the same enum, and the sibling byte-view / byte-owned
19378 // rejection witnesses
19379 // [`restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
19380 // (d9ef5f0) /
19381 // [`restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
19382 // (7592085) on the same enum.
19383 let unknown_wire_rejected: &[&str] = &[
19384 "",
19385 " ",
19386 "\n",
19387 "\t",
19388 "permanent",
19389 "temporary",
19390 "transient",
19391 "PERMANENT",
19392 "TEMPORARY",
19393 "TRANSIENT",
19394 "Permanents",
19395 "Permanent ",
19396 " Permanent",
19397 " Temporary ",
19398 "Permanent\n",
19399 "Transient\t",
19400 "\"Permanent\"",
19401 "Ephemeral",
19402 "Always",
19403 "Never",
19404 "OnAbnormalExit",
19405 "intrinsic",
19406 "?",
19407 ];
19408 for &input in unknown_wire_rejected {
19409 let owned: String = input.to_string();
19410 assert_eq!(
19411 <RestartPolicy as TryFrom<String>>::try_from(owned),
19412 Err(()),
19413 "TryFrom<String> impl on RestartPolicy must reject the \
19414 valid-UTF-8-but-unknown-wire byte-string {input:?} with \
19415 Err(()) — silent acceptance signals an accept-set \
19416 widening off the paired RestartPolicy::from_wire \
19417 resolver"
19418 );
19419 // Cross-axis witness against the borrowed str-view axis:
19420 // the two paths must agree by construction, since the owned
19421 // axis delegates to the borrowed peer.
19422 assert_eq!(
19423 <RestartPolicy as TryFrom<String>>::try_from(input.to_string()),
19424 <RestartPolicy as TryFrom<&str>>::try_from(input),
19425 "TryFrom<String> and TryFrom<&str> reverse-projection \
19426 axes on RestartPolicy must agree on the valid-UTF-8-\
19427 but-unknown-wire input {input:?} — divergence signals \
19428 the owned-`String` and borrowed-`&str` reverse paths \
19429 have drifted off the same substrate-primitive from_wire \
19430 accessor"
19431 );
19432 }
19433 }
19434
19435 #[test]
19436 fn restart_strategy_from_into_owned_box_bytes_routes_through_as_str_accessor() {
19437 // Fail-before-pass-after byte-parity pin on the newly lifted
19438 // `impl From<RestartStrategy> for Box<[u8]>` — asserts the
19439 // owned-input byte-owned reverse projection routes through the
19440 // substrate-primitive [`super::RestartStrategy::as_str`]
19441 // `pub const fn` accessor's `.as_bytes()` byte-view via
19442 // [`Box::<[u8]>::from`] on the returned `&'static [u8]` and
19443 // resolves to the same four-arm PascalCase wire byte-string
19444 // emit-set across every arm the exhaustive
19445 // [`super::RestartStrategy::ALL`] slice enumerates. Refuses any
19446 // future silent detour that would swap
19447 // `Box::<[u8]>::from(strategy.as_str().as_bytes())` for a
19448 // `Vec::<u8>::from(strategy).into_boxed_slice()` double-hop, a
19449 // routing through the sibling `fmt::Display` emitter, or a stray
19450 // normalization step that would drop or rebrand a canonical
19451 // PascalCase arm ahead of the boxed byte-emit. Cross-axis
19452 // partition against the paired owned-input byte-owned reverse-
19453 // projection axes ([`Vec<u8>`], [`Cow<'static, [u8]>`]) and the
19454 // paired string-side [`Box<str>`] forward-projection axis on the
19455 // same primitive — all four routes must byte-agree on every arm,
19456 // otherwise the byte-owned reverse-projection matrix has drifted
19457 // off the shared substrate-primitive `as_str` accessor.
19458 for &variant in RestartStrategy::ALL {
19459 let via_owned_from: Box<[u8]> = <Box<[u8]> as From<RestartStrategy>>::from(variant);
19460 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
19461 assert_eq!(
19462 via_owned_from.as_ref(),
19463 via_method_bytes,
19464 "From<RestartStrategy> for Box<[u8]> impl must byte-\
19465 equal RestartStrategy::as_str().as_bytes() on \
19466 RestartStrategy::{variant:?} — divergence signals a \
19467 silent detour off the substrate-primitive accessor"
19468 );
19469 // Cross-axis partition against the paired owned-input
19470 // `Vec<u8>` (98d38ed) and `Cow<'static, [u8]>` (7f81539)
19471 // byte-owned reverse-projection axes on the same enum — all
19472 // three axes must byte-agree on every arm.
19473 let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
19474 let via_cow_bytes: std::borrow::Cow<'static, [u8]> =
19475 <std::borrow::Cow<'static, [u8]> as From<RestartStrategy>>::from(variant);
19476 assert_eq!(
19477 via_owned_from.as_ref(),
19478 via_vec_bytes.as_slice(),
19479 "From<RestartStrategy> for Box<[u8]> and \
19480 From<RestartStrategy> for Vec<u8> must byte-agree on \
19481 RestartStrategy::{variant:?} — divergence signals the \
19482 owned-input byte-owned reverse-projection axes have \
19483 drifted off the same substrate-primitive as_str \
19484 accessor"
19485 );
19486 assert_eq!(
19487 via_owned_from.as_ref(),
19488 via_cow_bytes.as_ref(),
19489 "From<RestartStrategy> for Box<[u8]> and \
19490 From<RestartStrategy> for Cow<'static, [u8]> must \
19491 byte-agree on RestartStrategy::{variant:?} — \
19492 divergence signals the owned-input byte-owned reverse-\
19493 projection axes have drifted off the same substrate-\
19494 primitive as_str accessor"
19495 );
19496 // Cross-axis partition against the paired string-side
19497 // `Box<str>` (69ef45c) forward-projection axis on the same
19498 // enum — the byte-side and str-side `Box<_>` axes must byte-
19499 // agree on every arm (both route through Self::as_str's
19500 // `&'static str` return).
19501 let via_box_str: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
19502 assert_eq!(
19503 via_owned_from.as_ref(),
19504 via_box_str.as_bytes(),
19505 "From<RestartStrategy> for Box<[u8]> and \
19506 From<RestartStrategy> for Box<str> must byte-agree on \
19507 RestartStrategy::{variant:?} — divergence signals a \
19508 silent detour off the shared substrate-primitive \
19509 as_str accessor"
19510 );
19511 }
19512 }
19513
19514 #[test]
19515 fn restart_strategy_from_borrowed_into_owned_box_bytes_routes_through_as_str_accessor() {
19516 // Fail-before-pass-after byte-parity pin on the newly lifted
19517 // `impl From<&RestartStrategy> for Box<[u8]>` — asserts the
19518 // borrowed-input byte-owned reverse projection routes byte-for-
19519 // byte through the substrate-primitive
19520 // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
19521 // `.as_bytes()` byte-view via [`Box::<[u8]>::from`] on the
19522 // returned `&'static [u8]` on every arm the exhaustive
19523 // [`super::RestartStrategy::ALL`] slice enumerates, preserving
19524 // the source [`super::RestartStrategy`] intact (no move-out).
19525 // Additionally asserts the paired owned-input and borrowed-input
19526 // corners byte-agree on the same arm, closing the
19527 // `{Self, &Self} → Box<[u8]>` byte-owned reverse-projection
19528 // family on this primitive.
19529 //
19530 // Generic `<T: Into<Box<[u8]>>>`-bound consumer witness helper:
19531 // a future per-supervisor byte-writer that accepts a
19532 // [`Box<[u8]>`] composes on both owned and borrowed input shapes
19533 // without an open-coded `Box::<[u8]>::from(strategy.as_str().
19534 // as_bytes())` at every call site. Lifted to the top of the
19535 // function per `clippy::items_after_statements`.
19536 fn generic_box_bytes_sink<T: Into<Box<[u8]>>>(t: T) -> Box<[u8]> {
19537 t.into()
19538 }
19539 for &variant in RestartStrategy::ALL {
19540 let via_borrowed_from: Box<[u8]> =
19541 <Box<[u8]> as From<&RestartStrategy>>::from(&variant);
19542 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
19543 assert_eq!(
19544 via_borrowed_from.as_ref(),
19545 via_method_bytes,
19546 "From<&RestartStrategy> for Box<[u8]> impl must byte-\
19547 equal RestartStrategy::as_str().as_bytes() on \
19548 &RestartStrategy::{variant:?} — divergence signals a \
19549 silent detour off the substrate-primitive accessor"
19550 );
19551 // The borrowed-input impl must not move out of the source —
19552 // the source RestartStrategy must survive the projection.
19553 let survivor: &'static str = variant.as_str();
19554 assert_eq!(
19555 survivor.as_bytes(),
19556 via_method_bytes,
19557 "source &RestartStrategy::{variant:?} must survive \
19558 borrowed-input projection — a move-out here signals \
19559 the impl silently dereferences past the borrowed \
19560 handle"
19561 );
19562 // Cross-corner partition against the paired owned-input
19563 // `Box<[u8]>` axis on the same enum — the two corners must
19564 // byte-agree on every arm, closing the "owned-input move
19565 // vs. borrowed-input clone" bifurcation on the same wire
19566 // byte-string through the `Box<[u8]>` axis.
19567 let via_owned_from: Box<[u8]> = <Box<[u8]> as From<RestartStrategy>>::from(variant);
19568 assert_eq!(
19569 via_borrowed_from.as_ref(),
19570 via_owned_from.as_ref(),
19571 "From<&RestartStrategy> for Box<[u8]> and \
19572 From<RestartStrategy> for Box<[u8]> must byte-agree on \
19573 RestartStrategy::{variant:?} — divergence signals the \
19574 paired owned-input and borrowed-input corners have \
19575 drifted off the same substrate-primitive as_str \
19576 accessor"
19577 );
19578 let owned_via_generic = generic_box_bytes_sink(variant);
19579 let variant_ref: &RestartStrategy = &variant;
19580 let borrowed_via_generic = generic_box_bytes_sink(variant_ref);
19581 assert_eq!(
19582 owned_via_generic.as_ref(),
19583 via_method_bytes,
19584 "<T: Into<Box<[u8]>>>-bound composition on \
19585 RestartStrategy::{variant:?} must fold the same byte-\
19586 tail RestartStrategy::as_str().as_bytes() returns"
19587 );
19588 assert_eq!(
19589 borrowed_via_generic.as_ref(),
19590 via_method_bytes,
19591 "<T: Into<Box<[u8]>>>-bound composition on \
19592 &RestartStrategy::{variant:?} must fold the same byte-\
19593 tail RestartStrategy::as_str().as_bytes() returns"
19594 );
19595 }
19596 }
19597
19598 #[test]
19599 fn restart_strategy_from_into_owned_arc_bytes_routes_through_as_str_accessor() {
19600 // Fail-before-pass-after byte-parity pin on the newly lifted
19601 // `impl From<RestartStrategy> for std::sync::Arc<[u8]>` — asserts
19602 // the owned-input byte-owned reverse projection routes through the
19603 // substrate-primitive [`super::RestartStrategy::as_str`]
19604 // `pub const fn` accessor's `.as_bytes()` byte-view via
19605 // [`std::sync::Arc::<[u8]>::from`] on the returned `&'static [u8]`
19606 // and resolves to the same four-arm PascalCase wire byte-string
19607 // emit-set across every arm the exhaustive
19608 // [`super::RestartStrategy::ALL`] slice enumerates. Refuses any
19609 // future silent detour that would swap the substrate-primitive
19610 // routing for a `Box::<[u8]>::from(strategy).into()` double-hop,
19611 // a routing through the sibling `fmt::Display` emitter, or a stray
19612 // normalization step that would drop or rebrand a canonical
19613 // PascalCase arm ahead of the atomic-refcounted byte-emit. Cross-
19614 // axis partition against the paired owned-input byte-owned reverse-
19615 // projection axes ([`Vec<u8>`], [`Cow<'static, [u8]>`], and
19616 // [`Box<[u8]>`]) on the same primitive — all four routes must byte-
19617 // agree on every arm, otherwise the byte-owned reverse-projection
19618 // matrix has drifted off the shared substrate-primitive `as_str`
19619 // accessor.
19620 for &variant in RestartStrategy::ALL {
19621 let via_owned_from: std::sync::Arc<[u8]> =
19622 <std::sync::Arc<[u8]> as From<RestartStrategy>>::from(variant);
19623 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
19624 assert_eq!(
19625 via_owned_from.as_ref(),
19626 via_method_bytes,
19627 "From<RestartStrategy> for Arc<[u8]> impl must byte-\
19628 equal RestartStrategy::as_str().as_bytes() on \
19629 RestartStrategy::{variant:?} — divergence signals a \
19630 silent detour off the substrate-primitive accessor"
19631 );
19632 // Cross-axis partition against the paired owned-input
19633 // `Vec<u8>`, `Cow<'static, [u8]>`, and `Box<[u8]>` byte-owned
19634 // reverse-projection axes on the same enum — all four axes
19635 // must byte-agree on every arm.
19636 let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
19637 let via_cow_bytes: std::borrow::Cow<'static, [u8]> =
19638 <std::borrow::Cow<'static, [u8]> as From<RestartStrategy>>::from(variant);
19639 let via_box_bytes: Box<[u8]> = <Box<[u8]> as From<RestartStrategy>>::from(variant);
19640 assert_eq!(
19641 via_owned_from.as_ref(),
19642 via_vec_bytes.as_slice(),
19643 "From<RestartStrategy> for Arc<[u8]> and \
19644 From<RestartStrategy> for Vec<u8> must byte-agree on \
19645 RestartStrategy::{variant:?} — divergence signals the \
19646 owned-input byte-owned reverse-projection axes have \
19647 drifted off the same substrate-primitive as_str \
19648 accessor"
19649 );
19650 assert_eq!(
19651 via_owned_from.as_ref(),
19652 via_cow_bytes.as_ref(),
19653 "From<RestartStrategy> for Arc<[u8]> and \
19654 From<RestartStrategy> for Cow<'static, [u8]> must byte-\
19655 agree on RestartStrategy::{variant:?} — divergence \
19656 signals the owned-input byte-owned reverse-projection \
19657 axes have drifted off the same substrate-primitive \
19658 as_str accessor"
19659 );
19660 assert_eq!(
19661 via_owned_from.as_ref(),
19662 via_box_bytes.as_ref(),
19663 "From<RestartStrategy> for Arc<[u8]> and \
19664 From<RestartStrategy> for Box<[u8]> must byte-agree on \
19665 RestartStrategy::{variant:?} — divergence signals the \
19666 owned-input byte-owned reverse-projection axes have \
19667 drifted off the same substrate-primitive as_str \
19668 accessor"
19669 );
19670 }
19671 }
19672
19673 #[test]
19674 fn restart_strategy_from_borrowed_into_owned_arc_bytes_routes_through_as_str_accessor() {
19675 // Fail-before-pass-after byte-parity pin on the newly lifted
19676 // `impl From<&RestartStrategy> for std::sync::Arc<[u8]>` — asserts
19677 // the borrowed-input byte-owned reverse projection routes byte-
19678 // for-byte through the substrate-primitive
19679 // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
19680 // `.as_bytes()` byte-view via [`std::sync::Arc::<[u8]>::from`] on
19681 // the returned `&'static [u8]` on every arm the exhaustive
19682 // [`super::RestartStrategy::ALL`] slice enumerates, preserving
19683 // the source [`super::RestartStrategy`] intact (no move-out).
19684 // Additionally asserts the paired owned-input and borrowed-input
19685 // corners byte-agree on the same arm, closing the
19686 // `{Self, &Self} → std::sync::Arc<[u8]>` byte-owned reverse-
19687 // projection family on this primitive.
19688 //
19689 // Generic `<T: Into<std::sync::Arc<[u8]>>>`-bound consumer witness
19690 // helper: a future per-supervisor byte-writer that accepts a
19691 // [`std::sync::Arc<[u8]>`] composes on both owned and borrowed
19692 // input shapes without an open-coded
19693 // `std::sync::Arc::<[u8]>::from(strategy.as_str().as_bytes())` at
19694 // every call site. Lifted to the top of the function per
19695 // `clippy::items_after_statements`.
19696 fn generic_arc_bytes_sink<T: Into<std::sync::Arc<[u8]>>>(t: T) -> std::sync::Arc<[u8]> {
19697 t.into()
19698 }
19699 for &variant in RestartStrategy::ALL {
19700 let via_borrowed_from: std::sync::Arc<[u8]> =
19701 <std::sync::Arc<[u8]> as From<&RestartStrategy>>::from(&variant);
19702 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
19703 assert_eq!(
19704 via_borrowed_from.as_ref(),
19705 via_method_bytes,
19706 "From<&RestartStrategy> for Arc<[u8]> impl must byte-\
19707 equal RestartStrategy::as_str().as_bytes() on \
19708 &RestartStrategy::{variant:?} — divergence signals a \
19709 silent detour off the substrate-primitive accessor"
19710 );
19711 // The borrowed-input impl must not move out of the source —
19712 // the source RestartStrategy must survive the projection.
19713 let survivor: &'static str = variant.as_str();
19714 assert_eq!(
19715 survivor.as_bytes(),
19716 via_method_bytes,
19717 "source &RestartStrategy::{variant:?} must survive \
19718 borrowed-input projection — a move-out here signals \
19719 the impl silently dereferences past the borrowed \
19720 handle"
19721 );
19722 // Cross-corner partition against the paired owned-input
19723 // `Arc<[u8]>` axis on the same enum — the two corners must
19724 // byte-agree on every arm, closing the "owned-input move
19725 // vs. borrowed-input clone" bifurcation on the same wire
19726 // byte-string through the `Arc<[u8]>` axis.
19727 let via_owned_from: std::sync::Arc<[u8]> =
19728 <std::sync::Arc<[u8]> as From<RestartStrategy>>::from(variant);
19729 assert_eq!(
19730 via_borrowed_from.as_ref(),
19731 via_owned_from.as_ref(),
19732 "From<&RestartStrategy> for Arc<[u8]> and \
19733 From<RestartStrategy> for Arc<[u8]> must byte-agree on \
19734 RestartStrategy::{variant:?} — divergence signals the \
19735 paired owned-input and borrowed-input corners have \
19736 drifted off the same substrate-primitive as_str \
19737 accessor"
19738 );
19739 let owned_via_generic = generic_arc_bytes_sink(variant);
19740 let variant_ref: &RestartStrategy = &variant;
19741 let borrowed_via_generic = generic_arc_bytes_sink(variant_ref);
19742 assert_eq!(
19743 owned_via_generic.as_ref(),
19744 via_method_bytes,
19745 "<T: Into<Arc<[u8]>>>-bound composition on \
19746 RestartStrategy::{variant:?} must fold the same byte-\
19747 tail RestartStrategy::as_str().as_bytes() returns"
19748 );
19749 assert_eq!(
19750 borrowed_via_generic.as_ref(),
19751 via_method_bytes,
19752 "<T: Into<Arc<[u8]>>>-bound composition on \
19753 &RestartStrategy::{variant:?} must fold the same byte-\
19754 tail RestartStrategy::as_str().as_bytes() returns"
19755 );
19756 }
19757 }
19758
19759 #[test]
19760 fn restart_strategy_from_into_owned_rc_bytes_routes_through_as_str_accessor() {
19761 // Fail-before-pass-after byte-parity pin on the newly lifted
19762 // `impl From<RestartStrategy> for std::rc::Rc<[u8]>` — asserts the
19763 // owned-input byte-owned reverse projection routes through the
19764 // substrate-primitive [`super::RestartStrategy::as_str`]
19765 // `pub const fn` accessor's `.as_bytes()` byte-view via
19766 // [`std::rc::Rc::<[u8]>::from`] on the returned `&'static [u8]`
19767 // and resolves to the same four-arm PascalCase wire byte-string
19768 // emit-set across every arm the exhaustive
19769 // [`super::RestartStrategy::ALL`] slice enumerates. Refuses any
19770 // future silent detour that would swap the substrate-primitive
19771 // routing for a `Box::<[u8]>::from(strategy).into()` /
19772 // `Rc::<[u8]>::from(Vec::<u8>::from(strategy))` double-hop, a
19773 // routing through the sibling `fmt::Display` emitter, or a stray
19774 // normalization step that would drop or rebrand a canonical
19775 // PascalCase arm ahead of the single-threaded-refcounted byte-
19776 // emit. Cross-axis partition against the paired owned-input
19777 // byte-owned reverse-projection axes ([`Vec<u8>`],
19778 // [`Cow<'static, [u8]>`], [`Box<[u8]>`], and
19779 // [`std::sync::Arc<[u8]>`]) on the same primitive — all five
19780 // routes must byte-agree on every arm, otherwise the byte-owned
19781 // reverse-projection matrix has drifted off the shared substrate-
19782 // primitive `as_str` accessor.
19783 for &variant in RestartStrategy::ALL {
19784 let via_owned_from: std::rc::Rc<[u8]> =
19785 <std::rc::Rc<[u8]> as From<RestartStrategy>>::from(variant);
19786 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
19787 assert_eq!(
19788 via_owned_from.as_ref(),
19789 via_method_bytes,
19790 "From<RestartStrategy> for Rc<[u8]> impl must byte-\
19791 equal RestartStrategy::as_str().as_bytes() on \
19792 RestartStrategy::{variant:?} — divergence signals a \
19793 silent detour off the substrate-primitive accessor"
19794 );
19795 // Cross-axis partition against the paired owned-input
19796 // `Vec<u8>`, `Cow<'static, [u8]>`, `Box<[u8]>`, and
19797 // `Arc<[u8]>` byte-owned reverse-projection axes on the same
19798 // enum — all five axes must byte-agree on every arm, closing
19799 // the five-corner "owned-input into Vec/Cow/Box/Arc/Rc"
19800 // partition on the same wire byte-string.
19801 let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
19802 let via_cow_bytes: std::borrow::Cow<'static, [u8]> =
19803 <std::borrow::Cow<'static, [u8]> as From<RestartStrategy>>::from(variant);
19804 let via_box_bytes: Box<[u8]> = <Box<[u8]> as From<RestartStrategy>>::from(variant);
19805 let via_arc_bytes: std::sync::Arc<[u8]> =
19806 <std::sync::Arc<[u8]> as From<RestartStrategy>>::from(variant);
19807 assert_eq!(
19808 via_owned_from.as_ref(),
19809 via_vec_bytes.as_slice(),
19810 "From<RestartStrategy> for Rc<[u8]> and \
19811 From<RestartStrategy> for Vec<u8> must byte-agree on \
19812 RestartStrategy::{variant:?} — divergence signals the \
19813 owned-input byte-owned reverse-projection axes have \
19814 drifted off the same substrate-primitive as_str \
19815 accessor"
19816 );
19817 assert_eq!(
19818 via_owned_from.as_ref(),
19819 via_cow_bytes.as_ref(),
19820 "From<RestartStrategy> for Rc<[u8]> and \
19821 From<RestartStrategy> for Cow<'static, [u8]> must byte-\
19822 agree on RestartStrategy::{variant:?} — divergence \
19823 signals the owned-input byte-owned reverse-projection \
19824 axes have drifted off the same substrate-primitive \
19825 as_str accessor"
19826 );
19827 assert_eq!(
19828 via_owned_from.as_ref(),
19829 via_box_bytes.as_ref(),
19830 "From<RestartStrategy> for Rc<[u8]> and \
19831 From<RestartStrategy> for Box<[u8]> must byte-agree on \
19832 RestartStrategy::{variant:?} — divergence signals the \
19833 owned-input byte-owned reverse-projection axes have \
19834 drifted off the same substrate-primitive as_str \
19835 accessor"
19836 );
19837 assert_eq!(
19838 via_owned_from.as_ref(),
19839 via_arc_bytes.as_ref(),
19840 "From<RestartStrategy> for Rc<[u8]> and \
19841 From<RestartStrategy> for Arc<[u8]> must byte-agree on \
19842 RestartStrategy::{variant:?} — divergence signals the \
19843 owned-input byte-owned reverse-projection axes have \
19844 drifted off the same substrate-primitive as_str \
19845 accessor"
19846 );
19847 }
19848 }
19849
19850 #[test]
19851 fn restart_strategy_from_borrowed_into_owned_rc_bytes_routes_through_as_str_accessor() {
19852 // Fail-before-pass-after byte-parity pin on the newly lifted
19853 // `impl From<&RestartStrategy> for std::rc::Rc<[u8]>` — asserts
19854 // the borrowed-input byte-owned reverse projection routes byte-
19855 // for-byte through the substrate-primitive
19856 // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
19857 // `.as_bytes()` byte-view via [`std::rc::Rc::<[u8]>::from`] on the
19858 // returned `&'static [u8]` on every arm the exhaustive
19859 // [`super::RestartStrategy::ALL`] slice enumerates, preserving the
19860 // source [`super::RestartStrategy`] intact (no move-out).
19861 // Additionally asserts the paired owned-input and borrowed-input
19862 // corners byte-agree on the same arm, closing the
19863 // `{Self, &Self} → std::rc::Rc<[u8]>` byte-owned reverse-
19864 // projection family on this primitive.
19865 //
19866 // Generic `<T: Into<std::rc::Rc<[u8]>>>`-bound consumer witness
19867 // helper: a future per-supervisor byte-writer that accepts a
19868 // [`std::rc::Rc<[u8]>`] composes on both owned and borrowed input
19869 // shapes without an open-coded
19870 // `std::rc::Rc::<[u8]>::from(strategy.as_str().as_bytes())` at
19871 // every call site. Lifted to the top of the function per
19872 // `clippy::items_after_statements`.
19873 fn generic_rc_bytes_sink<T: Into<std::rc::Rc<[u8]>>>(t: T) -> std::rc::Rc<[u8]> {
19874 t.into()
19875 }
19876 for &variant in RestartStrategy::ALL {
19877 let via_borrowed_from: std::rc::Rc<[u8]> =
19878 <std::rc::Rc<[u8]> as From<&RestartStrategy>>::from(&variant);
19879 let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
19880 assert_eq!(
19881 via_borrowed_from.as_ref(),
19882 via_method_bytes,
19883 "From<&RestartStrategy> for Rc<[u8]> impl must byte-\
19884 equal RestartStrategy::as_str().as_bytes() on \
19885 &RestartStrategy::{variant:?} — divergence signals a \
19886 silent detour off the substrate-primitive accessor"
19887 );
19888 // The borrowed-input impl must not move out of the source —
19889 // the source RestartStrategy must survive the projection.
19890 let survivor: &'static str = variant.as_str();
19891 assert_eq!(
19892 survivor.as_bytes(),
19893 via_method_bytes,
19894 "source &RestartStrategy::{variant:?} must survive \
19895 borrowed-input projection — a move-out here signals \
19896 the impl silently dereferences past the borrowed \
19897 handle"
19898 );
19899 // Cross-corner partition against the paired owned-input
19900 // `Rc<[u8]>` axis on the same enum — the two corners must
19901 // byte-agree on every arm, closing the "owned-input move
19902 // vs. borrowed-input clone" bifurcation on the same wire
19903 // byte-string through the `Rc<[u8]>` axis.
19904 let via_owned_from: std::rc::Rc<[u8]> =
19905 <std::rc::Rc<[u8]> as From<RestartStrategy>>::from(variant);
19906 assert_eq!(
19907 via_borrowed_from.as_ref(),
19908 via_owned_from.as_ref(),
19909 "From<&RestartStrategy> for Rc<[u8]> and \
19910 From<RestartStrategy> for Rc<[u8]> must byte-agree on \
19911 RestartStrategy::{variant:?} — divergence signals the \
19912 paired owned-input and borrowed-input corners have \
19913 drifted off the same substrate-primitive as_str \
19914 accessor"
19915 );
19916 let owned_via_generic = generic_rc_bytes_sink(variant);
19917 let variant_ref: &RestartStrategy = &variant;
19918 let borrowed_via_generic = generic_rc_bytes_sink(variant_ref);
19919 assert_eq!(
19920 owned_via_generic.as_ref(),
19921 via_method_bytes,
19922 "<T: Into<Rc<[u8]>>>-bound composition on \
19923 RestartStrategy::{variant:?} must fold the same byte-\
19924 tail RestartStrategy::as_str().as_bytes() returns"
19925 );
19926 assert_eq!(
19927 borrowed_via_generic.as_ref(),
19928 via_method_bytes,
19929 "<T: Into<Rc<[u8]>>>-bound composition on \
19930 &RestartStrategy::{variant:?} must fold the same byte-\
19931 tail RestartStrategy::as_str().as_bytes() returns"
19932 );
19933 }
19934 }
19935}