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 Self::OneForOne
67 }
68}
69
70impl RestartStrategy {
71 /// Exhaustive iteration surface for every consumer that walks the
72 /// closed four-arm [`RestartStrategy`] discriminator set (the future
73 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
74 /// admission-webhook rejection body naming the accepted-`:estrategia`
75 /// list, a future `feira supervisor --estrategia …` CLI arg-parse's
76 /// "did you mean" hint via a [`Self::from_wire`]-scan over the slice,
77 /// the future `feira app graph` per-supervisor `:estrategia` column,
78 /// any future round-trip fuzz harness that sweeps every arm). A
79 /// future arm addition (an OTP-`rest_for_all` arm the theory
80 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
81 /// might reach for once the four canonical OTP strategies stop
82 /// covering the substrate's discovered load-shape) extends this
83 /// slice as one edit and every consumer picks up the new entry by
84 /// construction; the compiler-checked exhaustiveness on the sibling
85 /// method `match` arms ([`Self::as_str`] / [`Self::from_wire`]) is
86 /// the build-time guarantee that no arm forgets to grow.
87 ///
88 /// Peer of the sibling closed-set typed enums'
89 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
90 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
91 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
92 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
93 /// surfaces — the fifth (and the first M2 OTP-shape) closed-set
94 /// typed enum on the caixa surface to converge onto the same
95 /// one-canonical-arm-list-per-enum discipline.
96 pub const ALL: &'static [Self] = &[
97 Self::OneForOne,
98 Self::OneForAll,
99 Self::RestForOne,
100 Self::SimpleOneForOne,
101 ];
102
103 /// Canonical PascalCase discriminator scalar this variant serializes
104 /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
105 /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
106 /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
107 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
108 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
109 /// constants so every substrate consumer that dispatches on the
110 /// per-supervisor sibling-restart strategy (the future
111 /// wasm-operator's per-supervisor sibling-restart branch, the future
112 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
113 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
114 /// reconciliation scheduler's per-strategy fan-out) reads the same
115 /// byte-string the `Serialize` derive emits — the pin test in
116 /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
117 /// asserts the two paths agree, peer of the M3
118 /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
119 /// distribution-strategy axis.
120 #[must_use]
121 pub const fn as_str(self) -> &'static str {
122 match self {
123 Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
124 Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
125 Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
126 Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
127 }
128 }
129
130 /// Substrate-canonical reverse projection on the `:supervisor
131 /// :estrategia` closed-set axis — parses the `PascalCase`
132 /// discriminator scalar back to the typed variant, or `None` when
133 /// `s` is outside
134 /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
135 /// on the same lifted
136 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
137 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
138 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
139 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
140 /// constants the [`Self::as_str`] emitter walks, so the parse and
141 /// emit halves of the round-trip migrate through one caixa-core
142 /// edit on any future arm addition.
143 ///
144 /// Prior to this lift the substrate carried only the forward
145 /// `Self → &str` projection on the OTP sibling-restart axis (the
146 /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
147 /// through it, the `Serialize` derive that emits the same
148 /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
149 /// plus the kebab-case dispatcher-catalog identity via
150 /// [`Self::discriminant`] — every non-serde consumer that wanted to
151 /// parse a wire-form `PascalCase` strategy scalar had to re-inline
152 /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
153 /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
154 /// that expressed no compile-time link back to the typed variant's
155 /// canonical lifted constant. A future variant rename or per-arm
156 /// serde-attribute drift would silently split the wire byte-string
157 /// one non-serde consumer parsed from the one the emitter wrote,
158 /// with the failure surfacing at parse time far from the rebrand
159 /// commit.
160 ///
161 /// Distinct axis from the [`std::str::FromStr`] impl the
162 /// [`gen_platform::FromStrKind`] derive already installs on this
163 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
164 /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
165 /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
166 /// [`Self::discriminant`]), while this method inverts the
167 /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
168 /// two-axis split lets the dispatcher-catalog identity live in
169 /// kebab-case
170 /// (where every peer catalog identifier already lives) without
171 /// forcing a wire-format rename on the tatara-lisp author surface
172 /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
173 /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
174 /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
175 /// carry on their peer closed-set typed-enum wire round-trips.
176 ///
177 /// Same closed-set-reverse-projection discipline the sibling
178 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
179 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
180 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
181 /// carry on the peer wire-side `str → Self` axes — extended onto
182 /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
183 /// fifth substrate-side closed-set typed enum to converge on the
184 /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
185 /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
186 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
187 /// derive already installs on the sibling kebab-case axis. Returns
188 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
189 /// shapes: the caller picks the diagnostic form appropriate for
190 /// its use site.
191 #[must_use]
192 pub fn from_wire(s: &str) -> Option<Self> {
193 match s {
194 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
195 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
196 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
197 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
198 _ => None,
199 }
200 }
201}
202
203/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
204/// pretty-printed byte-string every consumer that formats the strategy as
205/// user-facing text lands on (the future wasm-operator's per-supervisor
206/// sibling-restart-strategy diagnostic line, the future `feira app graph`
207/// per-supervisor strategy line, the future M4
208/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
209/// rejection body) reaches for the same lifted
210/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
211/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
212/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
213/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
214/// wire-format `Serialize` derive already emits under
215/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
216/// [`RestartStrategy::as_str`] helper already returns.
217///
218/// Pre-convergence the two paths structurally disagreed — the
219/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
220/// route (now retired here) sent [`std::fmt::Display`] through the
221/// gen-platform discriminant catalog string, which arrives kebab-case as
222/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
223/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
224/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
225/// through the un-`rename`d serde derive. Every consumer that formatted
226/// the strategy for a diagnostic line, a graph, or a rejection body under
227/// `format!("{v}")` therefore landed under a different byte-string than
228/// the wire format the operator's per-strategy dispatch keyed off — a
229/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
230/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
231/// probed was `"OneForOne"`) surfaced as a confused correlate at
232/// operator-log time far from the two-declaration site.
233///
234/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
235/// path: every `format!("{v}")` call reaches the same lifted
236/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
237/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
238/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
239/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
240/// byte-string per variant. A future variant rename or
241/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
242/// exactly one place, structurally.
243///
244/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
245/// (from `#[derive(gen_platform::Discriminant)]`) still returns
246/// `"one-for-one"` / etc., and the fleet-wide
247/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
248/// registration keys the catalog off the same kebab identity. The two
249/// naming worlds now live on separate typed methods (`Display` /
250/// `as_str` for the wire byte-string, `discriminant` for the catalog
251/// identity) rather than sharing one `Display` route that structurally
252/// disagrees with the wire format.
253///
254/// Pin tests
255/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
256/// and
257/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
258/// assert the three paths agree byte-for-byte on every variant, so a
259/// future variant rename or per-arm serde attribute drift is a build
260/// error visible at caixa-core test time, not a silent per-consumer
261/// dispatch miss at apply / reconcile time.
262///
263/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
264/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
265/// axis — same three-path-convergence discipline, extended to close the
266/// second of three OTP-shaped closed-enum discriminator axes on the
267/// caixa typed surface.
268impl std::fmt::Display for RestartStrategy {
269 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270 f.write_str(self.as_str())
271 }
272}
273
274/// Per-child restart policy.
275///
276/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
277#[derive(
278 Serialize,
279 Deserialize,
280 Debug,
281 Clone,
282 Copy,
283 PartialEq,
284 Eq,
285 Hash,
286 gen_platform::TypedDispatcher,
287 gen_platform::Discriminant,
288 gen_platform::IsVariant,
289 gen_platform::FromStrKind,
290)]
291pub enum RestartPolicy {
292 /// Always restart the child, regardless of how it died. Used for
293 /// long-running services that must always be up.
294 Permanent,
295 /// Never restart. Used for one-shot work whose completion is
296 /// itself the success signal (`oneShot` triggers map here).
297 Temporary,
298 /// Restart only when the child died *abnormally* (non-zero exit
299 /// or unhandled exception). A clean exit completes the child.
300 Transient,
301}
302
303impl Default for RestartPolicy {
304 fn default() -> Self {
305 Self::Permanent
306 }
307}
308
309impl RestartPolicy {
310 /// Canonical PascalCase discriminator scalar this variant serializes
311 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
312 /// arms return the paired
313 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
314 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
315 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
316 /// constants so every substrate consumer that dispatches on the
317 /// per-child restart-decision policy (the future wasm-operator's
318 /// per-child post-exit restart-decision branch, the future M4
319 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
320 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
321 /// reconciliation scheduler's per-child-policy fan-out) reads the
322 /// same byte-string the `Serialize` derive emits — the pin test in
323 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
324 /// asserts the two paths agree, peer of the M2
325 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
326 /// sibling-restart-strategy axis and the M3
327 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
328 /// per-Aplicacao distribution-strategy axis — the third of three
329 /// OTP-shaped closed-enum discriminator axes on the caixa typed
330 /// surface to converge onto the same three-path-convergence
331 /// (`Serialize` derive → `as_str` helper → lifted constant)
332 /// drift-detection posture.
333 #[must_use]
334 pub const fn as_str(self) -> &'static str {
335 match self {
336 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
337 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
338 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
339 }
340 }
341}
342
343/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
344/// pretty-printed byte-string every consumer that formats the policy as
345/// user-facing text lands on (the future wasm-operator's per-child
346/// post-exit restart-decision diagnostic line, the future `feira app
347/// graph` per-child restart column, the future M4
348/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
349/// admission-webhook rejection body) reaches for the same lifted
350/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
351/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
352/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
353/// wire-format `Serialize` derive already emits under
354/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
355/// [`RestartPolicy::as_str`] helper already returns.
356///
357/// Pre-convergence the two paths structurally disagreed — the
358/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
359/// route (now retired here) sent [`std::fmt::Display`] through the
360/// gen-platform discriminant catalog string, which arrives kebab-case as
361/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
362/// (whose variant names each collapse to their own lowercase form under
363/// the kebab-case transform), while the wire format ran as `PascalCase`
364/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
365/// serde derive. Every consumer that formatted the policy for a
366/// diagnostic line, a graph column, or a rejection body under
367/// `format!("{v}")` therefore landed under a different byte-string than
368/// the wire format the operator's per-child-policy dispatch keyed off —
369/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
370/// diagnostic quoting `"permanent"` while the wire scalar the operator
371/// probed was `"Permanent"`) surfaced as a confused correlate at
372/// operator-log time far from the two-declaration site.
373///
374/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
375/// path: every `format!("{v}")` call reaches the same lifted
376/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
377/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
378/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
379/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
380/// byte-string per variant. A future variant rename or
381/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
382/// exactly one place, structurally.
383///
384/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
385/// (from `#[derive(gen_platform::Discriminant)]`) still returns
386/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
387/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
388/// registration keys the catalog off the same kebab identity. The two
389/// naming worlds now live on separate typed methods (`Display` /
390/// `as_str` for the wire byte-string, `discriminant` for the catalog
391/// identity) rather than sharing one `Display` route that structurally
392/// disagrees with the wire format.
393///
394/// Pin tests
395/// [`tests::restart_policy_display_routes_through_as_str_helper`]
396/// and
397/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
398/// assert the three paths agree byte-for-byte on every variant, so a
399/// future variant rename or per-arm serde attribute drift is a build
400/// error visible at caixa-core test time, not a silent per-consumer
401/// dispatch miss at apply / reconcile time.
402///
403/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
404/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
405/// and the sibling [`RestartStrategy`] `Display` impl on the
406/// per-supervisor sibling-restart-strategy axis — same three-path-
407/// convergence discipline, extended to close the third and final of
408/// three OTP-shaped closed-enum discriminator axes on the caixa typed
409/// surface.
410impl std::fmt::Display for RestartPolicy {
411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412 f.write_str(self.as_str())
413 }
414}
415
416// Fleet-wide dispatcher-catalog registrations for caixa's OTP
417// supervisor surface — two more typed shadows over Erlang/OTP
418// primitives the substrate now mechanically tracks (see
419// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
420// theory/TYPED-ABSORPTION.md for the absorption arc).
421gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
422gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
423
424/// One child entry in the supervisor's `:children` list.
425///
426/// Every child references another caixa by `:caixa <nome>` + version
427/// constraint. The supervisor materializes one ComputeUnit per entry.
428#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
429#[serde(rename_all = "camelCase")]
430pub struct ChildSpec {
431 /// The child caixa's `:nome`. Must resolve via the same dependency
432 /// resolution path as `:deps` (caixa-resolver).
433 pub caixa: String,
434
435 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
436 /// [`crate::dep::Dep::versao`].
437 pub versao: String,
438
439 /// Restart policy — defaults to [`RestartPolicy::Permanent`].
440 #[serde(default)]
441 pub restart: RestartPolicy,
442}
443
444impl ChildSpec {
445 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
446 /// accessor every consumer that reads the OTP-shape supervised
447 /// child's identity keys off — returns the author-declared
448 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
449 /// from the typed slot's own [`String`] storage.
450 ///
451 /// The `:children :caixa` slot carries the DNS-1123 label — the
452 /// child caixa's `:nome` — that every emitted cluster artifact
453 /// derives its `metadata.name` from verbatim: the rendered
454 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
455 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
456 /// identity, and the per-child K8s Service `metadata.name` the
457 /// future wasm-operator (M3) provisions for inter-child supervision-
458 /// tree wiring. Every downstream consumer that fans on the child's
459 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
460 /// per-child DNS-1123 gate at
461 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
462 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
463 /// [`validate_no_self_supervision`] cross-slot equality check
464 /// against the parent's `:nome`, every `SupervisorError` variant
465 /// carrying the offending child caixa verbatim for `feira lint`
466 /// rendering, the future wasm-operator's hierarchical reconciliation
467 /// scheduler's per-child ComputeUnit-name projection, the future M4
468 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
469 /// admission webhook).
470 ///
471 /// Prior to this lift the `.caixa` byte-string was accessed inline
472 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
473 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
474 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
475 /// carriers' `child.caixa.clone()`, the dedup key's
476 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
477 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
478 /// field-accesses that expressed no compile-time link back to the
479 /// typed slot. A future extension of the `:children :caixa` axis to
480 /// a richer author surface (a per-cluster alias table the operator
481 /// pins through a future `:placement`-scoped slot on the supervisor
482 /// tree, a namespace-qualified rewrite the M4 CR materializer
483 /// applies per-CR, a per-child overlay from the future `:children
484 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
485 /// acknowledges) would have had to be threaded through every
486 /// open-coded copy in lockstep or one consumer would silently
487 /// disagree with the peers on which caixa a given child resolves to
488 /// — a child-set lookup that treated the name as `"cart-worker"`
489 /// while the peer duplicate-detector treated it as
490 /// `"tenant-a/cart-worker"` would silently split the
491 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
492 /// self-supervision detector's parent-equality check, a two-consumer
493 /// split at the validator far from the source `caixa.lisp` with no
494 /// field naming the identity-drift root cause. Lifting the resolution
495 /// rule to a typed method on the substrate primitive means every
496 /// downstream consumer of the Supervisor's per-`:children` identity
497 /// surface reaches for exactly one typed dispatch — the resolver's
498 /// accept-set migrates as a unit on any future axis addition.
499 ///
500 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
501 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
502 /// mesh-slot surface — same "one typed dispatch on the substrate
503 /// primitive, thin projections at each consumer" discipline extended
504 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
505 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
506 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
507 /// accessor discipline for the shared substrate concept "another
508 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
509 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
510 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
511 /// slot family's typed-accessor discipline now spans both the
512 /// upgrade axis (`:upgrade-from`) and the supervision axis
513 /// (`:children`), matching the closed M3 mesh-slot accessor family's
514 /// shape. Named `nome()` to match the tatara-lisp author-surface
515 /// term the field's docstring already reaches for ("The child
516 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
517 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
518 /// discipline the substrate already carries — the accessor's name
519 /// maps directly onto the canonical caixa-identity vocabulary rather
520 /// than shadowing the field's storage-side `caixa` label.
521 #[must_use]
522 pub fn nome(&self) -> &str {
523 self.caixa.as_str()
524 }
525
526 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
527 /// requirement scalar accessor every consumer that reads the OTP-shape
528 /// supervised child's version pin keys off — returns the author-declared
529 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
530 /// the typed slot's own [`String`] storage.
531 ///
532 /// The `:children :versao` slot carries the Cargo-shaped semver
533 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
534 /// which release of the supervised child caixa the OTP-shape supervisor
535 /// tree materializes against — the same requirement grammar the peer
536 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
537 /// shared [`crate::render::require_valid_versao_requirement`] cascade
538 /// and the shared [`crate::version::parse_requirement`] parser. Every
539 /// downstream consumer that fans on the child's version pin keys off
540 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
541 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
542 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
543 /// for `feira lint` rendering, every future per-cluster version-lock
544 /// overlay the caixa-operator's hierarchical reconciliation scheduler
545 /// pins through a future `:placement`-scoped supervisor-tree slot, the
546 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
547 /// per-child version resolver, the future wasm-operator's per-child
548 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
549 ///
550 /// Prior to this lift the `.versao` byte-string was accessed inline at
551 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
552 /// [`SupervisorSpec::validate`] requirement-gate call
553 /// `require_valid_versao_requirement(&child.versao, …)` and the
554 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
555 /// `versao: child.versao.clone()` — two open-coded field-accesses that
556 /// expressed no compile-time link back to the typed slot. A future
557 /// extension of the `:children :versao` axis to a richer author surface
558 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
559 /// flow, a lacre-projected concrete-version rewrite the operator
560 /// materializes at CR-admission time, a future `:children :versao-lock`
561 /// per-cluster override slot the wasm-operator's hierarchical
562 /// reconciliation scheduler authors per-CR) would have had to be
563 /// threaded through both open-coded copies in lockstep or one consumer
564 /// would silently disagree with the peer on which release constraint a
565 /// given child resolves to — the requirement-gate call reading
566 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
567 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
568 /// the actual gate rejection input, a two-consumer split at the
569 /// validator far from the source `caixa.lisp` with no field naming the
570 /// version-pin drift root cause. Lifting the resolution rule to a typed
571 /// method on the substrate primitive means every downstream
572 /// requirement-facing consumer of the Supervisor's per-`:children`
573 /// version-pin surface reaches for exactly one typed dispatch — the
574 /// resolver's accept-set migrates as a unit on any future axis addition.
575 ///
576 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
577 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
578 /// surface — same "one typed dispatch on the substrate primitive, thin
579 /// projections at each consumer" discipline extended onto the M2
580 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
581 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
582 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
583 /// one accessor discipline for the shared substrate concept "another
584 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
585 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
586 /// `:nome` scalar accessor — the pair
587 /// `(nome(), versao_requirement())` jointly projects the
588 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
589 /// that fans on per-child identity + version pin keys off, closing the
590 /// last unlifted per-`:children` `String`-carry axis so every downstream
591 /// per-`:children` reader now routes through a typed dispatch on the
592 /// substrate primitive. Named `versao_requirement()` rather than
593 /// `versao()` because the field's storage-side `.versao` label is
594 /// already the author-surface term (`:versao`); the accessor's name
595 /// carries the semantic role — the semver *requirement* string the
596 /// shared [`crate::version::parse_requirement`] entry-point consumes —
597 /// so a raw field access and a typed dispatch read differently at every
598 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
599 /// naming discipline verbatim.
600 #[must_use]
601 pub fn versao_requirement(&self) -> &str {
602 self.versao.as_str()
603 }
604
605 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
606 /// per-child post-exit restart-decision policy scalar accessor every
607 /// consumer that dispatches on the supervised child's post-exit
608 /// reconcile posture keys off — returns the author-declared
609 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
610 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
611 /// storage.
612 ///
613 /// The `:children :restart` slot carries the closed-set OTP-shaped
614 /// per-child restart-decision policy discriminator
615 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
616 /// worker-child default; [`RestartPolicy::Transient`] — restart only
617 /// on abnormal exit, the OTP `transient` clean-completion-aware
618 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
619 /// `temporary` one-shot default) that every downstream consumer of
620 /// the Supervisor's per-child post-exit reconcile branch keys off.
621 /// Every future downstream consumer that fans on the per-child
622 /// restart-decision keys off this scalar (the future `feira app
623 /// graph` per-child restart column, the future wasm-operator's
624 /// per-child post-exit restart-decision branch, the future M4
625 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
626 /// admission webhook, the `caixa-operator`'s hierarchical
627 /// reconciliation scheduler's per-child post-exit reconcile branch,
628 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
629 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
630 /// pin threads through).
631 ///
632 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
633 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
634 /// scalar accessor and the M3 mesh-slot
635 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
636 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
637 /// — same "one typed dispatch on the substrate primitive,
638 /// `Copy`-projected closed-set enum-arm discriminator that partitions
639 /// the downstream renderer's per-arm fan-out" discipline extended
640 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
641 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
642 /// [`ChildSpec`] type — companion to the sibling per-`:children`
643 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
644 /// and the per-`:children` [`ChildSpec::versao_requirement`]
645 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
646 /// on the sibling `String`-carry axes. The triple
647 /// `(nome(), versao_requirement(), restart())` jointly projects the
648 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
649 /// tree consumer that fans on per-child identity + version pin +
650 /// restart-decision keys off, closing the last unlifted per-`:children`
651 /// axis so every downstream per-`:children` reader now routes through
652 /// a typed dispatch on the substrate primitive. Named `restart()` to
653 /// match the storage field's name and the author-surface
654 /// `:children :restart` slot term verbatim; the accessor's identity
655 /// name maps onto the canonical OTP-shape per-child restart-decision-
656 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
657 /// carries.
658 #[must_use]
659 pub fn restart(&self) -> RestartPolicy {
660 self.restart
661 }
662}
663
664/// Supervisor-typed slots that live alongside the standard Caixa
665/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
666/// the manifest stays a single typed form; this struct exists for
667/// validation + conversion.
668#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
669#[serde(rename_all = "camelCase")]
670pub struct SupervisorSpec {
671 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
672 #[serde(default)]
673 pub estrategia: RestartStrategy,
674
675 /// Max restarts within [`Self::restart_window`] before the
676 /// supervisor itself terminates (and its parent supervisor decides
677 /// what to do). Default 5.
678 #[serde(default = "default_max_restarts")]
679 pub max_restarts: u32,
680
681 /// Sliding window for `max_restarts`. Authored as a duration
682 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
683 /// is rejected by [`Self::validate`] — Erlang/OTP's
684 /// `MaxIntensity / Period` invariant requires a positive window
685 /// (a zero-period supervisor either trips on the first failure or
686 /// never trips, depending on operator interpretation, neither of
687 /// which is the author's intent). Omit the slot to express "no
688 /// reset"; carry a positive duration to express the sliding window.
689 #[serde(
690 default,
691 skip_serializing_if = "Option::is_none",
692 with = "duration_codec"
693 )]
694 pub restart_window: Option<Duration>,
695
696 /// Static children. Empty for `SimpleOneForOne` (children added
697 /// dynamically); required for the other three strategies.
698 #[serde(default)]
699 pub children: Vec<ChildSpec>,
700}
701
702const fn default_max_restarts() -> u32 {
703 5
704}
705
706/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
707/// validated [`SupervisorSpec::max_restarts`] past
708/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
709///
710/// The typed field is `u32` (the zero-floor arm
711/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
712/// so a programmatic struct literal
713/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
714/// author-surface form (`:max-restarts 4294967295` or any
715/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
716/// cleanly through serde — a structurally unbounded `u32` ceiling. The
717/// runtime substrate consuming the value (Erlang/OTP's
718/// `MaxIntensity / Period` ratio, the future wasm-operator's
719/// per-supervisor restart-intensity counter, the M4
720/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
721/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
722/// escalation threshold is structurally so high that no realistic
723/// restarts-per-`:restart-window` traffic shape can reach it, the
724/// supervisor never escalates to its parent, and a bad child can loop
725/// inside the window indefinitely with the parent supervisor structurally
726/// never receiving the "this subtree has exceeded its restart budget"
727/// signal the typed slot is meant to express — the canonical
728/// "supervisor intensity declared, no escalation" footgun, exactly the
729/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
730/// on the `:politicas :circuit-breaker :max-failures` axis (both are
731/// "trip the next-higher protection layer after N events in a rolling
732/// window" counters with identical degenerate-at-the-high-end shape).
733///
734/// The `1000` ceiling matches the sibling
735/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
736/// peer — same "events-per-window trip threshold" semantics, same `u32`
737/// type, same no-op-at-the-high-end failure mode) so the M4
738/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
739/// and the future wasm-operator's per-supervisor restart-intensity
740/// counter reach for either field knowing the value is in `1..=1000`
741/// without re-validating at the reconciler layer. The cap sits two
742/// orders of magnitude above every documented Erlang/OTP production
743/// playbook recommendation (Learn You Some Erlang's
744/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
745/// `max_restarts: 3` default, OTP's `supervisor` callback module
746/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
747/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
748/// default) and below the clearly-pathological "effectively no
749/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
750/// author can plausibly want at hyperscale (a long-running supervisor
751/// over a very-flaky pool tolerating thousands of transient restarts
752/// before escalating), but a hard wall above which the typed policy is
753/// structurally a no-op carried verbatim on every emitted child-restart
754/// reconciliation contract.
755///
756/// Lifted as a typed `pub const` so the bound has exactly one source of
757/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
758/// materializer's admission webhook and the wasm-operator-side
759/// per-supervisor restart-intensity reconciler read from one place. Same
760/// shape every other typed upper bound in this crate carries
761/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
762/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
763/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
764/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
765/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
766/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
767pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
768
769/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
770/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
771/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
772/// (inclusive on both ends, integer-millisecond magnitudes by the
773/// canonical-form gate immediately preceding).
774///
775/// The typed field is `Option<Duration>` (the zero-floor arm
776/// [`SupervisorError::RestartWindowZero`] already rejects
777/// `Some(Duration::ZERO)`, and the canonical-form arm
778/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
779/// sub-millisecond residue), so a programmatic struct literal
780/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
781/// .. }` — 24h) and the equivalent author-surface form
782/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
783/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
784/// cleanly through serde — a structurally unbounded `Duration` ceiling.
785/// A `:restart-window` value far above the documented Erlang/OTP
786/// `MaxIntensity / Period` production-playbook band (Learn You Some
787/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
788/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
789/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
790/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
791/// degenerates the supervisor's restart-intensity counter into a
792/// lifetime counter: the rolling failure-counting window is structurally
793/// so long that transient restarts are never forgotten, so the
794/// `MaxIntensity / Period` ratio degenerates from "trip the parent
795/// supervisor when the child has exceeded its restart budget *within
796/// the recent window*" to "trip the parent when the child has exceeded
797/// its restart budget *over its lifetime*" — every transient restart
798/// counts against the budget forever, the supervisor's reset semantic
799/// never reaches the child, and the typed `:restart-window` slot
800/// becomes a no-op rolling window carried on every emitted hierarchical
801/// reconciliation contract. The canonical
802/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
803/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
804/// `:politicas :circuit-breaker :window` axis with identical shape (both
805/// are "rolling failure-counting window with a per-`Period` reset" Duration
806/// axes whose lifetime-counter degenerate at the high end is the same
807/// "the reset semantic never fires" CSE invariant violation).
808///
809/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
810/// the shared duration codec emits (`"<n>h"` for any integer-hour
811/// magnitude) — every value in the canonical authoring form's
812/// `<integer><unit>` grammar at or below this cap renders to a clean
813/// canonical string — and matches the three sibling typed-`Duration`
814/// caps already lifted to this surface
815/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
816/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
817/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
818/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
819/// per-supervisor `:supervisor :restart-window` — now share a single
820/// uniform top edge at the codec's largest emitted unit so the next
821/// typed-slot wiring (the future wasm-operator's per-supervisor
822/// `MaxIntensity / Period` reconciler, the M4
823/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
824/// webhook, the `caixa-operator`'s hierarchical reconciliation
825/// scheduler) reaches for any of the four knowing the value is in
826/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
827/// two orders of magnitude above every documented Erlang/OTP / Elixir /
828/// Riak Core / RabbitMQ production-playbook recommendation band
829/// (`5s..=300s`) and below the clearly-pathological "rolling window
830/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
831/// a value the author can plausibly want for a very-low-traffic
832/// long-tail failure-restart window over a hyperscale-flaky child pool,
833/// but a hard wall above which the rolling-window contract is
834/// structurally a lifetime-counter contract.
835///
836/// Lifted as a typed `pub const` so the bound has exactly one source
837/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
838/// materializer's admission webhook, the wasm-operator-side
839/// per-supervisor `MaxIntensity / Period` reconciler, and the
840/// `caixa-operator`'s hierarchical reconciliation scheduler all read
841/// from one place. Same shape every other typed upper bound in this
842/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
843/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
844/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
845/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
846/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
847/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
848/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
849/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
850/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
851pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
852
853impl Default for SupervisorSpec {
854 fn default() -> Self {
855 Self {
856 estrategia: RestartStrategy::default(),
857 max_restarts: default_max_restarts(),
858 restart_window: Some(Duration::from_secs(60)),
859 children: Vec::new(),
860 }
861 }
862}
863
864impl SupervisorSpec {
865 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
866 /// sibling-restart-strategy scalar accessor every consumer that
867 /// dispatches on the supervisor's per-sibling restart-decision shape
868 /// keys off — returns the author-declared `:supervisor :estrategia`
869 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
870 /// the typed slot's own [`RestartStrategy`] storage.
871 ///
872 /// The `:supervisor :estrategia` slot carries the closed-set
873 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
874 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
875 /// [`RestartStrategy::OneForAll`] — restart every child on any child
876 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
877 /// [`RestartStrategy::RestForOne`] — restart the failed child and
878 /// every child started after it, the Erlang/OTP `rest_for_one`
879 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
880 /// dynamic children of the same shape, the Erlang/OTP
881 /// `simple_one_for_one` per-session default) that every downstream
882 /// consumer of the Supervisor's per-sibling restart-decision fan-out
883 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
884 /// paired coherently with the sibling `:children` axis
885 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
886 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
887 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
888 /// downstream consumer that reads the strategy keys off this scalar
889 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
890 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
891 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
892 /// `estrategia:` field, the future `feira app graph` per-Supervisor
893 /// strategy print line, the future wasm-operator's per-supervisor
894 /// sibling-restart-strategy branch, the future M4
895 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
896 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
897 /// reconciliation scheduler's per-strategy fan-out).
898 ///
899 /// Prior to this lift the `.estrategia` field was accessed inline at
900 /// two production sites in `caixa-core/src/supervisor.rs` — the
901 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
902 /// `match self.estrategia { … }` partition dispatch, and the
903 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
904 /// carrier at `estrategia: self.estrategia` — two open-coded
905 /// field-accesses that expressed no compile-time link back to the
906 /// typed slot. A future extension of the `:supervisor :estrategia`
907 /// axis to a richer author surface (a per-cluster strategy override
908 /// the operator pins through a future `:supervisor :estrategia-overrides`
909 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
910 /// acknowledges, a per-tenant strategy-alias table the M4 CR
911 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
912 /// derivation the future adaptive-supervision engine computes from
913 /// child-failure-history topology, a per-child-cohort strategy split
914 /// the future `RestForCohort` extension acknowledged by the
915 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
916 /// would have had to be threaded through every open-coded copy in
917 /// lockstep — one consumer reading the raw variant while a peer read
918 /// the operator-resolved variant would silently split the
919 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
920 /// the actual partition-dispatch input the empty-children refusal
921 /// arm reached under, a two-consumer split at the validator far from
922 /// the source `caixa.lisp` with no field naming the strategy-drift
923 /// root cause. Lifting the resolution rule to a typed method on the
924 /// substrate primitive means every downstream consumer of the
925 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
926 /// reaches for exactly one typed dispatch — the resolver's accept-set
927 /// migrates as a unit on any future axis addition.
928 ///
929 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
930 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
931 /// per-`:placement` distribution-strategy axis — same "one typed
932 /// dispatch on the substrate primitive, thin projections at each
933 /// consumer" discipline extended onto the M2 supervisor-slot
934 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
935 /// scalar axis. The two typed axes (`Placement::estrategia` on the
936 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
937 /// Supervisor side) now share one accessor discipline for the shared
938 /// substrate concept "a `Copy`-projected closed-set enum-arm
939 /// discriminator that partitions the downstream renderer's per-arm
940 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
941 /// `SupervisorSpec` type — companion to the sibling per-`:children`
942 /// [`crate::ChildSpec::nome`] (57c61d0) /
943 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
944 /// scalar accessors on the sibling per-`:children` `String`-carry
945 /// axes. Named `estrategia()` to match the storage field's name and
946 /// the peer [`crate::Placement::estrategia`] method-name discipline
947 /// verbatim; the accessor's identity name maps onto the canonical
948 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
949 /// docstring already carries.
950 #[must_use]
951 pub fn estrategia(&self) -> RestartStrategy {
952 self.estrategia
953 }
954
955 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
956 /// `MaxIntensity` restart-budget scalar accessor every consumer that
957 /// reads the supervisor's per-`:restart-window` restart-budget count
958 /// keys off — returns the author-declared `:supervisor :max-restarts`
959 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
960 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
961 /// borrow of `&self` past the call). Non-optional (the `u32` field
962 /// carries the restart-budget count as a required axis with a
963 /// [`default_max_restarts`]-supplied default; the zero-floor arm
964 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
965 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
966 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
967 ///
968 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
969 /// `MaxIntensity` restart-budget count that pairs with the sibling
970 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
971 /// restart-intensity ratio the supervisor trips its own escalation on
972 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
973 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
974 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
975 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
976 /// upper-cap bracket at
977 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
978 /// wasm-operator's per-supervisor restart-intensity counter's
979 /// budget-vs-count comparator, the future M4
980 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
981 /// webhook, the `caixa-operator`'s hierarchical reconciliation
982 /// scheduler's per-supervisor escalation-decision branch, every
983 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
984 /// offending count verbatim for `feira lint` rendering).
985 ///
986 /// Prior to this lift the `.max_restarts` field was accessed inline at
987 /// one production site in `caixa-core/src/supervisor.rs` — the
988 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
989 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
990 /// that expressed no compile-time link back to the typed slot. A
991 /// future extension of the `:max-restarts` axis to a richer author
992 /// surface (a per-cluster restart-budget override the operator pins
993 /// through a future `:supervisor :max-restarts-overrides` slot the
994 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
995 /// a per-tenant restart-budget-alias table the M4 CR materializer
996 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
997 /// the future adaptive-supervision engine computes from child-failure-
998 /// history topology, a promotion of the plain `u32` count to a richer
999 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
1000 /// budget-partition slot comes into scope) would have had to be
1001 /// threaded through every open-coded copy in lockstep or the validate
1002 /// gate and the future M4 emit path would silently disagree on which
1003 /// restart-budget count a given supervisor resolves to — an author's
1004 /// `:max-restarts 5` would satisfy validate while the emit path
1005 /// silently read a drifted other value (a `:max-restarts 10000`
1006 /// no-op supervisor at the emit boundary would carry the author's
1007 /// declared `5` verbatim in `feira lint` output while the future
1008 /// wasm-operator's restart-intensity counter operated under the
1009 /// drifted count), a two-consumer split at the validator far from the
1010 /// source `caixa.lisp` with no field naming the restart-budget-drift
1011 /// root cause. Lifting the resolution rule to a typed method on the
1012 /// substrate primitive means every downstream consumer of the
1013 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
1014 /// for exactly one typed dispatch — the resolver's accept-set migrates
1015 /// as a unit on any future axis addition.
1016 ///
1017 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
1018 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
1019 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
1020 /// outlier-detection trip-threshold axis — same "one typed dispatch on
1021 /// the substrate primitive, thin projections at each consumer"
1022 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
1023 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
1024 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
1025 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
1026 /// one accessor discipline for the shared substrate concept "a
1027 /// `Copy`-projected required `u32` count that trips the next-higher
1028 /// protection layer after N events in a rolling window" — both are
1029 /// counters with identical degenerate-at-the-high-end shape and share
1030 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
1031 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
1032 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
1033 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
1034 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
1035 /// the storage field's name verbatim and the peer
1036 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
1037 /// accessor's identity maps onto the canonical OTP-shape supervision
1038 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
1039 /// already carries.
1040 #[must_use]
1041 pub const fn max_restarts(&self) -> u32 {
1042 self.max_restarts
1043 }
1044
1045 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
1046 /// `Period` sliding-window scalar accessor every consumer of the
1047 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
1048 /// keys off — returns the author-declared `:supervisor :restart-window`
1049 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
1050 /// the typed slot's own `Option<Duration>` storage (`Duration` is
1051 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
1052 /// value; no borrow of `&self` past the call). `None` when the slot is
1053 /// absent (the canonical "never reset — every restart across the
1054 /// supervisor's lifetime counts against the sibling `:max-restarts`
1055 /// budget" sentinel the field's own docstring names and the peer
1056 /// `validate_accepts_none_restart_window` pin locks in on the
1057 /// [`SupervisorSpec::validate`] entry-side).
1058 ///
1059 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
1060 /// `Period` sliding-observation-interval that pairs with the sibling
1061 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
1062 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
1063 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
1064 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
1065 /// default). The typed slot's `Option<Duration>` accept-set —
1066 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
1067 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
1068 /// `Period > 0`; a zero period either trips on the first failure or
1069 /// never trips depending on operator interpretation, neither of which
1070 /// is the author's intent — omit the slot to express "no reset";
1071 /// carry a positive duration to express the sliding window),
1072 /// integer-millisecond canonical form enforced through
1073 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
1074 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
1075 /// future wasm-operator's per-supervisor restart-intensity counter
1076 /// quantizes at milliseconds), upper-bounded by
1077 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
1078 /// supervisor rolling window any operationally-reachable supervisor
1079 /// can honor without spanning multiple scheduler epochs the
1080 /// hierarchical-reconciliation scheduler treats as independent) —
1081 /// maps onto the future wasm-operator (M3) per-supervisor
1082 /// restart-intensity counter's rolling-observation-interval, the
1083 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1084 /// per-`spec.restartWindow` admission webhook, and the sibling
1085 /// `duration_codec`-serialized wire scalar every downstream consumer
1086 /// of the supervisor's per-`:supervisor` restart-intensity denominator
1087 /// keys off.
1088 ///
1089 /// Prior to this lift the `.restart_window` field was accessed inline
1090 /// at one production site in `caixa-core/src/supervisor.rs` — the
1091 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
1092 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
1093 /// open-coded field-access that expressed no compile-time link back to
1094 /// the typed slot. A future extension of the `:restart-window` axis to
1095 /// a richer author surface (a per-cluster restart-window override the
1096 /// operator pins through a future `:supervisor :restart-window-overrides`
1097 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1098 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
1099 /// materializer resolves per-CR, a per-supervisor dynamic
1100 /// restart-window derivation the future adaptive-supervision engine
1101 /// computes from child-failure-history topology, a promotion of the
1102 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
1103 /// pair once Erlang/OTP's per-child-cohort observation-interval-
1104 /// partition slot comes into scope) would have had to be threaded
1105 /// through every open-coded copy in lockstep or the validate gate and
1106 /// the future M4 emit path would silently disagree on which
1107 /// restart-window a given supervisor resolves to — an author's
1108 /// `:restart-window "60s"` would satisfy validate while the emit path
1109 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
1110 /// authored slot at the emit boundary would carry the author's
1111 /// declared window verbatim in `feira lint` output while the future
1112 /// wasm-operator's restart-intensity counter operated under a
1113 /// drifted window, or vice versa: an author's `:restart-window ()`
1114 /// would carry the "never reset" sentinel through validate while the
1115 /// emit path silently substituted a default sliding window), a
1116 /// two-consumer split at the validator far from the source
1117 /// `caixa.lisp` with no field naming the restart-window-drift root
1118 /// cause. Lifting the resolution rule to a typed method on the
1119 /// substrate primitive means every downstream consumer of the
1120 /// Supervisor's per-`:supervisor` restart-intensity-denominator
1121 /// surface reaches for exactly one typed dispatch — the resolver's
1122 /// accept-set migrates as a unit on any future axis addition.
1123 ///
1124 /// Third `Copy`-return accessor on the M2 supervisor-slot
1125 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
1126 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
1127 /// payload rather than a `Copy`-scalar, and the per-`:children`
1128 /// [`crate::ChildSpec::nome`] (57c61d0) /
1129 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1130 /// scalar accessors already close the per-element `String`-carry
1131 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
1132 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
1133 /// per-outermost-call wall-clock-deadline axis and the peer M3
1134 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
1135 /// accessor on the `:politicas` slot's per-call-deadline axis — all
1136 /// three share the shared substrate concept "a `Copy`-projected
1137 /// optional `Duration` that carries a positive integer-millisecond
1138 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
1139 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
1140 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
1141 /// bracket-helper the three axes each route through. Named
1142 /// `restart_window()` to match the storage field's name verbatim and
1143 /// the peer [`crate::LimitsSpec::wall_clock`] /
1144 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
1145 /// accessor's identity maps onto the canonical OTP-shape supervision
1146 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
1147 /// already carries.
1148 #[must_use]
1149 pub const fn restart_window(&self) -> Option<Duration> {
1150 self.restart_window
1151 }
1152
1153 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
1154 /// static-child-list slice accessor every consumer that walks the
1155 /// supervisor's declared child set keys off — returns the author-
1156 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
1157 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
1158 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
1159 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
1160 /// through). Non-optional: an empty slice is the load-bearing
1161 /// "author declared `:children ()`" sentinel every consumer of the
1162 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
1163 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
1164 /// three strategies require a non-empty slice — the paired
1165 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
1166 /// [`SupervisorError::NoChildren`] refusal cascade pins the
1167 /// partition on both arms).
1168 ///
1169 /// The `:supervisor :children` slot carries the OTP-shaped static
1170 /// child list the supervisor materializes one ComputeUnit per
1171 /// entry from — the Erlang/OTP `supervisor:init/1`'s
1172 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
1173 /// through the tatara-lisp `:children` author surface onto a typed
1174 /// `Vec<ChildSpec>` whose per-element `(nome(),
1175 /// versao_requirement(), restart)` triple the per-child
1176 /// [`SupervisorSpec::validate`] loop already gates through the
1177 /// lifted [`ChildSpec::nome`] (57c61d0) /
1178 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
1179 /// Every downstream consumer that fans on the static child list
1180 /// keys off this slice (the [`SupervisorSpec::validate`]
1181 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
1182 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
1183 /// per-child DNS-1123 / semver-requirement / duplicate-detection
1184 /// fan-out loop, every future wasm-operator (M3) per-supervisor
1185 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
1186 /// materialization loop, the future M4
1187 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1188 /// admission-webhook fan-out, the future `feira app graph`
1189 /// per-supervisor tree-print traversal).
1190 ///
1191 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
1192 /// inline at three production sites in `caixa-core/src/supervisor.rs`
1193 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
1194 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
1195 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
1196 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
1197 /// validate loop's `for child in &self.children` traversal head —
1198 /// three open-coded field-accesses that expressed no compile-time
1199 /// link back to the typed slot. A future extension of the
1200 /// `:supervisor :children` axis to a richer author surface (a
1201 /// per-cluster child-set overlay the operator pins through a future
1202 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
1203 /// supervision-canary roadmap acknowledges, a per-tenant
1204 /// child-set-alias table the M4 CR materializer resolves per-CR,
1205 /// a per-supervisor dynamic-child derivation the future adaptive-
1206 /// supervision engine computes from child-failure-history topology,
1207 /// a promotion of the plain `Vec<ChildSpec>` to a richer
1208 /// `{static, dynamic}` partition once Erlang/OTP's
1209 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
1210 /// would have had to be threaded through all three open-coded copies
1211 /// in lockstep or one consumer would silently disagree with the
1212 /// peers on which child-set a given supervisor resolves to — the
1213 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
1214 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
1215 /// would silently split the partition-dispatch's two-arm coherence
1216 /// (a supervisor that satisfies neither arm's precondition, or that
1217 /// satisfies both, at the cost of the paired
1218 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
1219 /// silently drifting from the per-child validate loop's actual
1220 /// traversal input), a three-consumer split at the validator far
1221 /// from the source `caixa.lisp` with no field naming the
1222 /// child-set-drift root cause. Lifting the resolution rule to a
1223 /// typed method on the substrate primitive means every downstream
1224 /// consumer of the Supervisor's per-`:supervisor` static-child-list
1225 /// surface reaches for exactly one typed dispatch — the resolver's
1226 /// accept-set migrates as a unit on any future axis addition.
1227 ///
1228 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
1229 /// — the seed for the same "one typed dispatch on the substrate
1230 /// primitive, thin projections at each consumer" discipline the
1231 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
1232 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
1233 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
1234 /// onto the first `Vec`-carry axis on the substrate. The four peer
1235 /// `Vec`-carry axes still unlifted at the time of this seed —
1236 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
1237 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
1238 /// (`Vec<Membro>` per-Aplicacao member list),
1239 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
1240 /// per-Aplicacao WIT-typed edge list),
1241 /// [`crate::UpgradeFromEntry::instructions`]
1242 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
1243 /// — inherit this accessor's discipline as future compounding runs
1244 /// migrate their consumers onto the shared slice-return shape.
1245 /// Fourth (and final) accessor on the M2 supervisor-slot
1246 /// `SupervisorSpec` type, sibling to the three `Copy`-return
1247 /// [`SupervisorSpec::estrategia`] (eafb619) /
1248 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
1249 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
1250 /// the last unlifted per-`:supervisor` field axis (the
1251 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
1252 /// per-`:supervisor` reader now routes through a typed dispatch on
1253 /// the substrate primitive. Named `children()` to match the storage
1254 /// field's name verbatim and the tatara-lisp author-surface term
1255 /// (`:children`) the field's own docstring already carries; the
1256 /// accessor's identity maps onto the canonical OTP-shape
1257 /// supervision vocabulary the [`SupervisorSpec::children`] field's
1258 /// docstring already reaches for ("Static children ..."). Returns
1259 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
1260 /// consumer of the child list treats it as a read-only sequence —
1261 /// the slice-view is the narrowest borrow that supports every
1262 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
1263 /// index, `.len()`) without leaking the backing `Vec`'s
1264 /// grow/push/reserve surface that no consumer of the typed view
1265 /// reaches for (the storage-side `Vec` remains reachable through
1266 /// the `pub children` field for the mutation-carrying
1267 /// `Caixa::supervisor_view` fold-in path in
1268 /// `manifest.rs:supervisor_view`).
1269 #[must_use]
1270 pub fn children(&self) -> &[ChildSpec] {
1271 self.children.as_slice()
1272 }
1273
1274 /// Validate the supervisor's typed shape — strategy ↔ children
1275 /// invariants, max_restarts > 0, restart_window > 0 when set,
1276 /// per-child non-empty + duplicate-free names.
1277 ///
1278 /// Mirrors the value-shape discipline applied to every other
1279 /// typed slot:
1280 ///
1281 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
1282 /// same "0 means the opposite of what you think" footgun
1283 /// closed for `:politicas :timeout` (Envoy interprets a zero
1284 /// timeout as `infinite`), `:politicas :circuit-breaker
1285 /// :window`, and `:limits :wall-clock`. The
1286 /// `MaxIntensity / Period` ratio in Erlang/OTP's
1287 /// `supervisor` requires `Period > 0`; a zero period either
1288 /// trips on the first failure or never trips depending on
1289 /// operator interpretation, neither of which is the
1290 /// author's intent. Omit `:restart-window` to express "no
1291 /// reset"; carry a positive duration to express the window.
1292 /// - duplicate `:children` `:caixa` names are the same
1293 /// graph-node-set / multiset distinction closed for
1294 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
1295 /// and `:entrada :paths` (eb3456d). Two children with the
1296 /// same `:caixa` materialize as two ComputeUnits with the
1297 /// same name in the cluster's HelmRelease values, one
1298 /// silently overwriting the other. Erlang/OTP's
1299 /// `child_spec.id` is required-unique per supervisor;
1300 /// pleme-io enforces the same set-not-multiset shape on
1301 /// `:caixa` (the load-bearing identity in our renderer).
1302 pub fn validate(&self) -> Result<(), SupervisorError> {
1303 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
1304 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
1305 // error carrier's `estrategia:` field through the lifted
1306 // [`SupervisorSpec::estrategia`] accessor rather than the raw
1307 // `self.estrategia` field access — the two production consumers
1308 // of the per-`:supervisor` sibling-restart-strategy scalar now
1309 // key off exactly one typed dispatch on the substrate primitive,
1310 // so any future rebrand on the axis (a per-cluster strategy
1311 // override the operator pins through a future `:supervisor
1312 // :estrategia-overrides` slot, a per-tenant strategy-alias table
1313 // the M4 CR materializer resolves per-CR) migrates as a single
1314 // caixa-core edit rather than a coordinated rewrite of the two
1315 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
1316 // (921fe1b) four-consumer migration on the per-`:placement`
1317 // distribution-strategy axis.
1318 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
1319 // dispatch's paired `.is_empty()` cross-slot refusal probes
1320 // (the `SimpleOneForOne`-arm
1321 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
1322 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
1323 // refusal) through the lifted [`SupervisorSpec::children`]
1324 // slice-return accessor rather than the raw `self.children`
1325 // field access — the two paired production consumers of the
1326 // per-`:supervisor` static-child-list scalar-shape now key off
1327 // exactly one typed dispatch on the substrate primitive, so any
1328 // future rebrand on the axis (a per-cluster child-set overlay
1329 // the operator pins through a future `:supervisor
1330 // :children-overrides` slot, a per-tenant child-set-alias table
1331 // the M4 CR materializer resolves per-CR) migrates as a single
1332 // caixa-core edit rather than a coordinated rewrite of the
1333 // paired arms — first slice-return migration on any typed slot,
1334 // seed for the peer per-`:placement :clusters`,
1335 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
1336 // :instructions` `Vec`-carry axes.
1337 match self.estrategia() {
1338 RestartStrategy::SimpleOneForOne => {
1339 // SimpleOneForOne: children added at runtime. Static
1340 // list must be empty (one shape declared elsewhere).
1341 if !self.children().is_empty() {
1342 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
1343 }
1344 }
1345 _ => {
1346 if self.children().is_empty() {
1347 return Err(SupervisorError::NoChildren {
1348 estrategia: self.estrategia(),
1349 });
1350 }
1351 }
1352 }
1353 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
1354 // axis. See [`crate::render::require_positive_bounded_u32`] for
1355 // the ordering discipline (zero-floor arm strictly precedes cap
1356 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
1357 // diagnostic with its counter-axis remediation directly named,
1358 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
1359 // cap-arm miss). Until this bracket landed the top edge ran all
1360 // the way to `u32::MAX` and a struct-literal
1361 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
1362 // equivalent author-surface `:max-restarts 100000` /
1363 // `:max-restarts 4294967295` typo landing in the slot) silently
1364 // passed validate. The runtime substrate consuming the value
1365 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
1366 // wasm-operator's per-supervisor restart-intensity counter, the
1367 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1368 // admission webhook) then turned a typed `:max-restarts`
1369 // policy into a no-op supervisor: the escalation threshold is
1370 // structurally so high that no realistic
1371 // restarts-per-`:restart-window` traffic shape can reach it,
1372 // the supervisor never escalates to its parent, and a bad
1373 // child can loop inside the window indefinitely with the
1374 // parent supervisor structurally never receiving the "this
1375 // subtree has exceeded its restart budget" signal the typed
1376 // slot is meant to express. The bracket set is
1377 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
1378 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
1379 // the sibling `:politicas :circuit-breaker :max-failures` axis:
1380 // both are "trip the next-higher protection layer after N
1381 // events in a rolling window" counters with identical
1382 // degenerate-at-the-high-end shape and now share one canonical
1383 // bracket helper. The bracket precedes the sibling
1384 // `:restart-window` zero-floor / canonical-millisecond arms so
1385 // an over-cap `max_restarts` paired with a structurally invalid
1386 // window surfaces the bracket diagnostic first, mirroring the
1387 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
1388 // ordering on the peer `:politicas :circuit-breaker` slot.
1389 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
1390 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
1391 // accessor rather than the raw `self.max_restarts` field access —
1392 // the one production consumer of the per-`:supervisor`
1393 // restart-budget-count scalar now keys off exactly one typed
1394 // dispatch on the substrate primitive, so any future rebrand on
1395 // the axis (a per-cluster restart-budget override the operator
1396 // pins through a future `:supervisor :max-restarts-overrides`
1397 // slot, a per-tenant restart-budget-alias table the M4 CR
1398 // materializer resolves per-CR) migrates as a single caixa-core
1399 // edit rather than a coordinated rewrite — sibling of the peer M3
1400 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
1401 // the per-`:politicas :circuit-breaker :max-failures` axis.
1402 crate::render::require_positive_bounded_u32(
1403 self.max_restarts(),
1404 SUPERVISOR_MAX_RESTARTS_MAX,
1405 || SupervisorError::ZeroMaxRestarts,
1406 |max_restarts| SupervisorError::MaxRestartsExceedsCap { max_restarts },
1407 )?;
1408 // Route the [`SupervisorSpec::validate`] `:restart-window`
1409 // zero-floor + integer-millisecond canonical-form + upper-cap
1410 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
1411 // accessor rather than the raw `self.restart_window` field access —
1412 // the one production consumer of the per-`:supervisor`
1413 // restart-intensity-denominator scalar now keys off exactly one
1414 // typed dispatch on the substrate primitive, so any future rebrand
1415 // on the axis (a per-cluster restart-window override the operator
1416 // pins through a future `:supervisor :restart-window-overrides`
1417 // slot, a per-tenant restart-window-alias table the M4 CR
1418 // materializer resolves per-CR) migrates as a single caixa-core
1419 // edit rather than a coordinated rewrite — sibling of the peer M2
1420 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
1421 // on the per-`:limits :wall-clock` axis and the peer M3
1422 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
1423 // per-`:politicas :timeout` axis.
1424 if let Some(w) = self.restart_window() {
1425 // Zero-floor + integer-millisecond canonical-form +
1426 // upper-cap bracket on the typed `:restart-window` axis.
1427 // See
1428 // [`crate::render::require_positive_canonical_bounded_duration`]
1429 // for the full three-arm ordering discipline (zero-floor
1430 // strictly precedes canonical-form so `Duration::ZERO`
1431 // surfaces the self-locating `RestartWindowZero`
1432 // diagnostic; canonical-form strictly precedes the cap arm
1433 // so a sub-millisecond above-cap value surfaces the more
1434 // fundamental round-trip-shape diagnostic first) and the
1435 // three peer typed-`Duration` sites that share this
1436 // canonical bracket ([`crate::MeshPolicy::timeout`],
1437 // [`crate::CircuitBreaker::window`],
1438 // [`crate::LimitsSpec::wall_clock`]). Every validated
1439 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1440 // (1ms..=1h), integer-millisecond granularity.
1441 crate::render::require_positive_canonical_bounded_duration(
1442 w,
1443 SUPERVISOR_RESTART_WINDOW_MAX,
1444 || SupervisorError::RestartWindowZero,
1445 |window| SupervisorError::RestartWindowNotCanonical { window },
1446 |window| SupervisorError::RestartWindowExceedsCap { window },
1447 )?;
1448 }
1449 // Route the per-child DNS-1123 / semver-requirement / duplicate-
1450 // detection fan-out loop's traversal head through the lifted
1451 // [`SupervisorSpec::children`] slice-return accessor rather than
1452 // the raw `self.children` field access — the third production
1453 // consumer of the per-`:supervisor` static-child-list surface
1454 // now keys off exactly one typed dispatch on the substrate
1455 // primitive. Paired with the sibling `SimpleOneForOne ↔
1456 // non-SimpleOneForOne` partition-dispatch two-arm probe above
1457 // to close the third and final open-coded `.children` field
1458 // access in [`SupervisorSpec::validate`], so a future extension
1459 // of the axis migrates as a single caixa-core edit rather than
1460 // a coordinated rewrite of three call sites.
1461 let mut seen = std::collections::HashSet::new();
1462 for child in self.children() {
1463 // Every emitted cluster artifact's `metadata.name` for a
1464 // supervised child derives from this `:children :caixa` value
1465 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
1466 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
1467 // label value on every child's pod identity, and the per-
1468 // child K8s [`Service`][svc] `metadata.name` the future
1469 // wasm-operator (M3) provisions for inter-child supervision
1470 // tree wiring. Each apiserver-side schema on each landing
1471 // site enforces the DNS-1123 label rule on admission; a
1472 // structurally invalid child name (`"Worker"`, `"my_worker"`,
1473 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
1474 // UUID-shaped mistaken-identity slug) silently passes the
1475 // prior empty-/duplicate-only gate and the failure surfaces
1476 // at `kubectl apply` time as a `metadata.name: Invalid value`
1477 // rejection, far from the source caixa.lisp, with no field
1478 // naming the offending `:children` entry. Lifting the gate
1479 // to caixa-build time mirrors the `:membros :caixa` value-
1480 // shape trajectory (3f9d7a0) and the `:placement :clusters`
1481 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
1482 // identifier axis — the supervisor tree's child names —
1483 // through the lifted
1484 // [`crate::render::require_valid_dns_1123_label`] gate the
1485 // seven peer name axes (`:membros :caixa`, `:placement
1486 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
1487 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
1488 // route through, so drift between the eight axes' accepted
1489 // DNS-1123-label sets is structurally impossible.
1490 //
1491 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
1492 crate::render::require_valid_dns_1123_label(
1493 child.nome(),
1494 || SupervisorError::EmptyChildName,
1495 |reason| SupervisorError::ChildCaixaInvalid {
1496 caixa: child.nome().to_string(),
1497 reason,
1498 },
1499 )?;
1500 // The author surface for `:children :versao` is the same
1501 // Cargo-shaped semver requirement string `:deps :versao` and
1502 // `:membros :versao` carry — and the lacre pipeline resolves
1503 // all three axes through the same
1504 // [`crate::version::parse_requirement`] entry-point. The
1505 // shared [`crate::render::require_valid_versao_requirement`]
1506 // helper brackets the empty-first + parse cascade both peer
1507 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
1508 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
1509 // :versao`) route through, so drift between the three axes'
1510 // accepted requirement sets is structurally impossible and
1511 // the parse-side no-op the empty-first arm closes (semver's
1512 // empty parse yields an implicit `*`) lives in exactly one
1513 // predicate. Every `ChildSpec::versao` past validate is
1514 // round-trippable through [`crate::parse_requirement`]
1515 // without re-checking at the resolver layer, and the three
1516 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
1517 // are now structurally equivalent by construction.
1518 crate::render::require_valid_versao_requirement(
1519 child.versao_requirement(),
1520 || SupervisorError::EmptyChildVersion {
1521 caixa: child.nome().to_string(),
1522 },
1523 |reason| SupervisorError::ChildVersaoInvalid {
1524 caixa: child.nome().to_string(),
1525 versao: child.versao_requirement().to_string(),
1526 reason,
1527 },
1528 )?;
1529 crate::render::insert_first_seen(&mut seen, child.nome(), || {
1530 SupervisorError::DuplicateChildCaixa {
1531 caixa: child.nome().to_string(),
1532 }
1533 })?;
1534 }
1535 Ok(())
1536 }
1537}
1538
1539/// Cross-slot coherence gate on the supervision tree: no
1540/// `:children :caixa` entry may name the supervisor's own `:nome`.
1541///
1542/// A supervisor that lists itself as a child is a degenerate self-parent
1543/// — the supervision tree is a DAG rooted at the supervisor (OTP child
1544/// specs reference *distinct* child processes; a supervisor is never its
1545/// own child), and the wasm-operator's hierarchical reconciliation would
1546/// otherwise be handed a node that is its own parent: a one-node cycle it
1547/// either rejects far from the source `caixa.lisp` or recurses on. Because
1548/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
1549/// lacre closure root), a child whose `:caixa` equals the supervisor's
1550/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
1551///
1552/// Lives outside [`SupervisorSpec::validate`] because the typed view
1553/// carries the children but not the parent `:nome`; mirrors the
1554/// cross-slot precedence gate `validate_upgrade_from_against_versao`
1555/// (which likewise reads one slot against another at the
1556/// [`crate::layout`] wire-up site) and the mesh self-edge gate
1557/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
1558/// node to itself is structurally not a tree/mesh edge" discipline, here
1559/// on the supervision-tree axis.
1560pub fn validate_no_self_supervision(
1561 children: &[ChildSpec],
1562 parent_nome: &str,
1563) -> Result<(), SupervisorError> {
1564 for child in children {
1565 if child.nome() == parent_nome {
1566 return Err(SupervisorError::ChildSupervisesSelf {
1567 caixa: parent_nome.to_string(),
1568 });
1569 }
1570 }
1571 Ok(())
1572}
1573
1574#[derive(Debug, Error, PartialEq, Eq)]
1575pub enum SupervisorError {
1576 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
1577 NoChildren { estrategia: RestartStrategy },
1578 #[error(
1579 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
1580 )]
1581 SimpleOneForOneWithStaticChildren,
1582 #[error(":max-restarts must be > 0")]
1583 ZeroMaxRestarts,
1584 #[error(
1585 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
1586 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
1587 restart-intensity policy into a no-op supervisor: the escalation threshold is \
1588 structurally so high that no realistic restarts-per-:restart-window traffic shape \
1589 can reach it, so the supervisor never escalates to its parent and a bad child can \
1590 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
1591 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
1592 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
1593 materializer's admission webhook) emits a `:max-restarts` declaration that is \
1594 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
1595 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
1596 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
1597 band) or restructure the supervision tree (split the flaky child into its own \
1598 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
1599 )]
1600 MaxRestartsExceedsCap { max_restarts: u32 },
1601 #[error(
1602 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
1603 requires Period > 0; a zero window either trips on the first failure or \
1604 never trips depending on operator interpretation. Omit :restart-window to \
1605 express `never reset`; carry a positive duration to express the window."
1606 )]
1607 RestartWindowZero,
1608 #[error(
1609 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
1610 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
1611 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
1612 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
1613 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
1614 )]
1615 RestartWindowNotCanonical { window: Duration },
1616 #[error(
1617 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
1618 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
1619 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
1620 failure-counting window is structurally so long that transient restarts are never \
1621 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
1622 when the child has exceeded its restart budget within the recent window` to `trip the \
1623 parent when the child has exceeded its restart budget over its lifetime`, and the \
1624 supervisor's reset semantic never reaches the child — every typed-slot consumer \
1625 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
1626 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
1627 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
1628 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
1629 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
1630 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
1631 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
1632 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
1633 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
1634 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
1635 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
1636 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
1637 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
1638 hiding it behind a rolling-window declaration the cap arm rejects)"
1639 )]
1640 RestartWindowExceedsCap { window: Duration },
1641 #[error("child entry has empty :caixa name")]
1642 EmptyChildName,
1643 #[error(
1644 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
1645 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
1646 name / label value the child name lands in — the per-child \
1647 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
1648 label value, and the future wasm-operator per-child Service `metadata.name` \
1649 — each apiserver-side schema rejects names that don't match; use a \
1650 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
1651 )]
1652 ChildCaixaInvalid { caixa: String, reason: String },
1653 #[error("child {caixa:?} has empty :versao constraint")]
1654 EmptyChildVersion { caixa: String },
1655 #[error(
1656 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
1657 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
1658 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
1659 `:membros :versao` carry; the lacre pipeline resolves all three \
1660 through the same parser)"
1661 )]
1662 ChildVersaoInvalid {
1663 caixa: String,
1664 versao: String,
1665 reason: String,
1666 },
1667 #[error(
1668 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
1669 child_spec.id per supervisor; duplicate children materialize as duplicate \
1670 ComputeUnits in the rendered chart, one silently overwriting the other)"
1671 )]
1672 DuplicateChildCaixa { caixa: String },
1673 #[error(
1674 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
1675 never its own child (the supervision tree is a DAG rooted at the supervisor; \
1676 OTP child specs reference distinct child processes). Since every :nome is a \
1677 globally-unique substrate identity, a child naming the supervisor's own :nome \
1678 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
1679 self-referential :children entry or rename it to the actual child caixa."
1680 )]
1681 ChildSupervisesSelf { caixa: String },
1682}
1683
1684/// Shared duration string codec for the typed slots that take a
1685/// duration (`restart_window`, `MeshPolicy::timeout`,
1686/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
1687/// reuse it without duplicating the parser.
1688pub mod duration_codec {
1689 use super::Duration;
1690 use serde::{Deserialize, Deserializer, Serializer};
1691
1692 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
1693 match v {
1694 Some(d) => s.serialize_str(&render(*d)),
1695 None => s.serialize_none(),
1696 }
1697 }
1698
1699 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
1700 let opt: Option<String> = Option::deserialize(d)?;
1701 match opt {
1702 None => Ok(None),
1703 Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
1704 }
1705 }
1706
1707 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
1708 // Whitespace-rejection arm — peer with the leading-`+` /
1709 // fractional-magnitude arm below (`"+30s"`, `"1.5s"`) and the
1710 // leading-zero arm below (`"030s"`) on the same canonical-form
1711 // render-determinism axis. Until this gate landed the parser
1712 // silently tolerated leading / trailing / internal whitespace
1713 // via the top-level `s.trim()` at parse entry and the per-part
1714 // `num_part.trim()` / `unit.trim()` calls below, so every
1715 // whitespace-carrying shape (`" 30s"` — paste-from-aligned-doc
1716 // / YAML-quoted-plain-scalar leading-space; `"30s "` —
1717 // paste-from-shell-history trailing-space; `"30 s"` —
1718 // paste-from-typography whitespace-between-magnitude-and-unit;
1719 // `"30\ts"` — peer tab byte between magnitude and unit;
1720 // `"30s\n"` — trailing newline from a multi-line paste;
1721 // `"\t30s"` — paste-from-indented-doc / YAML-block-scalar tab
1722 // byte) parsed to the same `Duration::from_secs(30)` and serde
1723 // silently round-tripped to `"30s"` on the next emit (a
1724 // *different* canonical string) — breaking the THEORY.md Part V
1725 // render-determinism contract on three typed-duration slots at
1726 // once (`:supervisor :restart-window`, `:politicas :timeout`,
1727 // `:politicas :circuit-breaker :window`) via the shared codec.
1728 //
1729 // The canonical author shape is `<integer><unit>` (or
1730 // `<integer>` for the bare-integer-as-seconds shorthand) with
1731 // no whitespace bytes anywhere — every string [`render`] emits
1732 // carries none, so the parser's accepted set must match for
1733 // serialize / deserialize to round-trip losslessly. This gate
1734 // makes the pre-existing `s.trim()` / `num_part.trim()` /
1735 // `unit.trim()` calls below strict no-ops on the accepted set
1736 // (every byte-position match they would perform is now already
1737 // trimmed away by the accepted set itself), while the arm
1738 // surfaces every rejected whitespace-carrying shape with a
1739 // self-locating diagnostic naming the offending byte and the
1740 // canonical form the author intended, peer with every prior
1741 // canonical-form-drift arm on this codec.
1742 //
1743 // Routed through the lifted
1744 // [`crate::render::find_ascii_whitespace_byte`] predicate —
1745 // the same source of truth the four peer typed-magnitude
1746 // codec sites (`limits::parse_byte_size`,
1747 // `limits::parse_duration`, `limits::parse_millicores`,
1748 // `rate_limit_codec`) share. `u8::is_ascii_whitespace()` at
1749 // the predicate covers the five WhatWG-conformant ASCII
1750 // whitespace bytes (space, tab, LF, FF, CR); the "single
1751 // lifted predicate" discipline the peer non-ASCII arm below
1752 // carries on the strictly-complementary Unicode `White_Space`
1753 // class extends here to the ASCII byte set as well. Covers
1754 // three typed-duration slots at once through the shared
1755 // codec: `:supervisor :restart-window`, `:politicas
1756 // :timeout`, and `:politicas :circuit-breaker :window`.
1757 if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
1758 return Err(format!(
1759 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
1760 authoring form for the typed duration slots routed through this shared codec \
1761 (`:supervisor :restart-window`, `:politicas :timeout`, \
1762 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
1763 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
1764 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
1765 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
1766 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
1767 Part V render-determinism contract every typed slot carries. Strip every \
1768 whitespace byte (write `\"30s\"` verbatim)"
1769 ));
1770 }
1771 // Non-ASCII Unicode `White_Space` arm — the strictly-
1772 // complementary class the ASCII arm above cannot see.
1773 // `str::trim` at the top of every peer codec uses
1774 // `char::is_whitespace` (Unicode `White_Space`, strictly wider
1775 // than the ASCII byte set), so an NBSP (`\u{00A0}`) / LINE
1776 // SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`) survives the
1777 // byte-scan (its UTF-8 bytes are not in `is_ascii_whitespace`),
1778 // gets silently stripped by the top-level `s.trim()` below,
1779 // and the value round-trips through `render` to a *different*
1780 // canonical form (`\"30s\"`) on next emit — breaking the
1781 // THEORY.md Part V render-determinism contract on three typed
1782 // duration slots at once (`:supervisor :restart-window`,
1783 // `:politicas :timeout`, `:politicas :circuit-breaker
1784 // :window`) via the shared codec. Closed here and at the
1785 // three peer codec sites (`limits::parse_byte_size`,
1786 // `limits::parse_duration`, `rate_limit_codec`) through the
1787 // shared [`crate::render::find_non_ascii_whitespace_char`]
1788 // predicate — the "single lifted predicate across all four
1789 // codec sites in one follow-up run" the 24a8ad4 commit body's
1790 // `Forward compounding` bullet named as the next compounding
1791 // step.
1792 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
1793 return Err(format!(
1794 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
1795 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
1796 duration slots routed through this shared codec (`:supervisor \
1797 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
1798 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
1799 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
1800 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
1801 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
1802 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
1803 `White_Space` property, strictly wider than the ASCII byte set) silently \
1804 strips it at parse entry, and the value round-trips through `render` to \
1805 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
1806 the THEORY.md Part V render-determinism contract every typed slot \
1807 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
1808 verbatim with only ASCII bytes)",
1809 cp = ch as u32
1810 ));
1811 }
1812 let s = s.trim();
1813 let split = s.find(|c: char| c.is_ascii_alphabetic()).unwrap_or(s.len());
1814 let (num_part, unit) = s.split_at(split);
1815 let num_trim = num_part.trim();
1816 // The canonical authoring form for every typed slot routed
1817 // through this shared codec — `:supervisor :restart-window`,
1818 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
1819 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
1820 // non-negative integer with no decimal point and no leading
1821 // sign, so the parser's accepted set must match for
1822 // serialize/deserialize to round-trip without canonical-form
1823 // drift. Until this gate landed the parser accepted any
1824 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
1825 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
1826 // tripped the value to a *different* canonical string on the
1827 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
1828 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
1829 // — breaking the THEORY.md Part V render-determinism contract
1830 // on three typed slots at once. Same canonical-form discipline
1831 // `crate::limits::parse_duration` (818dd38, the immediate
1832 // predecessor on the peer `:limits :wall-clock` codec) applies;
1833 // this gate lifts the discipline onto the shared codec that
1834 // backs the remaining three typed-duration slots in caixa-core.
1835 //
1836 // Strict canonical form: every byte of the magnitude is an
1837 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
1838 // inputs the gate distinguishes "non-canonical-but-numeric"
1839 // (parses as f64 or i64 — surfaced with a self-locating
1840 // diagnostic naming the canonical authoring form, the
1841 // round-trip drift each rejected shape would produce on first
1842 // serialize, and the canonical-form remediation) from
1843 // "garbage" (parses as neither — surfaced with the existing
1844 // narrower "bad duration magnitude" wording so its diagnostic
1845 // shape remains stable for the parser-shape footgun case).
1846 // The pre-existing `num < 0.0` arm is now unreachable — the
1847 // digit-only gate strictly precedes magnitude parsing, and a
1848 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
1849 // non-canonical-but-numeric branch with the `-30` named
1850 // verbatim in the diagnostic rather than the prior
1851 // value-laundered "negative duration in \"-30s\"" wording.
1852 //
1853 // Routed through the lifted
1854 // [`crate::render::is_digit_only_magnitude`] predicate — the
1855 // same source of truth the four peer typed-magnitude codec
1856 // sites share.
1857 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
1858 if !digit_only {
1859 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
1860 if numeric {
1861 return Err(format!(
1862 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
1863 canonical authoring form for the typed duration slots routed through \
1864 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
1865 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
1866 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
1867 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
1868 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
1869 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
1870 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
1871 THEORY.md Part V render-determinism contract every typed slot carries. \
1872 Pick an integer magnitude in the unit that divides cleanly (write \
1873 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
1874 ));
1875 }
1876 return Err(format!("bad duration magnitude in {s:?}"));
1877 }
1878 // Leading-zero arm — peer with the `rate_limit_codec` leading-
1879 // zero arm (4f46830) on the same canonical-form render-
1880 // determinism axis. The digit-only gate accepts `"030s"`,
1881 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
1882 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
1883 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
1884 // *different* canonical string on the next emit, breaking the
1885 // THEORY.md Part V render-determinism contract the same way
1886 // `"+30s"` did before the leading-`+` arm landed. The single-
1887 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
1888 // losslessly through `render` (`render(Duration::ZERO)` emits
1889 // `"0s"`) — the downstream semantic-zero gates (e.g.
1890 // `SupervisorError::ZeroRestartWindow` on
1891 // `:supervisor :restart-window`,
1892 // `AplicacaoError::PolicyTimeoutZero` /
1893 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
1894 // duration slots) refuse zero-magnitude authoring at the typed-
1895 // validate layer above, so the single-byte `"0"` stays in the
1896 // accepted set at this codec layer and the diagnostic
1897 // partitioning between canonical-form drift (this arm) and
1898 // semantic-zero (the downstream gates) remains stable.
1899 // Peer with the future leading-zero arms on the two remaining
1900 // typed-magnitude codecs the trajectory acknowledges:
1901 // `limits::parse_duration` backing `:limits :wall-clock`,
1902 // `limits::parse_byte_size` backing `:limits :memory` — each
1903 // carries the same canonical-form-drift class today; this
1904 // gate lands the discipline on the shared duration codec
1905 // first because the `rate_limit_codec` predecessor on the
1906 // same canonical-form-drift axis is the closest peer on the
1907 // trajectory.
1908 //
1909 // Routed through the lifted
1910 // [`crate::render::is_leading_zero_padded_magnitude`]
1911 // predicate — the same source of truth the four peer
1912 // typed-magnitude codec sites share.
1913 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
1914 return Err(format!(
1915 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
1916 canonical authoring form for the typed duration slots routed through \
1917 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
1918 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
1919 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
1920 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
1921 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
1922 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
1923 serialize — breaking the THEORY.md Part V render-determinism contract \
1924 every typed slot carries. Strip the leading zeros (write \
1925 `\"30s\"` instead of `\"030s\"`)"
1926 ));
1927 }
1928 // The digit-only gate guarantees every byte is `[0-9]`, and
1929 // the leading-zero arm above guarantees the magnitude is
1930 // either the single byte `"0"` or starts with `[1-9]`, so
1931 // the only way `u64::from_str` can fail here is overflow (the
1932 // magnitude exceeds `u64::MAX`). Surface that with an
1933 // overflow-shaped wording so the diagnostic names the offending
1934 // magnitude verbatim rather than collapsing onto the
1935 // non-canonical arm. The codec now operates on `u64` end-to-end
1936 // — every accepted magnitude is integer-exact; no f64 mantissa
1937 // drift between author-supplied magnitude and the consumer's
1938 // `Duration` value. Same shape `crate::limits::parse_duration`
1939 // (818dd38) carries on the peer `:limits :wall-clock` axis.
1940 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
1941 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
1942 })?;
1943 let unit_trim = unit.trim();
1944 let dur = match unit_trim {
1945 "ms" => Duration::from_millis(num),
1946 "s" | "" => Duration::from_secs(num),
1947 "m" => Duration::from_secs(num.checked_mul(60).ok_or_else(|| {
1948 format!("duration {num}{unit_trim} overflows u64 (magnitude × 60 > 2^64-1)")
1949 })?),
1950 "h" => Duration::from_secs(num.checked_mul(3600).ok_or_else(|| {
1951 format!("duration {num}{unit_trim} overflows u64 (magnitude × 3600 > 2^64-1)")
1952 })?),
1953 other => return Err(format!("unknown duration unit {other:?}")),
1954 };
1955 Ok(dur)
1956 }
1957
1958 /// Render a [`Duration`] in the canonical pleme-io duration string
1959 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
1960 /// caixa typed-duration slot serializes to and the same form K8s
1961 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
1962 /// EnvoyConfig per-route timeouts both expect (an integer
1963 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
1964 /// `+`). Lifted to `pub` so caixa-side renderers
1965 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
1966 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
1967 /// emitter, the future caixa-otel collector pipeline emitter) can
1968 /// consume the same canonical formatter without re-inlining the
1969 /// magnitude/unit decision tree (and inheriting the same drift
1970 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
1971 /// downstream apply-time parsing in non-obvious ways).
1972 pub fn render(d: Duration) -> String {
1973 let total_ms = d.as_millis();
1974 if total_ms == 0 {
1975 return "0s".into();
1976 }
1977 if total_ms % (3600 * 1000) == 0 {
1978 return format!("{}h", total_ms / (3600 * 1000));
1979 }
1980 if total_ms % (60 * 1000) == 0 {
1981 return format!("{}m", total_ms / (60 * 1000));
1982 }
1983 if total_ms % 1000 == 0 {
1984 return format!("{}s", total_ms / 1000);
1985 }
1986 format!("{total_ms}ms")
1987 }
1988
1989 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
1990 ///
1991 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
1992 /// largest divisor unit, so any sub-millisecond residue
1993 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
1994 /// §V.2.7 render-determinism contract:
1995 ///
1996 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
1997 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
1998 /// `1_000_000` ns ≠ original `1_500_000` ns;
1999 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
2000 /// renders the literal `"0s"`, which the per-axis zero-floor gate
2001 /// on every typed-`Duration` slot then rejects on re-validate.
2002 ///
2003 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
2004 /// the codec's round-trippable accepted set lives in exactly one place —
2005 /// every typed-`Duration` slot that routes through this shared codec
2006 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
2007 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
2008 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
2009 /// every typed-`Duration` slot whose own codec shares the same
2010 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
2011 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
2012 /// pair) calls this predicate from its `validate()` to bracket the
2013 /// accepted set against the codec's accepted set, structurally. Drift
2014 /// between the codec's granularity and any typed slot's accepted set is
2015 /// then a single-source-of-truth edit at this predicate rather than a
2016 /// silent round-trip break the next consumer discovers at apply time.
2017 ///
2018 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
2019 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
2020 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
2021 /// family — same "typed-slot's valid set matches its codec's accepted
2022 /// set, structurally" discipline carried at the codec layer.
2023 #[must_use]
2024 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
2025 d.subsec_nanos().is_multiple_of(1_000_000)
2026 }
2027}
2028
2029/// Required-Duration variant for fields that aren't Option<Duration>.
2030pub mod duration_codec_required {
2031 use super::Duration;
2032 use serde::{Deserialize, Deserializer, Serializer};
2033
2034 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
2035 s.serialize_str(&super::duration_codec::render(*v))
2036 }
2037
2038 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
2039 let s = String::deserialize(d)?;
2040 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
2041 }
2042}
2043
2044#[cfg(test)]
2045mod tests {
2046 use super::*;
2047
2048 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
2049 ChildSpec {
2050 caixa: name.into(),
2051 versao: ver.into(),
2052 restart,
2053 }
2054 }
2055
2056 #[test]
2057 fn default_has_one_for_one_and_5_restarts_in_60s() {
2058 let s = SupervisorSpec::default();
2059 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
2060 assert_eq!(s.max_restarts, 5);
2061 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
2062 assert!(s.children.is_empty());
2063 }
2064
2065 #[test]
2066 fn validate_one_for_one_requires_children() {
2067 let mut s = SupervisorSpec::default();
2068 s.children = vec![];
2069 assert!(matches!(
2070 s.validate().unwrap_err(),
2071 SupervisorError::NoChildren { .. }
2072 ));
2073 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
2074 s.validate().unwrap();
2075 }
2076
2077 #[test]
2078 fn validate_simple_one_for_one_forbids_static_children() {
2079 let mut s = SupervisorSpec {
2080 estrategia: RestartStrategy::SimpleOneForOne,
2081 ..SupervisorSpec::default()
2082 };
2083 s.children
2084 .push(child("w", "^0.1", RestartPolicy::Permanent));
2085 assert_eq!(
2086 s.validate().unwrap_err(),
2087 SupervisorError::SimpleOneForOneWithStaticChildren
2088 );
2089 s.children.clear();
2090 s.validate().unwrap();
2091 }
2092
2093 #[test]
2094 fn validate_rejects_zero_max_restarts() {
2095 let s = SupervisorSpec {
2096 max_restarts: 0,
2097 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2098 ..SupervisorSpec::default()
2099 };
2100 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
2101 }
2102
2103 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
2104 //
2105 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
2106 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
2107 // `:supervisor :max-restarts` axis — both fields are "trip the
2108 // next-higher protection layer after N events in a rolling window"
2109 // counters with identical degenerate-at-the-high-end shape, so the
2110 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
2111 // exactly as it lies in `1..=1000` on the breaker side.
2112
2113 #[test]
2114 fn validate_rejects_max_restarts_above_cap() {
2115 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
2116 // 1` is structurally one past the cap and silently passed
2117 // validate on every pre-gate codebase because the typed slot's
2118 // only check was the zero-floor arm. The no-op-supervisor vector
2119 // only surfaced at the runtime substrate (Erlang/OTP
2120 // MaxIntensity/Period ratio, the future wasm-operator's
2121 // per-supervisor restart-intensity counter) far from the source
2122 // caixa.lisp with no field naming the offending supervisor.
2123 let s = SupervisorSpec {
2124 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2125 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2126 ..SupervisorSpec::default()
2127 };
2128 assert_eq!(
2129 s.validate().unwrap_err(),
2130 SupervisorError::MaxRestartsExceedsCap {
2131 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2132 }
2133 );
2134 }
2135
2136 #[test]
2137 fn validate_rejects_max_restarts_far_above_cap() {
2138 // The `u32::MAX` worst case — the four-billion-restart
2139 // threshold a typo (`:max-restarts 4294967295`) or a
2140 // struct-literal copy-paste lands in the slot. Pin the cap
2141 // arm's coverage explicitly across the full `u32` overflow so
2142 // a future relaxation that drops the upper bound surfaces
2143 // here. Same shape every other typed-cap arm on this surface
2144 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
2145 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
2146 let s = SupervisorSpec {
2147 max_restarts: u32::MAX,
2148 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2149 ..SupervisorSpec::default()
2150 };
2151 assert_eq!(
2152 s.validate().unwrap_err(),
2153 SupervisorError::MaxRestartsExceedsCap {
2154 max_restarts: u32::MAX,
2155 }
2156 );
2157 }
2158
2159 #[test]
2160 fn validate_accepts_max_restarts_at_cap() {
2161 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
2162 // must validate. The cap is inclusive on the top edge,
2163 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
2164 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
2165 // discipline on the sibling capped axes. Pin the boundary
2166 // explicitly so a future off-by-one tightening
2167 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
2168 // here as a test failure rather than a silent contract
2169 // narrowing.
2170 let s = SupervisorSpec {
2171 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
2172 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2173 ..SupervisorSpec::default()
2174 };
2175 s.validate()
2176 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
2177 }
2178
2179 #[test]
2180 fn validate_accepts_max_restarts_typical_values() {
2181 // The documented production-playbook band positive-control
2182 // sweep — every value Erlang/OTP / Elixir / Riak Core /
2183 // RabbitMQ recommend (1..=100) must pass, plus a sweep
2184 // through the hyperscale band (200, 500, 1000) the cap
2185 // accepts. Pin the inclusive validated set explicitly so a
2186 // future tightening of the ceiling surfaces here.
2187 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
2188 let s = SupervisorSpec {
2189 max_restarts: n,
2190 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2191 ..SupervisorSpec::default()
2192 };
2193 s.validate()
2194 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
2195 }
2196 }
2197
2198 #[test]
2199 fn zero_max_restarts_takes_precedence_over_cap() {
2200 // The cross-arm ordering pin: `0` is structurally outside
2201 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
2202 // (cap), but the zero-floor diagnostic is the more
2203 // self-locating one (it directly names the counter-axis
2204 // remediation), so the validate gate must fire on zero first.
2205 // Same shape every other zero-then-shape ordering on this
2206 // surface uses (PolicyRetriesZero then
2207 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
2208 // PolicyBreakerMaxFailuresExceedsCap).
2209 let s = SupervisorSpec {
2210 max_restarts: 0,
2211 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2212 ..SupervisorSpec::default()
2213 };
2214 assert_eq!(
2215 s.validate().unwrap_err(),
2216 SupervisorError::ZeroMaxRestarts,
2217 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
2218 );
2219 }
2220
2221 #[test]
2222 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
2223 // The cross-arm ordering pin between the cap and the sibling
2224 // `:restart-window` gates (zero-window, canonical-window). A
2225 // supervisor carrying both an over-cap `max_restarts` AND a
2226 // structurally invalid window (zero, sub-ms) must surface the
2227 // cap diagnostic first — the cap arm is wired immediately
2228 // after the zero-restart arm and strictly before the window
2229 // arms, so the offending value the diagnostic names matches
2230 // the order the author would discover the gates by reading
2231 // top-to-bottom through `SupervisorSpec::validate`. Pin the
2232 // order so a future refactor that reorders the arms surfaces
2233 // here as a test failure rather than a silent diagnostic
2234 // regression. Peer of
2235 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
2236 // on the sibling `:politicas :circuit-breaker` slot.
2237 let s = SupervisorSpec {
2238 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2239 restart_window: Some(Duration::ZERO),
2240 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2241 ..SupervisorSpec::default()
2242 };
2243 assert_eq!(
2244 s.validate().unwrap_err(),
2245 SupervisorError::MaxRestartsExceedsCap {
2246 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
2247 },
2248 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
2249 );
2250 }
2251
2252 #[test]
2253 fn max_restarts_cap_diagnostic_carries_offending_value() {
2254 // The diagnostic-shape pin: the offending `u32` is carried
2255 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
2256 // variant so the surfaced error message names the value the
2257 // author wrote (`":supervisor :max-restarts (50000) exceeds the
2258 // supervisor-policy ceiling …"`), not just the cap. Same
2259 // self-locating diagnostic shape every other typed-cap arm on
2260 // this surface carries
2261 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
2262 // the offending failure count verbatim,
2263 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
2264 // retries count verbatim).
2265 let s = SupervisorSpec {
2266 max_restarts: 50_000,
2267 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2268 ..SupervisorSpec::default()
2269 };
2270 let err = s.validate().unwrap_err();
2271 assert!(
2272 matches!(
2273 err,
2274 SupervisorError::MaxRestartsExceedsCap {
2275 max_restarts: 50_000
2276 }
2277 ),
2278 "got {err:?}"
2279 );
2280 let msg = err.to_string();
2281 assert!(
2282 msg.contains("50000"),
2283 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
2284 );
2285 }
2286
2287 #[test]
2288 fn supervisor_max_restarts_cap_pins_canonical_value() {
2289 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
2290 // 1000 — the same ceiling the peer
2291 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
2292 // `:politicas :circuit-breaker :max-failures` axis (both are
2293 // "trip the next-higher protection layer after N events in a
2294 // rolling window" counters with identical
2295 // degenerate-at-the-high-end shape; uniform top edge so the
2296 // M4 CR materializers and the wasm-operator reconciler reach
2297 // for either field knowing the value is in `1..=1000`). Two
2298 // orders of magnitude above every documented Erlang/OTP /
2299 // Elixir / Riak Core / RabbitMQ production-playbook
2300 // recommendation band and below the clearly-pathological
2301 // "effectively no escalation" floor (10_000, 100_000,
2302 // u32::MAX). Pinning the literal value here surfaces a future
2303 // drift (a relaxation to 10_000, a tightening to 100) as a
2304 // deliberate test edit, not a silent contract narrowing.
2305 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
2306 }
2307
2308 #[test]
2309 fn validate_rejects_empty_child_name() {
2310 let s = SupervisorSpec {
2311 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
2312 ..SupervisorSpec::default()
2313 };
2314 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
2315 }
2316
2317 #[test]
2318 fn validate_rejects_empty_child_version() {
2319 let s = SupervisorSpec {
2320 children: vec![child("w", "", RestartPolicy::Permanent)],
2321 ..SupervisorSpec::default()
2322 };
2323 assert!(matches!(
2324 s.validate().unwrap_err(),
2325 SupervisorError::EmptyChildVersion { .. }
2326 ));
2327 }
2328
2329 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
2330
2331 #[test]
2332 fn validate_rejects_invalid_child_versao_requirement() {
2333 // The fail-before-pass-after pin: a non-empty but malformed
2334 // semver requirement (`"^bad-version"`) silently passed
2335 // `validate()` on every pre-gate codebase because the prior
2336 // shape only refused the empty string. The parse failure
2337 // surfaced far downstream at lacre-resolve time with a
2338 // `semver::Error` that didn't name which `:children` entry
2339 // carried the typo. The new gate moves the check to caixa-build
2340 // time at the source caixa.lisp — the third `:versao` typed
2341 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
2342 // structural parity.
2343 let s = SupervisorSpec {
2344 children: vec![
2345 child("worker", "^0.1", RestartPolicy::Permanent),
2346 child("cache", "^bad-version", RestartPolicy::Transient),
2347 ],
2348 ..SupervisorSpec::default()
2349 };
2350 let err = s.validate().unwrap_err();
2351 assert!(
2352 matches!(
2353 err,
2354 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
2355 if caixa == "cache" && versao == "^bad-version"
2356 ),
2357 "got {err:?}"
2358 );
2359 }
2360
2361 #[test]
2362 fn validate_rejects_child_versao_with_double_caret_typo() {
2363 // `"^^0.1"` is the canonical doubled-caret typo — looks
2364 // Cargo-shaped on first glance but fails the parser because
2365 // semver doesn't accept stacked operators. Pin this
2366 // adjacent-shape footgun explicitly so a future relaxation that
2367 // accepts "looks-canonical-but-isn't" forms surfaces here.
2368 let s = SupervisorSpec {
2369 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
2370 ..SupervisorSpec::default()
2371 };
2372 let err = s.validate().unwrap_err();
2373 assert!(
2374 matches!(
2375 err,
2376 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
2377 if caixa == "worker" && versao == "^^0.1"
2378 ),
2379 "got {err:?}"
2380 );
2381 }
2382
2383 #[test]
2384 fn validate_rejects_child_versao_with_v_prefixed_tag() {
2385 // `"v0.1"` is the canonical "git-tag-shape leaking into the
2386 // semver requirement slot" typo — an author copies the
2387 // publish-side git-tag string verbatim into `:versao`, but
2388 // Cargo's semver parser rejects the leading `v`. Same
2389 // adjacent-shape footgun pinned for `:membros :versao`
2390 // (9888b13).
2391 let s = SupervisorSpec {
2392 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
2393 ..SupervisorSpec::default()
2394 };
2395 let err = s.validate().unwrap_err();
2396 assert!(
2397 matches!(
2398 err,
2399 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
2400 if caixa == "worker" && versao == "v0.1"
2401 ),
2402 "got {err:?}"
2403 );
2404 }
2405
2406 #[test]
2407 fn validate_accepts_canonical_child_versao_forms() {
2408 // The Cargo-shaped requirement forms `:deps :versao` and
2409 // `:membros :versao` already accept via
2410 // `crate::parse_requirement` must pass the children gate
2411 // without re-validating at the resolver layer. Pin every leg so
2412 // a future tightening of the canonical set surfaces here as a
2413 // test failure.
2414 for form in [
2415 "^0.1", // caret — minor-range pin (the most common shape)
2416 "~0.1.2", // tilde — patch-range pin
2417 "0.1.0", // exact — single-version pin
2418 "*", // wildcard — any version (semver::VersionReq::STAR)
2419 ">=0.1, <2", // multi-range — comma-separated comparators
2420 ] {
2421 let s = SupervisorSpec {
2422 children: vec![child("worker", form, RestartPolicy::Permanent)],
2423 ..SupervisorSpec::default()
2424 };
2425 s.validate()
2426 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
2427 }
2428 }
2429
2430 #[test]
2431 fn child_versao_empty_takes_precedence_over_invalid() {
2432 // Order pin: the existing `EmptyChildVersion` diagnostic (which
2433 // doesn't try to parse) fires before the new
2434 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
2435 // `:versao` keeps its narrower error message —
2436 // `parse_requirement` would also reject `""`, but the
2437 // empty-string arm is the more self-locating diagnostic for the
2438 // author. Same ordering discipline as
2439 // `membro_versao_empty_takes_precedence_over_invalid` in
2440 // aplicacao.rs.
2441 let s = SupervisorSpec {
2442 children: vec![child("worker", "", RestartPolicy::Permanent)],
2443 ..SupervisorSpec::default()
2444 };
2445 let err = s.validate().unwrap_err();
2446 assert!(
2447 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
2448 "got {err:?}"
2449 );
2450 }
2451
2452 #[test]
2453 fn child_versao_invalid_fires_before_duplicate_check() {
2454 // Order pin: a malformed requirement on a non-duplicate entry
2455 // surfaces *its own* diagnostic (which names the offending
2456 // `:versao` string), even when a later entry would otherwise
2457 // collapse onto an earlier name. The per-entry shape gate runs
2458 // inline before the duplicate-key insert — parallel to
2459 // `membro_versao_invalid_fires_before_duplicate_check` in
2460 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
2461 let s = SupervisorSpec {
2462 children: vec![
2463 child("worker", "^bad", RestartPolicy::Permanent),
2464 child("cache", "^0.1", RestartPolicy::Transient),
2465 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
2466 ],
2467 ..SupervisorSpec::default()
2468 };
2469 let err = s.validate().unwrap_err();
2470 assert!(
2471 matches!(
2472 err,
2473 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
2474 ),
2475 "got {err:?}"
2476 );
2477 }
2478
2479 #[test]
2480 fn child_versao_invalid_diagnostic_carries_offending_versao() {
2481 // The diagnostic-shape pin: the error names the offending
2482 // `:versao` value verbatim so the author can grep their
2483 // caixa.lisp without re-running the build, and carries a
2484 // non-empty `reason` from `semver::VersionReq::parse` so the
2485 // parser's own wording flows through to the diagnostic.
2486 let s = SupervisorSpec {
2487 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
2488 ..SupervisorSpec::default()
2489 };
2490 let err = s.validate().unwrap_err();
2491 let SupervisorError::ChildVersaoInvalid {
2492 caixa,
2493 versao,
2494 reason,
2495 } = err
2496 else {
2497 panic!("expected ChildVersaoInvalid, got other variant");
2498 };
2499 assert_eq!(caixa, "worker");
2500 assert_eq!(versao, "not-a-req");
2501 assert!(
2502 !reason.is_empty(),
2503 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
2504 );
2505 }
2506
2507 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
2508
2509 #[test]
2510 fn validate_rejects_child_caixa_with_uppercase() {
2511 // The canonical "I copied the Servico's display name verbatim"
2512 // typo — child caixa names are lowercase per K8s DNS-1123 label
2513 // rule. The diagnostic names the offending name and suggests the
2514 // lower-cased fix in one edit, mirroring the
2515 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
2516 let s = SupervisorSpec {
2517 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
2518 ..SupervisorSpec::default()
2519 };
2520 let err = s.validate().unwrap_err();
2521 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
2522 panic!("expected ChildCaixaInvalid, got other variant");
2523 };
2524 assert_eq!(caixa, "Worker");
2525 assert!(
2526 reason.contains("uppercase"),
2527 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
2528 );
2529 assert!(
2530 reason.contains("\"worker\""),
2531 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
2532 );
2533 }
2534
2535 #[test]
2536 fn validate_rejects_child_caixa_with_underscore() {
2537 // The canonical "I'm thinking of a Python module / Postgres
2538 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
2539 // label schema. K8s rejects `metadata.name: my_worker` at
2540 // admission time with an opaque `field is invalid` (no source-
2541 // citing diagnostic). The gate moves it to caixa-build time.
2542 let s = SupervisorSpec {
2543 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
2544 ..SupervisorSpec::default()
2545 };
2546 let err = s.validate().unwrap_err();
2547 assert!(
2548 matches!(
2549 err,
2550 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
2551 if caixa == "my_worker" && reason.contains('_')
2552 ),
2553 "got {err:?}"
2554 );
2555 }
2556
2557 #[test]
2558 fn validate_rejects_child_caixa_with_dot() {
2559 // A `:children :caixa` entry is a single DNS-1123 label, not a
2560 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
2561 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
2562 // (3f9d7a0) on the peer name axis.
2563 let s = SupervisorSpec {
2564 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
2565 ..SupervisorSpec::default()
2566 };
2567 let err = s.validate().unwrap_err();
2568 assert!(
2569 matches!(
2570 err,
2571 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
2572 if caixa == "team.worker" && reason.contains('.')
2573 ),
2574 "got {err:?}"
2575 );
2576 }
2577
2578 #[test]
2579 fn validate_rejects_child_caixa_with_leading_hyphen() {
2580 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
2581 // with an alphanumeric. The K8s apiserver rejects `-worker`
2582 // outright; the renderer would emit a `metadata.name: "-worker"`
2583 // that fails admission far from the source caixa.lisp.
2584 let s = SupervisorSpec {
2585 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
2586 ..SupervisorSpec::default()
2587 };
2588 let err = s.validate().unwrap_err();
2589 assert!(
2590 matches!(
2591 err,
2592 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
2593 if caixa == "-worker" && reason.contains("start and end")
2594 ),
2595 "got {err:?}"
2596 );
2597 }
2598
2599 #[test]
2600 fn validate_rejects_child_caixa_with_trailing_hyphen() {
2601 // The symmetric arm of the boundary rule. Pin separately so
2602 // both ends of the label are covered against a future relaxation
2603 // that only checks one boundary.
2604 let s = SupervisorSpec {
2605 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
2606 ..SupervisorSpec::default()
2607 };
2608 let err = s.validate().unwrap_err();
2609 assert!(
2610 matches!(
2611 err,
2612 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
2613 if caixa == "worker-"
2614 ),
2615 "got {err:?}"
2616 );
2617 }
2618
2619 #[test]
2620 fn validate_rejects_child_caixa_with_unicode() {
2621 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
2622 // (`xn--…`) by the author before it reaches K8s. The byte-by-
2623 // byte ASCII validity check rejects multi-byte UTF-8 sequences
2624 // by the first byte that fails the `[a-z0-9-]` predicate.
2625 let s = SupervisorSpec {
2626 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
2627 ..SupervisorSpec::default()
2628 };
2629 let err = s.validate().unwrap_err();
2630 assert!(
2631 matches!(
2632 err,
2633 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
2634 if caixa == "café"
2635 ),
2636 "got {err:?}"
2637 );
2638 }
2639
2640 #[test]
2641 fn validate_rejects_child_caixa_with_whitespace() {
2642 // Whitespace is the canonical "I pasted from a sketch / doc"
2643 // footgun. The apiserver rejects every `metadata.name` value
2644 // carrying whitespace; pin the gate fires at the right boundary.
2645 let s = SupervisorSpec {
2646 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
2647 ..SupervisorSpec::default()
2648 };
2649 let err = s.validate().unwrap_err();
2650 assert!(
2651 matches!(
2652 err,
2653 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
2654 if caixa == "my worker"
2655 ),
2656 "got {err:?}"
2657 );
2658 }
2659
2660 #[test]
2661 fn validate_rejects_child_caixa_too_long() {
2662 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
2663 // 63 bytes; the K8s apiserver rejects every `metadata.name`
2664 // axis over the limit at admission time. The diagnostic names
2665 // both the cap and the actual length so the author can shorten
2666 // in one edit, mirroring `rejects_membro_caixa_too_long`
2667 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
2668 let too_long = "a".repeat(64);
2669 let s = SupervisorSpec {
2670 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
2671 ..SupervisorSpec::default()
2672 };
2673 let err = s.validate().unwrap_err();
2674 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
2675 panic!("expected ChildCaixaInvalid, got other variant");
2676 };
2677 assert_eq!(caixa, too_long);
2678 assert!(
2679 reason.contains("63"),
2680 "diagnostic must name the 63-byte cap (got: {reason:?})"
2681 );
2682 assert!(
2683 reason.contains("64"),
2684 "diagnostic must name the actual length (got: {reason:?})"
2685 );
2686 }
2687
2688 #[test]
2689 fn child_caixa_max_length_validates() {
2690 // The 63-byte boundary control pin — exactly-at-the-cap is
2691 // accepted, mirroring `membro_caixa_max_length_validates`
2692 // (3f9d7a0) and `placement_cluster_max_length_validates`
2693 // (6cbb900). Pinned separately so a future off-by-one tightening
2694 // surfaces here.
2695 let max_label = "a".repeat(63);
2696 let s = SupervisorSpec {
2697 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
2698 ..SupervisorSpec::default()
2699 };
2700 s.validate().unwrap();
2701 }
2702
2703 #[test]
2704 fn validate_accepts_canonical_child_caixa_forms() {
2705 // The realistic shapes a supervised child's `:caixa` carries —
2706 // single-word `worker`, version-suffixed `cache-v2`, single-char
2707 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
2708 // `payment-retry`, all-digit `0`. Pin every leg so a future
2709 // tightening (e.g. requiring a leading lowercase letter) surfaces
2710 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
2711 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
2712 // (6cbb900).
2713 for form in [
2714 "worker",
2715 "cache-v2",
2716 "a",
2717 "db",
2718 "2-pool",
2719 "payment-retry",
2720 "0",
2721 ] {
2722 let s = SupervisorSpec {
2723 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
2724 ..SupervisorSpec::default()
2725 };
2726 s.validate()
2727 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
2728 }
2729 }
2730
2731 #[test]
2732 fn child_caixa_empty_takes_precedence_over_invalid() {
2733 // Order pin: the existing `EmptyChildName` diagnostic (which
2734 // doesn't try to parse the DNS-1123 shape) fires before the new
2735 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
2736 // its narrower error message — `is_dns_1123_label` would reject
2737 // the empty string too (boundary check on the first byte), but
2738 // the empty-string arm is the more self-locating diagnostic for
2739 // the author. Same ordering discipline as
2740 // `membro_caixa_empty_takes_precedence_over_invalid` in
2741 // aplicacao.rs.
2742 let s = SupervisorSpec {
2743 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
2744 ..SupervisorSpec::default()
2745 };
2746 let err = s.validate().unwrap_err();
2747 assert_eq!(err, SupervisorError::EmptyChildName);
2748 }
2749
2750 #[test]
2751 fn child_caixa_invalid_fires_before_versao_check() {
2752 // Order pin: the per-axis shape gate runs inline before the
2753 // per-entry versao check, so a malformed `:caixa` on an entry
2754 // whose `:versao` would also fail surfaces the more self-
2755 // locating name-axis diagnostic first. Parallel to
2756 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
2757 // and `placement_cluster_invalid_fires_before_duplicate_check`
2758 // (6cbb900).
2759 let s = SupervisorSpec {
2760 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
2761 ..SupervisorSpec::default()
2762 };
2763 let err = s.validate().unwrap_err();
2764 assert!(
2765 matches!(
2766 err,
2767 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
2768 ),
2769 "got {err:?}"
2770 );
2771 }
2772
2773 #[test]
2774 fn child_caixa_invalid_fires_before_duplicate_check() {
2775 // Order pin: a malformed name on a non-duplicate entry surfaces
2776 // its own diagnostic, even when a later entry would otherwise
2777 // collapse onto an earlier name. The per-entry shape gate runs
2778 // inline before the duplicate-key HashSet insert, mirroring
2779 // `placement_cluster_invalid_fires_before_duplicate_check`
2780 // (6cbb900).
2781 let s = SupervisorSpec {
2782 children: vec![
2783 child("Worker", "^0.1", RestartPolicy::Permanent),
2784 child("cache", "^0.1", RestartPolicy::Transient),
2785 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
2786 ],
2787 ..SupervisorSpec::default()
2788 };
2789 let err = s.validate().unwrap_err();
2790 assert!(
2791 matches!(
2792 err,
2793 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
2794 ),
2795 "got {err:?}"
2796 );
2797 }
2798
2799 #[test]
2800 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
2801 // The diagnostic-shape pin: the error names the offending
2802 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
2803 // the author can grep their caixa.lisp without re-running the
2804 // build. Mirrors the diagnostic-shape sweep on every prior
2805 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
2806 let s = SupervisorSpec {
2807 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
2808 ..SupervisorSpec::default()
2809 };
2810 let err = s.validate().unwrap_err();
2811 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
2812 panic!("expected ChildCaixaInvalid, got other variant");
2813 };
2814 assert_eq!(caixa, "My_Worker");
2815 assert!(
2816 !reason.is_empty(),
2817 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
2818 );
2819 }
2820
2821 // ── value-shape: zero restart_window + duplicate child names ──────────
2822
2823 #[test]
2824 fn validate_accepts_none_restart_window() {
2825 // Omitted `:restart-window` is the "never reset" sentinel —
2826 // valid by design. Mirrors :limits axes where None = unbounded.
2827 let s = SupervisorSpec {
2828 restart_window: None,
2829 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2830 ..SupervisorSpec::default()
2831 };
2832 s.validate().unwrap();
2833 }
2834
2835 #[test]
2836 fn validate_rejects_zero_restart_window() {
2837 // Same "0 means the opposite of what you think" footgun closed
2838 // for :politicas :timeout (Envoy treats 0s as infinite) and
2839 // :limits :wall-clock (wasmtime traps before the call starts).
2840 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
2841 let s = SupervisorSpec {
2842 restart_window: Some(Duration::ZERO),
2843 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2844 ..SupervisorSpec::default()
2845 };
2846 assert_eq!(
2847 s.validate().unwrap_err(),
2848 SupervisorError::RestartWindowZero
2849 );
2850 }
2851
2852 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
2853 //
2854 // The fourth (and last) typed-`Duration` axis in caixa-core to get
2855 // the integer-millisecond canonical-form gate — peer with
2856 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
2857 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
2858 // path is already gated at the shared codec layer (see
2859 // `restart_window_serde_rejects_fractional_seconds`); this arm
2860 // closes the programmatic-struct-literal path the codec gate can't
2861 // see.
2862
2863 #[test]
2864 fn validate_rejects_sub_millisecond_restart_window() {
2865 // The fail-before-pass-after pin: a programmatic
2866 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
2867 // `validate` on every pre-gate codebase, then truncated to
2868 // `as_millis() == 1` on first serialize — the shared codec
2869 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
2870 // 1_000_000 ns, the typed `restart_window` no longer matches
2871 // its rendered form.
2872 let s = SupervisorSpec {
2873 restart_window: Some(Duration::from_micros(1500)),
2874 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2875 ..SupervisorSpec::default()
2876 };
2877 match s.validate().unwrap_err() {
2878 SupervisorError::RestartWindowNotCanonical { window } => {
2879 assert_eq!(window, Duration::from_micros(1500));
2880 }
2881 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
2882 }
2883 }
2884
2885 #[test]
2886 fn validate_rejects_one_nanosecond_restart_window() {
2887 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
2888 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
2889 // so the shared codec emits the literal `"0s"` — the next
2890 // serde round-trip would parse back to `Duration::ZERO`, which
2891 // the `RestartWindowZero` arm then rejects on re-validate. The
2892 // canonical-form gate at this layer surfaces a self-locating
2893 // diagnostic naming the offending Duration verbatim rather
2894 // than a downstream `RestartWindowZero` whose remediation
2895 // points at omitting the slot.
2896 let s = SupervisorSpec {
2897 restart_window: Some(Duration::from_nanos(1)),
2898 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2899 ..SupervisorSpec::default()
2900 };
2901 match s.validate().unwrap_err() {
2902 SupervisorError::RestartWindowNotCanonical { window } => {
2903 assert_eq!(window, Duration::from_nanos(1));
2904 }
2905 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
2906 }
2907 }
2908
2909 #[test]
2910 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
2911 // The 1-ns-past-1ms boundary case: a `Duration` carrying
2912 // 1_000_001 ns is structurally past the integer-ms granularity
2913 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
2914 // trip would truncate to `1ms` and the consumer would observe
2915 // a 1-ns drift on every emit. Same boundary the peer
2916 // `validate_rejects_nanosecond_past_canonical_boundary` test
2917 // in limits.rs pins for the `:limits :wall-clock` axis.
2918 let w = Duration::from_nanos(1_000_001);
2919 let s = SupervisorSpec {
2920 restart_window: Some(w),
2921 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2922 ..SupervisorSpec::default()
2923 };
2924 assert_eq!(
2925 s.validate().unwrap_err(),
2926 SupervisorError::RestartWindowNotCanonical { window: w }
2927 );
2928 }
2929
2930 #[test]
2931 fn validate_accepts_integer_millisecond_restart_window_values() {
2932 // The positive-control sweep: every `Duration` the shared
2933 // codec can round-trip losslessly — the canonical
2934 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
2935 // pair emits and accepts — passes `validate` without
2936 // surfacing the new canonical-form arm. Mirrors
2937 // `validate_accepts_integer_millisecond_wall_clock_values` on
2938 // the sibling `:limits :wall-clock` axis.
2939 for w in [
2940 Duration::from_millis(1),
2941 Duration::from_millis(500),
2942 Duration::from_millis(1500),
2943 Duration::from_secs(1),
2944 Duration::from_secs(30),
2945 Duration::from_secs(60),
2946 Duration::from_secs(120),
2947 Duration::from_secs(3600),
2948 ] {
2949 let s = SupervisorSpec {
2950 restart_window: Some(w),
2951 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2952 ..SupervisorSpec::default()
2953 };
2954 s.validate()
2955 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
2956 }
2957 }
2958
2959 #[test]
2960 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
2961 // Cross-arm ordering pin: `Duration::ZERO` has
2962 // `subsec_nanos() == 0` and would otherwise pass the
2963 // canonical-form arm — the zero-floor arm must fire first so
2964 // the more self-locating `RestartWindowZero` diagnostic (with
2965 // its omit-axis remediation directly named) leads. Same
2966 // posture every peer zero-then-shape gate uses
2967 // (`WallClockZero` → `WallClockNotCanonical`,
2968 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
2969 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
2970 let s = SupervisorSpec {
2971 restart_window: Some(Duration::ZERO),
2972 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2973 ..SupervisorSpec::default()
2974 };
2975 assert_eq!(
2976 s.validate().unwrap_err(),
2977 SupervisorError::RestartWindowZero
2978 );
2979 }
2980
2981 #[test]
2982 fn restart_window_canonical_diagnostic_carries_offending_duration() {
2983 // Diagnostic-shape pin: the canonical-form arm names the
2984 // offending `Duration` verbatim so the author's grep lands on
2985 // the field's value, not a generic "duration not canonical"
2986 // message. Same shape every other typed-canonical-form arm
2987 // on this surface carries (`WallClockNotCanonical` carries
2988 // the offending `Duration` verbatim,
2989 // `PolicyTimeoutNotCanonical` carries the offending
2990 // `Duration` verbatim).
2991 let w = Duration::from_micros(500);
2992 let s = SupervisorSpec {
2993 restart_window: Some(w),
2994 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
2995 ..SupervisorSpec::default()
2996 };
2997 let err = s.validate().unwrap_err();
2998 let msg = err.to_string();
2999 assert!(
3000 msg.contains("500"),
3001 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
3002 );
3003 assert!(
3004 msg.contains("sub-millisecond"),
3005 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
3006 );
3007 }
3008
3009 #[test]
3010 fn restart_window_validated_value_round_trips_through_codec() {
3011 // The structural property the canonical-ms gate enforces:
3012 // every `SupervisorSpec::restart_window` past
3013 // `SupervisorSpec::validate` round-trips losslessly through
3014 // the shared duration codec (serialize → string →
3015 // deserialize → equal value). Pin this end-to-end so a future
3016 // change to either side (the validate gate's accepted
3017 // granularity, the codec's parse/render unit set) that breaks
3018 // the alignment surfaces here. Peer of
3019 // `wall_clock_validated_value_round_trips_through_codec` on
3020 // the sibling `:limits :wall-clock` axis.
3021 for w in [
3022 Duration::from_millis(1),
3023 Duration::from_millis(1500),
3024 Duration::from_secs(30),
3025 Duration::from_secs(3600),
3026 ] {
3027 let s = SupervisorSpec {
3028 restart_window: Some(w),
3029 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3030 ..SupervisorSpec::default()
3031 };
3032 s.validate().unwrap();
3033 let json = serde_json::to_string(&s).unwrap();
3034 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
3035 assert_eq!(back.restart_window, Some(w));
3036 }
3037 }
3038
3039 // ── value-shape: upper cap on :restart-window ─────────────────────────
3040 //
3041 // The fourth (and last) typed-`Duration` axis in caixa-core to get
3042 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
3043 // `:politicas :timeout` (2e8ee7e), and `:politicas
3044 // :circuit-breaker :window` (379a814). Brackets the typed
3045 // `:restart-window` axis structurally: every validated value lies
3046 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
3047 // granularity, closing the
3048 // rolling-window-degenerates-to-lifetime-counter footgun the prior
3049 // zero-floor-and-canonical-form-only checks left open.
3050
3051 #[test]
3052 fn validate_rejects_restart_window_above_cap() {
3053 // The fail-before-pass-after pin: 3601s = 1h + 1s is
3054 // structurally one canonical-tick past the
3055 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
3056 // integer-millisecond magnitude the canonical-form arm above
3057 // accepts cleanly, that the shared duration codec round-trips
3058 // losslessly as `"3601s"`, and that silently passed validate on
3059 // every pre-gate codebase because the typed slot's only checks
3060 // were the zero-floor and canonical-form arms. The runtime
3061 // substrate consuming the value (Erlang/OTP's MaxIntensity/
3062 // Period reconciler, the future wasm-operator's per-supervisor
3063 // restart-intensity counter) reaches for a `Duration` so long
3064 // no realistic restart-recovery pattern resets the counter,
3065 // far from the source caixa.lisp.
3066 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
3067 let s = SupervisorSpec {
3068 restart_window: Some(w),
3069 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3070 ..SupervisorSpec::default()
3071 };
3072 assert_eq!(
3073 s.validate().unwrap_err(),
3074 SupervisorError::RestartWindowExceedsCap { window: w }
3075 );
3076 }
3077
3078 #[test]
3079 fn validate_rejects_restart_window_one_millisecond_above_cap() {
3080 // Boundary case: exactly 1ms past the cap (the granularity the
3081 // canonical-form gate enforces). Catches a future "strictly
3082 // less than" half-measure and pins the diagnostic to name the
3083 // offending `Duration` verbatim. Peer of
3084 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
3085 // `rejects_policy_timeout_one_millisecond_above_cap` /
3086 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
3087 // on the sibling typed-`Duration` axes' top edges.
3088 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
3089 let s = SupervisorSpec {
3090 restart_window: Some(w),
3091 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3092 ..SupervisorSpec::default()
3093 };
3094 assert_eq!(
3095 s.validate().unwrap_err(),
3096 SupervisorError::RestartWindowExceedsCap { window: w }
3097 );
3098 }
3099
3100 #[test]
3101 fn validate_rejects_restart_window_far_above_cap() {
3102 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
3103 // `(:restart-window "7d")`, or any "I want a lifetime counter
3104 // but wrote a `<integer>h` magnitude anyway" typo — values the
3105 // canonical-form arm accepts as integer-millisecond magnitudes,
3106 // the codec round-trips losslessly through serde, but the
3107 // operator's `MaxIntensity / Period` reconciler cannot honor
3108 // as a meaningful rolling window. Until this gate landed
3109 // validate accepted them. Pin the common above-cap values (24h,
3110 // 7d, ~11.5d) so a future relaxation that drops the upper bound
3111 // surfaces here.
3112 for w in [
3113 Duration::from_secs(86_400), // 24h
3114 Duration::from_secs(604_800), // 7d
3115 Duration::from_secs(1_000_000), // ~11.5 days
3116 ] {
3117 let s = SupervisorSpec {
3118 restart_window: Some(w),
3119 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3120 ..SupervisorSpec::default()
3121 };
3122 assert_eq!(
3123 s.validate().unwrap_err(),
3124 SupervisorError::RestartWindowExceedsCap { window: w }
3125 );
3126 }
3127 }
3128
3129 #[test]
3130 fn validate_accepts_restart_window_at_cap() {
3131 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
3132 // (1h) — must validate. The cap is inclusive on the top edge,
3133 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
3134 // [`crate::POLICY_TIMEOUT_MAX`] /
3135 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
3136 // capped axes. Pin the boundary explicitly so a future
3137 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
3138 // instead of `>`) surfaces here as a test failure rather than a
3139 // silent contract narrowing.
3140 let s = SupervisorSpec {
3141 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
3142 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3143 ..SupervisorSpec::default()
3144 };
3145 s.validate()
3146 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
3147 }
3148
3149 #[test]
3150 fn validate_accepts_restart_window_typical_values() {
3151 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
3152 // per-supervisor production-playbook band positive-control
3153 // sweep — every value Learn You Some Erlang's `{intensity, 5,
3154 // 60}` worker-supervisor `Period = 60s` default, Elixir's
3155 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
3156 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
3157 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
3158 // default recommend (5s..=300s) must pass, plus a sweep
3159 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
3160 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
3161 // on the sibling `:limits :wall-clock` axis.
3162 for w in [
3163 Duration::from_millis(1),
3164 Duration::from_millis(500),
3165 Duration::from_secs(1),
3166 Duration::from_secs(5), // RabbitMQ broker-supervisor default
3167 Duration::from_secs(10), // Riak Core lower
3168 Duration::from_secs(30),
3169 Duration::from_secs(60), // Learn You Some Erlang default
3170 Duration::from_secs(120), // OTP supervisor MaxT typical
3171 Duration::from_secs(300), // Riak Core upper
3172 Duration::from_secs(900), // 15m
3173 Duration::from_secs(1800),
3174 Duration::from_secs(3600), // exactly 1h, the cap
3175 ] {
3176 let s = SupervisorSpec {
3177 restart_window: Some(w),
3178 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3179 ..SupervisorSpec::default()
3180 };
3181 s.validate()
3182 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
3183 }
3184 }
3185
3186 #[test]
3187 fn restart_window_zero_takes_precedence_over_cap() {
3188 // The cross-arm ordering pin: `Duration::ZERO` is structurally
3189 // outside both `>= 1ms` (zero-floor) and `<=
3190 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
3191 // diagnostic is the more self-locating one (it directly names
3192 // the omit-axis remediation), so the validate gate must fire
3193 // on zero first. Same shape every other zero-then-cap ordering
3194 // on this surface uses (`WallClockZero` then
3195 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
3196 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
3197 // `PolicyBreakerWindowExceedsCap`).
3198 let s = SupervisorSpec {
3199 restart_window: Some(Duration::ZERO),
3200 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3201 ..SupervisorSpec::default()
3202 };
3203 assert_eq!(
3204 s.validate().unwrap_err(),
3205 SupervisorError::RestartWindowZero,
3206 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
3207 );
3208 }
3209
3210 #[test]
3211 fn restart_window_canonical_takes_precedence_over_cap() {
3212 // The cross-arm ordering pin: a `Duration` that is *both*
3213 // sub-millisecond (non-canonical-form) and structurally above
3214 // the cap surfaces the canonical-form diagnostic first,
3215 // because the round-trip-shape break is the more fundamental
3216 // issue (the value can't even round-trip through the codec,
3217 // so the cap diagnostic naming `1ms..=1h` would be misleading
3218 // — there's no integer-ms form of the offending value). Pin
3219 // the order so a future refactor that reorders the arms
3220 // surfaces here as a test failure rather than a silent
3221 // diagnostic regression. Peer of
3222 // `wall_clock_canonical_takes_precedence_over_cap` /
3223 // `policy_timeout_canonical_takes_precedence_over_cap`.
3224 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
3225 let s = SupervisorSpec {
3226 restart_window: Some(w),
3227 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3228 ..SupervisorSpec::default()
3229 };
3230 assert_eq!(
3231 s.validate().unwrap_err(),
3232 SupervisorError::RestartWindowNotCanonical { window: w },
3233 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
3234 );
3235 }
3236
3237 #[test]
3238 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
3239 // The cross-arm ordering pin between the `:max-restarts` cap
3240 // and the sibling `:restart-window` cap. A supervisor carrying
3241 // both an over-cap `max_restarts` AND an over-cap window must
3242 // surface the `MaxRestartsExceedsCap` diagnostic first — the
3243 // cap arm is wired immediately after the zero-restart arm and
3244 // strictly before every window-axis arm (zero / canonical /
3245 // cap), so the offending value the diagnostic names matches
3246 // the order the author would discover the gates by reading
3247 // top-to-bottom through `SupervisorSpec::validate`. Pin the
3248 // order so a future refactor that reorders the arms surfaces
3249 // here as a test failure rather than a silent diagnostic
3250 // regression. Peer of
3251 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
3252 // on the sibling zero / canonical window arms.
3253 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
3254 let s = SupervisorSpec {
3255 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3256 restart_window: Some(w),
3257 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3258 ..SupervisorSpec::default()
3259 };
3260 assert_eq!(
3261 s.validate().unwrap_err(),
3262 SupervisorError::MaxRestartsExceedsCap {
3263 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3264 },
3265 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3266 );
3267 }
3268
3269 #[test]
3270 fn restart_window_cap_diagnostic_carries_offending_value() {
3271 // The diagnostic-shape pin: the offending `Duration` is
3272 // carried verbatim into the
3273 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
3274 // surfaced error message names the value the author wrote,
3275 // not just the cap. Same self-locating diagnostic shape every
3276 // other typed-cap arm on this surface carries
3277 // (`WallClockExceedsCap` carries the offending `Duration`
3278 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
3279 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
3280 // the offending `Duration` verbatim).
3281 let w = Duration::from_secs(7200); // 2h
3282 let s = SupervisorSpec {
3283 restart_window: Some(w),
3284 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3285 ..SupervisorSpec::default()
3286 };
3287 let err = s.validate().unwrap_err();
3288 assert!(
3289 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
3290 "got {err:?}"
3291 );
3292 let msg = err.to_string();
3293 assert!(
3294 msg.contains("7200"),
3295 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
3296 );
3297 }
3298
3299 #[test]
3300 fn supervisor_restart_window_cap_pins_canonical_value() {
3301 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
3302 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
3303 // shared duration codec emits as a clean canonical string
3304 // (`"<n>h"`). Pinning the literal value here surfaces a future
3305 // drift (a relaxation to 24h, a tightening to 5m) as a
3306 // deliberate test edit, not a silent contract narrowing.
3307 //
3308 // The four typed-`Duration` caps on the validation surface
3309 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
3310 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
3311 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
3312 // single uniform top edge at the codec's largest emitted unit
3313 // — a structural-property invariant the equality assertions
3314 // here enshrine, so a future drift on any of the four
3315 // surfaces as a deliberate test edit. Same shape every other
3316 // typed-cap value pin uses
3317 // (`wall_clock_cap_pins_canonical_value`,
3318 // `policy_timeout_cap_pins_canonical_value`,
3319 // `circuit_breaker_window_cap_pins_canonical_value`).
3320 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
3321 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
3322 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
3323 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
3324 assert_eq!(
3325 SUPERVISOR_RESTART_WINDOW_MAX,
3326 crate::POLICY_BREAKER_WINDOW_MAX
3327 );
3328 }
3329
3330 #[test]
3331 fn restart_window_cap_value_round_trips_through_codec() {
3332 // The codec round-trip property the cap arm preserves: the
3333 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
3334 // through the shared duration codec — every value at the cap
3335 // serializes to the canonical `"1h"` form and parses back
3336 // identically. Pin the round-trip so a future change to the
3337 // codec's unit set or to the cap's magnitude that breaks the
3338 // round-trip property surfaces here. Peer of
3339 // `wall_clock_cap_value_round_trips_through_codec` on the
3340 // sibling `:limits :wall-clock` axis.
3341 let s = SupervisorSpec {
3342 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
3343 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3344 ..SupervisorSpec::default()
3345 };
3346 s.validate().unwrap();
3347 let json = serde_json::to_string(&s).unwrap();
3348 assert!(
3349 json.contains("\"1h\""),
3350 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
3351 );
3352 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
3353 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
3354 }
3355
3356 #[test]
3357 fn validate_rejects_duplicate_child_caixa() {
3358 // Two children with the same :caixa render to two ComputeUnits
3359 // with the same name in the cluster's HelmRelease values —
3360 // one silently overwrites the other. Erlang/OTP's child_spec.id
3361 // is required-unique per supervisor; same set-not-multiset
3362 // discipline applied here as for :membros / :placement
3363 // :clusters / :entrada :paths.
3364 let s = SupervisorSpec {
3365 children: vec![
3366 child("worker", "^0.1", RestartPolicy::Permanent),
3367 child("cache", "^0.1", RestartPolicy::Transient),
3368 child("worker", "^0.2", RestartPolicy::Permanent),
3369 ],
3370 ..SupervisorSpec::default()
3371 };
3372 let err = s.validate().unwrap_err();
3373 assert!(
3374 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
3375 "got {err:?}"
3376 );
3377 }
3378
3379 #[test]
3380 fn validate_duplicate_child_diagnostic_names_first_collision() {
3381 // Iteration walks the :children list in declaration order —
3382 // the diagnostic names the first repeat, deterministically,
3383 // even when multiple names duplicate.
3384 let s = SupervisorSpec {
3385 children: vec![
3386 child("a", "^0.1", RestartPolicy::Permanent),
3387 child("b", "^0.1", RestartPolicy::Permanent),
3388 child("a", "^0.1", RestartPolicy::Permanent),
3389 child("b", "^0.1", RestartPolicy::Permanent),
3390 ],
3391 ..SupervisorSpec::default()
3392 };
3393 let err = s.validate().unwrap_err();
3394 assert!(
3395 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
3396 "got {err:?}"
3397 );
3398 }
3399
3400 // ── self-supervision cross-slot gate ──────────────────────────
3401
3402 #[test]
3403 fn validate_no_self_supervision_rejects_self_referential_child() {
3404 // A supervisor whose `:children` lists its own `:nome` is a
3405 // one-node reconciliation cycle — rejected, naming the parent.
3406 let children = vec![
3407 child("worker", "^0.1", RestartPolicy::Permanent),
3408 child("orquestra", "^0.1", RestartPolicy::Permanent),
3409 ];
3410 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
3411 assert!(
3412 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
3413 "got {err:?}"
3414 );
3415 }
3416
3417 #[test]
3418 fn validate_no_self_supervision_accepts_distinct_children() {
3419 // Positive control: distinct child names (including a child that
3420 // is itself a supervisor — nested trees are valid OTP) pass.
3421 let children = vec![
3422 child("worker", "^0.1", RestartPolicy::Permanent),
3423 child("sub-tree", "^0.1", RestartPolicy::Permanent),
3424 ];
3425 validate_no_self_supervision(&children, "orquestra").unwrap();
3426 }
3427
3428 #[test]
3429 fn validate_no_self_supervision_empty_children_is_ok() {
3430 // SimpleOneForOne / no-static-children supervisors have nothing
3431 // to self-reference — the gate is vacuously satisfied.
3432 validate_no_self_supervision(&[], "orquestra").unwrap();
3433 }
3434
3435 #[test]
3436 fn validate_simple_one_for_one_skips_uniqueness_check() {
3437 // SimpleOneForOne supervisors carry no static children — the
3438 // duplicate-child loop never runs. A zero-window declaration
3439 // on a SimpleOneForOne supervisor still trips the window check
3440 // (window applies to dynamic children too).
3441 let s = SupervisorSpec {
3442 estrategia: RestartStrategy::SimpleOneForOne,
3443 restart_window: None,
3444 children: vec![],
3445 ..SupervisorSpec::default()
3446 };
3447 s.validate().unwrap();
3448 let s_zero = SupervisorSpec {
3449 estrategia: RestartStrategy::SimpleOneForOne,
3450 restart_window: Some(Duration::ZERO),
3451 children: vec![],
3452 ..SupervisorSpec::default()
3453 };
3454 assert_eq!(
3455 s_zero.validate().unwrap_err(),
3456 SupervisorError::RestartWindowZero
3457 );
3458 }
3459
3460 #[test]
3461 fn validate_zero_window_runs_after_max_restarts_check() {
3462 // Pin the order: max_restarts == 0 fires before
3463 // restart_window == 0s, so an author with both wrong sees the
3464 // counter-axis diagnostic first (matches the order in the
3465 // struct and in the doc comment).
3466 let s = SupervisorSpec {
3467 max_restarts: 0,
3468 restart_window: Some(Duration::ZERO),
3469 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3470 ..SupervisorSpec::default()
3471 };
3472 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3473 }
3474
3475 #[test]
3476 fn round_trip_all_strategies() {
3477 for &strat in RestartStrategy::ALL {
3478 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
3479 // shape partition through the [`gen_platform::IsVariant`]
3480 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
3481 // predicate rather than the raw
3482 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
3483 // open-coded pattern-match — same closed-set-typed-enum
3484 // arm-discriminator dispatch discipline the sibling
3485 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
3486 // (915a934) extended onto its two paired positive / negated
3487 // `matches!` filter sites, and the sibling
3488 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
3489 // predicate convergence (766ec63) extended onto the M3 mesh-
3490 // slot per-`:placement` distribution-strategy `matches!`
3491 // discriminator axis. See the sibling
3492 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
3493 // fixture and the peer `manifest::tests::
3494 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
3495 // fixture — all three sites (the last unlifted
3496 // `matches!`-based arm-discriminator axis on the OTP-shape
3497 // supervisor sibling-restart-strategy closed-set typed enum,
3498 // acknowledged in 915a934's Prior-commits footnote as the
3499 // outstanding follow-up) now consult one typed dispatch on
3500 // the substrate primitive.
3501 let s = SupervisorSpec {
3502 estrategia: strat,
3503 children: if strat.is_simple_one_for_one() {
3504 vec![]
3505 } else {
3506 vec![child("w", "^0.1", RestartPolicy::Permanent)]
3507 },
3508 ..SupervisorSpec::default()
3509 };
3510 let json = serde_json::to_string(&s).unwrap();
3511 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
3512 assert_eq!(s, back);
3513 }
3514 }
3515
3516 #[test]
3517 fn round_trip_all_restart_policies() {
3518 for policy in [
3519 RestartPolicy::Permanent,
3520 RestartPolicy::Temporary,
3521 RestartPolicy::Transient,
3522 ] {
3523 let c = child("w", "^0.1", policy);
3524 let json = serde_json::to_string(&c).unwrap();
3525 let back: ChildSpec = serde_json::from_str(&json).unwrap();
3526 assert_eq!(c, back);
3527 }
3528 }
3529
3530 #[test]
3531 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
3532 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
3533 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
3534 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
3535 // is the only variant that satisfies `.is_simple_one_for_one()`;
3536 // every static-children-bearing arm (`OneForOne` / `OneForAll`
3537 // / `RestForOne`) returns `false`. This pin makes the partition
3538 // invariant load-bearing at caixa-core test time so a future
3539 // derive regression (a hole that returns `false` for
3540 // `SimpleOneForOne` too, or a byte-collision that flips a second
3541 // variant to `true`) trips here rather than laundering the arm
3542 // at the three test-fixture builder sites (a hole flips the
3543 // `SimpleOneForOne` fixture to carry a non-empty children list
3544 // and the subsequent `SupervisorSpec::validate` would refuse the
3545 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
3546 // a collision flips a peer strategy's fixture to carry an empty
3547 // children list and the subsequent `validate` would refuse with
3548 // [`SupervisorError::NoChildren`] — either way, the pin fires
3549 // here, at the derive site, rather than at the fixture-refusal
3550 // site far away). Peer of the sibling
3551 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
3552 // (915a934) pin on the M2 OTP-appup axis and the sibling
3553 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
3554 // pin on the M0 `:kind` axis.
3555 let cases: &[(RestartStrategy, bool)] = &[
3556 (RestartStrategy::OneForOne, false),
3557 (RestartStrategy::OneForAll, false),
3558 (RestartStrategy::RestForOne, false),
3559 (RestartStrategy::SimpleOneForOne, true),
3560 ];
3561 for (variant, expected) in cases {
3562 assert_eq!(
3563 variant.is_simple_one_for_one(),
3564 *expected,
3565 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
3566 return {expected} (partition invariant on the \
3567 IsVariant-derived arm-discriminator predicate — every \
3568 test-fixture site that partitions the `:children` slot \
3569 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
3570 off this typed dispatch, so a derive regression must \
3571 surface here rather than at the fixture-refusal site)"
3572 );
3573 }
3574 }
3575
3576 #[test]
3577 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
3578 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
3579 // fixture-shape partition against the pre-lift
3580 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
3581 // pattern-match every test-fixture builder site previously
3582 // coupled to inline. Asserts the two projections agree byte-for-
3583 // byte on every arm of the enum, so a future derive regression
3584 // that flipped either predicate's arm-set would surface here at
3585 // caixa-core test time rather than at the three fixture-builder
3586 // sites (`supervisor::tests::round_trip_all_strategies`,
3587 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
3588 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
3589 // far from the derive site. Same peer-shape byte-identity pin
3590 // every sibling `IsVariant`-derive-routed convergence carries on
3591 // the substrate's closed-set typed-enum surface (peer of
3592 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
3593 // on the M2 OTP-appup axis).
3594 for &strat in RestartStrategy::ALL {
3595 let via_predicate = strat.is_simple_one_for_one();
3596 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
3597 assert_eq!(
3598 via_predicate, via_matches,
3599 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
3600 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
3601 the pre-lift open-coded pattern and the \
3602 IsVariant-derived predicate are the same axis, \
3603 one typed dispatch"
3604 );
3605 }
3606 }
3607
3608 #[test]
3609 fn duration_codec_round_trip_canonical_units() {
3610 // Note the canonical-form rule: durations serialize to the
3611 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
3612 // "60s" — but the round-trip preserves the underlying Duration.
3613 let cases = [
3614 ("30s", Duration::from_secs(30)),
3615 ("5m", Duration::from_secs(300)),
3616 ("1h", Duration::from_secs(3600)),
3617 ("500ms", Duration::from_millis(500)),
3618 ];
3619 for (lit, dur) in cases {
3620 let s = SupervisorSpec {
3621 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3622 restart_window: Some(dur),
3623 ..SupervisorSpec::default()
3624 };
3625 let json = serde_json::to_string(&s).unwrap();
3626 assert!(
3627 json.contains(&format!("\"{lit}\"")),
3628 "expected \"{lit}\" in {json}"
3629 );
3630 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
3631 assert_eq!(back.restart_window, Some(dur));
3632 }
3633 }
3634
3635 #[test]
3636 fn duration_canonicalizes_to_largest_unit() {
3637 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
3638 // typed Duration still equals 60s on the way back.
3639 let s = SupervisorSpec {
3640 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3641 restart_window: Some(Duration::from_secs(60)),
3642 ..SupervisorSpec::default()
3643 };
3644 let json = serde_json::to_string(&s).unwrap();
3645 assert!(json.contains("\"1m\""), "{json}");
3646 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
3647 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
3648 }
3649
3650 #[test]
3651 fn three_child_one_for_one_validates() {
3652 let s = SupervisorSpec {
3653 estrategia: RestartStrategy::OneForOne,
3654 max_restarts: 5,
3655 restart_window: Some(Duration::from_secs(60)),
3656 children: vec![
3657 child("worker", "^0.1", RestartPolicy::Permanent),
3658 child("cache", "^0.1", RestartPolicy::Transient),
3659 child("scratch", "^0.1", RestartPolicy::Temporary),
3660 ],
3661 };
3662 s.validate().unwrap();
3663 }
3664
3665 #[test]
3666 fn json_uses_pascal_case_for_strategy_and_policy() {
3667 // Variant names are PascalCase by default in serde, matching
3668 // tatara-lisp's enum convention (`:estrategia OneForOne`).
3669 let c = child("w", "^0.1", RestartPolicy::Permanent);
3670 let json = serde_json::to_string(&c).unwrap();
3671 assert!(json.contains("\"Permanent\""));
3672 assert!(!json.contains("\"permanent\""));
3673
3674 let s = SupervisorSpec {
3675 estrategia: RestartStrategy::OneForOne,
3676 children: vec![c],
3677 ..SupervisorSpec::default()
3678 };
3679 let json = serde_json::to_string(&s).unwrap();
3680 assert!(json.contains("\"estrategia\":\"OneForOne\""));
3681 }
3682
3683 // ── shared duration codec: integer-magnitude canonical-form gate ──
3684 //
3685 // The gate lifts the discipline `crate::limits::parse_duration`
3686 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
3687 // the shared codec backing the remaining three typed-duration
3688 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
3689 // `:politicas :circuit-breaker :window`. Every magnitude `render`
3690 // emits is a non-negative integer with no decimal point and no
3691 // leading sign, so the codec's accepted set must match for
3692 // serialize/deserialize to round-trip without canonical-form
3693 // drift.
3694
3695 #[test]
3696 fn parse_accepts_integer_canonical_units() {
3697 // Pin the happy-path: every canonical author shape `render`
3698 // ever emits parses to the same `Duration` value, so the
3699 // codec's accepted set is at least a superset of its emitted
3700 // set on the canonical-unit axis.
3701 for (lit, dur) in [
3702 ("30s", Duration::from_secs(30)),
3703 ("500ms", Duration::from_millis(500)),
3704 ("2m", Duration::from_secs(120)),
3705 ("1h", Duration::from_secs(3600)),
3706 ("0s", Duration::ZERO),
3707 ] {
3708 assert_eq!(
3709 duration_codec::parse(lit).unwrap(),
3710 dur,
3711 "parse({lit:?}) should be {dur:?}"
3712 );
3713 }
3714 }
3715
3716 #[test]
3717 fn parse_accepts_bare_integer_as_seconds() {
3718 // The `"s" | ""` arm: a bare integer with no unit is read as
3719 // seconds. Pin this so the unit-empty form keeps parsing (it
3720 // renders to `"<n>s"` on serialize — that's a unit-choice
3721 // drift the integer-magnitude gate does NOT close, matching
3722 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
3723 // the peer `:limits :memory` codec).
3724 assert_eq!(
3725 duration_codec::parse("30").unwrap(),
3726 Duration::from_secs(30)
3727 );
3728 }
3729
3730 #[test]
3731 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
3732 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
3733 // on first serialize — DRIFT. The integer-magnitude gate names
3734 // the offending `"1.5"` verbatim and points at the canonical
3735 // remediation `"1500ms"`.
3736 let err = duration_codec::parse("1.5s").unwrap_err();
3737 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
3738 assert!(
3739 err.contains("not a non-negative integer"),
3740 "missing canonical-form reason in {err:?}"
3741 );
3742 assert!(
3743 err.contains("\"1500ms\""),
3744 "missing canonical-form remediation in {err:?}"
3745 );
3746 }
3747
3748 #[test]
3749 fn parse_rejects_decimal_shaped_integer_seconds() {
3750 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
3751 // `1s` exactly, so the round-trip looks correct — but the
3752 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
3753 // decimal-shape-with-integer-value form so author intent is
3754 // never silently rewritten.
3755 let err = duration_codec::parse("1.0s").unwrap_err();
3756 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
3757 assert!(
3758 err.contains("not a non-negative integer"),
3759 "missing canonical-form reason in {err:?}"
3760 );
3761 }
3762
3763 #[test]
3764 fn parse_rejects_half_unit_minute() {
3765 // `"0.5m"` is the unit-fraction footgun — author writes a
3766 // human-readable half-minute, serde silently rewrites to
3767 // `"30s"` on next emit. The gate names the offending
3768 // magnitude `"0.5"` and points at the integer-in-smaller-unit
3769 // form.
3770 let err = duration_codec::parse("0.5m").unwrap_err();
3771 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
3772 assert!(
3773 err.contains("\"30s\""),
3774 "missing canonical-form remediation in {err:?}"
3775 );
3776 }
3777
3778 #[test]
3779 fn parse_rejects_leading_plus_sign() {
3780 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
3781 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
3782 // cleanly to 30s and round-tripped to `"30s"` on next emit
3783 // (DRIFT). The digit-only gate closes the leading-sign class
3784 // first; the diagnostic names `"+30"` verbatim.
3785 let err = duration_codec::parse("+30s").unwrap_err();
3786 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
3787 assert!(
3788 err.contains("not a non-negative integer"),
3789 "missing canonical-form reason in {err:?}"
3790 );
3791 }
3792
3793 #[test]
3794 fn parse_rejects_leading_minus_sign() {
3795 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
3796 // rejected with `"negative duration in \"-30s\""`. Under the
3797 // integer-magnitude gate the diagnostic is unified — `-30` is
3798 // non-digit-only, f64-numeric, and surfaces with the canonical-
3799 // form reason (no leading `+` / `-` sign) naming the offending
3800 // `"-30"` verbatim. Same diagnostic shape as every other
3801 // rejected non-integer magnitude.
3802 let err = duration_codec::parse("-30s").unwrap_err();
3803 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
3804 assert!(
3805 err.contains("not a non-negative integer"),
3806 "missing canonical-form reason in {err:?}"
3807 );
3808 }
3809
3810 #[test]
3811 fn parse_garbage_still_falls_through_to_bad_magnitude() {
3812 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
3813 // through to the narrower "bad duration magnitude" arm — the
3814 // canonical-form diagnostic is reserved for the parser-shape
3815 // footgun case, not the "not a number at all" case. Same
3816 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
3817 // the peer `:limits :memory` codec.
3818 let err = duration_codec::parse("--1s").unwrap_err();
3819 assert!(
3820 err.contains("bad duration magnitude"),
3821 "expected bad-magnitude wording in {err:?}"
3822 );
3823 }
3824
3825 #[test]
3826 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
3827 // The accepted set is now closed under `u64`-exact integer
3828 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
3829 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
3830 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
3831 // possible. Pin the integer-exact arms across the four unit
3832 // suffixes so a future refactor that reaches back for f64
3833 // (`from_secs_f64`, `mul_f64`) surfaces here.
3834 assert_eq!(
3835 duration_codec::parse("3600s").unwrap(),
3836 Duration::from_secs(3600)
3837 );
3838 assert_eq!(
3839 duration_codec::parse("60m").unwrap(),
3840 Duration::from_secs(3600)
3841 );
3842 assert_eq!(
3843 duration_codec::parse("1h").unwrap(),
3844 Duration::from_secs(3600)
3845 );
3846 assert_eq!(
3847 duration_codec::parse("999ms").unwrap(),
3848 Duration::from_millis(999)
3849 );
3850 }
3851
3852 #[test]
3853 fn restart_window_serde_rejects_fractional_seconds() {
3854 // The shared codec backs `SupervisorSpec::restart_window`
3855 // (`with = "duration_codec"`) — so the gate applies on serde
3856 // deserialize for the typed Supervisor slot. A
3857 // `{"restartWindow":"1.5s"}` payload that previously round-
3858 // tripped to a different canonical string on next serialize
3859 // is now refused at deserialize with the integer-magnitude
3860 // diagnostic.
3861 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
3862 "restartWindow":"1.5s",
3863 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
3864 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
3865 let msg = err.to_string();
3866 assert!(
3867 msg.contains("not a non-negative integer"),
3868 "expected integer-magnitude diagnostic in {msg:?}"
3869 );
3870 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
3871 }
3872
3873 #[test]
3874 fn restart_window_serde_rejects_leading_plus() {
3875 // The `u64::from_str` leading-`+` permissiveness gap that
3876 // motivated the digit-only gate (the `f64`-side accepted
3877 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
3878 // is now closed on the shared codec — surfaces as a structured
3879 // diagnostic at the serde layer for every typed-duration slot.
3880 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
3881 "restartWindow":"+30s",
3882 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
3883 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
3884 let msg = err.to_string();
3885 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
3886 assert!(
3887 msg.contains("not a non-negative integer"),
3888 "missing canonical-form reason in {msg:?}"
3889 );
3890 }
3891
3892 #[test]
3893 fn parse_rejects_leading_zero_magnitude() {
3894 // `"030s"` is digit-only, so the existing non-digit-only / sign
3895 // / fractional arm doesn't catch it — `u64::from_str("030")`
3896 // returns `Ok(30)`, so before this gate `"030s"` parsed to
3897 // `Duration::from_secs(30)` and round-tripped through `render`
3898 // to `"30s"` — a *different* canonical string on the next emit,
3899 // breaking the THEORY.md Part V render-determinism contract
3900 // exactly the way `"+30s"` did before the leading-`+` arm
3901 // landed. Peer with the `rate_limit_codec` leading-zero arm
3902 // (4f46830) on the same canonical-form-drift axis.
3903 let err = duration_codec::parse("030s").unwrap_err();
3904 assert!(
3905 err.contains("non-canonical leading zero"),
3906 "expected leading-zero diagnostic in {err:?}"
3907 );
3908 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
3909 assert!(
3910 err.contains("\"30s\""),
3911 "missing canonical-form remediation in {err:?}"
3912 );
3913 assert!(
3914 err.contains("THEORY.md"),
3915 "missing render-determinism citation in {err:?}"
3916 );
3917 }
3918
3919 #[test]
3920 fn parse_rejects_multi_digit_zero_magnitude() {
3921 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
3922 // digit-only, parse losslessly to `Duration::ZERO`, but render
3923 // back to `"0s"` (the single-byte canonical form) on the next
3924 // emit. The leading-zero arm refuses the drift class at the
3925 // codec layer; the semantic-zero gate downstream
3926 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
3927 // the single-byte canonical form `"0s"` separately on the
3928 // typed-validate layer.
3929 let err = duration_codec::parse("00s").unwrap_err();
3930 assert!(
3931 err.contains("non-canonical leading zero"),
3932 "expected leading-zero diagnostic in {err:?}"
3933 );
3934 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
3935 }
3936
3937 #[test]
3938 fn parse_rejects_leading_zero_per_hour_window() {
3939 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
3940 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
3941 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
3942 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
3943 // `h` / bare-integer-as-seconds) inherits the same gate.
3944 let err = duration_codec::parse("01h").unwrap_err();
3945 assert!(
3946 err.contains("non-canonical leading zero"),
3947 "expected leading-zero diagnostic in {err:?}"
3948 );
3949 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
3950 }
3951
3952 #[test]
3953 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
3954 // The `parse_accepts_bare_integer_as_seconds` happy-path
3955 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
3956 // multi-byte starts-with-`0`, parses losslessly to
3957 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
3958 // bare-integer surface accepts permissive unit-empty
3959 // shorthand but still must reject leading-zero padding.
3960 let err = duration_codec::parse("030").unwrap_err();
3961 assert!(
3962 err.contains("non-canonical leading zero"),
3963 "expected leading-zero diagnostic in {err:?}"
3964 );
3965 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
3966 }
3967
3968 #[test]
3969 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
3970 // The codec-layer / typed-validate-layer boundary: `"0s"` /
3971 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
3972 // each round-trips losslessly through `render`
3973 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
3974 // accepts them. The downstream semantic-zero gates
3975 // (`SupervisorError::ZeroRestartWindow`,
3976 // `AplicacaoError::PolicyTimeoutZero`,
3977 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
3978 // zero-magnitude authoring at the typed-validate layer above,
3979 // peer with the `rate_limit_codec` codec-layer / typed-
3980 // validate-layer partition for `"0/s"`.
3981 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
3982 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
3983 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
3984 }
3985
3986 #[test]
3987 fn parse_accepts_canonical_magnitude_with_leading_one() {
3988 // The complementary boundary: a future tightening cannot
3989 // drift into rejecting valid canonical magnitudes that
3990 // happen to start with `1` (or any digit `[1-9]`). Pin
3991 // every canonical-unit suffix so the leading-zero arm
3992 // remains strictly narrower than the digit-only arm.
3993 assert_eq!(
3994 duration_codec::parse("100ms").unwrap(),
3995 Duration::from_millis(100)
3996 );
3997 assert_eq!(
3998 duration_codec::parse("100s").unwrap(),
3999 Duration::from_secs(100)
4000 );
4001 assert_eq!(
4002 duration_codec::parse("10m").unwrap(),
4003 Duration::from_secs(600)
4004 );
4005 assert_eq!(
4006 duration_codec::parse("10h").unwrap(),
4007 Duration::from_secs(36_000)
4008 );
4009 }
4010
4011 #[test]
4012 fn restart_window_serde_rejects_leading_zero() {
4013 // The shared codec backs `SupervisorSpec::restart_window`
4014 // (`with = "duration_codec"`) — so the leading-zero arm
4015 // applies on serde deserialize for the typed Supervisor slot.
4016 // A `{"restartWindow":"030s"}` payload that previously round-
4017 // tripped to a different canonical string on next serialize
4018 // is now refused at deserialize with the leading-zero
4019 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
4020 // / `restart_window_serde_rejects_fractional_seconds` on the
4021 // same canonical-form-drift axis.
4022 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
4023 "restartWindow":"030s",
4024 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
4025 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
4026 let msg = err.to_string();
4027 assert!(
4028 msg.contains("non-canonical leading zero"),
4029 "expected leading-zero diagnostic in {msg:?}"
4030 );
4031 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
4032 }
4033
4034 #[test]
4035 fn parse_rejects_leading_whitespace() {
4036 // `" 30s"` — the canonical paste-from-aligned-doc /
4037 // paste-from-YAML-quoted-plain-scalar footgun. Before this
4038 // gate the top-level `s.trim()` at parse entry silently ate
4039 // the leading space and parsed the value to
4040 // `Duration::from_secs(30)`, which then round-tripped through
4041 // `render` to `"30s"` (a *different* canonical string on the
4042 // next emit) — the exact canonical-form-drift class the
4043 // leading-`+` / leading-zero arms already close, extended
4044 // to the whitespace-byte class. Peer with the sibling
4045 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
4046 // the M3 `:politicas` axis.
4047 let err = duration_codec::parse(" 30s").unwrap_err();
4048 assert!(
4049 err.contains("contains whitespace byte"),
4050 "expected whitespace diagnostic in {err:?}"
4051 );
4052 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
4053 assert!(
4054 err.contains("THEORY.md"),
4055 "missing render-determinism contract citation in {err:?}"
4056 );
4057 }
4058
4059 #[test]
4060 fn parse_rejects_trailing_whitespace() {
4061 // `"30s "` — the canonical shell-history / trailing-space
4062 // paste footgun. Before this gate the top-level `s.trim()`
4063 // silently ate the trailing space and parsed to
4064 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
4065 // next emit — same canonical-form drift as the leading-space
4066 // sibling, closed on the same whitespace-byte arm.
4067 let err = duration_codec::parse("30s ").unwrap_err();
4068 assert!(
4069 err.contains("contains whitespace byte"),
4070 "expected whitespace diagnostic in {err:?}"
4071 );
4072 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
4073 }
4074
4075 #[test]
4076 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
4077 // `"30 s"` — the canonical typographically-spaced author
4078 // shape (the same idiom every prose reference to a duration
4079 // renders as, mistakenly retained when the value is pasted
4080 // into a codec-shaped slot). Before this gate the per-part
4081 // `num_part.trim()` / `unit.trim()` calls silently ate the
4082 // whitespace between the magnitude and the unit and parsed
4083 // the value to `Duration::from_secs(30)`, round-tripping to
4084 // `"30s"` — the codec's *internal* whitespace-tolerance
4085 // vector, orthogonal to the leading / trailing surface but
4086 // the same canonical-form-drift class. Pins the arm as
4087 // strictly stronger than the pre-existing top-level
4088 // `s.trim()` behavior: it fires on whitespace anywhere in
4089 // the value, not just at the string boundary.
4090 let err = duration_codec::parse("30 s").unwrap_err();
4091 assert!(
4092 err.contains("contains whitespace byte"),
4093 "expected whitespace diagnostic in {err:?}"
4094 );
4095 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
4096 }
4097
4098 #[test]
4099 fn parse_rejects_tab_byte() {
4100 // `"\t30s"` — the canonical paste-from-indented-doc /
4101 // paste-from-YAML-block-scalar footgun where a tab byte leads
4102 // the magnitude. Pins that the gate covers tab (`0x09`) as
4103 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
4104 // members and both would be silently swallowed by `s.trim()`
4105 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
4106 // space alone to the full ASCII-whitespace set (space `0x20`,
4107 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
4108 // the tab arm as a representative of the non-space members.
4109 let err = duration_codec::parse("\t30s").unwrap_err();
4110 assert!(
4111 err.contains("contains whitespace byte"),
4112 "expected whitespace diagnostic in {err:?}"
4113 );
4114 assert!(
4115 err.contains("0x09"),
4116 "missing offending tab byte in {err:?}"
4117 );
4118 }
4119
4120 #[test]
4121 fn restart_window_serde_rejects_whitespace() {
4122 // The shared codec backs `SupervisorSpec::restart_window`
4123 // (`with = "duration_codec"`) — so the whitespace arm
4124 // applies on serde deserialize for the typed Supervisor slot.
4125 // A `{"restartWindow":" 30s"}` payload that previously round-
4126 // tripped to a different canonical string on next serialize
4127 // is now refused at deserialize with the whitespace-byte
4128 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
4129 // / `restart_window_serde_rejects_leading_plus` /
4130 // `restart_window_serde_rejects_fractional_seconds` on the
4131 // same canonical-form-drift axis.
4132 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
4133 "restartWindow":" 30s",
4134 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
4135 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
4136 let msg = err.to_string();
4137 assert!(
4138 msg.contains("contains whitespace byte"),
4139 "expected whitespace diagnostic in {msg:?}"
4140 );
4141 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
4142 }
4143
4144 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
4145 //
4146 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
4147 // duration codec — closes the strictly-complementary class the
4148 // byte-scan cannot see, through the lifted
4149 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
4150 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
4151 // and `:politicas :circuit-breaker :window` simultaneously via
4152 // this shared codec.
4153
4154 #[test]
4155 fn duration_codec_parse_rejects_leading_nbsp() {
4156 // NBSP prefix — the strictly-complementary drift class the
4157 // ASCII byte-scan cannot see. `str::trim` strips it silently
4158 // and the value drifts to `"30s"` on next serialize.
4159 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
4160 assert!(
4161 err.contains("non-ASCII Unicode whitespace character"),
4162 "expected non-ASCII whitespace diagnostic in {err:?}"
4163 );
4164 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
4165 }
4166
4167 #[test]
4168 fn duration_codec_parse_rejects_trailing_line_separator() {
4169 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
4170 // footgun.
4171 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
4172 assert!(
4173 err.contains("non-ASCII Unicode whitespace character"),
4174 "expected non-ASCII whitespace diagnostic in {err:?}"
4175 );
4176 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
4177 }
4178
4179 #[test]
4180 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
4181 // Positive-control pin: every ASCII-only canonical form the
4182 // renderer emits stays accepted through the new arm.
4183 assert_eq!(
4184 duration_codec::parse("30s").unwrap(),
4185 Duration::from_secs(30)
4186 );
4187 assert_eq!(
4188 duration_codec::parse("500ms").unwrap(),
4189 Duration::from_millis(500)
4190 );
4191 assert_eq!(
4192 duration_codec::parse("1h").unwrap(),
4193 Duration::from_secs(3600)
4194 );
4195 }
4196
4197 #[test]
4198 fn restart_window_serde_rejects_non_ascii_whitespace() {
4199 // The shared codec backs `SupervisorSpec::restart_window` — so
4200 // the new non-ASCII Unicode whitespace arm applies on serde
4201 // deserialize for the typed Supervisor slot. A
4202 // `{"restartWindow":" 30s"}` payload that previously
4203 // survived the ASCII byte-scan (only ASCII whitespace was
4204 // refused) is now refused at deserialize with the
4205 // non-ASCII-whitespace-and-codepoint diagnostic.
4206 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
4207 \"restartWindow\":\"\u{00A0}30s\",\
4208 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
4209 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
4210 let msg = err.to_string();
4211 assert!(
4212 msg.contains("non-ASCII Unicode whitespace character"),
4213 "expected non-ASCII whitespace diagnostic in {msg:?}"
4214 );
4215 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
4216 }
4217
4218 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
4219
4220 #[test]
4221 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
4222 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
4223 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
4224 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
4225 // name the exact camelCase JSON keys the
4226 // `#[serde(rename_all = "camelCase")]` attribute on
4227 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
4228 // field carries `Some(_)` / non-empty) and pin that each canonical
4229 // byte-sequence appears verbatim in the JSON — a future accidental
4230 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
4231 // name flip at the derive attribute (any of which would silently
4232 // break every downstream JSON consumer that reaches for one of the
4233 // four consts via `Value::get(...)`) surfaces here as a build-time
4234 // test failure at `supervisor.rs`, not as an apply-time
4235 // `.get(<stale-canonical-const>)` returning `None` far from the
4236 // derive-attr drift's commit. Peer with the sibling
4237 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
4238 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
4239 // M2 typed-slot family established, extended here to close the
4240 // top-level Supervisor axis.
4241 let spec = SupervisorSpec {
4242 estrategia: RestartStrategy::OneForOne,
4243 max_restarts: 5,
4244 restart_window: Some(Duration::from_secs(60)),
4245 children: vec![ChildSpec {
4246 caixa: "w".into(),
4247 versao: "^0.1".into(),
4248 restart: RestartPolicy::Permanent,
4249 }],
4250 };
4251 let json = serde_json::to_string(&spec).unwrap();
4252 for key in [
4253 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
4254 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
4255 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
4256 crate::render::SUPERVISOR_KEY_CHILDREN,
4257 ] {
4258 let quoted = format!("\"{key}\"");
4259 assert!(
4260 json.contains("ed),
4261 "serialized SupervisorSpec must carry the lifted \
4262 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
4263 the JSON emission (got: {json})",
4264 );
4265 }
4266 }
4267
4268 #[test]
4269 fn supervisor_key_consts_are_pairwise_distinct() {
4270 // Cross-axis drift-detection pin: a future collapse of two
4271 // canonical top-level byte-strings onto the same value (e.g. an
4272 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
4273 // also read `"estrategia"`) would silently reroute every
4274 // downstream probe on one axis onto the sibling axis's overlay
4275 // entry and pass every propagation-probe test that expected only
4276 // the stale axis's value. Peer of the sibling four-way distinct
4277 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
4278 let all = [
4279 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
4280 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
4281 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
4282 crate::render::SUPERVISOR_KEY_CHILDREN,
4283 ];
4284 for (i, a) in all.iter().enumerate() {
4285 for b in all.iter().skip(i + 1) {
4286 assert_ne!(
4287 a, b,
4288 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
4289 canonical byte-sequences — got `{a}` == `{b}`",
4290 );
4291 }
4292 }
4293 }
4294
4295 #[test]
4296 fn supervisor_key_consts_are_lower_camel_case_shape() {
4297 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
4298 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
4299 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
4300 // capital, no whitespace / dots) — the canonical shape the
4301 // `#[serde(rename_all = "camelCase")]` derive produces on
4302 // `SupervisorSpec`. A future flip to a non-camelCase attribute
4303 // at the derive surfaces both here (this test fails on the
4304 // stale-constant shape) and at
4305 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
4306 // (that test fails on the mismatch between const and derive).
4307 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
4308 // (d8b8b4f) on the sibling M2 `:limits` axis.
4309 for key in [
4310 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
4311 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
4312 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
4313 crate::render::SUPERVISOR_KEY_CHILDREN,
4314 ] {
4315 assert!(
4316 !key.is_empty(),
4317 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
4318 );
4319 let first = key.chars().next().unwrap();
4320 assert!(
4321 first.is_ascii_lowercase(),
4322 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
4323 (got {key:?}, leads with {first:?})",
4324 );
4325 assert!(
4326 key.chars().all(|c| c.is_ascii_alphanumeric()),
4327 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
4328 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
4329 );
4330 }
4331 }
4332
4333 #[test]
4334 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
4335 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
4336 // (camelCase JSON keys, no leading colon) must never collide
4337 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
4338 // consts (kebab-case author-facing labels with leading colon)
4339 // that sit next to them at `caixa_core::render`. Both families
4340 // cover the same four typed Supervisor slots on two distinct
4341 // axes (author-side kebab vs renderer-side camelCase);
4342 // collapsing either family onto the other's byte-shape would
4343 // silently reroute the render-side probe onto the author-facing
4344 // surface, or vice versa. Peer of the byte-distinctness
4345 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
4346 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
4347 let pairs = [
4348 (
4349 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
4350 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
4351 ),
4352 (
4353 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
4354 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
4355 ),
4356 (
4357 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
4358 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
4359 ),
4360 (
4361 crate::render::SUPERVISOR_KEY_CHILDREN,
4362 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
4363 ),
4364 ];
4365 for (json_key, author_key) in pairs {
4366 assert_ne!(
4367 json_key, author_key,
4368 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
4369 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
4370 got JSON `{json_key}` == author `{author_key}`",
4371 );
4372 }
4373 }
4374
4375 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
4376
4377 #[test]
4378 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
4379 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
4380 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
4381 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
4382 // keys the `#[serde(rename_all = "camelCase")]` attribute on
4383 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
4384 // pin that each canonical byte-sequence appears verbatim in the
4385 // JSON — a future accidental `rename_all = "snake_case"` /
4386 // `"kebab-case"` / verbatim-field-name flip at the derive
4387 // attribute (any of which would silently break every downstream
4388 // JSON consumer that reaches for one of the three consts via
4389 // `Value::get(...)`) surfaces here as a build-time test failure at
4390 // `supervisor.rs`, not as an apply-time
4391 // `.get(<stale-canonical-const>)` returning `None` far from the
4392 // derive-attr drift's commit. Peer with the enclosing
4393 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
4394 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
4395 // discipline the SupervisorSpec top-level lift established,
4396 // extended here to the sibling per-`:children` entry `ChildSpec`
4397 // derive so the last M2 typed-struct sub-block
4398 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
4399 // surface without a lifted serde-key peer joins the substrate's
4400 // "one canonical byte-string per typed serialized-key axis"
4401 // discipline.
4402 let c = ChildSpec {
4403 caixa: "worker".into(),
4404 versao: "^0.1".into(),
4405 restart: RestartPolicy::Permanent,
4406 };
4407 let json = serde_json::to_string(&c).unwrap();
4408 for key in [
4409 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
4410 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
4411 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
4412 ] {
4413 let quoted = format!("\"{key}\"");
4414 assert!(
4415 json.contains("ed),
4416 "serialized ChildSpec must carry the lifted \
4417 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
4418 in the JSON emission (got: {json})",
4419 );
4420 }
4421 }
4422
4423 #[test]
4424 fn supervisor_child_key_consts_are_pairwise_distinct() {
4425 // Cross-axis drift-detection pin: a future collapse of two
4426 // canonical `ChildSpec` per-entry byte-strings onto the same
4427 // value (e.g. an accidental copy-paste flip of
4428 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
4429 // silently reroute every downstream probe on one axis onto the
4430 // sibling axis's overlay entry and pass every propagation-probe
4431 // test that expected only the stale axis's value. Peer of the
4432 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
4433 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
4434 // pair (ce80ca0).
4435 let all = [
4436 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
4437 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
4438 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
4439 ];
4440 for (i, a) in all.iter().enumerate() {
4441 for b in all.iter().skip(i + 1) {
4442 assert_ne!(
4443 a, b,
4444 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
4445 distinct canonical byte-sequences — got `{a}` == `{b}`",
4446 );
4447 }
4448 }
4449 }
4450
4451 #[test]
4452 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
4453 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
4454 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
4455 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
4456 // capital, no whitespace / dots) — the canonical shape the
4457 // `#[serde(rename_all = "camelCase")]` derive produces on
4458 // `ChildSpec`. A future flip to a non-camelCase attribute at the
4459 // derive surfaces both here (this test fails on the
4460 // stale-constant shape) and at
4461 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
4462 // (that test fails on the mismatch between const and derive).
4463 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
4464 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
4465 for key in [
4466 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
4467 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
4468 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
4469 ] {
4470 assert!(
4471 !key.is_empty(),
4472 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
4473 );
4474 let first = key.chars().next().unwrap();
4475 assert!(
4476 first.is_ascii_lowercase(),
4477 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
4478 byte (got {key:?}, leads with {first:?})",
4479 );
4480 assert!(
4481 key.chars().all(|c| c.is_ascii_alphanumeric()),
4482 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
4483 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
4484 );
4485 }
4486 }
4487
4488 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
4489
4490 #[test]
4491 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
4492 // The fail-before-pass-after pin: pre-lift there was no
4493 // single-source binding between the [`RestartStrategy`] variant
4494 // name the un-`rename`d `Serialize` derive emits under
4495 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
4496 // every downstream cluster-side dispatcher (the future
4497 // wasm-operator's per-supervisor sibling-restart branch, the
4498 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4499 // admission-time enum-arm bind, the `caixa-operator`'s
4500 // hierarchical reconciliation scheduler's per-strategy fan-out)
4501 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
4502 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
4503 // override, or a variant rename in the source — would silently
4504 // rebrand the emitted scalar under one spelling while every
4505 // downstream dispatcher still probed the other, with the failure
4506 // surfacing at the operator's reconcile posture (subtrees coming
4507 // up under the `default()` `OneForOne` arm rather than the typed
4508 // slot's declared strategy — a bad child would then only take
4509 // itself down instead of the sibling set the author intended, so
4510 // shared-state children fall out of sync) far from the source
4511 // rebrand commit and with no field naming the drift. Pinning the
4512 // two paths (the `Serialize` derive's serialized string AND the
4513 // [`RestartStrategy::as_str`] helper) to the same four lifted
4514 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
4515 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
4516 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
4517 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
4518 // byte-strings makes any future drift on either endpoint fail
4519 // here at caixa-core build time. Peer of the M3
4520 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
4521 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
4522 // three-path-convergence discipline, extended to close the
4523 // OTP-shaped per-supervisor sibling-restart axis.
4524 for (variant, expected) in [
4525 (
4526 RestartStrategy::OneForOne,
4527 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
4528 ),
4529 (
4530 RestartStrategy::OneForAll,
4531 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
4532 ),
4533 (
4534 RestartStrategy::RestForOne,
4535 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
4536 ),
4537 (
4538 RestartStrategy::SimpleOneForOne,
4539 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
4540 ),
4541 ] {
4542 let json = serde_json::to_string(&variant).unwrap();
4543 assert_eq!(
4544 json,
4545 format!("\"{expected}\""),
4546 "RestartStrategy::{variant:?} must serialize to {expected:?}"
4547 );
4548 assert_eq!(
4549 variant.as_str(),
4550 expected,
4551 "RestartStrategy::{variant:?}.as_str() must return the lifted \
4552 SUPERVISOR_ESTRATEGIA_* constant"
4553 );
4554 }
4555 }
4556
4557 #[test]
4558 fn supervisor_estrategia_consts_are_pairwise_distinct() {
4559 // Cross-arm drift-detection pin: a future collapse of two
4560 // canonical variant byte-strings onto the same value (e.g. an
4561 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
4562 // to also read `"OneForOne"`) would silently reroute every
4563 // downstream operator's per-strategy dispatch onto the sibling
4564 // arm's reconcile branch and pass every propagation-probe test
4565 // that expected only the stale arm's value — the mis-strategied
4566 // subtree would come up with the wrong sibling-restart posture
4567 // on every subsequent failure. Peer of the sibling four-way
4568 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
4569 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
4570 let all = [
4571 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
4572 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
4573 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
4574 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
4575 ];
4576 for (i, a) in all.iter().enumerate() {
4577 for (j, b) in all.iter().enumerate() {
4578 if i != j {
4579 assert_ne!(
4580 a, b,
4581 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
4582 — got duplicate {a:?} at indices {i} and {j}",
4583 );
4584 }
4585 }
4586 }
4587 }
4588
4589 #[test]
4590 fn restart_strategy_display_routes_through_as_str_helper() {
4591 // The fail-before-pass-after pin on the first half of the
4592 // three-path convergence: pre-convergence the sibling
4593 // OTP-shape typed enum [`RestartStrategy`] carried a
4594 // [`std::fmt::Display`] surface via its
4595 // `#[discriminant(also_display)]` gen-platform derive route,
4596 // which arrived kebab-case as `"one-for-one"` /
4597 // `"one-for-all"` / `"rest-for-one"` /
4598 // `"simple-one-for-one"` while the wire format ran as
4599 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
4600 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
4601 // Every consumer reaching for a strategy byte-string past the
4602 // wire format had to pick between three paths
4603 // ([`RestartStrategy::as_str`], the `Serialize` derive's
4604 // serialized string, or `format!("{v}")` on the
4605 // discriminant-Display route), any two of which a future
4606 // variant rename or `#[serde(rename_all = "kebab-case")]`
4607 // attribute would silently desynchronize. Wiring
4608 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
4609 // closes the third path: every `format!("{v}")` call reaches
4610 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
4611 // const the wire format and the [`RestartStrategy::as_str`]
4612 // helper already route through, so a future variant rename
4613 // lands at exactly one place. Pin the routing here so a future
4614 // `impl std::fmt::Display for RestartStrategy`
4615 // reimplementation that hand-rolls the arms instead of
4616 // delegating to [`RestartStrategy::as_str`] fails at
4617 // caixa-core build time. Peer of the M3
4618 // `placement_strategy_display_routes_through_as_str_helper`
4619 // (cc8f749) which the M3 axis converged first.
4620 for &variant in RestartStrategy::ALL {
4621 assert_eq!(
4622 variant.to_string(),
4623 variant.as_str(),
4624 "RestartStrategy::{variant:?} Display must route through \
4625 RestartStrategy::as_str (single source of truth: the lifted \
4626 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
4627 );
4628 }
4629 }
4630
4631 #[test]
4632 fn restart_strategy_display_matches_serialized_wire_byte_string() {
4633 // The fail-before-pass-after pin on the second half of the
4634 // three-path convergence: `Display` (user-facing text) agrees
4635 // byte-for-byte with the `Serialize` derive's wire format
4636 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
4637 // scalar) on every variant. Pre-convergence the two paths
4638 // were structurally independent — a future
4639 // `#[serde(rename_all = "kebab-case")]` attribute on the
4640 // enum would silently rebrand the emitted wire scalar
4641 // (`one-for-one`, `one-for-all`, `rest-for-one`,
4642 // `simple-one-for-one`) while every consumer that
4643 // pretty-prints the strategy (the future wasm-operator's
4644 // per-supervisor sibling-restart-strategy diagnostic line,
4645 // the future `feira app graph` per-supervisor strategy line,
4646 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4647 // materializer's admission-webhook rejection body) would
4648 // still emit the PascalCase form the `as_str` / `Display`
4649 // route returns, with the mismatch surfacing at consumer
4650 // parse time / operator dispatch time far from the source
4651 // rebrand commit. Pin the two paths byte-for-byte here so any
4652 // future serde-attribute or variant-rename drift is a
4653 // caixa-core-build-time test failure at this call, not a
4654 // silent per-consumer dispatch miss. Peer of the M3
4655 // `placement_strategy_display_matches_serialized_wire_byte_string`
4656 // (cc8f749) which the M3 axis converged first.
4657 for &variant in RestartStrategy::ALL {
4658 let wire = serde_json::to_string(&variant).unwrap();
4659 let unquoted = wire
4660 .strip_prefix('"')
4661 .and_then(|s| s.strip_suffix('"'))
4662 .expect("serialized RestartStrategy is a JSON string");
4663 assert_eq!(
4664 variant.to_string(),
4665 unquoted,
4666 "RestartStrategy::{variant:?} Display byte-string must match the \
4667 Serialize derive's wire byte-string (three-path convergence: \
4668 Display + as_str + Serialize all resolve to the same \
4669 SUPERVISOR_ESTRATEGIA_* const)"
4670 );
4671 }
4672 }
4673
4674 #[test]
4675 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
4676 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
4677 // exhaustive-iteration surface: every variant appears exactly
4678 // once, and the slice length matches the arm count of the
4679 // closed set. Every consumer that walks the accepted-strategy
4680 // set (a future `feira supervisor --estrategia …` CLI-side
4681 // arg-parse's "did you mean" hint, a future M4 admission-
4682 // webhook's rejection body naming the accepted-`:estrategia`
4683 // list, the [`RestartStrategy::from_wire`] reverse-projection
4684 // consumers that iterate the accept-set for diagnostic
4685 // rendering) reads through this slice, so a future arm addition
4686 // that grows the enum but forgets to grow [`Self::ALL`]
4687 // silently truncates every downstream consumer's accept-set at
4688 // the same pre-addition boundary — this pin fails at caixa-core
4689 // build time on the pairwise-distinct + arm-count invariants.
4690 //
4691 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
4692 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
4693 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
4694 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4695 // pins on the peer closed-set typed-enum axes.
4696 let all: &[RestartStrategy] = RestartStrategy::ALL;
4697 assert_eq!(
4698 all.len(),
4699 4,
4700 "RestartStrategy::ALL must enumerate every variant of the \
4701 four-arm closed set (OneForOne, OneForAll, RestForOne, \
4702 SimpleOneForOne); got {all:?}"
4703 );
4704 for (i, a) in all.iter().enumerate() {
4705 for (j, b) in all.iter().enumerate() {
4706 if i != j {
4707 assert_ne!(
4708 a, b,
4709 "RestartStrategy::ALL must carry every variant exactly \
4710 once — got duplicate {a:?} at indices {i} and {j}"
4711 );
4712 }
4713 }
4714 }
4715 for variant in [
4716 RestartStrategy::OneForOne,
4717 RestartStrategy::OneForAll,
4718 RestartStrategy::RestForOne,
4719 RestartStrategy::SimpleOneForOne,
4720 ] {
4721 assert!(
4722 all.contains(&variant),
4723 "RestartStrategy::ALL must contain {variant:?} — a future arm \
4724 addition that grows the enum but forgets to grow the ALL slice \
4725 silently truncates every downstream consumer's accept-set at \
4726 the pre-addition boundary"
4727 );
4728 }
4729 }
4730
4731 #[test]
4732 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
4733 // Fail-before-pass-after pin on the forward accept-set of the
4734 // [`RestartStrategy::from_wire`] reverse projection: every
4735 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
4736 // constant the [`RestartStrategy::as_str`] emitter walks parses
4737 // back to its paired variant. Any future arm addition that
4738 // grows the emitter's `as_str` match but forgets to grow the
4739 // parser's `from_wire` match silently splits the two halves of
4740 // the round-trip — the wire byte-string one non-serde consumer
4741 // parses from the one the emitter wrote — with the failure
4742 // surfacing at parse time far from the rebrand commit. Pinning
4743 // the four-arm accept-set here catches the drift at caixa-core
4744 // build time.
4745 //
4746 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
4747 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
4748 // accept-set pins on the peer closed-set typed-enum `str → Self`
4749 // axes.
4750 for (wire, expected) in [
4751 (
4752 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
4753 RestartStrategy::OneForOne,
4754 ),
4755 (
4756 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
4757 RestartStrategy::OneForAll,
4758 ),
4759 (
4760 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
4761 RestartStrategy::RestForOne,
4762 ),
4763 (
4764 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
4765 RestartStrategy::SimpleOneForOne,
4766 ),
4767 ] {
4768 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
4769 panic!(
4770 "RestartStrategy::from_wire({wire:?}) must accept every \
4771 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
4772 lifted canonical byte-string that RestartStrategy::{expected:?} \
4773 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
4774 )
4775 });
4776 assert_eq!(
4777 parsed, expected,
4778 "RestartStrategy::from_wire({wire:?}) must return \
4779 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
4780 );
4781 }
4782 }
4783
4784 #[test]
4785 fn restart_strategy_from_wire_round_trips_through_as_str() {
4786 // Fail-before-pass-after pin on the closed round-trip between
4787 // the forward [`RestartStrategy::as_str`] emitter and the
4788 // reverse [`RestartStrategy::from_wire`] parser: for every
4789 // variant in [`RestartStrategy::ALL`], parsing the emitter's
4790 // output must return exactly the same variant. Any per-arm
4791 // divergence — a future arm added to `as_str` but not
4792 // `from_wire`, an accidental copy-paste flip in one but not
4793 // the other — silently splits the emit and parse halves and
4794 // the failure surfaces at consumer parse time far from the
4795 // drift site. The `ALL`-iterating shape means a future arm
4796 // addition picks up the coverage by construction.
4797 //
4798 // Peer of the sibling
4799 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
4800 // (18c7342) round-trip pin on
4801 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
4802 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
4803 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
4804 for &variant in RestartStrategy::ALL {
4805 let wire = variant.as_str();
4806 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
4807 panic!(
4808 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
4809 must be Some({variant:?}) — the two halves of the round-trip \
4810 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
4811 got None on wire byte-string {wire:?}"
4812 )
4813 });
4814 assert_eq!(
4815 parsed, variant,
4816 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
4817 must round-trip to the same variant; got {parsed:?}"
4818 );
4819 }
4820 }
4821
4822 #[test]
4823 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
4824 // Fail-before-pass-after pin on the closed-set refusal
4825 // discipline of [`RestartStrategy::from_wire`]: every
4826 // byte-string outside the four-arm accept-set returns `None`
4827 // rather than silently collapsing onto the [`Default`]
4828 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
4829 // exercised here sweeps the load-bearing drift shapes: the
4830 // empty string (a stripped serde-attribute drift), all-
4831 // whitespace strings (the canonical text-editor accidental
4832 // padding shape), the kebab-case dispatcher-catalog identities
4833 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
4834 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
4835 // derived [`std::str::FromStr`] accept-set, which parses the
4836 // *other* axis of this enum's two-axis split and must not leak
4837 // into the `from_wire` PascalCase-wire accept-set), the
4838 // lowercased single-word forms (`"oneforone"`), the padded
4839 // canonical scalar (`" OneForOne "`), the trailing-newline
4840 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
4841 // (`"AllForOne"` — the canonical typo direction).
4842 //
4843 // Peer of the sibling
4844 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
4845 // (2aa6d23) +
4846 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
4847 // (18c7342) refusal pins on the peer closed-set typed-enum
4848 // axes.
4849 for bad in [
4850 "",
4851 " ",
4852 "\n",
4853 "\t",
4854 "one-for-one",
4855 "one-for-all",
4856 "rest-for-one",
4857 "simple-one-for-one",
4858 "oneforone",
4859 "OneForOnes",
4860 "one_for_one",
4861 "one for one",
4862 "ONEFORONE",
4863 "OneForOne ",
4864 " OneForOne",
4865 " SimpleOneForOne ",
4866 "OneForOne\n",
4867 "restforone",
4868 "REST_FOR_ONE",
4869 "AllForOne",
4870 "Simple",
4871 "?",
4872 ] {
4873 assert!(
4874 RestartStrategy::from_wire(bad).is_none(),
4875 "RestartStrategy::from_wire({bad:?}) must return None — the \
4876 parser's accept-set is exactly the four RestartStrategy::as_str \
4877 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
4878 and this byte-string is outside that closed set"
4879 );
4880 }
4881 }
4882
4883 #[test]
4884 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
4885 // Fail-before-pass-after pin on the fourth path of the four-path
4886 // convergence: `from_wire` (the reverse projection) inverts the
4887 // `Serialize` derive's wire byte-string on every variant.
4888 // Together with the pre-existing three-path convergence
4889 // (`Display` + `as_str` + `Serialize` all resolve to the same
4890 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
4891 // pinned by
4892 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
4893 // this closes the round-trip: the wire byte-string the
4894 // `Serialize` derive emits parses back to the same variant
4895 // through `from_wire`, so any future serde-attribute or variant-
4896 // rename drift on the emit half now surfaces as a matched drift
4897 // on the parse half at caixa-core build time — the two halves
4898 // migrate as a unit through the lifted consts on any future
4899 // rename, and the round-trip cannot silently split.
4900 //
4901 // Peer of the sibling
4902 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
4903 // (18c7342) wire-format pin on
4904 // [`crate::aplicacao::PlacementStrategy::from_wire`].
4905 for &variant in RestartStrategy::ALL {
4906 let wire = serde_json::to_string(&variant).unwrap();
4907 let unquoted = wire
4908 .strip_prefix('"')
4909 .and_then(|s| s.strip_suffix('"'))
4910 .expect("serialized RestartStrategy is a JSON string");
4911 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
4912 panic!(
4913 "RestartStrategy::from_wire({unquoted:?}) must accept the \
4914 Serialize derive's wire byte-string for \
4915 RestartStrategy::{variant:?} — the four-path convergence \
4916 (Display + as_str + Serialize + from_wire) resolves through \
4917 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
4918 )
4919 });
4920 assert_eq!(
4921 parsed, variant,
4922 "RestartStrategy::from_wire of the Serialize derive's wire \
4923 byte-string for RestartStrategy::{variant:?} must round-trip \
4924 to the same variant; got {parsed:?}"
4925 );
4926 }
4927 }
4928
4929 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
4930
4931 #[test]
4932 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
4933 // The fail-before-pass-after pin: pre-lift there was no
4934 // single-source binding between the [`RestartPolicy`] variant
4935 // name the un-`rename`d `Serialize` derive emits under
4936 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
4937 // byte-string every downstream cluster-side dispatcher (the
4938 // future wasm-operator's per-child post-exit restart-decision
4939 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4940 // materializer's admission-time enum-arm bind, the
4941 // `caixa-operator`'s hierarchical reconciliation scheduler's
4942 // per-child-policy fan-out) probes verbatim. A future
4943 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
4944 // or a per-variant `#[serde(rename = "…")]` override, or a
4945 // variant rename in the source — would silently rebrand the
4946 // emitted scalar under one spelling while every downstream
4947 // dispatcher still probed the other, with the failure surfacing
4948 // at the operator's reconcile posture (children coming up under
4949 // the `default()` `Permanent` arm rather than the typed slot's
4950 // declared policy — a `:temporary` `oneShot` child would be
4951 // restarted on clean exit, treating the successful-completion
4952 // signal as failure and re-running the completion-terminal
4953 // one-shot indefinitely; a `:transient` child that clean-exited
4954 // would be restarted, masking the clean-completion contract)
4955 // far from the source rebrand commit and with no field naming
4956 // the drift. Pinning the two paths (the `Serialize` derive's
4957 // serialized string AND the [`RestartPolicy::as_str`] helper)
4958 // to the same three lifted
4959 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
4960 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
4961 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
4962 // byte-strings makes any future drift on either endpoint fail
4963 // here at caixa-core build time. Peer of the sibling
4964 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
4965 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
4966 // and the M3
4967 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
4968 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
4969 // same three-path-convergence discipline, extended to close the
4970 // third OTP-shaped closed-enum discriminator axis on the caixa
4971 // typed surface (per-child restart-decision policy).
4972 for (variant, expected) in [
4973 (
4974 RestartPolicy::Permanent,
4975 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
4976 ),
4977 (
4978 RestartPolicy::Temporary,
4979 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
4980 ),
4981 (
4982 RestartPolicy::Transient,
4983 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
4984 ),
4985 ] {
4986 let json = serde_json::to_string(&variant).unwrap();
4987 assert_eq!(
4988 json,
4989 format!("\"{expected}\""),
4990 "RestartPolicy::{variant:?} must serialize to {expected:?}"
4991 );
4992 assert_eq!(
4993 variant.as_str(),
4994 expected,
4995 "RestartPolicy::{variant:?}.as_str() must return the lifted \
4996 SUPERVISOR_CHILD_RESTART_* constant"
4997 );
4998 }
4999 }
5000
5001 #[test]
5002 fn supervisor_child_restart_consts_are_pairwise_distinct() {
5003 // Cross-arm drift-detection pin: a future collapse of two
5004 // canonical variant byte-strings onto the same value (e.g. an
5005 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
5006 // to also read `"Permanent"`) would silently reroute every
5007 // downstream operator's per-child-policy dispatch onto the
5008 // sibling arm's reconcile branch and pass every propagation-probe
5009 // test that expected only the stale arm's value — a `:transient`
5010 // child would come up under the `:permanent` restart-decision
5011 // posture on every subsequent clean exit, so a completion-terminal
5012 // child would be restarted indefinitely against its declared
5013 // policy. Peer of the sibling
5014 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
5015 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
5016 // and the four-way distinct pin
5017 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
5018 // top-level `SUPERVISOR_KEY_*` axis.
5019 let all = [
5020 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
5021 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
5022 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
5023 ];
5024 for (i, a) in all.iter().enumerate() {
5025 for (j, b) in all.iter().enumerate() {
5026 if i != j {
5027 assert_ne!(
5028 a, b,
5029 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
5030 — got duplicate {a:?} at indices {i} and {j}",
5031 );
5032 }
5033 }
5034 }
5035 }
5036
5037 #[test]
5038 fn restart_policy_display_routes_through_as_str_helper() {
5039 // The fail-before-pass-after pin on the first half of the
5040 // three-path convergence: pre-convergence [`RestartPolicy`]
5041 // carried a [`std::fmt::Display`] surface via its
5042 // `#[discriminant(also_display)]` gen-platform derive route,
5043 // which arrived kebab-case as `"permanent"` / `"temporary"`
5044 // / `"transient"` on this three-arm enum (whose variant
5045 // names each collapse to their own lowercase form under the
5046 // kebab-case transform) while the wire format ran as
5047 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
5048 // through the un-`rename`d serde derive. Every consumer
5049 // reaching for a policy byte-string past the wire format had
5050 // to pick between three paths ([`RestartPolicy::as_str`],
5051 // the `Serialize` derive's serialized string, or
5052 // `format!("{v}")` on the discriminant-Display route), any
5053 // two of which a future variant rename or
5054 // `#[serde(rename_all = "kebab-case")]` attribute would
5055 // silently desynchronize. Wiring [`std::fmt::Display`]
5056 // through [`RestartPolicy::as_str`] closes the third path:
5057 // every `format!("{v}")` call reaches the same lifted
5058 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
5059 // wire format and the [`RestartPolicy::as_str`] helper
5060 // already route through, so a future variant rename lands at
5061 // exactly one place. Pin the routing here so a future
5062 // `impl std::fmt::Display for RestartPolicy`
5063 // reimplementation that hand-rolls the arms instead of
5064 // delegating to [`RestartPolicy::as_str`] fails at
5065 // caixa-core build time. Peer of the sibling
5066 // [`restart_strategy_display_routes_through_as_str_helper`]
5067 // on the per-supervisor sibling-restart-strategy axis and
5068 // the M3
5069 // `placement_strategy_display_routes_through_as_str_helper`
5070 // (cc8f749) — the third of three OTP-shape closed-enum
5071 // discriminator axes on the caixa typed surface now
5072 // converged onto the same three-path
5073 // (Display → as_str → lifted const) discipline.
5074 for variant in [
5075 RestartPolicy::Permanent,
5076 RestartPolicy::Temporary,
5077 RestartPolicy::Transient,
5078 ] {
5079 assert_eq!(
5080 variant.to_string(),
5081 variant.as_str(),
5082 "RestartPolicy::{variant:?} Display must route through \
5083 RestartPolicy::as_str (single source of truth: the lifted \
5084 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
5085 );
5086 }
5087 }
5088
5089 #[test]
5090 fn restart_policy_display_matches_serialized_wire_byte_string() {
5091 // The fail-before-pass-after pin on the second half of the
5092 // three-path convergence: `Display` (user-facing text) agrees
5093 // byte-for-byte with the `Serialize` derive's wire format
5094 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
5095 // scalar) on every variant. Pre-convergence the two paths
5096 // were structurally independent — a future
5097 // `#[serde(rename_all = "kebab-case")]` attribute on the
5098 // enum would silently rebrand the emitted wire scalar
5099 // (`permanent`, `temporary`, `transient`) while every
5100 // consumer that pretty-prints the policy (the future
5101 // wasm-operator's per-child post-exit restart-decision
5102 // diagnostic line, the future `feira app graph` per-child
5103 // restart column, the future M4
5104 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5105 // per-child admission-webhook rejection body) would still
5106 // emit the PascalCase form the `as_str` / `Display` route
5107 // returns, with the mismatch surfacing at consumer parse
5108 // time / operator dispatch time far from the source rebrand
5109 // commit. Pin the two paths byte-for-byte here so any future
5110 // serde-attribute or variant-rename drift is a
5111 // caixa-core-build-time test failure at this call, not a
5112 // silent per-consumer dispatch miss. Peer of the sibling
5113 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
5114 // on the per-supervisor sibling-restart-strategy axis and
5115 // the M3
5116 // `placement_strategy_display_matches_serialized_wire_byte_string`
5117 // (cc8f749).
5118 for variant in [
5119 RestartPolicy::Permanent,
5120 RestartPolicy::Temporary,
5121 RestartPolicy::Transient,
5122 ] {
5123 let wire = serde_json::to_string(&variant).unwrap();
5124 let unquoted = wire
5125 .strip_prefix('"')
5126 .and_then(|s| s.strip_suffix('"'))
5127 .expect("serialized RestartPolicy is a JSON string");
5128 assert_eq!(
5129 variant.to_string(),
5130 unquoted,
5131 "RestartPolicy::{variant:?} Display byte-string must match the \
5132 Serialize derive's wire byte-string (three-path convergence: \
5133 Display + as_str + Serialize all resolve to the same \
5134 SUPERVISOR_CHILD_RESTART_* const)"
5135 );
5136 }
5137 }
5138
5139 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
5140 //
5141 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
5142 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
5143 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
5144 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
5145 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
5146 // the peer per-`:upgrade-from :from` axis. The three pins jointly
5147 // brace the accessor against every future silent detour that would
5148 // desynchronize it from the raw `.caixa` field access every consumer
5149 // previously open-coded.
5150
5151 #[test]
5152 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
5153 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
5154 // [`ChildSpec::nome`] must return the `:children :caixa` field
5155 // byte-for-byte across every DNS-1123-label value the upstream
5156 // [`crate::render::require_valid_dns_1123_label`] gate at
5157 // `SupervisorSpec::validate` admits. Peer of the sibling
5158 // `membro_nome_returns_caixa_byte_equal_across_permutations`
5159 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
5160 // substrate-primitive accessor must byte-equal the raw field
5161 // access verbatim across every author-declared value" discipline
5162 // extended to the M2 supervisor-tree per-`:children` arm. Pins
5163 // against a future silent detour that re-normalized the child
5164 // identity (an accidental `.to_lowercase()` — every `:children
5165 // :caixa` is validated as a DNS-1123 label upstream, so any
5166 // re-normalization is redundant + a drift surface between the
5167 // validator and the accessor), a namespace-prefix rewrite (an
5168 // accidental `format!("{namespace}/{caixa}")` per-CR
5169 // fully-qualified rewrite that didn't land on the peer axes), or
5170 // a per-cluster alias stamp the future wasm-operator's
5171 // hierarchical reconciliation scheduler authors on one consumer
5172 // without the others. Five values sweep the accept-set the
5173 // DNS-1123 gate upstream admits (short single-word / dashed /
5174 // v-suffixed / mixed-digit child names).
5175 for name in [
5176 "worker",
5177 "cache-server",
5178 "scratch-job",
5179 "orders-v2",
5180 "session-8080",
5181 ] {
5182 let c = ChildSpec {
5183 caixa: name.into(),
5184 versao: "^0.1".into(),
5185 restart: RestartPolicy::Permanent,
5186 };
5187 assert_eq!(
5188 c.nome(),
5189 name,
5190 "ChildSpec::nome must return :children :caixa verbatim \
5191 (got {:?}, expected {name:?})",
5192 c.nome(),
5193 );
5194 assert_eq!(
5195 c.nome(),
5196 c.caixa.as_str(),
5197 "ChildSpec::nome must byte-equal the .caixa field access",
5198 );
5199 }
5200 }
5201
5202 #[test]
5203 fn child_spec_nome_borrows_from_caixa_storage() {
5204 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
5205 // `&str` slice that borrows from the typed slot's own [`String`]
5206 // storage — same-address invariant with `c.caixa.as_str()`. Pins
5207 // against a future silent detour that allocated a fresh `String`
5208 // (`self.caixa.clone()` in the body would type-check but silently
5209 // drop the borrow, and every downstream consumer that assumed
5210 // the returned slice outlives `&self` would break on a stale-
5211 // reference use-after-free — the [`crate::render::insert_first_seen`]
5212 // dedup key at [`SupervisorSpec::validate`], the
5213 // [`validate_no_self_supervision`] equality check against the
5214 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
5215 // borrow — each would silently misbehave if this accessor
5216 // produced a detached copy). Peer of the sibling
5217 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
5218 // M3 per-`:membros` axis and the
5219 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
5220 // first M2 slot scalar accessor.
5221 let c = ChildSpec {
5222 caixa: "worker".into(),
5223 versao: "^0.1".into(),
5224 restart: RestartPolicy::Permanent,
5225 };
5226 let name = c.nome();
5227 let caixa_slice = c.caixa.as_str();
5228 assert_eq!(
5229 name.as_ptr(),
5230 caixa_slice.as_ptr(),
5231 "ChildSpec::nome must borrow from the .caixa String's backing \
5232 storage — a fresh allocation here means the accessor no \
5233 longer names the substrate-primitive typed dispatch and \
5234 every downstream consumer would silently carry a detached \
5235 copy",
5236 );
5237 assert_eq!(
5238 name.len(),
5239 caixa_slice.len(),
5240 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
5241 as well as in address",
5242 );
5243 }
5244
5245 #[test]
5246 fn validate_gates_child_nome_through_lifted_accessor() {
5247 // Bilateral coherence pin: every `:children :caixa` that
5248 // [`SupervisorSpec::validate`] accepts is one
5249 // [`crate::render::require_valid_dns_1123_label`] accepts on the
5250 // accessor-projected value, and vice versa on the reject side.
5251 // This closes the "the validator reads through the accessor"
5252 // contract structurally — a future silent detour that made the
5253 // accessor return a different byte-string than the validator
5254 // gates against would surface here as a coverage mismatch, not
5255 // as an apply-time DNS-1123 rejection at
5256 // `metadata.name: Invalid value` far from the caixa.lisp source.
5257 // Peer of the M2 sibling
5258 // `validate_parses_prior_versao_through_lifted_accessor`
5259 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
5260 // `validate_membros` peer discipline.
5261 //
5262 // Accept-set sweep: five DNS-1123-label values the upstream gate
5263 // admits.
5264 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
5265 let s = SupervisorSpec {
5266 children: vec![ChildSpec {
5267 caixa: ok_name.into(),
5268 versao: "^0.1".into(),
5269 restart: RestartPolicy::Permanent,
5270 }],
5271 ..SupervisorSpec::default()
5272 };
5273 s.validate().unwrap_or_else(|e| {
5274 panic!(
5275 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
5276 (upstream DNS-1123 gate accepts it): got {e:?}",
5277 );
5278 });
5279 let c = ChildSpec {
5280 caixa: ok_name.into(),
5281 versao: "^0.1".into(),
5282 restart: RestartPolicy::Permanent,
5283 };
5284 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
5285 .unwrap_or_else(|()| {
5286 panic!(
5287 "require_valid_dns_1123_label must accept the accessor-projected \
5288 :children :caixa {ok_name:?}",
5289 );
5290 });
5291 }
5292 // Reject-set sweep: five DNS-1123-label-violating shapes the
5293 // upstream gate refuses (empty / uppercase / underscore / dot /
5294 // leading-hyphen). Every rejection at the validator must
5295 // correspond to a rejection when the accessor's projected value
5296 // is fed back through the shared gate.
5297 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
5298 let s = SupervisorSpec {
5299 children: vec![ChildSpec {
5300 caixa: bad_name.into(),
5301 versao: "^0.1".into(),
5302 restart: RestartPolicy::Permanent,
5303 }],
5304 ..SupervisorSpec::default()
5305 };
5306 let err = s.validate().unwrap_err();
5307 assert!(
5308 matches!(
5309 err,
5310 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
5311 ),
5312 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
5313 via the DNS-1123 gate: got {err:?}",
5314 );
5315 let c = ChildSpec {
5316 caixa: bad_name.into(),
5317 versao: "^0.1".into(),
5318 restart: RestartPolicy::Permanent,
5319 };
5320 assert!(
5321 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
5322 .is_err(),
5323 "require_valid_dns_1123_label must reject the accessor-projected \
5324 :children :caixa {bad_name:?}",
5325 );
5326 }
5327 }
5328
5329 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
5330 //
5331 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
5332 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
5333 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
5334 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
5335 // trio on the peer per-`:children` `String`-carry axis. The three pins
5336 // jointly brace the accessor against every future silent detour that
5337 // would desynchronize it from the raw `.versao` field access the
5338 // requirement gate + error carrier previously open-coded.
5339 //
5340 // Closes the last unlifted per-`:children` `String`-carry axis: the
5341 // pair (`nome`, `versao_requirement`) now jointly projects the
5342 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
5343 // consumer that fans on per-child identity + version pin reads,
5344 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
5345 // pair discipline verbatim.
5346 #[test]
5347 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
5348 // The canonical per-`:children` child-`:versao`-scalar pin:
5349 // [`ChildSpec::versao_requirement`] must return the `:children
5350 // :versao` field byte-for-byte across every Cargo-shaped semver
5351 // requirement value the upstream
5352 // [`crate::render::require_valid_versao_requirement`] gate admits.
5353 // Peer of the sibling
5354 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
5355 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
5356 // substrate-primitive accessor must byte-equal the raw field
5357 // access verbatim across every author-declared value" discipline
5358 // extended to the M2 supervisor-tree per-`:children` arm. Pins
5359 // against a future silent detour that re-canonicalized the
5360 // requirement (an accidental `.to_string()` via
5361 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
5362 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
5363 // silently drifted the error carrier's quoted requirement away
5364 // from the source `caixa.lisp`, an accidental whitespace trim on
5365 // `"^ 0.1"` that no consumer ever produced from the field-access
5366 // side, an accidental per-cluster lacre-projected concrete-version
5367 // rewrite that didn't land on the peer requirement-gate call).
5368 // Five values sweep the accept-set the shared
5369 // [`crate::render::require_valid_versao_requirement`] gate admits
5370 // (caret / tilde / exact / wildcard / bare-major).
5371 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
5372 let c = ChildSpec {
5373 caixa: "worker".into(),
5374 versao: req.into(),
5375 restart: RestartPolicy::Permanent,
5376 };
5377 assert_eq!(
5378 c.versao_requirement(),
5379 req,
5380 "ChildSpec::versao_requirement must return :children :versao \
5381 verbatim (got {:?}, expected {req:?})",
5382 c.versao_requirement(),
5383 );
5384 assert_eq!(
5385 c.versao_requirement(),
5386 c.versao.as_str(),
5387 "ChildSpec::versao_requirement must byte-equal the .versao \
5388 field access",
5389 );
5390 }
5391 }
5392
5393 #[test]
5394 fn child_spec_versao_requirement_borrows_from_versao_storage() {
5395 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
5396 // return a `&str` slice that borrows from the typed slot's own
5397 // [`String`] storage — same-address invariant with
5398 // `c.versao.as_str()`. Pins against a future silent detour that
5399 // allocated a fresh `String` (`self.versao.clone()` in the body
5400 // would type-check but silently drop the borrow, and every
5401 // downstream consumer that assumed the returned slice outlives
5402 // `&self` — the [`crate::render::require_valid_versao_requirement`]
5403 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
5404 // `.to_string()` carrier's byte-length assumption — would silently
5405 // misbehave if this accessor produced a detached copy). Peer of
5406 // the sibling `child_spec_nome_borrows_from_caixa_storage`
5407 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
5408 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
5409 // pin on the peer per-`:membros` `:versao` axis.
5410 let c = ChildSpec {
5411 caixa: "worker".into(),
5412 versao: "^0.1".into(),
5413 restart: RestartPolicy::Permanent,
5414 };
5415 let req = c.versao_requirement();
5416 let versao_slice = c.versao.as_str();
5417 assert_eq!(
5418 req.as_ptr(),
5419 versao_slice.as_ptr(),
5420 "ChildSpec::versao_requirement must borrow from the .versao \
5421 String's backing storage — a fresh allocation here means the \
5422 accessor no longer names the substrate-primitive typed \
5423 dispatch and every downstream consumer would silently carry \
5424 a detached copy",
5425 );
5426 assert_eq!(
5427 req.len(),
5428 versao_slice.len(),
5429 "ChildSpec::versao_requirement and .versao.as_str() must \
5430 byte-equal in length as well as in address",
5431 );
5432 }
5433
5434 #[test]
5435 fn validate_gates_child_versao_through_lifted_accessor() {
5436 // Bilateral coherence pin: every `:children :versao` that
5437 // [`SupervisorSpec::validate`] accepts is one
5438 // [`crate::render::require_valid_versao_requirement`] accepts on
5439 // the accessor-projected value, and vice versa on the reject side.
5440 // This closes the "the validator reads through the accessor"
5441 // contract structurally — a future silent detour that made the
5442 // accessor return a different byte-string than the validator gates
5443 // against would surface here as a coverage mismatch, not as a
5444 // resolver-time semver-parse rejection at lacre-closure time far
5445 // from the caixa.lisp source. Peer of the sibling
5446 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
5447 // the per-`:children :caixa` axis and the M2
5448 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
5449 // on the peer per-`:upgrade-from :from` axis.
5450 //
5451 // Accept-set sweep: five Cargo-shaped semver requirement values
5452 // the upstream gate admits (caret / tilde / exact / wildcard /
5453 // bare-major).
5454 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
5455 let s = SupervisorSpec {
5456 children: vec![ChildSpec {
5457 caixa: "worker".into(),
5458 versao: ok_req.into(),
5459 restart: RestartPolicy::Permanent,
5460 }],
5461 ..SupervisorSpec::default()
5462 };
5463 s.validate().unwrap_or_else(|e| {
5464 panic!(
5465 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
5466 (upstream versao-requirement gate accepts it): got {e:?}",
5467 );
5468 });
5469 let c = ChildSpec {
5470 caixa: "worker".into(),
5471 versao: ok_req.into(),
5472 restart: RestartPolicy::Permanent,
5473 };
5474 crate::render::require_valid_versao_requirement(
5475 c.versao_requirement(),
5476 || (),
5477 |_reason| (),
5478 )
5479 .unwrap_or_else(|()| {
5480 panic!(
5481 "require_valid_versao_requirement must accept the accessor-projected \
5482 :children :versao {ok_req:?}",
5483 );
5484 });
5485 }
5486 // Reject-set sweep: five requirement-violating shapes the upstream
5487 // gate refuses. The empty string closes the empty-first arm of the
5488 // shared [`crate::render::require_valid_versao_requirement`]
5489 // cascade; the four non-empty arms exercise distinct semver-parse
5490 // failure modes the M3 peer per-`:membros` reject-set already pins
5491 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
5492 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
5493 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
5494 // shared parser routing means the same reject-set must fail
5495 // identically at the M2 supervisor-tree per-`:children` accessor
5496 // arm here. Every rejection at the validator must correspond to a
5497 // rejection when the accessor's projected value is fed back
5498 // through the shared gate.
5499 //
5500 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
5501 // `"not-a-semver"` are intentionally *not* in the reject-set: the
5502 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
5503 // and the identifier-tail arm's grammar admits some non-canonical
5504 // shapes — matching what the M3 peer test suite already documents
5505 // as the shared parser's accept-set edges.)
5506 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
5507 let s = SupervisorSpec {
5508 children: vec![ChildSpec {
5509 caixa: "worker".into(),
5510 versao: bad_req.into(),
5511 restart: RestartPolicy::Permanent,
5512 }],
5513 ..SupervisorSpec::default()
5514 };
5515 let err = s.validate().unwrap_err();
5516 assert!(
5517 matches!(
5518 err,
5519 SupervisorError::EmptyChildVersion { .. }
5520 | SupervisorError::ChildVersaoInvalid { .. }
5521 ),
5522 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
5523 via the versao-requirement gate: got {err:?}",
5524 );
5525 let c = ChildSpec {
5526 caixa: "worker".into(),
5527 versao: bad_req.into(),
5528 restart: RestartPolicy::Permanent,
5529 };
5530 assert!(
5531 crate::render::require_valid_versao_requirement(
5532 c.versao_requirement(),
5533 || (),
5534 |_reason| (),
5535 )
5536 .is_err(),
5537 "require_valid_versao_requirement must reject the accessor-projected \
5538 :children :versao {bad_req:?}",
5539 );
5540 }
5541 }
5542
5543 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
5544 //
5545 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
5546 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
5547 // already project the `String`-carry `(caixa, versao)` fields; the
5548 // `Copy`-composite-enum `restart` field is the third and final axis).
5549 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
5550 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
5551 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
5552 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
5553 // strategy scalar accessor — same "one typed dispatch on the substrate
5554 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
5555 // extended onto the M2 supervisor-slot per-`:children` restart-decision
5556 // axis. The pin below covers the accessor's byte-equal projection
5557 // against the raw field access across every variant in the closed
5558 // accept-set (`Permanent`, `Transient`, `Temporary`).
5559
5560 #[test]
5561 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
5562 // The canonical per-`:children` restart-decision-policy-scalar
5563 // pin: [`ChildSpec::restart`] must return the `:children :restart`
5564 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
5565 // typed slot's own [`RestartPolicy`] storage across every variant
5566 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
5567 // Pins against a future silent detour that re-derived the policy
5568 // from a peer axis (an accidental fallback to
5569 // `if is_supervisor_child { Permanent } else { Temporary }` that
5570 // collapsed the child's kind axis into the restart discriminator),
5571 // a variant remap the operator authors on one consumer without the
5572 // other, or a stale-derive detour that substituted
5573 // [`RestartPolicy::default`] when the field held any explicit
5574 // variant (which would silently collapse the distinction between
5575 // "author explicitly declared `:restart Permanent`" and "author
5576 // omitted the slot and inherited the default" the future
5577 // per-cluster restart-decision override slot depends on).
5578 //
5579 // Peer of the sibling per-`:supervisor`
5580 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5581 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
5582 // axis and the M3
5583 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
5584 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
5585 // — same "the substrate-primitive accessor must byte-equal the raw
5586 // field access verbatim across every author-declared value"
5587 // discipline extended onto the M2 supervisor-slot per-`:children`
5588 // restart-decision-policy axis, closing the last unlifted axis on
5589 // the per-`:children` [`ChildSpec`] type.
5590 for restart in [
5591 RestartPolicy::Permanent,
5592 RestartPolicy::Transient,
5593 RestartPolicy::Temporary,
5594 ] {
5595 let c = ChildSpec {
5596 caixa: "worker".into(),
5597 versao: "^0.1".into(),
5598 restart,
5599 };
5600 assert_eq!(
5601 c.restart(),
5602 restart,
5603 "ChildSpec::restart must return :children :restart \
5604 verbatim (got {:?}, expected {restart:?})",
5605 c.restart(),
5606 );
5607 assert_eq!(
5608 c.restart(),
5609 c.restart,
5610 "ChildSpec::restart accessor and .restart field access \
5611 must byte-equal — the accessor is the substrate-primitive \
5612 typed dispatch every downstream per-child restart-\
5613 decision consumer must route through",
5614 );
5615 }
5616 }
5617
5618 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
5619 //
5620 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
5621 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
5622 // distribution-strategy accessor discipline onto the M2 supervisor-slot
5623 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
5624 // scalar axis. The two pins below cover (1) the accessor's byte-equal
5625 // projection against the raw field access across every variant in the
5626 // closed accept-set, and (2) the two-consumer coherence between the
5627 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
5628 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
5629 // carrier's `estrategia:` field — peer of the sibling M3
5630 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
5631 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
5632 // pair on the per-`:placement` distribution-strategy axis.
5633
5634 #[test]
5635 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
5636 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
5637 // pin: [`SupervisorSpec::estrategia`] must return the
5638 // `:supervisor :estrategia` field verbatim as a
5639 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
5640 // [`RestartStrategy`] storage across every variant in the closed
5641 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
5642 // `SimpleOneForOne`). Pins against a future silent detour that
5643 // re-derived the strategy from a peer axis (an accidental
5644 // fallback to `if children.is_empty() { SimpleOneForOne } else {
5645 // OneForOne }` collapse that read the children-count axis into
5646 // the strategy discriminator), a variant remap the operator
5647 // authors on one consumer without the other, or a stale-derive
5648 // detour that substituted [`RestartStrategy::default`] when the
5649 // field held any explicit variant (which would silently collapse
5650 // the distinction between "author explicitly declared
5651 // `:estrategia OneForOne`" and "author omitted the slot and
5652 // inherited the default" the future per-cluster strategy override
5653 // slot depends on). Peer of the sibling M3
5654 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
5655 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
5656 // axis — same "the substrate-primitive accessor must byte-equal
5657 // the raw field access verbatim across every author-declared
5658 // value" discipline extended onto the M2 supervisor-slot
5659 // per-`:supervisor` sibling-restart-strategy axis.
5660 for &estrategia in RestartStrategy::ALL {
5661 // `SimpleOneForOne` requires `children.is_empty()`; the peer
5662 // three strategies require a non-empty static children list.
5663 // Build each shape coherently so the pin's fixture would
5664 // itself pass [`SupervisorSpec::validate`] once fed through
5665 // the sibling coherence pin below — the byte-equal projection
5666 // asserted here is a strictly weaker property (a `Copy` field
5667 // read) that does not depend on `validate` running, but
5668 // keeping the fixture validate-clean means a future extension
5669 // of the pin to exercise `validate` end-to-end does not have
5670 // to re-author the children shape.
5671 //
5672 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5673 // shape partition through the [`gen_platform::IsVariant`]
5674 // derive-generated
5675 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
5676 // than the raw `matches!(estrategia, RestartStrategy::
5677 // SimpleOneForOne)` open-coded pattern-match — same closed-
5678 // set-typed-enum arm-discriminator dispatch discipline the
5679 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
5680 // convergence (915a934) extended onto its two paired positive
5681 // / negated `matches!` sites and the peer
5682 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5683 // predicate convergence (766ec63) extended onto the M3 mesh-
5684 // slot per-`:placement` distribution-strategy discriminator
5685 // axis. See the sibling `round_trip_all_strategies` and the
5686 // peer `manifest::tests::
5687 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5688 // fixture for the two peer sites the same lift closes on.
5689 let children = if estrategia.is_simple_one_for_one() {
5690 Vec::new()
5691 } else {
5692 vec![ChildSpec {
5693 caixa: "worker".into(),
5694 versao: "^0.1".into(),
5695 restart: RestartPolicy::Permanent,
5696 }]
5697 };
5698 let s = SupervisorSpec {
5699 estrategia,
5700 children,
5701 ..SupervisorSpec::default()
5702 };
5703 assert_eq!(
5704 s.estrategia(),
5705 estrategia,
5706 "SupervisorSpec::estrategia must return :supervisor :estrategia \
5707 verbatim (got {:?}, expected {estrategia:?})",
5708 s.estrategia(),
5709 );
5710 assert_eq!(
5711 s.estrategia(),
5712 s.estrategia,
5713 "SupervisorSpec::estrategia accessor and .estrategia field \
5714 access must byte-equal — the accessor is the substrate-\
5715 primitive typed dispatch every downstream sibling-restart-\
5716 strategy consumer must route through",
5717 );
5718 }
5719 }
5720
5721 #[test]
5722 fn validate_reads_through_lifted_estrategia_accessor() {
5723 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
5724 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
5725 // dispatch (which reads through [`SupervisorSpec::estrategia`]
5726 // to fan across the strategy-arm shape-gate cascades) and the
5727 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
5728 // error carrier's `estrategia:` field (which reads through
5729 // [`SupervisorSpec::estrategia`] to name the strategy the empty
5730 // `:children` list was declared against) must both key off the
5731 // lifted accessor, so any future rebrand on the typed slot's
5732 // reader shape lands at exactly one place. Pins the two-site
5733 // coherence by exercising the `NoChildren` error surface end-to-
5734 // end across every non-`SimpleOneForOne` variant and asserting
5735 // the surfaced `estrategia:` field byte-equals the accessor's
5736 // return. Peer of the sibling M3
5737 // `validate_placement_reads_through_lifted_estrategia_accessor`
5738 // (921fe1b) three-consumer coherence pin on the per-`:placement`
5739 // distribution-strategy axis.
5740 for estrategia in [
5741 RestartStrategy::OneForOne,
5742 RestartStrategy::OneForAll,
5743 RestartStrategy::RestForOne,
5744 ] {
5745 let s = SupervisorSpec {
5746 estrategia,
5747 children: Vec::new(),
5748 ..SupervisorSpec::default()
5749 };
5750 let err = s.validate().unwrap_err();
5751 match err {
5752 SupervisorError::NoChildren { estrategia: e } => {
5753 assert_eq!(
5754 e,
5755 s.estrategia(),
5756 "NoChildren.estrategia must byte-equal \
5757 SupervisorSpec::estrategia() — the empty-`:children` \
5758 refusal reads through the lifted accessor",
5759 );
5760 assert_eq!(
5761 e, estrategia,
5762 "NoChildren.estrategia must carry the author-declared \
5763 :supervisor :estrategia variant verbatim (got {e:?}, \
5764 expected {estrategia:?})",
5765 );
5766 }
5767 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
5768 }
5769 }
5770 }
5771
5772 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
5773 //
5774 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
5775 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
5776 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
5777 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
5778 // The two pins below cover (1) the accessor's byte-equal projection
5779 // against the raw field access across every representative value in
5780 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
5781 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
5782 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
5783 // zero-floor / cap composition — the validate gate and the accessor
5784 // must route through the same substrate-primitive typed dispatch, so
5785 // any future silent detour that had the accessor perform a
5786 // bounds-collapsing clamp would fail here at caixa-core build time.
5787 // Peer of the sibling M3
5788 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
5789 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
5790
5791 #[test]
5792 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
5793 // The canonical per-`:supervisor` restart-budget-count scalar pin:
5794 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
5795 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
5796 // typed slot's own `u32` storage, byte-equal to the raw field
5797 // access across every representative value in the accept-set —
5798 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
5799 // accept-set the surrounding [`SupervisorSpec::validate`] gate
5800 // carves out on the sibling `ZeroMaxRestarts` refusal),
5801 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
5802 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
5803 // (a past-the-guard sentinel that pins the accessor doesn't
5804 // perform a silent bounds-collapse into `1` on the zero arm —
5805 // validate rejects zero but the accessor must ship the raw slot
5806 // verbatim so a validate-time gate regression surfaces at the
5807 // emit boundary rather than being silently absorbed), `u32::MAX`
5808 // (a past-the-guard sentinel that pins the accessor doesn't
5809 // perform a silent bounds-collapse through
5810 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
5811 //
5812 // Peer of the sibling M3
5813 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
5814 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
5815 // required-scalar axis — same "the substrate-primitive accessor
5816 // must byte-equal the raw field access verbatim across every
5817 // value in the `u32` accept-set" discipline extended onto the M2
5818 // supervisor-slot per-`:supervisor` restart-budget-count axis.
5819 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
5820 let s = SupervisorSpec {
5821 max_restarts,
5822 ..SupervisorSpec::default()
5823 };
5824 assert_eq!(
5825 s.max_restarts(),
5826 max_restarts,
5827 "SupervisorSpec::max_restarts must return :supervisor \
5828 :max-restarts verbatim (got {}, expected {max_restarts})",
5829 s.max_restarts(),
5830 );
5831 assert_eq!(
5832 s.max_restarts(),
5833 s.max_restarts,
5834 "SupervisorSpec::max_restarts accessor and .max_restarts \
5835 field access must byte-equal — the accessor is the \
5836 substrate-primitive typed dispatch every downstream \
5837 restart-budget-count consumer must route through",
5838 );
5839 }
5840 }
5841
5842 #[test]
5843 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
5844 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
5845 // zero-floor + upper-cap bracket must key off
5846 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
5847 // field access. Structurally: a `SupervisorSpec { max_restarts:
5848 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
5849 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5850 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
5851 // (with the offending count carried verbatim from the accessor
5852 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
5853 // lower boundary of the accept-set) plus a `SupervisorSpec {
5854 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
5855 // boundary) must pass validate. The four together jointly pin the
5856 // accessor + validate-gate composition: any future silent detour
5857 // that had the accessor return a fresh `1` on the zero arm (a
5858 // `.max_restarts().max(1)` collapse) would silently absorb the
5859 // `ZeroMaxRestarts` refusal at the accessor boundary and the
5860 // validate gate would accept a struct-literal `SupervisorSpec {
5861 // max_restarts: 0, .. }` — the composition pin catches that at
5862 // caixa-core build time.
5863 //
5864 // Peer of the sibling M3
5865 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
5866 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
5867 // composition axis — same "the validate / shape-gate predicate
5868 // must route through the substrate-primitive typed dispatch"
5869 // discipline extended onto the peer M2 supervisor-slot
5870 // required-`u32` composition axis.
5871 let child = ChildSpec {
5872 caixa: "worker".into(),
5873 versao: "^0.1".into(),
5874 restart: RestartPolicy::Permanent,
5875 };
5876 // Zero-floor arm.
5877 let s = SupervisorSpec {
5878 max_restarts: 0,
5879 children: vec![child.clone()],
5880 ..SupervisorSpec::default()
5881 };
5882 assert_eq!(
5883 s.validate().unwrap_err(),
5884 SupervisorError::ZeroMaxRestarts,
5885 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
5886 — the accessor and the validate gate must route through the \
5887 same substrate-primitive typed dispatch on the zero-floor arm",
5888 );
5889 // Cap arm — the surfaced `max_restarts:` field must byte-equal
5890 // the accessor's return so a future rebrand on the accessor
5891 // lands in the diagnostic without a coordinated rewrite.
5892 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
5893 let s = SupervisorSpec {
5894 max_restarts: over_cap,
5895 children: vec![child.clone()],
5896 ..SupervisorSpec::default()
5897 };
5898 match s.validate().unwrap_err() {
5899 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
5900 assert_eq!(
5901 max_restarts,
5902 s.max_restarts(),
5903 "MaxRestartsExceedsCap.max_restarts must byte-equal \
5904 SupervisorSpec::max_restarts() — the cap-arm refusal \
5905 reads through the lifted accessor",
5906 );
5907 assert_eq!(
5908 max_restarts, over_cap,
5909 "MaxRestartsExceedsCap.max_restarts must carry the \
5910 author-declared :supervisor :max-restarts value \
5911 verbatim (got {max_restarts}, expected {over_cap})",
5912 );
5913 }
5914 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
5915 }
5916 // Lower + upper accept-set boundaries.
5917 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
5918 let s = SupervisorSpec {
5919 max_restarts,
5920 children: vec![child.clone()],
5921 ..SupervisorSpec::default()
5922 };
5923 assert!(
5924 s.validate().is_ok(),
5925 "validate must accept max_restarts == {max_restarts} \
5926 (an accept-set boundary of \
5927 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
5928 );
5929 }
5930 }
5931
5932 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
5933 //
5934 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
5935 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
5936 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
5937 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
5938 // supervisor-slot per-`:supervisor` restart-intensity-denominator
5939 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
5940 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
5941 // per-`:supervisor` scalar-value axis. The three pins below cover
5942 // (1) the accessor's byte-equal projection against the raw field
5943 // access across every representative value in the `Option<Duration>`
5944 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
5945 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
5946 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
5947 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
5948 // `if let Some(w) = self.restart_window() { … }` bracket-arm
5949 // composition — the validate gate and the accessor must route through
5950 // the same substrate-primitive typed dispatch, so any future silent
5951 // detour that had the accessor perform a bounds-collapsing clamp
5952 // would fail here at caixa-core build time, and (3) the accessor's
5953 // by-copy idempotence pin — the returned `Option<Duration>` must
5954 // outlive `&self` and two successive calls must return byte-equal
5955 // values. Peer of the sibling M2
5956 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
5957 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
5958 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
5959 // (7073d0f) pin on the per-`:politicas :timeout` axis.
5960
5961 #[test]
5962 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
5963 // The canonical per-`:supervisor` restart-intensity-denominator
5964 // scalar pin: [`SupervisorSpec::restart_window`] must return the
5965 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
5966 // `Option<Duration>`, `Copy`-projected from the typed slot's own
5967 // `Option<Duration>` storage, byte-equal to the raw field access
5968 // across every representative value in the accept-set — `None`
5969 // (the "never reset — every restart across the supervisor's
5970 // lifetime counts against the sibling `:max-restarts` budget"
5971 // sentinel the field's own docstring names and the peer
5972 // `validate_accepts_none_restart_window` pin locks in on the
5973 // [`SupervisorSpec::validate`] entry-side),
5974 // `Some(Duration::from_millis(1))` (the structural minimum a
5975 // validated `:restart-window` may carry, the integer-millisecond
5976 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
5977 // everything sub-ms; `Duration::ZERO` is separately rejected by
5978 // [`SupervisorError::RestartWindowZero`]),
5979 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
5980 // surrounding [`SupervisorSpec::validate`] gate carves out on the
5981 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
5982 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
5983 // accessor doesn't perform a silent bounds-collapse into `None` on
5984 // the zero-Duration arm — validate rejects zero but the accessor
5985 // must ship the raw slot verbatim so a validate-time gate
5986 // regression surfaces at the emit boundary rather than being
5987 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
5988 // sentinel that pins the accessor doesn't perform a silent
5989 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
5990 // return path).
5991 //
5992 // Peer of the sibling M2
5993 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
5994 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
5995 // sibling M3
5996 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
5997 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
5998 // substrate-primitive accessor must byte-equal the raw field
5999 // access verbatim across every value in the `Option<Duration>`
6000 // accept-set" discipline extended onto the M2 supervisor-slot
6001 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
6002 // silent detour that re-derived the restart-window from a peer
6003 // axis (an accidental `.max_restarts.into()` collapse that read
6004 // the restart-budget-count as a duration — the two axes serve
6005 // different halves of the `MaxIntensity / Period` restart-
6006 // intensity ratio, and confusing them silently inverts the
6007 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
6008 // "zero means never reset" collapse (the canonical
6009 // `Option<Duration>` → `Duration` collapse footgun the
6010 // [`SupervisorError::RestartWindowZero`] validate arm guards on
6011 // the peer zero-floor axis; a zero period either trips on the
6012 // first failure or never trips depending on operator
6013 // interpretation, neither of which is the author's "never reset"
6014 // intent that `None` expresses structurally), or a per-arm
6015 // variant swap that landed on one consumer without the other.
6016 for restart_window in [
6017 None,
6018 Some(Duration::from_millis(1)),
6019 Some(SUPERVISOR_RESTART_WINDOW_MAX),
6020 Some(Duration::ZERO),
6021 Some(Duration::MAX),
6022 ] {
6023 let s = SupervisorSpec {
6024 restart_window,
6025 ..SupervisorSpec::default()
6026 };
6027 assert_eq!(
6028 s.restart_window(),
6029 restart_window,
6030 "SupervisorSpec::restart_window must return :supervisor \
6031 :restart-window verbatim (got {:?}, expected {restart_window:?})",
6032 s.restart_window(),
6033 );
6034 assert_eq!(
6035 s.restart_window(),
6036 s.restart_window,
6037 "SupervisorSpec::restart_window accessor and \
6038 .restart_window field access must byte-equal — the \
6039 accessor is the substrate-primitive typed dispatch every \
6040 downstream restart-intensity-denominator consumer must \
6041 route through",
6042 );
6043 }
6044 }
6045
6046 #[test]
6047 fn validate_restart_window_bracket_arm_routes_through_accessor() {
6048 // Composition pin: [`SupervisorSpec::validate`]'s
6049 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
6050 // zero-floor + integer-millisecond canonical-form + upper-cap
6051 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
6052 // the raw `.restart_window` field access. Structurally: a
6053 // `SupervisorSpec { restart_window: None, .. }` must pass the
6054 // arm gate structurally (the `if let Some(_)` shape returns
6055 // early on the `None` arm — the accessor and the validate gate
6056 // must agree on `None → skip the bracket cascade` so an authored
6057 // `:restart-window ()` structurally routes through the "never
6058 // reset" sentinel path), a `SupervisorSpec { restart_window:
6059 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
6060 // refusal exactly, a `SupervisorSpec { restart_window:
6061 // Some(Duration::from_micros(1500)), .. }` must surface the
6062 // `RestartWindowNotCanonical` refusal exactly (with the offending
6063 // duration carried verbatim from the accessor return), a
6064 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
6065 // + Duration::from_millis(1)), .. }` must surface the
6066 // `RestartWindowExceedsCap` refusal exactly (with the offending
6067 // duration carried verbatim from the accessor return), and a
6068 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
6069 // .. }` (the lower boundary of the accept-set) plus a
6070 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6071 // .. }` (the upper boundary) must pass validate. The six together
6072 // jointly pin the accessor + validate-gate composition: any future
6073 // silent detour that had the accessor return a fresh `None` on any
6074 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
6075 // collapse) would silently absorb the `RestartWindowZero` refusal
6076 // at the accessor boundary and the validate gate would accept a
6077 // struct-literal `SupervisorSpec { restart_window:
6078 // Some(Duration::ZERO), .. }` — the composition pin catches that
6079 // at caixa-core build time.
6080 //
6081 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
6082 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
6083 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
6084 // accessor-composition pin on the per-`:politicas :timeout` axis —
6085 // same "the validate / shape-gate predicate must route through
6086 // the substrate-primitive typed dispatch" discipline extended
6087 // onto the peer M2 supervisor-slot optional-`Duration` axis.
6088 let child = ChildSpec {
6089 caixa: "worker".into(),
6090 versao: "^0.1".into(),
6091 restart: RestartPolicy::Permanent,
6092 };
6093 // None arm — must not surface any :restart-window-shaped refusal;
6094 // the `if let Some(_)` bracket returns early on `None` structurally.
6095 let s = SupervisorSpec {
6096 restart_window: None,
6097 children: vec![child.clone()],
6098 ..SupervisorSpec::default()
6099 };
6100 assert!(
6101 s.validate().is_ok(),
6102 "validate must accept restart_window: None (the never-reset \
6103 sentinel) — the `if let Some(_)` bracket returns early on \
6104 the None arm and the accessor must agree",
6105 );
6106 // Zero-floor arm.
6107 let s = SupervisorSpec {
6108 restart_window: Some(Duration::ZERO),
6109 children: vec![child.clone()],
6110 ..SupervisorSpec::default()
6111 };
6112 assert_eq!(
6113 s.validate().unwrap_err(),
6114 SupervisorError::RestartWindowZero,
6115 "validate must reject restart_window == Some(Duration::ZERO) \
6116 with RestartWindowZero — the accessor and the validate gate \
6117 must route through the same substrate-primitive typed \
6118 dispatch on the zero-floor arm",
6119 );
6120 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
6121 // byte-equal the accessor's return so a future rebrand on the
6122 // accessor lands in the diagnostic without a coordinated rewrite.
6123 let sub_ms = Duration::from_micros(1500);
6124 let s = SupervisorSpec {
6125 restart_window: Some(sub_ms),
6126 children: vec![child.clone()],
6127 ..SupervisorSpec::default()
6128 };
6129 match s.validate().unwrap_err() {
6130 SupervisorError::RestartWindowNotCanonical { window } => {
6131 assert_eq!(
6132 Some(window),
6133 s.restart_window(),
6134 "RestartWindowNotCanonical.window must byte-equal \
6135 SupervisorSpec::restart_window().unwrap() — the \
6136 non-canonical-arm refusal reads through the lifted \
6137 accessor",
6138 );
6139 assert_eq!(
6140 window, sub_ms,
6141 "RestartWindowNotCanonical.window must carry the \
6142 author-declared :supervisor :restart-window value \
6143 verbatim (got {window:?}, expected {sub_ms:?})",
6144 );
6145 }
6146 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6147 }
6148 // Cap arm — the surfaced `window:` field must byte-equal the
6149 // accessor's return.
6150 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6151 let s = SupervisorSpec {
6152 restart_window: Some(over_cap),
6153 children: vec![child.clone()],
6154 ..SupervisorSpec::default()
6155 };
6156 match s.validate().unwrap_err() {
6157 SupervisorError::RestartWindowExceedsCap { window } => {
6158 assert_eq!(
6159 Some(window),
6160 s.restart_window(),
6161 "RestartWindowExceedsCap.window must byte-equal \
6162 SupervisorSpec::restart_window().unwrap() — the \
6163 cap-arm refusal reads through the lifted accessor",
6164 );
6165 assert_eq!(
6166 window, over_cap,
6167 "RestartWindowExceedsCap.window must carry the \
6168 author-declared :supervisor :restart-window value \
6169 verbatim (got {window:?}, expected {over_cap:?})",
6170 );
6171 }
6172 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
6173 }
6174 // Lower + upper accept-set boundaries.
6175 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
6176 let s = SupervisorSpec {
6177 restart_window: Some(restart_window),
6178 children: vec![child.clone()],
6179 ..SupervisorSpec::default()
6180 };
6181 assert!(
6182 s.validate().is_ok(),
6183 "validate must accept restart_window == Some({restart_window:?}) \
6184 (an accept-set boundary of \
6185 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
6186 );
6187 }
6188 }
6189
6190 #[test]
6191 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
6192 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
6193 // `Option<Duration>` by copy — `Duration` is `Copy` (so
6194 // `Option<Duration>` is `Copy`) and the accessor must return by
6195 // value, not by reference. Peer of the sibling M2
6196 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
6197 // per-`:limits :wall-clock` axis and the sibling M3
6198 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
6199 // per-`:politicas :timeout` axis, extended onto the peer M2
6200 // supervisor-slot `Option<Duration>` copy-invariant shape — the
6201 // accessor's returned `Option<Duration>` must outlive `&self`
6202 // (multiple calls must return equal values from a dropped-`&self`
6203 // copy, since the returned Option carries no borrow), and calling
6204 // the accessor twice on the same SupervisorSpec must yield the
6205 // same `Option<Duration>` verbatim (idempotent, no side effects
6206 // on `&self`).
6207 //
6208 // Pins against a future silent detour that returned
6209 // `Option<&Duration>` (which would type-check but silently break
6210 // every downstream caller — the future wasm-operator's
6211 // per-supervisor restart-intensity counter consumes `Duration` by
6212 // value and `&Duration` would fold to a detached copy at the call
6213 // site), an accidental `Option::as_ref()` projection
6214 // (`self.restart_window.as_ref()` would also type-check but
6215 // return `Option<&Duration>`), or a one-arm-only accessor that
6216 // reads `Some(*w)` in the Some arm but reads a fresh
6217 // `Default::default()` (which would collapse to `Duration::ZERO`,
6218 // not `None`) in the None arm — a footgun the
6219 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
6220 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
6221 // requires `Period > 0` and `None` structurally expresses "never
6222 // reset" instead.
6223 for restart_window in [
6224 None,
6225 Some(Duration::from_millis(1)),
6226 Some(Duration::from_secs(60)),
6227 Some(SUPERVISOR_RESTART_WINDOW_MAX),
6228 ] {
6229 let s = SupervisorSpec {
6230 restart_window,
6231 ..SupervisorSpec::default()
6232 };
6233 let first = s.restart_window();
6234 let second = s.restart_window();
6235 assert_eq!(
6236 first, second,
6237 "SupervisorSpec::restart_window must be idempotent — two \
6238 successive calls on the same &self must return the \
6239 same Option<Duration>",
6240 );
6241 assert_eq!(
6242 first, restart_window,
6243 "SupervisorSpec::restart_window must return :supervisor \
6244 :restart-window verbatim by copy — got {first:?}, \
6245 expected {restart_window:?}",
6246 );
6247 }
6248 }
6249
6250 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
6251 //
6252 // The [`SupervisorSpec::children`] accessor lift is the seed of the
6253 // slice-return (`&[T]`) accessor discipline on the substrate — the four
6254 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
6255 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
6256 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
6257 // access at the time of this seed, and inherit this pin family's
6258 // discipline as future compounding runs migrate their consumers. The
6259 // three pins below cover (1) the accessor's byte-equal projection
6260 // against the raw field access across the empty / singleton / cohort
6261 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
6262 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
6263 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
6264 // consumer routing through the accessor on both arms, and (3) the
6265 // per-child validate loop's traversal reading the same slice-view the
6266 // accessor projects. Peer of the sibling M2
6267 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
6268 // two-consumer coherence pin on the per-`:supervisor`
6269 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
6270 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
6271
6272 #[test]
6273 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
6274 // The canonical per-`:supervisor` static-child-list scalar-shape
6275 // pin: [`SupervisorSpec::children`] must return the `:supervisor
6276 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
6277 // slice-view over the same backing buffer the raw
6278 // `self.children.as_slice()` field access borrows from, byte-
6279 // equal across every representative fixture in the accept-set —
6280 // the empty slice (the `SimpleOneForOne`-arm sentinel),
6281 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
6282 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
6283 // with the peer three restart-policy variants in play).
6284 //
6285 // Pins against a future silent detour that returned
6286 // `&Vec<ChildSpec>` (which would type-check but leak the
6287 // storage-side `Vec`'s grow/push/reserve surface no consumer of
6288 // the typed view reaches for), a fresh-allocated
6289 // `Vec<ChildSpec>` copy (which would type-check via a coercion
6290 // but silently break every downstream caller that relied on the
6291 // slice sharing the backing buffer's identity), or an
6292 // out-of-order or length-drifted projection (which would silently
6293 // split the per-child validate loop's traversal input from the
6294 // paired partition-dispatch `.is_empty()` probe's input).
6295 //
6296 // Peer of the sibling
6297 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6298 // (eafb619) `Copy`-composite-enum byte-equal pin on the
6299 // per-`:supervisor` sibling-restart-strategy axis, extended onto
6300 // the per-`:supervisor` static-child-list `Vec`-carry axis.
6301 let fixtures: Vec<Vec<ChildSpec>> = vec![
6302 Vec::new(),
6303 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
6304 vec![
6305 child("worker", "^0.1", RestartPolicy::Permanent),
6306 child("cache-server", "^0.1", RestartPolicy::Transient),
6307 ],
6308 vec![
6309 child("worker", "^0.1", RestartPolicy::Permanent),
6310 child("cache-server", "^0.1", RestartPolicy::Transient),
6311 child("scratch-job", "^0.1", RestartPolicy::Temporary),
6312 ],
6313 ];
6314 for children in fixtures {
6315 let s = SupervisorSpec {
6316 children: children.clone(),
6317 ..SupervisorSpec::default()
6318 };
6319 assert_eq!(
6320 s.children(),
6321 children.as_slice(),
6322 "SupervisorSpec::children must return :supervisor \
6323 :children verbatim (got {:?}, expected {:?})",
6324 s.children(),
6325 children.as_slice(),
6326 );
6327 assert_eq!(
6328 s.children(),
6329 s.children.as_slice(),
6330 "SupervisorSpec::children accessor and \
6331 .children.as_slice() field access must byte-equal — \
6332 the accessor is the substrate-primitive typed \
6333 dispatch every downstream static-child-list consumer \
6334 must route through",
6335 );
6336 assert_eq!(
6337 s.children().len(),
6338 s.children.len(),
6339 "SupervisorSpec::children().len() must byte-equal \
6340 self.children.len() — a length-drift would silently \
6341 split the paired partition-dispatch `.is_empty()` \
6342 probe input from the per-child validate loop's \
6343 traversal input",
6344 );
6345 }
6346 }
6347
6348 #[test]
6349 fn validate_reads_through_lifted_children_accessor() {
6350 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
6351 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
6352 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
6353 // when the accessor projects a non-empty slice under a
6354 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
6355 // `self.children().is_empty()` refusal probe (which must trip
6356 // [`SupervisorError::NoChildren`] when the accessor projects the
6357 // empty slice under any peer estrategia), and the per-child
6358 // validate loop's `for child in self.children()` traversal
6359 // (which must reach every entry in the same order the accessor
6360 // projects) must all key off the lifted accessor, so any future
6361 // rebrand on the typed slot's reader shape lands at exactly one
6362 // place. Pins the three-site coherence by exercising each
6363 // production consumer end-to-end: (1) the
6364 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
6365 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
6366 // refusal under the empty slice + non-`SimpleOneForOne`
6367 // estrategia across every peer variant, and (3) the per-child
6368 // duplicate-detection surface fires on the second entry of a
6369 // two-child cohort that shares a `:caixa` name (which requires
6370 // the loop to reach both entries — a first-entry-only projection
6371 // would silently pass since the dedup HashSet has room for the
6372 // first insert).
6373 //
6374 // Peer of the sibling M2
6375 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
6376 // two-consumer coherence pin on the per-`:supervisor`
6377 // sibling-restart-strategy axis, extended onto the
6378 // per-`:supervisor` static-child-list `Vec`-carry axis.
6379
6380 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
6381 // `SimpleOneForOne` estrategia must trip
6382 // `SimpleOneForOneWithStaticChildren`.
6383 let s = SupervisorSpec {
6384 estrategia: RestartStrategy::SimpleOneForOne,
6385 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
6386 ..SupervisorSpec::default()
6387 };
6388 assert_eq!(
6389 s.validate().unwrap_err(),
6390 SupervisorError::SimpleOneForOneWithStaticChildren,
6391 "SimpleOneForOne + non-empty children must trip \
6392 SimpleOneForOneWithStaticChildren — the accessor projects \
6393 a non-empty slice, and the SimpleOneForOne-arm refusal \
6394 probe reads through the lifted accessor",
6395 );
6396 assert!(
6397 !s.children().is_empty(),
6398 "the SimpleOneForOne-arm refusal input must be a non-empty \
6399 slice per the accessor's projection",
6400 );
6401
6402 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
6403 // under any peer estrategia must trip `NoChildren`.
6404 for estrategia in [
6405 RestartStrategy::OneForOne,
6406 RestartStrategy::OneForAll,
6407 RestartStrategy::RestForOne,
6408 ] {
6409 let s = SupervisorSpec {
6410 estrategia,
6411 children: Vec::new(),
6412 ..SupervisorSpec::default()
6413 };
6414 match s.validate().unwrap_err() {
6415 SupervisorError::NoChildren { estrategia: e } => {
6416 assert_eq!(
6417 e, estrategia,
6418 "NoChildren.estrategia must carry the author-\
6419 declared :supervisor :estrategia variant \
6420 verbatim (got {e:?}, expected {estrategia:?})",
6421 );
6422 }
6423 other => panic!(
6424 "expected NoChildren, got {other:?} for \
6425 estrategia={estrategia:?}"
6426 ),
6427 }
6428 assert!(
6429 s.children().is_empty(),
6430 "the non-SimpleOneForOne-arm refusal input must be the \
6431 empty slice per the accessor's projection",
6432 );
6433 }
6434
6435 // (3) Per-child validate loop: a two-child cohort that shares a
6436 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
6437 // reach both entries through the accessor.
6438 let s = SupervisorSpec {
6439 estrategia: RestartStrategy::OneForOne,
6440 children: vec![
6441 child("worker", "^0.1", RestartPolicy::Permanent),
6442 child("worker", "^0.2", RestartPolicy::Transient),
6443 ],
6444 ..SupervisorSpec::default()
6445 };
6446 match s.validate().unwrap_err() {
6447 SupervisorError::DuplicateChildCaixa { caixa } => {
6448 assert_eq!(
6449 caixa, "worker",
6450 "DuplicateChildCaixa.caixa must carry the shared \
6451 child `:caixa` name verbatim",
6452 );
6453 }
6454 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
6455 }
6456 assert_eq!(
6457 s.children().len(),
6458 2,
6459 "the per-child validate loop's traversal input must be a \
6460 two-element slice per the accessor's projection",
6461 );
6462 }
6463}