caixa_core/supervisor.rs
1//! OTP-shaped supervisor trees, encoded as a typed `:kind Supervisor`
2//! caixa with a strategy + restart-policy children list.
3//!
4//! See `theory/INSPIRATIONS.md` §II.2 + §III.2 for the prior-art frame
5//! (Erlang OTP supervisor + Lunatic supervisor strategies as Rust types).
6//!
7//! ```lisp
8//! (defcaixa
9//! :nome "my-app-root"
10//! :versao "0.1.0"
11//! :kind Supervisor
12//! :estrategia OneForOne
13//! :max-restarts 5
14//! :restart-window "60s"
15//! :children ((:caixa "worker" :versao "^0.1" :restart Permanent)
16//! (:caixa "cache-server" :versao "^0.1" :restart Transient)
17//! (:caixa "scratch-job" :versao "^0.1" :restart Temporary)))
18//! ```
19//!
20//! wasm-operator (M3) walks the tree, materializes one ComputeUnit per
21//! child, and applies the strategy on child failure. The Rust types
22//! here are the typed contract; the runtime owns lifecycle.
23
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27use thiserror::Error;
28
29/// One of the four canonical Erlang/OTP restart strategies.
30///
31/// The strategy decides what happens to *sibling* children when one
32/// child dies. Per-child behaviour is governed by [`RestartPolicy`].
33#[derive(
34 Serialize,
35 Deserialize,
36 Debug,
37 Clone,
38 Copy,
39 PartialEq,
40 Eq,
41 Hash,
42 gen_platform::TypedDispatcher,
43 gen_platform::Discriminant,
44 gen_platform::IsVariant,
45 gen_platform::FromStrKind,
46)]
47pub enum RestartStrategy {
48 /// On child failure, restart only that child. Default; matches
49 /// most "tree of independent workers" use cases.
50 OneForOne,
51 /// On child failure, restart every child. Used when children
52 /// share state and must be in sync.
53 OneForAll,
54 /// On child failure, restart the failed child and every child
55 /// started *after* it (preserving startup order). Used when later
56 /// children depend on earlier ones.
57 RestForOne,
58 /// Dynamic children of the same shape, started on demand. The
59 /// supervisor doesn't know its children at boot; they're added as
60 /// they're needed (e.g. one child per session).
61 SimpleOneForOne,
62}
63
64impl Default for RestartStrategy {
65 fn default() -> Self {
66 // Route the [`Default for RestartStrategy`] impl through the
67 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
68 // `pub const` rather than a raw `Self::OneForOne` arm — one
69 // source of truth for the Erlang/OTP `one_for_one` half of Learn
70 // You Some Erlang's `{one_for_one, intensity, 5, 60}` worker-
71 // supervisor canonical default, paired with the sibling
72 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `MaxIntensity` half (b698ec0)
73 // and `SUPERVISOR_RESTART_WINDOW_DEFAULT` `Period` half (f7dcd0e).
74 // Pinned by `restart_strategy_default_routes_through_lifted_default`.
75 SUPERVISOR_ESTRATEGIA_DEFAULT
76 }
77}
78
79impl RestartStrategy {
80 /// Exhaustive iteration surface for every consumer that walks the
81 /// closed four-arm [`RestartStrategy`] discriminator set (the future
82 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
83 /// admission-webhook rejection body naming the accepted-`:estrategia`
84 /// list, a future `feira supervisor --estrategia …` CLI arg-parse's
85 /// "did you mean" hint via a [`Self::from_wire`]-scan over the slice,
86 /// the future `feira app graph` per-supervisor `:estrategia` column,
87 /// any future round-trip fuzz harness that sweeps every arm). A
88 /// future arm addition (an OTP-`rest_for_all` arm the theory
89 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
90 /// might reach for once the four canonical OTP strategies stop
91 /// covering the substrate's discovered load-shape) extends this
92 /// slice as one edit and every consumer picks up the new entry by
93 /// construction; the compiler-checked exhaustiveness on the sibling
94 /// method `match` arms ([`Self::as_str`] / [`Self::from_wire`]) is
95 /// the build-time guarantee that no arm forgets to grow.
96 ///
97 /// Peer of the sibling closed-set typed enums'
98 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
99 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
100 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
101 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
102 /// surfaces — the fifth (and the first M2 OTP-shape) closed-set
103 /// typed enum on the caixa surface to converge onto the same
104 /// one-canonical-arm-list-per-enum discipline.
105 pub const ALL: &'static [Self] = &[
106 Self::OneForOne,
107 Self::OneForAll,
108 Self::RestForOne,
109 Self::SimpleOneForOne,
110 ];
111
112 /// Canonical PascalCase discriminator scalar this variant serializes
113 /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
114 /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
115 /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
116 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
117 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
118 /// constants so every substrate consumer that dispatches on the
119 /// per-supervisor sibling-restart strategy (the future
120 /// wasm-operator's per-supervisor sibling-restart branch, the future
121 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
122 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
123 /// reconciliation scheduler's per-strategy fan-out) reads the same
124 /// byte-string the `Serialize` derive emits — the pin test in
125 /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
126 /// asserts the two paths agree, peer of the M3
127 /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
128 /// distribution-strategy axis.
129 #[must_use]
130 pub const fn as_str(self) -> &'static str {
131 match self {
132 Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
133 Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
134 Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
135 Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
136 }
137 }
138
139 /// Substrate-canonical reverse projection on the `:supervisor
140 /// :estrategia` closed-set axis — parses the `PascalCase`
141 /// discriminator scalar back to the typed variant, or `None` when
142 /// `s` is outside
143 /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
144 /// on the same lifted
145 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
146 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
147 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
148 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
149 /// constants the [`Self::as_str`] emitter walks, so the parse and
150 /// emit halves of the round-trip migrate through one caixa-core
151 /// edit on any future arm addition.
152 ///
153 /// Prior to this lift the substrate carried only the forward
154 /// `Self → &str` projection on the OTP sibling-restart axis (the
155 /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
156 /// through it, the `Serialize` derive that emits the same
157 /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
158 /// plus the kebab-case dispatcher-catalog identity via
159 /// [`Self::discriminant`] — every non-serde consumer that wanted to
160 /// parse a wire-form `PascalCase` strategy scalar had to re-inline
161 /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
162 /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
163 /// that expressed no compile-time link back to the typed variant's
164 /// canonical lifted constant. A future variant rename or per-arm
165 /// serde-attribute drift would silently split the wire byte-string
166 /// one non-serde consumer parsed from the one the emitter wrote,
167 /// with the failure surfacing at parse time far from the rebrand
168 /// commit.
169 ///
170 /// Distinct axis from the [`std::str::FromStr`] impl the
171 /// [`gen_platform::FromStrKind`] derive already installs on this
172 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
173 /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
174 /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
175 /// [`Self::discriminant`]), while this method inverts the
176 /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
177 /// two-axis split lets the dispatcher-catalog identity live in
178 /// kebab-case
179 /// (where every peer catalog identifier already lives) without
180 /// forcing a wire-format rename on the tatara-lisp author surface
181 /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
182 /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
183 /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
184 /// carry on their peer closed-set typed-enum wire round-trips.
185 ///
186 /// Same closed-set-reverse-projection discipline the sibling
187 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
188 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
189 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
190 /// carry on the peer wire-side `str → Self` axes — extended onto
191 /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
192 /// fifth substrate-side closed-set typed enum to converge on the
193 /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
194 /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
195 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
196 /// derive already installs on the sibling kebab-case axis. Returns
197 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
198 /// shapes: the caller picks the diagnostic form appropriate for
199 /// its use site.
200 #[must_use]
201 pub fn from_wire(s: &str) -> Option<Self> {
202 match s {
203 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
204 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
205 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
206 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
207 _ => None,
208 }
209 }
210}
211
212/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
213/// pretty-printed byte-string every consumer that formats the strategy as
214/// user-facing text lands on (the future wasm-operator's per-supervisor
215/// sibling-restart-strategy diagnostic line, the future `feira app graph`
216/// per-supervisor strategy line, the future M4
217/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
218/// rejection body) reaches for the same lifted
219/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
220/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
221/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
222/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
223/// wire-format `Serialize` derive already emits under
224/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
225/// [`RestartStrategy::as_str`] helper already returns.
226///
227/// Pre-convergence the two paths structurally disagreed — the
228/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
229/// route (now retired here) sent [`std::fmt::Display`] through the
230/// gen-platform discriminant catalog string, which arrives kebab-case as
231/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
232/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
233/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
234/// through the un-`rename`d serde derive. Every consumer that formatted
235/// the strategy for a diagnostic line, a graph, or a rejection body under
236/// `format!("{v}")` therefore landed under a different byte-string than
237/// the wire format the operator's per-strategy dispatch keyed off — a
238/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
239/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
240/// probed was `"OneForOne"`) surfaced as a confused correlate at
241/// operator-log time far from the two-declaration site.
242///
243/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
244/// path: every `format!("{v}")` call reaches the same lifted
245/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
246/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
247/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
248/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
249/// byte-string per variant. A future variant rename or
250/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
251/// exactly one place, structurally.
252///
253/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
254/// (from `#[derive(gen_platform::Discriminant)]`) still returns
255/// `"one-for-one"` / etc., and the fleet-wide
256/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
257/// registration keys the catalog off the same kebab identity. The two
258/// naming worlds now live on separate typed methods (`Display` /
259/// `as_str` for the wire byte-string, `discriminant` for the catalog
260/// identity) rather than sharing one `Display` route that structurally
261/// disagrees with the wire format.
262///
263/// Pin tests
264/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
265/// and
266/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
267/// assert the three paths agree byte-for-byte on every variant, so a
268/// future variant rename or per-arm serde attribute drift is a build
269/// error visible at caixa-core test time, not a silent per-consumer
270/// dispatch miss at apply / reconcile time.
271///
272/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
273/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
274/// axis — same three-path-convergence discipline, extended to close the
275/// second of three OTP-shaped closed-enum discriminator axes on the
276/// caixa typed surface.
277impl std::fmt::Display for RestartStrategy {
278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279 f.write_str(self.as_str())
280 }
281}
282
283/// Per-child restart policy.
284///
285/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
286#[derive(
287 Serialize,
288 Deserialize,
289 Debug,
290 Clone,
291 Copy,
292 PartialEq,
293 Eq,
294 Hash,
295 gen_platform::TypedDispatcher,
296 gen_platform::Discriminant,
297 gen_platform::IsVariant,
298 gen_platform::FromStrKind,
299)]
300pub enum RestartPolicy {
301 /// Always restart the child, regardless of how it died. Used for
302 /// long-running services that must always be up.
303 Permanent,
304 /// Never restart. Used for one-shot work whose completion is
305 /// itself the success signal (`oneShot` triggers map here).
306 Temporary,
307 /// Restart only when the child died *abnormally* (non-zero exit
308 /// or unhandled exception). A clean exit completes the child.
309 Transient,
310}
311
312impl Default for RestartPolicy {
313 fn default() -> Self {
314 // Route the [`Default for RestartPolicy`] impl's return arm through
315 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
316 // `pub const` rather than a raw `Self::Permanent` arm — one source
317 // of truth for the Erlang/OTP-canonical `permanent` worker-child
318 // default across the two production consumers that currently
319 // dispatch on it (this impl at the [`RestartPolicy::default`] call
320 // and the serde-side `#[serde(default)]` on
321 // [`ChildSpec::restart`] that resolves an author-omitted
322 // `:children :restart` slot through `RestartPolicy::default()`).
323 // Peer of the sibling per-`:supervisor` axis
324 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
325 // route (95ffacc) — the two impls now share one substrate-primitive
326 // lift discipline, so any future coherent rebrand of the OTP-shape
327 // supervisor+child default set migrates through typed constants in
328 // lockstep instead of splitting a lifted supervisor half against
329 // an open-coded child half. Pinned by
330 // `restart_policy_default_routes_through_lifted_default` +
331 // `child_spec_serde_default_restart_routes_through_lifted_default`
332 // in the tests module.
333 SUPERVISOR_CHILD_RESTART_DEFAULT
334 }
335}
336
337impl RestartPolicy {
338 /// Exhaustive iteration surface for every consumer that walks the
339 /// closed three-arm [`RestartPolicy`] discriminator set (the future
340 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
341 /// per-child admission-webhook rejection body naming the accepted-
342 /// `:restart` list, a future `feira supervisor --restart …` CLI
343 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
344 /// over the slice, the future `feira app graph` per-child restart
345 /// column, any future round-trip fuzz harness that sweeps every
346 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
347 /// theory
348 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
349 /// might reach for once the three canonical OTP restart policies
350 /// stop covering the substrate's discovered load-shape) extends
351 /// this slice as one edit and every consumer picks up the new entry
352 /// by construction; the compiler-checked exhaustiveness on the
353 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
354 /// is the build-time guarantee that no arm forgets to grow.
355 ///
356 /// Peer of the sibling closed-set typed enums'
357 /// [`RestartStrategy::ALL`] (4eec29c) /
358 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
359 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
360 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
361 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
362 /// surfaces — the sixth (and the third and final M2 OTP-shape)
363 /// closed-set typed enum on the caixa surface to converge onto the
364 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
365 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
366 /// sibling-restart-strategy axis; this closes the per-child
367 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
368 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
369
370 /// Canonical PascalCase discriminator scalar this variant serializes
371 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
372 /// arms return the paired
373 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
374 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
375 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
376 /// constants so every substrate consumer that dispatches on the
377 /// per-child restart-decision policy (the future wasm-operator's
378 /// per-child post-exit restart-decision branch, the future M4
379 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
380 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
381 /// reconciliation scheduler's per-child-policy fan-out) reads the
382 /// same byte-string the `Serialize` derive emits — the pin test in
383 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
384 /// asserts the two paths agree, peer of the M2
385 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
386 /// sibling-restart-strategy axis and the M3
387 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
388 /// per-Aplicacao distribution-strategy axis — the third of three
389 /// OTP-shaped closed-enum discriminator axes on the caixa typed
390 /// surface to converge onto the same three-path-convergence
391 /// (`Serialize` derive → `as_str` helper → lifted constant)
392 /// drift-detection posture.
393 #[must_use]
394 pub const fn as_str(self) -> &'static str {
395 match self {
396 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
397 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
398 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
399 }
400 }
401
402 /// Substrate-canonical reverse projection on the `:children :restart`
403 /// closed-set axis — parses the `PascalCase` discriminator scalar
404 /// back to the typed variant, or `None` when `s` is outside the
405 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
406 /// the same lifted
407 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
408 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
409 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
410 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
411 /// of the round-trip migrate through one caixa-core edit on any
412 /// future arm addition.
413 ///
414 /// Prior to this lift the substrate carried only the forward
415 /// `Self → &str` projection on the OTP per-child restart-policy
416 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
417 /// impl routed through it, the `Serialize` derive that emits the
418 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
419 /// plus the kebab-case dispatcher-catalog identity via
420 /// [`Self::discriminant`] — every non-serde consumer that wanted to
421 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
422 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
423 /// "Transient" => …, _ => … }` cascade that expressed no
424 /// compile-time link back to the typed variant's canonical lifted
425 /// constant. A future variant rename or per-arm serde-attribute
426 /// drift would silently split the wire byte-string one non-serde
427 /// consumer parsed from the one the emitter wrote, with the failure
428 /// surfacing at the operator's reconcile posture (a `:temporary`
429 /// `oneShot` child being restarted on clean exit, treating the
430 /// successful-completion signal as failure and re-running the
431 /// completion-terminal one-shot indefinitely; a `:transient` child
432 /// that clean-exited being restarted, masking the clean-completion
433 /// contract) far from the rebrand commit and with no field naming
434 /// the drift.
435 ///
436 /// Distinct axis from the [`std::str::FromStr`] impl the
437 /// [`gen_platform::FromStrKind`] derive already installs on this
438 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
439 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
440 /// `"transient"` — the inverse of [`Self::discriminant`]), while
441 /// this method inverts the `PascalCase` wire byte-string
442 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
443 /// catalog identity live in kebab-case (where every peer catalog
444 /// identifier already lives) without forcing a wire-format rename
445 /// on the tatara-lisp author surface (`:restart Permanent`,
446 /// `PascalCase`) — the same two-axis distinction the sibling
447 /// [`RestartStrategy::from_wire`] (4eec29c) /
448 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
449 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
450 /// carry on their peer closed-set typed-enum wire round-trips.
451 ///
452 /// Same closed-set-reverse-projection discipline the sibling
453 /// [`RestartStrategy::from_wire`] (4eec29c) /
454 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
455 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
456 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
457 /// carry on the peer wire-side `str → Self` axes — extended onto
458 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
459 /// sixth substrate-side closed-set typed enum (and the third and
460 /// final OTP-shape closed-enum discriminator axis) to converge on
461 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
462 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
463 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
464 /// derive already installs on the sibling kebab-case axis. Returns
465 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
466 /// shapes: the caller picks the diagnostic form appropriate for
467 /// its use site.
468 #[must_use]
469 pub fn from_wire(s: &str) -> Option<Self> {
470 match s {
471 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
472 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
473 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
474 _ => None,
475 }
476 }
477}
478
479/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
480/// pretty-printed byte-string every consumer that formats the policy as
481/// user-facing text lands on (the future wasm-operator's per-child
482/// post-exit restart-decision diagnostic line, the future `feira app
483/// graph` per-child restart column, the future M4
484/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
485/// admission-webhook rejection body) reaches for the same lifted
486/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
487/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
488/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
489/// wire-format `Serialize` derive already emits under
490/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
491/// [`RestartPolicy::as_str`] helper already returns.
492///
493/// Pre-convergence the two paths structurally disagreed — the
494/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
495/// route (now retired here) sent [`std::fmt::Display`] through the
496/// gen-platform discriminant catalog string, which arrives kebab-case as
497/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
498/// (whose variant names each collapse to their own lowercase form under
499/// the kebab-case transform), while the wire format ran as `PascalCase`
500/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
501/// serde derive. Every consumer that formatted the policy for a
502/// diagnostic line, a graph column, or a rejection body under
503/// `format!("{v}")` therefore landed under a different byte-string than
504/// the wire format the operator's per-child-policy dispatch keyed off —
505/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
506/// diagnostic quoting `"permanent"` while the wire scalar the operator
507/// probed was `"Permanent"`) surfaced as a confused correlate at
508/// operator-log time far from the two-declaration site.
509///
510/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
511/// path: every `format!("{v}")` call reaches the same lifted
512/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
513/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
514/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
515/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
516/// byte-string per variant. A future variant rename or
517/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
518/// exactly one place, structurally.
519///
520/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
521/// (from `#[derive(gen_platform::Discriminant)]`) still returns
522/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
523/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
524/// registration keys the catalog off the same kebab identity. The two
525/// naming worlds now live on separate typed methods (`Display` /
526/// `as_str` for the wire byte-string, `discriminant` for the catalog
527/// identity) rather than sharing one `Display` route that structurally
528/// disagrees with the wire format.
529///
530/// Pin tests
531/// [`tests::restart_policy_display_routes_through_as_str_helper`]
532/// and
533/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
534/// assert the three paths agree byte-for-byte on every variant, so a
535/// future variant rename or per-arm serde attribute drift is a build
536/// error visible at caixa-core test time, not a silent per-consumer
537/// dispatch miss at apply / reconcile time.
538///
539/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
540/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
541/// and the sibling [`RestartStrategy`] `Display` impl on the
542/// per-supervisor sibling-restart-strategy axis — same three-path-
543/// convergence discipline, extended to close the third and final of
544/// three OTP-shaped closed-enum discriminator axes on the caixa typed
545/// surface.
546impl std::fmt::Display for RestartPolicy {
547 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548 f.write_str(self.as_str())
549 }
550}
551
552// Fleet-wide dispatcher-catalog registrations for caixa's OTP
553// supervisor surface — two more typed shadows over Erlang/OTP
554// primitives the substrate now mechanically tracks (see
555// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
556// theory/TYPED-ABSORPTION.md for the absorption arc).
557gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
558gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
559
560/// One child entry in the supervisor's `:children` list.
561///
562/// Every child references another caixa by `:caixa <nome>` + version
563/// constraint. The supervisor materializes one ComputeUnit per entry.
564#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
565#[serde(rename_all = "camelCase")]
566pub struct ChildSpec {
567 /// The child caixa's `:nome`. Must resolve via the same dependency
568 /// resolution path as `:deps` (caixa-resolver).
569 pub caixa: String,
570
571 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
572 /// [`crate::dep::Dep::versao`].
573 pub versao: String,
574
575 /// Restart policy — an author-omitted slot degrades onto the
576 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
577 /// (`permanent`, the Erlang/OTP worker-child default) through the
578 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
579 /// to.
580 #[serde(default)]
581 pub restart: RestartPolicy,
582}
583
584impl ChildSpec {
585 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
586 /// accessor every consumer that reads the OTP-shape supervised
587 /// child's identity keys off — returns the author-declared
588 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
589 /// from the typed slot's own [`String`] storage.
590 ///
591 /// The `:children :caixa` slot carries the DNS-1123 label — the
592 /// child caixa's `:nome` — that every emitted cluster artifact
593 /// derives its `metadata.name` from verbatim: the rendered
594 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
595 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
596 /// identity, and the per-child K8s Service `metadata.name` the
597 /// future wasm-operator (M3) provisions for inter-child supervision-
598 /// tree wiring. Every downstream consumer that fans on the child's
599 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
600 /// per-child DNS-1123 gate at
601 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
602 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
603 /// [`validate_no_self_supervision`] cross-slot equality check
604 /// against the parent's `:nome`, every `SupervisorError` variant
605 /// carrying the offending child caixa verbatim for `feira lint`
606 /// rendering, the future wasm-operator's hierarchical reconciliation
607 /// scheduler's per-child ComputeUnit-name projection, the future M4
608 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
609 /// admission webhook).
610 ///
611 /// Prior to this lift the `.caixa` byte-string was accessed inline
612 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
613 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
614 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
615 /// carriers' `child.caixa.clone()`, the dedup key's
616 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
617 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
618 /// field-accesses that expressed no compile-time link back to the
619 /// typed slot. A future extension of the `:children :caixa` axis to
620 /// a richer author surface (a per-cluster alias table the operator
621 /// pins through a future `:placement`-scoped slot on the supervisor
622 /// tree, a namespace-qualified rewrite the M4 CR materializer
623 /// applies per-CR, a per-child overlay from the future `:children
624 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
625 /// acknowledges) would have had to be threaded through every
626 /// open-coded copy in lockstep or one consumer would silently
627 /// disagree with the peers on which caixa a given child resolves to
628 /// — a child-set lookup that treated the name as `"cart-worker"`
629 /// while the peer duplicate-detector treated it as
630 /// `"tenant-a/cart-worker"` would silently split the
631 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
632 /// self-supervision detector's parent-equality check, a two-consumer
633 /// split at the validator far from the source `caixa.lisp` with no
634 /// field naming the identity-drift root cause. Lifting the resolution
635 /// rule to a typed method on the substrate primitive means every
636 /// downstream consumer of the Supervisor's per-`:children` identity
637 /// surface reaches for exactly one typed dispatch — the resolver's
638 /// accept-set migrates as a unit on any future axis addition.
639 ///
640 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
641 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
642 /// mesh-slot surface — same "one typed dispatch on the substrate
643 /// primitive, thin projections at each consumer" discipline extended
644 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
645 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
646 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
647 /// accessor discipline for the shared substrate concept "another
648 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
649 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
650 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
651 /// slot family's typed-accessor discipline now spans both the
652 /// upgrade axis (`:upgrade-from`) and the supervision axis
653 /// (`:children`), matching the closed M3 mesh-slot accessor family's
654 /// shape. Named `nome()` to match the tatara-lisp author-surface
655 /// term the field's docstring already reaches for ("The child
656 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
657 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
658 /// discipline the substrate already carries — the accessor's name
659 /// maps directly onto the canonical caixa-identity vocabulary rather
660 /// than shadowing the field's storage-side `caixa` label.
661 #[must_use]
662 pub const fn nome(&self) -> &str {
663 self.caixa.as_str()
664 }
665
666 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
667 /// requirement scalar accessor every consumer that reads the OTP-shape
668 /// supervised child's version pin keys off — returns the author-declared
669 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
670 /// the typed slot's own [`String`] storage.
671 ///
672 /// The `:children :versao` slot carries the Cargo-shaped semver
673 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
674 /// which release of the supervised child caixa the OTP-shape supervisor
675 /// tree materializes against — the same requirement grammar the peer
676 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
677 /// shared [`crate::render::require_valid_versao_requirement`] cascade
678 /// and the shared [`crate::version::parse_requirement`] parser. Every
679 /// downstream consumer that fans on the child's version pin keys off
680 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
681 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
682 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
683 /// for `feira lint` rendering, every future per-cluster version-lock
684 /// overlay the caixa-operator's hierarchical reconciliation scheduler
685 /// pins through a future `:placement`-scoped supervisor-tree slot, the
686 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
687 /// per-child version resolver, the future wasm-operator's per-child
688 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
689 ///
690 /// Prior to this lift the `.versao` byte-string was accessed inline at
691 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
692 /// [`SupervisorSpec::validate`] requirement-gate call
693 /// `require_valid_versao_requirement(&child.versao, …)` and the
694 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
695 /// `versao: child.versao.clone()` — two open-coded field-accesses that
696 /// expressed no compile-time link back to the typed slot. A future
697 /// extension of the `:children :versao` axis to a richer author surface
698 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
699 /// flow, a lacre-projected concrete-version rewrite the operator
700 /// materializes at CR-admission time, a future `:children :versao-lock`
701 /// per-cluster override slot the wasm-operator's hierarchical
702 /// reconciliation scheduler authors per-CR) would have had to be
703 /// threaded through both open-coded copies in lockstep or one consumer
704 /// would silently disagree with the peer on which release constraint a
705 /// given child resolves to — the requirement-gate call reading
706 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
707 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
708 /// the actual gate rejection input, a two-consumer split at the
709 /// validator far from the source `caixa.lisp` with no field naming the
710 /// version-pin drift root cause. Lifting the resolution rule to a typed
711 /// method on the substrate primitive means every downstream
712 /// requirement-facing consumer of the Supervisor's per-`:children`
713 /// version-pin surface reaches for exactly one typed dispatch — the
714 /// resolver's accept-set migrates as a unit on any future axis addition.
715 ///
716 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
717 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
718 /// surface — same "one typed dispatch on the substrate primitive, thin
719 /// projections at each consumer" discipline extended onto the M2
720 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
721 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
722 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
723 /// one accessor discipline for the shared substrate concept "another
724 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
725 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
726 /// `:nome` scalar accessor — the pair
727 /// `(nome(), versao_requirement())` jointly projects the
728 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
729 /// that fans on per-child identity + version pin keys off, closing the
730 /// last unlifted per-`:children` `String`-carry axis so every downstream
731 /// per-`:children` reader now routes through a typed dispatch on the
732 /// substrate primitive. Named `versao_requirement()` rather than
733 /// `versao()` because the field's storage-side `.versao` label is
734 /// already the author-surface term (`:versao`); the accessor's name
735 /// carries the semantic role — the semver *requirement* string the
736 /// shared [`crate::version::parse_requirement`] entry-point consumes —
737 /// so a raw field access and a typed dispatch read differently at every
738 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
739 /// naming discipline verbatim.
740 #[must_use]
741 pub const fn versao_requirement(&self) -> &str {
742 self.versao.as_str()
743 }
744
745 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
746 /// per-child post-exit restart-decision policy scalar accessor every
747 /// consumer that dispatches on the supervised child's post-exit
748 /// reconcile posture keys off — returns the author-declared
749 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
750 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
751 /// storage.
752 ///
753 /// The `:children :restart` slot carries the closed-set OTP-shaped
754 /// per-child restart-decision policy discriminator
755 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
756 /// worker-child default; [`RestartPolicy::Transient`] — restart only
757 /// on abnormal exit, the OTP `transient` clean-completion-aware
758 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
759 /// `temporary` one-shot default) that every downstream consumer of
760 /// the Supervisor's per-child post-exit reconcile branch keys off.
761 /// Every future downstream consumer that fans on the per-child
762 /// restart-decision keys off this scalar (the future `feira app
763 /// graph` per-child restart column, the future wasm-operator's
764 /// per-child post-exit restart-decision branch, the future M4
765 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
766 /// admission webhook, the `caixa-operator`'s hierarchical
767 /// reconciliation scheduler's per-child post-exit reconcile branch,
768 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
769 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
770 /// pin threads through).
771 ///
772 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
773 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
774 /// scalar accessor and the M3 mesh-slot
775 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
776 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
777 /// — same "one typed dispatch on the substrate primitive,
778 /// `Copy`-projected closed-set enum-arm discriminator that partitions
779 /// the downstream renderer's per-arm fan-out" discipline extended
780 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
781 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
782 /// [`ChildSpec`] type — companion to the sibling per-`:children`
783 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
784 /// and the per-`:children` [`ChildSpec::versao_requirement`]
785 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
786 /// on the sibling `String`-carry axes. The triple
787 /// `(nome(), versao_requirement(), restart())` jointly projects the
788 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
789 /// tree consumer that fans on per-child identity + version pin +
790 /// restart-decision keys off, closing the last unlifted per-`:children`
791 /// axis so every downstream per-`:children` reader now routes through
792 /// a typed dispatch on the substrate primitive. Named `restart()` to
793 /// match the storage field's name and the author-surface
794 /// `:children :restart` slot term verbatim; the accessor's identity
795 /// name maps onto the canonical OTP-shape per-child restart-decision-
796 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
797 /// carries.
798 ///
799 /// Declared `pub const fn` to close the last non-`const`
800 /// `Copy`-return raw-field-getter posture on the M2
801 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
802 /// of the sibling M2 per-`:supervisor`
803 /// [`SupervisorSpec::estrategia`] (converted in this commit)
804 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
805 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
806 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
807 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
808 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
809 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
810 /// downstream substrate-side `const`-context consumer of the
811 /// per-`:children` restart-decision-policy scalar (a future
812 /// module-scope `const _:() = assert!(matches!(child.restart(),
813 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
814 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
815 /// admission-webhook `const fn` per-child restart-decision floor
816 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
817 /// composer over the substrate primitive that fans on the per-child
818 /// restart-decision policy at compile time) now reaches through the
819 /// same typed dispatch on the substrate primitive at const-eval
820 /// time as at runtime. A future non-`Copy`-return promotion of the
821 /// scalar (an `Option<RestartPolicy>`-shape migration on the
822 /// per-child restart-decision axis once heterogeneous per-cluster
823 /// restart-policy overlays land, a per-tenant restart-policy-alias
824 /// table the M4 CR materializer resolves per-CR) that would drop
825 /// the `const` qualifier fails the fail-before-pass-after pin
826 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
827 /// build time rather than surfacing as a downstream consumer
828 /// regression.
829 #[must_use]
830 pub const fn restart(&self) -> RestartPolicy {
831 self.restart
832 }
833}
834
835/// Supervisor-typed slots that live alongside the standard Caixa
836/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
837/// the manifest stays a single typed form; this struct exists for
838/// validation + conversion.
839#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
840#[serde(rename_all = "camelCase")]
841pub struct SupervisorSpec {
842 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
843 #[serde(default)]
844 pub estrategia: RestartStrategy,
845
846 /// Max restarts within [`Self::restart_window`] before the
847 /// supervisor itself terminates (and its parent supervisor decides
848 /// what to do). Default 5.
849 #[serde(default = "default_max_restarts")]
850 pub max_restarts: u32,
851
852 /// Sliding window for `max_restarts`. Authored as a duration
853 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
854 /// is rejected by [`Self::validate`] — Erlang/OTP's
855 /// `MaxIntensity / Period` invariant requires a positive window
856 /// (a zero-period supervisor either trips on the first failure or
857 /// never trips, depending on operator interpretation, neither of
858 /// which is the author's intent). Omit the slot to express "no
859 /// reset"; carry a positive duration to express the sliding window.
860 #[serde(
861 default,
862 skip_serializing_if = "Option::is_none",
863 with = "duration_codec"
864 )]
865 pub restart_window: Option<Duration>,
866
867 /// Static children. Empty for `SimpleOneForOne` (children added
868 /// dynamically); required for the other three strategies.
869 #[serde(default)]
870 pub children: Vec<ChildSpec>,
871}
872
873const fn default_max_restarts() -> u32 {
874 // Route the private serde-`#[serde(default = "…")]` helper through
875 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
876 // `pub const` rather than the raw `5` literal — one source of truth
877 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
878 // default across the two production consumers that currently
879 // dispatch on it (this helper via `#[serde(default = "…")]` on
880 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
881 // impl at line 962). Pinned by
882 // `default_max_restarts_helper_routes_through_lifted_default` +
883 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
884 // in the tests module; peer of the sibling caixa-core
885 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
886 // that now routes its author-omitted `:max-restarts` arm through
887 // the same lifted constant.
888 SUPERVISOR_MAX_RESTARTS_DEFAULT
889}
890
891/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
892/// count default for the `:supervisor :max-restarts` axis — the
893/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
894/// Erlang's worker-supervisor default, extracted as a typed `pub const`
895/// so every substrate-side consumer that resolves "what
896/// [`SupervisorSpec::max_restarts`] value does an author-omitted
897/// `:max-restarts` slot degrade onto?" reaches for exactly one
898/// substrate-primitive `u32`.
899///
900/// The `:max-restarts` default axis has two production consumers on the
901/// substrate side today (both prior to this lift folded onto raw `5`
902/// literals with no compile-time link back to a shared truth): the
903/// serde-`#[serde(default = "default_max_restarts")]` helper on
904/// [`SupervisorSpec::max_restarts`] that every author-omitted
905/// `:supervisor :max-restarts` slot lands in past the derive-macro's
906/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
907/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
908/// the composed [`SupervisorSpec`] altitude reaches through
909/// (`feira app graph`, the future wasm-operator's per-supervisor
910/// restart-intensity counter, the future M4
911/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
912/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
913/// A pair of open-coded `5`s across two files that expressed no
914/// compile-time link back to the shared OTP-canonical default — a
915/// future rebrand of the default (a tightening to Elixir's
916/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
917/// the operator pins through a future
918/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
919/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
920/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
921/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
922/// per-child-cohort roadmap lands) would have had to be threaded
923/// through both open-coded copies in lockstep or the wire-format
924/// author-omitted arm and the view-construction author-omitted arm
925/// would silently disagree on which restart-budget an omitted
926/// `:max-restarts` resolves to (an author writing `:supervisor
927/// (:max-restarts ())` would round-trip through serde with the new
928/// default while `supervisor_view` silently continued to compose the
929/// stale `5`, or vice versa), a two-consumer split at the composition
930/// boundary far from the source `caixa.lisp` with no field naming the
931/// default-drift root cause. Lifting the resolution rule to a typed
932/// `pub const` on the substrate primitive means every downstream
933/// consumer of the per-Supervisor default-restart-budget-count surface
934/// reaches for exactly one substrate-primitive `u32` — the resolver's
935/// accepted value migrates as a unit on any future axis change.
936///
937/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
938/// worker-supervisor default (the closest canonical OTP-shape
939/// production reference the substrate carries, matching the sibling
940/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
941/// this constant with on the paired sliding-window axis). Two orders of
942/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
943/// (the upper bracket on the same axis, sibling of this lower default;
944/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
945/// axis and now share one accessor discipline on the substrate) and
946/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
947/// restart floor — the "one restart, then escalate" default is
948/// deliberately loose enough to absorb a short burst of transient
949/// child failures without escalating past the supervisor's parent
950/// while remaining tight enough to trip the `MaxIntensity / Period`
951/// ratio's escalation on a genuinely-stuck child within the sibling
952/// `60s` sliding window.
953///
954/// Lifted as a typed `pub const` so the bound has exactly one source
955/// of truth — the serde-side wire-format author-omitted arm at
956/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
957/// struct-literal default field, and the caixa-core
958/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
959/// arm all read from one place. Same shape every other typed default
960/// in this crate carries (the sibling
961/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
962/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
963/// sibling `:restart-window` axis, and the peer
964/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
965/// per-renderer defaults on the caixa-flux / caixa-helm rendering
966/// axes).
967pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
968
969/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
970/// validated [`SupervisorSpec::max_restarts`] past
971/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
972///
973/// The typed field is `u32` (the zero-floor arm
974/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
975/// so a programmatic struct literal
976/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
977/// author-surface form (`:max-restarts 4294967295` or any
978/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
979/// cleanly through serde — a structurally unbounded `u32` ceiling. The
980/// runtime substrate consuming the value (Erlang/OTP's
981/// `MaxIntensity / Period` ratio, the future wasm-operator's
982/// per-supervisor restart-intensity counter, the M4
983/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
984/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
985/// escalation threshold is structurally so high that no realistic
986/// restarts-per-`:restart-window` traffic shape can reach it, the
987/// supervisor never escalates to its parent, and a bad child can loop
988/// inside the window indefinitely with the parent supervisor structurally
989/// never receiving the "this subtree has exceeded its restart budget"
990/// signal the typed slot is meant to express — the canonical
991/// "supervisor intensity declared, no escalation" footgun, exactly the
992/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
993/// on the `:politicas :circuit-breaker :max-failures` axis (both are
994/// "trip the next-higher protection layer after N events in a rolling
995/// window" counters with identical degenerate-at-the-high-end shape).
996///
997/// The `1000` ceiling matches the sibling
998/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
999/// peer — same "events-per-window trip threshold" semantics, same `u32`
1000/// type, same no-op-at-the-high-end failure mode) so the M4
1001/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1002/// and the future wasm-operator's per-supervisor restart-intensity
1003/// counter reach for either field knowing the value is in `1..=1000`
1004/// without re-validating at the reconciler layer. The cap sits two
1005/// orders of magnitude above every documented Erlang/OTP production
1006/// playbook recommendation (Learn You Some Erlang's
1007/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1008/// `max_restarts: 3` default, OTP's `supervisor` callback module
1009/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1010/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1011/// default) and below the clearly-pathological "effectively no
1012/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1013/// author can plausibly want at hyperscale (a long-running supervisor
1014/// over a very-flaky pool tolerating thousands of transient restarts
1015/// before escalating), but a hard wall above which the typed policy is
1016/// structurally a no-op carried verbatim on every emitted child-restart
1017/// reconciliation contract.
1018///
1019/// Lifted as a typed `pub const` so the bound has exactly one source of
1020/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1021/// materializer's admission webhook and the wasm-operator-side
1022/// per-supervisor restart-intensity reconciler read from one place. Same
1023/// shape every other typed upper bound in this crate carries
1024/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1025/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1026/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1027/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1028/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1029/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1030pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1031
1032/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1033/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1034/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1035/// (inclusive on both ends, integer-millisecond magnitudes by the
1036/// canonical-form gate immediately preceding).
1037///
1038/// The typed field is `Option<Duration>` (the zero-floor arm
1039/// [`SupervisorError::RestartWindowZero`] already rejects
1040/// `Some(Duration::ZERO)`, and the canonical-form arm
1041/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1042/// sub-millisecond residue), so a programmatic struct literal
1043/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1044/// .. }` — 24h) and the equivalent author-surface form
1045/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1046/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1047/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1048/// A `:restart-window` value far above the documented Erlang/OTP
1049/// `MaxIntensity / Period` production-playbook band (Learn You Some
1050/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1051/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1052/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1053/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1054/// degenerates the supervisor's restart-intensity counter into a
1055/// lifetime counter: the rolling failure-counting window is structurally
1056/// so long that transient restarts are never forgotten, so the
1057/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1058/// supervisor when the child has exceeded its restart budget *within
1059/// the recent window*" to "trip the parent when the child has exceeded
1060/// its restart budget *over its lifetime*" — every transient restart
1061/// counts against the budget forever, the supervisor's reset semantic
1062/// never reaches the child, and the typed `:restart-window` slot
1063/// becomes a no-op rolling window carried on every emitted hierarchical
1064/// reconciliation contract. The canonical
1065/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1066/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1067/// `:politicas :circuit-breaker :window` axis with identical shape (both
1068/// are "rolling failure-counting window with a per-`Period` reset" Duration
1069/// axes whose lifetime-counter degenerate at the high end is the same
1070/// "the reset semantic never fires" CSE invariant violation).
1071///
1072/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1073/// the shared duration codec emits (`"<n>h"` for any integer-hour
1074/// magnitude) — every value in the canonical authoring form's
1075/// `<integer><unit>` grammar at or below this cap renders to a clean
1076/// canonical string — and matches the three sibling typed-`Duration`
1077/// caps already lifted to this surface
1078/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1079/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1080/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1081/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1082/// per-supervisor `:supervisor :restart-window` — now share a single
1083/// uniform top edge at the codec's largest emitted unit so the next
1084/// typed-slot wiring (the future wasm-operator's per-supervisor
1085/// `MaxIntensity / Period` reconciler, the M4
1086/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1087/// webhook, the `caixa-operator`'s hierarchical reconciliation
1088/// scheduler) reaches for any of the four knowing the value is in
1089/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1090/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1091/// Riak Core / RabbitMQ production-playbook recommendation band
1092/// (`5s..=300s`) and below the clearly-pathological "rolling window
1093/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1094/// a value the author can plausibly want for a very-low-traffic
1095/// long-tail failure-restart window over a hyperscale-flaky child pool,
1096/// but a hard wall above which the rolling-window contract is
1097/// structurally a lifetime-counter contract.
1098///
1099/// Lifted as a typed `pub const` so the bound has exactly one source
1100/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1101/// materializer's admission webhook, the wasm-operator-side
1102/// per-supervisor `MaxIntensity / Period` reconciler, and the
1103/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1104/// from one place. Same shape every other typed upper bound in this
1105/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1106/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1107/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1108/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1109/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1110/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1111/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1112/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1113/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1114pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1115
1116/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1117/// default for the `:supervisor :restart-window` axis — the canonical
1118/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1119/// worker-supervisor default, extracted as a typed `pub const` so every
1120/// substrate-side consumer that resolves "what
1121/// [`SupervisorSpec::restart_window`] value does an author-omitted
1122/// `:restart-window` slot degrade onto?" reaches for exactly one
1123/// substrate-primitive [`Duration`].
1124///
1125/// The `:restart-window` default axis has one production consumer on the
1126/// substrate side today: the [`Default for SupervisorSpec`] impl's
1127/// struct-literal `restart_window` field, which prior to this lift folded
1128/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1129/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1130/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1131/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1132/// *not* fall back to this default on the sibling `:restart-window` axis
1133/// — an author-omitted `:supervisor :restart-window` composes to
1134/// `restart_window: None` (the shared codec's soft-swallow shape),
1135/// keeping author-declared intent ("no reset — never escalate on rolling
1136/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1137/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1138/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1139/// default was split across two files with no compile-time link between
1140/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1141/// `MaxIntensity` half at the substrate primitive while the `Period`
1142/// half rode as an open-coded literal at the composition site, so a
1143/// future coherent rebrand of the paired canonical (a tightening to
1144/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1145/// per-cluster overlay the operator pins through a future
1146/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1147/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1148/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1149/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1150/// roadmap lands) would have had to migrate the `MaxIntensity` half
1151/// through the lifted constant and the `Period` half through a raw
1152/// literal in lockstep or the two halves of the same OTP-canonical
1153/// default would silently drift out of pairing. Lifting the resolution
1154/// rule to a typed `pub const` on the substrate primitive means the
1155/// paired OTP-canonical default migrates as one unit on any future
1156/// axis change.
1157///
1158/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1159/// worker-supervisor default (the closest canonical OTP-shape
1160/// production reference the substrate carries, matching the paired
1161/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1162/// constant is the `Period` denominator of on the same
1163/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1164/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1165/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1166/// this lower default; both are typed [`Duration`] const bounds on the
1167/// `:supervisor :restart-window` axis and now share one accessor
1168/// discipline on the substrate) and above the OTP-`supervisor`
1169/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1170/// rolling window" default is deliberately loose enough to absorb a
1171/// short burst of transient child failures without escalating past the
1172/// supervisor's parent while remaining tight enough for the paired
1173/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1174/// stuck child within a human-scale observation window.
1175///
1176/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1177/// exactly one source of truth on each half — the sibling
1178/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1179/// `Period` `60s` half now share the same substrate-primitive lift
1180/// discipline. Same shape every other typed default in this crate
1181/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1182/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1183/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1184/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1185/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1186/// caixa-flux / caixa-helm rendering axes).
1187pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1188
1189/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1190/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1191/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1192/// worker-supervisor default, extracted as a typed `pub const` so every
1193/// substrate-side consumer that resolves "what
1194/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1195/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1196/// primitive [`RestartStrategy`].
1197///
1198/// The `:estrategia` default axis has three production consumers on the
1199/// substrate side today: the [`Default for RestartStrategy`] impl's
1200/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1201/// `estrategia` field, and the
1202/// [`crate::manifest::Caixa::supervisor_view`] fold's
1203/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1204/// collapse arm — three entry points onto the same OTP-canonical
1205/// `one_for_one` value that prior to this lift folded onto a raw
1206/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1207/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1208/// with no compile-time link back to the paired
1209/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1210/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1211/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1212/// triple was split across three altitudes with no compile-time link
1213/// between the halves: the `MaxIntensity` half rode through the lifted
1214/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1215/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1216/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1217/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1218/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1219/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1220/// intensity/period; an OTP `rest_for_one` widening once the substrate
1221/// discovers startup-order-coupled child cohorts as the more common
1222/// worker-supervisor default; a per-cluster overlay the operator pins
1223/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1224/// §III.2 supervision-canary roadmap acknowledges) would have had to
1225/// migrate the `MaxIntensity` + `Period` halves through the lifted
1226/// constants and the `one_for_one` half through an open-coded arm in
1227/// lockstep or the three halves of the same OTP-canonical default would
1228/// silently drift out of pairing. Lifting the resolution rule to a typed
1229/// `pub const` on the substrate primitive means the paired OTP-canonical
1230/// worker-supervisor default migrates as one unit on any future axis
1231/// change.
1232///
1233/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1234/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1235/// closest canonical OTP-shape production reference the substrate
1236/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1237/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1238/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1239/// failed child, leaving siblings untouched — is the default for tree-of-
1240/// independent-workers use cases the substrate's [`RestartStrategy`]
1241/// discriminator's own docstring already carries as the default arm; it
1242/// composes with the `{5, 60}` restart-intensity ratio to name the same
1243/// substrate-canonical "canonical worker-supervisor" shape the paired
1244/// halves close on their respective axes.
1245///
1246/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1247/// exactly one source of truth on each of its three halves — the sibling
1248/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1249/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1250/// this `one_for_one` strategy half now share the same substrate-
1251/// primitive lift discipline. Same shape every other typed default in
1252/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1253/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1254/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1255/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1256/// upper caps on the paired sibling axes, and the peer
1257/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1258/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1259pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1260
1261/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1262/// default for the `:children :restart` axis — the OTP `permanent`
1263/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1264/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1265/// `pub const` so every substrate-side consumer that resolves "what
1266/// [`ChildSpec::restart`] variant does an author-omitted `:children
1267/// :restart` slot degrade onto?" reaches for exactly one substrate-
1268/// primitive [`RestartPolicy`].
1269///
1270/// Completes the OTP-shape supervisor-tree default set at the substrate
1271/// primitive. The per-`:supervisor` axis already carries all three of its
1272/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1273/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1274/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1275/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1276/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1277/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1278/// the M2 `:supervisor` slot family. The split mattered because the two
1279/// axes resolve *together* on every author-omitted supervisor: a
1280/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1281/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1282/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1283/// `permanent` through an open-coded enum arm, so a future coherent
1284/// rebrand of the OTP-shape default set (an Elixir-shaped
1285/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1286/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1287/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1288/// once the substrate discovers clean-completion-aware children as the
1289/// more common child shape) would have had to migrate three halves
1290/// through typed constants and the fourth through a raw enum arm in
1291/// lockstep or the supervisor-level and child-level defaults would
1292/// silently drift apart.
1293///
1294/// The `:children :restart` default axis has two production consumers on
1295/// the substrate side today: the [`Default for RestartPolicy`] impl's
1296/// return arm, and the serde-side `#[serde(default)]` on
1297/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1298/// :restart` slot through that same impl. Both now key off this one
1299/// substrate primitive, so the future wasm-operator's per-child post-exit
1300/// restart-decision branch, the future M4
1301/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1302/// admission webhook, and the `caixa-operator`'s hierarchical
1303/// reconciliation scheduler's per-child fan-out all reach for one typed
1304/// identifier when they resolve an omitted per-child restart posture.
1305///
1306/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1307/// worker-child restart type — always restart the child regardless of how
1308/// it died, the canonical posture for long-running services that must
1309/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1310/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1311/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1312/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1313/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1314/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1315/// one-shot / clean-completion-aware postures an author declares
1316/// explicitly, never a posture an omitted slot should silently assume.
1317pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1318
1319impl Default for SupervisorSpec {
1320 fn default() -> Self {
1321 Self {
1322 // Route the struct-literal `estrategia` default arm through
1323 // the substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1324 // typed `pub const` rather than the transitively-derived
1325 // `RestartStrategy::default()` route — one source of truth
1326 // for the Erlang/OTP `one_for_one` half of Learn You Some
1327 // Erlang's `{one_for_one, intensity, 5, 60}` worker-
1328 // supervisor canonical default, paired with the sibling
1329 // `max_restarts: default_max_restarts()` arm below that
1330 // routes through the peer [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1331 // `MaxIntensity` half (b698ec0) and the sibling
1332 // `restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT)`
1333 // arm that routes through the peer
1334 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half
1335 // (f7dcd0e). All three halves of the same OTP-canonical
1336 // default now share the same substrate-primitive lift
1337 // discipline so any future coherent rebrand of the paired
1338 // triple migrates through three typed constants in lockstep
1339 // instead of splitting two lifted halves against a
1340 // transitively-derived third. Pinned by
1341 // `supervisor_spec_default_estrategia_routes_through_lifted_default`.
1342 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1343 max_restarts: default_max_restarts(),
1344 // Route the struct-literal `restart_window` default arm
1345 // through the substrate-canonical
1346 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] typed `pub const`
1347 // rather than a raw `Duration::from_secs(60)` literal — one
1348 // source of truth for the Erlang/OTP-canonical
1349 // `{intensity, 5, 60}` `Period` half of Learn You Some
1350 // Erlang's worker-supervisor default, paired with the
1351 // sibling `max_restarts: default_max_restarts()` arm above
1352 // that already routes through the peer
1353 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half
1354 // (b698ec0). The two halves of the same OTP-canonical
1355 // default now share the same substrate-primitive lift
1356 // discipline so any future coherent rebrand of the paired
1357 // default (Elixir's `{max_restarts: 3, max_seconds: 5}`, a
1358 // per-cluster overlay via a future
1359 // `:restart-window-overrides` slot, a per-child-cohort
1360 // promotion) migrates through two typed constants in
1361 // lockstep instead of splitting a lifted `MaxIntensity` half
1362 // against an open-coded `Period` literal. Pinned by
1363 // `supervisor_spec_default_restart_window_routes_through_lifted_default`
1364 // in the tests module; peer of the sibling
1365 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1366 // byte-parity pin on the paired `max_restarts` field.
1367 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1368 children: Vec::new(),
1369 }
1370 }
1371}
1372
1373impl SupervisorSpec {
1374 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1375 /// sibling-restart-strategy scalar accessor every consumer that
1376 /// dispatches on the supervisor's per-sibling restart-decision shape
1377 /// keys off — returns the author-declared `:supervisor :estrategia`
1378 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1379 /// the typed slot's own [`RestartStrategy`] storage.
1380 ///
1381 /// The `:supervisor :estrategia` slot carries the closed-set
1382 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
1383 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
1384 /// [`RestartStrategy::OneForAll`] — restart every child on any child
1385 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
1386 /// [`RestartStrategy::RestForOne`] — restart the failed child and
1387 /// every child started after it, the Erlang/OTP `rest_for_one`
1388 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
1389 /// dynamic children of the same shape, the Erlang/OTP
1390 /// `simple_one_for_one` per-session default) that every downstream
1391 /// consumer of the Supervisor's per-sibling restart-decision fan-out
1392 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
1393 /// paired coherently with the sibling `:children` axis
1394 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
1395 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
1396 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
1397 /// downstream consumer that reads the strategy keys off this scalar
1398 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1399 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
1400 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
1401 /// `estrategia:` field, the future `feira app graph` per-Supervisor
1402 /// strategy print line, the future wasm-operator's per-supervisor
1403 /// sibling-restart-strategy branch, the future M4
1404 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
1405 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
1406 /// reconciliation scheduler's per-strategy fan-out).
1407 ///
1408 /// Prior to this lift the `.estrategia` field was accessed inline at
1409 /// two production sites in `caixa-core/src/supervisor.rs` — the
1410 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1411 /// `match self.estrategia { … }` partition dispatch, and the
1412 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
1413 /// carrier at `estrategia: self.estrategia` — two open-coded
1414 /// field-accesses that expressed no compile-time link back to the
1415 /// typed slot. A future extension of the `:supervisor :estrategia`
1416 /// axis to a richer author surface (a per-cluster strategy override
1417 /// the operator pins through a future `:supervisor :estrategia-overrides`
1418 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1419 /// acknowledges, a per-tenant strategy-alias table the M4 CR
1420 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
1421 /// derivation the future adaptive-supervision engine computes from
1422 /// child-failure-history topology, a per-child-cohort strategy split
1423 /// the future `RestForCohort` extension acknowledged by the
1424 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
1425 /// would have had to be threaded through every open-coded copy in
1426 /// lockstep — one consumer reading the raw variant while a peer read
1427 /// the operator-resolved variant would silently split the
1428 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
1429 /// the actual partition-dispatch input the empty-children refusal
1430 /// arm reached under, a two-consumer split at the validator far from
1431 /// the source `caixa.lisp` with no field naming the strategy-drift
1432 /// root cause. Lifting the resolution rule to a typed method on the
1433 /// substrate primitive means every downstream consumer of the
1434 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
1435 /// reaches for exactly one typed dispatch — the resolver's accept-set
1436 /// migrates as a unit on any future axis addition.
1437 ///
1438 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
1439 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
1440 /// per-`:placement` distribution-strategy axis — same "one typed
1441 /// dispatch on the substrate primitive, thin projections at each
1442 /// consumer" discipline extended onto the M2 supervisor-slot
1443 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
1444 /// scalar axis. The two typed axes (`Placement::estrategia` on the
1445 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
1446 /// Supervisor side) now share one accessor discipline for the shared
1447 /// substrate concept "a `Copy`-projected closed-set enum-arm
1448 /// discriminator that partitions the downstream renderer's per-arm
1449 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
1450 /// `SupervisorSpec` type — companion to the sibling per-`:children`
1451 /// [`crate::ChildSpec::nome`] (57c61d0) /
1452 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1453 /// scalar accessors on the sibling per-`:children` `String`-carry
1454 /// axes. Named `estrategia()` to match the storage field's name and
1455 /// the peer [`crate::Placement::estrategia`] method-name discipline
1456 /// verbatim; the accessor's identity name maps onto the canonical
1457 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
1458 /// docstring already carries.
1459 ///
1460 /// Declared `pub const fn` to close the M2 supervisor-slot
1461 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
1462 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
1463 /// (converted in this commit) `Copy`-composite-enum accessor, peer
1464 /// of the sibling M2 per-`:supervisor`
1465 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1466 /// already lifted, and mirror of the peer M3 mesh-slot
1467 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
1468 /// `Copy`-return `pub const fn` scalar accessor whose method-name
1469 /// discipline this accessor was authored to match. Every downstream
1470 /// substrate-side `const`-context consumer of the per-`:supervisor`
1471 /// sibling-restart-strategy scalar (a future module-scope `const
1472 /// _:() = assert!(matches!(sup.estrategia(),
1473 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
1474 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1475 /// admission-webhook `const fn` per-supervisor strategy-arm floor
1476 /// over a typed [`SupervisorSpec`], any future `const fn`
1477 /// supervisor-tree composer over the substrate primitive that fans
1478 /// on the sibling-restart-strategy at compile time) now reaches
1479 /// through the same typed dispatch on the substrate primitive at
1480 /// const-eval time as at runtime. A future non-`Copy`-return
1481 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
1482 /// migration once the substrate grows per-cluster strategy overlays
1483 /// the [`SupervisorSpec`] docstring already anticipates, a
1484 /// per-tenant strategy-alias table the M4 CR materializer resolves
1485 /// per-CR) that would drop the `const` qualifier fails the
1486 /// fail-before-pass-after pin
1487 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
1488 /// caixa-core build time rather than surfacing as a downstream
1489 /// consumer regression.
1490 #[must_use]
1491 pub const fn estrategia(&self) -> RestartStrategy {
1492 self.estrategia
1493 }
1494
1495 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
1496 /// `MaxIntensity` restart-budget scalar accessor every consumer that
1497 /// reads the supervisor's per-`:restart-window` restart-budget count
1498 /// keys off — returns the author-declared `:supervisor :max-restarts`
1499 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
1500 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
1501 /// borrow of `&self` past the call). Non-optional (the `u32` field
1502 /// carries the restart-budget count as a required axis with a
1503 /// [`default_max_restarts`]-supplied default; the zero-floor arm
1504 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
1505 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
1506 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
1507 ///
1508 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
1509 /// `MaxIntensity` restart-budget count that pairs with the sibling
1510 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
1511 /// restart-intensity ratio the supervisor trips its own escalation on
1512 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
1513 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
1514 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
1515 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
1516 /// upper-cap bracket at
1517 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
1518 /// wasm-operator's per-supervisor restart-intensity counter's
1519 /// budget-vs-count comparator, the future M4
1520 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1521 /// webhook, the `caixa-operator`'s hierarchical reconciliation
1522 /// scheduler's per-supervisor escalation-decision branch, every
1523 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
1524 /// offending count verbatim for `feira lint` rendering).
1525 ///
1526 /// Prior to this lift the `.max_restarts` field was accessed inline at
1527 /// one production site in `caixa-core/src/supervisor.rs` — the
1528 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
1529 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
1530 /// that expressed no compile-time link back to the typed slot. A
1531 /// future extension of the `:max-restarts` axis to a richer author
1532 /// surface (a per-cluster restart-budget override the operator pins
1533 /// through a future `:supervisor :max-restarts-overrides` slot the
1534 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
1535 /// a per-tenant restart-budget-alias table the M4 CR materializer
1536 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
1537 /// the future adaptive-supervision engine computes from child-failure-
1538 /// history topology, a promotion of the plain `u32` count to a richer
1539 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
1540 /// budget-partition slot comes into scope) would have had to be
1541 /// threaded through every open-coded copy in lockstep or the validate
1542 /// gate and the future M4 emit path would silently disagree on which
1543 /// restart-budget count a given supervisor resolves to — an author's
1544 /// `:max-restarts 5` would satisfy validate while the emit path
1545 /// silently read a drifted other value (a `:max-restarts 10000`
1546 /// no-op supervisor at the emit boundary would carry the author's
1547 /// declared `5` verbatim in `feira lint` output while the future
1548 /// wasm-operator's restart-intensity counter operated under the
1549 /// drifted count), a two-consumer split at the validator far from the
1550 /// source `caixa.lisp` with no field naming the restart-budget-drift
1551 /// root cause. Lifting the resolution rule to a typed method on the
1552 /// substrate primitive means every downstream consumer of the
1553 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
1554 /// for exactly one typed dispatch — the resolver's accept-set migrates
1555 /// as a unit on any future axis addition.
1556 ///
1557 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
1558 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
1559 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
1560 /// outlier-detection trip-threshold axis — same "one typed dispatch on
1561 /// the substrate primitive, thin projections at each consumer"
1562 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
1563 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
1564 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
1565 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
1566 /// one accessor discipline for the shared substrate concept "a
1567 /// `Copy`-projected required `u32` count that trips the next-higher
1568 /// protection layer after N events in a rolling window" — both are
1569 /// counters with identical degenerate-at-the-high-end shape and share
1570 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
1571 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
1572 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
1573 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
1574 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
1575 /// the storage field's name verbatim and the peer
1576 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
1577 /// accessor's identity maps onto the canonical OTP-shape supervision
1578 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
1579 /// already carries.
1580 #[must_use]
1581 pub const fn max_restarts(&self) -> u32 {
1582 self.max_restarts
1583 }
1584
1585 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
1586 /// `Period` sliding-window scalar accessor every consumer of the
1587 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
1588 /// keys off — returns the author-declared `:supervisor :restart-window`
1589 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
1590 /// the typed slot's own `Option<Duration>` storage (`Duration` is
1591 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
1592 /// value; no borrow of `&self` past the call). `None` when the slot is
1593 /// absent (the canonical "never reset — every restart across the
1594 /// supervisor's lifetime counts against the sibling `:max-restarts`
1595 /// budget" sentinel the field's own docstring names and the peer
1596 /// `validate_accepts_none_restart_window` pin locks in on the
1597 /// [`SupervisorSpec::validate`] entry-side).
1598 ///
1599 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
1600 /// `Period` sliding-observation-interval that pairs with the sibling
1601 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
1602 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
1603 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
1604 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
1605 /// default). The typed slot's `Option<Duration>` accept-set —
1606 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
1607 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
1608 /// `Period > 0`; a zero period either trips on the first failure or
1609 /// never trips depending on operator interpretation, neither of which
1610 /// is the author's intent — omit the slot to express "no reset";
1611 /// carry a positive duration to express the sliding window),
1612 /// integer-millisecond canonical form enforced through
1613 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
1614 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
1615 /// future wasm-operator's per-supervisor restart-intensity counter
1616 /// quantizes at milliseconds), upper-bounded by
1617 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
1618 /// supervisor rolling window any operationally-reachable supervisor
1619 /// can honor without spanning multiple scheduler epochs the
1620 /// hierarchical-reconciliation scheduler treats as independent) —
1621 /// maps onto the future wasm-operator (M3) per-supervisor
1622 /// restart-intensity counter's rolling-observation-interval, the
1623 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1624 /// per-`spec.restartWindow` admission webhook, and the sibling
1625 /// `duration_codec`-serialized wire scalar every downstream consumer
1626 /// of the supervisor's per-`:supervisor` restart-intensity denominator
1627 /// keys off.
1628 ///
1629 /// Prior to this lift the `.restart_window` field was accessed inline
1630 /// at one production site in `caixa-core/src/supervisor.rs` — the
1631 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
1632 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
1633 /// open-coded field-access that expressed no compile-time link back to
1634 /// the typed slot. A future extension of the `:restart-window` axis to
1635 /// a richer author surface (a per-cluster restart-window override the
1636 /// operator pins through a future `:supervisor :restart-window-overrides`
1637 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1638 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
1639 /// materializer resolves per-CR, a per-supervisor dynamic
1640 /// restart-window derivation the future adaptive-supervision engine
1641 /// computes from child-failure-history topology, a promotion of the
1642 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
1643 /// pair once Erlang/OTP's per-child-cohort observation-interval-
1644 /// partition slot comes into scope) would have had to be threaded
1645 /// through every open-coded copy in lockstep or the validate gate and
1646 /// the future M4 emit path would silently disagree on which
1647 /// restart-window a given supervisor resolves to — an author's
1648 /// `:restart-window "60s"` would satisfy validate while the emit path
1649 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
1650 /// authored slot at the emit boundary would carry the author's
1651 /// declared window verbatim in `feira lint` output while the future
1652 /// wasm-operator's restart-intensity counter operated under a
1653 /// drifted window, or vice versa: an author's `:restart-window ()`
1654 /// would carry the "never reset" sentinel through validate while the
1655 /// emit path silently substituted a default sliding window), a
1656 /// two-consumer split at the validator far from the source
1657 /// `caixa.lisp` with no field naming the restart-window-drift root
1658 /// cause. Lifting the resolution rule to a typed method on the
1659 /// substrate primitive means every downstream consumer of the
1660 /// Supervisor's per-`:supervisor` restart-intensity-denominator
1661 /// surface reaches for exactly one typed dispatch — the resolver's
1662 /// accept-set migrates as a unit on any future axis addition.
1663 ///
1664 /// Third `Copy`-return accessor on the M2 supervisor-slot
1665 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
1666 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
1667 /// payload rather than a `Copy`-scalar, and the per-`:children`
1668 /// [`crate::ChildSpec::nome`] (57c61d0) /
1669 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1670 /// scalar accessors already close the per-element `String`-carry
1671 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
1672 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
1673 /// per-outermost-call wall-clock-deadline axis and the peer M3
1674 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
1675 /// accessor on the `:politicas` slot's per-call-deadline axis — all
1676 /// three share the shared substrate concept "a `Copy`-projected
1677 /// optional `Duration` that carries a positive integer-millisecond
1678 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
1679 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
1680 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
1681 /// bracket-helper the three axes each route through. Named
1682 /// `restart_window()` to match the storage field's name verbatim and
1683 /// the peer [`crate::LimitsSpec::wall_clock`] /
1684 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
1685 /// accessor's identity maps onto the canonical OTP-shape supervision
1686 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
1687 /// already carries.
1688 #[must_use]
1689 pub const fn restart_window(&self) -> Option<Duration> {
1690 self.restart_window
1691 }
1692
1693 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
1694 /// static-child-list slice accessor every consumer that walks the
1695 /// supervisor's declared child set keys off — returns the author-
1696 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
1697 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
1698 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
1699 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
1700 /// through). Non-optional: an empty slice is the load-bearing
1701 /// "author declared `:children ()`" sentinel every consumer of the
1702 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
1703 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
1704 /// three strategies require a non-empty slice — the paired
1705 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
1706 /// [`SupervisorError::NoChildren`] refusal cascade pins the
1707 /// partition on both arms).
1708 ///
1709 /// The `:supervisor :children` slot carries the OTP-shaped static
1710 /// child list the supervisor materializes one ComputeUnit per
1711 /// entry from — the Erlang/OTP `supervisor:init/1`'s
1712 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
1713 /// through the tatara-lisp `:children` author surface onto a typed
1714 /// `Vec<ChildSpec>` whose per-element `(nome(),
1715 /// versao_requirement(), restart)` triple the per-child
1716 /// [`SupervisorSpec::validate`] loop already gates through the
1717 /// lifted [`ChildSpec::nome`] (57c61d0) /
1718 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
1719 /// Every downstream consumer that fans on the static child list
1720 /// keys off this slice (the [`SupervisorSpec::validate`]
1721 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
1722 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
1723 /// per-child DNS-1123 / semver-requirement / duplicate-detection
1724 /// fan-out loop, every future wasm-operator (M3) per-supervisor
1725 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
1726 /// materialization loop, the future M4
1727 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1728 /// admission-webhook fan-out, the future `feira app graph`
1729 /// per-supervisor tree-print traversal).
1730 ///
1731 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
1732 /// inline at three production sites in `caixa-core/src/supervisor.rs`
1733 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
1734 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
1735 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
1736 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
1737 /// validate loop's `for child in &self.children` traversal head —
1738 /// three open-coded field-accesses that expressed no compile-time
1739 /// link back to the typed slot. A future extension of the
1740 /// `:supervisor :children` axis to a richer author surface (a
1741 /// per-cluster child-set overlay the operator pins through a future
1742 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
1743 /// supervision-canary roadmap acknowledges, a per-tenant
1744 /// child-set-alias table the M4 CR materializer resolves per-CR,
1745 /// a per-supervisor dynamic-child derivation the future adaptive-
1746 /// supervision engine computes from child-failure-history topology,
1747 /// a promotion of the plain `Vec<ChildSpec>` to a richer
1748 /// `{static, dynamic}` partition once Erlang/OTP's
1749 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
1750 /// would have had to be threaded through all three open-coded copies
1751 /// in lockstep or one consumer would silently disagree with the
1752 /// peers on which child-set a given supervisor resolves to — the
1753 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
1754 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
1755 /// would silently split the partition-dispatch's two-arm coherence
1756 /// (a supervisor that satisfies neither arm's precondition, or that
1757 /// satisfies both, at the cost of the paired
1758 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
1759 /// silently drifting from the per-child validate loop's actual
1760 /// traversal input), a three-consumer split at the validator far
1761 /// from the source `caixa.lisp` with no field naming the
1762 /// child-set-drift root cause. Lifting the resolution rule to a
1763 /// typed method on the substrate primitive means every downstream
1764 /// consumer of the Supervisor's per-`:supervisor` static-child-list
1765 /// surface reaches for exactly one typed dispatch — the resolver's
1766 /// accept-set migrates as a unit on any future axis addition.
1767 ///
1768 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
1769 /// — the seed for the same "one typed dispatch on the substrate
1770 /// primitive, thin projections at each consumer" discipline the
1771 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
1772 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
1773 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
1774 /// onto the first `Vec`-carry axis on the substrate. The four peer
1775 /// `Vec`-carry axes still unlifted at the time of this seed —
1776 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
1777 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
1778 /// (`Vec<Membro>` per-Aplicacao member list),
1779 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
1780 /// per-Aplicacao WIT-typed edge list),
1781 /// [`crate::UpgradeFromEntry::instructions`]
1782 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
1783 /// — inherit this accessor's discipline as future compounding runs
1784 /// migrate their consumers onto the shared slice-return shape.
1785 /// Fourth (and final) accessor on the M2 supervisor-slot
1786 /// `SupervisorSpec` type, sibling to the three `Copy`-return
1787 /// [`SupervisorSpec::estrategia`] (eafb619) /
1788 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
1789 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
1790 /// the last unlifted per-`:supervisor` field axis (the
1791 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
1792 /// per-`:supervisor` reader now routes through a typed dispatch on
1793 /// the substrate primitive. Named `children()` to match the storage
1794 /// field's name verbatim and the tatara-lisp author-surface term
1795 /// (`:children`) the field's own docstring already carries; the
1796 /// accessor's identity maps onto the canonical OTP-shape
1797 /// supervision vocabulary the [`SupervisorSpec::children`] field's
1798 /// docstring already reaches for ("Static children ..."). Returns
1799 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
1800 /// consumer of the child list treats it as a read-only sequence —
1801 /// the slice-view is the narrowest borrow that supports every
1802 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
1803 /// index, `.len()`) without leaking the backing `Vec`'s
1804 /// grow/push/reserve surface that no consumer of the typed view
1805 /// reaches for (the storage-side `Vec` remains reachable through
1806 /// the `pub children` field for the mutation-carrying
1807 /// `Caixa::supervisor_view` fold-in path in
1808 /// `manifest.rs:supervisor_view`).
1809 #[must_use]
1810 pub const fn children(&self) -> &[ChildSpec] {
1811 self.children.as_slice()
1812 }
1813
1814 /// Validate the supervisor's typed shape — strategy ↔ children
1815 /// invariants, max_restarts > 0, restart_window > 0 when set,
1816 /// per-child non-empty + duplicate-free names.
1817 ///
1818 /// Mirrors the value-shape discipline applied to every other
1819 /// typed slot:
1820 ///
1821 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
1822 /// same "0 means the opposite of what you think" footgun
1823 /// closed for `:politicas :timeout` (Envoy interprets a zero
1824 /// timeout as `infinite`), `:politicas :circuit-breaker
1825 /// :window`, and `:limits :wall-clock`. The
1826 /// `MaxIntensity / Period` ratio in Erlang/OTP's
1827 /// `supervisor` requires `Period > 0`; a zero period either
1828 /// trips on the first failure or never trips depending on
1829 /// operator interpretation, neither of which is the
1830 /// author's intent. Omit `:restart-window` to express "no
1831 /// reset"; carry a positive duration to express the window.
1832 /// - duplicate `:children` `:caixa` names are the same
1833 /// graph-node-set / multiset distinction closed for
1834 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
1835 /// and `:entrada :paths` (eb3456d). Two children with the
1836 /// same `:caixa` materialize as two ComputeUnits with the
1837 /// same name in the cluster's HelmRelease values, one
1838 /// silently overwriting the other. Erlang/OTP's
1839 /// `child_spec.id` is required-unique per supervisor;
1840 /// pleme-io enforces the same set-not-multiset shape on
1841 /// `:caixa` (the load-bearing identity in our renderer).
1842 pub fn validate(&self) -> Result<(), SupervisorError> {
1843 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
1844 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
1845 // error carrier's `estrategia:` field through the lifted
1846 // [`SupervisorSpec::estrategia`] accessor rather than the raw
1847 // `self.estrategia` field access — the two production consumers
1848 // of the per-`:supervisor` sibling-restart-strategy scalar now
1849 // key off exactly one typed dispatch on the substrate primitive,
1850 // so any future rebrand on the axis (a per-cluster strategy
1851 // override the operator pins through a future `:supervisor
1852 // :estrategia-overrides` slot, a per-tenant strategy-alias table
1853 // the M4 CR materializer resolves per-CR) migrates as a single
1854 // caixa-core edit rather than a coordinated rewrite of the two
1855 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
1856 // (921fe1b) four-consumer migration on the per-`:placement`
1857 // distribution-strategy axis.
1858 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
1859 // dispatch's paired `.is_empty()` cross-slot refusal probes
1860 // (the `SimpleOneForOne`-arm
1861 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
1862 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
1863 // refusal) through the lifted [`SupervisorSpec::children`]
1864 // slice-return accessor rather than the raw `self.children`
1865 // field access — the two paired production consumers of the
1866 // per-`:supervisor` static-child-list scalar-shape now key off
1867 // exactly one typed dispatch on the substrate primitive, so any
1868 // future rebrand on the axis (a per-cluster child-set overlay
1869 // the operator pins through a future `:supervisor
1870 // :children-overrides` slot, a per-tenant child-set-alias table
1871 // the M4 CR materializer resolves per-CR) migrates as a single
1872 // caixa-core edit rather than a coordinated rewrite of the
1873 // paired arms — first slice-return migration on any typed slot,
1874 // seed for the peer per-`:placement :clusters`,
1875 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
1876 // :instructions` `Vec`-carry axes.
1877 match self.estrategia() {
1878 RestartStrategy::SimpleOneForOne => {
1879 // SimpleOneForOne: children added at runtime. Static
1880 // list must be empty (one shape declared elsewhere).
1881 if !self.children().is_empty() {
1882 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
1883 }
1884 }
1885 _ => {
1886 if self.children().is_empty() {
1887 return Err(SupervisorError::no_children(self.estrategia()));
1888 }
1889 }
1890 }
1891 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
1892 // axis. See [`crate::render::require_positive_bounded_u32`] for
1893 // the ordering discipline (zero-floor arm strictly precedes cap
1894 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
1895 // diagnostic with its counter-axis remediation directly named,
1896 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
1897 // cap-arm miss). Until this bracket landed the top edge ran all
1898 // the way to `u32::MAX` and a struct-literal
1899 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
1900 // equivalent author-surface `:max-restarts 100000` /
1901 // `:max-restarts 4294967295` typo landing in the slot) silently
1902 // passed validate. The runtime substrate consuming the value
1903 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
1904 // wasm-operator's per-supervisor restart-intensity counter, the
1905 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1906 // admission webhook) then turned a typed `:max-restarts`
1907 // policy into a no-op supervisor: the escalation threshold is
1908 // structurally so high that no realistic
1909 // restarts-per-`:restart-window` traffic shape can reach it,
1910 // the supervisor never escalates to its parent, and a bad
1911 // child can loop inside the window indefinitely with the
1912 // parent supervisor structurally never receiving the "this
1913 // subtree has exceeded its restart budget" signal the typed
1914 // slot is meant to express. The bracket set is
1915 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
1916 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
1917 // the sibling `:politicas :circuit-breaker :max-failures` axis:
1918 // both are "trip the next-higher protection layer after N
1919 // events in a rolling window" counters with identical
1920 // degenerate-at-the-high-end shape and now share one canonical
1921 // bracket helper. The bracket precedes the sibling
1922 // `:restart-window` zero-floor / canonical-millisecond arms so
1923 // an over-cap `max_restarts` paired with a structurally invalid
1924 // window surfaces the bracket diagnostic first, mirroring the
1925 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
1926 // ordering on the peer `:politicas :circuit-breaker` slot.
1927 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
1928 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
1929 // accessor rather than the raw `self.max_restarts` field access —
1930 // the one production consumer of the per-`:supervisor`
1931 // restart-budget-count scalar now keys off exactly one typed
1932 // dispatch on the substrate primitive, so any future rebrand on
1933 // the axis (a per-cluster restart-budget override the operator
1934 // pins through a future `:supervisor :max-restarts-overrides`
1935 // slot, a per-tenant restart-budget-alias table the M4 CR
1936 // materializer resolves per-CR) migrates as a single caixa-core
1937 // edit rather than a coordinated rewrite — sibling of the peer M3
1938 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
1939 // the per-`:politicas :circuit-breaker :max-failures` axis.
1940 crate::render::require_positive_bounded_u32(
1941 self.max_restarts(),
1942 SUPERVISOR_MAX_RESTARTS_MAX,
1943 || SupervisorError::ZeroMaxRestarts,
1944 SupervisorError::max_restarts_exceeds_cap,
1945 )?;
1946 // Route the [`SupervisorSpec::validate`] `:restart-window`
1947 // zero-floor + integer-millisecond canonical-form + upper-cap
1948 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
1949 // accessor rather than the raw `self.restart_window` field access —
1950 // the one production consumer of the per-`:supervisor`
1951 // restart-intensity-denominator scalar now keys off exactly one
1952 // typed dispatch on the substrate primitive, so any future rebrand
1953 // on the axis (a per-cluster restart-window override the operator
1954 // pins through a future `:supervisor :restart-window-overrides`
1955 // slot, a per-tenant restart-window-alias table the M4 CR
1956 // materializer resolves per-CR) migrates as a single caixa-core
1957 // edit rather than a coordinated rewrite — sibling of the peer M2
1958 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
1959 // on the per-`:limits :wall-clock` axis and the peer M3
1960 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
1961 // per-`:politicas :timeout` axis.
1962 if let Some(w) = self.restart_window() {
1963 // Zero-floor + integer-millisecond canonical-form +
1964 // upper-cap bracket on the typed `:restart-window` axis.
1965 // See
1966 // [`crate::render::require_positive_canonical_bounded_duration`]
1967 // for the full three-arm ordering discipline (zero-floor
1968 // strictly precedes canonical-form so `Duration::ZERO`
1969 // surfaces the self-locating `RestartWindowZero`
1970 // diagnostic; canonical-form strictly precedes the cap arm
1971 // so a sub-millisecond above-cap value surfaces the more
1972 // fundamental round-trip-shape diagnostic first) and the
1973 // three peer typed-`Duration` sites that share this
1974 // canonical bracket ([`crate::MeshPolicy::timeout`],
1975 // [`crate::CircuitBreaker::window`],
1976 // [`crate::LimitsSpec::wall_clock`]). Every validated
1977 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1978 // (1ms..=1h), integer-millisecond granularity.
1979 crate::render::require_positive_canonical_bounded_duration(
1980 w,
1981 SUPERVISOR_RESTART_WINDOW_MAX,
1982 || SupervisorError::RestartWindowZero,
1983 SupervisorError::restart_window_not_canonical,
1984 SupervisorError::restart_window_exceeds_cap,
1985 )?;
1986 }
1987 // Route the per-child DNS-1123 / semver-requirement / duplicate-
1988 // detection fan-out loop through the lifted named per-slot gate
1989 // [`SupervisorSpec::validate_children`] rather than an inline
1990 // three-per-child cascade — every future consumer that wants to
1991 // re-check only the `:children` slot's per-entry axes (the M4
1992 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1993 // admission webhook re-validating one added/renamed child, the
1994 // future wasm-operator's per-child dynamic-add re-validator on
1995 // the `SimpleOneForOne` runtime-add path once dynamic-children
1996 // graduate to a typed slot, a future partial re-validator on a
1997 // per-`:children`-entry patch) reaches every per-entry axis
1998 // through one dispatch rather than re-inlining the three-arm
1999 // cascade in lockstep with `validate` or paying the peer
2000 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2001 // reach one entry check. Sibling of the peer M3 mesh-slot
2002 // per-slot gate family (`validate_membros` — the exact peer on
2003 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2004 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2005 // `validate_placement`; `validate_politicas` routing through
2006 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2007 // per-slot gate discipline now spans both the M3 mesh-slot
2008 // family and the M2 `:children` per-child-cascade axis on one
2009 // shape: one named per-slot gate per typed per-entry loop.
2010 self.validate_children()?;
2011 Ok(())
2012 }
2013
2014 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2015 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2016 /// gate, and duplicate-`:caixa` dedup arm into one call every
2017 /// consumer that wants to re-validate one `:children` entry (or the
2018 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2019 /// admits reaches through.
2020 ///
2021 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2022 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2023 /// three-per-entry shape (DNS-1123 name + semver-requirement +
2024 /// duplicate-`:caixa` dedup), lifted to one named substrate
2025 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2026 /// materializer's admission webhook re-checking one added or renamed
2027 /// child, the future wasm-operator's per-child dynamic-add
2028 /// re-validator on the `SimpleOneForOne` runtime-add path once
2029 /// dynamic-children graduate to a typed slot, a future partial
2030 /// re-validator on a per-`:children`-entry patch — each reaches the
2031 /// three per-entry axes through this one dispatch rather than
2032 /// re-inlining the three-arm cascade in lockstep with `validate`
2033 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2034 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2035 /// reach one entry check.
2036 ///
2037 /// Self-contained on `&self` — resolves its own dedup `HashSet`
2038 /// through [`SupervisorSpec::children`] rather than borrowing one
2039 /// threaded down from `validate`, the same posture the peer M3
2040 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2041 /// [`crate::AplicacaoSpec::validate_contratos`],
2042 /// [`crate::AplicacaoSpec::validate_entrada`],
2043 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2044 /// consumer that reaches this gate directly (without first calling
2045 /// `validate`) still runs the full per-child cascade — pinned by
2046 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2047 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2048 /// + `validate_children_is_self_contained_on_children_slot`.
2049 ///
2050 /// The three per-entry arms run in the same canonical order the
2051 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2052 /// the diagnostic every author-declared per-`:children` entry surfaces
2053 /// through `validate` is byte-equal to the diagnostic this gate
2054 /// surfaces when called directly — the equivalence-pin pair
2055 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2056 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2057 /// asserts the two altitudes discriminate the same set on every
2058 /// per-entry-covered input.
2059 pub fn validate_children(&self) -> Result<(), SupervisorError> {
2060 let mut seen = std::collections::HashSet::new();
2061 for child in self.children() {
2062 // Every emitted cluster artifact's `metadata.name` for a
2063 // supervised child derives from this `:children :caixa` value
2064 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2065 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2066 // label value on every child's pod identity, and the per-
2067 // child K8s [`Service`][svc] `metadata.name` the future
2068 // wasm-operator (M3) provisions for inter-child supervision
2069 // tree wiring. Each apiserver-side schema on each landing
2070 // site enforces the DNS-1123 label rule on admission; a
2071 // structurally invalid child name (`"Worker"`, `"my_worker"`,
2072 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2073 // UUID-shaped mistaken-identity slug) silently passes the
2074 // prior empty-/duplicate-only gate and the failure surfaces
2075 // at `kubectl apply` time as a `metadata.name: Invalid value`
2076 // rejection, far from the source caixa.lisp, with no field
2077 // naming the offending `:children` entry. Lifting the gate
2078 // to caixa-build time mirrors the `:membros :caixa` value-
2079 // shape trajectory (3f9d7a0) and the `:placement :clusters`
2080 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2081 // identifier axis — the supervisor tree's child names —
2082 // through the lifted
2083 // [`crate::render::require_valid_dns_1123_label`] gate the
2084 // seven peer name axes (`:membros :caixa`, `:placement
2085 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2086 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2087 // route through, so drift between the eight axes' accepted
2088 // DNS-1123-label sets is structurally impossible.
2089 //
2090 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2091 crate::render::require_valid_dns_1123_label(
2092 child.nome(),
2093 || SupervisorError::EmptyChildName,
2094 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2095 )?;
2096 // The author surface for `:children :versao` is the same
2097 // Cargo-shaped semver requirement string `:deps :versao` and
2098 // `:membros :versao` carry — and the lacre pipeline resolves
2099 // all three axes through the same
2100 // [`crate::version::parse_requirement`] entry-point. The
2101 // shared [`crate::render::require_valid_versao_requirement`]
2102 // helper brackets the empty-first + parse cascade both peer
2103 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2104 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2105 // :versao`) route through, so drift between the three axes'
2106 // accepted requirement sets is structurally impossible and
2107 // the parse-side no-op the empty-first arm closes (semver's
2108 // empty parse yields an implicit `*`) lives in exactly one
2109 // predicate. Every `ChildSpec::versao` past validate is
2110 // round-trippable through [`crate::parse_requirement`]
2111 // without re-checking at the resolver layer, and the three
2112 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2113 // are now structurally equivalent by construction.
2114 crate::render::require_valid_versao_requirement(
2115 child.versao_requirement(),
2116 || SupervisorError::empty_child_version(child.nome()),
2117 |reason| {
2118 SupervisorError::child_versao_invalid(
2119 child.nome(),
2120 child.versao_requirement(),
2121 reason,
2122 )
2123 },
2124 )?;
2125 crate::render::insert_first_seen(&mut seen, child.nome(), || {
2126 SupervisorError::duplicate_child_caixa(child.nome())
2127 })?;
2128 }
2129 Ok(())
2130 }
2131}
2132
2133/// Cross-slot coherence gate on the supervision tree: no
2134/// `:children :caixa` entry may name the supervisor's own `:nome`.
2135///
2136/// A supervisor that lists itself as a child is a degenerate self-parent
2137/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2138/// specs reference *distinct* child processes; a supervisor is never its
2139/// own child), and the wasm-operator's hierarchical reconciliation would
2140/// otherwise be handed a node that is its own parent: a one-node cycle it
2141/// either rejects far from the source `caixa.lisp` or recurses on. Because
2142/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2143/// lacre closure root), a child whose `:caixa` equals the supervisor's
2144/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2145///
2146/// Lives outside [`SupervisorSpec::validate`] because the typed view
2147/// carries the children but not the parent `:nome`; mirrors the
2148/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2149/// (which likewise reads one slot against another at the
2150/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2151/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2152/// node to itself is structurally not a tree/mesh edge" discipline, here
2153/// on the supervision-tree axis.
2154pub fn validate_no_self_supervision(
2155 children: &[ChildSpec],
2156 parent_nome: &str,
2157) -> Result<(), SupervisorError> {
2158 for child in children {
2159 if child.nome() == parent_nome {
2160 return Err(SupervisorError::child_supervises_self(parent_nome));
2161 }
2162 }
2163 Ok(())
2164}
2165
2166#[derive(Debug, Error, PartialEq, Eq)]
2167pub enum SupervisorError {
2168 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2169 NoChildren { estrategia: RestartStrategy },
2170 #[error(
2171 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2172 )]
2173 SimpleOneForOneWithStaticChildren,
2174 #[error(":max-restarts must be > 0")]
2175 ZeroMaxRestarts,
2176 #[error(
2177 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2178 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2179 restart-intensity policy into a no-op supervisor: the escalation threshold is \
2180 structurally so high that no realistic restarts-per-:restart-window traffic shape \
2181 can reach it, so the supervisor never escalates to its parent and a bad child can \
2182 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2183 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2184 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2185 materializer's admission webhook) emits a `:max-restarts` declaration that is \
2186 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2187 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2188 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2189 band) or restructure the supervision tree (split the flaky child into its own \
2190 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2191 )]
2192 MaxRestartsExceedsCap { max_restarts: u32 },
2193 #[error(
2194 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2195 requires Period > 0; a zero window either trips on the first failure or \
2196 never trips depending on operator interpretation. Omit :restart-window to \
2197 express `never reset`; carry a positive duration to express the window."
2198 )]
2199 RestartWindowZero,
2200 #[error(
2201 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2202 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2203 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2204 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2205 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2206 )]
2207 RestartWindowNotCanonical { window: Duration },
2208 #[error(
2209 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2210 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2211 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2212 failure-counting window is structurally so long that transient restarts are never \
2213 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2214 when the child has exceeded its restart budget within the recent window` to `trip the \
2215 parent when the child has exceeded its restart budget over its lifetime`, and the \
2216 supervisor's reset semantic never reaches the child — every typed-slot consumer \
2217 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2218 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2219 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2220 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2221 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2222 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2223 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2224 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2225 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2226 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2227 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2228 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2229 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2230 hiding it behind a rolling-window declaration the cap arm rejects)"
2231 )]
2232 RestartWindowExceedsCap { window: Duration },
2233 #[error("child entry has empty :caixa name")]
2234 EmptyChildName,
2235 #[error(
2236 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2237 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2238 name / label value the child name lands in — the per-child \
2239 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2240 label value, and the future wasm-operator per-child Service `metadata.name` \
2241 — each apiserver-side schema rejects names that don't match; use a \
2242 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2243 )]
2244 ChildCaixaInvalid { caixa: String, reason: String },
2245 #[error("child {caixa:?} has empty :versao constraint")]
2246 EmptyChildVersion { caixa: String },
2247 #[error(
2248 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2249 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2250 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2251 `:membros :versao` carry; the lacre pipeline resolves all three \
2252 through the same parser)"
2253 )]
2254 ChildVersaoInvalid {
2255 caixa: String,
2256 versao: String,
2257 reason: String,
2258 },
2259 #[error(
2260 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2261 child_spec.id per supervisor; duplicate children materialize as duplicate \
2262 ComputeUnits in the rendered chart, one silently overwriting the other)"
2263 )]
2264 DuplicateChildCaixa { caixa: String },
2265 #[error(
2266 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2267 never its own child (the supervision tree is a DAG rooted at the supervisor; \
2268 OTP child specs reference distinct child processes). Since every :nome is a \
2269 globally-unique substrate identity, a child naming the supervisor's own :nome \
2270 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2271 self-referential :children entry or rename it to the actual child caixa."
2272 )]
2273 ChildSupervisesSelf { caixa: String },
2274}
2275
2276// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2277// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2278// and [`validate_no_self_supervision`] onto one substrate primitive per
2279// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2280// `LayoutError`-envelope constructor families the peer
2281// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2282// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2283// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2284// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2285// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2286// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2287// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2288// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2289// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2290// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2291// variants on `{ de, para }`) already at that discipline on the peer
2292// `AplicacaoError` envelopes.
2293//
2294// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2295// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2296// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2297// self-supervision arm) opened the identical
2298// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2299// the exact "same block re-inlined at every consumer" shape the PRIME
2300// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2301// `AplicacaoError` families each closed on their sibling envelopes. The
2302// three variants share one `{ caixa: String }` shape, so the fold routes
2303// each wire-up site through one dispatch per typed variant.
2304//
2305// The macro below generates one static constructor per variant of shape
2306// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2307// collapses onto one dispatch:
2308// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2309// struct-literal on the same `&str` fixture. The uniform one-field
2310// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2311// macro — rather than at every wire-up site. Every constructor is
2312// `#[must_use]` so a caller who mistakenly discards the constructed error
2313// trips a compile warning at the wire-up site.
2314//
2315// Every future consumer that wants to construct one of these three
2316// variants outside `SupervisorSpec::validate_children` /
2317// `validate_no_self_supervision` — a deferred
2318// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2319// webhook re-checking one added/renamed child, a future
2320// `feira validate --supervisor` per-caixa admission verb, a per-child
2321// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2322// once dynamic-children graduate to a typed slot, a per-Supervisor
2323// overlay resolver rejecting a duplicate/self-supervising child against
2324// a cluster-local snapshot — now reaches each variant through one call
2325// rather than re-inlining the three-line struct-literal in lockstep
2326// with the three in-crate wire-up sites.
2327macro_rules! supervisor_caixa_only_ctors {
2328 ($($ctor:ident => $variant:ident),* $(,)?) => {
2329 impl SupervisorError {
2330 $(
2331 #[doc = concat!(
2332 "Construct a [`SupervisorError::",
2333 stringify!($variant),
2334 "`] naming the offending `:children :caixa` (or ",
2335 "supervisor `:nome`, on the self-supervision arm). ",
2336 "Folds the uniform `Self::",
2337 stringify!($variant),
2338 " { caixa: caixa.to_string() }` one-field ",
2339 "struct-literal onto one substrate primitive so ",
2340 "every [`SupervisorSpec::validate_children`] / ",
2341 "[`validate_no_self_supervision`] wire-up on this ",
2342 "variant reads through one dispatch rather than the ",
2343 "pre-lift open-coded struct-literal block."
2344 )]
2345 #[must_use]
2346 pub fn $ctor(caixa: &str) -> Self {
2347 Self::$variant { caixa: caixa.to_string() }
2348 }
2349 )*
2350 }
2351 };
2352}
2353
2354supervisor_caixa_only_ctors! {
2355 empty_child_version => EmptyChildVersion,
2356 duplicate_child_caixa => DuplicateChildCaixa,
2357 child_supervises_self => ChildSupervisesSelf,
2358}
2359
2360// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2361// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2362// one substrate primitive per typed variant — the M2 supervisor-side siblings
2363// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2364// already lifted through the sibling
2365// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2366// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2367// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2368// String }` two-slot shape the peer seven-variant
2369// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2370// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2371// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2372// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2373// variant carries the `{ caixa: String, versao: String, reason: String }`
2374// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2375// carries on the same `:versao` value-shape.
2376//
2377// Each of the two wire-up sites opened the same closure-shaped
2378// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2379// [versao: child.versao_requirement().to_string(),] reason }` block inside
2380// the paired [`crate::render::require_valid_dns_1123_label`] and
2381// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2382// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2383// as a bug, on the same altitude the peer `AplicacaoError` /
2384// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
2385// families already closed on their sibling envelopes.
2386//
2387// The two `#[must_use]` inherent constructors below fold each wire-up onto
2388// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
2389// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
2390// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
2391// The uniform per-field `.to_string()` / `.into()` construction is spelled
2392// once — inside each ctor body — rather than at every wire-up site. The
2393// `reason: impl Into<String>` bound accepts both `&str` literals and
2394// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
2395// diagnostic shape at the lift, matching the peer
2396// [`aplicacao_field_reason_ctors!`] and
2397// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
2398// sibling envelopes.
2399//
2400// Every future consumer that wants to construct one of these two variants
2401// outside `SupervisorSpec::validate_children` — a deferred
2402// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
2403// re-checking one added/renamed child's `:caixa` or `:versao`, a future
2404// `feira validate --supervisor` per-caixa admission verb, a per-child
2405// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
2406// dynamic-children graduate to a typed slot, a per-Supervisor overlay
2407// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
2408// cluster-local snapshot — now reaches each variant through one call rather
2409// than re-inlining the per-shape struct-literal block in lockstep with the
2410// two in-crate wire-up sites.
2411impl SupervisorError {
2412 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
2413 /// offending `:children :caixa` value under the given `reason`. Folds
2414 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
2415 /// reason: reason.into() }` two-slot struct-literal onto one substrate
2416 /// primitive so every wire-up on this variant reads through one
2417 /// dispatch, matching the peer
2418 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
2419 /// sibling `AplicacaoError { caixa: String, reason: String }`
2420 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
2421 /// outputs through the `impl Into<String>` bound.
2422 #[must_use]
2423 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
2424 Self::ChildCaixaInvalid {
2425 caixa: caixa.to_string(),
2426 reason: reason.into(),
2427 }
2428 }
2429
2430 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
2431 /// offending `:children :caixa` and its `:versao` requirement under
2432 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
2433 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
2434 /// reason.into() }` three-slot struct-literal onto one substrate
2435 /// primitive so every wire-up on this variant reads through one
2436 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
2437 /// { caixa, versao, reason }` three-slot axis on the peer
2438 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
2439 /// and `format!(…)` outputs through the `impl Into<String>` bound.
2440 #[must_use]
2441 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
2442 Self::ChildVersaoInvalid {
2443 caixa: caixa.to_string(),
2444 versao: versao.to_string(),
2445 reason: reason.into(),
2446 }
2447 }
2448}
2449
2450// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
2451// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
2452// three bracket-arms — one struct-literal at the `:children`-empty
2453// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
2454// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
2455// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
2456// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
2457// [`crate::render::require_positive_canonical_bounded_duration`]
2458// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
2459// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
2460// primitive per typed variant, matching the sibling
2461// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
2462// variants on the same `{ <field>: Duration | u32 }` shape) at that
2463// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
2464// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
2465// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
2466// wire-up site through one dispatch per typed variant without a runtime-
2467// work delta.
2468//
2469// Each of the four wire-up sites opened the identical
2470// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
2471// exact "same block re-inlined at every consumer" shape the PRIME
2472// DIRECTIVE names as a bug, on the same altitude the peer
2473// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
2474// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
2475// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
2476// the fold routes each wire-up site through one dispatch per typed
2477// variant.
2478//
2479// The macro below generates one static constructor per variant of shape
2480// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
2481// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
2482// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
2483// fixture — as a direct call at the [`SupervisorSpec::validate`]
2484// `:children`-empty refusal, or as a bare function pointer in the
2485// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
2486// [`crate::render::require_positive_bounded_u32`] /
2487// [`crate::render::require_positive_canonical_bounded_duration`] gate
2488// carries — rather than the pre-lift open-coded one-line closure over
2489// the same one-field struct-literal. `const fn` preserves the `Copy`-
2490// pass-through's zero-runtime-work property verbatim. Every constructor
2491// is `#[must_use]` so a caller who mistakenly discards the constructed
2492// error trips a compile warning at the wire-up site.
2493//
2494// Every future consumer that wants to construct one of these four
2495// variants outside `SupervisorSpec::validate` — a deferred
2496// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2497// webhook re-checking one edited `:estrategia` / `:max-restarts` /
2498// `:restart-window` slot against the cap + canonical-form cascade, a
2499// future `feira validate --supervisor` per-caixa admission verb re-
2500// running the shape gates on demand, a per-Supervisor overlay resolver
2501// rejecting an author-supplied slot against a cluster-local snapshot —
2502// now reaches each variant through one call rather than re-inlining the
2503// per-shape struct-literal block in lockstep with the four in-crate
2504// wire-up sites.
2505macro_rules! supervisor_scalar_ctors {
2506 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
2507 impl SupervisorError {
2508 $(
2509 #[doc = concat!(
2510 "Construct a [`SupervisorError::",
2511 stringify!($variant),
2512 "`] naming the offending per-`:supervisor` `",
2513 stringify!($field),
2514 "` scalar. Folds the uniform `Self::",
2515 stringify!($variant),
2516 " { ",
2517 stringify!($field),
2518 " }` one-field `Copy`-pass-through struct-literal onto ",
2519 "one substrate primitive so every per-axis wire-up on ",
2520 "this variant reads through one dispatch — as a direct ",
2521 "call (`SupervisorError::",
2522 stringify!($ctor),
2523 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
2524 "the same `Copy`-`",
2525 stringify!($ty),
2526 "` fixture) or as a bare function pointer in the ",
2527 "`impl FnOnce(",
2528 stringify!($ty),
2529 ") -> SupervisorError` bracket-closure slot every ",
2530 "`crate::render::require_positive_bounded_*` / ",
2531 "`crate::render::require_positive_canonical_bounded_*` ",
2532 "gate carries — rather than the pre-lift open-coded ",
2533 "one-line closure over the same one-field struct-",
2534 "literal. `const fn` preserves the `Copy`-pass-through's ",
2535 "zero-runtime-work property verbatim."
2536 )]
2537 #[must_use]
2538 pub const fn $ctor($field: $ty) -> Self {
2539 Self::$variant { $field }
2540 }
2541 )*
2542 }
2543 };
2544}
2545
2546supervisor_scalar_ctors! {
2547 no_children => NoChildren { estrategia: RestartStrategy },
2548 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
2549 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
2550 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
2551}
2552
2553/// Shared duration string codec for the typed slots that take a
2554/// duration (`restart_window`, `MeshPolicy::timeout`,
2555/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
2556/// reuse it without duplicating the parser.
2557pub mod duration_codec {
2558 use super::Duration;
2559 use serde::{Deserializer, Serializer};
2560
2561 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
2562 // Route through the canonical [`crate::render::serialize_option_via_str`]
2563 // — the substrate-side single-owner primitive for the forward
2564 // arm of the typed-magnitude codec family. See its docstring
2565 // for the full sibling roster.
2566 crate::render::serialize_option_via_str(v, s, render)
2567 }
2568
2569 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
2570 // Route through the canonical [`crate::render::deserialize_option_via_str`]
2571 // — the substrate-side single-owner primitive for the reverse
2572 // arm of the typed-magnitude codec family. See its docstring
2573 // for the full sibling roster.
2574 crate::render::deserialize_option_via_str(d, parse)
2575 }
2576
2577 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
2578 // Paired whitespace-rejection arm — same canonical-form
2579 // render-determinism discipline as the peer
2580 // `limits::parse_byte_size` / `limits::parse_duration` /
2581 // `limits::parse_millicores` /
2582 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
2583 // byte-scan closes the WhatWG-conformant whitespace bytes
2584 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
2585 // `char::is_whitespace` scan closes the strictly-complementary
2586 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
2587 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
2588 // codepoints) that `str::trim` at parse entry silently strips.
2589 // Either drift class would round-trip through `render` to a
2590 // *different* canonical form on next emit — breaking the
2591 // THEORY.md Part V render-determinism contract on three typed-
2592 // duration slots at once (`:supervisor :restart-window`,
2593 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
2594 // via the shared codec.
2595 //
2596 // Routed through the lifted [`crate::render::reject_whitespace`]
2597 // primitive — the substrate-side single-owner paired-arm gate
2598 // every typed-magnitude codec in caixa-core shares.
2599 crate::render::reject_whitespace::<String, _, _>(
2600 s,
2601 |b| {
2602 format!(
2603 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
2604 authoring form for the typed duration slots routed through this shared codec \
2605 (`:supervisor :restart-window`, `:politicas :timeout`, \
2606 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2607 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
2608 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
2609 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
2610 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
2611 Part V render-determinism contract every typed slot carries. Strip every \
2612 whitespace byte (write `\"30s\"` verbatim)"
2613 )
2614 },
2615 |ch| {
2616 format!(
2617 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
2618 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
2619 duration slots routed through this shared codec (`:supervisor \
2620 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
2621 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
2622 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
2623 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
2624 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
2625 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
2626 `White_Space` property, strictly wider than the ASCII byte set) silently \
2627 strips it at parse entry, and the value round-trips through `render` to \
2628 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
2629 the THEORY.md Part V render-determinism contract every typed slot \
2630 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
2631 verbatim with only ASCII bytes)",
2632 cp = ch as u32
2633 )
2634 },
2635 )?;
2636 let s = s.trim();
2637 // Routed through the lifted
2638 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
2639 // the single-owner split every ASCII-alphabetic-unit typed-
2640 // magnitude codec in caixa-core (`limits::parse_byte_size` /
2641 // `limits::parse_duration` / this shared duration codec) shares.
2642 // See its docstring for the full sibling roster on the same
2643 // primitive altitude.
2644 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
2645 let num_trim = num_part.trim();
2646 // The canonical authoring form for every typed slot routed
2647 // through this shared codec — `:supervisor :restart-window`,
2648 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
2649 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
2650 // non-negative integer with no decimal point and no leading
2651 // sign, so the parser's accepted set must match for
2652 // serialize/deserialize to round-trip without canonical-form
2653 // drift. Until this gate landed the parser accepted any
2654 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
2655 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
2656 // tripped the value to a *different* canonical string on the
2657 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
2658 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
2659 // — breaking the THEORY.md Part V render-determinism contract
2660 // on three typed slots at once. Same canonical-form discipline
2661 // `crate::limits::parse_duration` (818dd38, the immediate
2662 // predecessor on the peer `:limits :wall-clock` codec) applies;
2663 // this gate lifts the discipline onto the shared codec that
2664 // backs the remaining three typed-duration slots in caixa-core.
2665 //
2666 // Strict canonical form: every byte of the magnitude is an
2667 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
2668 // inputs the gate distinguishes "non-canonical-but-numeric"
2669 // (parses as f64 or i64 — surfaced with a self-locating
2670 // diagnostic naming the canonical authoring form, the
2671 // round-trip drift each rejected shape would produce on first
2672 // serialize, and the canonical-form remediation) from
2673 // "garbage" (parses as neither — surfaced with the existing
2674 // narrower "bad duration magnitude" wording so its diagnostic
2675 // shape remains stable for the parser-shape footgun case).
2676 // The pre-existing `num < 0.0` arm is now unreachable — the
2677 // digit-only gate strictly precedes magnitude parsing, and a
2678 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
2679 // non-canonical-but-numeric branch with the `-30` named
2680 // verbatim in the diagnostic rather than the prior
2681 // value-laundered "negative duration in \"-30s\"" wording.
2682 //
2683 // Routed through the lifted
2684 // [`crate::render::is_digit_only_magnitude`] predicate — the
2685 // same source of truth the four peer typed-magnitude codec
2686 // sites share.
2687 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
2688 if !digit_only {
2689 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
2690 if numeric {
2691 return Err(format!(
2692 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
2693 canonical authoring form for the typed duration slots routed through \
2694 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2695 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2696 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
2697 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
2698 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
2699 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
2700 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
2701 THEORY.md Part V render-determinism contract every typed slot carries. \
2702 Pick an integer magnitude in the unit that divides cleanly (write \
2703 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
2704 ));
2705 }
2706 return Err(format!("bad duration magnitude in {s:?}"));
2707 }
2708 // Leading-zero arm — peer with the `rate_limit_codec` leading-
2709 // zero arm (4f46830) on the same canonical-form render-
2710 // determinism axis. The digit-only gate accepts `"030s"`,
2711 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
2712 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
2713 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
2714 // *different* canonical string on the next emit, breaking the
2715 // THEORY.md Part V render-determinism contract the same way
2716 // `"+30s"` did before the leading-`+` arm landed. The single-
2717 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
2718 // losslessly through `render` (`render(Duration::ZERO)` emits
2719 // `"0s"`) — the downstream semantic-zero gates (e.g.
2720 // `SupervisorError::ZeroRestartWindow` on
2721 // `:supervisor :restart-window`,
2722 // `AplicacaoError::PolicyTimeoutZero` /
2723 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
2724 // duration slots) refuse zero-magnitude authoring at the typed-
2725 // validate layer above, so the single-byte `"0"` stays in the
2726 // accepted set at this codec layer and the diagnostic
2727 // partitioning between canonical-form drift (this arm) and
2728 // semantic-zero (the downstream gates) remains stable.
2729 // Peer with the future leading-zero arms on the two remaining
2730 // typed-magnitude codecs the trajectory acknowledges:
2731 // `limits::parse_duration` backing `:limits :wall-clock`,
2732 // `limits::parse_byte_size` backing `:limits :memory` — each
2733 // carries the same canonical-form-drift class today; this
2734 // gate lands the discipline on the shared duration codec
2735 // first because the `rate_limit_codec` predecessor on the
2736 // same canonical-form-drift axis is the closest peer on the
2737 // trajectory.
2738 //
2739 // Routed through the lifted
2740 // [`crate::render::is_leading_zero_padded_magnitude`]
2741 // predicate — the same source of truth the four peer
2742 // typed-magnitude codec sites share.
2743 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
2744 return Err(format!(
2745 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
2746 canonical authoring form for the typed duration slots routed through \
2747 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2748 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2749 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
2750 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
2751 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
2752 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
2753 serialize — breaking the THEORY.md Part V render-determinism contract \
2754 every typed slot carries. Strip the leading zeros (write \
2755 `\"30s\"` instead of `\"030s\"`)"
2756 ));
2757 }
2758 // The digit-only gate guarantees every byte is `[0-9]`, and
2759 // the leading-zero arm above guarantees the magnitude is
2760 // either the single byte `"0"` or starts with `[1-9]`, so
2761 // the only way `u64::from_str` can fail here is overflow (the
2762 // magnitude exceeds `u64::MAX`). Surface that with an
2763 // overflow-shaped wording so the diagnostic names the offending
2764 // magnitude verbatim rather than collapsing onto the
2765 // non-canonical arm. The codec now operates on `u64` end-to-end
2766 // — every accepted magnitude is integer-exact; no f64 mantissa
2767 // drift between author-supplied magnitude and the consumer's
2768 // `Duration` value. Same shape `crate::limits::parse_duration`
2769 // (818dd38) carries on the peer `:limits :wall-clock` axis.
2770 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
2771 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
2772 })?;
2773 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
2774 // unit-arm dispatch through the canonical
2775 // [`crate::render::duration_from_integer_magnitude_and_unit`]
2776 // primitive — the substrate-side single-owner unit-dispatch
2777 // table every typed-duration codec in caixa-core routes
2778 // through (peer: `crate::limits::parse_duration` backing
2779 // `:limits :wall-clock`). Every unit conversion is integer-
2780 // exact for an integer magnitude; overflow surfaces via the
2781 // typed `DurationUnitError::Overflow { multiplier }`
2782 // discriminant so this arm reconstructs the pre-lift
2783 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
2784 // wording verbatim from `num` / `unit_trim` / the returned
2785 // `multiplier`, and the unknown-unit arm reconstructs the
2786 // pre-lift `"unknown duration unit \"<other>\""` wording from
2787 // the caller-scoped `unit_trim`. Load-bearing pinned by
2788 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
2789 let unit_trim = unit.trim();
2790 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
2791 |e| match e {
2792 crate::render::DurationUnitError::Overflow { multiplier } => format!(
2793 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
2794 ),
2795 crate::render::DurationUnitError::UnknownUnit => {
2796 format!("unknown duration unit {unit_trim:?}")
2797 }
2798 },
2799 )?;
2800 Ok(dur)
2801 }
2802
2803 /// Render a [`Duration`] in the canonical pleme-io duration string
2804 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
2805 /// caixa typed-duration slot serializes to and the same form K8s
2806 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
2807 /// EnvoyConfig per-route timeouts both expect (an integer
2808 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
2809 /// `+`). Lifted to `pub` so caixa-side renderers
2810 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
2811 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
2812 /// emitter, the future caixa-otel collector pipeline emitter) can
2813 /// consume the same canonical formatter without re-inlining the
2814 /// magnitude/unit decision tree (and inheriting the same drift
2815 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
2816 /// downstream apply-time parsing in non-obvious ways).
2817 pub fn render(d: Duration) -> String {
2818 let total_ms = d.as_millis();
2819 if total_ms == 0 {
2820 return "0s".into();
2821 }
2822 if total_ms.is_multiple_of(3600 * 1000) {
2823 return format!("{}h", total_ms / (3600 * 1000));
2824 }
2825 if total_ms.is_multiple_of(60 * 1000) {
2826 return format!("{}m", total_ms / (60 * 1000));
2827 }
2828 if total_ms.is_multiple_of(1000) {
2829 return format!("{}s", total_ms / 1000);
2830 }
2831 format!("{total_ms}ms")
2832 }
2833
2834 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
2835 ///
2836 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
2837 /// largest divisor unit, so any sub-millisecond residue
2838 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
2839 /// §V.2.7 render-determinism contract:
2840 ///
2841 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
2842 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
2843 /// `1_000_000` ns ≠ original `1_500_000` ns;
2844 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
2845 /// renders the literal `"0s"`, which the per-axis zero-floor gate
2846 /// on every typed-`Duration` slot then rejects on re-validate.
2847 ///
2848 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
2849 /// the codec's round-trippable accepted set lives in exactly one place —
2850 /// every typed-`Duration` slot that routes through this shared codec
2851 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
2852 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
2853 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
2854 /// every typed-`Duration` slot whose own codec shares the same
2855 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
2856 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
2857 /// pair) calls this predicate from its `validate()` to bracket the
2858 /// accepted set against the codec's accepted set, structurally. Drift
2859 /// between the codec's granularity and any typed slot's accepted set is
2860 /// then a single-source-of-truth edit at this predicate rather than a
2861 /// silent round-trip break the next consumer discovers at apply time.
2862 ///
2863 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
2864 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
2865 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
2866 /// family — same "typed-slot's valid set matches its codec's accepted
2867 /// set, structurally" discipline carried at the codec layer.
2868 #[must_use]
2869 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
2870 d.subsec_nanos().is_multiple_of(1_000_000)
2871 }
2872}
2873
2874/// Required-Duration variant for fields that aren't Option<Duration>.
2875pub mod duration_codec_required {
2876 use super::Duration;
2877 use serde::{Deserialize, Deserializer, Serializer};
2878
2879 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
2880 s.serialize_str(&super::duration_codec::render(*v))
2881 }
2882
2883 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
2884 let s = String::deserialize(d)?;
2885 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
2886 }
2887}
2888
2889#[cfg(test)]
2890mod tests {
2891 use super::*;
2892
2893 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
2894 ChildSpec {
2895 caixa: name.into(),
2896 versao: ver.into(),
2897 restart,
2898 }
2899 }
2900
2901 #[test]
2902 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
2903 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
2904 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
2905 // posture. Each accessor projects the per-`:children :caixa`
2906 // / per-`:children :versao` [`String`] storage through the
2907 // `pub const fn` [`String::as_str`] (const-stable since Rust
2908 // 1.87, well within the workspace MSRV) — any future
2909 // accidental downgrade to non-`const` fails the corresponding
2910 // `<name>_via_const_fn` wrapper at caixa-core build time with
2911 // E0015 (`cannot call non-const method`), strictly stronger
2912 // than a runtime `assert!`. Sibling of the peer
2913 // per-M2/M3/universal-axis `String → &str` scalar-accessor
2914 // family pins on the sibling `const`-eval-surface passes
2915 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
2916 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
2917 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
2918 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
2919 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
2920 // [`crate::aplicacao::Entrada::destination`] at the M3
2921 // ingress axis,
2922 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
2923 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
2924 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
2925 // axis, and the per-`:contratos`
2926 // [`crate::aplicacao::WitContract::source`] /
2927 // [`crate::aplicacao::WitContract::destination`] /
2928 // [`crate::aplicacao::WitContract::world_ref`] trio the
2929 // sibling pin at 279823b already anchors).
2930 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
2931 c.nome()
2932 }
2933 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
2934 c.versao_requirement()
2935 }
2936 for (caixa, versao) in [
2937 ("worker-a", "^0.1"),
2938 ("worker-b", "~0.2.3"),
2939 ("collector", "*"),
2940 ] {
2941 let c = child(caixa, versao, RestartPolicy::Permanent);
2942 assert_eq!(nome_via_const_fn(&c), c.nome());
2943 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
2944 assert_eq!(c.nome(), caixa);
2945 assert_eq!(c.versao_requirement(), versao);
2946 }
2947 }
2948
2949 #[test]
2950 fn supervisor_children_slice_return_accessor_is_const_fn() {
2951 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
2952 // `const`-eval-surface posture. The accessor destructures the
2953 // per-`:children` `Vec<ChildSpec>` storage through the
2954 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
2955 // 1.66, well within the workspace MSRV) — any future
2956 // accidental downgrade to non-`const` fails
2957 // `children_via_const_fn` at caixa-core build time with E0015
2958 // (`cannot call non-const method`), strictly stronger than a
2959 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
2960 // `Vec → &[T]` slice-return accessor family pin
2961 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
2962 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
2963 // per-`:membros` / per-`:contratos` slice-return axes, and of
2964 // the peer M2 upgrade-appup axis pin
2965 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
2966 // on the per-`:upgrade-from :instructions` slice-return axis.
2967 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
2968 s.children()
2969 }
2970 // Sweep both the empty-children (leaf-supervisor with no
2971 // static children — the `SimpleOneForOne` dynamic-child
2972 // arm's canonical shape) and the populated-children
2973 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
2974 // arm's canonical shape) axes so the accessor carries a
2975 // const-dispatch pin on both arms.
2976 let s_empty = SupervisorSpec {
2977 estrategia: RestartStrategy::SimpleOneForOne,
2978 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
2979 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2980 children: vec![],
2981 };
2982 assert!(children_via_const_fn(&s_empty).is_empty());
2983 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
2984 let s_full = SupervisorSpec {
2985 estrategia: RestartStrategy::OneForOne,
2986 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
2987 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2988 children: vec![
2989 child("worker-a", "^0.1", RestartPolicy::Permanent),
2990 child("worker-b", "~0.2.3", RestartPolicy::Transient),
2991 child("collector", "*", RestartPolicy::Temporary),
2992 ],
2993 };
2994 assert_eq!(children_via_const_fn(&s_full).len(), 3);
2995 assert_eq!(children_via_const_fn(&s_full), s_full.children());
2996 }
2997
2998 #[test]
2999 fn default_has_one_for_one_and_5_restarts_in_60s() {
3000 let s = SupervisorSpec::default();
3001 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3002 assert_eq!(s.max_restarts, 5);
3003 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3004 assert!(s.children.is_empty());
3005 }
3006
3007 #[test]
3008 fn validate_one_for_one_requires_children() {
3009 let mut s = SupervisorSpec::default();
3010 s.children = vec![];
3011 assert!(matches!(
3012 s.validate().unwrap_err(),
3013 SupervisorError::NoChildren { .. }
3014 ));
3015 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3016 s.validate().unwrap();
3017 }
3018
3019 #[test]
3020 fn validate_simple_one_for_one_forbids_static_children() {
3021 let mut s = SupervisorSpec {
3022 estrategia: RestartStrategy::SimpleOneForOne,
3023 ..SupervisorSpec::default()
3024 };
3025 s.children
3026 .push(child("w", "^0.1", RestartPolicy::Permanent));
3027 assert_eq!(
3028 s.validate().unwrap_err(),
3029 SupervisorError::SimpleOneForOneWithStaticChildren
3030 );
3031 s.children.clear();
3032 s.validate().unwrap();
3033 }
3034
3035 #[test]
3036 fn validate_rejects_zero_max_restarts() {
3037 let s = SupervisorSpec {
3038 max_restarts: 0,
3039 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3040 ..SupervisorSpec::default()
3041 };
3042 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3043 }
3044
3045 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3046 //
3047 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3048 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3049 // `:supervisor :max-restarts` axis — both fields are "trip the
3050 // next-higher protection layer after N events in a rolling window"
3051 // counters with identical degenerate-at-the-high-end shape, so the
3052 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3053 // exactly as it lies in `1..=1000` on the breaker side.
3054
3055 #[test]
3056 fn validate_rejects_max_restarts_above_cap() {
3057 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3058 // 1` is structurally one past the cap and silently passed
3059 // validate on every pre-gate codebase because the typed slot's
3060 // only check was the zero-floor arm. The no-op-supervisor vector
3061 // only surfaced at the runtime substrate (Erlang/OTP
3062 // MaxIntensity/Period ratio, the future wasm-operator's
3063 // per-supervisor restart-intensity counter) far from the source
3064 // caixa.lisp with no field naming the offending supervisor.
3065 let s = SupervisorSpec {
3066 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3067 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3068 ..SupervisorSpec::default()
3069 };
3070 assert_eq!(
3071 s.validate().unwrap_err(),
3072 SupervisorError::MaxRestartsExceedsCap {
3073 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3074 }
3075 );
3076 }
3077
3078 #[test]
3079 fn validate_rejects_max_restarts_far_above_cap() {
3080 // The `u32::MAX` worst case — the four-billion-restart
3081 // threshold a typo (`:max-restarts 4294967295`) or a
3082 // struct-literal copy-paste lands in the slot. Pin the cap
3083 // arm's coverage explicitly across the full `u32` overflow so
3084 // a future relaxation that drops the upper bound surfaces
3085 // here. Same shape every other typed-cap arm on this surface
3086 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3087 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3088 let s = SupervisorSpec {
3089 max_restarts: u32::MAX,
3090 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3091 ..SupervisorSpec::default()
3092 };
3093 assert_eq!(
3094 s.validate().unwrap_err(),
3095 SupervisorError::MaxRestartsExceedsCap {
3096 max_restarts: u32::MAX,
3097 }
3098 );
3099 }
3100
3101 #[test]
3102 fn validate_accepts_max_restarts_at_cap() {
3103 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3104 // must validate. The cap is inclusive on the top edge,
3105 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3106 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3107 // discipline on the sibling capped axes. Pin the boundary
3108 // explicitly so a future off-by-one tightening
3109 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3110 // here as a test failure rather than a silent contract
3111 // narrowing.
3112 let s = SupervisorSpec {
3113 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3114 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3115 ..SupervisorSpec::default()
3116 };
3117 s.validate()
3118 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3119 }
3120
3121 #[test]
3122 fn validate_accepts_max_restarts_typical_values() {
3123 // The documented production-playbook band positive-control
3124 // sweep — every value Erlang/OTP / Elixir / Riak Core /
3125 // RabbitMQ recommend (1..=100) must pass, plus a sweep
3126 // through the hyperscale band (200, 500, 1000) the cap
3127 // accepts. Pin the inclusive validated set explicitly so a
3128 // future tightening of the ceiling surfaces here.
3129 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3130 let s = SupervisorSpec {
3131 max_restarts: n,
3132 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3133 ..SupervisorSpec::default()
3134 };
3135 s.validate()
3136 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3137 }
3138 }
3139
3140 #[test]
3141 fn zero_max_restarts_takes_precedence_over_cap() {
3142 // The cross-arm ordering pin: `0` is structurally outside
3143 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3144 // (cap), but the zero-floor diagnostic is the more
3145 // self-locating one (it directly names the counter-axis
3146 // remediation), so the validate gate must fire on zero first.
3147 // Same shape every other zero-then-shape ordering on this
3148 // surface uses (PolicyRetriesZero then
3149 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3150 // PolicyBreakerMaxFailuresExceedsCap).
3151 let s = SupervisorSpec {
3152 max_restarts: 0,
3153 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3154 ..SupervisorSpec::default()
3155 };
3156 assert_eq!(
3157 s.validate().unwrap_err(),
3158 SupervisorError::ZeroMaxRestarts,
3159 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3160 );
3161 }
3162
3163 #[test]
3164 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3165 // The cross-arm ordering pin between the cap and the sibling
3166 // `:restart-window` gates (zero-window, canonical-window). A
3167 // supervisor carrying both an over-cap `max_restarts` AND a
3168 // structurally invalid window (zero, sub-ms) must surface the
3169 // cap diagnostic first — the cap arm is wired immediately
3170 // after the zero-restart arm and strictly before the window
3171 // arms, so the offending value the diagnostic names matches
3172 // the order the author would discover the gates by reading
3173 // top-to-bottom through `SupervisorSpec::validate`. Pin the
3174 // order so a future refactor that reorders the arms surfaces
3175 // here as a test failure rather than a silent diagnostic
3176 // regression. Peer of
3177 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3178 // on the sibling `:politicas :circuit-breaker` slot.
3179 let s = SupervisorSpec {
3180 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3181 restart_window: Some(Duration::ZERO),
3182 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3183 ..SupervisorSpec::default()
3184 };
3185 assert_eq!(
3186 s.validate().unwrap_err(),
3187 SupervisorError::MaxRestartsExceedsCap {
3188 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3189 },
3190 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3191 );
3192 }
3193
3194 #[test]
3195 fn max_restarts_cap_diagnostic_carries_offending_value() {
3196 // The diagnostic-shape pin: the offending `u32` is carried
3197 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3198 // variant so the surfaced error message names the value the
3199 // author wrote (`":supervisor :max-restarts (50000) exceeds the
3200 // supervisor-policy ceiling …"`), not just the cap. Same
3201 // self-locating diagnostic shape every other typed-cap arm on
3202 // this surface carries
3203 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3204 // the offending failure count verbatim,
3205 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3206 // retries count verbatim).
3207 let s = SupervisorSpec {
3208 max_restarts: 50_000,
3209 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3210 ..SupervisorSpec::default()
3211 };
3212 let err = s.validate().unwrap_err();
3213 assert!(
3214 matches!(
3215 err,
3216 SupervisorError::MaxRestartsExceedsCap {
3217 max_restarts: 50_000
3218 }
3219 ),
3220 "got {err:?}"
3221 );
3222 let msg = err.to_string();
3223 assert!(
3224 msg.contains("50000"),
3225 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3226 );
3227 }
3228
3229 #[test]
3230 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3231 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3232 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3233 // half of Learn You Some Erlang's worker-supervisor default,
3234 // sibling of the `60s` `Period` half that the paired
3235 // [`Default for SupervisorSpec`] impl already pins on the
3236 // sibling `restart_window` axis. Pinning the literal here
3237 // surfaces a future rebrand (a tightening to Elixir's `3`,
3238 // a widening to a per-cluster overlay the operator pins
3239 // through a future `:max-restarts-overrides` slot) as a
3240 // deliberate test edit, not a silent contract migration.
3241 // Peer of the sibling
3242 // [`supervisor_max_restarts_cap_pins_canonical_value`]
3243 // upper-bracket pin on the same axis.
3244 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3245 }
3246
3247 #[test]
3248 fn default_max_restarts_helper_routes_through_lifted_default() {
3249 // Composition pin: the private `default_max_restarts()`
3250 // serde-`#[serde(default = "…")]` helper on
3251 // [`SupervisorSpec::max_restarts`] must route through the
3252 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3253 // typed `pub const` rather than a raw `5` literal. Prior to
3254 // the lift the helper carried an inline `5` with no compile-
3255 // time link back to the shared default, so the wire-format
3256 // author-omitted arm and the caixa-core
3257 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3258 // arm could silently split on any future default rebrand.
3259 // Byte-parity against the lifted constant closes the split.
3260 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3261 }
3262
3263 #[test]
3264 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3265 // Composition pin: the [`Default for SupervisorSpec`] impl's
3266 // struct-literal `max_restarts` field must route through the
3267 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3268 // typed `pub const` (via the private helper this test's
3269 // sibling `default_max_restarts_helper_routes_through_lifted_default`
3270 // already pins onto the constant). Structurally: every
3271 // `SupervisorSpec::default()` call must yield a
3272 // `max_restarts` field byte-equal to the lifted constant
3273 // (the two paired defaults — the serde-side wire-format arm
3274 // and the struct-literal default arm — cannot silently split
3275 // on any future default rebrand). Peer of the sibling
3276 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3277 // — this pin closes the byte-parity arm on the two paired
3278 // altitude entry points onto the shared substrate constant.
3279 assert_eq!(
3280 SupervisorSpec::default().max_restarts(),
3281 SUPERVISOR_MAX_RESTARTS_DEFAULT,
3282 );
3283 }
3284
3285 #[test]
3286 fn supervisor_restart_window_default_pins_otp_canonical_value() {
3287 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3288 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3289 // Learn You Some Erlang's worker-supervisor default, paired
3290 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3291 // `MaxIntensity` half this constant is the sliding-window
3292 // denominator of on the same `MaxIntensity / Period`
3293 // restart-intensity ratio. Pinning the literal here surfaces a
3294 // future coherent rebrand of the paired default (Elixir's
3295 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3296 // the operator pins through a future
3297 // `:restart-window-overrides` slot) as a deliberate test edit,
3298 // not a silent contract migration. Peer of the sibling
3299 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3300 // paired-half pin on the same OTP-canonical default and the
3301 // [`supervisor_restart_window_cap_pins_canonical_value`]
3302 // upper-bracket pin on the same axis.
3303 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3304 }
3305
3306 #[test]
3307 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3308 // Composition pin: the [`Default for SupervisorSpec`] impl's
3309 // struct-literal `restart_window` field must route through the
3310 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3311 // typed `pub const` rather than a raw
3312 // `Duration::from_secs(60)` literal. Prior to this lift the
3313 // paired `{intensity, 5, 60}` OTP-canonical default was split
3314 // across two altitudes with no compile-time link between the
3315 // halves — the `MaxIntensity` half rode through the lifted
3316 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3317 // `Period` half rode as an open-coded literal at the
3318 // composition site, so a future coherent rebrand of the paired
3319 // canonical would have had to migrate one half through the
3320 // constant and the other through a raw literal in lockstep.
3321 // Byte-parity against the lifted constant on the `Period` half
3322 // closes the split — the paired OTP-canonical default now
3323 // migrates as one unit on any future axis change. Peer of the
3324 // sibling
3325 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3326 // byte-parity pin on the paired `MaxIntensity` half.
3327 assert_eq!(
3328 SupervisorSpec::default().restart_window(),
3329 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3330 );
3331 }
3332
3333 #[test]
3334 fn supervisor_estrategia_default_pins_otp_canonical_value() {
3335 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3336 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3337 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3338 // canonical default, paired with the sibling
3339 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3340 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3341 // this constant is the strategy discriminator of on the same
3342 // OTP-canonical worker-supervisor default. Pinning the arm here
3343 // surfaces a future coherent rebrand of the paired triple (Elixir's
3344 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3345 // intensity/period axes leaving this strategy arm untouched, an OTP
3346 // `rest_for_one` widening once the substrate discovers startup-
3347 // order-coupled child cohorts as the more common worker-supervisor
3348 // shape, a per-cluster overlay the operator pins through a future
3349 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3350 // supervision-canary roadmap acknowledges) as a deliberate test
3351 // edit, not a silent contract migration. Peer of the sibling
3352 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3353 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3354 // paired-half pins on the same OTP-canonical default.
3355 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3356 }
3357
3358 #[test]
3359 fn restart_strategy_default_routes_through_lifted_default() {
3360 // Composition pin: the [`Default for RestartStrategy`] impl's
3361 // return arm must route through the substrate-canonical
3362 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3363 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3364 // an inline `Self::OneForOne` with no compile-time link back to
3365 // the shared OTP-canonical `one_for_one` strategy the paired
3366 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3367 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3368 // `.unwrap_or_default()` (now
3369 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3370 // so a future rebrand of the OTP-canonical strategy default (an
3371 // OTP `rest_for_one` widening once the substrate discovers
3372 // startup-order-coupled child cohorts as the more common worker-
3373 // supervisor shape, a per-cluster overlay the operator pins
3374 // through a future `:estrategia-overrides` slot) would have had to
3375 // be threaded through the `Default` impl and the two peer routes
3376 // in lockstep or the three consumers would silently split. Byte-
3377 // parity against the lifted constant closes the split. Peer of
3378 // the sibling
3379 // [`default_max_restarts_helper_routes_through_lifted_default`] +
3380 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3381 // composition pins on the paired `MaxIntensity` + `Period` halves.
3382 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3383 }
3384
3385 #[test]
3386 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3387 // Composition pin: the [`Default for SupervisorSpec`] impl's
3388 // struct-literal `estrategia` field must route through the
3389 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3390 // `pub const` (either directly, or via the
3391 // [`RestartStrategy::default`] impl that the sibling
3392 // `restart_strategy_default_routes_through_lifted_default` pin
3393 // already routes onto the constant). Structurally: every
3394 // `SupervisorSpec::default()` call must yield an `estrategia`
3395 // field byte-equal to the lifted constant (the three paired
3396 // defaults — the [`Default for RestartStrategy`] impl arm, the
3397 // struct-literal default arm here, and the
3398 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3399 // silently split on any future default rebrand). Peer of the
3400 // sibling
3401 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3402 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3403 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3404 // of the same `SupervisorSpec::default()` composed altitude.
3405 assert_eq!(
3406 SupervisorSpec::default().estrategia(),
3407 SUPERVISOR_ESTRATEGIA_DEFAULT,
3408 );
3409 }
3410
3411 #[test]
3412 fn supervisor_child_restart_default_pins_otp_canonical_value() {
3413 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
3414 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
3415 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
3416 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
3417 // half of the same OTP-shape supervisor-tree default set whose
3418 // per-`:supervisor` halves the sibling
3419 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3420 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
3421 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
3422 // arm here surfaces a future rebrand of the per-child default (an
3423 // OTP-`transient` widening once the substrate discovers clean-
3424 // completion-aware children as the more common child shape, a
3425 // per-cluster overlay the operator pins through a future
3426 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
3427 // supervision-canary roadmap acknowledges) as a deliberate test
3428 // edit, not a silent contract migration. Peer of the sibling
3429 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
3430 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
3431 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3432 // value pins on the per-`:supervisor` halves.
3433 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
3434 }
3435
3436 #[test]
3437 fn restart_policy_default_routes_through_lifted_default() {
3438 // Composition pin: the [`Default for RestartPolicy`] impl's return
3439 // arm must route through the substrate-canonical
3440 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
3441 // than a raw `Self::Permanent` arm. Prior to the lift the impl
3442 // carried an inline `Self::Permanent` with no compile-time link
3443 // back to the OTP-shape supervisor-tree default set whose three
3444 // per-`:supervisor` halves already rode through lifted constants
3445 // — so a future coherent rebrand of the set would have had to
3446 // migrate three halves through typed constants and this fourth
3447 // through a raw enum arm in lockstep or the supervisor-level and
3448 // child-level defaults would silently drift apart. Byte-parity
3449 // against the lifted constant closes the split. Peer of the
3450 // sibling
3451 // [`restart_strategy_default_routes_through_lifted_default`]
3452 // composition pin on the per-`:supervisor` `:estrategia` axis.
3453 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
3454 }
3455
3456 #[test]
3457 fn child_spec_serde_default_restart_routes_through_lifted_default() {
3458 // Composition pin: the serde-side `#[serde(default)]` on
3459 // [`ChildSpec::restart`] — the wire-format author-omitted
3460 // `:children :restart` arm — must resolve onto the substrate-
3461 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
3462 // (via the [`Default for RestartPolicy`] impl the sibling
3463 // `restart_policy_default_routes_through_lifted_default` pin
3464 // already routes onto the constant). Structurally: a `ChildSpec`
3465 // deserialized from a payload that omits the `restart` key must
3466 // yield a `restart` field byte-equal to the lifted constant, so
3467 // the wire-format author-omitted arm and the
3468 // [`RestartPolicy::default`] impl arm cannot silently split on any
3469 // future default rebrand. Peer of the sibling
3470 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
3471 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3472 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3473 // byte-parity pins on the per-`:supervisor` halves of the same
3474 // author-omitted-slot resolution surface.
3475 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
3476 .expect("ChildSpec must deserialize with the restart key omitted");
3477 assert_eq!(
3478 omitted.restart(),
3479 SUPERVISOR_CHILD_RESTART_DEFAULT,
3480 "an author-omitted :children :restart slot must degrade onto \
3481 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
3482 {:?}, expected {:?})",
3483 omitted.restart(),
3484 SUPERVISOR_CHILD_RESTART_DEFAULT,
3485 );
3486 }
3487
3488 #[test]
3489 fn supervisor_max_restarts_cap_pins_canonical_value() {
3490 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
3491 // 1000 — the same ceiling the peer
3492 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
3493 // `:politicas :circuit-breaker :max-failures` axis (both are
3494 // "trip the next-higher protection layer after N events in a
3495 // rolling window" counters with identical
3496 // degenerate-at-the-high-end shape; uniform top edge so the
3497 // M4 CR materializers and the wasm-operator reconciler reach
3498 // for either field knowing the value is in `1..=1000`). Two
3499 // orders of magnitude above every documented Erlang/OTP /
3500 // Elixir / Riak Core / RabbitMQ production-playbook
3501 // recommendation band and below the clearly-pathological
3502 // "effectively no escalation" floor (10_000, 100_000,
3503 // u32::MAX). Pinning the literal value here surfaces a future
3504 // drift (a relaxation to 10_000, a tightening to 100) as a
3505 // deliberate test edit, not a silent contract narrowing.
3506 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
3507 }
3508
3509 #[test]
3510 fn validate_rejects_empty_child_name() {
3511 let s = SupervisorSpec {
3512 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3513 ..SupervisorSpec::default()
3514 };
3515 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
3516 }
3517
3518 #[test]
3519 fn validate_rejects_empty_child_version() {
3520 let s = SupervisorSpec {
3521 children: vec![child("w", "", RestartPolicy::Permanent)],
3522 ..SupervisorSpec::default()
3523 };
3524 assert!(matches!(
3525 s.validate().unwrap_err(),
3526 SupervisorError::EmptyChildVersion { .. }
3527 ));
3528 }
3529
3530 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
3531
3532 #[test]
3533 fn validate_rejects_invalid_child_versao_requirement() {
3534 // The fail-before-pass-after pin: a non-empty but malformed
3535 // semver requirement (`"^bad-version"`) silently passed
3536 // `validate()` on every pre-gate codebase because the prior
3537 // shape only refused the empty string. The parse failure
3538 // surfaced far downstream at lacre-resolve time with a
3539 // `semver::Error` that didn't name which `:children` entry
3540 // carried the typo. The new gate moves the check to caixa-build
3541 // time at the source caixa.lisp — the third `:versao` typed
3542 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
3543 // structural parity.
3544 let s = SupervisorSpec {
3545 children: vec![
3546 child("worker", "^0.1", RestartPolicy::Permanent),
3547 child("cache", "^bad-version", RestartPolicy::Transient),
3548 ],
3549 ..SupervisorSpec::default()
3550 };
3551 let err = s.validate().unwrap_err();
3552 assert!(
3553 matches!(
3554 err,
3555 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3556 if caixa == "cache" && versao == "^bad-version"
3557 ),
3558 "got {err:?}"
3559 );
3560 }
3561
3562 #[test]
3563 fn validate_rejects_child_versao_with_double_caret_typo() {
3564 // `"^^0.1"` is the canonical doubled-caret typo — looks
3565 // Cargo-shaped on first glance but fails the parser because
3566 // semver doesn't accept stacked operators. Pin this
3567 // adjacent-shape footgun explicitly so a future relaxation that
3568 // accepts "looks-canonical-but-isn't" forms surfaces here.
3569 let s = SupervisorSpec {
3570 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
3571 ..SupervisorSpec::default()
3572 };
3573 let err = s.validate().unwrap_err();
3574 assert!(
3575 matches!(
3576 err,
3577 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3578 if caixa == "worker" && versao == "^^0.1"
3579 ),
3580 "got {err:?}"
3581 );
3582 }
3583
3584 #[test]
3585 fn validate_rejects_child_versao_with_v_prefixed_tag() {
3586 // `"v0.1"` is the canonical "git-tag-shape leaking into the
3587 // semver requirement slot" typo — an author copies the
3588 // publish-side git-tag string verbatim into `:versao`, but
3589 // Cargo's semver parser rejects the leading `v`. Same
3590 // adjacent-shape footgun pinned for `:membros :versao`
3591 // (9888b13).
3592 let s = SupervisorSpec {
3593 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
3594 ..SupervisorSpec::default()
3595 };
3596 let err = s.validate().unwrap_err();
3597 assert!(
3598 matches!(
3599 err,
3600 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3601 if caixa == "worker" && versao == "v0.1"
3602 ),
3603 "got {err:?}"
3604 );
3605 }
3606
3607 #[test]
3608 fn validate_accepts_canonical_child_versao_forms() {
3609 // The Cargo-shaped requirement forms `:deps :versao` and
3610 // `:membros :versao` already accept via
3611 // `crate::parse_requirement` must pass the children gate
3612 // without re-validating at the resolver layer. Pin every leg so
3613 // a future tightening of the canonical set surfaces here as a
3614 // test failure.
3615 for form in [
3616 "^0.1", // caret — minor-range pin (the most common shape)
3617 "~0.1.2", // tilde — patch-range pin
3618 "0.1.0", // exact — single-version pin
3619 "*", // wildcard — any version (semver::VersionReq::STAR)
3620 ">=0.1, <2", // multi-range — comma-separated comparators
3621 ] {
3622 let s = SupervisorSpec {
3623 children: vec![child("worker", form, RestartPolicy::Permanent)],
3624 ..SupervisorSpec::default()
3625 };
3626 s.validate()
3627 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3628 }
3629 }
3630
3631 #[test]
3632 fn child_versao_empty_takes_precedence_over_invalid() {
3633 // Order pin: the existing `EmptyChildVersion` diagnostic (which
3634 // doesn't try to parse) fires before the new
3635 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
3636 // `:versao` keeps its narrower error message —
3637 // `parse_requirement` would also reject `""`, but the
3638 // empty-string arm is the more self-locating diagnostic for the
3639 // author. Same ordering discipline as
3640 // `membro_versao_empty_takes_precedence_over_invalid` in
3641 // aplicacao.rs.
3642 let s = SupervisorSpec {
3643 children: vec![child("worker", "", RestartPolicy::Permanent)],
3644 ..SupervisorSpec::default()
3645 };
3646 let err = s.validate().unwrap_err();
3647 assert!(
3648 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
3649 "got {err:?}"
3650 );
3651 }
3652
3653 #[test]
3654 fn child_versao_invalid_fires_before_duplicate_check() {
3655 // Order pin: a malformed requirement on a non-duplicate entry
3656 // surfaces *its own* diagnostic (which names the offending
3657 // `:versao` string), even when a later entry would otherwise
3658 // collapse onto an earlier name. The per-entry shape gate runs
3659 // inline before the duplicate-key insert — parallel to
3660 // `membro_versao_invalid_fires_before_duplicate_check` in
3661 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
3662 let s = SupervisorSpec {
3663 children: vec![
3664 child("worker", "^bad", RestartPolicy::Permanent),
3665 child("cache", "^0.1", RestartPolicy::Transient),
3666 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
3667 ],
3668 ..SupervisorSpec::default()
3669 };
3670 let err = s.validate().unwrap_err();
3671 assert!(
3672 matches!(
3673 err,
3674 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
3675 ),
3676 "got {err:?}"
3677 );
3678 }
3679
3680 #[test]
3681 fn child_versao_invalid_diagnostic_carries_offending_versao() {
3682 // The diagnostic-shape pin: the error names the offending
3683 // `:versao` value verbatim so the author can grep their
3684 // caixa.lisp without re-running the build, and carries a
3685 // non-empty `reason` from `semver::VersionReq::parse` so the
3686 // parser's own wording flows through to the diagnostic.
3687 let s = SupervisorSpec {
3688 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
3689 ..SupervisorSpec::default()
3690 };
3691 let err = s.validate().unwrap_err();
3692 let SupervisorError::ChildVersaoInvalid {
3693 caixa,
3694 versao,
3695 reason,
3696 } = err
3697 else {
3698 panic!("expected ChildVersaoInvalid, got other variant");
3699 };
3700 assert_eq!(caixa, "worker");
3701 assert_eq!(versao, "not-a-req");
3702 assert!(
3703 !reason.is_empty(),
3704 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
3705 );
3706 }
3707
3708 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
3709
3710 #[test]
3711 fn validate_rejects_child_caixa_with_uppercase() {
3712 // The canonical "I copied the Servico's display name verbatim"
3713 // typo — child caixa names are lowercase per K8s DNS-1123 label
3714 // rule. The diagnostic names the offending name and suggests the
3715 // lower-cased fix in one edit, mirroring the
3716 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
3717 let s = SupervisorSpec {
3718 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
3719 ..SupervisorSpec::default()
3720 };
3721 let err = s.validate().unwrap_err();
3722 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3723 panic!("expected ChildCaixaInvalid, got other variant");
3724 };
3725 assert_eq!(caixa, "Worker");
3726 assert!(
3727 reason.contains("uppercase"),
3728 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
3729 );
3730 assert!(
3731 reason.contains("\"worker\""),
3732 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
3733 );
3734 }
3735
3736 #[test]
3737 fn validate_rejects_child_caixa_with_underscore() {
3738 // The canonical "I'm thinking of a Python module / Postgres
3739 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
3740 // label schema. K8s rejects `metadata.name: my_worker` at
3741 // admission time with an opaque `field is invalid` (no source-
3742 // citing diagnostic). The gate moves it to caixa-build time.
3743 let s = SupervisorSpec {
3744 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
3745 ..SupervisorSpec::default()
3746 };
3747 let err = s.validate().unwrap_err();
3748 assert!(
3749 matches!(
3750 err,
3751 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3752 if caixa == "my_worker" && reason.contains('_')
3753 ),
3754 "got {err:?}"
3755 );
3756 }
3757
3758 #[test]
3759 fn validate_rejects_child_caixa_with_dot() {
3760 // A `:children :caixa` entry is a single DNS-1123 label, not a
3761 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
3762 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
3763 // (3f9d7a0) on the peer name axis.
3764 let s = SupervisorSpec {
3765 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
3766 ..SupervisorSpec::default()
3767 };
3768 let err = s.validate().unwrap_err();
3769 assert!(
3770 matches!(
3771 err,
3772 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3773 if caixa == "team.worker" && reason.contains('.')
3774 ),
3775 "got {err:?}"
3776 );
3777 }
3778
3779 #[test]
3780 fn validate_rejects_child_caixa_with_leading_hyphen() {
3781 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
3782 // with an alphanumeric. The K8s apiserver rejects `-worker`
3783 // outright; the renderer would emit a `metadata.name: "-worker"`
3784 // that fails admission far from the source caixa.lisp.
3785 let s = SupervisorSpec {
3786 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
3787 ..SupervisorSpec::default()
3788 };
3789 let err = s.validate().unwrap_err();
3790 assert!(
3791 matches!(
3792 err,
3793 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
3794 if caixa == "-worker" && reason.contains("start and end")
3795 ),
3796 "got {err:?}"
3797 );
3798 }
3799
3800 #[test]
3801 fn validate_rejects_child_caixa_with_trailing_hyphen() {
3802 // The symmetric arm of the boundary rule. Pin separately so
3803 // both ends of the label are covered against a future relaxation
3804 // that only checks one boundary.
3805 let s = SupervisorSpec {
3806 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
3807 ..SupervisorSpec::default()
3808 };
3809 let err = s.validate().unwrap_err();
3810 assert!(
3811 matches!(
3812 err,
3813 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3814 if caixa == "worker-"
3815 ),
3816 "got {err:?}"
3817 );
3818 }
3819
3820 #[test]
3821 fn validate_rejects_child_caixa_with_unicode() {
3822 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
3823 // (`xn--…`) by the author before it reaches K8s. The byte-by-
3824 // byte ASCII validity check rejects multi-byte UTF-8 sequences
3825 // by the first byte that fails the `[a-z0-9-]` predicate.
3826 let s = SupervisorSpec {
3827 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
3828 ..SupervisorSpec::default()
3829 };
3830 let err = s.validate().unwrap_err();
3831 assert!(
3832 matches!(
3833 err,
3834 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3835 if caixa == "café"
3836 ),
3837 "got {err:?}"
3838 );
3839 }
3840
3841 #[test]
3842 fn validate_rejects_child_caixa_with_whitespace() {
3843 // Whitespace is the canonical "I pasted from a sketch / doc"
3844 // footgun. The apiserver rejects every `metadata.name` value
3845 // carrying whitespace; pin the gate fires at the right boundary.
3846 let s = SupervisorSpec {
3847 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
3848 ..SupervisorSpec::default()
3849 };
3850 let err = s.validate().unwrap_err();
3851 assert!(
3852 matches!(
3853 err,
3854 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
3855 if caixa == "my worker"
3856 ),
3857 "got {err:?}"
3858 );
3859 }
3860
3861 #[test]
3862 fn validate_rejects_child_caixa_too_long() {
3863 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
3864 // 63 bytes; the K8s apiserver rejects every `metadata.name`
3865 // axis over the limit at admission time. The diagnostic names
3866 // both the cap and the actual length so the author can shorten
3867 // in one edit, mirroring `rejects_membro_caixa_too_long`
3868 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
3869 let too_long = "a".repeat(64);
3870 let s = SupervisorSpec {
3871 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
3872 ..SupervisorSpec::default()
3873 };
3874 let err = s.validate().unwrap_err();
3875 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
3876 panic!("expected ChildCaixaInvalid, got other variant");
3877 };
3878 assert_eq!(caixa, too_long);
3879 assert!(
3880 reason.contains("63"),
3881 "diagnostic must name the 63-byte cap (got: {reason:?})"
3882 );
3883 assert!(
3884 reason.contains("64"),
3885 "diagnostic must name the actual length (got: {reason:?})"
3886 );
3887 }
3888
3889 #[test]
3890 fn child_caixa_max_length_validates() {
3891 // The 63-byte boundary control pin — exactly-at-the-cap is
3892 // accepted, mirroring `membro_caixa_max_length_validates`
3893 // (3f9d7a0) and `placement_cluster_max_length_validates`
3894 // (6cbb900). Pinned separately so a future off-by-one tightening
3895 // surfaces here.
3896 let max_label = "a".repeat(63);
3897 let s = SupervisorSpec {
3898 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
3899 ..SupervisorSpec::default()
3900 };
3901 s.validate().unwrap();
3902 }
3903
3904 #[test]
3905 fn validate_accepts_canonical_child_caixa_forms() {
3906 // The realistic shapes a supervised child's `:caixa` carries —
3907 // single-word `worker`, version-suffixed `cache-v2`, single-char
3908 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
3909 // `payment-retry`, all-digit `0`. Pin every leg so a future
3910 // tightening (e.g. requiring a leading lowercase letter) surfaces
3911 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
3912 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
3913 // (6cbb900).
3914 for form in [
3915 "worker",
3916 "cache-v2",
3917 "a",
3918 "db",
3919 "2-pool",
3920 "payment-retry",
3921 "0",
3922 ] {
3923 let s = SupervisorSpec {
3924 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
3925 ..SupervisorSpec::default()
3926 };
3927 s.validate()
3928 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3929 }
3930 }
3931
3932 #[test]
3933 fn child_caixa_empty_takes_precedence_over_invalid() {
3934 // Order pin: the existing `EmptyChildName` diagnostic (which
3935 // doesn't try to parse the DNS-1123 shape) fires before the new
3936 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
3937 // its narrower error message — `is_dns_1123_label` would reject
3938 // the empty string too (boundary check on the first byte), but
3939 // the empty-string arm is the more self-locating diagnostic for
3940 // the author. Same ordering discipline as
3941 // `membro_caixa_empty_takes_precedence_over_invalid` in
3942 // aplicacao.rs.
3943 let s = SupervisorSpec {
3944 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3945 ..SupervisorSpec::default()
3946 };
3947 let err = s.validate().unwrap_err();
3948 assert_eq!(err, SupervisorError::EmptyChildName);
3949 }
3950
3951 #[test]
3952 fn child_caixa_invalid_fires_before_versao_check() {
3953 // Order pin: the per-axis shape gate runs inline before the
3954 // per-entry versao check, so a malformed `:caixa` on an entry
3955 // whose `:versao` would also fail surfaces the more self-
3956 // locating name-axis diagnostic first. Parallel to
3957 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
3958 // and `placement_cluster_invalid_fires_before_duplicate_check`
3959 // (6cbb900).
3960 let s = SupervisorSpec {
3961 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
3962 ..SupervisorSpec::default()
3963 };
3964 let err = s.validate().unwrap_err();
3965 assert!(
3966 matches!(
3967 err,
3968 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
3969 ),
3970 "got {err:?}"
3971 );
3972 }
3973
3974 #[test]
3975 fn child_caixa_invalid_fires_before_duplicate_check() {
3976 // Order pin: a malformed name on a non-duplicate entry surfaces
3977 // its own diagnostic, even when a later entry would otherwise
3978 // collapse onto an earlier name. The per-entry shape gate runs
3979 // inline before the duplicate-key HashSet insert, mirroring
3980 // `placement_cluster_invalid_fires_before_duplicate_check`
3981 // (6cbb900).
3982 let s = SupervisorSpec {
3983 children: vec![
3984 child("Worker", "^0.1", RestartPolicy::Permanent),
3985 child("cache", "^0.1", RestartPolicy::Transient),
3986 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
3987 ],
3988 ..SupervisorSpec::default()
3989 };
3990 let err = s.validate().unwrap_err();
3991 assert!(
3992 matches!(
3993 err,
3994 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
3995 ),
3996 "got {err:?}"
3997 );
3998 }
3999
4000 #[test]
4001 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4002 // The diagnostic-shape pin: the error names the offending
4003 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4004 // the author can grep their caixa.lisp without re-running the
4005 // build. Mirrors the diagnostic-shape sweep on every prior
4006 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4007 let s = SupervisorSpec {
4008 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4009 ..SupervisorSpec::default()
4010 };
4011 let err = s.validate().unwrap_err();
4012 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4013 panic!("expected ChildCaixaInvalid, got other variant");
4014 };
4015 assert_eq!(caixa, "My_Worker");
4016 assert!(
4017 !reason.is_empty(),
4018 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4019 );
4020 }
4021
4022 // ── value-shape: zero restart_window + duplicate child names ──────────
4023
4024 #[test]
4025 fn validate_accepts_none_restart_window() {
4026 // Omitted `:restart-window` is the "never reset" sentinel —
4027 // valid by design. Mirrors :limits axes where None = unbounded.
4028 let s = SupervisorSpec {
4029 restart_window: None,
4030 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4031 ..SupervisorSpec::default()
4032 };
4033 s.validate().unwrap();
4034 }
4035
4036 #[test]
4037 fn validate_rejects_zero_restart_window() {
4038 // Same "0 means the opposite of what you think" footgun closed
4039 // for :politicas :timeout (Envoy treats 0s as infinite) and
4040 // :limits :wall-clock (wasmtime traps before the call starts).
4041 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4042 let s = SupervisorSpec {
4043 restart_window: Some(Duration::ZERO),
4044 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4045 ..SupervisorSpec::default()
4046 };
4047 assert_eq!(
4048 s.validate().unwrap_err(),
4049 SupervisorError::RestartWindowZero
4050 );
4051 }
4052
4053 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4054 //
4055 // The fourth (and last) typed-`Duration` axis in caixa-core to get
4056 // the integer-millisecond canonical-form gate — peer with
4057 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4058 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4059 // path is already gated at the shared codec layer (see
4060 // `restart_window_serde_rejects_fractional_seconds`); this arm
4061 // closes the programmatic-struct-literal path the codec gate can't
4062 // see.
4063
4064 #[test]
4065 fn validate_rejects_sub_millisecond_restart_window() {
4066 // The fail-before-pass-after pin: a programmatic
4067 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4068 // `validate` on every pre-gate codebase, then truncated to
4069 // `as_millis() == 1` on first serialize — the shared codec
4070 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4071 // 1_000_000 ns, the typed `restart_window` no longer matches
4072 // its rendered form.
4073 let s = SupervisorSpec {
4074 restart_window: Some(Duration::from_micros(1500)),
4075 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4076 ..SupervisorSpec::default()
4077 };
4078 match s.validate().unwrap_err() {
4079 SupervisorError::RestartWindowNotCanonical { window } => {
4080 assert_eq!(window, Duration::from_micros(1500));
4081 }
4082 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4083 }
4084 }
4085
4086 #[test]
4087 fn validate_rejects_one_nanosecond_restart_window() {
4088 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4089 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4090 // so the shared codec emits the literal `"0s"` — the next
4091 // serde round-trip would parse back to `Duration::ZERO`, which
4092 // the `RestartWindowZero` arm then rejects on re-validate. The
4093 // canonical-form gate at this layer surfaces a self-locating
4094 // diagnostic naming the offending Duration verbatim rather
4095 // than a downstream `RestartWindowZero` whose remediation
4096 // points at omitting the slot.
4097 let s = SupervisorSpec {
4098 restart_window: Some(Duration::from_nanos(1)),
4099 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4100 ..SupervisorSpec::default()
4101 };
4102 match s.validate().unwrap_err() {
4103 SupervisorError::RestartWindowNotCanonical { window } => {
4104 assert_eq!(window, Duration::from_nanos(1));
4105 }
4106 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4107 }
4108 }
4109
4110 #[test]
4111 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4112 // The 1-ns-past-1ms boundary case: a `Duration` carrying
4113 // 1_000_001 ns is structurally past the integer-ms granularity
4114 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4115 // trip would truncate to `1ms` and the consumer would observe
4116 // a 1-ns drift on every emit. Same boundary the peer
4117 // `validate_rejects_nanosecond_past_canonical_boundary` test
4118 // in limits.rs pins for the `:limits :wall-clock` axis.
4119 let w = Duration::from_nanos(1_000_001);
4120 let s = SupervisorSpec {
4121 restart_window: Some(w),
4122 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4123 ..SupervisorSpec::default()
4124 };
4125 assert_eq!(
4126 s.validate().unwrap_err(),
4127 SupervisorError::RestartWindowNotCanonical { window: w }
4128 );
4129 }
4130
4131 #[test]
4132 fn validate_accepts_integer_millisecond_restart_window_values() {
4133 // The positive-control sweep: every `Duration` the shared
4134 // codec can round-trip losslessly — the canonical
4135 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4136 // pair emits and accepts — passes `validate` without
4137 // surfacing the new canonical-form arm. Mirrors
4138 // `validate_accepts_integer_millisecond_wall_clock_values` on
4139 // the sibling `:limits :wall-clock` axis.
4140 for w in [
4141 Duration::from_millis(1),
4142 Duration::from_millis(500),
4143 Duration::from_millis(1500),
4144 Duration::from_secs(1),
4145 Duration::from_secs(30),
4146 Duration::from_secs(60),
4147 Duration::from_secs(120),
4148 Duration::from_secs(3600),
4149 ] {
4150 let s = SupervisorSpec {
4151 restart_window: Some(w),
4152 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4153 ..SupervisorSpec::default()
4154 };
4155 s.validate()
4156 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4157 }
4158 }
4159
4160 #[test]
4161 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4162 // Cross-arm ordering pin: `Duration::ZERO` has
4163 // `subsec_nanos() == 0` and would otherwise pass the
4164 // canonical-form arm — the zero-floor arm must fire first so
4165 // the more self-locating `RestartWindowZero` diagnostic (with
4166 // its omit-axis remediation directly named) leads. Same
4167 // posture every peer zero-then-shape gate uses
4168 // (`WallClockZero` → `WallClockNotCanonical`,
4169 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4170 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4171 let s = SupervisorSpec {
4172 restart_window: Some(Duration::ZERO),
4173 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4174 ..SupervisorSpec::default()
4175 };
4176 assert_eq!(
4177 s.validate().unwrap_err(),
4178 SupervisorError::RestartWindowZero
4179 );
4180 }
4181
4182 #[test]
4183 fn restart_window_canonical_diagnostic_carries_offending_duration() {
4184 // Diagnostic-shape pin: the canonical-form arm names the
4185 // offending `Duration` verbatim so the author's grep lands on
4186 // the field's value, not a generic "duration not canonical"
4187 // message. Same shape every other typed-canonical-form arm
4188 // on this surface carries (`WallClockNotCanonical` carries
4189 // the offending `Duration` verbatim,
4190 // `PolicyTimeoutNotCanonical` carries the offending
4191 // `Duration` verbatim).
4192 let w = Duration::from_micros(500);
4193 let s = SupervisorSpec {
4194 restart_window: Some(w),
4195 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4196 ..SupervisorSpec::default()
4197 };
4198 let err = s.validate().unwrap_err();
4199 let msg = err.to_string();
4200 assert!(
4201 msg.contains("500"),
4202 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4203 );
4204 assert!(
4205 msg.contains("sub-millisecond"),
4206 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4207 );
4208 }
4209
4210 #[test]
4211 fn restart_window_validated_value_round_trips_through_codec() {
4212 // The structural property the canonical-ms gate enforces:
4213 // every `SupervisorSpec::restart_window` past
4214 // `SupervisorSpec::validate` round-trips losslessly through
4215 // the shared duration codec (serialize → string →
4216 // deserialize → equal value). Pin this end-to-end so a future
4217 // change to either side (the validate gate's accepted
4218 // granularity, the codec's parse/render unit set) that breaks
4219 // the alignment surfaces here. Peer of
4220 // `wall_clock_validated_value_round_trips_through_codec` on
4221 // the sibling `:limits :wall-clock` axis.
4222 for w in [
4223 Duration::from_millis(1),
4224 Duration::from_millis(1500),
4225 Duration::from_secs(30),
4226 Duration::from_secs(3600),
4227 ] {
4228 let s = SupervisorSpec {
4229 restart_window: Some(w),
4230 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4231 ..SupervisorSpec::default()
4232 };
4233 s.validate().unwrap();
4234 let json = serde_json::to_string(&s).unwrap();
4235 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4236 assert_eq!(back.restart_window, Some(w));
4237 }
4238 }
4239
4240 // ── value-shape: upper cap on :restart-window ─────────────────────────
4241 //
4242 // The fourth (and last) typed-`Duration` axis in caixa-core to get
4243 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4244 // `:politicas :timeout` (2e8ee7e), and `:politicas
4245 // :circuit-breaker :window` (379a814). Brackets the typed
4246 // `:restart-window` axis structurally: every validated value lies
4247 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4248 // granularity, closing the
4249 // rolling-window-degenerates-to-lifetime-counter footgun the prior
4250 // zero-floor-and-canonical-form-only checks left open.
4251
4252 #[test]
4253 fn validate_rejects_restart_window_above_cap() {
4254 // The fail-before-pass-after pin: 3601s = 1h + 1s is
4255 // structurally one canonical-tick past the
4256 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4257 // integer-millisecond magnitude the canonical-form arm above
4258 // accepts cleanly, that the shared duration codec round-trips
4259 // losslessly as `"3601s"`, and that silently passed validate on
4260 // every pre-gate codebase because the typed slot's only checks
4261 // were the zero-floor and canonical-form arms. The runtime
4262 // substrate consuming the value (Erlang/OTP's MaxIntensity/
4263 // Period reconciler, the future wasm-operator's per-supervisor
4264 // restart-intensity counter) reaches for a `Duration` so long
4265 // no realistic restart-recovery pattern resets the counter,
4266 // far from the source caixa.lisp.
4267 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4268 let s = SupervisorSpec {
4269 restart_window: Some(w),
4270 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4271 ..SupervisorSpec::default()
4272 };
4273 assert_eq!(
4274 s.validate().unwrap_err(),
4275 SupervisorError::RestartWindowExceedsCap { window: w }
4276 );
4277 }
4278
4279 #[test]
4280 fn validate_rejects_restart_window_one_millisecond_above_cap() {
4281 // Boundary case: exactly 1ms past the cap (the granularity the
4282 // canonical-form gate enforces). Catches a future "strictly
4283 // less than" half-measure and pins the diagnostic to name the
4284 // offending `Duration` verbatim. Peer of
4285 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4286 // `rejects_policy_timeout_one_millisecond_above_cap` /
4287 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4288 // on the sibling typed-`Duration` axes' top edges.
4289 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4290 let s = SupervisorSpec {
4291 restart_window: Some(w),
4292 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4293 ..SupervisorSpec::default()
4294 };
4295 assert_eq!(
4296 s.validate().unwrap_err(),
4297 SupervisorError::RestartWindowExceedsCap { window: w }
4298 );
4299 }
4300
4301 #[test]
4302 fn validate_rejects_restart_window_far_above_cap() {
4303 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4304 // `(:restart-window "7d")`, or any "I want a lifetime counter
4305 // but wrote a `<integer>h` magnitude anyway" typo — values the
4306 // canonical-form arm accepts as integer-millisecond magnitudes,
4307 // the codec round-trips losslessly through serde, but the
4308 // operator's `MaxIntensity / Period` reconciler cannot honor
4309 // as a meaningful rolling window. Until this gate landed
4310 // validate accepted them. Pin the common above-cap values (24h,
4311 // 7d, ~11.5d) so a future relaxation that drops the upper bound
4312 // surfaces here.
4313 for w in [
4314 Duration::from_secs(86_400), // 24h
4315 Duration::from_secs(604_800), // 7d
4316 Duration::from_secs(1_000_000), // ~11.5 days
4317 ] {
4318 let s = SupervisorSpec {
4319 restart_window: Some(w),
4320 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4321 ..SupervisorSpec::default()
4322 };
4323 assert_eq!(
4324 s.validate().unwrap_err(),
4325 SupervisorError::RestartWindowExceedsCap { window: w }
4326 );
4327 }
4328 }
4329
4330 #[test]
4331 fn validate_accepts_restart_window_at_cap() {
4332 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4333 // (1h) — must validate. The cap is inclusive on the top edge,
4334 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4335 // [`crate::POLICY_TIMEOUT_MAX`] /
4336 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4337 // capped axes. Pin the boundary explicitly so a future
4338 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4339 // instead of `>`) surfaces here as a test failure rather than a
4340 // silent contract narrowing.
4341 let s = SupervisorSpec {
4342 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4343 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4344 ..SupervisorSpec::default()
4345 };
4346 s.validate()
4347 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4348 }
4349
4350 #[test]
4351 fn validate_accepts_restart_window_typical_values() {
4352 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4353 // per-supervisor production-playbook band positive-control
4354 // sweep — every value Learn You Some Erlang's `{intensity, 5,
4355 // 60}` worker-supervisor `Period = 60s` default, Elixir's
4356 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4357 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4358 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4359 // default recommend (5s..=300s) must pass, plus a sweep
4360 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4361 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4362 // on the sibling `:limits :wall-clock` axis.
4363 for w in [
4364 Duration::from_millis(1),
4365 Duration::from_millis(500),
4366 Duration::from_secs(1),
4367 Duration::from_secs(5), // RabbitMQ broker-supervisor default
4368 Duration::from_secs(10), // Riak Core lower
4369 Duration::from_secs(30),
4370 Duration::from_secs(60), // Learn You Some Erlang default
4371 Duration::from_secs(120), // OTP supervisor MaxT typical
4372 Duration::from_secs(300), // Riak Core upper
4373 Duration::from_secs(900), // 15m
4374 Duration::from_secs(1800),
4375 Duration::from_secs(3600), // exactly 1h, the cap
4376 ] {
4377 let s = SupervisorSpec {
4378 restart_window: Some(w),
4379 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4380 ..SupervisorSpec::default()
4381 };
4382 s.validate()
4383 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
4384 }
4385 }
4386
4387 #[test]
4388 fn restart_window_zero_takes_precedence_over_cap() {
4389 // The cross-arm ordering pin: `Duration::ZERO` is structurally
4390 // outside both `>= 1ms` (zero-floor) and `<=
4391 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
4392 // diagnostic is the more self-locating one (it directly names
4393 // the omit-axis remediation), so the validate gate must fire
4394 // on zero first. Same shape every other zero-then-cap ordering
4395 // on this surface uses (`WallClockZero` then
4396 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
4397 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
4398 // `PolicyBreakerWindowExceedsCap`).
4399 let s = SupervisorSpec {
4400 restart_window: Some(Duration::ZERO),
4401 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4402 ..SupervisorSpec::default()
4403 };
4404 assert_eq!(
4405 s.validate().unwrap_err(),
4406 SupervisorError::RestartWindowZero,
4407 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
4408 );
4409 }
4410
4411 #[test]
4412 fn restart_window_canonical_takes_precedence_over_cap() {
4413 // The cross-arm ordering pin: a `Duration` that is *both*
4414 // sub-millisecond (non-canonical-form) and structurally above
4415 // the cap surfaces the canonical-form diagnostic first,
4416 // because the round-trip-shape break is the more fundamental
4417 // issue (the value can't even round-trip through the codec,
4418 // so the cap diagnostic naming `1ms..=1h` would be misleading
4419 // — there's no integer-ms form of the offending value). Pin
4420 // the order so a future refactor that reorders the arms
4421 // surfaces here as a test failure rather than a silent
4422 // diagnostic regression. Peer of
4423 // `wall_clock_canonical_takes_precedence_over_cap` /
4424 // `policy_timeout_canonical_takes_precedence_over_cap`.
4425 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
4426 let s = SupervisorSpec {
4427 restart_window: Some(w),
4428 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4429 ..SupervisorSpec::default()
4430 };
4431 assert_eq!(
4432 s.validate().unwrap_err(),
4433 SupervisorError::RestartWindowNotCanonical { window: w },
4434 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
4435 );
4436 }
4437
4438 #[test]
4439 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
4440 // The cross-arm ordering pin between the `:max-restarts` cap
4441 // and the sibling `:restart-window` cap. A supervisor carrying
4442 // both an over-cap `max_restarts` AND an over-cap window must
4443 // surface the `MaxRestartsExceedsCap` diagnostic first — the
4444 // cap arm is wired immediately after the zero-restart arm and
4445 // strictly before every window-axis arm (zero / canonical /
4446 // cap), so the offending value the diagnostic names matches
4447 // the order the author would discover the gates by reading
4448 // top-to-bottom through `SupervisorSpec::validate`. Pin the
4449 // order so a future refactor that reorders the arms surfaces
4450 // here as a test failure rather than a silent diagnostic
4451 // regression. Peer of
4452 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
4453 // on the sibling zero / canonical window arms.
4454 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4455 let s = SupervisorSpec {
4456 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4457 restart_window: Some(w),
4458 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4459 ..SupervisorSpec::default()
4460 };
4461 assert_eq!(
4462 s.validate().unwrap_err(),
4463 SupervisorError::MaxRestartsExceedsCap {
4464 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4465 },
4466 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4467 );
4468 }
4469
4470 #[test]
4471 fn restart_window_cap_diagnostic_carries_offending_value() {
4472 // The diagnostic-shape pin: the offending `Duration` is
4473 // carried verbatim into the
4474 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
4475 // surfaced error message names the value the author wrote,
4476 // not just the cap. Same self-locating diagnostic shape every
4477 // other typed-cap arm on this surface carries
4478 // (`WallClockExceedsCap` carries the offending `Duration`
4479 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
4480 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
4481 // the offending `Duration` verbatim).
4482 let w = Duration::from_secs(7200); // 2h
4483 let s = SupervisorSpec {
4484 restart_window: Some(w),
4485 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4486 ..SupervisorSpec::default()
4487 };
4488 let err = s.validate().unwrap_err();
4489 assert!(
4490 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
4491 "got {err:?}"
4492 );
4493 let msg = err.to_string();
4494 assert!(
4495 msg.contains("7200"),
4496 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
4497 );
4498 }
4499
4500 #[test]
4501 fn supervisor_restart_window_cap_pins_canonical_value() {
4502 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
4503 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
4504 // shared duration codec emits as a clean canonical string
4505 // (`"<n>h"`). Pinning the literal value here surfaces a future
4506 // drift (a relaxation to 24h, a tightening to 5m) as a
4507 // deliberate test edit, not a silent contract narrowing.
4508 //
4509 // The four typed-`Duration` caps on the validation surface
4510 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
4511 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
4512 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
4513 // single uniform top edge at the codec's largest emitted unit
4514 // — a structural-property invariant the equality assertions
4515 // here enshrine, so a future drift on any of the four
4516 // surfaces as a deliberate test edit. Same shape every other
4517 // typed-cap value pin uses
4518 // (`wall_clock_cap_pins_canonical_value`,
4519 // `policy_timeout_cap_pins_canonical_value`,
4520 // `circuit_breaker_window_cap_pins_canonical_value`).
4521 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
4522 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
4523 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
4524 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
4525 assert_eq!(
4526 SUPERVISOR_RESTART_WINDOW_MAX,
4527 crate::POLICY_BREAKER_WINDOW_MAX
4528 );
4529 }
4530
4531 #[test]
4532 fn restart_window_cap_value_round_trips_through_codec() {
4533 // The codec round-trip property the cap arm preserves: the
4534 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
4535 // through the shared duration codec — every value at the cap
4536 // serializes to the canonical `"1h"` form and parses back
4537 // identically. Pin the round-trip so a future change to the
4538 // codec's unit set or to the cap's magnitude that breaks the
4539 // round-trip property surfaces here. Peer of
4540 // `wall_clock_cap_value_round_trips_through_codec` on the
4541 // sibling `:limits :wall-clock` axis.
4542 let s = SupervisorSpec {
4543 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4544 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4545 ..SupervisorSpec::default()
4546 };
4547 s.validate().unwrap();
4548 let json = serde_json::to_string(&s).unwrap();
4549 assert!(
4550 json.contains("\"1h\""),
4551 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
4552 );
4553 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4554 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
4555 }
4556
4557 #[test]
4558 fn validate_rejects_duplicate_child_caixa() {
4559 // Two children with the same :caixa render to two ComputeUnits
4560 // with the same name in the cluster's HelmRelease values —
4561 // one silently overwrites the other. Erlang/OTP's child_spec.id
4562 // is required-unique per supervisor; same set-not-multiset
4563 // discipline applied here as for :membros / :placement
4564 // :clusters / :entrada :paths.
4565 let s = SupervisorSpec {
4566 children: vec![
4567 child("worker", "^0.1", RestartPolicy::Permanent),
4568 child("cache", "^0.1", RestartPolicy::Transient),
4569 child("worker", "^0.2", RestartPolicy::Permanent),
4570 ],
4571 ..SupervisorSpec::default()
4572 };
4573 let err = s.validate().unwrap_err();
4574 assert!(
4575 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
4576 "got {err:?}"
4577 );
4578 }
4579
4580 #[test]
4581 fn validate_duplicate_child_diagnostic_names_first_collision() {
4582 // Iteration walks the :children list in declaration order —
4583 // the diagnostic names the first repeat, deterministically,
4584 // even when multiple names duplicate.
4585 let s = SupervisorSpec {
4586 children: vec![
4587 child("a", "^0.1", RestartPolicy::Permanent),
4588 child("b", "^0.1", RestartPolicy::Permanent),
4589 child("a", "^0.1", RestartPolicy::Permanent),
4590 child("b", "^0.1", RestartPolicy::Permanent),
4591 ],
4592 ..SupervisorSpec::default()
4593 };
4594 let err = s.validate().unwrap_err();
4595 assert!(
4596 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
4597 "got {err:?}"
4598 );
4599 }
4600
4601 // ── self-supervision cross-slot gate ──────────────────────────
4602
4603 #[test]
4604 fn validate_no_self_supervision_rejects_self_referential_child() {
4605 // A supervisor whose `:children` lists its own `:nome` is a
4606 // one-node reconciliation cycle — rejected, naming the parent.
4607 let children = vec![
4608 child("worker", "^0.1", RestartPolicy::Permanent),
4609 child("orquestra", "^0.1", RestartPolicy::Permanent),
4610 ];
4611 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
4612 assert!(
4613 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
4614 "got {err:?}"
4615 );
4616 }
4617
4618 #[test]
4619 fn validate_no_self_supervision_accepts_distinct_children() {
4620 // Positive control: distinct child names (including a child that
4621 // is itself a supervisor — nested trees are valid OTP) pass.
4622 let children = vec![
4623 child("worker", "^0.1", RestartPolicy::Permanent),
4624 child("sub-tree", "^0.1", RestartPolicy::Permanent),
4625 ];
4626 validate_no_self_supervision(&children, "orquestra").unwrap();
4627 }
4628
4629 #[test]
4630 fn validate_no_self_supervision_empty_children_is_ok() {
4631 // SimpleOneForOne / no-static-children supervisors have nothing
4632 // to self-reference — the gate is vacuously satisfied.
4633 validate_no_self_supervision(&[], "orquestra").unwrap();
4634 }
4635
4636 #[test]
4637 fn validate_simple_one_for_one_skips_uniqueness_check() {
4638 // SimpleOneForOne supervisors carry no static children — the
4639 // duplicate-child loop never runs. A zero-window declaration
4640 // on a SimpleOneForOne supervisor still trips the window check
4641 // (window applies to dynamic children too).
4642 let s = SupervisorSpec {
4643 estrategia: RestartStrategy::SimpleOneForOne,
4644 restart_window: None,
4645 children: vec![],
4646 ..SupervisorSpec::default()
4647 };
4648 s.validate().unwrap();
4649 let s_zero = SupervisorSpec {
4650 estrategia: RestartStrategy::SimpleOneForOne,
4651 restart_window: Some(Duration::ZERO),
4652 children: vec![],
4653 ..SupervisorSpec::default()
4654 };
4655 assert_eq!(
4656 s_zero.validate().unwrap_err(),
4657 SupervisorError::RestartWindowZero
4658 );
4659 }
4660
4661 #[test]
4662 fn validate_zero_window_runs_after_max_restarts_check() {
4663 // Pin the order: max_restarts == 0 fires before
4664 // restart_window == 0s, so an author with both wrong sees the
4665 // counter-axis diagnostic first (matches the order in the
4666 // struct and in the doc comment).
4667 let s = SupervisorSpec {
4668 max_restarts: 0,
4669 restart_window: Some(Duration::ZERO),
4670 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4671 ..SupervisorSpec::default()
4672 };
4673 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4674 }
4675
4676 #[test]
4677 fn round_trip_all_strategies() {
4678 for &strat in RestartStrategy::ALL {
4679 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
4680 // shape partition through the [`gen_platform::IsVariant`]
4681 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
4682 // predicate rather than the raw
4683 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
4684 // open-coded pattern-match — same closed-set-typed-enum
4685 // arm-discriminator dispatch discipline the sibling
4686 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
4687 // (915a934) extended onto its two paired positive / negated
4688 // `matches!` filter sites, and the sibling
4689 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
4690 // predicate convergence (766ec63) extended onto the M3 mesh-
4691 // slot per-`:placement` distribution-strategy `matches!`
4692 // discriminator axis. See the sibling
4693 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
4694 // fixture and the peer `manifest::tests::
4695 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
4696 // fixture — all three sites (the last unlifted
4697 // `matches!`-based arm-discriminator axis on the OTP-shape
4698 // supervisor sibling-restart-strategy closed-set typed enum,
4699 // acknowledged in 915a934's Prior-commits footnote as the
4700 // outstanding follow-up) now consult one typed dispatch on
4701 // the substrate primitive.
4702 let s = SupervisorSpec {
4703 estrategia: strat,
4704 children: if strat.is_simple_one_for_one() {
4705 vec![]
4706 } else {
4707 vec![child("w", "^0.1", RestartPolicy::Permanent)]
4708 },
4709 ..SupervisorSpec::default()
4710 };
4711 let json = serde_json::to_string(&s).unwrap();
4712 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4713 assert_eq!(s, back);
4714 }
4715 }
4716
4717 #[test]
4718 fn round_trip_all_restart_policies() {
4719 for policy in [
4720 RestartPolicy::Permanent,
4721 RestartPolicy::Temporary,
4722 RestartPolicy::Transient,
4723 ] {
4724 let c = child("w", "^0.1", policy);
4725 let json = serde_json::to_string(&c).unwrap();
4726 let back: ChildSpec = serde_json::from_str(&json).unwrap();
4727 assert_eq!(c, back);
4728 }
4729 }
4730
4731 #[test]
4732 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
4733 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
4734 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
4735 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
4736 // is the only variant that satisfies `.is_simple_one_for_one()`;
4737 // every static-children-bearing arm (`OneForOne` / `OneForAll`
4738 // / `RestForOne`) returns `false`. This pin makes the partition
4739 // invariant load-bearing at caixa-core test time so a future
4740 // derive regression (a hole that returns `false` for
4741 // `SimpleOneForOne` too, or a byte-collision that flips a second
4742 // variant to `true`) trips here rather than laundering the arm
4743 // at the three test-fixture builder sites (a hole flips the
4744 // `SimpleOneForOne` fixture to carry a non-empty children list
4745 // and the subsequent `SupervisorSpec::validate` would refuse the
4746 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
4747 // a collision flips a peer strategy's fixture to carry an empty
4748 // children list and the subsequent `validate` would refuse with
4749 // [`SupervisorError::NoChildren`] — either way, the pin fires
4750 // here, at the derive site, rather than at the fixture-refusal
4751 // site far away). Peer of the sibling
4752 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
4753 // (915a934) pin on the M2 OTP-appup axis and the sibling
4754 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
4755 // pin on the M0 `:kind` axis.
4756 let cases: &[(RestartStrategy, bool)] = &[
4757 (RestartStrategy::OneForOne, false),
4758 (RestartStrategy::OneForAll, false),
4759 (RestartStrategy::RestForOne, false),
4760 (RestartStrategy::SimpleOneForOne, true),
4761 ];
4762 for (variant, expected) in cases {
4763 assert_eq!(
4764 variant.is_simple_one_for_one(),
4765 *expected,
4766 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
4767 return {expected} (partition invariant on the \
4768 IsVariant-derived arm-discriminator predicate — every \
4769 test-fixture site that partitions the `:children` slot \
4770 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
4771 off this typed dispatch, so a derive regression must \
4772 surface here rather than at the fixture-refusal site)"
4773 );
4774 }
4775 }
4776
4777 #[test]
4778 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
4779 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
4780 // fixture-shape partition against the pre-lift
4781 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
4782 // pattern-match every test-fixture builder site previously
4783 // coupled to inline. Asserts the two projections agree byte-for-
4784 // byte on every arm of the enum, so a future derive regression
4785 // that flipped either predicate's arm-set would surface here at
4786 // caixa-core test time rather than at the three fixture-builder
4787 // sites (`supervisor::tests::round_trip_all_strategies`,
4788 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
4789 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
4790 // far from the derive site. Same peer-shape byte-identity pin
4791 // every sibling `IsVariant`-derive-routed convergence carries on
4792 // the substrate's closed-set typed-enum surface (peer of
4793 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
4794 // on the M2 OTP-appup axis).
4795 for &strat in RestartStrategy::ALL {
4796 let via_predicate = strat.is_simple_one_for_one();
4797 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
4798 assert_eq!(
4799 via_predicate, via_matches,
4800 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
4801 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
4802 the pre-lift open-coded pattern and the \
4803 IsVariant-derived predicate are the same axis, \
4804 one typed dispatch"
4805 );
4806 }
4807 }
4808
4809 #[test]
4810 fn duration_codec_round_trip_canonical_units() {
4811 // Note the canonical-form rule: durations serialize to the
4812 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
4813 // "60s" — but the round-trip preserves the underlying Duration.
4814 let cases = [
4815 ("30s", Duration::from_secs(30)),
4816 ("5m", Duration::from_secs(300)),
4817 ("1h", Duration::from_secs(3600)),
4818 ("500ms", Duration::from_millis(500)),
4819 ];
4820 for (lit, dur) in cases {
4821 let s = SupervisorSpec {
4822 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4823 restart_window: Some(dur),
4824 ..SupervisorSpec::default()
4825 };
4826 let json = serde_json::to_string(&s).unwrap();
4827 assert!(
4828 json.contains(&format!("\"{lit}\"")),
4829 "expected \"{lit}\" in {json}"
4830 );
4831 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4832 assert_eq!(back.restart_window, Some(dur));
4833 }
4834 }
4835
4836 #[test]
4837 fn duration_canonicalizes_to_largest_unit() {
4838 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
4839 // typed Duration still equals 60s on the way back.
4840 let s = SupervisorSpec {
4841 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4842 restart_window: Some(Duration::from_secs(60)),
4843 ..SupervisorSpec::default()
4844 };
4845 let json = serde_json::to_string(&s).unwrap();
4846 assert!(json.contains("\"1m\""), "{json}");
4847 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4848 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
4849 }
4850
4851 #[test]
4852 fn three_child_one_for_one_validates() {
4853 let s = SupervisorSpec {
4854 estrategia: RestartStrategy::OneForOne,
4855 max_restarts: 5,
4856 restart_window: Some(Duration::from_secs(60)),
4857 children: vec![
4858 child("worker", "^0.1", RestartPolicy::Permanent),
4859 child("cache", "^0.1", RestartPolicy::Transient),
4860 child("scratch", "^0.1", RestartPolicy::Temporary),
4861 ],
4862 };
4863 s.validate().unwrap();
4864 }
4865
4866 #[test]
4867 fn json_uses_pascal_case_for_strategy_and_policy() {
4868 // Variant names are PascalCase by default in serde, matching
4869 // tatara-lisp's enum convention (`:estrategia OneForOne`).
4870 let c = child("w", "^0.1", RestartPolicy::Permanent);
4871 let json = serde_json::to_string(&c).unwrap();
4872 assert!(json.contains("\"Permanent\""));
4873 assert!(!json.contains("\"permanent\""));
4874
4875 let s = SupervisorSpec {
4876 estrategia: RestartStrategy::OneForOne,
4877 children: vec![c],
4878 ..SupervisorSpec::default()
4879 };
4880 let json = serde_json::to_string(&s).unwrap();
4881 assert!(json.contains("\"estrategia\":\"OneForOne\""));
4882 }
4883
4884 // ── shared duration codec: integer-magnitude canonical-form gate ──
4885 //
4886 // The gate lifts the discipline `crate::limits::parse_duration`
4887 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
4888 // the shared codec backing the remaining three typed-duration
4889 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
4890 // `:politicas :circuit-breaker :window`. Every magnitude `render`
4891 // emits is a non-negative integer with no decimal point and no
4892 // leading sign, so the codec's accepted set must match for
4893 // serialize/deserialize to round-trip without canonical-form
4894 // drift.
4895
4896 #[test]
4897 fn parse_accepts_integer_canonical_units() {
4898 // Pin the happy-path: every canonical author shape `render`
4899 // ever emits parses to the same `Duration` value, so the
4900 // codec's accepted set is at least a superset of its emitted
4901 // set on the canonical-unit axis.
4902 for (lit, dur) in [
4903 ("30s", Duration::from_secs(30)),
4904 ("500ms", Duration::from_millis(500)),
4905 ("2m", Duration::from_secs(120)),
4906 ("1h", Duration::from_secs(3600)),
4907 ("0s", Duration::ZERO),
4908 ] {
4909 assert_eq!(
4910 duration_codec::parse(lit).unwrap(),
4911 dur,
4912 "parse({lit:?}) should be {dur:?}"
4913 );
4914 }
4915 }
4916
4917 #[test]
4918 fn parse_accepts_bare_integer_as_seconds() {
4919 // The `"s" | ""` arm: a bare integer with no unit is read as
4920 // seconds. Pin this so the unit-empty form keeps parsing (it
4921 // renders to `"<n>s"` on serialize — that's a unit-choice
4922 // drift the integer-magnitude gate does NOT close, matching
4923 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
4924 // the peer `:limits :memory` codec).
4925 assert_eq!(
4926 duration_codec::parse("30").unwrap(),
4927 Duration::from_secs(30)
4928 );
4929 }
4930
4931 #[test]
4932 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
4933 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
4934 // on first serialize — DRIFT. The integer-magnitude gate names
4935 // the offending `"1.5"` verbatim and points at the canonical
4936 // remediation `"1500ms"`.
4937 let err = duration_codec::parse("1.5s").unwrap_err();
4938 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
4939 assert!(
4940 err.contains("not a non-negative integer"),
4941 "missing canonical-form reason in {err:?}"
4942 );
4943 assert!(
4944 err.contains("\"1500ms\""),
4945 "missing canonical-form remediation in {err:?}"
4946 );
4947 }
4948
4949 #[test]
4950 fn parse_rejects_decimal_shaped_integer_seconds() {
4951 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
4952 // `1s` exactly, so the round-trip looks correct — but the
4953 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
4954 // decimal-shape-with-integer-value form so author intent is
4955 // never silently rewritten.
4956 let err = duration_codec::parse("1.0s").unwrap_err();
4957 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
4958 assert!(
4959 err.contains("not a non-negative integer"),
4960 "missing canonical-form reason in {err:?}"
4961 );
4962 }
4963
4964 #[test]
4965 fn parse_rejects_half_unit_minute() {
4966 // `"0.5m"` is the unit-fraction footgun — author writes a
4967 // human-readable half-minute, serde silently rewrites to
4968 // `"30s"` on next emit. The gate names the offending
4969 // magnitude `"0.5"` and points at the integer-in-smaller-unit
4970 // form.
4971 let err = duration_codec::parse("0.5m").unwrap_err();
4972 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
4973 assert!(
4974 err.contains("\"30s\""),
4975 "missing canonical-form remediation in {err:?}"
4976 );
4977 }
4978
4979 #[test]
4980 fn parse_rejects_leading_plus_sign() {
4981 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
4982 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
4983 // cleanly to 30s and round-tripped to `"30s"` on next emit
4984 // (DRIFT). The digit-only gate closes the leading-sign class
4985 // first; the diagnostic names `"+30"` verbatim.
4986 let err = duration_codec::parse("+30s").unwrap_err();
4987 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
4988 assert!(
4989 err.contains("not a non-negative integer"),
4990 "missing canonical-form reason in {err:?}"
4991 );
4992 }
4993
4994 #[test]
4995 fn parse_rejects_leading_minus_sign() {
4996 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
4997 // rejected with `"negative duration in \"-30s\""`. Under the
4998 // integer-magnitude gate the diagnostic is unified — `-30` is
4999 // non-digit-only, f64-numeric, and surfaces with the canonical-
5000 // form reason (no leading `+` / `-` sign) naming the offending
5001 // `"-30"` verbatim. Same diagnostic shape as every other
5002 // rejected non-integer magnitude.
5003 let err = duration_codec::parse("-30s").unwrap_err();
5004 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5005 assert!(
5006 err.contains("not a non-negative integer"),
5007 "missing canonical-form reason in {err:?}"
5008 );
5009 }
5010
5011 #[test]
5012 fn parse_garbage_still_falls_through_to_bad_magnitude() {
5013 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5014 // through to the narrower "bad duration magnitude" arm — the
5015 // canonical-form diagnostic is reserved for the parser-shape
5016 // footgun case, not the "not a number at all" case. Same
5017 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5018 // the peer `:limits :memory` codec.
5019 let err = duration_codec::parse("--1s").unwrap_err();
5020 assert!(
5021 err.contains("bad duration magnitude"),
5022 "expected bad-magnitude wording in {err:?}"
5023 );
5024 }
5025
5026 #[test]
5027 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5028 // The accepted set is now closed under `u64`-exact integer
5029 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5030 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5031 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5032 // possible. Pin the integer-exact arms across the four unit
5033 // suffixes so a future refactor that reaches back for f64
5034 // (`from_secs_f64`, `mul_f64`) surfaces here.
5035 assert_eq!(
5036 duration_codec::parse("3600s").unwrap(),
5037 Duration::from_secs(3600)
5038 );
5039 assert_eq!(
5040 duration_codec::parse("60m").unwrap(),
5041 Duration::from_secs(3600)
5042 );
5043 assert_eq!(
5044 duration_codec::parse("1h").unwrap(),
5045 Duration::from_secs(3600)
5046 );
5047 assert_eq!(
5048 duration_codec::parse("999ms").unwrap(),
5049 Duration::from_millis(999)
5050 );
5051 }
5052
5053 #[test]
5054 fn restart_window_serde_rejects_fractional_seconds() {
5055 // The shared codec backs `SupervisorSpec::restart_window`
5056 // (`with = "duration_codec"`) — so the gate applies on serde
5057 // deserialize for the typed Supervisor slot. A
5058 // `{"restartWindow":"1.5s"}` payload that previously round-
5059 // tripped to a different canonical string on next serialize
5060 // is now refused at deserialize with the integer-magnitude
5061 // diagnostic.
5062 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5063 "restartWindow":"1.5s",
5064 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5065 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5066 let msg = err.to_string();
5067 assert!(
5068 msg.contains("not a non-negative integer"),
5069 "expected integer-magnitude diagnostic in {msg:?}"
5070 );
5071 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5072 }
5073
5074 #[test]
5075 fn restart_window_serde_rejects_leading_plus() {
5076 // The `u64::from_str` leading-`+` permissiveness gap that
5077 // motivated the digit-only gate (the `f64`-side accepted
5078 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5079 // is now closed on the shared codec — surfaces as a structured
5080 // diagnostic at the serde layer for every typed-duration slot.
5081 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5082 "restartWindow":"+30s",
5083 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5084 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5085 let msg = err.to_string();
5086 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5087 assert!(
5088 msg.contains("not a non-negative integer"),
5089 "missing canonical-form reason in {msg:?}"
5090 );
5091 }
5092
5093 #[test]
5094 fn parse_rejects_leading_zero_magnitude() {
5095 // `"030s"` is digit-only, so the existing non-digit-only / sign
5096 // / fractional arm doesn't catch it — `u64::from_str("030")`
5097 // returns `Ok(30)`, so before this gate `"030s"` parsed to
5098 // `Duration::from_secs(30)` and round-tripped through `render`
5099 // to `"30s"` — a *different* canonical string on the next emit,
5100 // breaking the THEORY.md Part V render-determinism contract
5101 // exactly the way `"+30s"` did before the leading-`+` arm
5102 // landed. Peer with the `rate_limit_codec` leading-zero arm
5103 // (4f46830) on the same canonical-form-drift axis.
5104 let err = duration_codec::parse("030s").unwrap_err();
5105 assert!(
5106 err.contains("non-canonical leading zero"),
5107 "expected leading-zero diagnostic in {err:?}"
5108 );
5109 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5110 assert!(
5111 err.contains("\"30s\""),
5112 "missing canonical-form remediation in {err:?}"
5113 );
5114 assert!(
5115 err.contains("THEORY.md"),
5116 "missing render-determinism citation in {err:?}"
5117 );
5118 }
5119
5120 #[test]
5121 fn parse_rejects_multi_digit_zero_magnitude() {
5122 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5123 // digit-only, parse losslessly to `Duration::ZERO`, but render
5124 // back to `"0s"` (the single-byte canonical form) on the next
5125 // emit. The leading-zero arm refuses the drift class at the
5126 // codec layer; the semantic-zero gate downstream
5127 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5128 // the single-byte canonical form `"0s"` separately on the
5129 // typed-validate layer.
5130 let err = duration_codec::parse("00s").unwrap_err();
5131 assert!(
5132 err.contains("non-canonical leading zero"),
5133 "expected leading-zero diagnostic in {err:?}"
5134 );
5135 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5136 }
5137
5138 #[test]
5139 fn parse_rejects_leading_zero_per_hour_window() {
5140 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5141 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5142 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5143 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5144 // `h` / bare-integer-as-seconds) inherits the same gate.
5145 let err = duration_codec::parse("01h").unwrap_err();
5146 assert!(
5147 err.contains("non-canonical leading zero"),
5148 "expected leading-zero diagnostic in {err:?}"
5149 );
5150 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5151 }
5152
5153 #[test]
5154 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5155 // The `parse_accepts_bare_integer_as_seconds` happy-path
5156 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5157 // multi-byte starts-with-`0`, parses losslessly to
5158 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5159 // bare-integer surface accepts permissive unit-empty
5160 // shorthand but still must reject leading-zero padding.
5161 let err = duration_codec::parse("030").unwrap_err();
5162 assert!(
5163 err.contains("non-canonical leading zero"),
5164 "expected leading-zero diagnostic in {err:?}"
5165 );
5166 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5167 }
5168
5169 #[test]
5170 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5171 // The codec-layer / typed-validate-layer boundary: `"0s"` /
5172 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5173 // each round-trips losslessly through `render`
5174 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5175 // accepts them. The downstream semantic-zero gates
5176 // (`SupervisorError::ZeroRestartWindow`,
5177 // `AplicacaoError::PolicyTimeoutZero`,
5178 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5179 // zero-magnitude authoring at the typed-validate layer above,
5180 // peer with the `rate_limit_codec` codec-layer / typed-
5181 // validate-layer partition for `"0/s"`.
5182 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5183 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5184 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5185 }
5186
5187 #[test]
5188 fn parse_accepts_canonical_magnitude_with_leading_one() {
5189 // The complementary boundary: a future tightening cannot
5190 // drift into rejecting valid canonical magnitudes that
5191 // happen to start with `1` (or any digit `[1-9]`). Pin
5192 // every canonical-unit suffix so the leading-zero arm
5193 // remains strictly narrower than the digit-only arm.
5194 assert_eq!(
5195 duration_codec::parse("100ms").unwrap(),
5196 Duration::from_millis(100)
5197 );
5198 assert_eq!(
5199 duration_codec::parse("100s").unwrap(),
5200 Duration::from_secs(100)
5201 );
5202 assert_eq!(
5203 duration_codec::parse("10m").unwrap(),
5204 Duration::from_secs(600)
5205 );
5206 assert_eq!(
5207 duration_codec::parse("10h").unwrap(),
5208 Duration::from_secs(36_000)
5209 );
5210 }
5211
5212 #[test]
5213 fn restart_window_serde_rejects_leading_zero() {
5214 // The shared codec backs `SupervisorSpec::restart_window`
5215 // (`with = "duration_codec"`) — so the leading-zero arm
5216 // applies on serde deserialize for the typed Supervisor slot.
5217 // A `{"restartWindow":"030s"}` payload that previously round-
5218 // tripped to a different canonical string on next serialize
5219 // is now refused at deserialize with the leading-zero
5220 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5221 // / `restart_window_serde_rejects_fractional_seconds` on the
5222 // same canonical-form-drift axis.
5223 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5224 "restartWindow":"030s",
5225 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5226 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5227 let msg = err.to_string();
5228 assert!(
5229 msg.contains("non-canonical leading zero"),
5230 "expected leading-zero diagnostic in {msg:?}"
5231 );
5232 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5233 }
5234
5235 #[test]
5236 fn parse_rejects_leading_whitespace() {
5237 // `" 30s"` — the canonical paste-from-aligned-doc /
5238 // paste-from-YAML-quoted-plain-scalar footgun. Before this
5239 // gate the top-level `s.trim()` at parse entry silently ate
5240 // the leading space and parsed the value to
5241 // `Duration::from_secs(30)`, which then round-tripped through
5242 // `render` to `"30s"` (a *different* canonical string on the
5243 // next emit) — the exact canonical-form-drift class the
5244 // leading-`+` / leading-zero arms already close, extended
5245 // to the whitespace-byte class. Peer with the sibling
5246 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5247 // the M3 `:politicas` axis.
5248 let err = duration_codec::parse(" 30s").unwrap_err();
5249 assert!(
5250 err.contains("contains whitespace byte"),
5251 "expected whitespace diagnostic in {err:?}"
5252 );
5253 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5254 assert!(
5255 err.contains("THEORY.md"),
5256 "missing render-determinism contract citation in {err:?}"
5257 );
5258 }
5259
5260 #[test]
5261 fn parse_rejects_trailing_whitespace() {
5262 // `"30s "` — the canonical shell-history / trailing-space
5263 // paste footgun. Before this gate the top-level `s.trim()`
5264 // silently ate the trailing space and parsed to
5265 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5266 // next emit — same canonical-form drift as the leading-space
5267 // sibling, closed on the same whitespace-byte arm.
5268 let err = duration_codec::parse("30s ").unwrap_err();
5269 assert!(
5270 err.contains("contains whitespace byte"),
5271 "expected whitespace diagnostic in {err:?}"
5272 );
5273 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5274 }
5275
5276 #[test]
5277 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5278 // `"30 s"` — the canonical typographically-spaced author
5279 // shape (the same idiom every prose reference to a duration
5280 // renders as, mistakenly retained when the value is pasted
5281 // into a codec-shaped slot). Before this gate the per-part
5282 // `num_part.trim()` / `unit.trim()` calls silently ate the
5283 // whitespace between the magnitude and the unit and parsed
5284 // the value to `Duration::from_secs(30)`, round-tripping to
5285 // `"30s"` — the codec's *internal* whitespace-tolerance
5286 // vector, orthogonal to the leading / trailing surface but
5287 // the same canonical-form-drift class. Pins the arm as
5288 // strictly stronger than the pre-existing top-level
5289 // `s.trim()` behavior: it fires on whitespace anywhere in
5290 // the value, not just at the string boundary.
5291 let err = duration_codec::parse("30 s").unwrap_err();
5292 assert!(
5293 err.contains("contains whitespace byte"),
5294 "expected whitespace diagnostic in {err:?}"
5295 );
5296 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5297 }
5298
5299 #[test]
5300 fn parse_rejects_tab_byte() {
5301 // `"\t30s"` — the canonical paste-from-indented-doc /
5302 // paste-from-YAML-block-scalar footgun where a tab byte leads
5303 // the magnitude. Pins that the gate covers tab (`0x09`) as
5304 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5305 // members and both would be silently swallowed by `s.trim()`
5306 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5307 // space alone to the full ASCII-whitespace set (space `0x20`,
5308 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5309 // the tab arm as a representative of the non-space members.
5310 let err = duration_codec::parse("\t30s").unwrap_err();
5311 assert!(
5312 err.contains("contains whitespace byte"),
5313 "expected whitespace diagnostic in {err:?}"
5314 );
5315 assert!(
5316 err.contains("0x09"),
5317 "missing offending tab byte in {err:?}"
5318 );
5319 }
5320
5321 #[test]
5322 fn restart_window_serde_rejects_whitespace() {
5323 // The shared codec backs `SupervisorSpec::restart_window`
5324 // (`with = "duration_codec"`) — so the whitespace arm
5325 // applies on serde deserialize for the typed Supervisor slot.
5326 // A `{"restartWindow":" 30s"}` payload that previously round-
5327 // tripped to a different canonical string on next serialize
5328 // is now refused at deserialize with the whitespace-byte
5329 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5330 // / `restart_window_serde_rejects_leading_plus` /
5331 // `restart_window_serde_rejects_fractional_seconds` on the
5332 // same canonical-form-drift axis.
5333 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5334 "restartWindow":" 30s",
5335 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5336 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5337 let msg = err.to_string();
5338 assert!(
5339 msg.contains("contains whitespace byte"),
5340 "expected whitespace diagnostic in {msg:?}"
5341 );
5342 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5343 }
5344
5345 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5346 //
5347 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5348 // duration codec — closes the strictly-complementary class the
5349 // byte-scan cannot see, through the lifted
5350 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5351 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5352 // and `:politicas :circuit-breaker :window` simultaneously via
5353 // this shared codec.
5354
5355 #[test]
5356 fn duration_codec_parse_rejects_leading_nbsp() {
5357 // NBSP prefix — the strictly-complementary drift class the
5358 // ASCII byte-scan cannot see. `str::trim` strips it silently
5359 // and the value drifts to `"30s"` on next serialize.
5360 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5361 assert!(
5362 err.contains("non-ASCII Unicode whitespace character"),
5363 "expected non-ASCII whitespace diagnostic in {err:?}"
5364 );
5365 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5366 }
5367
5368 #[test]
5369 fn duration_codec_parse_rejects_trailing_line_separator() {
5370 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5371 // footgun.
5372 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5373 assert!(
5374 err.contains("non-ASCII Unicode whitespace character"),
5375 "expected non-ASCII whitespace diagnostic in {err:?}"
5376 );
5377 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5378 }
5379
5380 #[test]
5381 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
5382 // Positive-control pin: every ASCII-only canonical form the
5383 // renderer emits stays accepted through the new arm.
5384 assert_eq!(
5385 duration_codec::parse("30s").unwrap(),
5386 Duration::from_secs(30)
5387 );
5388 assert_eq!(
5389 duration_codec::parse("500ms").unwrap(),
5390 Duration::from_millis(500)
5391 );
5392 assert_eq!(
5393 duration_codec::parse("1h").unwrap(),
5394 Duration::from_secs(3600)
5395 );
5396 }
5397
5398 #[test]
5399 fn restart_window_serde_rejects_non_ascii_whitespace() {
5400 // The shared codec backs `SupervisorSpec::restart_window` — so
5401 // the new non-ASCII Unicode whitespace arm applies on serde
5402 // deserialize for the typed Supervisor slot. A
5403 // `{"restartWindow":" 30s"}` payload that previously
5404 // survived the ASCII byte-scan (only ASCII whitespace was
5405 // refused) is now refused at deserialize with the
5406 // non-ASCII-whitespace-and-codepoint diagnostic.
5407 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
5408 \"restartWindow\":\"\u{00A0}30s\",\
5409 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
5410 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5411 let msg = err.to_string();
5412 assert!(
5413 msg.contains("non-ASCII Unicode whitespace character"),
5414 "expected non-ASCII whitespace diagnostic in {msg:?}"
5415 );
5416 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
5417 }
5418
5419 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
5420
5421 #[test]
5422 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
5423 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
5424 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
5425 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
5426 // name the exact camelCase JSON keys the
5427 // `#[serde(rename_all = "camelCase")]` attribute on
5428 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
5429 // field carries `Some(_)` / non-empty) and pin that each canonical
5430 // byte-sequence appears verbatim in the JSON — a future accidental
5431 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
5432 // name flip at the derive attribute (any of which would silently
5433 // break every downstream JSON consumer that reaches for one of the
5434 // four consts via `Value::get(...)`) surfaces here as a build-time
5435 // test failure at `supervisor.rs`, not as an apply-time
5436 // `.get(<stale-canonical-const>)` returning `None` far from the
5437 // derive-attr drift's commit. Peer with the sibling
5438 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
5439 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
5440 // M2 typed-slot family established, extended here to close the
5441 // top-level Supervisor axis.
5442 let spec = SupervisorSpec {
5443 estrategia: RestartStrategy::OneForOne,
5444 max_restarts: 5,
5445 restart_window: Some(Duration::from_secs(60)),
5446 children: vec![ChildSpec {
5447 caixa: "w".into(),
5448 versao: "^0.1".into(),
5449 restart: RestartPolicy::Permanent,
5450 }],
5451 };
5452 let json = serde_json::to_string(&spec).unwrap();
5453 for key in [
5454 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5455 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5456 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5457 crate::render::SUPERVISOR_KEY_CHILDREN,
5458 ] {
5459 let quoted = format!("\"{key}\"");
5460 assert!(
5461 json.contains("ed),
5462 "serialized SupervisorSpec must carry the lifted \
5463 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
5464 the JSON emission (got: {json})",
5465 );
5466 }
5467 }
5468
5469 #[test]
5470 fn supervisor_key_consts_are_pairwise_distinct() {
5471 // Cross-axis drift-detection pin: a future collapse of two
5472 // canonical top-level byte-strings onto the same value (e.g. an
5473 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
5474 // also read `"estrategia"`) would silently reroute every
5475 // downstream probe on one axis onto the sibling axis's overlay
5476 // entry and pass every propagation-probe test that expected only
5477 // the stale axis's value. Peer of the sibling four-way distinct
5478 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
5479 let all = [
5480 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5481 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5482 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5483 crate::render::SUPERVISOR_KEY_CHILDREN,
5484 ];
5485 for (i, a) in all.iter().enumerate() {
5486 for b in all.iter().skip(i + 1) {
5487 assert_ne!(
5488 a, b,
5489 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
5490 canonical byte-sequences — got `{a}` == `{b}`",
5491 );
5492 }
5493 }
5494 }
5495
5496 #[test]
5497 fn supervisor_key_consts_are_lower_camel_case_shape() {
5498 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
5499 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5500 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5501 // capital, no whitespace / dots) — the canonical shape the
5502 // `#[serde(rename_all = "camelCase")]` derive produces on
5503 // `SupervisorSpec`. A future flip to a non-camelCase attribute
5504 // at the derive surfaces both here (this test fails on the
5505 // stale-constant shape) and at
5506 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5507 // (that test fails on the mismatch between const and derive).
5508 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
5509 // (d8b8b4f) on the sibling M2 `:limits` axis.
5510 for key in [
5511 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5512 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5513 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5514 crate::render::SUPERVISOR_KEY_CHILDREN,
5515 ] {
5516 assert!(
5517 !key.is_empty(),
5518 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
5519 );
5520 let first = key.chars().next().unwrap();
5521 assert!(
5522 first.is_ascii_lowercase(),
5523 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
5524 (got {key:?}, leads with {first:?})",
5525 );
5526 assert!(
5527 key.chars().all(|c| c.is_ascii_alphanumeric()),
5528 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
5529 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5530 );
5531 }
5532 }
5533
5534 #[test]
5535 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
5536 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
5537 // (camelCase JSON keys, no leading colon) must never collide
5538 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
5539 // consts (kebab-case author-facing labels with leading colon)
5540 // that sit next to them at `caixa_core::render`. Both families
5541 // cover the same four typed Supervisor slots on two distinct
5542 // axes (author-side kebab vs renderer-side camelCase);
5543 // collapsing either family onto the other's byte-shape would
5544 // silently reroute the render-side probe onto the author-facing
5545 // surface, or vice versa. Peer of the byte-distinctness
5546 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
5547 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
5548 let pairs = [
5549 (
5550 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5551 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
5552 ),
5553 (
5554 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5555 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
5556 ),
5557 (
5558 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5559 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
5560 ),
5561 (
5562 crate::render::SUPERVISOR_KEY_CHILDREN,
5563 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
5564 ),
5565 ];
5566 for (json_key, author_key) in pairs {
5567 assert_ne!(
5568 json_key, author_key,
5569 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
5570 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
5571 got JSON `{json_key}` == author `{author_key}`",
5572 );
5573 }
5574 }
5575
5576 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
5577
5578 #[test]
5579 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
5580 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
5581 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
5582 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
5583 // keys the `#[serde(rename_all = "camelCase")]` attribute on
5584 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
5585 // pin that each canonical byte-sequence appears verbatim in the
5586 // JSON — a future accidental `rename_all = "snake_case"` /
5587 // `"kebab-case"` / verbatim-field-name flip at the derive
5588 // attribute (any of which would silently break every downstream
5589 // JSON consumer that reaches for one of the three consts via
5590 // `Value::get(...)`) surfaces here as a build-time test failure at
5591 // `supervisor.rs`, not as an apply-time
5592 // `.get(<stale-canonical-const>)` returning `None` far from the
5593 // derive-attr drift's commit. Peer with the enclosing
5594 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5595 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
5596 // discipline the SupervisorSpec top-level lift established,
5597 // extended here to the sibling per-`:children` entry `ChildSpec`
5598 // derive so the last M2 typed-struct sub-block
5599 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
5600 // surface without a lifted serde-key peer joins the substrate's
5601 // "one canonical byte-string per typed serialized-key axis"
5602 // discipline.
5603 let c = ChildSpec {
5604 caixa: "worker".into(),
5605 versao: "^0.1".into(),
5606 restart: RestartPolicy::Permanent,
5607 };
5608 let json = serde_json::to_string(&c).unwrap();
5609 for key in [
5610 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5611 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5612 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5613 ] {
5614 let quoted = format!("\"{key}\"");
5615 assert!(
5616 json.contains("ed),
5617 "serialized ChildSpec must carry the lifted \
5618 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
5619 in the JSON emission (got: {json})",
5620 );
5621 }
5622 }
5623
5624 #[test]
5625 fn supervisor_child_key_consts_are_pairwise_distinct() {
5626 // Cross-axis drift-detection pin: a future collapse of two
5627 // canonical `ChildSpec` per-entry byte-strings onto the same
5628 // value (e.g. an accidental copy-paste flip of
5629 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
5630 // silently reroute every downstream probe on one axis onto the
5631 // sibling axis's overlay entry and pass every propagation-probe
5632 // test that expected only the stale axis's value. Peer of the
5633 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
5634 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
5635 // pair (ce80ca0).
5636 let all = [
5637 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5638 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5639 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5640 ];
5641 for (i, a) in all.iter().enumerate() {
5642 for b in all.iter().skip(i + 1) {
5643 assert_ne!(
5644 a, b,
5645 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
5646 distinct canonical byte-sequences — got `{a}` == `{b}`",
5647 );
5648 }
5649 }
5650 }
5651
5652 #[test]
5653 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
5654 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
5655 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5656 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5657 // capital, no whitespace / dots) — the canonical shape the
5658 // `#[serde(rename_all = "camelCase")]` derive produces on
5659 // `ChildSpec`. A future flip to a non-camelCase attribute at the
5660 // derive surfaces both here (this test fails on the
5661 // stale-constant shape) and at
5662 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
5663 // (that test fails on the mismatch between const and derive).
5664 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
5665 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
5666 for key in [
5667 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5668 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5669 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5670 ] {
5671 assert!(
5672 !key.is_empty(),
5673 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
5674 );
5675 let first = key.chars().next().unwrap();
5676 assert!(
5677 first.is_ascii_lowercase(),
5678 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
5679 byte (got {key:?}, leads with {first:?})",
5680 );
5681 assert!(
5682 key.chars().all(|c| c.is_ascii_alphanumeric()),
5683 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
5684 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5685 );
5686 }
5687 }
5688
5689 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
5690
5691 #[test]
5692 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
5693 // The fail-before-pass-after pin: pre-lift there was no
5694 // single-source binding between the [`RestartStrategy`] variant
5695 // name the un-`rename`d `Serialize` derive emits under
5696 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
5697 // every downstream cluster-side dispatcher (the future
5698 // wasm-operator's per-supervisor sibling-restart branch, the
5699 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5700 // admission-time enum-arm bind, the `caixa-operator`'s
5701 // hierarchical reconciliation scheduler's per-strategy fan-out)
5702 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
5703 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
5704 // override, or a variant rename in the source — would silently
5705 // rebrand the emitted scalar under one spelling while every
5706 // downstream dispatcher still probed the other, with the failure
5707 // surfacing at the operator's reconcile posture (subtrees coming
5708 // up under the `default()` `OneForOne` arm rather than the typed
5709 // slot's declared strategy — a bad child would then only take
5710 // itself down instead of the sibling set the author intended, so
5711 // shared-state children fall out of sync) far from the source
5712 // rebrand commit and with no field naming the drift. Pinning the
5713 // two paths (the `Serialize` derive's serialized string AND the
5714 // [`RestartStrategy::as_str`] helper) to the same four lifted
5715 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
5716 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
5717 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
5718 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
5719 // byte-strings makes any future drift on either endpoint fail
5720 // here at caixa-core build time. Peer of the M3
5721 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
5722 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
5723 // three-path-convergence discipline, extended to close the
5724 // OTP-shaped per-supervisor sibling-restart axis.
5725 for (variant, expected) in [
5726 (
5727 RestartStrategy::OneForOne,
5728 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5729 ),
5730 (
5731 RestartStrategy::OneForAll,
5732 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5733 ),
5734 (
5735 RestartStrategy::RestForOne,
5736 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5737 ),
5738 (
5739 RestartStrategy::SimpleOneForOne,
5740 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5741 ),
5742 ] {
5743 let json = serde_json::to_string(&variant).unwrap();
5744 assert_eq!(
5745 json,
5746 format!("\"{expected}\""),
5747 "RestartStrategy::{variant:?} must serialize to {expected:?}"
5748 );
5749 assert_eq!(
5750 variant.as_str(),
5751 expected,
5752 "RestartStrategy::{variant:?}.as_str() must return the lifted \
5753 SUPERVISOR_ESTRATEGIA_* constant"
5754 );
5755 }
5756 }
5757
5758 #[test]
5759 fn supervisor_estrategia_consts_are_pairwise_distinct() {
5760 // Cross-arm drift-detection pin: a future collapse of two
5761 // canonical variant byte-strings onto the same value (e.g. an
5762 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
5763 // to also read `"OneForOne"`) would silently reroute every
5764 // downstream operator's per-strategy dispatch onto the sibling
5765 // arm's reconcile branch and pass every propagation-probe test
5766 // that expected only the stale arm's value — the mis-strategied
5767 // subtree would come up with the wrong sibling-restart posture
5768 // on every subsequent failure. Peer of the sibling four-way
5769 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
5770 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
5771 let all = [
5772 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5773 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5774 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5775 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5776 ];
5777 for (i, a) in all.iter().enumerate() {
5778 for (j, b) in all.iter().enumerate() {
5779 if i != j {
5780 assert_ne!(
5781 a, b,
5782 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
5783 — got duplicate {a:?} at indices {i} and {j}",
5784 );
5785 }
5786 }
5787 }
5788 }
5789
5790 #[test]
5791 fn restart_strategy_display_routes_through_as_str_helper() {
5792 // The fail-before-pass-after pin on the first half of the
5793 // three-path convergence: pre-convergence the sibling
5794 // OTP-shape typed enum [`RestartStrategy`] carried a
5795 // [`std::fmt::Display`] surface via its
5796 // `#[discriminant(also_display)]` gen-platform derive route,
5797 // which arrived kebab-case as `"one-for-one"` /
5798 // `"one-for-all"` / `"rest-for-one"` /
5799 // `"simple-one-for-one"` while the wire format ran as
5800 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
5801 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
5802 // Every consumer reaching for a strategy byte-string past the
5803 // wire format had to pick between three paths
5804 // ([`RestartStrategy::as_str`], the `Serialize` derive's
5805 // serialized string, or `format!("{v}")` on the
5806 // discriminant-Display route), any two of which a future
5807 // variant rename or `#[serde(rename_all = "kebab-case")]`
5808 // attribute would silently desynchronize. Wiring
5809 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
5810 // closes the third path: every `format!("{v}")` call reaches
5811 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
5812 // const the wire format and the [`RestartStrategy::as_str`]
5813 // helper already route through, so a future variant rename
5814 // lands at exactly one place. Pin the routing here so a future
5815 // `impl std::fmt::Display for RestartStrategy`
5816 // reimplementation that hand-rolls the arms instead of
5817 // delegating to [`RestartStrategy::as_str`] fails at
5818 // caixa-core build time. Peer of the M3
5819 // `placement_strategy_display_routes_through_as_str_helper`
5820 // (cc8f749) which the M3 axis converged first.
5821 for &variant in RestartStrategy::ALL {
5822 assert_eq!(
5823 variant.to_string(),
5824 variant.as_str(),
5825 "RestartStrategy::{variant:?} Display must route through \
5826 RestartStrategy::as_str (single source of truth: the lifted \
5827 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
5828 );
5829 }
5830 }
5831
5832 #[test]
5833 fn restart_strategy_display_matches_serialized_wire_byte_string() {
5834 // The fail-before-pass-after pin on the second half of the
5835 // three-path convergence: `Display` (user-facing text) agrees
5836 // byte-for-byte with the `Serialize` derive's wire format
5837 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
5838 // scalar) on every variant. Pre-convergence the two paths
5839 // were structurally independent — a future
5840 // `#[serde(rename_all = "kebab-case")]` attribute on the
5841 // enum would silently rebrand the emitted wire scalar
5842 // (`one-for-one`, `one-for-all`, `rest-for-one`,
5843 // `simple-one-for-one`) while every consumer that
5844 // pretty-prints the strategy (the future wasm-operator's
5845 // per-supervisor sibling-restart-strategy diagnostic line,
5846 // the future `feira app graph` per-supervisor strategy line,
5847 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
5848 // materializer's admission-webhook rejection body) would
5849 // still emit the PascalCase form the `as_str` / `Display`
5850 // route returns, with the mismatch surfacing at consumer
5851 // parse time / operator dispatch time far from the source
5852 // rebrand commit. Pin the two paths byte-for-byte here so any
5853 // future serde-attribute or variant-rename drift is a
5854 // caixa-core-build-time test failure at this call, not a
5855 // silent per-consumer dispatch miss. Peer of the M3
5856 // `placement_strategy_display_matches_serialized_wire_byte_string`
5857 // (cc8f749) which the M3 axis converged first.
5858 for &variant in RestartStrategy::ALL {
5859 let wire = serde_json::to_string(&variant).unwrap();
5860 let unquoted = wire
5861 .strip_prefix('"')
5862 .and_then(|s| s.strip_suffix('"'))
5863 .expect("serialized RestartStrategy is a JSON string");
5864 assert_eq!(
5865 variant.to_string(),
5866 unquoted,
5867 "RestartStrategy::{variant:?} Display byte-string must match the \
5868 Serialize derive's wire byte-string (three-path convergence: \
5869 Display + as_str + Serialize all resolve to the same \
5870 SUPERVISOR_ESTRATEGIA_* const)"
5871 );
5872 }
5873 }
5874
5875 #[test]
5876 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
5877 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
5878 // exhaustive-iteration surface: every variant appears exactly
5879 // once, and the slice length matches the arm count of the
5880 // closed set. Every consumer that walks the accepted-strategy
5881 // set (a future `feira supervisor --estrategia …` CLI-side
5882 // arg-parse's "did you mean" hint, a future M4 admission-
5883 // webhook's rejection body naming the accepted-`:estrategia`
5884 // list, the [`RestartStrategy::from_wire`] reverse-projection
5885 // consumers that iterate the accept-set for diagnostic
5886 // rendering) reads through this slice, so a future arm addition
5887 // that grows the enum but forgets to grow [`Self::ALL`]
5888 // silently truncates every downstream consumer's accept-set at
5889 // the same pre-addition boundary — this pin fails at caixa-core
5890 // build time on the pairwise-distinct + arm-count invariants.
5891 //
5892 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
5893 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
5894 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
5895 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5896 // pins on the peer closed-set typed-enum axes.
5897 let all: &[RestartStrategy] = RestartStrategy::ALL;
5898 assert_eq!(
5899 all.len(),
5900 4,
5901 "RestartStrategy::ALL must enumerate every variant of the \
5902 four-arm closed set (OneForOne, OneForAll, RestForOne, \
5903 SimpleOneForOne); got {all:?}"
5904 );
5905 for (i, a) in all.iter().enumerate() {
5906 for (j, b) in all.iter().enumerate() {
5907 if i != j {
5908 assert_ne!(
5909 a, b,
5910 "RestartStrategy::ALL must carry every variant exactly \
5911 once — got duplicate {a:?} at indices {i} and {j}"
5912 );
5913 }
5914 }
5915 }
5916 for variant in [
5917 RestartStrategy::OneForOne,
5918 RestartStrategy::OneForAll,
5919 RestartStrategy::RestForOne,
5920 RestartStrategy::SimpleOneForOne,
5921 ] {
5922 assert!(
5923 all.contains(&variant),
5924 "RestartStrategy::ALL must contain {variant:?} — a future arm \
5925 addition that grows the enum but forgets to grow the ALL slice \
5926 silently truncates every downstream consumer's accept-set at \
5927 the pre-addition boundary"
5928 );
5929 }
5930 }
5931
5932 #[test]
5933 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
5934 // Fail-before-pass-after pin on the forward accept-set of the
5935 // [`RestartStrategy::from_wire`] reverse projection: every
5936 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
5937 // constant the [`RestartStrategy::as_str`] emitter walks parses
5938 // back to its paired variant. Any future arm addition that
5939 // grows the emitter's `as_str` match but forgets to grow the
5940 // parser's `from_wire` match silently splits the two halves of
5941 // the round-trip — the wire byte-string one non-serde consumer
5942 // parses from the one the emitter wrote — with the failure
5943 // surfacing at parse time far from the rebrand commit. Pinning
5944 // the four-arm accept-set here catches the drift at caixa-core
5945 // build time.
5946 //
5947 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
5948 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
5949 // accept-set pins on the peer closed-set typed-enum `str → Self`
5950 // axes.
5951 for (wire, expected) in [
5952 (
5953 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
5954 RestartStrategy::OneForOne,
5955 ),
5956 (
5957 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
5958 RestartStrategy::OneForAll,
5959 ),
5960 (
5961 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
5962 RestartStrategy::RestForOne,
5963 ),
5964 (
5965 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
5966 RestartStrategy::SimpleOneForOne,
5967 ),
5968 ] {
5969 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
5970 panic!(
5971 "RestartStrategy::from_wire({wire:?}) must accept every \
5972 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
5973 lifted canonical byte-string that RestartStrategy::{expected:?} \
5974 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
5975 )
5976 });
5977 assert_eq!(
5978 parsed, expected,
5979 "RestartStrategy::from_wire({wire:?}) must return \
5980 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
5981 );
5982 }
5983 }
5984
5985 #[test]
5986 fn restart_strategy_from_wire_round_trips_through_as_str() {
5987 // Fail-before-pass-after pin on the closed round-trip between
5988 // the forward [`RestartStrategy::as_str`] emitter and the
5989 // reverse [`RestartStrategy::from_wire`] parser: for every
5990 // variant in [`RestartStrategy::ALL`], parsing the emitter's
5991 // output must return exactly the same variant. Any per-arm
5992 // divergence — a future arm added to `as_str` but not
5993 // `from_wire`, an accidental copy-paste flip in one but not
5994 // the other — silently splits the emit and parse halves and
5995 // the failure surfaces at consumer parse time far from the
5996 // drift site. The `ALL`-iterating shape means a future arm
5997 // addition picks up the coverage by construction.
5998 //
5999 // Peer of the sibling
6000 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6001 // (18c7342) round-trip pin on
6002 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6003 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6004 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6005 for &variant in RestartStrategy::ALL {
6006 let wire = variant.as_str();
6007 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6008 panic!(
6009 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6010 must be Some({variant:?}) — the two halves of the round-trip \
6011 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6012 got None on wire byte-string {wire:?}"
6013 )
6014 });
6015 assert_eq!(
6016 parsed, variant,
6017 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6018 must round-trip to the same variant; got {parsed:?}"
6019 );
6020 }
6021 }
6022
6023 #[test]
6024 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6025 // Fail-before-pass-after pin on the closed-set refusal
6026 // discipline of [`RestartStrategy::from_wire`]: every
6027 // byte-string outside the four-arm accept-set returns `None`
6028 // rather than silently collapsing onto the [`Default`]
6029 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6030 // exercised here sweeps the load-bearing drift shapes: the
6031 // empty string (a stripped serde-attribute drift), all-
6032 // whitespace strings (the canonical text-editor accidental
6033 // padding shape), the kebab-case dispatcher-catalog identities
6034 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6035 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6036 // derived [`std::str::FromStr`] accept-set, which parses the
6037 // *other* axis of this enum's two-axis split and must not leak
6038 // into the `from_wire` PascalCase-wire accept-set), the
6039 // lowercased single-word forms (`"oneforone"`), the padded
6040 // canonical scalar (`" OneForOne "`), the trailing-newline
6041 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6042 // (`"AllForOne"` — the canonical typo direction).
6043 //
6044 // Peer of the sibling
6045 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6046 // (2aa6d23) +
6047 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6048 // (18c7342) refusal pins on the peer closed-set typed-enum
6049 // axes.
6050 for bad in [
6051 "",
6052 " ",
6053 "\n",
6054 "\t",
6055 "one-for-one",
6056 "one-for-all",
6057 "rest-for-one",
6058 "simple-one-for-one",
6059 "oneforone",
6060 "OneForOnes",
6061 "one_for_one",
6062 "one for one",
6063 "ONEFORONE",
6064 "OneForOne ",
6065 " OneForOne",
6066 " SimpleOneForOne ",
6067 "OneForOne\n",
6068 "restforone",
6069 "REST_FOR_ONE",
6070 "AllForOne",
6071 "Simple",
6072 "?",
6073 ] {
6074 assert!(
6075 RestartStrategy::from_wire(bad).is_none(),
6076 "RestartStrategy::from_wire({bad:?}) must return None — the \
6077 parser's accept-set is exactly the four RestartStrategy::as_str \
6078 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6079 and this byte-string is outside that closed set"
6080 );
6081 }
6082 }
6083
6084 #[test]
6085 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6086 // Fail-before-pass-after pin on the fourth path of the four-path
6087 // convergence: `from_wire` (the reverse projection) inverts the
6088 // `Serialize` derive's wire byte-string on every variant.
6089 // Together with the pre-existing three-path convergence
6090 // (`Display` + `as_str` + `Serialize` all resolve to the same
6091 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6092 // pinned by
6093 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6094 // this closes the round-trip: the wire byte-string the
6095 // `Serialize` derive emits parses back to the same variant
6096 // through `from_wire`, so any future serde-attribute or variant-
6097 // rename drift on the emit half now surfaces as a matched drift
6098 // on the parse half at caixa-core build time — the two halves
6099 // migrate as a unit through the lifted consts on any future
6100 // rename, and the round-trip cannot silently split.
6101 //
6102 // Peer of the sibling
6103 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6104 // (18c7342) wire-format pin on
6105 // [`crate::aplicacao::PlacementStrategy::from_wire`].
6106 for &variant in RestartStrategy::ALL {
6107 let wire = serde_json::to_string(&variant).unwrap();
6108 let unquoted = wire
6109 .strip_prefix('"')
6110 .and_then(|s| s.strip_suffix('"'))
6111 .expect("serialized RestartStrategy is a JSON string");
6112 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6113 panic!(
6114 "RestartStrategy::from_wire({unquoted:?}) must accept the \
6115 Serialize derive's wire byte-string for \
6116 RestartStrategy::{variant:?} — the four-path convergence \
6117 (Display + as_str + Serialize + from_wire) resolves through \
6118 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6119 )
6120 });
6121 assert_eq!(
6122 parsed, variant,
6123 "RestartStrategy::from_wire of the Serialize derive's wire \
6124 byte-string for RestartStrategy::{variant:?} must round-trip \
6125 to the same variant; got {parsed:?}"
6126 );
6127 }
6128 }
6129
6130 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
6131
6132 #[test]
6133 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
6134 // The fail-before-pass-after pin: pre-lift there was no
6135 // single-source binding between the [`RestartPolicy`] variant
6136 // name the un-`rename`d `Serialize` derive emits under
6137 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
6138 // byte-string every downstream cluster-side dispatcher (the
6139 // future wasm-operator's per-child post-exit restart-decision
6140 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6141 // materializer's admission-time enum-arm bind, the
6142 // `caixa-operator`'s hierarchical reconciliation scheduler's
6143 // per-child-policy fan-out) probes verbatim. A future
6144 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
6145 // or a per-variant `#[serde(rename = "…")]` override, or a
6146 // variant rename in the source — would silently rebrand the
6147 // emitted scalar under one spelling while every downstream
6148 // dispatcher still probed the other, with the failure surfacing
6149 // at the operator's reconcile posture (children coming up under
6150 // the `default()` `Permanent` arm rather than the typed slot's
6151 // declared policy — a `:temporary` `oneShot` child would be
6152 // restarted on clean exit, treating the successful-completion
6153 // signal as failure and re-running the completion-terminal
6154 // one-shot indefinitely; a `:transient` child that clean-exited
6155 // would be restarted, masking the clean-completion contract)
6156 // far from the source rebrand commit and with no field naming
6157 // the drift. Pinning the two paths (the `Serialize` derive's
6158 // serialized string AND the [`RestartPolicy::as_str`] helper)
6159 // to the same three lifted
6160 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
6161 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
6162 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
6163 // byte-strings makes any future drift on either endpoint fail
6164 // here at caixa-core build time. Peer of the sibling
6165 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
6166 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6167 // and the M3
6168 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6169 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
6170 // same three-path-convergence discipline, extended to close the
6171 // third OTP-shaped closed-enum discriminator axis on the caixa
6172 // typed surface (per-child restart-decision policy).
6173 for (variant, expected) in [
6174 (
6175 RestartPolicy::Permanent,
6176 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6177 ),
6178 (
6179 RestartPolicy::Temporary,
6180 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6181 ),
6182 (
6183 RestartPolicy::Transient,
6184 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6185 ),
6186 ] {
6187 let json = serde_json::to_string(&variant).unwrap();
6188 assert_eq!(
6189 json,
6190 format!("\"{expected}\""),
6191 "RestartPolicy::{variant:?} must serialize to {expected:?}"
6192 );
6193 assert_eq!(
6194 variant.as_str(),
6195 expected,
6196 "RestartPolicy::{variant:?}.as_str() must return the lifted \
6197 SUPERVISOR_CHILD_RESTART_* constant"
6198 );
6199 }
6200 }
6201
6202 #[test]
6203 fn supervisor_child_restart_consts_are_pairwise_distinct() {
6204 // Cross-arm drift-detection pin: a future collapse of two
6205 // canonical variant byte-strings onto the same value (e.g. an
6206 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
6207 // to also read `"Permanent"`) would silently reroute every
6208 // downstream operator's per-child-policy dispatch onto the
6209 // sibling arm's reconcile branch and pass every propagation-probe
6210 // test that expected only the stale arm's value — a `:transient`
6211 // child would come up under the `:permanent` restart-decision
6212 // posture on every subsequent clean exit, so a completion-terminal
6213 // child would be restarted indefinitely against its declared
6214 // policy. Peer of the sibling
6215 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
6216 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6217 // and the four-way distinct pin
6218 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
6219 // top-level `SUPERVISOR_KEY_*` axis.
6220 let all = [
6221 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6222 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6223 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6224 ];
6225 for (i, a) in all.iter().enumerate() {
6226 for (j, b) in all.iter().enumerate() {
6227 if i != j {
6228 assert_ne!(
6229 a, b,
6230 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
6231 — got duplicate {a:?} at indices {i} and {j}",
6232 );
6233 }
6234 }
6235 }
6236 }
6237
6238 #[test]
6239 fn restart_policy_display_routes_through_as_str_helper() {
6240 // The fail-before-pass-after pin on the first half of the
6241 // three-path convergence: pre-convergence [`RestartPolicy`]
6242 // carried a [`std::fmt::Display`] surface via its
6243 // `#[discriminant(also_display)]` gen-platform derive route,
6244 // which arrived kebab-case as `"permanent"` / `"temporary"`
6245 // / `"transient"` on this three-arm enum (whose variant
6246 // names each collapse to their own lowercase form under the
6247 // kebab-case transform) while the wire format ran as
6248 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
6249 // through the un-`rename`d serde derive. Every consumer
6250 // reaching for a policy byte-string past the wire format had
6251 // to pick between three paths ([`RestartPolicy::as_str`],
6252 // the `Serialize` derive's serialized string, or
6253 // `format!("{v}")` on the discriminant-Display route), any
6254 // two of which a future variant rename or
6255 // `#[serde(rename_all = "kebab-case")]` attribute would
6256 // silently desynchronize. Wiring [`std::fmt::Display`]
6257 // through [`RestartPolicy::as_str`] closes the third path:
6258 // every `format!("{v}")` call reaches the same lifted
6259 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
6260 // wire format and the [`RestartPolicy::as_str`] helper
6261 // already route through, so a future variant rename lands at
6262 // exactly one place. Pin the routing here so a future
6263 // `impl std::fmt::Display for RestartPolicy`
6264 // reimplementation that hand-rolls the arms instead of
6265 // delegating to [`RestartPolicy::as_str`] fails at
6266 // caixa-core build time. Peer of the sibling
6267 // [`restart_strategy_display_routes_through_as_str_helper`]
6268 // on the per-supervisor sibling-restart-strategy axis and
6269 // the M3
6270 // `placement_strategy_display_routes_through_as_str_helper`
6271 // (cc8f749) — the third of three OTP-shape closed-enum
6272 // discriminator axes on the caixa typed surface now
6273 // converged onto the same three-path
6274 // (Display → as_str → lifted const) discipline.
6275 for variant in [
6276 RestartPolicy::Permanent,
6277 RestartPolicy::Temporary,
6278 RestartPolicy::Transient,
6279 ] {
6280 assert_eq!(
6281 variant.to_string(),
6282 variant.as_str(),
6283 "RestartPolicy::{variant:?} Display must route through \
6284 RestartPolicy::as_str (single source of truth: the lifted \
6285 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
6286 );
6287 }
6288 }
6289
6290 #[test]
6291 fn restart_policy_display_matches_serialized_wire_byte_string() {
6292 // The fail-before-pass-after pin on the second half of the
6293 // three-path convergence: `Display` (user-facing text) agrees
6294 // byte-for-byte with the `Serialize` derive's wire format
6295 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
6296 // scalar) on every variant. Pre-convergence the two paths
6297 // were structurally independent — a future
6298 // `#[serde(rename_all = "kebab-case")]` attribute on the
6299 // enum would silently rebrand the emitted wire scalar
6300 // (`permanent`, `temporary`, `transient`) while every
6301 // consumer that pretty-prints the policy (the future
6302 // wasm-operator's per-child post-exit restart-decision
6303 // diagnostic line, the future `feira app graph` per-child
6304 // restart column, the future M4
6305 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6306 // per-child admission-webhook rejection body) would still
6307 // emit the PascalCase form the `as_str` / `Display` route
6308 // returns, with the mismatch surfacing at consumer parse
6309 // time / operator dispatch time far from the source rebrand
6310 // commit. Pin the two paths byte-for-byte here so any future
6311 // serde-attribute or variant-rename drift is a
6312 // caixa-core-build-time test failure at this call, not a
6313 // silent per-consumer dispatch miss. Peer of the sibling
6314 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
6315 // on the per-supervisor sibling-restart-strategy axis and
6316 // the M3
6317 // `placement_strategy_display_matches_serialized_wire_byte_string`
6318 // (cc8f749).
6319 for variant in [
6320 RestartPolicy::Permanent,
6321 RestartPolicy::Temporary,
6322 RestartPolicy::Transient,
6323 ] {
6324 let wire = serde_json::to_string(&variant).unwrap();
6325 let unquoted = wire
6326 .strip_prefix('"')
6327 .and_then(|s| s.strip_suffix('"'))
6328 .expect("serialized RestartPolicy is a JSON string");
6329 assert_eq!(
6330 variant.to_string(),
6331 unquoted,
6332 "RestartPolicy::{variant:?} Display byte-string must match the \
6333 Serialize derive's wire byte-string (three-path convergence: \
6334 Display + as_str + Serialize all resolve to the same \
6335 SUPERVISOR_CHILD_RESTART_* const)"
6336 );
6337 }
6338 }
6339
6340 #[test]
6341 fn restart_policy_all_enumerates_every_variant_exactly_once() {
6342 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
6343 // exhaustive-iteration surface: every variant appears exactly
6344 // once, and the slice length matches the arm count of the
6345 // closed set. Every consumer that walks the accepted-policy
6346 // set (a future `feira supervisor --restart …` CLI-side
6347 // arg-parse's "did you mean" hint, a future M4 admission-
6348 // webhook's per-child rejection body naming the accepted-
6349 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
6350 // projection consumers that iterate the accept-set for
6351 // diagnostic rendering) reads through this slice, so a future
6352 // arm addition that grows the enum but forgets to grow
6353 // [`Self::ALL`] silently truncates every downstream consumer's
6354 // accept-set at the same pre-addition boundary — this pin
6355 // fails at caixa-core build time on the pairwise-distinct +
6356 // arm-count invariants.
6357 //
6358 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
6359 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
6360 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6361 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6362 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6363 // pins on the peer closed-set typed-enum axes.
6364 let all: &[RestartPolicy] = RestartPolicy::ALL;
6365 assert_eq!(
6366 all.len(),
6367 3,
6368 "RestartPolicy::ALL must enumerate every variant of the \
6369 three-arm closed set (Permanent, Temporary, Transient); \
6370 got {all:?}"
6371 );
6372 for (i, a) in all.iter().enumerate() {
6373 for (j, b) in all.iter().enumerate() {
6374 if i != j {
6375 assert_ne!(
6376 a, b,
6377 "RestartPolicy::ALL must carry every variant exactly \
6378 once — got duplicate {a:?} at indices {i} and {j}"
6379 );
6380 }
6381 }
6382 }
6383 for variant in [
6384 RestartPolicy::Permanent,
6385 RestartPolicy::Temporary,
6386 RestartPolicy::Transient,
6387 ] {
6388 assert!(
6389 all.contains(&variant),
6390 "RestartPolicy::ALL must contain {variant:?} — a future arm \
6391 addition that grows the enum but forgets to grow the ALL slice \
6392 silently truncates every downstream consumer's accept-set at \
6393 the pre-addition boundary"
6394 );
6395 }
6396 }
6397
6398 #[test]
6399 fn restart_policy_from_wire_accepts_every_lifted_constant() {
6400 // Fail-before-pass-after pin on the forward accept-set of the
6401 // [`RestartPolicy::from_wire`] reverse projection: every
6402 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
6403 // constant the [`RestartPolicy::as_str`] emitter walks parses
6404 // back to its paired variant. Any future arm addition that
6405 // grows the emitter's `as_str` match but forgets to grow the
6406 // parser's `from_wire` match silently splits the two halves of
6407 // the round-trip — the wire byte-string one non-serde consumer
6408 // parses from the one the emitter wrote — with the failure
6409 // surfacing at the operator's reconcile posture (a `:temporary`
6410 // `oneShot` child restarted on clean exit, a `:transient` child
6411 // restarted after clean completion) far from the rebrand
6412 // commit. Pinning the three-arm accept-set here catches the
6413 // drift at caixa-core build time.
6414 //
6415 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
6416 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
6417 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6418 // accept-set pins on the peer closed-set typed-enum `str → Self`
6419 // axes.
6420 for (wire, expected) in [
6421 (
6422 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6423 RestartPolicy::Permanent,
6424 ),
6425 (
6426 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6427 RestartPolicy::Temporary,
6428 ),
6429 (
6430 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6431 RestartPolicy::Transient,
6432 ),
6433 ] {
6434 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6435 panic!(
6436 "RestartPolicy::from_wire({wire:?}) must accept every \
6437 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
6438 lifted canonical byte-string that RestartPolicy::{expected:?} \
6439 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
6440 )
6441 });
6442 assert_eq!(
6443 parsed, expected,
6444 "RestartPolicy::from_wire({wire:?}) must return \
6445 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
6446 );
6447 }
6448 }
6449
6450 #[test]
6451 fn restart_policy_from_wire_round_trips_through_as_str() {
6452 // Fail-before-pass-after pin on the closed round-trip between
6453 // the forward [`RestartPolicy::as_str`] emitter and the
6454 // reverse [`RestartPolicy::from_wire`] parser: for every
6455 // variant in [`RestartPolicy::ALL`], parsing the emitter's
6456 // output must return exactly the same variant. Any per-arm
6457 // divergence — a future arm added to `as_str` but not
6458 // `from_wire`, an accidental copy-paste flip in one but not
6459 // the other — silently splits the emit and parse halves and
6460 // the failure surfaces at consumer parse time far from the
6461 // drift site. The `ALL`-iterating shape means a future arm
6462 // addition picks up the coverage by construction.
6463 //
6464 // Peer of the sibling
6465 // [`restart_strategy_from_wire_round_trips_through_as_str`]
6466 // (4eec29c) round-trip pin on
6467 // [`RestartStrategy::from_wire`] and the M3
6468 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6469 // (18c7342) round-trip pin on
6470 // [`crate::aplicacao::PlacementStrategy::from_wire`].
6471 for &variant in RestartPolicy::ALL {
6472 let wire = variant.as_str();
6473 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
6474 panic!(
6475 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6476 must be Some({variant:?}) — the two halves of the round-trip \
6477 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
6478 got None on wire byte-string {wire:?}"
6479 )
6480 });
6481 assert_eq!(
6482 parsed, variant,
6483 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
6484 must round-trip to the same variant; got {parsed:?}"
6485 );
6486 }
6487 }
6488
6489 #[test]
6490 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
6491 // Fail-before-pass-after pin on the closed-set refusal
6492 // discipline of [`RestartPolicy::from_wire`]: every
6493 // byte-string outside the three-arm accept-set returns `None`
6494 // rather than silently collapsing onto the [`Default`]
6495 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
6496 // exercised here sweeps the load-bearing drift shapes: the
6497 // empty string (a stripped serde-attribute drift), all-
6498 // whitespace strings (the canonical text-editor accidental
6499 // padding shape), the kebab-case dispatcher-catalog identities
6500 // (`"permanent"` / `"temporary"` / `"transient"` — the
6501 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
6502 // accept-set, which parses the *other* axis of this enum's
6503 // two-axis split and must not leak into the `from_wire`
6504 // PascalCase-wire accept-set — a lowercase leak here would
6505 // silently accept the operator's kebab-case
6506 // dispatcher-catalog probe under the wire-axis parser and mis-
6507 // route a `:permanent` intent), the padded canonical scalar
6508 // (`" Permanent "`), the trailing-newline shapes
6509 // (`"Permanent\n"`), the uppercase-single-word forms
6510 // (`"PERMANENT"`), and neighboring-but-unknown arms
6511 // (`"Restart"` — the canonical typo direction toward the
6512 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
6513 //
6514 // Peer of the sibling
6515 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
6516 // (4eec29c) +
6517 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6518 // (2aa6d23) +
6519 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6520 // (18c7342) refusal pins on the peer closed-set typed-enum
6521 // axes.
6522 for bad in [
6523 "",
6524 " ",
6525 "\n",
6526 "\t",
6527 "permanent",
6528 "temporary",
6529 "transient",
6530 "PERMANENT",
6531 "TEMPORARY",
6532 "TRANSIENT",
6533 "Permanents",
6534 "Permanent ",
6535 " Permanent",
6536 " Transient ",
6537 "Permanent\n",
6538 "perma",
6539 "Trans",
6540 "OneForOne",
6541 "Restart",
6542 "?",
6543 ] {
6544 assert!(
6545 RestartPolicy::from_wire(bad).is_none(),
6546 "RestartPolicy::from_wire({bad:?}) must return None — the \
6547 parser's accept-set is exactly the three RestartPolicy::as_str \
6548 outputs (Permanent, Temporary, Transient), and this \
6549 byte-string is outside that closed set"
6550 );
6551 }
6552 }
6553
6554 #[test]
6555 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
6556 // Fail-before-pass-after pin on the fourth path of the four-path
6557 // convergence: `from_wire` (the reverse projection) inverts the
6558 // `Serialize` derive's wire byte-string on every variant.
6559 // Together with the pre-existing three-path convergence
6560 // (`Display` + `as_str` + `Serialize` all resolve to the same
6561 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
6562 // pinned by
6563 // [`restart_policy_display_matches_serialized_wire_byte_string`])
6564 // this closes the round-trip: the wire byte-string the
6565 // `Serialize` derive emits parses back to the same variant
6566 // through `from_wire`, so any future serde-attribute or variant-
6567 // rename drift on the emit half now surfaces as a matched drift
6568 // on the parse half at caixa-core build time — the two halves
6569 // migrate as a unit through the lifted consts on any future
6570 // rename, and the round-trip cannot silently split.
6571 //
6572 // Peer of the sibling
6573 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6574 // (4eec29c) wire-format pin on
6575 // [`RestartStrategy::from_wire`] and the M3
6576 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6577 // (18c7342) wire-format pin on
6578 // [`crate::aplicacao::PlacementStrategy::from_wire`].
6579 for &variant in RestartPolicy::ALL {
6580 let wire = serde_json::to_string(&variant).unwrap();
6581 let unquoted = wire
6582 .strip_prefix('"')
6583 .and_then(|s| s.strip_suffix('"'))
6584 .expect("serialized RestartPolicy is a JSON string");
6585 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
6586 panic!(
6587 "RestartPolicy::from_wire({unquoted:?}) must accept the \
6588 Serialize derive's wire byte-string for \
6589 RestartPolicy::{variant:?} — the four-path convergence \
6590 (Display + as_str + Serialize + from_wire) resolves through \
6591 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
6592 )
6593 });
6594 assert_eq!(
6595 parsed, variant,
6596 "RestartPolicy::from_wire of the Serialize derive's wire \
6597 byte-string for RestartPolicy::{variant:?} must round-trip \
6598 to the same variant; got {parsed:?}"
6599 );
6600 }
6601 }
6602
6603 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
6604 //
6605 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
6606 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
6607 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
6608 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
6609 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
6610 // the peer per-`:upgrade-from :from` axis. The three pins jointly
6611 // brace the accessor against every future silent detour that would
6612 // desynchronize it from the raw `.caixa` field access every consumer
6613 // previously open-coded.
6614
6615 #[test]
6616 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
6617 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
6618 // [`ChildSpec::nome`] must return the `:children :caixa` field
6619 // byte-for-byte across every DNS-1123-label value the upstream
6620 // [`crate::render::require_valid_dns_1123_label`] gate at
6621 // `SupervisorSpec::validate` admits. Peer of the sibling
6622 // `membro_nome_returns_caixa_byte_equal_across_permutations`
6623 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
6624 // substrate-primitive accessor must byte-equal the raw field
6625 // access verbatim across every author-declared value" discipline
6626 // extended to the M2 supervisor-tree per-`:children` arm. Pins
6627 // against a future silent detour that re-normalized the child
6628 // identity (an accidental `.to_lowercase()` — every `:children
6629 // :caixa` is validated as a DNS-1123 label upstream, so any
6630 // re-normalization is redundant + a drift surface between the
6631 // validator and the accessor), a namespace-prefix rewrite (an
6632 // accidental `format!("{namespace}/{caixa}")` per-CR
6633 // fully-qualified rewrite that didn't land on the peer axes), or
6634 // a per-cluster alias stamp the future wasm-operator's
6635 // hierarchical reconciliation scheduler authors on one consumer
6636 // without the others. Five values sweep the accept-set the
6637 // DNS-1123 gate upstream admits (short single-word / dashed /
6638 // v-suffixed / mixed-digit child names).
6639 for name in [
6640 "worker",
6641 "cache-server",
6642 "scratch-job",
6643 "orders-v2",
6644 "session-8080",
6645 ] {
6646 let c = ChildSpec {
6647 caixa: name.into(),
6648 versao: "^0.1".into(),
6649 restart: RestartPolicy::Permanent,
6650 };
6651 assert_eq!(
6652 c.nome(),
6653 name,
6654 "ChildSpec::nome must return :children :caixa verbatim \
6655 (got {:?}, expected {name:?})",
6656 c.nome(),
6657 );
6658 assert_eq!(
6659 c.nome(),
6660 c.caixa.as_str(),
6661 "ChildSpec::nome must byte-equal the .caixa field access",
6662 );
6663 }
6664 }
6665
6666 #[test]
6667 fn child_spec_nome_borrows_from_caixa_storage() {
6668 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
6669 // `&str` slice that borrows from the typed slot's own [`String`]
6670 // storage — same-address invariant with `c.caixa.as_str()`. Pins
6671 // against a future silent detour that allocated a fresh `String`
6672 // (`self.caixa.clone()` in the body would type-check but silently
6673 // drop the borrow, and every downstream consumer that assumed
6674 // the returned slice outlives `&self` would break on a stale-
6675 // reference use-after-free — the [`crate::render::insert_first_seen`]
6676 // dedup key at [`SupervisorSpec::validate`], the
6677 // [`validate_no_self_supervision`] equality check against the
6678 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
6679 // borrow — each would silently misbehave if this accessor
6680 // produced a detached copy). Peer of the sibling
6681 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
6682 // M3 per-`:membros` axis and the
6683 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
6684 // first M2 slot scalar accessor.
6685 let c = ChildSpec {
6686 caixa: "worker".into(),
6687 versao: "^0.1".into(),
6688 restart: RestartPolicy::Permanent,
6689 };
6690 let name = c.nome();
6691 let caixa_slice = c.caixa.as_str();
6692 assert_eq!(
6693 name.as_ptr(),
6694 caixa_slice.as_ptr(),
6695 "ChildSpec::nome must borrow from the .caixa String's backing \
6696 storage — a fresh allocation here means the accessor no \
6697 longer names the substrate-primitive typed dispatch and \
6698 every downstream consumer would silently carry a detached \
6699 copy",
6700 );
6701 assert_eq!(
6702 name.len(),
6703 caixa_slice.len(),
6704 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
6705 as well as in address",
6706 );
6707 }
6708
6709 #[test]
6710 fn validate_gates_child_nome_through_lifted_accessor() {
6711 // Bilateral coherence pin: every `:children :caixa` that
6712 // [`SupervisorSpec::validate`] accepts is one
6713 // [`crate::render::require_valid_dns_1123_label`] accepts on the
6714 // accessor-projected value, and vice versa on the reject side.
6715 // This closes the "the validator reads through the accessor"
6716 // contract structurally — a future silent detour that made the
6717 // accessor return a different byte-string than the validator
6718 // gates against would surface here as a coverage mismatch, not
6719 // as an apply-time DNS-1123 rejection at
6720 // `metadata.name: Invalid value` far from the caixa.lisp source.
6721 // Peer of the M2 sibling
6722 // `validate_parses_prior_versao_through_lifted_accessor`
6723 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
6724 // `validate_membros` peer discipline.
6725 //
6726 // Accept-set sweep: five DNS-1123-label values the upstream gate
6727 // admits.
6728 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
6729 let s = SupervisorSpec {
6730 children: vec![ChildSpec {
6731 caixa: ok_name.into(),
6732 versao: "^0.1".into(),
6733 restart: RestartPolicy::Permanent,
6734 }],
6735 ..SupervisorSpec::default()
6736 };
6737 s.validate().unwrap_or_else(|e| {
6738 panic!(
6739 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
6740 (upstream DNS-1123 gate accepts it): got {e:?}",
6741 );
6742 });
6743 let c = ChildSpec {
6744 caixa: ok_name.into(),
6745 versao: "^0.1".into(),
6746 restart: RestartPolicy::Permanent,
6747 };
6748 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
6749 .unwrap_or_else(|()| {
6750 panic!(
6751 "require_valid_dns_1123_label must accept the accessor-projected \
6752 :children :caixa {ok_name:?}",
6753 );
6754 });
6755 }
6756 // Reject-set sweep: five DNS-1123-label-violating shapes the
6757 // upstream gate refuses (empty / uppercase / underscore / dot /
6758 // leading-hyphen). Every rejection at the validator must
6759 // correspond to a rejection when the accessor's projected value
6760 // is fed back through the shared gate.
6761 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
6762 let s = SupervisorSpec {
6763 children: vec![ChildSpec {
6764 caixa: bad_name.into(),
6765 versao: "^0.1".into(),
6766 restart: RestartPolicy::Permanent,
6767 }],
6768 ..SupervisorSpec::default()
6769 };
6770 let err = s.validate().unwrap_err();
6771 assert!(
6772 matches!(
6773 err,
6774 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
6775 ),
6776 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
6777 via the DNS-1123 gate: got {err:?}",
6778 );
6779 let c = ChildSpec {
6780 caixa: bad_name.into(),
6781 versao: "^0.1".into(),
6782 restart: RestartPolicy::Permanent,
6783 };
6784 assert!(
6785 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
6786 .is_err(),
6787 "require_valid_dns_1123_label must reject the accessor-projected \
6788 :children :caixa {bad_name:?}",
6789 );
6790 }
6791 }
6792
6793 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
6794 //
6795 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
6796 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
6797 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
6798 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
6799 // trio on the peer per-`:children` `String`-carry axis. The three pins
6800 // jointly brace the accessor against every future silent detour that
6801 // would desynchronize it from the raw `.versao` field access the
6802 // requirement gate + error carrier previously open-coded.
6803 //
6804 // Closes the last unlifted per-`:children` `String`-carry axis: the
6805 // pair (`nome`, `versao_requirement`) now jointly projects the
6806 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
6807 // consumer that fans on per-child identity + version pin reads,
6808 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
6809 // pair discipline verbatim.
6810 #[test]
6811 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
6812 // The canonical per-`:children` child-`:versao`-scalar pin:
6813 // [`ChildSpec::versao_requirement`] must return the `:children
6814 // :versao` field byte-for-byte across every Cargo-shaped semver
6815 // requirement value the upstream
6816 // [`crate::render::require_valid_versao_requirement`] gate admits.
6817 // Peer of the sibling
6818 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
6819 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
6820 // substrate-primitive accessor must byte-equal the raw field
6821 // access verbatim across every author-declared value" discipline
6822 // extended to the M2 supervisor-tree per-`:children` arm. Pins
6823 // against a future silent detour that re-canonicalized the
6824 // requirement (an accidental `.to_string()` via
6825 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
6826 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
6827 // silently drifted the error carrier's quoted requirement away
6828 // from the source `caixa.lisp`, an accidental whitespace trim on
6829 // `"^ 0.1"` that no consumer ever produced from the field-access
6830 // side, an accidental per-cluster lacre-projected concrete-version
6831 // rewrite that didn't land on the peer requirement-gate call).
6832 // Five values sweep the accept-set the shared
6833 // [`crate::render::require_valid_versao_requirement`] gate admits
6834 // (caret / tilde / exact / wildcard / bare-major).
6835 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
6836 let c = ChildSpec {
6837 caixa: "worker".into(),
6838 versao: req.into(),
6839 restart: RestartPolicy::Permanent,
6840 };
6841 assert_eq!(
6842 c.versao_requirement(),
6843 req,
6844 "ChildSpec::versao_requirement must return :children :versao \
6845 verbatim (got {:?}, expected {req:?})",
6846 c.versao_requirement(),
6847 );
6848 assert_eq!(
6849 c.versao_requirement(),
6850 c.versao.as_str(),
6851 "ChildSpec::versao_requirement must byte-equal the .versao \
6852 field access",
6853 );
6854 }
6855 }
6856
6857 #[test]
6858 fn child_spec_versao_requirement_borrows_from_versao_storage() {
6859 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
6860 // return a `&str` slice that borrows from the typed slot's own
6861 // [`String`] storage — same-address invariant with
6862 // `c.versao.as_str()`. Pins against a future silent detour that
6863 // allocated a fresh `String` (`self.versao.clone()` in the body
6864 // would type-check but silently drop the borrow, and every
6865 // downstream consumer that assumed the returned slice outlives
6866 // `&self` — the [`crate::render::require_valid_versao_requirement`]
6867 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
6868 // `.to_string()` carrier's byte-length assumption — would silently
6869 // misbehave if this accessor produced a detached copy). Peer of
6870 // the sibling `child_spec_nome_borrows_from_caixa_storage`
6871 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
6872 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
6873 // pin on the peer per-`:membros` `:versao` axis.
6874 let c = ChildSpec {
6875 caixa: "worker".into(),
6876 versao: "^0.1".into(),
6877 restart: RestartPolicy::Permanent,
6878 };
6879 let req = c.versao_requirement();
6880 let versao_slice = c.versao.as_str();
6881 assert_eq!(
6882 req.as_ptr(),
6883 versao_slice.as_ptr(),
6884 "ChildSpec::versao_requirement must borrow from the .versao \
6885 String's backing storage — a fresh allocation here means the \
6886 accessor no longer names the substrate-primitive typed \
6887 dispatch and every downstream consumer would silently carry \
6888 a detached copy",
6889 );
6890 assert_eq!(
6891 req.len(),
6892 versao_slice.len(),
6893 "ChildSpec::versao_requirement and .versao.as_str() must \
6894 byte-equal in length as well as in address",
6895 );
6896 }
6897
6898 #[test]
6899 fn validate_gates_child_versao_through_lifted_accessor() {
6900 // Bilateral coherence pin: every `:children :versao` that
6901 // [`SupervisorSpec::validate`] accepts is one
6902 // [`crate::render::require_valid_versao_requirement`] accepts on
6903 // the accessor-projected value, and vice versa on the reject side.
6904 // This closes the "the validator reads through the accessor"
6905 // contract structurally — a future silent detour that made the
6906 // accessor return a different byte-string than the validator gates
6907 // against would surface here as a coverage mismatch, not as a
6908 // resolver-time semver-parse rejection at lacre-closure time far
6909 // from the caixa.lisp source. Peer of the sibling
6910 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
6911 // the per-`:children :caixa` axis and the M2
6912 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
6913 // on the peer per-`:upgrade-from :from` axis.
6914 //
6915 // Accept-set sweep: five Cargo-shaped semver requirement values
6916 // the upstream gate admits (caret / tilde / exact / wildcard /
6917 // bare-major).
6918 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
6919 let s = SupervisorSpec {
6920 children: vec![ChildSpec {
6921 caixa: "worker".into(),
6922 versao: ok_req.into(),
6923 restart: RestartPolicy::Permanent,
6924 }],
6925 ..SupervisorSpec::default()
6926 };
6927 s.validate().unwrap_or_else(|e| {
6928 panic!(
6929 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
6930 (upstream versao-requirement gate accepts it): got {e:?}",
6931 );
6932 });
6933 let c = ChildSpec {
6934 caixa: "worker".into(),
6935 versao: ok_req.into(),
6936 restart: RestartPolicy::Permanent,
6937 };
6938 crate::render::require_valid_versao_requirement(
6939 c.versao_requirement(),
6940 || (),
6941 |_reason| (),
6942 )
6943 .unwrap_or_else(|()| {
6944 panic!(
6945 "require_valid_versao_requirement must accept the accessor-projected \
6946 :children :versao {ok_req:?}",
6947 );
6948 });
6949 }
6950 // Reject-set sweep: five requirement-violating shapes the upstream
6951 // gate refuses. The empty string closes the empty-first arm of the
6952 // shared [`crate::render::require_valid_versao_requirement`]
6953 // cascade; the four non-empty arms exercise distinct semver-parse
6954 // failure modes the M3 peer per-`:membros` reject-set already pins
6955 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
6956 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
6957 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
6958 // shared parser routing means the same reject-set must fail
6959 // identically at the M2 supervisor-tree per-`:children` accessor
6960 // arm here. Every rejection at the validator must correspond to a
6961 // rejection when the accessor's projected value is fed back
6962 // through the shared gate.
6963 //
6964 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
6965 // `"not-a-semver"` are intentionally *not* in the reject-set: the
6966 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
6967 // and the identifier-tail arm's grammar admits some non-canonical
6968 // shapes — matching what the M3 peer test suite already documents
6969 // as the shared parser's accept-set edges.)
6970 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
6971 let s = SupervisorSpec {
6972 children: vec![ChildSpec {
6973 caixa: "worker".into(),
6974 versao: bad_req.into(),
6975 restart: RestartPolicy::Permanent,
6976 }],
6977 ..SupervisorSpec::default()
6978 };
6979 let err = s.validate().unwrap_err();
6980 assert!(
6981 matches!(
6982 err,
6983 SupervisorError::EmptyChildVersion { .. }
6984 | SupervisorError::ChildVersaoInvalid { .. }
6985 ),
6986 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
6987 via the versao-requirement gate: got {err:?}",
6988 );
6989 let c = ChildSpec {
6990 caixa: "worker".into(),
6991 versao: bad_req.into(),
6992 restart: RestartPolicy::Permanent,
6993 };
6994 assert!(
6995 crate::render::require_valid_versao_requirement(
6996 c.versao_requirement(),
6997 || (),
6998 |_reason| (),
6999 )
7000 .is_err(),
7001 "require_valid_versao_requirement must reject the accessor-projected \
7002 :children :versao {bad_req:?}",
7003 );
7004 }
7005 }
7006
7007 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
7008 //
7009 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
7010 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
7011 // already project the `String`-carry `(caixa, versao)` fields; the
7012 // `Copy`-composite-enum `restart` field is the third and final axis).
7013 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
7014 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
7015 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
7016 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
7017 // strategy scalar accessor — same "one typed dispatch on the substrate
7018 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
7019 // extended onto the M2 supervisor-slot per-`:children` restart-decision
7020 // axis. The pin below covers the accessor's byte-equal projection
7021 // against the raw field access across every variant in the closed
7022 // accept-set (`Permanent`, `Transient`, `Temporary`).
7023
7024 #[test]
7025 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
7026 // The canonical per-`:children` restart-decision-policy-scalar
7027 // pin: [`ChildSpec::restart`] must return the `:children :restart`
7028 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
7029 // typed slot's own [`RestartPolicy`] storage across every variant
7030 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
7031 // Pins against a future silent detour that re-derived the policy
7032 // from a peer axis (an accidental fallback to
7033 // `if is_supervisor_child { Permanent } else { Temporary }` that
7034 // collapsed the child's kind axis into the restart discriminator),
7035 // a variant remap the operator authors on one consumer without the
7036 // other, or a stale-derive detour that substituted
7037 // [`RestartPolicy::default`] when the field held any explicit
7038 // variant (which would silently collapse the distinction between
7039 // "author explicitly declared `:restart Permanent`" and "author
7040 // omitted the slot and inherited the default" the future
7041 // per-cluster restart-decision override slot depends on).
7042 //
7043 // Peer of the sibling per-`:supervisor`
7044 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7045 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
7046 // axis and the M3
7047 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7048 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
7049 // — same "the substrate-primitive accessor must byte-equal the raw
7050 // field access verbatim across every author-declared value"
7051 // discipline extended onto the M2 supervisor-slot per-`:children`
7052 // restart-decision-policy axis, closing the last unlifted axis on
7053 // the per-`:children` [`ChildSpec`] type.
7054 for restart in [
7055 RestartPolicy::Permanent,
7056 RestartPolicy::Transient,
7057 RestartPolicy::Temporary,
7058 ] {
7059 let c = ChildSpec {
7060 caixa: "worker".into(),
7061 versao: "^0.1".into(),
7062 restart,
7063 };
7064 assert_eq!(
7065 c.restart(),
7066 restart,
7067 "ChildSpec::restart must return :children :restart \
7068 verbatim (got {:?}, expected {restart:?})",
7069 c.restart(),
7070 );
7071 assert_eq!(
7072 c.restart(),
7073 c.restart,
7074 "ChildSpec::restart accessor and .restart field access \
7075 must byte-equal — the accessor is the substrate-primitive \
7076 typed dispatch every downstream per-child restart-\
7077 decision consumer must route through",
7078 );
7079 }
7080 }
7081
7082 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
7083 //
7084 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
7085 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
7086 // distribution-strategy accessor discipline onto the M2 supervisor-slot
7087 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
7088 // scalar axis. The two pins below cover (1) the accessor's byte-equal
7089 // projection against the raw field access across every variant in the
7090 // closed accept-set, and (2) the two-consumer coherence between the
7091 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
7092 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
7093 // carrier's `estrategia:` field — peer of the sibling M3
7094 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7095 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
7096 // pair on the per-`:placement` distribution-strategy axis.
7097
7098 #[test]
7099 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
7100 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
7101 // pin: [`SupervisorSpec::estrategia`] must return the
7102 // `:supervisor :estrategia` field verbatim as a
7103 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
7104 // [`RestartStrategy`] storage across every variant in the closed
7105 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
7106 // `SimpleOneForOne`). Pins against a future silent detour that
7107 // re-derived the strategy from a peer axis (an accidental
7108 // fallback to `if children.is_empty() { SimpleOneForOne } else {
7109 // OneForOne }` collapse that read the children-count axis into
7110 // the strategy discriminator), a variant remap the operator
7111 // authors on one consumer without the other, or a stale-derive
7112 // detour that substituted [`RestartStrategy::default`] when the
7113 // field held any explicit variant (which would silently collapse
7114 // the distinction between "author explicitly declared
7115 // `:estrategia OneForOne`" and "author omitted the slot and
7116 // inherited the default" the future per-cluster strategy override
7117 // slot depends on). Peer of the sibling M3
7118 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7119 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
7120 // axis — same "the substrate-primitive accessor must byte-equal
7121 // the raw field access verbatim across every author-declared
7122 // value" discipline extended onto the M2 supervisor-slot
7123 // per-`:supervisor` sibling-restart-strategy axis.
7124 for &estrategia in RestartStrategy::ALL {
7125 // `SimpleOneForOne` requires `children.is_empty()`; the peer
7126 // three strategies require a non-empty static children list.
7127 // Build each shape coherently so the pin's fixture would
7128 // itself pass [`SupervisorSpec::validate`] once fed through
7129 // the sibling coherence pin below — the byte-equal projection
7130 // asserted here is a strictly weaker property (a `Copy` field
7131 // read) that does not depend on `validate` running, but
7132 // keeping the fixture validate-clean means a future extension
7133 // of the pin to exercise `validate` end-to-end does not have
7134 // to re-author the children shape.
7135 //
7136 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7137 // shape partition through the [`gen_platform::IsVariant`]
7138 // derive-generated
7139 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
7140 // than the raw `matches!(estrategia, RestartStrategy::
7141 // SimpleOneForOne)` open-coded pattern-match — same closed-
7142 // set-typed-enum arm-discriminator dispatch discipline the
7143 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
7144 // convergence (915a934) extended onto its two paired positive
7145 // / negated `matches!` sites and the peer
7146 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7147 // predicate convergence (766ec63) extended onto the M3 mesh-
7148 // slot per-`:placement` distribution-strategy discriminator
7149 // axis. See the sibling `round_trip_all_strategies` and the
7150 // peer `manifest::tests::
7151 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7152 // fixture for the two peer sites the same lift closes on.
7153 let children = if estrategia.is_simple_one_for_one() {
7154 Vec::new()
7155 } else {
7156 vec![ChildSpec {
7157 caixa: "worker".into(),
7158 versao: "^0.1".into(),
7159 restart: RestartPolicy::Permanent,
7160 }]
7161 };
7162 let s = SupervisorSpec {
7163 estrategia,
7164 children,
7165 ..SupervisorSpec::default()
7166 };
7167 assert_eq!(
7168 s.estrategia(),
7169 estrategia,
7170 "SupervisorSpec::estrategia must return :supervisor :estrategia \
7171 verbatim (got {:?}, expected {estrategia:?})",
7172 s.estrategia(),
7173 );
7174 assert_eq!(
7175 s.estrategia(),
7176 s.estrategia,
7177 "SupervisorSpec::estrategia accessor and .estrategia field \
7178 access must byte-equal — the accessor is the substrate-\
7179 primitive typed dispatch every downstream sibling-restart-\
7180 strategy consumer must route through",
7181 );
7182 }
7183 }
7184
7185 #[test]
7186 fn validate_reads_through_lifted_estrategia_accessor() {
7187 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
7188 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
7189 // dispatch (which reads through [`SupervisorSpec::estrategia`]
7190 // to fan across the strategy-arm shape-gate cascades) and the
7191 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
7192 // error carrier's `estrategia:` field (which reads through
7193 // [`SupervisorSpec::estrategia`] to name the strategy the empty
7194 // `:children` list was declared against) must both key off the
7195 // lifted accessor, so any future rebrand on the typed slot's
7196 // reader shape lands at exactly one place. Pins the two-site
7197 // coherence by exercising the `NoChildren` error surface end-to-
7198 // end across every non-`SimpleOneForOne` variant and asserting
7199 // the surfaced `estrategia:` field byte-equals the accessor's
7200 // return. Peer of the sibling M3
7201 // `validate_placement_reads_through_lifted_estrategia_accessor`
7202 // (921fe1b) three-consumer coherence pin on the per-`:placement`
7203 // distribution-strategy axis.
7204 for estrategia in [
7205 RestartStrategy::OneForOne,
7206 RestartStrategy::OneForAll,
7207 RestartStrategy::RestForOne,
7208 ] {
7209 let s = SupervisorSpec {
7210 estrategia,
7211 children: Vec::new(),
7212 ..SupervisorSpec::default()
7213 };
7214 let err = s.validate().unwrap_err();
7215 match err {
7216 SupervisorError::NoChildren { estrategia: e } => {
7217 assert_eq!(
7218 e,
7219 s.estrategia(),
7220 "NoChildren.estrategia must byte-equal \
7221 SupervisorSpec::estrategia() — the empty-`:children` \
7222 refusal reads through the lifted accessor",
7223 );
7224 assert_eq!(
7225 e, estrategia,
7226 "NoChildren.estrategia must carry the author-declared \
7227 :supervisor :estrategia variant verbatim (got {e:?}, \
7228 expected {estrategia:?})",
7229 );
7230 }
7231 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
7232 }
7233 }
7234 }
7235
7236 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
7237 //
7238 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
7239 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
7240 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
7241 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
7242 // The two pins below cover (1) the accessor's byte-equal projection
7243 // against the raw field access across every representative value in
7244 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
7245 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
7246 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
7247 // zero-floor / cap composition — the validate gate and the accessor
7248 // must route through the same substrate-primitive typed dispatch, so
7249 // any future silent detour that had the accessor perform a
7250 // bounds-collapsing clamp would fail here at caixa-core build time.
7251 // Peer of the sibling M3
7252 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7253 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
7254
7255 #[test]
7256 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
7257 // The canonical per-`:supervisor` restart-budget-count scalar pin:
7258 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
7259 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
7260 // typed slot's own `u32` storage, byte-equal to the raw field
7261 // access across every representative value in the accept-set —
7262 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
7263 // accept-set the surrounding [`SupervisorSpec::validate`] gate
7264 // carves out on the sibling `ZeroMaxRestarts` refusal),
7265 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
7266 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
7267 // (a past-the-guard sentinel that pins the accessor doesn't
7268 // perform a silent bounds-collapse into `1` on the zero arm —
7269 // validate rejects zero but the accessor must ship the raw slot
7270 // verbatim so a validate-time gate regression surfaces at the
7271 // emit boundary rather than being silently absorbed), `u32::MAX`
7272 // (a past-the-guard sentinel that pins the accessor doesn't
7273 // perform a silent bounds-collapse through
7274 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
7275 //
7276 // Peer of the sibling M3
7277 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7278 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
7279 // required-scalar axis — same "the substrate-primitive accessor
7280 // must byte-equal the raw field access verbatim across every
7281 // value in the `u32` accept-set" discipline extended onto the M2
7282 // supervisor-slot per-`:supervisor` restart-budget-count axis.
7283 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
7284 let s = SupervisorSpec {
7285 max_restarts,
7286 ..SupervisorSpec::default()
7287 };
7288 assert_eq!(
7289 s.max_restarts(),
7290 max_restarts,
7291 "SupervisorSpec::max_restarts must return :supervisor \
7292 :max-restarts verbatim (got {}, expected {max_restarts})",
7293 s.max_restarts(),
7294 );
7295 assert_eq!(
7296 s.max_restarts(),
7297 s.max_restarts,
7298 "SupervisorSpec::max_restarts accessor and .max_restarts \
7299 field access must byte-equal — the accessor is the \
7300 substrate-primitive typed dispatch every downstream \
7301 restart-budget-count consumer must route through",
7302 );
7303 }
7304 }
7305
7306 #[test]
7307 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
7308 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
7309 // zero-floor + upper-cap bracket must key off
7310 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
7311 // field access. Structurally: a `SupervisorSpec { max_restarts:
7312 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
7313 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7314 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
7315 // (with the offending count carried verbatim from the accessor
7316 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
7317 // lower boundary of the accept-set) plus a `SupervisorSpec {
7318 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
7319 // boundary) must pass validate. The four together jointly pin the
7320 // accessor + validate-gate composition: any future silent detour
7321 // that had the accessor return a fresh `1` on the zero arm (a
7322 // `.max_restarts().max(1)` collapse) would silently absorb the
7323 // `ZeroMaxRestarts` refusal at the accessor boundary and the
7324 // validate gate would accept a struct-literal `SupervisorSpec {
7325 // max_restarts: 0, .. }` — the composition pin catches that at
7326 // caixa-core build time.
7327 //
7328 // Peer of the sibling M3
7329 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
7330 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
7331 // composition axis — same "the validate / shape-gate predicate
7332 // must route through the substrate-primitive typed dispatch"
7333 // discipline extended onto the peer M2 supervisor-slot
7334 // required-`u32` composition axis.
7335 let child = ChildSpec {
7336 caixa: "worker".into(),
7337 versao: "^0.1".into(),
7338 restart: RestartPolicy::Permanent,
7339 };
7340 // Zero-floor arm.
7341 let s = SupervisorSpec {
7342 max_restarts: 0,
7343 children: vec![child.clone()],
7344 ..SupervisorSpec::default()
7345 };
7346 assert_eq!(
7347 s.validate().unwrap_err(),
7348 SupervisorError::ZeroMaxRestarts,
7349 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
7350 — the accessor and the validate gate must route through the \
7351 same substrate-primitive typed dispatch on the zero-floor arm",
7352 );
7353 // Cap arm — the surfaced `max_restarts:` field must byte-equal
7354 // the accessor's return so a future rebrand on the accessor
7355 // lands in the diagnostic without a coordinated rewrite.
7356 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
7357 let s = SupervisorSpec {
7358 max_restarts: over_cap,
7359 children: vec![child.clone()],
7360 ..SupervisorSpec::default()
7361 };
7362 match s.validate().unwrap_err() {
7363 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
7364 assert_eq!(
7365 max_restarts,
7366 s.max_restarts(),
7367 "MaxRestartsExceedsCap.max_restarts must byte-equal \
7368 SupervisorSpec::max_restarts() — the cap-arm refusal \
7369 reads through the lifted accessor",
7370 );
7371 assert_eq!(
7372 max_restarts, over_cap,
7373 "MaxRestartsExceedsCap.max_restarts must carry the \
7374 author-declared :supervisor :max-restarts value \
7375 verbatim (got {max_restarts}, expected {over_cap})",
7376 );
7377 }
7378 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
7379 }
7380 // Lower + upper accept-set boundaries.
7381 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
7382 let s = SupervisorSpec {
7383 max_restarts,
7384 children: vec![child.clone()],
7385 ..SupervisorSpec::default()
7386 };
7387 assert!(
7388 s.validate().is_ok(),
7389 "validate must accept max_restarts == {max_restarts} \
7390 (an accept-set boundary of \
7391 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
7392 );
7393 }
7394 }
7395
7396 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
7397 //
7398 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
7399 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
7400 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
7401 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
7402 // supervisor-slot per-`:supervisor` restart-intensity-denominator
7403 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
7404 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
7405 // per-`:supervisor` scalar-value axis. The three pins below cover
7406 // (1) the accessor's byte-equal projection against the raw field
7407 // access across every representative value in the `Option<Duration>`
7408 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
7409 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
7410 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
7411 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
7412 // `if let Some(w) = self.restart_window() { … }` bracket-arm
7413 // composition — the validate gate and the accessor must route through
7414 // the same substrate-primitive typed dispatch, so any future silent
7415 // detour that had the accessor perform a bounds-collapsing clamp
7416 // would fail here at caixa-core build time, and (3) the accessor's
7417 // by-copy idempotence pin — the returned `Option<Duration>` must
7418 // outlive `&self` and two successive calls must return byte-equal
7419 // values. Peer of the sibling M2
7420 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7421 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
7422 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7423 // (7073d0f) pin on the per-`:politicas :timeout` axis.
7424
7425 #[test]
7426 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
7427 // The canonical per-`:supervisor` restart-intensity-denominator
7428 // scalar pin: [`SupervisorSpec::restart_window`] must return the
7429 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
7430 // `Option<Duration>`, `Copy`-projected from the typed slot's own
7431 // `Option<Duration>` storage, byte-equal to the raw field access
7432 // across every representative value in the accept-set — `None`
7433 // (the "never reset — every restart across the supervisor's
7434 // lifetime counts against the sibling `:max-restarts` budget"
7435 // sentinel the field's own docstring names and the peer
7436 // `validate_accepts_none_restart_window` pin locks in on the
7437 // [`SupervisorSpec::validate`] entry-side),
7438 // `Some(Duration::from_millis(1))` (the structural minimum a
7439 // validated `:restart-window` may carry, the integer-millisecond
7440 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
7441 // everything sub-ms; `Duration::ZERO` is separately rejected by
7442 // [`SupervisorError::RestartWindowZero`]),
7443 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
7444 // surrounding [`SupervisorSpec::validate`] gate carves out on the
7445 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
7446 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
7447 // accessor doesn't perform a silent bounds-collapse into `None` on
7448 // the zero-Duration arm — validate rejects zero but the accessor
7449 // must ship the raw slot verbatim so a validate-time gate
7450 // regression surfaces at the emit boundary rather than being
7451 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
7452 // sentinel that pins the accessor doesn't perform a silent
7453 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
7454 // return path).
7455 //
7456 // Peer of the sibling M2
7457 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
7458 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
7459 // sibling M3
7460 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
7461 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
7462 // substrate-primitive accessor must byte-equal the raw field
7463 // access verbatim across every value in the `Option<Duration>`
7464 // accept-set" discipline extended onto the M2 supervisor-slot
7465 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
7466 // silent detour that re-derived the restart-window from a peer
7467 // axis (an accidental `.max_restarts.into()` collapse that read
7468 // the restart-budget-count as a duration — the two axes serve
7469 // different halves of the `MaxIntensity / Period` restart-
7470 // intensity ratio, and confusing them silently inverts the
7471 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
7472 // "zero means never reset" collapse (the canonical
7473 // `Option<Duration>` → `Duration` collapse footgun the
7474 // [`SupervisorError::RestartWindowZero`] validate arm guards on
7475 // the peer zero-floor axis; a zero period either trips on the
7476 // first failure or never trips depending on operator
7477 // interpretation, neither of which is the author's "never reset"
7478 // intent that `None` expresses structurally), or a per-arm
7479 // variant swap that landed on one consumer without the other.
7480 for restart_window in [
7481 None,
7482 Some(Duration::from_millis(1)),
7483 Some(SUPERVISOR_RESTART_WINDOW_MAX),
7484 Some(Duration::ZERO),
7485 Some(Duration::MAX),
7486 ] {
7487 let s = SupervisorSpec {
7488 restart_window,
7489 ..SupervisorSpec::default()
7490 };
7491 assert_eq!(
7492 s.restart_window(),
7493 restart_window,
7494 "SupervisorSpec::restart_window must return :supervisor \
7495 :restart-window verbatim (got {:?}, expected {restart_window:?})",
7496 s.restart_window(),
7497 );
7498 assert_eq!(
7499 s.restart_window(),
7500 s.restart_window,
7501 "SupervisorSpec::restart_window accessor and \
7502 .restart_window field access must byte-equal — the \
7503 accessor is the substrate-primitive typed dispatch every \
7504 downstream restart-intensity-denominator consumer must \
7505 route through",
7506 );
7507 }
7508 }
7509
7510 #[test]
7511 fn validate_restart_window_bracket_arm_routes_through_accessor() {
7512 // Composition pin: [`SupervisorSpec::validate`]'s
7513 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
7514 // zero-floor + integer-millisecond canonical-form + upper-cap
7515 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
7516 // the raw `.restart_window` field access. Structurally: a
7517 // `SupervisorSpec { restart_window: None, .. }` must pass the
7518 // arm gate structurally (the `if let Some(_)` shape returns
7519 // early on the `None` arm — the accessor and the validate gate
7520 // must agree on `None → skip the bracket cascade` so an authored
7521 // `:restart-window ()` structurally routes through the "never
7522 // reset" sentinel path), a `SupervisorSpec { restart_window:
7523 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
7524 // refusal exactly, a `SupervisorSpec { restart_window:
7525 // Some(Duration::from_micros(1500)), .. }` must surface the
7526 // `RestartWindowNotCanonical` refusal exactly (with the offending
7527 // duration carried verbatim from the accessor return), a
7528 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
7529 // + Duration::from_millis(1)), .. }` must surface the
7530 // `RestartWindowExceedsCap` refusal exactly (with the offending
7531 // duration carried verbatim from the accessor return), and a
7532 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
7533 // .. }` (the lower boundary of the accept-set) plus a
7534 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7535 // .. }` (the upper boundary) must pass validate. The six together
7536 // jointly pin the accessor + validate-gate composition: any future
7537 // silent detour that had the accessor return a fresh `None` on any
7538 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
7539 // collapse) would silently absorb the `RestartWindowZero` refusal
7540 // at the accessor boundary and the validate gate would accept a
7541 // struct-literal `SupervisorSpec { restart_window:
7542 // Some(Duration::ZERO), .. }` — the composition pin catches that
7543 // at caixa-core build time.
7544 //
7545 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
7546 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
7547 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
7548 // accessor-composition pin on the per-`:politicas :timeout` axis —
7549 // same "the validate / shape-gate predicate must route through
7550 // the substrate-primitive typed dispatch" discipline extended
7551 // onto the peer M2 supervisor-slot optional-`Duration` axis.
7552 let child = ChildSpec {
7553 caixa: "worker".into(),
7554 versao: "^0.1".into(),
7555 restart: RestartPolicy::Permanent,
7556 };
7557 // None arm — must not surface any :restart-window-shaped refusal;
7558 // the `if let Some(_)` bracket returns early on `None` structurally.
7559 let s = SupervisorSpec {
7560 restart_window: None,
7561 children: vec![child.clone()],
7562 ..SupervisorSpec::default()
7563 };
7564 assert!(
7565 s.validate().is_ok(),
7566 "validate must accept restart_window: None (the never-reset \
7567 sentinel) — the `if let Some(_)` bracket returns early on \
7568 the None arm and the accessor must agree",
7569 );
7570 // Zero-floor arm.
7571 let s = SupervisorSpec {
7572 restart_window: Some(Duration::ZERO),
7573 children: vec![child.clone()],
7574 ..SupervisorSpec::default()
7575 };
7576 assert_eq!(
7577 s.validate().unwrap_err(),
7578 SupervisorError::RestartWindowZero,
7579 "validate must reject restart_window == Some(Duration::ZERO) \
7580 with RestartWindowZero — the accessor and the validate gate \
7581 must route through the same substrate-primitive typed \
7582 dispatch on the zero-floor arm",
7583 );
7584 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
7585 // byte-equal the accessor's return so a future rebrand on the
7586 // accessor lands in the diagnostic without a coordinated rewrite.
7587 let sub_ms = Duration::from_micros(1500);
7588 let s = SupervisorSpec {
7589 restart_window: Some(sub_ms),
7590 children: vec![child.clone()],
7591 ..SupervisorSpec::default()
7592 };
7593 match s.validate().unwrap_err() {
7594 SupervisorError::RestartWindowNotCanonical { window } => {
7595 assert_eq!(
7596 Some(window),
7597 s.restart_window(),
7598 "RestartWindowNotCanonical.window must byte-equal \
7599 SupervisorSpec::restart_window().unwrap() — the \
7600 non-canonical-arm refusal reads through the lifted \
7601 accessor",
7602 );
7603 assert_eq!(
7604 window, sub_ms,
7605 "RestartWindowNotCanonical.window must carry the \
7606 author-declared :supervisor :restart-window value \
7607 verbatim (got {window:?}, expected {sub_ms:?})",
7608 );
7609 }
7610 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
7611 }
7612 // Cap arm — the surfaced `window:` field must byte-equal the
7613 // accessor's return.
7614 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
7615 let s = SupervisorSpec {
7616 restart_window: Some(over_cap),
7617 children: vec![child.clone()],
7618 ..SupervisorSpec::default()
7619 };
7620 match s.validate().unwrap_err() {
7621 SupervisorError::RestartWindowExceedsCap { window } => {
7622 assert_eq!(
7623 Some(window),
7624 s.restart_window(),
7625 "RestartWindowExceedsCap.window must byte-equal \
7626 SupervisorSpec::restart_window().unwrap() — the \
7627 cap-arm refusal reads through the lifted accessor",
7628 );
7629 assert_eq!(
7630 window, over_cap,
7631 "RestartWindowExceedsCap.window must carry the \
7632 author-declared :supervisor :restart-window value \
7633 verbatim (got {window:?}, expected {over_cap:?})",
7634 );
7635 }
7636 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
7637 }
7638 // Lower + upper accept-set boundaries.
7639 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
7640 let s = SupervisorSpec {
7641 restart_window: Some(restart_window),
7642 children: vec![child.clone()],
7643 ..SupervisorSpec::default()
7644 };
7645 assert!(
7646 s.validate().is_ok(),
7647 "validate must accept restart_window == Some({restart_window:?}) \
7648 (an accept-set boundary of \
7649 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
7650 );
7651 }
7652 }
7653
7654 #[test]
7655 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
7656 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
7657 // `Option<Duration>` by copy — `Duration` is `Copy` (so
7658 // `Option<Duration>` is `Copy`) and the accessor must return by
7659 // value, not by reference. Peer of the sibling M2
7660 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
7661 // per-`:limits :wall-clock` axis and the sibling M3
7662 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
7663 // per-`:politicas :timeout` axis, extended onto the peer M2
7664 // supervisor-slot `Option<Duration>` copy-invariant shape — the
7665 // accessor's returned `Option<Duration>` must outlive `&self`
7666 // (multiple calls must return equal values from a dropped-`&self`
7667 // copy, since the returned Option carries no borrow), and calling
7668 // the accessor twice on the same SupervisorSpec must yield the
7669 // same `Option<Duration>` verbatim (idempotent, no side effects
7670 // on `&self`).
7671 //
7672 // Pins against a future silent detour that returned
7673 // `Option<&Duration>` (which would type-check but silently break
7674 // every downstream caller — the future wasm-operator's
7675 // per-supervisor restart-intensity counter consumes `Duration` by
7676 // value and `&Duration` would fold to a detached copy at the call
7677 // site), an accidental `Option::as_ref()` projection
7678 // (`self.restart_window.as_ref()` would also type-check but
7679 // return `Option<&Duration>`), or a one-arm-only accessor that
7680 // reads `Some(*w)` in the Some arm but reads a fresh
7681 // `Default::default()` (which would collapse to `Duration::ZERO`,
7682 // not `None`) in the None arm — a footgun the
7683 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
7684 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
7685 // requires `Period > 0` and `None` structurally expresses "never
7686 // reset" instead.
7687 for restart_window in [
7688 None,
7689 Some(Duration::from_millis(1)),
7690 Some(Duration::from_secs(60)),
7691 Some(SUPERVISOR_RESTART_WINDOW_MAX),
7692 ] {
7693 let s = SupervisorSpec {
7694 restart_window,
7695 ..SupervisorSpec::default()
7696 };
7697 let first = s.restart_window();
7698 let second = s.restart_window();
7699 assert_eq!(
7700 first, second,
7701 "SupervisorSpec::restart_window must be idempotent — two \
7702 successive calls on the same &self must return the \
7703 same Option<Duration>",
7704 );
7705 assert_eq!(
7706 first, restart_window,
7707 "SupervisorSpec::restart_window must return :supervisor \
7708 :restart-window verbatim by copy — got {first:?}, \
7709 expected {restart_window:?}",
7710 );
7711 }
7712 }
7713
7714 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
7715 //
7716 // The [`SupervisorSpec::children`] accessor lift is the seed of the
7717 // slice-return (`&[T]`) accessor discipline on the substrate — the four
7718 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
7719 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
7720 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
7721 // access at the time of this seed, and inherit this pin family's
7722 // discipline as future compounding runs migrate their consumers. The
7723 // three pins below cover (1) the accessor's byte-equal projection
7724 // against the raw field access across the empty / singleton / cohort
7725 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
7726 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
7727 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
7728 // consumer routing through the accessor on both arms, and (3) the
7729 // per-child validate loop's traversal reading the same slice-view the
7730 // accessor projects. Peer of the sibling M2
7731 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
7732 // two-consumer coherence pin on the per-`:supervisor`
7733 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
7734 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
7735
7736 #[test]
7737 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
7738 // The canonical per-`:supervisor` static-child-list scalar-shape
7739 // pin: [`SupervisorSpec::children`] must return the `:supervisor
7740 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
7741 // slice-view over the same backing buffer the raw
7742 // `self.children.as_slice()` field access borrows from, byte-
7743 // equal across every representative fixture in the accept-set —
7744 // the empty slice (the `SimpleOneForOne`-arm sentinel),
7745 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
7746 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
7747 // with the peer three restart-policy variants in play).
7748 //
7749 // Pins against a future silent detour that returned
7750 // `&Vec<ChildSpec>` (which would type-check but leak the
7751 // storage-side `Vec`'s grow/push/reserve surface no consumer of
7752 // the typed view reaches for), a fresh-allocated
7753 // `Vec<ChildSpec>` copy (which would type-check via a coercion
7754 // but silently break every downstream caller that relied on the
7755 // slice sharing the backing buffer's identity), or an
7756 // out-of-order or length-drifted projection (which would silently
7757 // split the per-child validate loop's traversal input from the
7758 // paired partition-dispatch `.is_empty()` probe's input).
7759 //
7760 // Peer of the sibling
7761 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7762 // (eafb619) `Copy`-composite-enum byte-equal pin on the
7763 // per-`:supervisor` sibling-restart-strategy axis, extended onto
7764 // the per-`:supervisor` static-child-list `Vec`-carry axis.
7765 let fixtures: Vec<Vec<ChildSpec>> = vec![
7766 Vec::new(),
7767 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
7768 vec![
7769 child("worker", "^0.1", RestartPolicy::Permanent),
7770 child("cache-server", "^0.1", RestartPolicy::Transient),
7771 ],
7772 vec![
7773 child("worker", "^0.1", RestartPolicy::Permanent),
7774 child("cache-server", "^0.1", RestartPolicy::Transient),
7775 child("scratch-job", "^0.1", RestartPolicy::Temporary),
7776 ],
7777 ];
7778 for children in fixtures {
7779 let s = SupervisorSpec {
7780 children: children.clone(),
7781 ..SupervisorSpec::default()
7782 };
7783 assert_eq!(
7784 s.children(),
7785 children.as_slice(),
7786 "SupervisorSpec::children must return :supervisor \
7787 :children verbatim (got {:?}, expected {:?})",
7788 s.children(),
7789 children.as_slice(),
7790 );
7791 assert_eq!(
7792 s.children(),
7793 s.children.as_slice(),
7794 "SupervisorSpec::children accessor and \
7795 .children.as_slice() field access must byte-equal — \
7796 the accessor is the substrate-primitive typed \
7797 dispatch every downstream static-child-list consumer \
7798 must route through",
7799 );
7800 assert_eq!(
7801 s.children().len(),
7802 s.children.len(),
7803 "SupervisorSpec::children().len() must byte-equal \
7804 self.children.len() — a length-drift would silently \
7805 split the paired partition-dispatch `.is_empty()` \
7806 probe input from the per-child validate loop's \
7807 traversal input",
7808 );
7809 }
7810 }
7811
7812 #[test]
7813 fn validate_reads_through_lifted_children_accessor() {
7814 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
7815 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
7816 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
7817 // when the accessor projects a non-empty slice under a
7818 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
7819 // `self.children().is_empty()` refusal probe (which must trip
7820 // [`SupervisorError::NoChildren`] when the accessor projects the
7821 // empty slice under any peer estrategia), and the per-child
7822 // validate loop's `for child in self.children()` traversal
7823 // (which must reach every entry in the same order the accessor
7824 // projects) must all key off the lifted accessor, so any future
7825 // rebrand on the typed slot's reader shape lands at exactly one
7826 // place. Pins the three-site coherence by exercising each
7827 // production consumer end-to-end: (1) the
7828 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
7829 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
7830 // refusal under the empty slice + non-`SimpleOneForOne`
7831 // estrategia across every peer variant, and (3) the per-child
7832 // duplicate-detection surface fires on the second entry of a
7833 // two-child cohort that shares a `:caixa` name (which requires
7834 // the loop to reach both entries — a first-entry-only projection
7835 // would silently pass since the dedup HashSet has room for the
7836 // first insert).
7837 //
7838 // Peer of the sibling M2
7839 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
7840 // two-consumer coherence pin on the per-`:supervisor`
7841 // sibling-restart-strategy axis, extended onto the
7842 // per-`:supervisor` static-child-list `Vec`-carry axis.
7843
7844 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
7845 // `SimpleOneForOne` estrategia must trip
7846 // `SimpleOneForOneWithStaticChildren`.
7847 let s = SupervisorSpec {
7848 estrategia: RestartStrategy::SimpleOneForOne,
7849 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
7850 ..SupervisorSpec::default()
7851 };
7852 assert_eq!(
7853 s.validate().unwrap_err(),
7854 SupervisorError::SimpleOneForOneWithStaticChildren,
7855 "SimpleOneForOne + non-empty children must trip \
7856 SimpleOneForOneWithStaticChildren — the accessor projects \
7857 a non-empty slice, and the SimpleOneForOne-arm refusal \
7858 probe reads through the lifted accessor",
7859 );
7860 assert!(
7861 !s.children().is_empty(),
7862 "the SimpleOneForOne-arm refusal input must be a non-empty \
7863 slice per the accessor's projection",
7864 );
7865
7866 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
7867 // under any peer estrategia must trip `NoChildren`.
7868 for estrategia in [
7869 RestartStrategy::OneForOne,
7870 RestartStrategy::OneForAll,
7871 RestartStrategy::RestForOne,
7872 ] {
7873 let s = SupervisorSpec {
7874 estrategia,
7875 children: Vec::new(),
7876 ..SupervisorSpec::default()
7877 };
7878 match s.validate().unwrap_err() {
7879 SupervisorError::NoChildren { estrategia: e } => {
7880 assert_eq!(
7881 e, estrategia,
7882 "NoChildren.estrategia must carry the author-\
7883 declared :supervisor :estrategia variant \
7884 verbatim (got {e:?}, expected {estrategia:?})",
7885 );
7886 }
7887 other => panic!(
7888 "expected NoChildren, got {other:?} for \
7889 estrategia={estrategia:?}"
7890 ),
7891 }
7892 assert!(
7893 s.children().is_empty(),
7894 "the non-SimpleOneForOne-arm refusal input must be the \
7895 empty slice per the accessor's projection",
7896 );
7897 }
7898
7899 // (3) Per-child validate loop: a two-child cohort that shares a
7900 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
7901 // reach both entries through the accessor.
7902 let s = SupervisorSpec {
7903 estrategia: RestartStrategy::OneForOne,
7904 children: vec![
7905 child("worker", "^0.1", RestartPolicy::Permanent),
7906 child("worker", "^0.2", RestartPolicy::Transient),
7907 ],
7908 ..SupervisorSpec::default()
7909 };
7910 match s.validate().unwrap_err() {
7911 SupervisorError::DuplicateChildCaixa { caixa } => {
7912 assert_eq!(
7913 caixa, "worker",
7914 "DuplicateChildCaixa.caixa must carry the shared \
7915 child `:caixa` name verbatim",
7916 );
7917 }
7918 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
7919 }
7920 assert_eq!(
7921 s.children().len(),
7922 2,
7923 "the per-child validate loop's traversal input must be a \
7924 two-element slice per the accessor's projection",
7925 );
7926 }
7927
7928 // Shared helper for the M2 per-`:children` per-slot-gate ≡
7929 // `validate` equivalence pins: builds an `OneForOne`-estrategia
7930 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
7931 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
7932 // bracket all pass cleanly so the sole failing surface is the
7933 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
7934 // pins the two-altitude equivalence on the paired probe.
7935 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
7936 let s = SupervisorSpec {
7937 estrategia: RestartStrategy::OneForOne,
7938 children,
7939 ..SupervisorSpec::default()
7940 };
7941 let via_gate = s.validate_children().unwrap_err();
7942 let via_validate = s.validate().unwrap_err();
7943 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
7944 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
7945 assert_eq!(
7946 via_gate, via_validate,
7947 "per-slot gate ≡ validate() must discriminate the same \
7948 refusal shape",
7949 );
7950 }
7951
7952 #[test]
7953 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
7954 // Fail-before-pass-after equivalence pin on the M2
7955 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
7956 // convergence — sibling of the M3 mesh-slot
7957 // `validate_membros_*` / `validate_contratos_*` /
7958 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
7959 // peer per-entry axes. Sweeps four of the five refusal shapes
7960 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
7961 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
7962 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
7963 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
7964 // duplicate-`:caixa` fan-out. Companion pin
7965 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
7966 // covers `ChildVersaoInvalid` (whose parser-owned reason string
7967 // needs pattern-matching, not equality) and the clean-pass
7968 // canonical fixture; together the two pins guarantee the
7969 // per-slot gate and `validate` discriminate the same set on
7970 // every per-child-covered input.
7971 assert_validate_children_matches_gate(
7972 vec![child("", "^0.1", RestartPolicy::Permanent)],
7973 &SupervisorError::EmptyChildName,
7974 );
7975 assert_validate_children_matches_gate(
7976 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
7977 &SupervisorError::ChildCaixaInvalid {
7978 caixa: "Worker".into(),
7979 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
7980 },
7981 );
7982 assert_validate_children_matches_gate(
7983 vec![child("worker", "", RestartPolicy::Permanent)],
7984 &SupervisorError::EmptyChildVersion {
7985 caixa: "worker".into(),
7986 },
7987 );
7988 assert_validate_children_matches_gate(
7989 vec![
7990 child("worker", "^0.1", RestartPolicy::Permanent),
7991 child("worker", "^0.2", RestartPolicy::Transient),
7992 ],
7993 &SupervisorError::DuplicateChildCaixa {
7994 caixa: "worker".into(),
7995 },
7996 );
7997 }
7998
7999 #[test]
8000 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
8001 // Second half of the two-altitude equivalence pin — covers the
8002 // one refusal shape whose reason string is parser-owned
8003 // (`ChildVersaoInvalid`, whose reason comes from the shared
8004 // [`crate::version::parse_requirement`] impl and may drift) and
8005 // the clean-pass canonical fixture. Sibling pin
8006 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
8007 // covers the four equality-comparable refusal shapes.
8008 let s_bad_versao = SupervisorSpec {
8009 estrategia: RestartStrategy::OneForOne,
8010 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
8011 ..SupervisorSpec::default()
8012 };
8013 let via_gate = s_bad_versao.validate_children().unwrap_err();
8014 let via_validate = s_bad_versao.validate().unwrap_err();
8015 match (&via_gate, &via_validate) {
8016 (
8017 SupervisorError::ChildVersaoInvalid {
8018 caixa: cg,
8019 versao: vg,
8020 ..
8021 },
8022 SupervisorError::ChildVersaoInvalid {
8023 caixa: cv,
8024 versao: vv,
8025 ..
8026 },
8027 ) => {
8028 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
8029 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
8030 assert_eq!(cv, "worker", "validate() :caixa carrier");
8031 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
8032 }
8033 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
8034 }
8035 assert_eq!(
8036 via_gate, via_validate,
8037 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
8038 );
8039
8040 let s_ok = SupervisorSpec {
8041 estrategia: RestartStrategy::OneForOne,
8042 children: vec![
8043 child("worker-a", "^0.1", RestartPolicy::Permanent),
8044 child("worker-b", "~0.2.3", RestartPolicy::Transient),
8045 child("collector", "*", RestartPolicy::Temporary),
8046 ],
8047 ..SupervisorSpec::default()
8048 };
8049 s_ok.validate_children()
8050 .expect("per-slot gate must accept the clean-pass fixture");
8051 s_ok.validate()
8052 .expect("validate() must accept the clean-pass fixture");
8053 }
8054
8055 #[test]
8056 fn validate_children_is_self_contained_on_children_slot() {
8057 // Self-containment pin: [`SupervisorSpec::validate_children`]
8058 // resolves the per-child cascade against `&self` alone, without
8059 // depending on the peer `:estrategia`/`:max-restarts`/
8060 // `:restart-window` gates having run first — same posture the M3
8061 // peer per-slot gates carry (`validate_membros`,
8062 // `validate_contratos`, `validate_entrada`, `validate_placement`,
8063 // routing through their own oracles rather than borrowing state
8064 // threaded down from `validate`). A future consumer that reaches
8065 // the per-slot gate directly on a spec whose peer slots would
8066 // fail `validate` still surfaces the per-child refusal, not the
8067 // peer refusal.
8068 //
8069 // Construct a spec whose `:max-restarts` is `0` (which would
8070 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
8071 // the partition-dispatch) and whose `:children` carries a
8072 // `DuplicateChildCaixa` shape: the per-slot gate called directly
8073 // must surface `DuplicateChildCaixa`, proving it does not depend
8074 // on the peer `:max-restarts` gate running first.
8075 let s = SupervisorSpec {
8076 estrategia: RestartStrategy::OneForOne,
8077 max_restarts: 0,
8078 restart_window: Some(Duration::from_secs(60)),
8079 children: vec![
8080 child("worker", "^0.1", RestartPolicy::Permanent),
8081 child("worker", "^0.2", RestartPolicy::Transient),
8082 ],
8083 };
8084 assert_eq!(
8085 s.validate_children().unwrap_err(),
8086 SupervisorError::DuplicateChildCaixa {
8087 caixa: "worker".into(),
8088 },
8089 "per-slot gate must resolve per-child refusal directly against \
8090 `&self` — a dependency on the peer `:max-restarts` gate \
8091 running first would surface ZeroMaxRestarts here instead",
8092 );
8093 // The peer gate is still the surface `validate` reaches — pin
8094 // the ordering to establish that `validate_children` truly runs
8095 // last in `validate`'s dispatch, so a direct call bypasses the
8096 // peer gates on any spec whose per-child cascade would fail.
8097 assert_eq!(
8098 s.validate().unwrap_err(),
8099 SupervisorError::ZeroMaxRestarts,
8100 "validate() must surface the peer `:max-restarts` gate before \
8101 reaching the per-child cascade — this pins the dispatch \
8102 ordering the per-slot gate's self-containment complements",
8103 );
8104 }
8105
8106 #[test]
8107 fn child_spec_restart_accessor_is_const_fn() {
8108 // The [`ChildSpec::restart`] per-`:children` restart-decision-
8109 // policy `Copy`-return scalar accessor is declared
8110 // `#[must_use] pub const fn` — matching the sibling M2
8111 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
8112 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
8113 // both converted in this commit), the sibling M2
8114 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
8115 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
8116 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
8117 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
8118 // `Copy`-return `pub const fn` scalar accessors on the sibling
8119 // M3 surface. Pin the `const`-eval posture here so a future
8120 // accidental downgrade to non-`const` (an added runtime helper
8121 // reachable only from a non-`const` context, an
8122 // `Option<RestartPolicy>`-shape migration on the per-child
8123 // restart-decision axis once heterogeneous per-cluster
8124 // restart-policy overlays land that would silently drop the
8125 // `const` qualifier, a manual hand-rolled shadow) trips at
8126 // caixa-core build time rather than surfacing as a downstream
8127 // `const`-context regression far from the declaration.
8128 //
8129 // Same shape as the sibling M3
8130 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
8131 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
8132 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
8133 // accessor axis — the load-bearing witness lives in the
8134 // module-scope `const fn` wrapper `restart_via_const_fn` below:
8135 // a body that calls [`ChildSpec::restart`] under a `const fn`
8136 // signature is well-formed only when the callee is itself
8137 // `const fn`, so any future accidental downgrade of
8138 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
8139 // build time (const-eval E0015 `cannot call non-const method`),
8140 // strictly stronger than a runtime `assert!(CONST)` and
8141 // side-stepping the destructor-in-const restriction that
8142 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
8143 // items on `ChildSpec`'s `String` carriers.
8144 //
8145 // The runtime body sweeps every closed-set [`RestartPolicy`]
8146 // arm and asserts the wrapped and direct dispatches agree.
8147 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
8148 c.restart()
8149 }
8150 for restart in [
8151 RestartPolicy::Permanent,
8152 RestartPolicy::Transient,
8153 RestartPolicy::Temporary,
8154 ] {
8155 let c = ChildSpec {
8156 caixa: "worker".into(),
8157 versao: "^0.1".into(),
8158 restart,
8159 };
8160 assert_eq!(
8161 restart_via_const_fn(&c),
8162 c.restart(),
8163 "const-fn-wrapped and direct dispatch on \
8164 ChildSpec::restart must agree for {restart:?}",
8165 );
8166 assert_eq!(
8167 c.restart(),
8168 restart,
8169 "ChildSpec::restart must return the storage-side \
8170 RestartPolicy verbatim for {restart:?} (a violation \
8171 means the accessor stopped being a raw field-return \
8172 copy)",
8173 );
8174 }
8175 }
8176
8177 #[test]
8178 fn supervisor_spec_estrategia_accessor_is_const_fn() {
8179 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
8180 // sibling-restart-strategy `Copy`-return scalar accessor is
8181 // declared `#[must_use] pub const fn` — matching the sibling M2
8182 // per-`:children` [`ChildSpec::restart`] (pinned by
8183 // [`child_spec_restart_accessor_is_const_fn`] above, both
8184 // converted in this commit), the sibling M2 per-`:supervisor`
8185 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
8186 // accessor already `pub const fn`, and mirroring the peer M3
8187 // mesh-slot per-`:placement`
8188 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
8189 // `pub const fn` scalar accessor whose method-name discipline
8190 // the [`SupervisorSpec::estrategia`] method was authored to
8191 // match. Pin the `const`-eval posture here so a future
8192 // accidental downgrade to non-`const` (an added runtime helper
8193 // reachable only from a non-`const` context, an
8194 // `Option<RestartStrategy>`-shape migration once the substrate
8195 // grows per-cluster strategy overlays that would silently drop
8196 // the `const` qualifier, a manual hand-rolled shadow) trips at
8197 // caixa-core build time rather than surfacing as a downstream
8198 // `const`-context regression far from the declaration.
8199 //
8200 // Same shape as the sibling
8201 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
8202 // load-bearing witness lives in the module-scope `const fn`
8203 // wrapper `estrategia_via_const_fn` below: a body that calls
8204 // [`SupervisorSpec::estrategia`] under a `const fn` signature
8205 // is well-formed only when the callee is itself `const fn`,
8206 // side-stepping the destructor-in-const restriction that would
8207 // otherwise block a direct
8208 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
8209 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
8210 // carriers.
8211 //
8212 // The runtime body sweeps every closed-set [`RestartStrategy`]
8213 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
8214 // direct dispatches agree.
8215 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
8216 s.estrategia()
8217 }
8218 for &estrategia in RestartStrategy::ALL {
8219 let s = SupervisorSpec {
8220 estrategia,
8221 max_restarts: 5,
8222 restart_window: Some(Duration::from_secs(60)),
8223 children: Vec::new(),
8224 };
8225 assert_eq!(
8226 estrategia_via_const_fn(&s),
8227 s.estrategia(),
8228 "const-fn-wrapped and direct dispatch on \
8229 SupervisorSpec::estrategia must agree for {estrategia:?}",
8230 );
8231 assert_eq!(
8232 s.estrategia(),
8233 estrategia,
8234 "SupervisorSpec::estrategia must return the storage-side \
8235 RestartStrategy verbatim for {estrategia:?} (a violation \
8236 means the accessor stopped being a raw field-return \
8237 copy)",
8238 );
8239 }
8240 }
8241
8242 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
8243 // macro definition (see the paired doc-block above the macro
8244 // definition) — every generated `<ctor>(caixa: &str) -> Self`
8245 // constructor folds the uniform `Self::<Variant> { caixa:
8246 // caixa.to_string() }` one-field struct-literal onto one substrate
8247 // primitive. The three per-variant equivalence pins below
8248 // (fail-before-pass-after by construction — a byte-mismatched macro
8249 // arm would trip its equivalence pin first) lock each generated
8250 // constructor to its struct-literal peer under `PartialEq`, so
8251 // every wire-up in [`SupervisorSpec::validate_children`] and
8252 // [`validate_no_self_supervision`] on that variant produces a
8253 // byte-equal `SupervisorError` to the pre-lift open-coded
8254 // struct-literal. The cross-axis pin that follows (non-default
8255 // caixa name) routes the sole constructor input axis through
8256 // `.to_string()`, so the fold does not silently collapse onto a
8257 // fixed name.
8258 //
8259 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
8260 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
8261 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
8262 // `missing_entry_ctor_matches_struct_literal_wrap` /
8263 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
8264 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
8265 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
8266 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
8267 // on the six sibling ctor families the recent trajectory closed
8268 // on the peer `LayoutError` / `AplicacaoError` envelopes.
8269
8270 #[test]
8271 fn empty_child_version_ctor_matches_struct_literal_wrap() {
8272 assert_eq!(
8273 SupervisorError::empty_child_version("worker"),
8274 SupervisorError::EmptyChildVersion {
8275 caixa: "worker".to_string(),
8276 },
8277 "generated empty_child_version ctor must produce byte-equal \
8278 SupervisorError to the open-coded struct-literal wrap on the \
8279 same &str fixture",
8280 );
8281 }
8282
8283 #[test]
8284 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
8285 assert_eq!(
8286 SupervisorError::duplicate_child_caixa("worker"),
8287 SupervisorError::DuplicateChildCaixa {
8288 caixa: "worker".to_string(),
8289 },
8290 "generated duplicate_child_caixa ctor must produce byte-equal \
8291 SupervisorError to the open-coded struct-literal wrap on the \
8292 same &str fixture",
8293 );
8294 }
8295
8296 #[test]
8297 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
8298 assert_eq!(
8299 SupervisorError::child_supervises_self("orquestra"),
8300 SupervisorError::ChildSupervisesSelf {
8301 caixa: "orquestra".to_string(),
8302 },
8303 "generated child_supervises_self ctor must produce byte-equal \
8304 SupervisorError to the open-coded struct-literal wrap on the \
8305 same &str fixture",
8306 );
8307 }
8308
8309 // Per-variant equivalence pins for the two lifted
8310 // [`SupervisorError::child_caixa_invalid`] /
8311 // [`SupervisorError::child_versao_invalid`] inherent constructors
8312 // (fail-before-pass-after by construction — a byte-mismatched ctor body
8313 // would trip its equivalence pin first). Each pins the ctor output to
8314 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
8315 // in [`SupervisorSpec::validate_children`] on the two variants
8316 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
8317 // struct-literal on the same scalar fixtures. Peers of the sibling
8318 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
8319 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
8320 // the peer `AplicacaoError` envelope's
8321 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
8322
8323 #[test]
8324 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
8325 let caixa = "Worker";
8326 let reason = "sample reason text";
8327 assert_eq!(
8328 SupervisorError::child_caixa_invalid(caixa, reason),
8329 SupervisorError::ChildCaixaInvalid {
8330 caixa: caixa.to_string(),
8331 reason: reason.to_string(),
8332 },
8333 "lifted child_caixa_invalid ctor must produce byte-equal \
8334 SupervisorError to the open-coded struct-literal wrap on the \
8335 same (&str, reason) fixture",
8336 );
8337 }
8338
8339 #[test]
8340 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
8341 let caixa = "worker";
8342 let versao = "not-a-req";
8343 let reason = "sample reason text";
8344 assert_eq!(
8345 SupervisorError::child_versao_invalid(caixa, versao, reason),
8346 SupervisorError::ChildVersaoInvalid {
8347 caixa: caixa.to_string(),
8348 versao: versao.to_string(),
8349 reason: reason.to_string(),
8350 },
8351 "lifted child_versao_invalid ctor must produce byte-equal \
8352 SupervisorError to the open-coded struct-literal wrap on the \
8353 same (&str, &str, reason) fixture",
8354 );
8355 }
8356
8357 #[test]
8358 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
8359 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
8360 // against a `&str`-literal vs. `format!(…)` reason input to pin
8361 // both constructors accept the `impl Into<String>` bound
8362 // uniformly, so neither wire-up site drifts under a per-arm
8363 // wrapper transformation on the caller-side `reason` axis. Peer
8364 // of the sibling
8365 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
8366 // sweep on the peer `AplicacaoError` envelope.
8367 let via_literal = "literal reason text";
8368 let via_format = format!("{} reason text", "literal");
8369 assert_eq!(
8370 SupervisorError::child_caixa_invalid("Worker", via_literal),
8371 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
8372 );
8373 assert_eq!(
8374 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
8375 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
8376 );
8377 }
8378
8379 #[test]
8380 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
8381 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
8382 // &str`) through a non-default fixture name against every
8383 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
8384 // so any wrapper-side lowercase / trim / truncate / re-order on
8385 // the `caixa.to_string()` sole-field construction surfaces
8386 // here rather than at a downstream diagnostic-shape mismatch.
8387 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
8388 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
8389 // through_to_string` / `contrato_target_ctors_route_edge_
8390 // triple_through_verbatim` / `contrato_empty_pair_ctors_
8391 // route_edge_pair_through_verbatim` cross-axis routing pins on
8392 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
8393 // here onto the `SupervisorError` `{ caixa: String }` envelope
8394 // so every substrate-primitive ctor family in caixa-core
8395 // guarantees the sole-field construction routes the caller's
8396 // `&str` through `.to_string()` verbatim.
8397 let name = "cache-v2";
8398 assert_eq!(
8399 SupervisorError::empty_child_version(name),
8400 SupervisorError::EmptyChildVersion {
8401 caixa: name.to_string(),
8402 },
8403 );
8404 assert_eq!(
8405 SupervisorError::duplicate_child_caixa(name),
8406 SupervisorError::DuplicateChildCaixa {
8407 caixa: name.to_string(),
8408 },
8409 );
8410 assert_eq!(
8411 SupervisorError::child_supervises_self(name),
8412 SupervisorError::ChildSupervisesSelf {
8413 caixa: name.to_string(),
8414 },
8415 );
8416 }
8417
8418 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
8419 //
8420 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
8421 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
8422 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
8423 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
8424 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
8425 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
8426 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
8427 // / silent constant-substitution on any one variant surfaces here rather
8428 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
8429 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
8430 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
8431 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
8432 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
8433 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
8434 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
8435 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
8436 #[test]
8437 fn no_children_ctor_matches_struct_literal_wrap() {
8438 let estrategia = RestartStrategy::OneForAll;
8439 assert_eq!(
8440 SupervisorError::no_children(estrategia),
8441 SupervisorError::NoChildren { estrategia },
8442 "generated no_children ctor must produce byte-equal \
8443 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
8444 on the same `Copy`-`RestartStrategy` fixture",
8445 );
8446 }
8447
8448 #[test]
8449 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
8450 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
8451 assert_eq!(
8452 SupervisorError::max_restarts_exceeds_cap(max_restarts),
8453 SupervisorError::MaxRestartsExceedsCap { max_restarts },
8454 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
8455 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
8456 struct-literal wrap on the same `Copy`-`u32` fixture",
8457 );
8458 }
8459
8460 #[test]
8461 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
8462 let window = Duration::from_micros(1_500);
8463 assert_eq!(
8464 SupervisorError::restart_window_not_canonical(window),
8465 SupervisorError::RestartWindowNotCanonical { window },
8466 "generated restart_window_not_canonical ctor must produce \
8467 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
8468 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
8469 );
8470 }
8471
8472 #[test]
8473 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
8474 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8475 assert_eq!(
8476 SupervisorError::restart_window_exceeds_cap(window),
8477 SupervisorError::RestartWindowExceedsCap { window },
8478 "generated restart_window_exceeds_cap ctor must produce \
8479 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
8480 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
8481 );
8482 }
8483
8484 #[test]
8485 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
8486 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
8487 // constructor input axis through a non-default `Copy` fixture against
8488 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
8489 // side silent `.into()` / silent constant-substitution / silent field
8490 // re-name away from the canonical `estrategia | max_restarts | window`
8491 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
8492 // axis silently rerouted through some other `Copy` coercion, surfaces
8493 // here rather than at a downstream per-`:supervisor` diagnostic-shape
8494 // drift. Peer of the sibling
8495 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
8496 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
8497 // envelope's per-`:politicas` per-axis ctor family, extended here onto
8498 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
8499 // variant family folded onto a substrate primitive.
8500 //
8501 // Fixtures picked out of each variant's accept-set boundary rather
8502 // than the default value so a silent constant-substitution to a per-
8503 // variant sentinel surfaces here on the structural-equality assertion.
8504 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
8505 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
8506 // isn't the `SimpleOneForOne` arm the sibling
8507 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
8508 // `max_restarts` fixture picks an above-cap magnitude the cap arm
8509 // rejects; the two `Duration` fixtures pick the sub-millisecond and
8510 // above-cap ends of the `:restart-window` canonical-form + cap
8511 // bracket respectively.
8512 let estrategia = RestartStrategy::RestForOne;
8513 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
8514 let sub_ms = Duration::from_micros(1_500);
8515 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
8516 assert_eq!(
8517 SupervisorError::no_children(estrategia),
8518 SupervisorError::NoChildren { estrategia },
8519 );
8520 assert_eq!(
8521 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
8522 SupervisorError::MaxRestartsExceedsCap {
8523 max_restarts: above_cap_restarts,
8524 },
8525 );
8526 assert_eq!(
8527 SupervisorError::restart_window_not_canonical(sub_ms),
8528 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
8529 );
8530 assert_eq!(
8531 SupervisorError::restart_window_exceeds_cap(above_hour),
8532 SupervisorError::RestartWindowExceedsCap { window: above_hour },
8533 );
8534 }
8535
8536 #[test]
8537 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
8538 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
8539 // generated ctor `const fn` so a caller can pin a `SupervisorError`
8540 // at compile time — the same zero-runtime-work property the pre-lift
8541 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
8542 // its `Copy`-pass-through construction path (no `.to_string()` /
8543 // `.into()` allocation, no branching). If any future edit silently
8544 // drops the `const` qualifier from the macro body the per-arm `const`
8545 // bindings below fail to compile, which surfaces the regression at
8546 // the substrate-primitive definition rather than at some downstream
8547 // consumer that had come to rely on the `const`-constructibility.
8548 // Peer of the sibling
8549 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
8550 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
8551 // per-`:politicas` per-axis ctor family.
8552 const NO_CHILDREN: SupervisorError =
8553 SupervisorError::no_children(RestartStrategy::OneForAll);
8554 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
8555 const WINDOW_NC: SupervisorError =
8556 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
8557 const WINDOW_CAP: SupervisorError =
8558 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
8559 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
8560 assert!(matches!(
8561 MAX_RESTARTS_CAP,
8562 SupervisorError::MaxRestartsExceedsCap { .. }
8563 ));
8564 assert!(matches!(
8565 WINDOW_NC,
8566 SupervisorError::RestartWindowNotCanonical { .. }
8567 ));
8568 assert!(matches!(
8569 WINDOW_CAP,
8570 SupervisorError::RestartWindowExceedsCap { .. }
8571 ));
8572 }
8573}