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