Skip to main content

caixa_core/
limits.rs

1//! Lunatic-style per-process resource limits — the typed slot of
2//! `caixa.lisp` that wasm-engine consumes at component instantiation.
3//!
4//! See `theory/INSPIRATIONS.md` §III.1 for the prior-art frame: every
5//! caixa Servico runs sandboxed by default; no "trust the author".
6//!
7//! ```lisp
8//! (defcaixa
9//!   :nome   "my-service"
10//!   :versao "0.1.0"
11//!   :kind   Servico
12//!   :limits ((:memory     "64MiB")     ;; max linear memory per instance
13//!            (:fuel       1000000)     ;; max wasm-instructions per request
14//!            (:wall-clock "30s")       ;; max wall-clock per request
15//!            (:cpu        "500m"))     ;; soft cgroup CPU share (millicores)
16//!   :servicos ("servicos/my-service.computeunit.yaml"))
17//! ```
18//!
19//! Authors omit the slot for "no limits" (today's behavior). When set,
20//! wasm-engine M2 wires:
21//!
22//!   - [`LimitsSpec::memory`]      → `wasmtime::StoreLimits::memory_size`
23//!   - [`LimitsSpec::fuel`]        → `Store::set_fuel` + per-tick refill
24//!   - [`LimitsSpec::wall_clock`]  → epoch deadline cancellation
25//!   - [`LimitsSpec::cpu`]         → cgroup-v2 hint propagated via the pod spec
26
27use std::time::Duration;
28
29use serde::{Deserialize, Deserializer, Serialize, Serializer};
30use thiserror::Error;
31
32/// Hard upper bound for `:limits :memory`, in bytes — the
33/// `wasm32-wasip2` linear-memory ceiling. The canonical caixa Servico
34/// compilation target ([`theory/CAIXA-SDLC.md` §V — *Substrate /
35/// Nix*][sdlc-v]) is `wasm32-wasip2`, whose linear memory is 32-bit-
36/// addressed at a 64 KiB page size; the in-spec maximum is
37/// `2^16 pages × 2^16 bytes/page = 2^32` bytes = 4 GiB exactly.
38/// A `:limits :memory` value above this bound is structurally
39/// unreachable under wasm32: wasmtime's `Store::limiter` cannot grow
40/// past the 32-bit address space, so an authored `"8GiB"` either
41/// silently saturates at the engine's effective cap or surfaces as a
42/// `memory.grow` trap at runtime, far from the source caixa.lisp.
43///
44/// Pairs with [`LimitsError::MemoryZero`] (the zero-floor gate added
45/// by the prior typed-shape lift on this axis) to bracket the valid
46/// `:memory` set top-to-bottom: every validated value lies in
47/// `1..=LIMITS_MEMORY_WASM32_MAX_BYTES` (inclusive on both ends).
48/// Renderers ([`crate::render::servico_m2_overlay`] and the M2.5
49/// `wasm-engine` instantiator the ABSORPTION-ROADMAP names as the
50/// downstream wiring) consume the typed value with no re-validation
51/// — the value-shape gate is the structural contract.
52///
53/// Lifted as a typed `pub const` (rather than an inline literal at
54/// the [`LimitsSpec::validate`] call site) so the bound has exactly
55/// one source of truth — a future axis reaching for the same value
56/// (a future `memory64`-target opt-in raising the cap to 2^64, a
57/// wasm-engine smoke test asserting the engine's effective limit
58/// matches the typed bound, the M4 `mesh.pleme.io/v1alpha1/Caixa`
59/// CR materializer's per-`:limits :memory` admission webhook)
60/// reads from one place. Same shape every other typed bound in this
61/// crate carries ([`crate::render::DNS_1123_LABEL_MAX_LEN`],
62/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
63/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
64///
65/// [sdlc-v]: https://github.com/pleme-io/theory/blob/main/CAIXA-SDLC.md
66pub const LIMITS_MEMORY_WASM32_MAX_BYTES: u64 = 4 * 1024 * 1024 * 1024;
67
68/// Structural floor for `:limits :memory`, in bytes — the
69/// `wasm32-wasip2` linear-memory page size. The wasm spec defines
70/// linear memory in fixed 64 KiB pages (`2^16` bytes); every typed
71/// memory cap is consumed by `wasmtime::StoreLimits::memory_size` as a
72/// per-component byte ceiling against which the engine checks every
73/// `memory.grow` request. A cap below one page (`< 65536` bytes) is
74/// structurally a "no wasm linear memory allowed" cap — instantiation
75/// of any wasm component that declares `(memory 1)` (i.e. min=1 page,
76/// the canonical default for every cdylib-shaped wasm component cargo
77/// emits) fails immediately with `memory minimum size of 1 pages
78/// exceeds memory limits`; a min=0 component traps the first
79/// `memory.grow(1)` because the next-page allocation would cross the
80/// sub-page cap. Either way the typed value the wasm-engine consumes
81/// is operationally indistinguishable from [`LimitsError::MemoryZero`]
82/// (no memory at all), but the diagnostic surfaces at engine-load
83/// time rather than at caixa-build time, far from the source
84/// caixa.lisp.
85///
86/// Pairs with [`LIMITS_MEMORY_WASM32_MAX_BYTES`] (the 4 GiB upper
87/// cap added by the prior typed-shape lift on this axis) to bracket
88/// the valid `:memory` set top-to-bottom in *operational* units, not
89/// just byte units: every validated value lies in
90/// `LIMITS_MEMORY_WASM32_PAGE_BYTES..=LIMITS_MEMORY_WASM32_MAX_BYTES`
91/// inclusive on both ends — i.e. at least one wasm32 linear memory
92/// page can be allocated, and at most the wasm32 address-space
93/// ceiling fits.
94///
95/// Lifted as a typed `pub const` (rather than an inline literal at
96/// the [`LimitsSpec::validate`] call site) so the bound has exactly
97/// one source of truth — a future axis reaching for the same value
98/// (a future `memory64`-target opt-in raising the page size, the M4
99/// `mesh.pleme.io/v1alpha1/Caixa` CR materializer's per-`:limits
100/// :memory` admission webhook, a wasm-engine smoke test asserting
101/// every instantiated component can fit one page within its
102/// configured cap) reads from one place. Same single-source-of-truth
103/// shape every typed bound in this crate carries
104/// ([`LIMITS_MEMORY_WASM32_MAX_BYTES`],
105/// [`crate::render::DNS_1123_LABEL_MAX_LEN`]).
106pub const LIMITS_MEMORY_WASM32_PAGE_BYTES: u64 = 64 * 1024;
107
108/// Upper-bound ceiling on the `:limits :wall-clock` axis — every
109/// validated [`LimitsSpec::wall_clock`] past [`LimitsSpec::validate`]
110/// lies in `1ms..=LIMITS_WALL_CLOCK_MAX` (inclusive on both ends,
111/// integer-millisecond magnitudes by the canonical-form gate
112/// immediately preceding).
113///
114/// The typed field is `Option<Duration>` (the zero-floor arm
115/// [`LimitsError::WallClockZero`] already rejects `Duration::ZERO`, and
116/// the canonical-form arm [`LimitsError::WallClockNotCanonical`]
117/// already rejects sub-millisecond residue), so a programmatic struct
118/// literal (`LimitsSpec { wall_clock: Some(Duration::from_secs(86_400)),
119/// .. }` — 24h) and the equivalent author-surface form
120/// (`(:limits (:wall-clock "24h"))` — the codec emits `"<n>h"` for any
121/// integer-hour magnitude) both round-trip cleanly through serde — a
122/// structurally unbounded `Duration` ceiling. A `:wall-clock` value far
123/// above the per-process production band (Lunatic / Wasmtime documented
124/// per-call deadlines sit in the seconds-to-minutes range; Kubernetes
125/// activeDeadlineSeconds typical `≤ 3600s`; the longest per-request
126/// timeout any upstream HTTP runtime documents — Kubernetes
127/// ingress-nginx `proxy_read_timeout` — caps at the same 3600s) turns
128/// the typed per-process deadline into a nominal-only contract: the
129/// wasm-engine's epoch-deadline cancellation reaches for a `Duration`
130/// so long no realistic synchronous wasm call can hit it, the runaway-
131/// process invariant the MESH-COMPOSITION §V "no infinite blocking" CSE
132/// invariant pins at the per-Servico layer degenerates to a runtime,
133/// not build-time, contract. Pairs with the
134/// [`crate::POLICY_TIMEOUT_MAX`] cap on the sibling `:politicas :timeout`
135/// mesh-edge axis and the [`crate::POLICY_BREAKER_WINDOW_MAX`] cap on
136/// the sibling `:politicas :circuit-breaker :window` rolling-window
137/// axis — all three close the "structurally unbounded `Duration`
138/// ceiling on a typed slot" footgun the prior zero-floor-and-canonical-
139/// form-only checks left open.
140///
141/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit
142/// the shared duration codec emits (`"<n>h"` for any integer-hour
143/// magnitude) — every value in the canonical authoring form's
144/// `<integer><unit>` grammar at or below this cap renders to a clean
145/// canonical string — and matches the two sibling typed-`Duration`
146/// caps already lifted to this surface
147/// ([`crate::POLICY_TIMEOUT_MAX`], [`crate::POLICY_BREAKER_WINDOW_MAX`]).
148/// The three typed-`Duration` axes — per-process `:limits :wall-clock`,
149/// per-edge `:politicas :timeout`, per-breaker `:politicas
150/// :circuit-breaker :window` — now share a single uniform top edge so
151/// the next typed-slot wiring (the wasm-engine M2.5 epoch-deadline
152/// cancellation hook, the future caixa-helm `pleme-computeunit` chart's
153/// `:limits` value mapping, the M4 `mesh.pleme.io/v1alpha1/Caixa` CR
154/// materializer's per-`:limits :wall-clock` admission webhook) reaches
155/// for any of the three knowing the value is in `1ms..=1h` without
156/// re-validating at the renderer layer. The cap sits above the
157/// documented per-request playbook band (Envoy / Istio / Linkerd
158/// production `≤ 60s`, AWS App Mesh / ingress-nginx typical `≤ 300s`,
159/// Kubernetes activeDeadlineSeconds typical `≤ 3600s`) and below the
160/// clearly-pathological "effectively no deadline" floor (`24h`, `7d`,
161/// `Duration::MAX`): a value the author can plausibly want for a
162/// long-running synchronous workflow, but a hard wall above which the
163/// per-process deadline is structurally a non-deadline.
164///
165/// Lifted as a typed `pub const` so the bound has exactly one source
166/// of truth — the wasm-engine M2.5 epoch-deadline wiring, a wasm-engine
167/// smoke test asserting the engine's epoch interrupt fires within the
168/// typed bound, the M4 `mesh.pleme.io/v1alpha1/Caixa` CR materializer's
169/// per-`:limits :wall-clock` admission webhook all read from one place.
170/// Same shape every other typed upper bound in this crate carries
171/// ([`LIMITS_MEMORY_WASM32_MAX_BYTES`], [`crate::POLICY_TIMEOUT_MAX`],
172/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
173/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
174/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
175pub const LIMITS_WALL_CLOCK_MAX: Duration = Duration::from_secs(3600);
176
177/// Upper-bound ceiling on the `:limits :cpu` axis, in Kubernetes
178/// millicores — every validated [`LimitsSpec::cpu`] past
179/// [`LimitsSpec::validate`] lies in `1..=LIMITS_CPU_MILLICORES_MAX`
180/// (inclusive on both ends).
181///
182/// The typed field is `Option<u32>` (the zero-floor arm
183/// [`LimitsError::CpuZero`] already rejects `Some(0)` — a zero cgroup
184/// share starves the process), so a programmatic struct literal
185/// (`LimitsSpec { cpu: Some(u32::MAX), .. }` — ≈ 4.3 million cores)
186/// and the equivalent author-surface form (`(:limits (:cpu
187/// "1000000m"))` — the millicore codec parses any `u32`-shaped
188/// magnitude) both round-trip cleanly through serde — a structurally
189/// unbounded `u32` ceiling. The runtime substrate consuming the value
190/// ([`crate::render::servico_m2_overlay`]'s `pleme-computeunit.limits.cpu`
191/// projection, the M2.5 `wasm-engine` instantiator the
192/// `ABSORPTION-ROADMAP` names as the downstream wiring, the future
193/// M4 `mesh.pleme.io/v1alpha1/Caixa` CR materializer's admission
194/// webhook) lands the value verbatim as the K8s pod's
195/// `resources.requests.cpu`. A value far above the largest commodity
196/// node's vCPU count turns the typed slot into an unschedulable hint:
197/// the Kubernetes scheduler refuses to bind the pod to any node
198/// (insufficient `cpu` available), the Servico sits `Pending`
199/// indefinitely, and the per-process CSE invariant (every typed
200/// `:cpu` reaches a node) is a runtime, not build-time, contract —
201/// the canonical declared-but-unschedulable footgun the sibling
202/// `:limits :memory` wasm32-cap arm closes on its peer "cannot be
203/// honored" shape.
204///
205/// The `128_000` (128 cores) ceiling matches the largest commercially
206/// common non-metal cloud Kubernetes node vCPU count (AWS m7i.32xlarge
207/// / c7i.32xlarge = 128 vCPU; Azure HBv3-128rs = 128 vCPU; GCP
208/// c3-standard-128 = 128 vCPU — every major managed-Kubernetes provider
209/// tops out at 128 vCPU on its general-purpose non-metal SKUs) and sits
210/// two orders of magnitude above every realistic per-Servico
211/// production-playbook band (the canonical caixa Servico runs in the
212/// 100m–2000m band; the in-tree
213/// `limits_slot_propagates_into_values_block` smoke test pins
214/// `cpu: Some(500)` = 500m as the load-bearing example, peer to the
215/// `caixa-flux` projector's identical 500m default). A value above this
216/// cap is structurally unschedulable on any commercial managed
217/// Kubernetes node pool: GKE Standard / EKS managed / AKS default
218/// node-group SKU ladders cap at 128 vCPU per node for general-purpose
219/// instance families, so a `:cpu` request above `128_000m` cannot bind to
220/// any node the operator can provision through the standard
221/// cloud-provider control plane. The wasm32-wasip2 single-threaded
222/// execution model the canonical caixa Servico targets
223/// ([`theory/CAIXA-SDLC.md` §V][sdlc-v]) reinforces the structural
224/// argument: a single wasm component cannot saturate more than one
225/// core, so even the Lunatic-style supervised-multi-process host
226/// (`theory/INSPIRATIONS.md` §III.1) — which fans wasm processes across
227/// the host runtime's Tokio thread pool — bounds its useful CPU request
228/// to the host node's vCPU count, never higher.
229///
230/// Lifted as a typed `pub const` (rather than an inline literal at the
231/// [`LimitsSpec::validate`] call site) so the bound has exactly one
232/// source of truth — the future M4
233/// `mesh.pleme.io/v1alpha1/Caixa` CR materializer's per-`:limits :cpu`
234/// admission webhook, the caixa-helm `pleme-computeunit` chart's
235/// resource-request mapping, the M2.5 `wasm-engine` host-runtime
236/// thread-pool sizing hint all read from one place. Same shape every
237/// other typed upper bound in this crate carries
238/// ([`LIMITS_MEMORY_WASM32_MAX_BYTES`], [`LIMITS_WALL_CLOCK_MAX`],
239/// [`crate::POLICY_TIMEOUT_MAX`], [`crate::POLICY_BREAKER_WINDOW_MAX`],
240/// [`crate::POLICY_RATE_LIMIT_MAX`],
241/// [`crate::render::DNS_1123_LABEL_MAX_LEN`]).
242///
243/// [sdlc-v]: https://github.com/pleme-io/theory/blob/main/CAIXA-SDLC.md
244pub const LIMITS_CPU_MILLICORES_MAX: u32 = 128_000;
245
246/// Upper-bound ceiling on the `:limits :fuel` axis, in wasm
247/// instructions per outermost call — every validated
248/// [`LimitsSpec::fuel`] past [`LimitsSpec::validate`] lies in
249/// `1..=LIMITS_FUEL_MAX` (inclusive on both ends).
250///
251/// The typed field is `Option<u64>` (the zero-floor arm
252/// [`LimitsError::FuelZero`] already rejects `Some(0)` — wasmtime
253/// traps the first instruction at `fuel=0`), so a programmatic
254/// struct literal (`LimitsSpec { fuel: Some(u64::MAX), .. }` —
255/// ≈ 1.8 × 10¹⁹ instructions) and the equivalent author-surface
256/// form (`(:limits (:fuel 18446744073709551615))`) both
257/// round-trip cleanly through serde — a structurally unbounded
258/// `u64` ceiling. The runtime substrate consuming the value
259/// ([`crate::render::servico_m2_overlay`]'s
260/// `pleme-computeunit.limits.fuel` projection, the M2.5
261/// `wasm-engine` `Store::set_fuel` call the
262/// `ABSORPTION-ROADMAP` names as the downstream wiring, the
263/// future M4 `mesh.pleme.io/v1alpha1/Caixa` CR materializer's
264/// admission webhook) lands the value verbatim as the
265/// wasmtime store's per-call fuel budget. A value far above any
266/// reachable wasm execution count turns the typed slot into a
267/// no-op budget: the sibling [`LIMITS_WALL_CLOCK_MAX`] (1h)
268/// cap fires before the fuel counter ever drains, the per-call
269/// fuel-tracking contract degenerates to "rely on `:wall-clock`
270/// instead" enforcement, and the per-process CSE invariant
271/// (every typed `:fuel` is a meaningful budget the wasm-engine
272/// can actually consume) is a runtime, not build-time, contract
273/// on every above-cap input — the canonical declared-but-no-op
274/// footgun the sibling `:wall-clock` / `:cpu` / `:memory` cap
275/// arms close on the peer "cannot be honored" /
276/// "unschedulable hint" / "no-op budget" shapes, and the peer
277/// `:politicas :rate-limit` / `:politicas :timeout` /
278/// `:politicas :circuit-breaker :window` /
279/// `:supervisor :max-restarts` cap arms close on every other
280/// `Option<numeric>` axis on the typed Caixa surface.
281///
282/// The `1_000_000_000_000` (10¹² = 1 trillion wasm instructions)
283/// ceiling matches the operational envelope the sibling
284/// [`LIMITS_WALL_CLOCK_MAX`] cap pins: at wasmtime's documented
285/// fuel-tracked execution rate (~10⁸–10⁹ fuel-units per second
286/// on modern x86_64 / aarch64 hosts running wasmtime through
287/// Cranelift — the substrate's wasm32-wasip2 default backend per
288/// the `caixa-feira` runner), the largest realistic per-call
289/// fuel budget reachable within `LIMITS_WALL_CLOCK_MAX` (1h)
290/// sits at ~3.6 × 10¹¹–3.6 × 10¹² fuel-units. The 10¹² cap is
291/// the round-number ceiling above this operational envelope,
292/// sits six orders of magnitude above the canonical fixture
293/// (the in-tree `Caixa::template` documentation and
294/// `caixa-feira` examples carry `:fuel 1_000_000` = 10⁶,
295/// peer to wasmtime's official `Store::set_fuel(1_000_000)`
296/// example in the `wasmtime` book), and surfaces every
297/// paste-from-binary / overflow / u64-magnitude-typo footgun
298/// (`u64::MAX`, `0xFFFF_FFFF_FFFF_FFFF`, large hex literals
299/// confused for instruction-count budgets) at validate time.
300/// A value above this cap is operationally a no-op fuel
301/// counter: the wall-clock deadline ([`LIMITS_WALL_CLOCK_MAX`]
302/// = 3600s × ~10⁹ fuel/sec ≈ 3.6 × 10¹² instructions reachable)
303/// fires before the fuel counter could ever be drained,
304/// so the typed `:fuel` slot becomes a no-op budget far from
305/// the source caixa.lisp. The wasm32-wasip2 single-threaded
306/// execution model the canonical caixa Servico targets
307/// ([`theory/CAIXA-SDLC.md` §V][sdlc-v]) reinforces the
308/// structural argument: a single wasm component cannot
309/// out-execute its host's CPU clock, so even the Lunatic-style
310/// supervised-multi-process host (`theory/INSPIRATIONS.md`
311/// §III.1) bounds its useful fuel-per-call budget to a
312/// per-clock-tick magnitude, never higher.
313///
314/// Lifted as a typed `pub const` (rather than an inline literal
315/// at the [`LimitsSpec::validate`] call site) so the bound has
316/// exactly one source of truth — the future M4
317/// `mesh.pleme.io/v1alpha1/Caixa` CR materializer's per-`:limits
318/// :fuel` admission webhook, the caixa-helm `pleme-computeunit`
319/// chart's fuel-budget mapping, the M2.5 `wasm-engine` host-
320/// runtime `Store::set_fuel` propagation all read from one
321/// place. Same shape every other typed upper bound in this
322/// crate carries ([`LIMITS_MEMORY_WASM32_MAX_BYTES`],
323/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
324/// [`crate::POLICY_TIMEOUT_MAX`],
325/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
326/// [`crate::POLICY_RATE_LIMIT_MAX`],
327/// [`crate::SUPERVISOR_MAX_RESTARTS_MAX`],
328/// [`crate::render::DNS_1123_LABEL_MAX_LEN`]).
329///
330/// [sdlc-v]: https://github.com/pleme-io/theory/blob/main/CAIXA-SDLC.md
331pub const LIMITS_FUEL_MAX: u64 = 1_000_000_000_000;
332
333/// Per-process limits. All fields optional — `None` = unbounded for that axis.
334#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
335#[serde(rename_all = "camelCase")]
336pub struct LimitsSpec {
337    /// Max linear memory in bytes. Authored as a byte-size string
338    /// (`"64MiB"`, `"1GiB"`, `"512KB"`). Round-trips back to the same
339    /// canonical string on serialize.
340    #[serde(
341        default,
342        skip_serializing_if = "Option::is_none",
343        serialize_with = "ser_byte_size",
344        deserialize_with = "de_byte_size"
345    )]
346    pub memory: Option<u64>,
347
348    /// Max wasm instructions per outermost call (`wasmtime` fuel).
349    /// Plain integer; `None` = unbounded.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub fuel: Option<u64>,
352
353    /// Wall-clock cap per outermost call. Authored as a duration
354    /// string (`"30s"`, `"500ms"`, `"2m"`).
355    #[serde(
356        default,
357        skip_serializing_if = "Option::is_none",
358        serialize_with = "ser_duration",
359        deserialize_with = "de_duration"
360    )]
361    pub wall_clock: Option<Duration>,
362
363    /// Soft CPU share. Authored as a Kubernetes-style millicore string
364    /// (`"500m"` for half a core, `"2"` or `"2000m"` for two cores).
365    /// Stored as millicores (u32).
366    #[serde(
367        default,
368        skip_serializing_if = "Option::is_none",
369        serialize_with = "ser_millicores",
370        deserialize_with = "de_millicores"
371    )]
372    pub cpu: Option<u32>,
373}
374
375impl LimitsSpec {
376    /// True when no axis is bounded.
377    #[must_use]
378    pub const fn is_empty(&self) -> bool {
379        self.memory().is_none()
380            && self.fuel().is_none()
381            && self.wall_clock().is_none()
382            && self.cpu().is_none()
383    }
384
385    /// Substrate-canonical per-`:limits` `:memory` Lunatic-per-process
386    /// wasm32-linear-memory byte-cap scalar accessor every consumer of
387    /// the Servico's `wasmtime::StoreLimits::memory_size` propagation
388    /// keys off — returns the author-declared `:limits :memory` typed
389    /// byte-cap verbatim as an `Option<u64>`, copied out of the typed
390    /// slot's own `Option<u64>` storage (`Option<u64>` is `Copy`, so
391    /// the accessor returns by value; no borrow of `&self` past the
392    /// call). `None` when the slot is absent (the "no memory cap
393    /// declared — engine-default applies, today the pre-M2 unbounded-
394    /// linear-memory shape" arm the module-level docstring names on
395    /// [`LimitsSpec::memory`] itself — [`LimitsSpec::is_empty`]'s
396    /// `memory().is_none()` arm reads this predicate too, so an
397    /// authored-but-unset `:limits (:memory ())` round-trips to a
398    /// `servico_m2_overlay` emission structurally identical to one
399    /// that omits the slot entirely).
400    ///
401    /// The `:limits :memory` slot carries the "per-process wasm32
402    /// linear-memory byte-cap" Lunatic-shaped sandboxing contract
403    /// (`theory/INSPIRATIONS.md` §III.1) — the typed slot's
404    /// `Option<u64>` accept-set (zero-floor rejected through
405    /// [`LimitsError::MemoryZero`], wasm32-page-floor rejected through
406    /// [`LimitsError::MemoryBelowWasm32Page`], upper-bounded by
407    /// [`LIMITS_MEMORY_WASM32_MAX_BYTES`], authored as a byte-size
408    /// string that round-trips back to the canonical form through
409    /// [`ser_byte_size`] / [`de_byte_size`]) maps onto the wasmtime
410    /// `Store::limiter`-side `memory_size` projection the wasm-engine
411    /// M2 wires and, via [`crate::render::servico_m2_overlay`], onto
412    /// the `pleme-computeunit` Helm-library-chart values sub-block's
413    /// `limits.memory` key that lands as the ComputeUnit CR's
414    /// `spec.limits.memory` field.
415    ///
416    /// Prior to this lift the `.memory` field was accessed inline at
417    /// four sites inside `impl LimitsSpec` — [`LimitsSpec::is_empty`]'s
418    /// `self.memory.is_none()` arm and three [`LimitsSpec::validate`]
419    /// arms (the numeric zero-floor arm at line 397, the wasm32-page
420    /// structural floor arm at line 427, and the wasm32 upper-cap
421    /// arm at line 449) — four open-coded field-accesses that
422    /// expressed no compile-time link back to the typed slot. A
423    /// future extension of the `:limits :memory` axis to a richer
424    /// author surface — a per-instance memory-declaration override
425    /// the operator pins through a future ComputeUnit CR-side
426    /// `spec.limits.memory` overlay, a split of the single `u64`
427    /// byte-cap into a `{min, max}` pair once wasm32's `(memory M N)`
428    /// two-arg form promotes past its current single-`max` typed
429    /// bound, a wasm64 promotion once the wasm-engine grows past the
430    /// wasm32 4 GiB structural ceiling — would have had to be
431    /// threaded through every open-coded copy in lockstep or the
432    /// emptiness predicate and the validate call would silently
433    /// disagree on which cap a given [`LimitsSpec`] resolves to.
434    /// Lifting the resolution to a typed method on the substrate
435    /// primitive means every downstream consumer of the Servico's
436    /// per-`:limits` byte-cap surface reaches for exactly one typed
437    /// dispatch — the resolver's accept-set migrates as a unit on any
438    /// future axis addition.
439    ///
440    /// First `Option<Copy-T>`-return accessor on the M2 slot family
441    /// (peer of the sibling per-`:politicas` [`crate::MeshPolicy::mtls_required`]
442    /// c0110f1 `Option<bool>` accessor, per-`:politicas`
443    /// [`crate::MeshPolicy::retries`] bdfb399 `Option<u32>` accessor,
444    /// and per-`:politicas` [`crate::MeshPolicy::timeout`] 7073d0f
445    /// `Option<Duration>` accessor on the M3 mesh-slot family — same
446    /// "one typed dispatch on the substrate primitive, thin
447    /// projections at each consumer" discipline extended onto the
448    /// peer per-`:limits` typed-`u64` optional-scalar axis; opens the
449    /// "optional per-slot Copy-T scalar" projection pattern the
450    /// sibling per-`:limits` `:fuel` (Option<u64>) / `:wall-clock`
451    /// (Option<Duration>) / `:cpu` (Option<u32>) future lifts fold
452    /// on). Named `memory()` to match the storage field's name; the
453    /// accessor's identity maps onto the canonical Lunatic-shaped
454    /// `theory/INSPIRATIONS.md` §III.1 vocabulary the slot's docstring
455    /// already carries.
456    #[must_use]
457    pub const fn memory(&self) -> Option<u64> {
458        self.memory
459    }
460
461    /// Substrate-canonical per-`:limits` `:fuel` wasmtime-per-call
462    /// wasm-instruction budget scalar accessor every consumer of the
463    /// Servico's `wasmtime::Store::set_fuel` propagation keys off —
464    /// returns the author-declared `:limits :fuel` typed
465    /// wasm-instruction budget verbatim as an `Option<u64>`, copied
466    /// out of the typed slot's own `Option<u64>` storage
467    /// (`Option<u64>` is `Copy`, so the accessor returns by value; no
468    /// borrow of `&self` past the call). `None` when the slot is
469    /// absent (the "no fuel budget declared — engine-default applies,
470    /// today the pre-M2 unbounded-fuel-counter shape" arm the
471    /// module-level docstring names on [`LimitsSpec::fuel`] itself —
472    /// [`LimitsSpec::is_empty`]'s `fuel().is_none()` arm reads this
473    /// predicate too, so an authored-but-unset `:limits (:fuel ())`
474    /// round-trips to a `servico_m2_overlay` emission structurally
475    /// identical to one that omits the slot entirely).
476    ///
477    /// The `:limits :fuel` slot carries the "per-call wasm-instruction
478    /// budget" wasmtime-shaped sandboxing contract
479    /// (`theory/INSPIRATIONS.md` §III.1 — Lunatic's supervised
480    /// wasm-`Store`-per-process fuel accounting, translated onto
481    /// pleme-io's typed `:limits` slot) — the typed slot's
482    /// `Option<u64>` accept-set (zero-floor rejected through
483    /// [`LimitsError::FuelZero`] because wasmtime traps the first
484    /// instruction at `fuel=0`, upper-bounded by [`LIMITS_FUEL_MAX`]
485    /// (10¹² wasm instructions — the operationally-reachable
486    /// per-call budget within the sibling [`LIMITS_WALL_CLOCK_MAX`]
487    /// 1h ceiling)) maps onto the wasmtime `Store::set_fuel` call
488    /// the M2.5 wasm-engine wires per outermost call and, via
489    /// [`crate::render::servico_m2_overlay`], onto the
490    /// `pleme-computeunit` Helm-library-chart values sub-block's
491    /// `limits.fuel` key that lands as the `ComputeUnit` CR's
492    /// `spec.limits.fuel` field.
493    ///
494    /// Prior to this lift the `.fuel` field was accessed inline at
495    /// two sites inside `impl LimitsSpec` — [`LimitsSpec::is_empty`]'s
496    /// `self.fuel.is_none()` arm and [`LimitsSpec::validate`]'s
497    /// `if let Some(f) = self.fuel { … }` zero-floor + upper-cap
498    /// bracket arm — two open-coded field-accesses that expressed no
499    /// compile-time link back to the typed slot. A future extension
500    /// of the `:limits :fuel` axis to a richer author surface — a
501    /// per-instance `ComputeUnit` CR-side `spec.limits.fuel` overlay
502    /// the operator pins per-cluster, a wasm-instruction-count →
503    /// wasmtime-fuel-unit rescale once the fuel-tracking backend
504    /// switches from Cranelift's implicit 1:1 count to a
505    /// per-opcode-weighted budget, a split of the single
506    /// per-outermost-call `u64` budget into a `{per_call, per_second}`
507    /// pair once the wasm-engine grows a sustained-throughput cap —
508    /// would have had to be threaded through every open-coded copy in
509    /// lockstep or the emptiness predicate and the validate call
510    /// would silently disagree on which fuel budget a given
511    /// [`LimitsSpec`] resolves to. Lifting the resolution to a typed
512    /// method on the substrate primitive means every downstream
513    /// consumer of the Servico's per-`:limits` fuel-budget surface
514    /// reaches for exactly one typed dispatch — the resolver's
515    /// accept-set migrates as a unit on any future axis addition.
516    ///
517    /// Second `Option<Copy-T>`-return accessor on the M2 slot family
518    /// (peer of the sibling per-`:limits` [`LimitsSpec::memory`]
519    /// (620c067) `Option<u64>` accessor — same typed-`u64`
520    /// optional-scalar shape, extended to the peer per-`:limits`
521    /// wasm-instruction-budget axis; sibling to
522    /// [`crate::MeshPolicy::mtls_required`] (c0110f1) / [`crate::MeshPolicy::retries`]
523    /// (bdfb399) / [`crate::MeshPolicy::timeout`] (7073d0f) on the
524    /// closed M3 mesh-slot `Option<Copy-T>` accessor family). The
525    /// pair `(memory(), fuel())` jointly projects the two `Option<u64>`
526    /// axes every M2 `:limits` consumer that fans on
527    /// wasm-linear-memory-cap + wasm-fuel-budget keys off. Two of the
528    /// four `:limits` axes now route through a typed dispatch on the
529    /// substrate primitive; the two remaining (`wall_clock:
530    /// Option<Duration>`, `cpu: Option<u32>`) fold on the same
531    /// one-line accessor + is_empty-arm-route + validate-arm-route +
532    /// three-test pattern. Named `fuel()` to match the storage field's
533    /// name; the accessor's identity maps onto the canonical
534    /// wasmtime-`Store::set_fuel`-shaped vocabulary the slot's
535    /// docstring already carries.
536    #[must_use]
537    pub const fn fuel(&self) -> Option<u64> {
538        self.fuel
539    }
540
541    /// Substrate-canonical per-`:limits` `:wall-clock` wasmtime-per-call
542    /// wall-clock deadline scalar accessor every consumer of the
543    /// Servico's `wasmtime::Store::epoch_deadline_*` / `wasi:clocks`
544    /// propagation keys off — returns the author-declared `:limits
545    /// :wall-clock` typed `Duration` verbatim as an `Option<Duration>`,
546    /// copied out of the typed slot's own `Option<Duration>` storage
547    /// (`Duration` is `Copy`, so `Option<Duration>` is `Copy` and the
548    /// accessor returns by value; no borrow of `&self` past the call).
549    /// `None` when the slot is absent (the "no wall-clock deadline
550    /// declared — engine-default applies, today the pre-M2
551    /// unbounded-wall-clock shape" arm the module-level docstring names
552    /// on [`LimitsSpec::wall_clock`] itself — [`LimitsSpec::is_empty`]'s
553    /// `wall_clock().is_none()` arm reads this predicate too, so an
554    /// authored-but-unset `:limits (:wall-clock ())` round-trips to a
555    /// `servico_m2_overlay` emission structurally identical to one that
556    /// omits the slot entirely).
557    ///
558    /// The `:limits :wall-clock` slot carries the "per-outermost-call
559    /// wall-clock deadline" wasmtime-shaped sandboxing contract
560    /// (`theory/INSPIRATIONS.md` §III.1 — Lunatic's supervised
561    /// wasm-`Store`-per-process epoch-deadline accounting, translated
562    /// onto pleme-io's typed `:limits` slot) — the typed slot's
563    /// `Option<Duration>` accept-set (zero-floor rejected through
564    /// [`LimitsError::WallClockZero`] because a zero deadline traps the
565    /// first instruction; integer-millisecond granularity enforced
566    /// through [`LimitsError::WallClockNotCanonical`] because the
567    /// duration codec's canonical form emits `"1500ms"` not `"1.5s"`
568    /// and the operator's wall-clock scheduler quantizes at
569    /// milliseconds; upper-bounded by [`LIMITS_WALL_CLOCK_MAX`] (1h —
570    /// the coarsest per-call deadline any operationally-reachable
571    /// Servico can honor without spanning multiple scheduler epochs))
572    /// maps onto the wasmtime `Store::epoch_deadline_*` call the M2.5
573    /// wasm-engine wires per outermost call and, via
574    /// [`crate::render::servico_m2_overlay`], onto the
575    /// `pleme-computeunit` Helm-library-chart values sub-block's
576    /// `limits.wallClock` key that lands as the `ComputeUnit` CR's
577    /// `spec.limits.wallClock` field.
578    ///
579    /// Prior to this lift the `.wall_clock` field was accessed inline at
580    /// two sites inside `impl LimitsSpec` — [`LimitsSpec::is_empty`]'s
581    /// `self.wall_clock.is_none()` arm and [`LimitsSpec::validate`]'s
582    /// `if let Some(w) = self.wall_clock { … }` zero-floor +
583    /// canonical-form + upper-cap bracket arm — two open-coded
584    /// field-accesses that expressed no compile-time link back to the
585    /// typed slot. A future extension of the `:limits :wall-clock` axis
586    /// to a richer author surface — a per-instance `ComputeUnit`
587    /// CR-side `spec.limits.wallClock` overlay the operator pins
588    /// per-cluster, a wall-clock-vs-monotonic-clock discriminator once
589    /// the wasm-engine grows a `:limits (:wall-clock (:kind monotonic
590    /// …))` axis, a split of the single per-outermost-call `Duration`
591    /// budget into a `{deadline, warn_at}` pair once the wasm-engine
592    /// grows a soft-deadline warning surface — would have had to be
593    /// threaded through every open-coded copy in lockstep or the
594    /// emptiness predicate and the validate call would silently
595    /// disagree on which deadline a given [`LimitsSpec`] resolves to.
596    /// Lifting the resolution to a typed method on the substrate
597    /// primitive means every downstream consumer of the Servico's
598    /// per-`:limits` wall-clock-deadline surface reaches for exactly
599    /// one typed dispatch — the resolver's accept-set migrates as a
600    /// unit on any future axis addition.
601    ///
602    /// Third `Option<Copy-T>`-return accessor on the M2 slot family
603    /// (peer of the sibling per-`:limits` [`LimitsSpec::memory`]
604    /// (620c067) `Option<u64>` accessor and per-`:limits`
605    /// [`LimitsSpec::fuel`] (795dee7) `Option<u64>` accessor — same
606    /// typed-optional-scalar shape extended to the peer per-`:limits`
607    /// wall-clock-deadline axis; sibling to [`crate::MeshPolicy::timeout`]
608    /// (7073d0f) on the closed M3 mesh-slot `Option<Duration>` accessor
609    /// axis — same typed-`Duration` shape extended from the M3
610    /// per-call-timeout to the M2 per-outermost-call deadline). The
611    /// triple `(memory(), fuel(), wall_clock())` jointly projects three
612    /// of the four `Option<Copy-T>` axes every M2 `:limits` consumer
613    /// that fans on wasm-linear-memory-cap + wasm-fuel-budget +
614    /// wall-clock-deadline keys off. Three of the four `:limits` axes
615    /// now route through a typed dispatch on the substrate primitive;
616    /// the one remaining (`cpu: Option<u32>`) folds on the same
617    /// one-line accessor + is_empty-arm-route + validate-arm-route +
618    /// three-test pattern in the next run, closing the M2 `:limits`
619    /// slot family's `Option<Copy-T>` accessor axis. Named `wall_clock()`
620    /// to match the storage field's name; the accessor's identity maps
621    /// onto the canonical wasmtime-`Store::epoch_deadline_*`-shaped
622    /// vocabulary the slot's docstring already carries.
623    #[must_use]
624    pub const fn wall_clock(&self) -> Option<Duration> {
625        self.wall_clock
626    }
627
628    /// Substrate-canonical per-`:limits` `:cpu` Kubernetes-millicore
629    /// soft cgroup-share scalar accessor every consumer of the Servico's
630    /// pod-spec `resources.requests.cpu` propagation keys off — returns
631    /// the author-declared `:limits :cpu` typed millicore magnitude
632    /// verbatim as an `Option<u32>`, copied out of the typed slot's own
633    /// `Option<u32>` storage (`Option<u32>` is `Copy`, so the accessor
634    /// returns by value; no borrow of `&self` past the call). `None`
635    /// when the slot is absent (the "no cpu share declared —
636    /// scheduler-default applies, today the pre-M2 unbounded-cpu-share
637    /// shape" arm the module-level docstring names on
638    /// [`LimitsSpec::cpu`] itself — [`LimitsSpec::is_empty`]'s
639    /// `cpu().is_none()` arm reads this predicate too, so an
640    /// authored-but-unset `:limits (:cpu ())` round-trips to a
641    /// `servico_m2_overlay` emission structurally identical to one that
642    /// omits the slot entirely).
643    ///
644    /// The `:limits :cpu` slot carries the "per-process soft cgroup-v2
645    /// CPU share" Kubernetes-scheduler-shaped sandboxing hint
646    /// (`theory/INSPIRATIONS.md` §III.1 — Lunatic's supervised
647    /// wasm-`Store`-per-process host-runtime CPU accounting, translated
648    /// onto pleme-io's typed `:limits` slot as a scheduler-facing
649    /// millicore request the pod's kubelet propagates to the container's
650    /// cgroup) — the typed slot's `Option<u32>` accept-set (zero-floor
651    /// rejected through [`LimitsError::CpuZero`] because a zero cgroup
652    /// share starves the process; upper-bounded by
653    /// [`LIMITS_CPU_MILLICORES_MAX`] (128 cores — the largest commercially-
654    /// common non-metal cloud Kubernetes node vCPU count on managed GKE
655    /// / EKS / AKS general-purpose SKUs)) maps onto the K8s pod spec's
656    /// `spec.containers[].resources.requests.cpu` field the
657    /// M2.5 `wasm-engine` host-runtime lands on the `ComputeUnit` CR-side
658    /// pod template and, via [`crate::render::servico_m2_overlay`], onto
659    /// the `pleme-computeunit` Helm-library-chart values sub-block's
660    /// `limits.cpu` key that lands as the `ComputeUnit` CR's
661    /// `spec.limits.cpu` field.
662    ///
663    /// Prior to this lift the `.cpu` field was accessed inline at two
664    /// sites inside `impl LimitsSpec` — [`LimitsSpec::is_empty`]'s
665    /// `self.cpu.is_none()` arm and [`LimitsSpec::validate`]'s
666    /// `if let Some(m) = self.cpu { … }` zero-floor + upper-cap bracket
667    /// arm — two open-coded field-accesses that expressed no
668    /// compile-time link back to the typed slot. A future extension of
669    /// the `:limits :cpu` axis to a richer author surface — a
670    /// per-instance `ComputeUnit` CR-side `spec.limits.cpu` overlay the
671    /// operator pins per-cluster, a split of the single `u32` millicore
672    /// request into a `{request, limit}` pair once the pod spec's
673    /// `resources.requests.cpu` / `resources.limits.cpu` distinction
674    /// promotes past its current single-request author surface, a
675    /// millicore → cgroup-v2 `cpu.weight` rescale once the operator's
676    /// scheduler-facing translation lands past its current kubelet
677    /// passthrough — would have had to be threaded through every
678    /// open-coded copy in lockstep or the emptiness predicate and the
679    /// validate call would silently disagree on which cgroup share a
680    /// given [`LimitsSpec`] resolves to. Lifting the resolution to a
681    /// typed method on the substrate primitive means every downstream
682    /// consumer of the Servico's per-`:limits` cpu-share surface reaches
683    /// for exactly one typed dispatch — the resolver's accept-set
684    /// migrates as a unit on any future axis addition.
685    ///
686    /// Fourth and final `Option<Copy-T>`-return accessor on the M2 slot
687    /// family (peer of the sibling per-`:limits` [`LimitsSpec::memory`]
688    /// (620c067) `Option<u64>` accessor, per-`:limits`
689    /// [`LimitsSpec::fuel`] (795dee7) `Option<u64>` accessor, and
690    /// per-`:limits` [`LimitsSpec::wall_clock`] (8cb717b)
691    /// `Option<Duration>` accessor — same typed-optional-scalar shape
692    /// extended to the peer per-`:limits` cgroup-cpu-share axis; sibling
693    /// to [`crate::MeshPolicy::mtls_required`] (c0110f1) /
694    /// [`crate::MeshPolicy::retries`] (bdfb399) /
695    /// [`crate::MeshPolicy::timeout`] (7073d0f) on the closed M3
696    /// mesh-slot `Option<Copy-T>` accessor family). The four-tuple
697    /// `(memory(), fuel(), wall_clock(), cpu())` jointly projects every
698    /// `Option<Copy-T>` axis on the M2 `:limits` slot every consumer
699    /// that fans on wasm-linear-memory-cap + wasm-fuel-budget +
700    /// wall-clock-deadline + cgroup-cpu-share keys off — closes the M2
701    /// `:limits` slot family's `Option<Copy-T>` accessor axis (the
702    /// last unlifted `:limits` field-access site on the M2 slot family;
703    /// every axis now routes through a typed dispatch on the substrate
704    /// primitive, with no open-coded field access anywhere on the impl).
705    /// Named `cpu()` to match the storage field's name; the accessor's
706    /// identity maps onto the canonical Kubernetes-`resources.requests.cpu`-
707    /// shaped vocabulary the slot's docstring already carries.
708    #[must_use]
709    pub const fn cpu(&self) -> Option<u32> {
710        self.cpu
711    }
712
713    /// Reject operationally-meaningless zero values on every declared
714    /// axis. Each axis remains optional — omitting a field expresses
715    /// "no bound on this axis"; the bug being closed is *carrying* a
716    /// zero value, which the wasm-engine consumes as "trap the first
717    /// instruction" / "instantiation refused" / "immediate timeout"
718    /// rather than the author's intended "an unspecified bound".
719    ///
720    /// Mirrors the discipline applied to `:politicas` axes in
721    /// `AplicacaoSpec::validate` and to `SupervisorSpec::max_restarts`
722    /// — every typed value carried by a slot is either absent or
723    /// meaningfully non-zero.
724    pub fn validate(&self) -> Result<(), LimitsError> {
725        // Route the `:memory` axis's four value-shape gates
726        // (zero-floor → wasm32-page-floor → wasm32-address-cap →
727        // page-multiple) through the substrate helper
728        // [`crate::render::require_positive_quantum_multiple_bounded_u64`]
729        // rather than four sequential inline
730        // `if let Some(m) = self.memory()` guards each restating one
731        // arm. Brings the `:memory` axis onto the same "one substrate
732        // helper per typed axis" discipline the peer `:fuel` (routed
733        // through [`crate::render::require_positive_bounded_u64`]),
734        // `:wall-clock` (through
735        // [`crate::render::require_positive_canonical_bounded_duration`]),
736        // and `:cpu` (through
737        // [`crate::render::require_positive_bounded_u32`]) axes
738        // already carry — every `LimitsSpec::validate` axis is now
739        // exactly one typed-helper dispatch, with the four-arm
740        // ordering (zero → below-quantum → cap → not-multiple)
741        // promoted from a per-site convention four inline blocks
742        // re-derived by hand to a structural contract on the
743        // substrate primitive. Byte-equal today: the helper fires the
744        // same four arms in the same canonical order at the same
745        // boundary values, threading the offending byte count into
746        // the same `MemoryBelowWasm32Page` / `MemoryExceedsWasm32Cap`
747        // / `MemoryNotPageMultiple` discriminator fields the four
748        // pre-lift inline arms already carried, so every existing
749        // per-arm test in this module continues to pin the same
750        // shape unchanged. Pinned end-to-end by
751        // `validate_memory_axis_routes_through_quantum_multiple_bounded_helper`.
752        if let Some(m) = self.memory() {
753            crate::render::require_positive_quantum_multiple_bounded_u64(
754                m,
755                LIMITS_MEMORY_WASM32_PAGE_BYTES,
756                LIMITS_MEMORY_WASM32_MAX_BYTES,
757                || LimitsError::MemoryZero,
758                LimitsError::memory_below_wasm32_page,
759                LimitsError::memory_exceeds_wasm32_cap,
760                LimitsError::memory_not_page_multiple,
761            )?;
762        }
763        // Zero-floor + upper-cap bracket on the typed `:fuel` axis. See
764        // [`crate::render::require_positive_bounded_u64`] for the
765        // ordering discipline (zero-floor arm strictly precedes cap arm
766        // so `Some(0)` surfaces the self-locating `FuelZero` diagnostic
767        // with its omit-axis remediation directly named, not the
768        // misleading `0 > LIMITS_FUEL_MAX == false` cap-arm miss).
769        // Until this bracket landed the `Option<u64>` slot accepted any
770        // value past zero (the parser's only upper bound was `u64::MAX`),
771        // so `(:fuel 18446744073709551615)` round-tripped cleanly
772        // through serde and the per-process CSE invariant (no value the
773        // wasm-engine's fuel counter can't honor as a meaningful budget
774        // before the sibling `:wall-clock` deadline fires) was a
775        // runtime, not build-time, contract on every above-cap input
776        // — the canonical declared-but-no-op footgun the sibling
777        // [`LimitsError::MemoryExceedsWasm32Cap`] /
778        // [`LimitsError::WallClockExceedsCap`] /
779        // [`LimitsError::CpuExceedsCap`] arms close on the peer
780        // "cannot be honored" / "unschedulable hint" /
781        // "nominal-only deadline" shapes, the peer
782        // [`crate::AplicacaoError::PolicyTimeoutExceedsCap`] /
783        // [`crate::AplicacaoError::PolicyBreakerWindowExceedsCap`] /
784        // [`crate::AplicacaoError::PolicyRateLimitExceedsCap`] arms
785        // close on the no-op-deadline / lifetime-counter / no-op-limiter
786        // shapes, and the
787        // [`crate::SupervisorError::MaxRestartsExceedsCap`] arm closes
788        // on the no-op-supervisor shape. The four `:limits` axes are
789        // now uniformly bracketed top and bottom (`:memory` in
790        // `LIMITS_MEMORY_WASM32_PAGE_BYTES..=LIMITS_MEMORY_WASM32_MAX_BYTES`,
791        // `:fuel` in `1..=LIMITS_FUEL_MAX`, `:wall-clock` in
792        // `1ms..=LIMITS_WALL_CLOCK_MAX`, `:cpu` in
793        // `1..=LIMITS_CPU_MILLICORES_MAX`).
794        if let Some(f) = self.fuel() {
795            crate::render::require_positive_bounded_u64(
796                f,
797                LIMITS_FUEL_MAX,
798                || LimitsError::FuelZero,
799                LimitsError::fuel_exceeds_cap,
800            )?;
801        }
802        if let Some(w) = self.wall_clock() {
803            // Zero-floor + integer-millisecond canonical-form +
804            // upper-cap bracket on the typed `:wall-clock` axis. See
805            // [`crate::render::require_positive_canonical_bounded_duration`]
806            // for the full three-arm ordering discipline (zero-floor
807            // strictly precedes canonical-form so `Duration::ZERO`
808            // surfaces the self-locating `WallClockZero` diagnostic;
809            // canonical-form strictly precedes the cap arm so a
810            // sub-millisecond above-cap value surfaces the more
811            // fundamental round-trip-shape diagnostic first) and the
812            // three peer typed-`Duration` sites that share this
813            // canonical bracket ([`crate::MeshPolicy::timeout`],
814            // [`crate::CircuitBreaker::window`],
815            // [`crate::SupervisorSpec::restart_window`]). Every
816            // validated value lies in `1ms..=LIMITS_WALL_CLOCK_MAX`
817            // (1ms..=1h), integer-millisecond granularity.
818            crate::render::require_positive_canonical_bounded_duration(
819                w,
820                LIMITS_WALL_CLOCK_MAX,
821                || LimitsError::WallClockZero,
822                LimitsError::wall_clock_not_canonical,
823                LimitsError::wall_clock_exceeds_cap,
824            )?;
825        }
826        // Zero-floor + upper-cap bracket on the typed `:cpu` axis. See
827        // [`crate::render::require_positive_bounded_u32`] for the
828        // ordering discipline (zero-floor arm strictly precedes cap arm
829        // so `Some(0)` surfaces the self-locating `CpuZero` diagnostic
830        // with its omit-axis remediation directly named, not the
831        // misleading `0 > LIMITS_CPU_MILLICORES_MAX == false` cap-arm
832        // miss). The bracket set is `1..=LIMITS_CPU_MILLICORES_MAX`
833        // (128 cores = 128_000 millicores — the largest commercially-
834        // common non-metal cloud Kubernetes node vCPU count). Until
835        // this bracket landed the millicore codec accepted any
836        // `Option<u32>` past zero (the prior numeric-zero arm's only
837        // floor), so `(:cpu "1000000m")` (1000 cores) round-tripped
838        // cleanly through serde and the per-axis CSE invariant (no
839        // value the Kubernetes scheduler can't honor) was a runtime,
840        // not build-time, contract on every above-cap input: the
841        // `pleme-computeunit` chart's `resources.requests.cpu` landed
842        // verbatim, the pod sat `Pending` indefinitely with a `0/N
843        // nodes are available: N Insufficient cpu` event, and the
844        // typed `:cpu` slot became an unschedulable hint far from the
845        // source caixa.lisp. Closes the same gap the wasm32-wasip2
846        // upper ceiling closes on the `:memory` axis — the typed `:cpu`
847        // axis is now operationally bracketed. Peer with every sibling
848        // cap arm on this surface ([`LimitsError::MemoryExceedsWasm32Cap`],
849        // [`LimitsError::WallClockExceedsCap`],
850        // [`crate::AplicacaoError::PolicyTimeoutExceedsCap`],
851        // [`crate::AplicacaoError::PolicyRetriesExceedsCap`],
852        // [`crate::AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`],
853        // [`crate::AplicacaoError::PolicyBreakerWindowExceedsCap`],
854        // [`crate::AplicacaoError::PolicyRateLimitExceedsCap`],
855        // [`crate::SupervisorError::MaxRestartsExceedsCap`]).
856        if let Some(m) = self.cpu() {
857            crate::render::require_positive_bounded_u32(
858                m,
859                LIMITS_CPU_MILLICORES_MAX,
860                || LimitsError::CpuZero,
861                LimitsError::cpu_exceeds_cap,
862            )?;
863        }
864        Ok(())
865    }
866}
867
868#[derive(Debug, Error, PartialEq, Eq)]
869pub enum LimitsError {
870    #[error("byte-size: missing magnitude in {0:?}")]
871    EmptyByteSize(String),
872    #[error("byte-size: unknown unit {unit:?} (expected one of B, KB, MB, GB, KiB, MiB, GiB)")]
873    UnknownByteUnit { unit: String },
874    #[error("byte-size: failed to parse magnitude {0:?}")]
875    BadByteMagnitude(String),
876    #[error(
877        "byte-size: magnitude {value:?} is not a non-negative integer — the canonical \
878         authoring form for `:limits :memory` is `<integer><unit>` (e.g. `\"1024\"`, \
879         `\"64MiB\"`, `\"1GiB\"`) with no decimal point and no leading `+` sign. A \
880         fractional / decimal-shaped magnitude (`\"1.5KiB\"`, `\"1.0MiB\"`, `\"0.5GiB\"`, \
881         `\"+1024\"`) round-trips through `render_byte_size` to a *different* canonical \
882         form (`\"1536\"`, `\"1MiB\"`, `\"512MiB\"`, `\"1KiB\"`) on first serialize — \
883         breaking the THEORY.md §V.2.7 render-determinism contract every typed slot \
884         carries. Pick an integer magnitude in the unit that divides cleanly (write \
885         `\"1536\"` instead of `\"1.5KiB\"`; `\"512MiB\"` instead of `\"0.5GiB\"`)"
886    )]
887    NonIntegerByteMagnitude { value: String },
888    #[error(
889        "byte-size: magnitude {value:?} has a non-canonical leading zero — the canonical \
890         authoring form for `:limits :memory` is `<integer><unit>` (e.g. `\"64MiB\"`, \
891         `\"1GiB\"`, `\"512KiB\"`, `\"1024\"`) with no leading-zero padding on the magnitude. \
892         A leading-zero magnitude (`\"064MiB\"`, `\"01024\"`, `\"00KiB\"`, `\"0500MB\"`) round-trips \
893         through `render_byte_size` to a *different* canonical form (`\"64MiB\"`, `\"1KiB\"`, \
894         `\"0\"`, `\"500MB\"`) on first serialize — breaking the THEORY.md Part V \
895         render-determinism contract every typed slot carries. Strip the leading zeros \
896         (write `\"64MiB\"` instead of `\"064MiB\"`)"
897    )]
898    LeadingZeroByteMagnitude { value: String },
899    #[error(
900        "byte-size: value {value:?} contains whitespace byte 0x{byte:02x} — the canonical \
901         authoring form for `:limits :memory` is `<integer><unit>` (e.g. `\"64MiB\"`, \
902         `\"1GiB\"`, `\"512KiB\"`, `\"1024\"`) with no whitespace bytes anywhere. A \
903         whitespace-carrying shape (`\" 64MiB\"`, `\"64MiB \"`, `\"64 MiB\"`, `\"\\t64MiB\"`, \
904         `\"64MiB\\n\"`) round-trips through `render_byte_size` to a *different* canonical \
905         form (`\"64MiB\"`) on first serialize — breaking the THEORY.md Part V \
906         render-determinism contract every typed slot carries. Strip every whitespace byte \
907         (write `\"64MiB\"` verbatim)"
908    )]
909    WhitespaceInByteSize { value: String, byte: u8 },
910    #[error(
911        "byte-size: value {value:?} contains a non-ASCII Unicode whitespace character \
912         {ch:?} (U+{codepoint:04X}) — the canonical authoring form for `:limits :memory` \
913         is `<integer><unit>` (e.g. `\"64MiB\"`, `\"1GiB\"`, `\"512KiB\"`, `\"1024\"`) \
914         with no whitespace characters anywhere (ASCII or Unicode). A non-ASCII-whitespace-\
915         carrying shape (`\"\\u{{00A0}}64MiB\"` — paste-from-typography NBSP prefix; \
916         `\"64MiB\\u{{2028}}\"` — paste-from-web-doc line-separator suffix; \
917         `\"64\\u{{2003}}MiB\"` — paste-from-typography EM-SPACE between magnitude and \
918         unit) survives the pre-existing `u8::is_ascii_whitespace` byte-scan (none of \
919         its bytes match the ASCII whitespace set) but `str::trim` (which uses \
920         `char::is_whitespace` — the Unicode `White_Space` property, strictly wider than \
921         the ASCII byte set) silently strips it at parse entry, and the value round-trips \
922         through `render_byte_size` to a *different* canonical form (`\"64MiB\"`) on \
923         first serialize — breaking the THEORY.md Part V render-determinism contract \
924         every typed slot carries. Strip every non-ASCII whitespace character (write \
925         `\"64MiB\"` verbatim with only ASCII bytes)"
926    )]
927    NonAsciiWhitespaceInByteSize {
928        value: String,
929        ch: char,
930        codepoint: u32,
931    },
932    #[error("duration: missing magnitude in {0:?}")]
933    EmptyDuration(String),
934    #[error("duration: unknown unit {unit:?} (expected one of ms, s, m, h)")]
935    UnknownDurationUnit { unit: String },
936    #[error("duration: failed to parse magnitude {0:?}")]
937    BadDurationMagnitude(String),
938    #[error(
939        "duration: magnitude {value:?} is not a non-negative integer — the canonical \
940         authoring form for `:limits :wall-clock` is `<integer><unit>` (e.g. `\"30s\"`, \
941         `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and no leading `+` sign. A \
942         fractional / decimal-shaped magnitude (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, \
943         `\"+30s\"`, `\"-30s\"`) round-trips through `render_duration` to a *different* \
944         canonical form (`\"1500ms\"`, `\"1s\"`, `\"30s\"`, `\"30s\"`) on first serialize \
945         — breaking the THEORY.md Part V render-determinism contract every typed slot \
946         carries. Pick an integer magnitude in the unit that divides cleanly (write \
947         `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
948    )]
949    NonIntegerDurationMagnitude { value: String },
950    #[error(
951        "duration: magnitude {value:?} has a non-canonical leading zero — the canonical \
952         authoring form for `:limits :wall-clock` is `<integer><unit>` (e.g. `\"30s\"`, \
953         `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding on the magnitude. \
954         A leading-zero magnitude (`\"030s\"`, `\"00s\"`, `\"01h\"`, `\"0500ms\"`) round-trips \
955         through `render_duration` to a *different* canonical form (`\"30s\"`, `\"0s\"`, \
956         `\"1h\"`, `\"500ms\"`) on first serialize — breaking the THEORY.md Part V \
957         render-determinism contract every typed slot carries. Strip the leading zeros \
958         (write `\"30s\"` instead of `\"030s\"`)"
959    )]
960    LeadingZeroDurationMagnitude { value: String },
961    #[error(
962        "duration: value {value:?} contains whitespace byte 0x{byte:02x} — the canonical \
963         authoring form for `:limits :wall-clock` is `<integer><unit>` (e.g. `\"30s\"`, \
964         `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes anywhere. A \
965         whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, `\"\\t30s\"`, \
966         `\"30s\\n\"`) round-trips through `render_duration` to a *different* canonical form \
967         (`\"30s\"`) on first serialize — breaking the THEORY.md Part V render-determinism \
968         contract every typed slot carries. Strip every whitespace byte (write `\"30s\"` \
969         verbatim)"
970    )]
971    WhitespaceInDuration { value: String, byte: u8 },
972    #[error(
973        "duration: value {value:?} contains a non-ASCII Unicode whitespace character \
974         {ch:?} (U+{codepoint:04X}) — the canonical authoring form for `:limits :wall-clock` \
975         is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no \
976         whitespace characters anywhere (ASCII or Unicode). A non-ASCII-whitespace-\
977         carrying shape (`\"\\u{{00A0}}30s\"` — paste-from-typography NBSP prefix; \
978         `\"30s\\u{{2028}}\"` — paste-from-web-doc line-separator suffix; \
979         `\"30\\u{{2003}}s\"` — paste-from-typography EM-SPACE between magnitude and \
980         unit) survives the pre-existing `u8::is_ascii_whitespace` byte-scan (none of \
981         its bytes match the ASCII whitespace set) but `str::trim` (which uses \
982         `char::is_whitespace` — the Unicode `White_Space` property, strictly wider than \
983         the ASCII byte set) silently strips it at parse entry, and the value round-trips \
984         through `render_duration` to a *different* canonical form (`\"30s\"`) on first \
985         serialize — breaking the THEORY.md Part V render-determinism contract every \
986         typed slot carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
987         verbatim with only ASCII bytes)"
988    )]
989    NonAsciiWhitespaceInDuration {
990        value: String,
991        ch: char,
992        codepoint: u32,
993    },
994    #[error("millicores: bad value {0:?} (expected `<int>m` or `<int>`)")]
995    BadMillicores(String),
996    #[error(
997        "millicores: magnitude {value:?} is not a non-negative integer — the canonical \
998         authoring form for `:limits :cpu` is `<integer>m` (Kubernetes millicores, e.g. \
999         `\"500m\"` for half a core, `\"2000m\"` for two cores) or the bare-core \
1000         shorthand `<integer>` (e.g. `\"2\"` = `\"2000m\"`), with no decimal point and \
1001         no leading `+` sign. A fractional / decimal-shaped magnitude (`\"1.5\"`, \
1002         `\"500.0m\"`, `\"+500m\"`, `\"-100m\"`) round-trips through `render_millicores` \
1003         to a *different* canonical form (`\"1500m\"`, `\"500m\"`, `\"500m\"`, \
1004         parse-rejection) on first serialize — breaking the THEORY.md Part V \
1005         render-determinism contract every typed slot carries. Pick an integer magnitude \
1006         in millicores (write `\"1500m\"` instead of `\"1.5\"`; `\"500m\"` instead of \
1007         `\"500.0m\"`)"
1008    )]
1009    NonIntegerMillicoreMagnitude { value: String },
1010    #[error(
1011        "millicores: magnitude {value:?} has a non-canonical leading zero — the canonical \
1012         authoring form for `:limits :cpu` is `<integer>m` (Kubernetes millicores, e.g. \
1013         `\"500m\"` for half a core, `\"2000m\"` for two cores) or the bare-core shorthand \
1014         `<integer>` (e.g. `\"2\"` = `\"2000m\"`) with no leading-zero padding on the \
1015         magnitude. A leading-zero magnitude (`\"0500m\"`, `\"00m\"`, `\"02\"`, `\"01500m\"`) \
1016         round-trips through `render_millicores` to a *different* canonical form (`\"500m\"`, \
1017         `\"0m\"`, `\"2000m\"`, `\"1500m\"`) on first serialize — breaking the THEORY.md Part \
1018         V render-determinism contract every typed slot carries. Strip the leading zeros \
1019         (write `\"500m\"` instead of `\"0500m\"`; `\"2\"` instead of `\"02\"`)"
1020    )]
1021    LeadingZeroMillicoreMagnitude { value: String },
1022    #[error(
1023        "millicores: value {value:?} contains whitespace byte 0x{byte:02x} — the canonical \
1024         authoring form for `:limits :cpu` is `<integer>m` (Kubernetes millicores, e.g. \
1025         `\"500m\"`, `\"2000m\"`) or the bare-core shorthand `<integer>` (e.g. `\"2\"`) \
1026         with no whitespace bytes anywhere. A whitespace-carrying shape (`\" 500m\"`, \
1027         `\"500m \"`, `\"500 m\"`, `\"\\t500m\"`, `\"500m\\n\"`) round-trips through \
1028         `render_millicores` to a *different* canonical form (`\"500m\"`) on first \
1029         serialize — breaking the THEORY.md Part V render-determinism contract every \
1030         typed slot carries. Strip every whitespace byte (write `\"500m\"` verbatim)"
1031    )]
1032    WhitespaceInMillicores { value: String, byte: u8 },
1033    #[error(
1034        "millicores: value {value:?} contains a non-ASCII Unicode whitespace character \
1035         {ch:?} (U+{codepoint:04X}) — the canonical authoring form for `:limits :cpu` is \
1036         `<integer>m` (Kubernetes millicores, e.g. `\"500m\"`, `\"2000m\"`) or the \
1037         bare-core shorthand `<integer>` (e.g. `\"2\"`) with no whitespace characters \
1038         anywhere (ASCII or Unicode). A non-ASCII-whitespace-carrying shape \
1039         (`\"\\u{{00A0}}500m\"` — paste-from-typography NBSP prefix; \
1040         `\"500m\\u{{2028}}\"` — paste-from-web-doc line-separator suffix; \
1041         `\"500\\u{{2003}}m\"` — paste-from-typography EM-SPACE between magnitude and \
1042         unit) survives the pre-existing `u8::is_ascii_whitespace` byte-scan (none of \
1043         its bytes match the ASCII whitespace set) but `str::trim` (which uses \
1044         `char::is_whitespace` — the Unicode `White_Space` property, strictly wider than \
1045         the ASCII byte set) silently strips it at parse entry, and the value round-trips \
1046         through `render_millicores` to a *different* canonical form (`\"500m\"`) on \
1047         first serialize — breaking the THEORY.md Part V render-determinism contract \
1048         every typed slot carries. Strip every non-ASCII whitespace character (write \
1049         `\"500m\"` verbatim with only ASCII bytes)"
1050    )]
1051    NonAsciiWhitespaceInMillicores {
1052        value: String,
1053        ch: char,
1054        codepoint: u32,
1055    },
1056    #[error(
1057        ":limits :memory must be > 0 — wasmtime StoreLimits refuses a zero memory cap; omit the field for unbounded"
1058    )]
1059    MemoryZero,
1060    #[error(
1061        ":limits :memory ({bytes} bytes) is below the wasm32-wasip2 linear-memory page size (64 KiB = 65536 bytes) — a sub-page cap cannot hold a single wasm linear memory page, so instantiation of any component declaring `(memory 1)` traps with `memory minimum size of 1 pages exceeds memory limits` and a `(memory 0)` component traps the first `memory.grow(1)`. Pin a value ≥ 64 KiB (e.g. `\"64KiB\"`, `\"1MiB\"`, `\"64MiB\"`) or omit the field for unbounded"
1062    )]
1063    MemoryBelowWasm32Page { bytes: u64 },
1064    #[error(
1065        ":limits :memory ({bytes} bytes) exceeds the wasm32-wasip2 linear-memory ceiling (4 GiB = 4294967296 bytes); pin a value ≤ 4 GiB or omit the field for unbounded"
1066    )]
1067    MemoryExceedsWasm32Cap { bytes: u64 },
1068    #[error(
1069        ":limits :memory ({bytes} bytes) carries a sub-page residue the wasm32-wasip2 \
1070         linear-memory model cannot honor — the wasm spec defines linear memory in \
1071         fixed 64 KiB pages (LIMITS_MEMORY_WASM32_PAGE_BYTES = 65536 bytes) and \
1072         wasmtime's StoreLimits::memory_size is consumed as a page-quantized ceiling: \
1073         the engine can grow at most floor({bytes} / 65536) pages, and the bytes in \
1074         [floor({bytes} / 65536) * 65536, {bytes}] are structural dead space the \
1075         runtime cannot honor. Pin a page-aligned value in 64KiB..=4GiB \
1076         (the canonical authoring magnitudes — `\"64KiB\"`, `\"128KiB\"`, `\"1MiB\"`, \
1077         `\"64MiB\"`, `\"1GiB\"`, `\"4GiB\"` — every power-of-1024 unit the byte-size \
1078         codec emits divides cleanly by the page size) or omit the field for unbounded"
1079    )]
1080    MemoryNotPageMultiple { bytes: u64 },
1081    #[error(
1082        ":limits :fuel must be > 0 — wasmtime traps the first instruction at fuel=0; omit the field for unbounded"
1083    )]
1084    FuelZero,
1085    #[error(
1086        ":limits :fuel ({fuel} instructions) exceeds the per-process ceiling \
1087         (LIMITS_FUEL_MAX = 1_000_000_000_000 = 10^12 wasm instructions) — a value \
1088         above this cap turns the typed per-call fuel counter into a no-op budget: \
1089         the sibling `:wall-clock` cap (LIMITS_WALL_CLOCK_MAX = 1h = 3600s) fires \
1090         before the fuel counter could ever be drained (wasmtime's documented \
1091         fuel-tracked execution rate sits at ~10^8–10^9 fuel-units per second on \
1092         modern x86_64 / aarch64 hosts running wasmtime through Cranelift, so the \
1093         largest realistic per-call fuel budget reachable within 1h sits at ~3.6 × \
1094         10^11–3.6 × 10^12 fuel-units, and a value above 10^12 is structurally \
1095         unreachable as a per-call counter), so the typed `:fuel` slot becomes a \
1096         declared-but-no-op contract far from the source caixa.lisp. Pin a value \
1097         in 1..=1_000_000_000_000 (the canonical caixa Servico runs in the \
1098         10^6..=10^9 fuel band — the in-tree `Caixa::template` documentation and \
1099         `caixa-feira` examples carry `:fuel 1_000_000` = 10^6, peer to \
1100         wasmtime's official `Store::set_fuel(1_000_000)` example in the wasmtime \
1101         book; production-shape per-request fuel budgets sit in the 10^7..=10^9 \
1102         band for compute-bound workloads) or omit :fuel to express `no per-call \
1103         fuel budget on this axis` (the wasm-engine then relies entirely on the \
1104         sibling `:wall-clock` cgroup / Kubernetes activeDeadlineSeconds deadline)"
1105    )]
1106    FuelExceedsCap { fuel: u64 },
1107    #[error(
1108        ":limits :wall-clock must be > 0 — a zero deadline expires before the call starts; omit the field for unbounded"
1109    )]
1110    WallClockZero,
1111    #[error(
1112        ":limits :wall-clock ({wall_clock:?}) carries a sub-millisecond residue the typed `:wall-clock` duration codec cannot round-trip — \
1113         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
1114         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
1115         as \"0s\" the `WallClockZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
1116         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for unbounded"
1117    )]
1118    WallClockNotCanonical { wall_clock: Duration },
1119    #[error(
1120        ":limits :wall-clock ({wall_clock:?}) exceeds the per-process ceiling \
1121         (LIMITS_WALL_CLOCK_MAX = 1h = 3600s) — a value above this cap turns the typed \
1122         per-call deadline into a nominal-only contract (the wasm-engine's epoch-deadline \
1123         cancellation reaches for a `Duration` so long no realistic synchronous wasm call \
1124         can hit it), and the MESH-COMPOSITION §V \"no infinite blocking\" CSE invariant \
1125         degenerates to enforcement only at the per-Servico cgroup / Kubernetes \
1126         activeDeadlineSeconds layer — far above the per-call granularity the typed \
1127         `:limits :wall-clock` slot is meant to express. Pin a value in 1ms..=1h \
1128         (Envoy / Istio / Linkerd production per-request playbooks all recommend ≤ 60s; \
1129         AWS App Mesh / ingress-nginx typical ≤ 300s; the longest per-request \
1130         `proxy_read_timeout` ingress-nginx documents maxes out at the same 3600s ceiling) \
1131         or omit :wall-clock to express `no per-process deadline on this axis` (the \
1132         deadline then relies entirely on the cluster-level cgroup / pod \
1133         activeDeadlineSeconds bound)"
1134    )]
1135    WallClockExceedsCap { wall_clock: Duration },
1136    #[error(
1137        ":limits :cpu must be > 0m — a zero cgroup share starves the process; omit the field for unbounded"
1138    )]
1139    CpuZero,
1140    #[error(
1141        ":limits :cpu ({millicores}m) exceeds the per-process ceiling \
1142         (LIMITS_CPU_MILLICORES_MAX = 128_000m = 128 cores) — a value above this cap is \
1143         structurally unschedulable on every commercially-common managed-Kubernetes node \
1144         pool (GKE Standard / EKS managed / AKS default general-purpose SKU ladders top out \
1145         at 128 vCPU per node; AWS m7i.32xlarge / c7i.32xlarge, Azure HBv3-128rs, GCP \
1146         c3-standard-128 all sit at the same 128-vCPU ceiling), so the resulting \
1147         `pleme-computeunit` chart's `resources.requests.cpu` lands as a hint the \
1148         Kubernetes scheduler cannot bind to any node — the pod sits `Pending` indefinitely \
1149         with a `0/N nodes are available: N Insufficient cpu` event, and the typed `:cpu` \
1150         slot becomes an unschedulable contract far from the source caixa.lisp. The \
1151         wasm32-wasip2 single-threaded execution model the canonical caixa Servico targets \
1152         reinforces the structural argument: a single wasm component cannot saturate more \
1153         than one core, so even the Lunatic-style supervised-multi-process host bounds its \
1154         useful CPU request to the host node's vCPU count. Pin a value in 1m..=128000m \
1155         (the canonical caixa Servico runs in the 100m..=2000m band — every in-tree \
1156         example uses 500m; AWS App Mesh / Envoy / Istio per-pod CPU production playbooks \
1157         all sit ≤ 8000m / 8 cores; the longest documented per-Servico CPU request any \
1158         pleme-io substrate playbook recommends maxes at ~16 cores) or omit :cpu to \
1159         express `no per-process CPU hint on this axis` (the cgroup share then defaults to \
1160         the cluster-level `LimitRange` / `ResourceQuota` policy the operator pins on the \
1161         host namespace)"
1162    )]
1163    CpuExceedsCap { millicores: u32 },
1164}
1165
1166// ── byte-size codec ────────────────────────────────────────────────────
1167
1168fn parse_byte_size(s: &str) -> Result<u64, LimitsError> {
1169    // Paired whitespace-rejection arm — the ASCII byte-scan
1170    // (paste-from-aligned-doc leading space, shell-history trailing
1171    // space, typography space between magnitude and unit, block-scalar
1172    // tab, multi-line trailing newline) closes the WhatWG-conformant
1173    // ASCII whitespace bytes (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`);
1174    // the non-ASCII `char::is_whitespace` scan closes the strictly-
1175    // complementary Unicode `White_Space` class (NBSP `\u{00A0}`, LINE
1176    // SEPARATOR `\u{2028}`, EM-SPACE `\u{2003}`, and the peer
1177    // typography codepoints) that `str::trim` at parse entry silently
1178    // strips. Either drift class would round-trip through
1179    // `render_byte_size` to a *different* canonical form on next emit
1180    // — breaking the THEORY.md Part V render-determinism contract every
1181    // typed slot carries. Diagnostics stay typed at
1182    // `WhitespaceInByteSize` / `NonAsciiWhitespaceInByteSize` so the
1183    // failing byte / char + U+XXXX codepoint reaches the author verbatim
1184    // rather than being value-laundered through a downstream
1185    // `BadByteMagnitude` arm.
1186    //
1187    // Routed through the lifted [`crate::render::reject_whitespace`]
1188    // primitive — the substrate-side single-owner gate every typed-
1189    // magnitude codec in caixa-core (`parse_byte_size` /
1190    // `parse_duration` / `parse_millicores` /
1191    // `supervisor::duration_codec` / `rate_limit_codec`) shares. Drift
1192    // between any two codec sites' paired-arm rejection set becomes a
1193    // single-edit fix at the composed predicate rather than five
1194    // independent paired-arm re-inlines diverging over time.
1195    crate::render::reject_whitespace(
1196        s,
1197        |byte| LimitsError::whitespace_in_byte_size(s, byte),
1198        |ch| LimitsError::non_ascii_whitespace_in_byte_size(s, ch),
1199    )?;
1200    let s = s.trim();
1201    if s.is_empty() {
1202        return Err(LimitsError::EmptyByteSize(s.into()));
1203    }
1204    // Route the `<integer><ASCII-alphabetic-unit>` split through the
1205    // lifted [`crate::render::split_magnitude_and_alpha_unit`] primitive
1206    // — the substrate-side single-owner split every ASCII-alphabetic-unit
1207    // typed-magnitude codec in caixa-core (`parse_byte_size` /
1208    // `parse_duration` / `supervisor::duration_codec::parse`) shares.
1209    // Drift between any two codec sites' magnitude/unit split rule
1210    // becomes a single-edit fix at the composed helper rather than three
1211    // independent `s.find(|c: char| c.is_ascii_alphabetic())` re-inlines
1212    // diverging over time.
1213    let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
1214    let num_trim = num_part.trim();
1215    // The canonical authoring form for `:limits :memory` is
1216    // `<integer><unit>` — every magnitude `render_byte_size` emits is a
1217    // non-negative integer with no decimal point and no leading sign,
1218    // so the parser's accepted set must match for serialize/deserialize
1219    // to round-trip without canonical-form drift. Until this gate
1220    // landed the parser accepted any `f64`-shaped magnitude
1221    // (`"1.5KiB"` → 1536 bytes, `"1.0MiB"` → 1MiB, `"0.5GiB"` → 512MiB,
1222    // `"+1024"` → 1024) and serde silently round-tripped the value to
1223    // a *different* canonical string on the next emit (`"1.5KiB"` →
1224    // 1536 → `"1536"`, `"1.0MiB"` → 1048576 → `"1MiB"`, `"0.5GiB"` →
1225    // 536870912 → `"512MiB"`, `"+1024"` → 1024 → `"1KiB"`) — breaking
1226    // the THEORY.md §V.2.7 render-determinism contract every typed slot
1227    // carries.
1228    //
1229    // Strict canonical form: every byte of the magnitude is an ASCII
1230    // digit (no `.`, no `+`, no `-`). On current Rust `u64::from_str`
1231    // permissively accepts a leading `+` (`"+1024"` → 1024) — that's a
1232    // canonical-drift shape `render_byte_size` never emits, so the
1233    // digit-only check is what closes the leading-sign class; relying
1234    // on `u64::from_str`'s strictness alone would silently admit it.
1235    // On non-digit-only inputs the gate distinguishes "non-canonical-
1236    // but-numeric" (parses as f64 or i64, so it's an authoring-shape
1237    // footgun) from "garbage" (parses as neither, so it's not a
1238    // numeric input at all) — the diagnostic names the offending
1239    // magnitude shape verbatim rather than collapsing both authoring
1240    // footguns into a single opaque `BadByteMagnitude`.
1241    //
1242    // Same canonical-form discipline
1243    // [`crate::AplicacaoSpec::validate_politicas`]'s
1244    // [`is_canonical_rate_limit_window`] gate (808017c) applies to the
1245    // rate-limit `:window` axis — the codec's accepted set matches its
1246    // emitted set, structurally.
1247    //
1248    // (Scientific-notation magnitudes like `"1e3KiB"` are also rejected,
1249    // but on a different arm: the parser splits on the first ASCII-
1250    // alphabetic byte, so the `e` is read as a unit prefix and the
1251    // input falls into the `UnknownByteUnit { unit: "e3KiB" }` branch
1252    // before this gate is consulted — that's the existing diagnostic
1253    // for the scientific-shape footgun, and this gate is additive to
1254    // it.)
1255    //
1256    // Routed through the lifted
1257    // [`crate::render::is_digit_only_magnitude`] predicate — the
1258    // single source of truth every typed-magnitude codec in
1259    // caixa-core (`parse_byte_size` / `parse_duration` /
1260    // `parse_millicores` / `supervisor::duration_codec` /
1261    // `rate_limit_codec`) shares. Drift between any two codec sites'
1262    // digit-only rejection set becomes a single-edit fix at the
1263    // shared predicate rather than five independent
1264    // `!<var>.is_empty() && <var>.bytes().all(|b| b.is_ascii_digit())`
1265    // scans diverging over time — same "single lifted source of truth"
1266    // discipline the peer canonical-form predicates
1267    // ([`crate::render::find_ascii_whitespace_byte`] /
1268    // [`crate::render::find_non_ascii_whitespace_char`] /
1269    // [`crate::render::is_leading_zero_padded_magnitude`]) carry on
1270    // the whitespace and leading-zero-padding drift-class axes.
1271    let digit_only = crate::render::is_digit_only_magnitude(num_trim);
1272    if !digit_only {
1273        // Distinguish "non-canonical-but-numeric" (`"1.5"`, `"1.0"`,
1274        // `"+1024"`, `"-1"`) from "garbage" (`"abc"`, `"--1"`) so the
1275        // diagnostic names the offending magnitude shape verbatim.
1276        // Use f64 + i64 fallbacks for the "numeric" detection so every
1277        // non-digit-only-but-parseable input lands on
1278        // `NonIntegerByteMagnitude` regardless of sign or fractionality.
1279        let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
1280        if numeric {
1281            return Err(LimitsError::non_integer_byte_magnitude(num_trim));
1282        }
1283        return Err(LimitsError::bad_byte_magnitude(num_part));
1284    }
1285    // Leading-zero arm — peer with the `parse_duration` leading-zero
1286    // arm (39762d7), the `supervisor::duration_codec` leading-zero arm
1287    // (9178904) and the `rate_limit_codec` leading-zero arm (4f46830)
1288    // on the same canonical-form render-determinism axis. The
1289    // digit-only gate accepts `"0064MiB"`, `"01024"`, `"00KiB"`,
1290    // `"0500MB"` as `u64::from_str` parses them losslessly (= 64, 1024,
1291    // 0, 500), but `render_byte_size` emits the leading-zero-stripped
1292    // form (`"64MiB"`, `"1KiB"`, `"0"`, `"500MB"`) — a *different*
1293    // canonical string on the next emit, breaking the THEORY.md Part V
1294    // render-determinism contract the same way `"+1024"` did before the
1295    // leading-`+` arm landed. The single-byte magnitude `"0"` (or
1296    // `"0B"` / `"0KiB"`) round-trips losslessly through
1297    // `render_byte_size` (`render_byte_size(0)` emits `"0"`) — the
1298    // downstream semantic-zero gate [`LimitsError::MemoryZero`] refuses
1299    // zero-magnitude authoring at the typed-validate layer above, so
1300    // the single-byte `"0"` stays in the accepted set at this codec
1301    // layer and the diagnostic partitioning between canonical-form
1302    // drift (this arm) and semantic-zero (the downstream gate) remains
1303    // stable. Same codec-layer / typed-validate-layer partition the
1304    // peer codecs preserve.
1305    //
1306    // Routed through the lifted
1307    // [`crate::render::is_leading_zero_padded_magnitude`] predicate —
1308    // the single source of truth every typed-magnitude codec in
1309    // caixa-core (`parse_byte_size` / `parse_duration` /
1310    // `parse_millicores` / `supervisor::duration_codec` /
1311    // `rate_limit_codec`) shares. Drift between any two codec sites'
1312    // leading-zero rejection set becomes a single-edit fix at the
1313    // shared predicate rather than five independent
1314    // `s.len() > 1 && s.as_bytes()[0] == b'0'` scans diverging over
1315    // time — same "single lifted source of truth" discipline the
1316    // peer whitespace predicates
1317    // ([`crate::render::find_ascii_whitespace_byte`] /
1318    // [`crate::render::find_non_ascii_whitespace_char`]) carry on
1319    // their strictly-complementary axes.
1320    if crate::render::is_leading_zero_padded_magnitude(num_trim) {
1321        return Err(LimitsError::leading_zero_byte_magnitude(num_trim));
1322    }
1323    // `digit_only` guarantees every byte is `[0-9]`, so the only way
1324    // u64::from_str can fail here is overflow (the magnitude exceeds
1325    // u64::MAX). Surface that as `BadByteMagnitude` with an overflow-
1326    // shaped wording so the diagnostic names the offending magnitude
1327    // verbatim rather than collapsing onto the non-canonical arm.
1328    let num: u64 = num_trim.parse::<u64>().map_err(|_| {
1329        LimitsError::bad_byte_magnitude(format!("{num_trim} (digit-only magnitude overflows u64)"))
1330    })?;
1331    let multiplier: u64 = match unit.trim() {
1332        "" | "B" => 1,
1333        "KB" => 1_000,
1334        "MB" => 1_000_000,
1335        "GB" => 1_000_000_000,
1336        "KiB" => 1024,
1337        "MiB" => 1024 * 1024,
1338        "GiB" => 1024 * 1024 * 1024,
1339        other => {
1340            return Err(LimitsError::unknown_byte_unit(other));
1341        }
1342    };
1343    // Overflow surfaces as `BadByteMagnitude` (a u64-saturating
1344    // multiply would silently truncate to `u64::MAX` and then the
1345    // wasm32-cap gate at validate time would catch it — but a u64
1346    // overflow is a parse-shaped failure on the author's input, not a
1347    // domain-cap rejection on a well-formed value, so it surfaces here
1348    // as a parser diagnostic naming the offending magnitude × unit
1349    // pair rather than as `MemoryExceedsWasm32Cap { bytes: u64::MAX }`
1350    // far from the author's intent).
1351    num.checked_mul(multiplier).ok_or_else(|| {
1352        LimitsError::bad_byte_magnitude(format!(
1353            "{num_trim}{unit_trim} overflows u64 (magnitude × unit > 2^64-1)",
1354            unit_trim = unit.trim()
1355        ))
1356    })
1357}
1358
1359fn render_byte_size(n: u64) -> String {
1360    // Prefer the largest power-of-1024 unit that divides cleanly; fall
1361    // back to bytes if nothing matches.
1362    const UNITS: &[(u64, &str)] = &[
1363        (1024 * 1024 * 1024, "GiB"),
1364        (1024 * 1024, "MiB"),
1365        (1024, "KiB"),
1366    ];
1367    for (mult, label) in UNITS {
1368        if n >= *mult && n.is_multiple_of(*mult) {
1369            return format!("{}{label}", n / mult);
1370        }
1371    }
1372    format!("{n}")
1373}
1374
1375fn ser_byte_size<S: Serializer>(v: &Option<u64>, s: S) -> Result<S::Ok, S::Error> {
1376    // Route through the canonical [`crate::render::serialize_option_via_str`]
1377    // — the substrate-side single-owner primitive for the forward arm
1378    // of the typed-magnitude codec family. See its docstring for the
1379    // full sibling roster and the compounding rationale that pins this
1380    // lift; load-bearing pinned by
1381    // `tests::ser_byte_size_routes_through_render_serialize_option_via_str_canonical`.
1382    crate::render::serialize_option_via_str(v, s, render_byte_size)
1383}
1384
1385fn de_byte_size<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
1386    // Route through the canonical [`crate::render::deserialize_option_via_str`]
1387    // — the substrate-side single-owner primitive for the reverse arm
1388    // of the typed-magnitude codec family. See its docstring for the
1389    // full sibling roster and the compounding rationale that pins this
1390    // lift; load-bearing pinned by
1391    // `tests::de_byte_size_routes_through_render_deserialize_option_via_str_canonical`.
1392    crate::render::deserialize_option_via_str(d, parse_byte_size)
1393}
1394
1395// ── duration codec ─────────────────────────────────────────────────────
1396
1397fn parse_duration(s: &str) -> Result<Duration, LimitsError> {
1398    // Paired whitespace-rejection arm — same canonical-form
1399    // render-determinism discipline as the peer `parse_byte_size` /
1400    // `parse_millicores` / `supervisor::duration_codec::parse` /
1401    // `rate_limit_codec::parse` sites: the ASCII byte-scan closes the
1402    // WhatWG-conformant whitespace bytes every downstream YAML / JSON /
1403    // TOML parser can feed through a quoted-scalar value verbatim
1404    // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
1405    // `char::is_whitespace` scan closes the strictly-complementary
1406    // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
1407    // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
1408    // codepoints) that `str::trim` at parse entry silently strips.
1409    // Either drift class would round-trip through `render_duration` to
1410    // a *different* canonical form on next emit — breaking the
1411    // THEORY.md Part V render-determinism contract. Diagnostics stay
1412    // typed at `WhitespaceInDuration` / `NonAsciiWhitespaceInDuration`.
1413    //
1414    // Routed through the lifted [`crate::render::reject_whitespace`]
1415    // primitive — the substrate-side single-owner paired-arm gate every
1416    // typed-magnitude codec in caixa-core shares.
1417    crate::render::reject_whitespace(
1418        s,
1419        |byte| LimitsError::whitespace_in_duration(s, byte),
1420        |ch| LimitsError::non_ascii_whitespace_in_duration(s, ch),
1421    )?;
1422    let s = s.trim();
1423    if s.is_empty() {
1424        return Err(LimitsError::EmptyDuration(s.into()));
1425    }
1426    // Routed through the lifted
1427    // [`crate::render::split_magnitude_and_alpha_unit`] primitive — the
1428    // single-owner split every ASCII-alphabetic-unit typed-magnitude
1429    // codec in caixa-core shares. See its docstring for the full
1430    // sibling roster on the same primitive altitude.
1431    let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
1432    let num_trim = num_part.trim();
1433    // The canonical authoring form for `:limits :wall-clock` is
1434    // `<integer><unit>` — every magnitude `render_duration` emits is a
1435    // non-negative integer with no decimal point and no leading sign,
1436    // so the parser's accepted set must match for serialize/deserialize
1437    // to round-trip without canonical-form drift. Until this gate
1438    // landed the parser accepted any `f64`-shaped magnitude
1439    // (`"1.5s"` → 1500ms, `"1.0s"` → 1s, `"0.5m"` → 30s, `"+30s"` →
1440    // 30s) and serde silently round-tripped the value to a *different*
1441    // canonical string on the next emit (`"1.5s"` → 1500ms →
1442    // `"1500ms"`, `"1.0s"` → 1s → `"1s"`, `"0.5m"` → 30s → `"30s"`,
1443    // `"+30s"` → 30s → `"30s"`) — breaking the THEORY.md Part V
1444    // render-determinism contract every typed slot carries. The same
1445    // canonical-form discipline `parse_byte_size`'s integer-magnitude
1446    // gate (the immediate predecessor on the peer `:limits :memory`
1447    // codec) applies; this gate is the direct successor on the
1448    // `:limits :wall-clock` codec.
1449    //
1450    // Strict canonical form: every byte of the magnitude is an ASCII
1451    // digit (no `.`, no `+`, no `-`). On current Rust `u64::from_str`
1452    // permissively accepts a leading `+` (`"+30"` → 30) — that's a
1453    // canonical-drift shape `render_duration` never emits, so the
1454    // digit-only check is what closes the leading-sign class; relying
1455    // on `u64::from_str`'s strictness alone would silently admit it.
1456    // On non-digit-only inputs the gate distinguishes "non-canonical-
1457    // but-numeric" (parses as f64 or i64 — surfaced as the new
1458    // `NonIntegerDurationMagnitude` variant with a self-locating
1459    // diagnostic) from "garbage" (parses as neither — surfaced as the
1460    // existing `BadDurationMagnitude` so its narrower diagnostic
1461    // remains load-bearing).
1462    //
1463    // Routed through the lifted
1464    // [`crate::render::is_digit_only_magnitude`] predicate — the same
1465    // source of truth the four peer typed-magnitude codec sites share.
1466    let digit_only = crate::render::is_digit_only_magnitude(num_trim);
1467    if !digit_only {
1468        let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
1469        if numeric {
1470            return Err(LimitsError::non_integer_duration_magnitude(num_trim));
1471        }
1472        return Err(LimitsError::bad_duration_magnitude(num_part));
1473    }
1474    // Leading-zero arm — peer with the `supervisor::duration_codec`
1475    // leading-zero arm (9178904) and the `rate_limit_codec`
1476    // leading-zero arm (4f46830) on the same canonical-form
1477    // render-determinism axis. The digit-only gate accepts `"030s"`,
1478    // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
1479    // losslessly (= 30, 0, 1, 500), but `render_duration` emits the
1480    // leading-zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`)
1481    // — a *different* canonical string on the next emit, breaking the
1482    // THEORY.md Part V render-determinism contract the same way
1483    // `"+30s"` did before the leading-`+` arm landed. The single-byte
1484    // magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips losslessly
1485    // through `render_duration` (`render_duration(Duration::ZERO)`
1486    // emits `"0s"`) — the downstream semantic-zero gate
1487    // [`LimitsError::WallClockZero`] refuses zero-magnitude authoring
1488    // at the typed-validate layer above, so the single-byte `"0"`
1489    // stays in the accepted set at this codec layer and the
1490    // diagnostic partitioning between canonical-form drift (this arm)
1491    // and semantic-zero (the downstream gate) remains stable. Same
1492    // codec-layer / typed-validate-layer partition the peer codecs
1493    // preserve.
1494    //
1495    // Routed through the lifted
1496    // [`crate::render::is_leading_zero_padded_magnitude`] predicate —
1497    // the same source of truth the four peer typed-magnitude codec
1498    // sites share.
1499    if crate::render::is_leading_zero_padded_magnitude(num_trim) {
1500        return Err(LimitsError::leading_zero_duration_magnitude(num_trim));
1501    }
1502    // The digit-only gate guarantees every byte is `[0-9]`, and the
1503    // leading-zero arm above guarantees the magnitude is either the
1504    // single byte `"0"` or starts with `[1-9]`, so the only way
1505    // `u64::from_str` can fail here is overflow.
1506    let num: u64 = num_trim.parse::<u64>().map_err(|_| {
1507        LimitsError::bad_duration_magnitude(format!(
1508            "{num_trim} (digit-only magnitude overflows u64)"
1509        ))
1510    })?;
1511    // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration` unit-arm
1512    // dispatch through the canonical
1513    // [`crate::render::duration_from_integer_magnitude_and_unit`]
1514    // primitive — the substrate-side single-owner unit-dispatch table
1515    // every typed-duration codec in caixa-core routes through
1516    // (peer: `supervisor::duration_codec::parse` backing the shared
1517    // `:supervisor :restart-window` / `:politicas :timeout` /
1518    // `:politicas :circuit-breaker :window` slots). Every unit
1519    // conversion is integer-exact for an integer magnitude; overflow
1520    // surfaces via the typed `DurationUnitError::Overflow { multiplier }`
1521    // discriminant so this arm reconstructs the pre-lift
1522    // `"…overflows u64 (magnitude × 60 > 2^64-1)"` /
1523    // `"…overflows u64 (magnitude × 3600 > 2^64-1)"` wording verbatim
1524    // from `num_trim` / `unit_trim` / the returned `multiplier`, and
1525    // the unknown-unit arm reconstructs the pre-lift
1526    // `LimitsError::UnknownDurationUnit { unit }` variant from the
1527    // caller-scoped `unit_trim`. Load-bearing pinned by
1528    // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
1529    let unit_trim = unit.trim();
1530    let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
1531        |e| match e {
1532            crate::render::DurationUnitError::Overflow { multiplier } => {
1533                LimitsError::bad_duration_magnitude(format!(
1534                    "{num_trim}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
1535                ))
1536            }
1537            crate::render::DurationUnitError::UnknownUnit => {
1538                LimitsError::unknown_duration_unit(unit_trim)
1539            }
1540        },
1541    )?;
1542    Ok(dur)
1543}
1544
1545fn ser_duration<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
1546    // Route through the canonical [`crate::render::serialize_option_via_str`]
1547    // — the substrate-side single-owner primitive for the forward arm
1548    // of the typed-magnitude codec family — around the canonical
1549    // [`crate::supervisor::duration_codec::render`] duration-byte
1550    // dispatch. The `render` dispatch is itself the load-bearing
1551    // single-owner primitive for duration bytes across every caixa
1552    // typed-duration surface (`:limits :wall-clock`,
1553    // `:politicas :timeout`, `:circuit-breaker :window`, future OTP
1554    // `gen_server` per-call timeouts); the outer
1555    // `serialize_option_via_str` closes the `Some(_) => serialize_str`
1556    // / `None => serialize_none` `Option`-arm dispatch every peer
1557    // typed-magnitude serializer shares. Load-bearing pinned by
1558    // `tests::ser_duration_routes_through_supervisor_duration_codec_render_canonical`.
1559    crate::render::serialize_option_via_str(v, s, crate::supervisor::duration_codec::render)
1560}
1561
1562fn de_duration<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
1563    // Route through the canonical [`crate::render::deserialize_option_via_str`]
1564    // — the substrate-side single-owner primitive for the reverse arm
1565    // of the typed-magnitude codec family. See its docstring for the
1566    // full sibling roster and the compounding rationale that pins this
1567    // lift.
1568    crate::render::deserialize_option_via_str(d, parse_duration)
1569}
1570
1571// ── millicores codec ───────────────────────────────────────────────────
1572
1573fn parse_millicores(s: &str) -> Result<u32, LimitsError> {
1574    // Paired whitespace-rejection arm — same canonical-form
1575    // render-determinism discipline as the peer `parse_byte_size` /
1576    // `parse_duration` / `supervisor::duration_codec::parse` /
1577    // `rate_limit_codec::parse` sites: the ASCII byte-scan closes the
1578    // WhatWG-conformant whitespace bytes (`0x20`, `0x09`, `0x0A`,
1579    // `0x0C`, `0x0D`), the non-ASCII `char::is_whitespace` scan closes
1580    // the strictly-complementary Unicode `White_Space` class (NBSP
1581    // `\u{00A0}`, LINE SEPARATOR `\u{2028}`, EM-SPACE `\u{2003}`, and
1582    // the peer typography codepoints) that `str::trim` at parse entry
1583    // silently strips. Either drift class would round-trip through
1584    // `render_millicores` to a *different* canonical form on next emit
1585    // — breaking the THEORY.md Part V render-determinism contract.
1586    // Diagnostics stay typed at `WhitespaceInMillicores` /
1587    // `NonAsciiWhitespaceInMillicores` — peer with every prior
1588    // canonical-form-drift arm on this codec
1589    // (`NonIntegerMillicoreMagnitude`, `LeadingZeroMillicoreMagnitude`).
1590    //
1591    // Routed through the lifted [`crate::render::reject_whitespace`]
1592    // primitive — the substrate-side single-owner paired-arm gate every
1593    // typed-magnitude codec in caixa-core shares.
1594    crate::render::reject_whitespace(
1595        s,
1596        |byte| LimitsError::whitespace_in_millicores(s, byte),
1597        |ch| LimitsError::non_ascii_whitespace_in_millicores(s, ch),
1598    )?;
1599    let s_trim = s.trim();
1600    if s_trim.is_empty() {
1601        return Err(LimitsError::bad_millicores(s));
1602    }
1603    let (magnitude, has_m_suffix) = match s_trim.strip_suffix('m') {
1604        Some(stripped) => (stripped.trim(), true),
1605        None => (s_trim, false),
1606    };
1607    if magnitude.is_empty() {
1608        // Bare `"m"` (or `" m "`) — no magnitude was authored. The
1609        // canonical millicores authoring form requires a magnitude in
1610        // front of the unit (`"500m"`, not `"m"`). Surface as
1611        // `BadMillicores` so the existing narrower-arm wording stays
1612        // load-bearing for "no recognizable magnitude" inputs.
1613        return Err(LimitsError::bad_millicores(s));
1614    }
1615    // The canonical authoring form for `:limits :cpu` is `<integer>m`
1616    // (Kubernetes millicores) or the bare-core shorthand `<integer>`
1617    // (`"2"` = 2000 millicores). Every magnitude `render_millicores`
1618    // emits is a non-negative integer (`format!("{m}m")`) — no decimal
1619    // point, no leading sign — so the parser's accepted set must match
1620    // for serialize/deserialize to round-trip without canonical-form
1621    // drift. Until this gate landed the parser accepted any
1622    // `u32::from_str`-shaped magnitude (`"+500m"` → 500, `"+2"` →
1623    // 2000) and serde silently round-tripped the value to a *different*
1624    // canonical string on the next emit (`"+500m"` → `"500m"`, `"+2"`
1625    // → `"2000m"`) — breaking the THEORY.md Part V render-determinism
1626    // contract every typed slot carries. Closes the sixth (and last)
1627    // typed-codec surface in caixa-core on the integer-magnitude
1628    // canonical-form axis, peer with the five duration / byte-size /
1629    // rate-limit codecs the prior trajectory (1c55a2a / 818dd38 /
1630    // d1fd67b / f479c41 / d53c922) covered.
1631    //
1632    // Strict canonical form: every byte of the magnitude is an ASCII
1633    // digit (no `.`, no `+`, no `-`). On current Rust `u32::from_str`
1634    // permissively accepts a leading `+` (`"+500"` → 500) — that's a
1635    // canonical-drift shape `render_millicores` never emits, so the
1636    // digit-only check is what closes the leading-sign class; relying
1637    // on `u32::from_str`'s strictness alone would silently admit it.
1638    // On non-digit-only inputs the gate distinguishes "non-canonical-
1639    // but-numeric" (parses as f64 or i64 — surfaced as the new
1640    // `NonIntegerMillicoreMagnitude` variant naming the offending
1641    // magnitude verbatim with the canonical-form remediation) from
1642    // "garbage" (parses as neither — surfaced as the existing
1643    // `BadMillicores` so its narrower diagnostic shape remains
1644    // load-bearing for the not-a-numeric-input class).
1645    //
1646    // Routed through the lifted
1647    // [`crate::render::is_digit_only_magnitude`] predicate — the same
1648    // source of truth the four peer typed-magnitude codec sites share.
1649    // The predicate carries a `!<var>.is_empty()` gate that is
1650    // strictly no-op here (the `magnitude.is_empty()` arm above
1651    // already surfaces an empty magnitude as
1652    // [`LimitsError::BadMillicores`] before this line is reached), so
1653    // the semantics are preserved verbatim: on every reachable input
1654    // the predicate returns `magnitude.bytes().all(|b|
1655    // b.is_ascii_digit())`, byte-for-byte what the removed inline
1656    // expression computed.
1657    let digit_only = crate::render::is_digit_only_magnitude(magnitude);
1658    if !digit_only {
1659        let numeric = magnitude.parse::<f64>().is_ok() || magnitude.parse::<i64>().is_ok();
1660        if numeric {
1661            return Err(LimitsError::non_integer_millicore_magnitude(magnitude));
1662        }
1663        return Err(LimitsError::bad_millicores(s));
1664    }
1665    // Leading-zero arm — peer with the `parse_byte_size` leading-zero
1666    // arm (cea9a78), the `parse_duration` leading-zero arm (39762d7),
1667    // the `supervisor::duration_codec` leading-zero arm (9178904) and
1668    // the `rate_limit_codec` leading-zero arm (4f46830) on the same
1669    // canonical-form render-determinism axis. The digit-only gate
1670    // accepts `"0500m"`, `"00m"`, `"02"`, `"01500m"` as `u32::from_str`
1671    // parses them losslessly (= 500, 0, 2, 1500), but `render_millicores`
1672    // emits the leading-zero-stripped form (`"500m"`, `"0m"`, `"2000m"`,
1673    // `"1500m"`) — a *different* canonical string on the next emit,
1674    // breaking the THEORY.md Part V render-determinism contract the
1675    // same way `"+500m"` did before the leading-`+` arm landed. The
1676    // single-byte magnitude `"0"` (or `"0m"`) round-trips losslessly
1677    // through `render_millicores` (`render_millicores(0)` emits `"0m"`)
1678    // — the downstream semantic-zero gate [`LimitsError::CpuZero`]
1679    // refuses zero-magnitude authoring at the typed-validate layer
1680    // above, so the single-byte `"0"` stays in the accepted set at this
1681    // codec layer and the diagnostic partitioning between canonical-
1682    // form drift (this arm) and semantic-zero (the downstream gate)
1683    // remains stable. Same codec-layer / typed-validate-layer partition
1684    // the peer codecs preserve. Closes the sixth (and last) typed
1685    // numeric-codec surface in caixa-core on the integer-magnitude
1686    // leading-zero axis — the trajectory the prior `parse_byte_size`
1687    // arm (cea9a78) explicitly named.
1688    //
1689    // Routed through the lifted
1690    // [`crate::render::is_leading_zero_padded_magnitude`] predicate —
1691    // the same source of truth the four peer typed-magnitude codec
1692    // sites share.
1693    if crate::render::is_leading_zero_padded_magnitude(magnitude) {
1694        return Err(LimitsError::leading_zero_millicore_magnitude(magnitude));
1695    }
1696    // The digit-only gate guarantees every byte is `[0-9]`, and the
1697    // leading-zero arm above guarantees the magnitude is either the
1698    // single byte `"0"` or starts with `[1-9]`, so the only way
1699    // `u32::from_str` can fail here is overflow (the magnitude exceeds
1700    // `u32::MAX`). Surface that as `BadMillicores` with an overflow-
1701    // shaped wording so the diagnostic names the offending magnitude
1702    // verbatim rather than collapsing onto the non-canonical arm —
1703    // matches `parse_byte_size` / `parse_duration` / `rate_limit_codec`
1704    // overflow-arm shape on the peer typed codecs.
1705    let num: u32 = magnitude.parse::<u32>().map_err(|_| {
1706        LimitsError::bad_millicores(format!("{magnitude} (digit-only magnitude overflows u32)"))
1707    })?;
1708    if has_m_suffix {
1709        Ok(num)
1710    } else {
1711        // Bare-core shorthand: `"2"` = 2000 millicores. Use
1712        // `checked_mul` (not the prior `saturating_mul`) so a
1713        // magnitude that overflows u32 on the × 1000 conversion
1714        // surfaces a parser-shaped diagnostic at parse time rather
1715        // than silently saturating to `u32::MAX` (which would land
1716        // as the cap value far from the author's intent and bypass
1717        // any future validate-time upper-bound gate the `:cpu` axis
1718        // grows). Matches `parse_byte_size`'s overflow-arm shape on
1719        // the magnitude × unit multiply.
1720        num.checked_mul(1000).ok_or_else(|| {
1721            LimitsError::bad_millicores(format!(
1722                "{magnitude} cores × 1000 overflows u32 (write the value in millicores: max \"{}m\")",
1723                u32::MAX
1724            ))
1725        })
1726    }
1727}
1728
1729fn render_millicores(m: u32) -> String {
1730    format!("{m}m")
1731}
1732
1733fn ser_millicores<S: Serializer>(v: &Option<u32>, s: S) -> Result<S::Ok, S::Error> {
1734    // Route through the canonical [`crate::render::serialize_option_via_str`]
1735    // — see peer `ser_byte_size` / `ser_duration` routing notes above.
1736    crate::render::serialize_option_via_str(v, s, render_millicores)
1737}
1738
1739fn de_millicores<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u32>, D::Error> {
1740    // Route through the canonical [`crate::render::deserialize_option_via_str`]
1741    // — see peer `de_byte_size` / `de_duration` routing notes above.
1742    crate::render::deserialize_option_via_str(d, parse_millicores)
1743}
1744
1745// Fold the six `LimitsError::{NonInteger,LeadingZero}<Kind>Magnitude
1746// { value: <val>.into() }` wire-up sites on the three typed-magnitude
1747// codec surfaces (`parse_byte_size` / `parse_duration` /
1748// `parse_millicores`) onto one substrate-primitive family per typed
1749// variant — the paired `{ value: String }` single-slot family on
1750// [`LimitsError`]. First fold family on [`LimitsError`], peer of the
1751// four `LayoutError` ctor macro families (`layout_violation_ctors!`
1752// 131ca0d — 16 `{ caixa, issue }` variants; `layout_slot_kind_ctors!`
1753// 0419438 — 4 `{ caixa, kind, slots }` variants;
1754// `LayoutError::missing_entry` 1b09f9d — 1 `{ kind, path }` variant;
1755// `layout_nome_only_ctors!` 3fe3dd7 — 6 `<Variant>(String)` variants)
1756// on the sibling layout-side envelopes, and of the four `AplicacaoError`
1757// ctor macro families (`aplicacao_field_reason_ctors!` 981060b — 7
1758// `{ <field>, reason }` variants; `contrato_target_ctors!` 14b81d5 — 2
1759// `{ de, para, wit, expected }` variants; `contrato_empty_pair_ctors!`
1760// 8580068 — 4 `{ de, para }` variants; `contrato_pair_value_reason_ctors!`
1761// 14e13f1 — 3 `{ de, para, <field>, reason }` variants) on the sibling
1762// mesh-side envelopes.
1763//
1764// Every one of the six wire-up sites — the `NonInteger` / `LeadingZero`
1765// arms inside [`parse_byte_size`], [`parse_duration`], and
1766// [`parse_millicores`] — opened the identical three-line
1767// `return Err(LimitsError::<Variant> { value: <val>.into() });` block
1768// against the per-codec local magnitude binding (`num_trim` on the two
1769// alpha-unit codecs, `magnitude` on the millicores codec) — the exact
1770// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
1771// names as a bug, on the same altitude the peer four `LayoutError` and
1772// four `AplicacaoError` constructor families each closed on their
1773// sibling envelopes.
1774//
1775// The macro below generates one `#[must_use]` inherent constructor per
1776// variant of shape `fn <ctor>(value: &str) -> LimitsError`, collapsing
1777// the six sites onto one dispatch per arm:
1778// `return Err(LimitsError::<ctor>(<val>));`, byte-equal to the pre-lift
1779// struct-literal on the same `value` argument. The uniform single-field
1780// construction (`value: value.to_string()`) is spelled once — inside the
1781// macro — rather than at every wire-up site. `#[must_use]` fires a
1782// compile warning at any wire-up that mistakenly discards the
1783// constructed error.
1784//
1785// Every future consumer that wants to construct one of these six
1786// variants outside the three current codec surfaces (a deferred
1787// `feira lint --canonical-magnitudes` per-caixa admission verb probing
1788// each authored `:memory` / `:wall-clock` / `:cpu` value against the
1789// same canonical-form gate, an M4 typed `mesh.pleme.io/v1alpha1/Servico`
1790// CR materializer's per-`:limits` admission validators, a per-
1791// `computeunit.yaml` value-shape pre-emitter probing each declared
1792// magnitude ahead of the operator's admit-cycle) reaches the variant
1793// through one call rather than re-inlining the three-line struct-literal
1794// in lockstep with the pre-existing six sites.
1795macro_rules! limits_codec_value_only_ctors {
1796    ($($ctor:ident => $variant:ident),* $(,)?) => {
1797        impl LimitsError {
1798            $(
1799                #[doc = concat!(
1800                    "Construct a [`LimitsError::",
1801                    stringify!($variant),
1802                    "`] naming the offending magnitude `value`. Folds the ",
1803                    "uniform `{ value: value.to_string() }` single-slot ",
1804                    "construction onto one substrate primitive so every ",
1805                    "wire-up on this variant reads through one dispatch ",
1806                    "rather than the pre-lift three-line struct-literal ",
1807                    "block."
1808                )]
1809                #[must_use]
1810                pub fn $ctor(value: &str) -> Self {
1811                    Self::$variant { value: value.to_string() }
1812                }
1813            )*
1814        }
1815    };
1816}
1817
1818limits_codec_value_only_ctors! {
1819    non_integer_byte_magnitude => NonIntegerByteMagnitude,
1820    leading_zero_byte_magnitude => LeadingZeroByteMagnitude,
1821    non_integer_duration_magnitude => NonIntegerDurationMagnitude,
1822    leading_zero_duration_magnitude => LeadingZeroDurationMagnitude,
1823    non_integer_millicore_magnitude => NonIntegerMillicoreMagnitude,
1824    leading_zero_millicore_magnitude => LeadingZeroMillicoreMagnitude,
1825}
1826
1827// Fold the two `LimitsError::Unknown<Kind>Unit { unit: <val>.into() }`
1828// wire-up sites on the two alpha-unit typed-magnitude codec surfaces
1829// (`parse_byte_size` at the `KB | MB | GB | KiB | MiB | GiB | "" | B`
1830// unit-dispatch table's fallthrough arm; `parse_duration` at the
1831// `crate::render::DurationUnitError::UnknownUnit` reverse-map arm of the
1832// `ms | s | "" | m | h` unit-dispatch table) onto one substrate-primitive
1833// family per typed variant — the paired `{ unit: String }` single-slot
1834// family on [`LimitsError`]. Direct peer of the sibling
1835// [`limits_codec_value_only_ctors!`] single-slot family on the same
1836// [`LimitsError`] envelope (6 variants on the `{ value: String }` axis
1837// of the codec surface) and of the peer [`limits_codec_value_byte_ctors!`]
1838// / [`limits_codec_value_char_ctors!`] families on the wider two-slot /
1839// three-slot whitespace-class axes of the same three codec surfaces.
1840//
1841// Every one of the two wire-up sites — the fallthrough of
1842// [`parse_byte_size`]'s unit-dispatch `match` on the caller-scoped
1843// `other: &str` binding; the [`crate::render::DurationUnitError::UnknownUnit`]
1844// reverse-map arm of [`parse_duration`]'s codec-scoped `unit_trim: &str`
1845// binding — opened the identical two-line
1846// `LimitsError::Unknown<Kind>Unit { unit: <val>.into() }` block against
1847// the codec-scoped unit binding — the exact "same block re-inlined at
1848// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
1849// altitude the peer [`limits_codec_value_only_ctors!`] family closed on
1850// the sibling `{ value: String }` axis of the same codec surface.
1851//
1852// The macro below generates one `#[must_use]` inherent constructor per
1853// variant of shape `fn <ctor>(unit: &str) -> LimitsError`, collapsing
1854// the two sites onto one dispatch per arm: `LimitsError::<ctor>(<val>)`,
1855// byte-equal to the pre-lift struct-literal on the same `unit` argument.
1856// The uniform single-field construction (`unit: unit.to_string()`) is
1857// spelled once — inside the macro — rather than at every wire-up site.
1858// `#[must_use]` fires a compile warning at any wire-up that mistakenly
1859// discards the constructed error.
1860//
1861// Every future consumer that wants to construct one of these two
1862// variants outside the two current codec surfaces (a deferred
1863// `feira lint --canonical-units` per-caixa admission verb probing each
1864// authored `:memory` / `:wall-clock` value against the same
1865// unit-dispatch table, an M4 typed `mesh.pleme.io/v1alpha1/Servico` CR
1866// materializer's per-`:limits` admission validators pre-checking a
1867// per-slot unit alphabet against a cluster-local snapshot, a future
1868// unit-alphabet widening on either codec that shares the same
1869// unknown-unit fallthrough shape) now reaches each variant through one
1870// call rather than re-inlining the two-line struct-literal in lockstep
1871// with the pre-existing two sites.
1872macro_rules! limits_codec_unit_only_ctors {
1873    ($($ctor:ident => $variant:ident),* $(,)?) => {
1874        impl LimitsError {
1875            $(
1876                #[doc = concat!(
1877                    "Construct a [`LimitsError::",
1878                    stringify!($variant),
1879                    "`] naming the offending magnitude `unit`. Folds the ",
1880                    "uniform `{ unit: unit.to_string() }` single-slot ",
1881                    "construction onto one substrate primitive so every ",
1882                    "wire-up on this variant reads through one dispatch ",
1883                    "rather than the pre-lift two-line struct-literal ",
1884                    "block."
1885                )]
1886                #[must_use]
1887                pub fn $ctor(unit: &str) -> Self {
1888                    Self::$variant { unit: unit.to_string() }
1889                }
1890            )*
1891        }
1892    };
1893}
1894
1895limits_codec_unit_only_ctors! {
1896    unknown_byte_unit => UnknownByteUnit,
1897    unknown_duration_unit => UnknownDurationUnit,
1898}
1899
1900// Fold the three `LimitsError::WhitespaceIn<Kind> { value: <val>.into(),
1901// byte }` wire-up sites on the three typed-magnitude codec surfaces
1902// (`parse_byte_size` / `parse_duration` / `parse_millicores`) onto one
1903// substrate-primitive family per typed variant — the paired
1904// `{ value: String, byte: u8 }` two-slot family on [`LimitsError`].
1905// Sibling of the peer [`limits_codec_value_only_ctors!`] single-slot
1906// family on the same three codec surfaces, and of the peer
1907// [`limits_codec_value_char_ctors!`] three-slot family on the
1908// strictly-complementary non-ASCII whitespace class.
1909//
1910// Every one of the three wire-up sites — the ASCII-whitespace-rejection
1911// arm of the paired [`crate::render::reject_whitespace`] closure at
1912// each codec — opened the identical four-line
1913// `|byte| LimitsError::WhitespaceIn<Kind> { value: <s>.into(), byte }`
1914// block against the codec-scoped `<s>: &str` binding.
1915//
1916// The macro below generates one `#[must_use]` inherent constructor per
1917// variant of shape `fn <ctor>(value: &str, byte: u8) -> LimitsError`,
1918// collapsing the three sites onto one dispatch per arm:
1919// `|byte| LimitsError::<ctor>(s, byte)`, byte-equal to the pre-lift
1920// struct-literal on the same `(value, byte)` pair. The uniform two-field
1921// construction (`value: value.to_string()`, `byte`) is spelled once —
1922// inside the macro — rather than at every wire-up site.
1923macro_rules! limits_codec_value_byte_ctors {
1924    ($($ctor:ident => $variant:ident),* $(,)?) => {
1925        impl LimitsError {
1926            $(
1927                #[doc = concat!(
1928                    "Construct a [`LimitsError::",
1929                    stringify!($variant),
1930                    "`] naming the offending magnitude `value` and the ",
1931                    "raw ASCII-whitespace `byte` that fell inside it. ",
1932                    "Folds the uniform `{ value: value.to_string(), byte }` ",
1933                    "two-slot construction onto one substrate primitive so ",
1934                    "every wire-up on this variant reads through one dispatch ",
1935                    "rather than the pre-lift four-line struct-literal block."
1936                )]
1937                #[must_use]
1938                pub fn $ctor(value: &str, byte: u8) -> Self {
1939                    Self::$variant { value: value.to_string(), byte }
1940                }
1941            )*
1942        }
1943    };
1944}
1945
1946limits_codec_value_byte_ctors! {
1947    whitespace_in_byte_size => WhitespaceInByteSize,
1948    whitespace_in_duration => WhitespaceInDuration,
1949    whitespace_in_millicores => WhitespaceInMillicores,
1950}
1951
1952// Fold the three `LimitsError::NonAsciiWhitespaceIn<Kind>
1953// { value: <val>.into(), ch, codepoint: ch as u32 }` wire-up sites on
1954// the three typed-magnitude codec surfaces (`parse_byte_size` /
1955// `parse_duration` / `parse_millicores`) onto one substrate-primitive
1956// family per typed variant — the paired `{ value: String, ch: char,
1957// codepoint: u32 }` three-slot family on [`LimitsError`]. Sibling of
1958// the peer [`limits_codec_value_only_ctors!`] single-slot family on the
1959// same three codec surfaces, and of the peer
1960// [`limits_codec_value_byte_ctors!`] two-slot family on the strictly-
1961// complementary ASCII whitespace class.
1962//
1963// Every one of the three wire-up sites — the Unicode-`White_Space`-
1964// rejection arm of the paired [`crate::render::reject_whitespace`]
1965// closure at each codec — opened the identical five-line
1966// `|ch| LimitsError::NonAsciiWhitespaceIn<Kind> { value: <s>.into(),
1967// ch, codepoint: ch as u32 }` block against the codec-scoped
1968// `<s>: &str` binding, with the load-bearing `codepoint: ch as u32`
1969// derivation open-coded at every wire-up. The macro pulls the
1970// derivation inside the ctor body so every wire-up now reads
1971// `|ch| LimitsError::<ctor>(s, ch)` and every future consumer of the
1972// variant is guaranteed to carry the derivation through one canonical
1973// path rather than re-open-coding it in lockstep with the pre-existing
1974// three sites.
1975//
1976// The macro below generates one `#[must_use]` inherent constructor per
1977// variant of shape `fn <ctor>(value: &str, ch: char) -> LimitsError`,
1978// collapsing the three sites onto one dispatch per arm:
1979// `|ch| LimitsError::<ctor>(s, ch)`, byte-equal to the pre-lift
1980// struct-literal on the same `(value, ch, ch as u32)` triple.
1981macro_rules! limits_codec_value_char_ctors {
1982    ($($ctor:ident => $variant:ident),* $(,)?) => {
1983        impl LimitsError {
1984            $(
1985                #[doc = concat!(
1986                    "Construct a [`LimitsError::",
1987                    stringify!($variant),
1988                    "`] naming the offending magnitude `value` and the ",
1989                    "non-ASCII Unicode whitespace `ch` that fell inside it. ",
1990                    "Folds the uniform `{ value: value.to_string(), ch, ",
1991                    "codepoint: ch as u32 }` three-slot construction onto ",
1992                    "one substrate primitive so every wire-up on this ",
1993                    "variant reads through one dispatch rather than the ",
1994                    "pre-lift five-line struct-literal block. The load-",
1995                    "bearing `codepoint = ch as u32` derivation is pulled ",
1996                    "inside the ctor body so every future consumer of the ",
1997                    "variant carries it through one canonical path."
1998                )]
1999                #[must_use]
2000                pub fn $ctor(value: &str, ch: char) -> Self {
2001                    Self::$variant {
2002                        value: value.to_string(),
2003                        ch,
2004                        codepoint: ch as u32,
2005                    }
2006                }
2007            )*
2008        }
2009    };
2010}
2011
2012limits_codec_value_char_ctors! {
2013    non_ascii_whitespace_in_byte_size => NonAsciiWhitespaceInByteSize,
2014    non_ascii_whitespace_in_duration => NonAsciiWhitespaceInDuration,
2015    non_ascii_whitespace_in_millicores => NonAsciiWhitespaceInMillicores,
2016}
2017
2018// Fold the seven `LimitsError::<Variant> { <field>: <Copy> }` one-field
2019// `Copy`-scalar struct-variant wire-up sites at [`LimitsSpec::validate`]'s
2020// four typed-axis bracket cascades — three closure-slots at the
2021// [`crate::render::require_positive_quantum_multiple_bounded_u64`] `:memory`
2022// axis (`MemoryBelowWasm32Page { bytes }`, `MemoryExceedsWasm32Cap { bytes }`,
2023// `MemoryNotPageMultiple { bytes }`), one at the
2024// [`crate::render::require_positive_bounded_u64`] `:fuel` axis
2025// (`FuelExceedsCap { fuel }`), two at the
2026// [`crate::render::require_positive_canonical_bounded_duration`]
2027// `:wall-clock` axis (`WallClockNotCanonical { wall_clock }`,
2028// `WallClockExceedsCap { wall_clock }`), and one at the
2029// [`crate::render::require_positive_bounded_u32`] `:cpu` axis
2030// (`CpuExceedsCap { millicores }`) — onto one substrate primitive per typed
2031// variant, matching the sibling
2032// [`crate::supervisor::supervisor_scalar_ctors!`] macro (f0f77a2, 4 variants
2033// on the same `{ <field>: RestartStrategy | u32 | Duration }` shape) and the
2034// peer [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e,
2035// 8 variants on the same `{ <field>: Duration | u32 }` shape) at that
2036// discipline on the sibling `SupervisorError` per-`:supervisor` scalar axis
2037// and the peer `AplicacaoError` per-`:politicas` scalar axis. Every variant
2038// is a one-field `Copy`-pass-through struct-literal — `u64 | u32 |
2039// Duration` — so the fold routes each wire-up site through one dispatch per
2040// typed variant without a runtime-work delta. Last unlifted per-`:limits`
2041// scalar `LimitsError` variant family folded onto a substrate primitive;
2042// every M2 `LimitsSpec::validate` per-axis bracket-closure slot now reaches
2043// for a bare-function-pointer `LimitsError::<ctor>` in place of the pre-lift
2044// open-coded `|<field>| LimitsError::<Variant> { <field> }` one-line
2045// closure over the same one-field struct-literal.
2046//
2047// Each of the seven wire-up sites opened the identical
2048// `|<field>| LimitsError::<Variant> { <field> }` bracket-closure — the exact
2049// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2050// as a bug, on the same altitude the peer `supervisor_scalar_ctors!` /
2051// `aplicacao_policy_scalar_ctors!` folds each closed on the sibling
2052// `SupervisorError` / `AplicacaoError` envelopes' per-axis cap /
2053// canonical-form / below-quantum arms. The seven variants share one
2054// `{ <field>: <Copy> }` shape, so the fold routes each wire-up site through
2055// one dispatch per typed variant.
2056//
2057// The macro below generates one static constructor per variant of shape
2058// `const fn <ctor>(<field>: <ty>) -> LimitsError`, so every wire-up site
2059// collapses onto one dispatch: `LimitsError::<ctor>(<val>)`, byte-equal to
2060// the pre-lift struct-literal on the same `Copy`-`<ty>` fixture — as a bare
2061// function pointer in the `impl FnOnce(<ty>) -> LimitsError` bracket-
2062// closure slot every [`crate::render::require_positive_bounded_u32`] /
2063// [`crate::render::require_positive_bounded_u64`] /
2064// [`crate::render::require_positive_canonical_bounded_duration`] /
2065// [`crate::render::require_positive_quantum_multiple_bounded_u64`] gate
2066// carries — rather than the pre-lift open-coded one-line closure over the
2067// same one-field struct-literal. `const fn` preserves the `Copy`-pass-
2068// through's zero-runtime-work property verbatim. Every constructor is
2069// `#[must_use]` so a caller who mistakenly discards the constructed error
2070// trips a compile warning at the wire-up site.
2071//
2072// Every future consumer that wants to construct one of these seven variants
2073// outside `LimitsSpec::validate` — a deferred
2074// `mesh.pleme.io/v1alpha1/Servico` CR materializer's admission webhook
2075// re-checking one edited `:memory` / `:fuel` / `:wall-clock` / `:cpu` slot
2076// against the below-quantum + cap + canonical-form cascade, a future
2077// `feira validate --limits` per-caixa admission verb re-running the shape
2078// gates on demand, a per-Servico overlay resolver rejecting an author-
2079// supplied slot against a cluster-local snapshot — now reaches each variant
2080// through one call rather than re-inlining the per-shape struct-literal
2081// block in lockstep with the seven in-crate wire-up sites.
2082macro_rules! limits_scalar_ctors {
2083    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
2084        impl LimitsError {
2085            $(
2086                #[doc = concat!(
2087                    "Construct a [`LimitsError::",
2088                    stringify!($variant),
2089                    "`] naming the offending per-`:limits` `",
2090                    stringify!($field),
2091                    "` scalar. Folds the uniform `Self::",
2092                    stringify!($variant),
2093                    " { ",
2094                    stringify!($field),
2095                    " }` one-field `Copy`-pass-through struct-literal onto ",
2096                    "one substrate primitive so every per-axis wire-up on ",
2097                    "this variant reads through one dispatch — as a bare ",
2098                    "function pointer in the `impl FnOnce(",
2099                    stringify!($ty),
2100                    ") -> LimitsError` bracket-closure slot every ",
2101                    "`crate::render::require_positive_bounded_*` / ",
2102                    "`crate::render::require_positive_canonical_bounded_*` / ",
2103                    "`crate::render::require_positive_quantum_multiple_bounded_*` ",
2104                    "gate carries — rather than the pre-lift open-coded ",
2105                    "one-line closure over the same one-field struct-literal. ",
2106                    "`const fn` preserves the `Copy`-pass-through's ",
2107                    "zero-runtime-work property verbatim."
2108                )]
2109                #[must_use]
2110                pub const fn $ctor($field: $ty) -> Self {
2111                    Self::$variant { $field }
2112                }
2113            )*
2114        }
2115    };
2116}
2117
2118limits_scalar_ctors! {
2119    memory_below_wasm32_page => MemoryBelowWasm32Page { bytes: u64 },
2120    memory_exceeds_wasm32_cap => MemoryExceedsWasm32Cap { bytes: u64 },
2121    memory_not_page_multiple => MemoryNotPageMultiple { bytes: u64 },
2122    fuel_exceeds_cap => FuelExceedsCap { fuel: u64 },
2123    wall_clock_not_canonical => WallClockNotCanonical { wall_clock: Duration },
2124    wall_clock_exceeds_cap => WallClockExceedsCap { wall_clock: Duration },
2125    cpu_exceeds_cap => CpuExceedsCap { millicores: u32 },
2126}
2127
2128// Fold the five `LimitsError::BadMillicores(<into-String-expr>)` wire-up
2129// sites on the [`parse_millicores`] codec surface onto one substrate
2130// primitive per typed variant — the paired `(String)` single-slot
2131// tuple-newtype [`LimitsError::BadMillicores`] on the millicores codec
2132// surface. Peer of the sibling [`limits_codec_value_only_ctors!`] /
2133// [`limits_codec_unit_only_ctors!`] / [`limits_codec_value_byte_ctors!`]
2134// / [`limits_codec_value_char_ctors!`] families on the same
2135// [`LimitsError`] envelope (the paired `{ value: String }` /
2136// `{ unit: String }` / `{ value: String, byte: u8 }` /
2137// `{ value: String, ch: char, codepoint: u32 }` struct-shaped families
2138// on the same codec surface) and of the peer [`limits_scalar_ctors!`]
2139// family on the wider `Copy`-`{ <field>: <ty> }` typed-scalar axis of
2140// the same [`LimitsError`] envelope. Closes the widest un-lifted variant
2141// on [`LimitsError`] — every one of the five wire-up sites opened the
2142// identical `LimitsError::BadMillicores(<into-String-expr>)` block
2143// against the codec-scoped `&str` (`s`) or `String` (`format!(...)`)
2144// binding, so the fold routes each site through one dispatch on a
2145// uniform `impl Into<String>` param, byte-equal to the pre-lift tuple-
2146// newtype construction on the same argument. The `impl Into<String>`
2147// bound covers both wire-up shapes — the three `s.into()` `&str` sites
2148// (empty-`:cpu`, bare-`m`-magnitude fallthrough, non-digit-only garbage
2149// fallthrough) and the two `format!(...)` `String` sites (digit-only
2150// magnitude overflows u32, bare-core-shorthand × 1000 overflow) —
2151// without forcing either caller to spell the conversion at the wire-up
2152// site. `#[must_use]` fires a compile warning at any wire-up that
2153// mistakenly discards the constructed error.
2154//
2155// Every future consumer that wants to construct this variant outside
2156// [`parse_millicores`] (a deferred `feira lint --canonical-magnitudes`
2157// per-caixa admission verb probing each authored `:cpu` value against
2158// the same canonical-form gate, an M4 typed
2159// `mesh.pleme.io/v1alpha1/Servico` CR materializer's per-`:limits`
2160// admission validator re-checking one edited `:cpu` slot against the
2161// codec's parser floor, a per-`computeunit.yaml` value-shape pre-emitter
2162// probing each declared millicores magnitude ahead of the operator's
2163// admit-cycle) now reaches the variant through one call rather than
2164// re-inlining the tuple-newtype block in lockstep with the pre-existing
2165// five sites — same discipline the peer per-variant lifts on
2166// [`AplicacaoError`] / [`SupervisorError`] / [`UpgradeError`] /
2167// [`LayoutError`] / [`DepError`] / [`ManifestError`] have converged
2168// through the "one substrate primitive per emit-site variant" ratchet.
2169impl LimitsError {
2170    /// Construct a [`LimitsError::BadMillicores`] carrying the offending
2171    /// millicores authoring string `value` verbatim in the variant's
2172    /// tuple-newtype payload. Folds the uniform
2173    /// `Self::BadMillicores(value.into())` tuple-newtype construction
2174    /// onto one substrate primitive so every wire-up on the variant
2175    /// reads through one dispatch rather than the pre-lift open-coded
2176    /// `LimitsError::BadMillicores(<into-String-expr>)` block. The
2177    /// `impl Into<String>` bound covers both wire-up shapes on
2178    /// [`parse_millicores`] — a `&str` binding (`s.into()`) and a
2179    /// `String` binding (`format!(...)`) — without forcing the caller
2180    /// to spell the conversion at the wire-up site.
2181    #[must_use]
2182    pub fn bad_millicores(value: impl Into<String>) -> Self {
2183        Self::BadMillicores(value.into())
2184    }
2185}
2186
2187// Fold the three `LimitsError::BadByteMagnitude(<into-String-expr>)`
2188// wire-up sites on the [`parse_byte_size`] codec surface onto one
2189// substrate primitive — the paired `(String)` single-slot tuple-newtype
2190// [`LimitsError::BadByteMagnitude`] on the byte-size codec surface, the
2191// direct sibling to the [`LimitsError::bad_millicores`] fold above on
2192// the peer [`parse_millicores`] codec surface (da7602f). Same
2193// discipline the peer per-variant lifts on [`AplicacaoError`] /
2194// [`SupervisorError`] / [`UpgradeError`] / [`LayoutError`] /
2195// [`DepError`] / [`ManifestError`] have converged through the
2196// "one substrate primitive per emit-site variant" ratchet: the three
2197// wire-up sites open the identical
2198// `LimitsError::BadByteMagnitude(<into-String-expr>)` block against
2199// the codec-scoped `&str` (`num_part.into()` — non-digit-only garbage
2200// fallthrough after the numeric-shape gate) or `String`
2201// (`format!(...)` — digit-only magnitude overflows u64, magnitude ×
2202// unit overflows u64) binding, so the fold routes each site through
2203// one dispatch on a uniform `impl Into<String>` param, byte-equal to
2204// the pre-lift tuple-newtype construction on the same argument.
2205//
2206// Every future consumer that wants to construct this variant outside
2207// [`parse_byte_size`] (a deferred `feira lint --canonical-magnitudes`
2208// per-caixa admission verb probing each authored `:memory` value
2209// against the same canonical-form gate, an M4 typed
2210// `mesh.pleme.io/v1alpha1/Servico` CR materializer's per-`:limits`
2211// admission validator re-checking one edited `:memory` slot against
2212// the codec's parser floor, a per-`computeunit.yaml` value-shape pre-
2213// emitter probing each declared byte-size magnitude ahead of the
2214// operator's admit-cycle) now reaches the variant through one call
2215// rather than re-inlining the tuple-newtype block in lockstep with
2216// the pre-existing three sites.
2217impl LimitsError {
2218    /// Construct a [`LimitsError::BadByteMagnitude`] carrying the
2219    /// offending byte-size authoring string `value` verbatim in the
2220    /// variant's tuple-newtype payload. Folds the uniform
2221    /// `Self::BadByteMagnitude(value.into())` tuple-newtype
2222    /// construction onto one substrate primitive so every wire-up on
2223    /// the variant reads through one dispatch rather than the pre-lift
2224    /// open-coded `LimitsError::BadByteMagnitude(<into-String-expr>)`
2225    /// block. The `impl Into<String>` bound covers both wire-up shapes
2226    /// on [`parse_byte_size`] — a `&str` binding (`num_part.into()`)
2227    /// and a `String` binding (`format!(...)`) — without forcing the
2228    /// caller to spell the conversion at the wire-up site. Direct
2229    /// sibling to [`LimitsError::bad_millicores`] on the peer
2230    /// [`parse_millicores`] codec surface.
2231    #[must_use]
2232    pub fn bad_byte_magnitude(value: impl Into<String>) -> Self {
2233        Self::BadByteMagnitude(value.into())
2234    }
2235}
2236
2237// Fold the three `LimitsError::BadDurationMagnitude(<into-String-expr>)`
2238// wire-up sites on the [`parse_duration`] codec surface onto one
2239// substrate primitive — the paired `(String)` single-slot tuple-newtype
2240// [`LimitsError::BadDurationMagnitude`] on the duration codec surface,
2241// the direct sibling to the [`LimitsError::bad_millicores`] (da7602f)
2242// and [`LimitsError::bad_byte_magnitude`] (837babc) folds above on the
2243// peer [`parse_millicores`] / [`parse_byte_size`] codec surfaces. Same
2244// discipline the peer per-variant lifts on [`AplicacaoError`] /
2245// [`SupervisorError`] / [`UpgradeError`] / [`LayoutError`] /
2246// [`DepError`] / [`ManifestError`] have converged through the
2247// "one substrate primitive per emit-site variant" ratchet: the three
2248// wire-up sites open the identical
2249// `LimitsError::BadDurationMagnitude(<into-String-expr>)` block against
2250// the codec-scoped `&str` (`num_part.into()` — non-digit-only garbage
2251// fallthrough after the numeric-shape gate) or `String`
2252// (`format!(...)` — digit-only magnitude overflows u64, magnitude ×
2253// unit overflows u64) binding, so the fold routes each site through
2254// one dispatch on a uniform `impl Into<String>` param, byte-equal to
2255// the pre-lift tuple-newtype construction on the same argument. Closes
2256// the last un-lifted variant of the paired `(String)` tuple-newtype
2257// codec-magnitude family across the three typed-magnitude codec
2258// surfaces the peer folds already own.
2259//
2260// Every future consumer that wants to construct this variant outside
2261// [`parse_duration`] (a deferred `feira lint --canonical-magnitudes`
2262// per-caixa admission verb probing each authored `:wall-clock` /
2263// `:restart-window` / `:politicas :timeout` /
2264// `:politicas :circuit-breaker :window` value against the same
2265// canonical-form gate, an M4 typed `mesh.pleme.io/v1alpha1/Servico` CR
2266// materializer's per-`:limits` admission validator re-checking one
2267// edited `:wall-clock` slot against the codec's parser floor, a
2268// per-`computeunit.yaml` value-shape pre-emitter probing each declared
2269// duration magnitude ahead of the operator's admit-cycle) now reaches
2270// the variant through one call rather than re-inlining the tuple-
2271// newtype block in lockstep with the pre-existing three sites.
2272impl LimitsError {
2273    /// Construct a [`LimitsError::BadDurationMagnitude`] carrying the
2274    /// offending duration authoring string `value` verbatim in the
2275    /// variant's tuple-newtype payload. Folds the uniform
2276    /// `Self::BadDurationMagnitude(value.into())` tuple-newtype
2277    /// construction onto one substrate primitive so every wire-up on
2278    /// the variant reads through one dispatch rather than the pre-lift
2279    /// open-coded `LimitsError::BadDurationMagnitude(<into-String-expr>)`
2280    /// block. The `impl Into<String>` bound covers both wire-up shapes
2281    /// on [`parse_duration`] — a `&str` binding (`num_part.into()`)
2282    /// and a `String` binding (`format!(...)`) — without forcing the
2283    /// caller to spell the conversion at the wire-up site. Direct
2284    /// sibling to [`LimitsError::bad_millicores`] on the peer
2285    /// [`parse_millicores`] codec surface and to
2286    /// [`LimitsError::bad_byte_magnitude`] on the peer [`parse_byte_size`]
2287    /// codec surface — closes the last un-lifted `(String)` tuple-
2288    /// newtype variant on the paired codec-magnitude family.
2289    #[must_use]
2290    pub fn bad_duration_magnitude(value: impl Into<String>) -> Self {
2291        Self::BadDurationMagnitude(value.into())
2292    }
2293}
2294
2295#[cfg(test)]
2296mod tests {
2297    use super::*;
2298
2299    #[test]
2300    fn parse_byte_size_known_units() {
2301        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
2302        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
2303        assert_eq!(parse_byte_size("512KiB").unwrap(), 512 * 1024);
2304        assert_eq!(parse_byte_size("1KB").unwrap(), 1_000);
2305        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
2306    }
2307
2308    #[test]
2309    fn parse_byte_size_rejects_unknown() {
2310        assert!(matches!(
2311            parse_byte_size("1YiB"),
2312            Err(LimitsError::UnknownByteUnit { .. })
2313        ));
2314        assert!(matches!(
2315            parse_byte_size("not-a-number"),
2316            Err(LimitsError::BadByteMagnitude(_))
2317        ));
2318    }
2319
2320    #[test]
2321    fn parse_duration_known_units() {
2322        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
2323        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
2324        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
2325        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
2326    }
2327
2328    #[test]
2329    fn parse_millicores_both_forms() {
2330        assert_eq!(parse_millicores("500m").unwrap(), 500);
2331        assert_eq!(parse_millicores("2").unwrap(), 2000);
2332    }
2333
2334    #[test]
2335    fn render_byte_size_canonical() {
2336        assert_eq!(render_byte_size(64 * 1024 * 1024), "64MiB");
2337        assert_eq!(render_byte_size(1024 * 1024 * 1024), "1GiB");
2338        assert_eq!(render_byte_size(1024), "1KiB");
2339        assert_eq!(render_byte_size(123), "123");
2340    }
2341
2342    #[test]
2343    fn ser_byte_size_routes_through_render_serialize_option_via_str_canonical() {
2344        // Routing pin: `ser_byte_size` (the `#[serde(serialize_with = …)]`
2345        // hook on `LimitsSpec::memory`) MUST emit exactly the bytes the
2346        // canonical `crate::render::serialize_option_via_str` primitive
2347        // produces when threaded through the peer `render_byte_size`
2348        // dispatch. Any future accidental re-inline of a bespoke
2349        // `match v { Some(_) => s.serialize_str(_), None =>
2350        // s.serialize_none() }` block inside this module — the shape
2351        // this lift removed — surfaces here as a byte-value drift on
2352        // the very first canonical form the two implementations
2353        // disagree on. Peer of
2354        // `ser_duration_routes_through_supervisor_duration_codec_render_canonical`
2355        // on the sibling `LimitsSpec::wall_clock` axis; same "one
2356        // canonical dispatch per axis, thin projections at each
2357        // consumer" discipline the sibling caixa-core substrate
2358        // primitives already carry.
2359        for n in [
2360            0u64,
2361            1,
2362            1023,
2363            1024,
2364            64 * 1024 * 1024,
2365            4 * 1024 * 1024 * 1024,
2366        ] {
2367            let limits = LimitsSpec {
2368                memory: Some(n),
2369                fuel: None,
2370                wall_clock: None,
2371                cpu: None,
2372            };
2373            let json: serde_json::Value =
2374                serde_json::from_str(&serde_json::to_string(&limits).unwrap()).unwrap();
2375            let emitted = json[crate::render::M2_LIMITS_KEY_MEMORY]
2376                .as_str()
2377                .expect("memory must serialize to a string");
2378            let canonical = render_byte_size(n);
2379            assert_eq!(
2380                emitted, canonical,
2381                "ser_byte_size drifted from render_byte_size via \
2382                 serialize_option_via_str on {n} bytes",
2383            );
2384        }
2385    }
2386
2387    #[test]
2388    fn de_byte_size_routes_through_render_deserialize_option_via_str_canonical() {
2389        // Routing pin: `de_byte_size` (the
2390        // `#[serde(deserialize_with = …)]` hook on
2391        // `LimitsSpec::memory`) MUST accept exactly the canonical
2392        // string set the peer `parse_byte_size` function accepts, and
2393        // reject everything else with the parser's typed `LimitsError`
2394        // surfaced through `serde::de::Error::custom` — the shape the
2395        // lifted `crate::render::deserialize_option_via_str` primitive
2396        // enforces. A future accidental re-inline of a bespoke `let
2397        // opt: Option<String> = Option::deserialize(d)?; match opt {
2398        // … }` block inside this module — the shape this lift removed
2399        // — that drifted on either arm (silently accepting a value the
2400        // parser rejects, or swallowing a parser error as `Ok(None)`)
2401        // surfaces here.
2402        for raw in ["64MiB", "1024", "0", "4GiB"] {
2403            let field = crate::render::M2_LIMITS_KEY_MEMORY;
2404            let payload = format!("{{\"{field}\":\"{raw}\"}}");
2405            let limits: LimitsSpec =
2406                serde_json::from_str(&payload).expect("canonical memory string must round-trip");
2407            let canonical = parse_byte_size(raw).expect("parse_byte_size accepts canonical form");
2408            assert_eq!(
2409                limits.memory,
2410                Some(canonical),
2411                "de_byte_size drifted from parse_byte_size via \
2412                 deserialize_option_via_str on {raw:?}",
2413            );
2414        }
2415        // Null-arm pin: `null` folds to `None` without invoking the
2416        // parser — the exact contract the lifted primitive's null-arm
2417        // test pins.
2418        let field = crate::render::M2_LIMITS_KEY_MEMORY;
2419        let null_payload = format!("{{\"{field}\":null}}");
2420        let empty: LimitsSpec = serde_json::from_str(&null_payload)
2421            .expect("null memory field must fold to LimitsSpec::memory = None");
2422        assert_eq!(
2423            empty.memory, None,
2424            "de_byte_size must fold null → None via \
2425             deserialize_option_via_str's null-arm",
2426        );
2427        // Reject-arm pin: a bogus string surfaces the parser's error
2428        // through `serde::de::Error::custom` — not `Ok(None)`.
2429        let bad_payload = format!("{{\"{field}\":\"64XiB\"}}");
2430        let err = serde_json::from_str::<LimitsSpec>(&bad_payload)
2431            .expect_err("bogus memory string must surface the parser's error");
2432        let err_text = err.to_string();
2433        assert!(
2434            err_text.contains("64XiB") || err_text.contains("XiB"),
2435            "de_byte_size must surface parse_byte_size's typed \
2436             LimitsError through serde::de::Error::custom — got \
2437             {err_text:?}",
2438        );
2439    }
2440
2441    #[test]
2442    fn ser_duration_routes_through_supervisor_duration_codec_render_canonical() {
2443        // Routing pin: `ser_duration` (the `#[serde(serialize_with = …)]`
2444        // hook on `LimitsSpec::wall_clock`) MUST emit exactly the bytes
2445        // the canonical `crate::supervisor::duration_codec::render`
2446        // primitive produces. Any future accidental re-introduction of a
2447        // sibling free-function `render_duration` shadow inside this
2448        // module — or a per-slot `serialize_with` closure that inlines
2449        // its own magnitude/unit decision tree — surfaces here as a
2450        // byte-value drift on the very first canonical form the two
2451        // implementations disagree on, well before the drift reaches any
2452        // downstream renderer's `wall_clock:` overlay. Same "one
2453        // canonical dispatch per axis, thin projections at each consumer"
2454        // discipline the sibling caixa-core substrate primitives already
2455        // carry on the peer WIT-shape / M2 supervisor-strategy / M3
2456        // mesh-slot free-function classifier families.
2457        for d in [
2458            Duration::from_secs(30),
2459            Duration::from_millis(500),
2460            Duration::from_secs(120),
2461            Duration::from_secs(3600),
2462            Duration::from_millis(0),
2463            Duration::from_millis(1500),
2464        ] {
2465            let limits = LimitsSpec {
2466                memory: None,
2467                fuel: None,
2468                wall_clock: Some(d),
2469                cpu: None,
2470            };
2471            let json: serde_json::Value =
2472                serde_json::from_str(&serde_json::to_string(&limits).unwrap()).unwrap();
2473            let emitted = json[crate::render::M2_LIMITS_KEY_WALL_CLOCK]
2474                .as_str()
2475                .expect("wall_clock must serialize to a string");
2476            let canonical = crate::supervisor::duration_codec::render(d);
2477            assert_eq!(
2478                emitted, canonical,
2479                "ser_duration drifted from supervisor::duration_codec::render on {d:?}",
2480            );
2481        }
2482    }
2483
2484    #[test]
2485    fn parse_byte_size_routes_whitespace_through_render_reject_whitespace_canonical() {
2486        // Routing pin: the paired whitespace-rejection block at the
2487        // top of `parse_byte_size` MUST route through the substrate-
2488        // side [`crate::render::reject_whitespace`] primitive — the
2489        // single-owner paired-arm gate every typed-magnitude codec
2490        // in caixa-core shares. Any future accidental re-inline of a
2491        // bespoke
2492        //
2493        // ```ignore
2494        // if let Some(byte) = find_ascii_whitespace_byte(s) { … }
2495        // if let Some(ch)   = find_non_ascii_whitespace_char(s)  { … }
2496        // ```
2497        //
2498        // block inside this module — the shape this lift removed —
2499        // that drifted on either arm surfaces here as a variant-shape
2500        // drift on the very first canonical form the two
2501        // implementations disagree on. Byte-shape pins cover the
2502        // ASCII WhatWG-conformant set (space / tab / LF / FF / CR)
2503        // and the strictly-complementary non-ASCII Unicode
2504        // `White_Space` class (NBSP / LINE SEPARATOR / EM-SPACE /
2505        // IDEOGRAPHIC SPACE) on the exemplar `:limits :memory` axis
2506        // — peer of the pre-existing `ser_byte_size_routes_through_
2507        // render_serialize_option_via_str_canonical` /
2508        // `de_byte_size_routes_through_render_deserialize_option_
2509        // via_str_canonical` pins on the sibling codec-hook axis.
2510        for (raw, byte) in [
2511            (" 64MiB", 0x20u8),
2512            ("64MiB ", 0x20u8),
2513            ("64 MiB", 0x20u8),
2514            ("\t64MiB", 0x09u8),
2515            ("64MiB\n", 0x0Au8),
2516        ] {
2517            let err = parse_byte_size(raw)
2518                .expect_err("ASCII-whitespace-carrying byte-size input must be rejected");
2519            let via_primitive = crate::render::reject_whitespace::<LimitsError, _, _>(
2520                raw,
2521                |b| LimitsError::WhitespaceInByteSize {
2522                    value: raw.into(),
2523                    byte: b,
2524                },
2525                |ch| LimitsError::NonAsciiWhitespaceInByteSize {
2526                    value: raw.into(),
2527                    ch,
2528                    codepoint: ch as u32,
2529                },
2530            )
2531            .expect_err("primitive must reject the same ASCII-whitespace shape");
2532            assert_eq!(
2533                err, via_primitive,
2534                "parse_byte_size drifted from crate::render::reject_whitespace \
2535                 on ASCII-whitespace input {raw:?}"
2536            );
2537            assert!(
2538                matches!(
2539                    err,
2540                    LimitsError::WhitespaceInByteSize { value: ref v, byte: b } if v == raw && b == byte
2541                ),
2542                "parse_byte_size must surface WhitespaceInByteSize {{ value: {raw:?}, byte: 0x{byte:02x} }}"
2543            );
2544        }
2545        for (raw, expected_ch) in [
2546            ("\u{00A0}64MiB", '\u{00A0}'),
2547            ("64\u{2003}MiB", '\u{2003}'),
2548            ("64MiB\u{2028}", '\u{2028}'),
2549            ("\u{3000}64MiB", '\u{3000}'),
2550        ] {
2551            let err = parse_byte_size(raw)
2552                .expect_err("non-ASCII-whitespace-carrying byte-size input must be rejected");
2553            let via_primitive = crate::render::reject_whitespace::<LimitsError, _, _>(
2554                raw,
2555                |b| LimitsError::WhitespaceInByteSize {
2556                    value: raw.into(),
2557                    byte: b,
2558                },
2559                |ch| LimitsError::NonAsciiWhitespaceInByteSize {
2560                    value: raw.into(),
2561                    ch,
2562                    codepoint: ch as u32,
2563                },
2564            )
2565            .expect_err("primitive must reject the same non-ASCII-whitespace shape");
2566            assert_eq!(
2567                err, via_primitive,
2568                "parse_byte_size drifted from crate::render::reject_whitespace \
2569                 on non-ASCII-whitespace input {raw:?}"
2570            );
2571            assert!(
2572                matches!(
2573                    err,
2574                    LimitsError::NonAsciiWhitespaceInByteSize { value: ref v, ch, codepoint }
2575                        if v == raw && ch == expected_ch && codepoint == expected_ch as u32
2576                ),
2577                "parse_byte_size must surface NonAsciiWhitespaceInByteSize \
2578                 {{ value: {raw:?}, ch: {expected_ch:?}, codepoint: {cp:#06X} }}",
2579                cp = expected_ch as u32
2580            );
2581        }
2582    }
2583
2584    #[test]
2585    fn limits_round_trip_through_json() {
2586        let limits = LimitsSpec {
2587            memory: Some(64 * 1024 * 1024),
2588            fuel: Some(1_000_000),
2589            wall_clock: Some(Duration::from_secs(30)),
2590            cpu: Some(500),
2591        };
2592        let json = serde_json::to_string(&limits).unwrap();
2593        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
2594        assert_eq!(limits, back);
2595    }
2596
2597    #[test]
2598    fn empty_limits_serialises_to_empty_object() {
2599        let limits = LimitsSpec::default();
2600        assert!(limits.is_empty());
2601        let json = serde_json::to_string(&limits).unwrap();
2602        assert_eq!(json, "{}");
2603    }
2604
2605    // ── drift-detection: serde-derive-to-M2_LIMITS_KEY_* identity ────────
2606
2607    #[test]
2608    fn limits_spec_serde_keys_match_lifted_m2_limits_key_consts() {
2609        // Load-bearing invariant: the four `M2_LIMITS_KEY_*` consts
2610        // (`M2_LIMITS_KEY_MEMORY` / `M2_LIMITS_KEY_FUEL` /
2611        // `M2_LIMITS_KEY_WALL_CLOCK` / `M2_LIMITS_KEY_CPU`) name the
2612        // exact camelCase JSON keys the `#[serde(rename_all = "camelCase")]`
2613        // attribute on `LimitsSpec` emits, and every test-side probe
2614        // across the caixa-core / caixa-flux / caixa-helm renderer test
2615        // fixtures navigates into the rendered `:limits` overlay
2616        // sub-block by consulting one of these four `&'static str`s.
2617        // Serialize a fully-populated LimitsSpec and pin that each
2618        // canonical byte-sequence appears verbatim in the JSON — a
2619        // future accidental `rename_all = "snake_case"` /
2620        // `"kebab-case"` / verbatim-field-name flip at the derive
2621        // attribute (any of which would silently break every test-side
2622        // probe that reaches for one of the four consts) surfaces here
2623        // as a build-time test failure at `limits.rs`, not as an
2624        // apply-time `.get(<stale-canonical-const>)` returning `None`
2625        // far from the derive-attr drift's commit. Same discipline the
2626        // sibling M3 `PlacementStrategy::as_str` lift (0a2f653)
2627        // established on the peer per-`:placement :estrategia` axis:
2628        // one canonical byte-string per typed sub-key axis, pinned to
2629        // the load-bearing serde derivation at the type itself.
2630        let limits = LimitsSpec {
2631            memory: Some(64 * 1024 * 1024),
2632            fuel: Some(1_000_000),
2633            wall_clock: Some(Duration::from_secs(30)),
2634            cpu: Some(500),
2635        };
2636        let json = serde_json::to_string(&limits).unwrap();
2637        for key in [
2638            crate::render::M2_LIMITS_KEY_MEMORY,
2639            crate::render::M2_LIMITS_KEY_FUEL,
2640            crate::render::M2_LIMITS_KEY_WALL_CLOCK,
2641            crate::render::M2_LIMITS_KEY_CPU,
2642        ] {
2643            let quoted = format!("\"{key}\"");
2644            assert!(
2645                json.contains(&quoted),
2646                "serialized LimitsSpec must carry the lifted \
2647                 M2_LIMITS_KEY_* byte-sequence {quoted} verbatim in \
2648                 the JSON emission (got: {json})",
2649            );
2650        }
2651    }
2652
2653    #[test]
2654    fn m2_limits_key_consts_are_pairwise_distinct() {
2655        // Cross-axis drift-detection pin: a future collapse of two
2656        // canonical sub-key byte-strings onto the same value (e.g. an
2657        // accidental copy-paste flip of `M2_LIMITS_KEY_CPU` to also
2658        // read `"memory"`) would silently reroute every test-side
2659        // probe on one axis onto the sibling axis's overlay entry and
2660        // pass every propagation-probe test that expected only the
2661        // stale axis's value. Peer of the sibling three-way distinct
2662        // pin on the `FLUX_GITREPOSITORY_REF_KEY_*` trio (7d40380).
2663        let all = [
2664            crate::render::M2_LIMITS_KEY_MEMORY,
2665            crate::render::M2_LIMITS_KEY_FUEL,
2666            crate::render::M2_LIMITS_KEY_WALL_CLOCK,
2667            crate::render::M2_LIMITS_KEY_CPU,
2668        ];
2669        for (i, a) in all.iter().enumerate() {
2670            for b in all.iter().skip(i + 1) {
2671                assert_ne!(
2672                    a, b,
2673                    "M2_LIMITS_KEY_* consts must be pairwise-distinct \
2674                     canonical byte-sequences — got `{a}` == `{b}`",
2675                );
2676            }
2677        }
2678    }
2679
2680    #[test]
2681    fn m2_limits_key_consts_are_lower_camel_case_shape() {
2682        // Shape-pin: every `M2_LIMITS_KEY_*` const must be a
2683        // lowerCamelCase byte-sequence (no `snake_case` underscores,
2684        // no `kebab-case` hyphens, no `PascalCase` leading capital, no
2685        // whitespace / colons / dots) — the canonical shape the
2686        // `#[serde(rename_all = "camelCase")]` derive produces on
2687        // `LimitsSpec`. A future flip to a non-camelCase attribute at
2688        // the derive surfaces both here (this test fails on the
2689        // stale-constant shape) and at
2690        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
2691        // (that test fails on the mismatch between const and derive).
2692        for key in [
2693            crate::render::M2_LIMITS_KEY_MEMORY,
2694            crate::render::M2_LIMITS_KEY_FUEL,
2695            crate::render::M2_LIMITS_KEY_WALL_CLOCK,
2696            crate::render::M2_LIMITS_KEY_CPU,
2697        ] {
2698            assert!(
2699                !key.is_empty(),
2700                "M2_LIMITS_KEY_* must be non-empty (got {key:?})"
2701            );
2702            let first = key.chars().next().unwrap();
2703            assert!(
2704                first.is_ascii_lowercase(),
2705                "M2_LIMITS_KEY_* must lead with an ASCII-lowercase byte \
2706                 (got {key:?}, leads with {first:?})",
2707            );
2708            assert!(
2709                key.chars().all(|c| c.is_ascii_alphanumeric()),
2710                "M2_LIMITS_KEY_* must be ASCII-alphanumeric only \
2711                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
2712            );
2713        }
2714    }
2715
2716    // ── value-shape: zero on any declared axis is rejected ────────────────
2717
2718    #[test]
2719    fn validate_accepts_default_unbounded_limits() {
2720        // Every axis None → "no bound declared" is the omit-the-slot
2721        // shape and stays valid. This is the pre-M2 default behaviour.
2722        LimitsSpec::default().validate().unwrap();
2723    }
2724
2725    #[test]
2726    fn validate_accepts_full_nonzero_limits() {
2727        let l = LimitsSpec {
2728            memory: Some(64 * 1024 * 1024),
2729            fuel: Some(1_000_000),
2730            wall_clock: Some(Duration::from_secs(30)),
2731            cpu: Some(500),
2732        };
2733        l.validate().unwrap();
2734    }
2735
2736    #[test]
2737    fn validate_rejects_zero_memory() {
2738        let l = LimitsSpec {
2739            memory: Some(0),
2740            ..Default::default()
2741        };
2742        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
2743    }
2744
2745    #[test]
2746    fn validate_rejects_zero_fuel() {
2747        let l = LimitsSpec {
2748            fuel: Some(0),
2749            ..Default::default()
2750        };
2751        assert_eq!(l.validate().unwrap_err(), LimitsError::FuelZero);
2752    }
2753
2754    #[test]
2755    fn validate_rejects_zero_wall_clock() {
2756        let l = LimitsSpec {
2757            wall_clock: Some(Duration::ZERO),
2758            ..Default::default()
2759        };
2760        assert_eq!(l.validate().unwrap_err(), LimitsError::WallClockZero);
2761    }
2762
2763    #[test]
2764    fn validate_rejects_zero_cpu() {
2765        let l = LimitsSpec {
2766            cpu: Some(0),
2767            ..Default::default()
2768        };
2769        assert_eq!(l.validate().unwrap_err(), LimitsError::CpuZero);
2770    }
2771
2772    #[test]
2773    fn validate_rejects_first_zero_axis_deterministically() {
2774        // Memory is checked first; with multiple zero axes, the
2775        // diagnostic names :memory rather than reporting some other
2776        // axis non-deterministically.
2777        let l = LimitsSpec {
2778            memory: Some(0),
2779            fuel: Some(0),
2780            wall_clock: Some(Duration::ZERO),
2781            cpu: Some(0),
2782        };
2783        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
2784    }
2785
2786    // ── value-shape: :memory upper bound — wasm32-wasip2 4 GiB ceiling ────
2787
2788    #[test]
2789    fn wasm32_memory_cap_matches_parsed_4_gib() {
2790        // The cap constant tracks the canonical "4 GiB" byte-size
2791        // codec output structurally — drift between the codec's
2792        // accepted magnitude for `"4GiB"` and the validate gate's
2793        // accepted upper bound would surface here, not as a silent
2794        // round-trip break at the renderer layer. Same single-source-
2795        // of-truth shape the is_canonical_rate_limit_window predicate
2796        // gives the rate-limit window set.
2797        assert_eq!(
2798            parse_byte_size("4GiB").unwrap(),
2799            LIMITS_MEMORY_WASM32_MAX_BYTES
2800        );
2801        assert_eq!(LIMITS_MEMORY_WASM32_MAX_BYTES, 4 * 1024 * 1024 * 1024);
2802        assert_eq!(LIMITS_MEMORY_WASM32_MAX_BYTES, 1u64 << 32);
2803    }
2804
2805    #[test]
2806    fn validate_accepts_memory_at_wasm32_cap() {
2807        // 4 GiB exactly is the wasm32 in-spec maximum — `2^16 pages ×
2808        // 2^16 bytes/page`. The validate gate is inclusive on the
2809        // upper end (mirrors the inclusive lower-end rejection: zero
2810        // is *out*, one is *in*; 4 GiB+1 is *out*, 4 GiB is *in*).
2811        let l = LimitsSpec {
2812            memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
2813            ..Default::default()
2814        };
2815        l.validate().unwrap();
2816    }
2817
2818    #[test]
2819    fn validate_rejects_memory_one_byte_above_wasm32_cap() {
2820        // Boundary case: exactly 1 byte past the cap. Catches a
2821        // future "strictly less than" half-measure and pins the
2822        // diagnostic to name the offending byte count verbatim.
2823        let bytes = LIMITS_MEMORY_WASM32_MAX_BYTES + 1;
2824        let l = LimitsSpec {
2825            memory: Some(bytes),
2826            ..Default::default()
2827        };
2828        assert_eq!(
2829            l.validate().unwrap_err(),
2830            LimitsError::MemoryExceedsWasm32Cap { bytes }
2831        );
2832    }
2833
2834    #[test]
2835    fn validate_rejects_memory_8_gib() {
2836        // The "obvious authoring footgun" case: a value the byte-size
2837        // codec accepts cleanly (`"8GiB"` → 8 * 1024^3 bytes) and
2838        // serde round-trips silently, but no wasm32 component can
2839        // honor. Until this gate landed `validate` accepted it.
2840        let bytes = parse_byte_size("8GiB").unwrap();
2841        let l = LimitsSpec {
2842            memory: Some(bytes),
2843            ..Default::default()
2844        };
2845        assert_eq!(
2846            l.validate().unwrap_err(),
2847            LimitsError::MemoryExceedsWasm32Cap { bytes }
2848        );
2849    }
2850
2851    #[test]
2852    fn validate_memory_zero_takes_precedence_over_cap_check() {
2853        // Memory zero is structurally meaningless under *any* wasm
2854        // engine (zero-cap traps the first allocation); above-cap is
2855        // wasm32-specific. The zero arm fires first so the canonical
2856        // "omit the slot for unbounded" remediation in the existing
2857        // MemoryZero diagnostic still leads — pinning this precedence
2858        // guards against a future re-ordering that would surface the
2859        // wasm32-specific message in the case where the simpler
2860        // zero-floor message is more actionable.
2861        let l = LimitsSpec {
2862            memory: Some(0),
2863            ..Default::default()
2864        };
2865        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
2866    }
2867
2868    #[test]
2869    fn validate_rejects_memory_cap_before_other_axes() {
2870        // With both an above-cap :memory and a zero :fuel, the
2871        // diagnostic names :memory rather than :fuel — peer of the
2872        // existing `validate_rejects_first_zero_axis_deterministically`
2873        // ordering pin.
2874        let bytes = LIMITS_MEMORY_WASM32_MAX_BYTES + 1024;
2875        let l = LimitsSpec {
2876            memory: Some(bytes),
2877            fuel: Some(0),
2878            wall_clock: Some(Duration::ZERO),
2879            cpu: Some(0),
2880        };
2881        assert_eq!(
2882            l.validate().unwrap_err(),
2883            LimitsError::MemoryExceedsWasm32Cap { bytes }
2884        );
2885    }
2886
2887    #[test]
2888    fn above_cap_value_still_round_trips_through_serde() {
2889        // The byte-size codec accepts the above-cap value (the cap
2890        // lives in the validate gate, not the codec). This pins that
2891        // the structural property is "above-cap is rejected by
2892        // validate" — not "above-cap is unparseable by the codec";
2893        // the latter would prevent the diagnostic from naming the
2894        // offending byte count at all, since deserialize would fail
2895        // first.
2896        let l = LimitsSpec {
2897            memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES + 1),
2898            ..Default::default()
2899        };
2900        let json = serde_json::to_string(&l).unwrap();
2901        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
2902        assert_eq!(l, back);
2903        assert!(back.validate().is_err());
2904    }
2905
2906    // ── value-shape: :memory lower bound — wasm32-wasip2 64 KiB page floor ─
2907
2908    #[test]
2909    fn wasm32_memory_page_matches_parsed_64_kib() {
2910        // The page-floor constant tracks the canonical "64 KiB"
2911        // byte-size codec output structurally — drift between the
2912        // codec's accepted magnitude for `"64KiB"` and the validate
2913        // gate's accepted lower bound would surface here, not as a
2914        // silent round-trip break at the renderer layer. Same single-
2915        // source-of-truth shape `wasm32_memory_cap_matches_parsed_4_gib`
2916        // pins on the peer upper-cap bound and
2917        // `is_canonical_rate_limit_window` gives the rate-limit window
2918        // set. The page-size identities (2^16, integer-divides the
2919        // upper cap exactly 2^16 times) are pinned alongside so a
2920        // future memory64-target opt-in raising one bound surfaces
2921        // here if the other bound's relationship to it drifts.
2922        assert_eq!(
2923            parse_byte_size("64KiB").unwrap(),
2924            LIMITS_MEMORY_WASM32_PAGE_BYTES
2925        );
2926        assert_eq!(LIMITS_MEMORY_WASM32_PAGE_BYTES, 64 * 1024);
2927        assert_eq!(LIMITS_MEMORY_WASM32_PAGE_BYTES, 1u64 << 16);
2928        assert_eq!(
2929            LIMITS_MEMORY_WASM32_MAX_BYTES / LIMITS_MEMORY_WASM32_PAGE_BYTES,
2930            1u64 << 16,
2931            "the wasm32 page count cap is 2^16 pages exactly",
2932        );
2933        assert_eq!(
2934            LIMITS_MEMORY_WASM32_MAX_BYTES % LIMITS_MEMORY_WASM32_PAGE_BYTES,
2935            0
2936        );
2937    }
2938
2939    #[test]
2940    fn validate_rejects_memory_below_wasm32_page() {
2941        // The fail-before-pass-after pin: until this gate landed a
2942        // `(:memory "32KiB")` (or any programmatic struct literal with
2943        // a sub-page byte count — `LimitsSpec { memory: Some(50000),
2944        // .. }`) silently passed validate, the byte-size codec
2945        // round-tripped cleanly through serde, and the wasm-engine
2946        // either refused instantiation (`memory minimum size of 1
2947        // pages exceeds memory limits` on any cdylib-shaped component
2948        // declaring `(memory 1)`) or trapped the first `memory.grow(1)`
2949        // far from the source caixa.lisp.
2950        let bytes = parse_byte_size("32KiB").unwrap();
2951        let l = LimitsSpec {
2952            memory: Some(bytes),
2953            ..Default::default()
2954        };
2955        assert_eq!(
2956            l.validate().unwrap_err(),
2957            LimitsError::MemoryBelowWasm32Page { bytes }
2958        );
2959    }
2960
2961    #[test]
2962    fn validate_rejects_memory_one_byte_below_page() {
2963        // Boundary case: exactly 1 byte below the page-size floor
2964        // (`LIMITS_MEMORY_WASM32_PAGE_BYTES - 1` = 65535 bytes). Pins
2965        // the inclusive-upper-end / strict-lower-end relationship on
2966        // the page-floor arm: 65535 is *out*, 65536 is *in*. Catches a
2967        // future "strictly greater than" half-measure and matches the
2968        // peer `validate_rejects_memory_one_byte_above_wasm32_cap`
2969        // shape on the top edge.
2970        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES - 1;
2971        let l = LimitsSpec {
2972            memory: Some(bytes),
2973            ..Default::default()
2974        };
2975        assert_eq!(
2976            l.validate().unwrap_err(),
2977            LimitsError::MemoryBelowWasm32Page { bytes }
2978        );
2979    }
2980
2981    #[test]
2982    fn validate_rejects_memory_one_byte() {
2983        // The far-floor case: a `(:memory "1")` cap is non-zero (so
2984        // `MemoryZero` doesn't fire) but structurally cannot hold any
2985        // wasm linear memory page. The page-floor gate at this layer
2986        // surfaces a self-locating diagnostic naming the offending
2987        // byte count verbatim rather than a downstream wasm-engine
2988        // instantiation failure whose error message points at the
2989        // engine's internals, not the caixa.lisp `:memory` slot.
2990        let l = LimitsSpec {
2991            memory: Some(1),
2992            ..Default::default()
2993        };
2994        assert_eq!(
2995            l.validate().unwrap_err(),
2996            LimitsError::MemoryBelowWasm32Page { bytes: 1 }
2997        );
2998    }
2999
3000    #[test]
3001    fn validate_accepts_memory_at_wasm32_page() {
3002        // 64 KiB exactly is the wasm32 linear-memory page size — the
3003        // smallest cap that admits one wasm `(memory 1)` page. The
3004        // page-floor gate is inclusive on the lower end (mirrors the
3005        // inclusive upper-end acceptance: 4 GiB is *in*, 4 GiB+1 is
3006        // *out*; 64 KiB is *in*, 64 KiB-1 is *out*).
3007        let l = LimitsSpec {
3008            memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
3009            ..Default::default()
3010        };
3011        l.validate().unwrap();
3012    }
3013
3014    #[test]
3015    fn validate_accepts_multi_page_memory() {
3016        // The positive-control sweep: every typed `:memory` cap that
3017        // admits at least one wasm linear memory page (i.e. ≥
3018        // `LIMITS_MEMORY_WASM32_PAGE_BYTES`) passes `validate`. Sweeps
3019        // single-page, two-page, the canonical 64 MiB / 1 GiB / 4 GiB
3020        // upper-bound boundary so a future tightening of either edge
3021        // surfaces here. Peer of
3022        // `validate_accepts_integer_millisecond_wall_clock_values` on
3023        // the sibling `:wall-clock` axis.
3024        for bytes in [
3025            LIMITS_MEMORY_WASM32_PAGE_BYTES,
3026            2 * LIMITS_MEMORY_WASM32_PAGE_BYTES,
3027            64 * 1024 * 1024,
3028            1024 * 1024 * 1024,
3029            LIMITS_MEMORY_WASM32_MAX_BYTES,
3030        ] {
3031            let l = LimitsSpec {
3032                memory: Some(bytes),
3033                ..Default::default()
3034            };
3035            l.validate()
3036                .unwrap_or_else(|e| panic!("multi-page {bytes} must validate, got {e:?}"));
3037        }
3038    }
3039
3040    #[test]
3041    fn validate_memory_zero_takes_precedence_over_page_floor() {
3042        // Cross-arm ordering pin: `Some(0)` would otherwise pass the
3043        // page-floor arm's `m < PAGE_BYTES` check (0 < 65536), but the
3044        // zero-floor arm strictly precedes the page-floor arm so the
3045        // more self-locating `MemoryZero` diagnostic (with its omit-
3046        // axis remediation directly named, applicable under *any* wasm
3047        // engine not just wasm32) leads. Same posture every peer
3048        // zero-then-shape gate uses on this surface
3049        // (`PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
3050        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`,
3051        // `WallClockZero` → `WallClockNotCanonical`).
3052        let l = LimitsSpec {
3053            memory: Some(0),
3054            ..Default::default()
3055        };
3056        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
3057    }
3058
3059    #[test]
3060    fn validate_memory_page_floor_takes_precedence_over_other_axes() {
3061        // With a sub-page `:memory` and zero values on every other
3062        // axis, the diagnostic names `:memory` rather than `:fuel` /
3063        // `:wall-clock` / `:cpu` — peer of the existing
3064        // `validate_rejects_first_zero_axis_deterministically` and
3065        // `validate_rejects_memory_cap_before_other_axes` ordering
3066        // pins. Memory is the first axis the validate cascade checks,
3067        // so a sub-page value surfaces before any other-axis
3068        // diagnostic regardless of how many other axes are
3069        // simultaneously invalid.
3070        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES / 2;
3071        let l = LimitsSpec {
3072            memory: Some(bytes),
3073            fuel: Some(0),
3074            wall_clock: Some(Duration::ZERO),
3075            cpu: Some(0),
3076        };
3077        assert_eq!(
3078            l.validate().unwrap_err(),
3079            LimitsError::MemoryBelowWasm32Page { bytes }
3080        );
3081    }
3082
3083    #[test]
3084    fn memory_page_floor_diagnostic_carries_offending_bytes() {
3085        // Diagnostic-shape pin: the page-floor arm names the
3086        // offending byte count verbatim so the author's grep lands on
3087        // the field's value, not a generic "memory too small" message.
3088        // Same shape every other typed-cap arm on this surface
3089        // carries (`MemoryExceedsWasm32Cap` carries the offending byte
3090        // count verbatim, `WallClockNotCanonical` carries the
3091        // offending `Duration` verbatim, `PolicyRetriesExceedsCap`
3092        // carries the offending retry count verbatim).
3093        let l = LimitsSpec {
3094            memory: Some(50_000),
3095            ..Default::default()
3096        };
3097        let err = l.validate().unwrap_err();
3098        let msg = err.to_string();
3099        assert!(
3100            msg.contains("50000"),
3101            "diagnostic must carry the offending byte count verbatim (got {msg:?})"
3102        );
3103        assert!(
3104            msg.contains("64 KiB") || msg.contains("65536"),
3105            "diagnostic must name the page-size floor (got {msg:?})"
3106        );
3107    }
3108
3109    #[test]
3110    fn below_page_value_still_round_trips_through_serde() {
3111        // The byte-size codec accepts the sub-page value (the floor
3112        // lives in the validate gate, not the codec) — peer of
3113        // `above_cap_value_still_round_trips_through_serde` on the top
3114        // edge. Pins that the structural property is "sub-page is
3115        // rejected by validate" — not "sub-page is unparseable by the
3116        // codec"; the latter would prevent the diagnostic from naming
3117        // the offending byte count at all, since deserialize would
3118        // fail first.
3119        let l = LimitsSpec {
3120            memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES - 1),
3121            ..Default::default()
3122        };
3123        let json = serde_json::to_string(&l).unwrap();
3124        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
3125        assert_eq!(l, back);
3126        assert!(back.validate().is_err());
3127    }
3128
3129    // ── value-shape: :memory page-multiple granularity gate ───────────────
3130
3131    #[test]
3132    fn validate_rejects_memory_one_byte_above_page() {
3133        // The fail-before-pass-after pin: until this gate landed a
3134        // `LimitsSpec { memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES +
3135        // 1), .. }` (65537 bytes — one wasm32 page plus a 1-byte
3136        // unreachable residue) silently passed validate, the byte-size
3137        // codec round-tripped cleanly through serde (`render_byte_size`
3138        // falls through to `"65537"` on any non-power-of-1024 magnitude),
3139        // and wasmtime's `StoreLimits::memory_size` consumed the value
3140        // verbatim as a page-quantized ceiling — the engine grew at
3141        // most floor(65537 / 65536) = 1 page, and the byte at offset
3142        // 65536 became structural dead space the runtime cannot honor.
3143        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
3144        let l = LimitsSpec {
3145            memory: Some(bytes),
3146            ..Default::default()
3147        };
3148        assert_eq!(
3149            l.validate().unwrap_err(),
3150            LimitsError::MemoryNotPageMultiple { bytes }
3151        );
3152    }
3153
3154    #[test]
3155    fn validate_rejects_memory_just_below_two_pages() {
3156        // Boundary case: exactly 1 byte below two pages (`2 *
3157        // LIMITS_MEMORY_WASM32_PAGE_BYTES - 1` = 131071 bytes). Pins
3158        // the inclusive-page-boundary / strict-sub-page-residue
3159        // relationship on the page-multiple arm: 131071 is *out*
3160        // (sub-page residue), 131072 is *in* (exactly two pages).
3161        // Matches the peer `validate_rejects_memory_one_byte_below_page`
3162        // / `validate_rejects_memory_one_byte_above_wasm32_cap` shape
3163        // on the surrounding edges.
3164        let bytes = 2 * LIMITS_MEMORY_WASM32_PAGE_BYTES - 1;
3165        let l = LimitsSpec {
3166            memory: Some(bytes),
3167            ..Default::default()
3168        };
3169        assert_eq!(
3170            l.validate().unwrap_err(),
3171            LimitsError::MemoryNotPageMultiple { bytes }
3172        );
3173    }
3174
3175    #[test]
3176    fn validate_rejects_memory_100000_bytes() {
3177        // The "obvious authoring footgun" case: a magnitude the
3178        // byte-size codec accepts cleanly (`"100000"` → 100000 bytes
3179        // ≈ 97.65 KiB) and serde round-trips silently, but no wasm32
3180        // engine can honor as a meaningful ceiling — the engine grows
3181        // at most floor(100000 / 65536) = 1 page, and the 34464 bytes
3182        // between offsets 65536 and 100000 are structural dead space.
3183        // Until this gate landed `validate` accepted it. Peer of
3184        // `validate_rejects_memory_8_gib` on the cap arm.
3185        let bytes = parse_byte_size("100000").unwrap();
3186        let l = LimitsSpec {
3187            memory: Some(bytes),
3188            ..Default::default()
3189        };
3190        assert_eq!(
3191            l.validate().unwrap_err(),
3192            LimitsError::MemoryNotPageMultiple { bytes }
3193        );
3194    }
3195
3196    #[test]
3197    fn validate_accepts_every_page_aligned_value_through_serde() {
3198        // Positive-control sweep through the byte-size codec: every
3199        // canonical magnitude `render_byte_size` emits at or above
3200        // the page floor divides cleanly by the page size, so the
3201        // page-multiple gate accepts the entire canonical-output
3202        // domain at and above the page floor. The sweep walks
3203        // single-page (`"64KiB"`), two-page (`"128KiB"`), every
3204        // power-of-1024 unit (`"1MiB"`, `"64MiB"`, `"1GiB"`, `"4GiB"`),
3205        // and the cap (`"4GiB"`) — pinning that the codec's
3206        // emitted-canonical-form set is a structural subset of the
3207        // validate gate's accepted set. Drift between the codec's
3208        // emit alphabet and the validate gate would surface here
3209        // rather than at a future serializer round trip.
3210        for s in ["64KiB", "128KiB", "1MiB", "64MiB", "1GiB", "4GiB"] {
3211            let bytes = parse_byte_size(s).unwrap();
3212            assert_eq!(
3213                bytes % LIMITS_MEMORY_WASM32_PAGE_BYTES,
3214                0,
3215                "canonical byte-size codec output {s:?} ({bytes}) must be page-aligned",
3216            );
3217            let l = LimitsSpec {
3218                memory: Some(bytes),
3219                ..Default::default()
3220            };
3221            l.validate()
3222                .unwrap_or_else(|e| panic!("canonical {s:?} = {bytes} must validate, got {e:?}"));
3223        }
3224    }
3225
3226    #[test]
3227    fn validate_memory_below_page_takes_precedence_over_page_multiple() {
3228        // Cross-arm ordering pin: `Some(1)` would otherwise pass the
3229        // page-multiple arm's `m % PAGE_BYTES != 0` check (1 % 65536
3230        // == 1 ≠ 0), but the page-floor arm strictly precedes the
3231        // page-multiple arm so the more self-locating
3232        // `MemoryBelowWasm32Page` diagnostic (with its "single page
3233        // cannot fit" remediation, applicable to every sub-page
3234        // value uniformly) leads. Peer of `MemoryZero` →
3235        // `MemoryBelowWasm32Page` precedence on the zero edge:
3236        // every value `m` in the range `1..=PAGE_BYTES-1` satisfies
3237        // both `m < PAGE_BYTES` and `m % PAGE_BYTES != 0`, but the
3238        // structurally-narrower diagnostic (page-floor) leads.
3239        let l = LimitsSpec {
3240            memory: Some(1),
3241            ..Default::default()
3242        };
3243        assert_eq!(
3244            l.validate().unwrap_err(),
3245            LimitsError::MemoryBelowWasm32Page { bytes: 1 }
3246        );
3247    }
3248
3249    #[test]
3250    fn validate_memory_cap_takes_precedence_over_page_multiple() {
3251        // Cross-arm ordering pin: `LIMITS_MEMORY_WASM32_MAX_BYTES + 1`
3252        // (4 GiB + 1 byte) is *both* above-cap and not page-aligned.
3253        // The cap arm strictly precedes the page-multiple arm so the
3254        // more aggressive cap-shape diagnostic leads (the page-multiple
3255        // remediation would be misleading when the offending value
3256        // exceeds the wasm32 address-space ceiling anyway — the
3257        // canonical fix collapses both into "pin a page-aligned value
3258        // ≤ 4 GiB"). Peer of `WallClockNotCanonical` →
3259        // `WallClockExceedsCap` ordering on the sibling `:wall-clock`
3260        // axis (with the inverse polarity — there the granularity
3261        // gate leads because sub-millisecond residue breaks serde
3262        // round-trip; here the cap leads because both gates' offending
3263        // values round-trip cleanly through serde and the broader
3264        // magnitude constraint is the more aggressive one).
3265        let bytes = LIMITS_MEMORY_WASM32_MAX_BYTES + 1;
3266        let l = LimitsSpec {
3267            memory: Some(bytes),
3268            ..Default::default()
3269        };
3270        assert_eq!(
3271            l.validate().unwrap_err(),
3272            LimitsError::MemoryExceedsWasm32Cap { bytes }
3273        );
3274    }
3275
3276    #[test]
3277    fn validate_rejects_memory_page_multiple_before_other_axes() {
3278        // With a sub-page-residue `:memory` and zero values on every
3279        // other axis, the diagnostic names `:memory` rather than
3280        // `:fuel` / `:wall-clock` / `:cpu` — peer of the existing
3281        // `validate_memory_page_floor_takes_precedence_over_other_axes`
3282        // and `validate_rejects_memory_cap_before_other_axes` ordering
3283        // pins. Memory is the first axis the validate cascade checks,
3284        // so a sub-page-residue value surfaces before any other-axis
3285        // diagnostic regardless of how many other axes are
3286        // simultaneously invalid.
3287        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
3288        let l = LimitsSpec {
3289            memory: Some(bytes),
3290            fuel: Some(0),
3291            wall_clock: Some(Duration::ZERO),
3292            cpu: Some(0),
3293        };
3294        assert_eq!(
3295            l.validate().unwrap_err(),
3296            LimitsError::MemoryNotPageMultiple { bytes }
3297        );
3298    }
3299
3300    #[test]
3301    fn memory_page_multiple_diagnostic_carries_offending_bytes() {
3302        // Diagnostic-shape pin: the page-multiple arm names the
3303        // offending byte count verbatim so the author's grep lands on
3304        // the field's value, not a generic "memory not aligned"
3305        // message. Same shape every other typed-cap arm on this
3306        // surface carries (`MemoryExceedsWasm32Cap` carries the
3307        // offending byte count verbatim, `WallClockNotCanonical`
3308        // carries the offending `Duration` verbatim).
3309        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 12345;
3310        let l = LimitsSpec {
3311            memory: Some(bytes),
3312            ..Default::default()
3313        };
3314        let err = l.validate().unwrap_err();
3315        let msg = err.to_string();
3316        assert!(
3317            msg.contains(&bytes.to_string()),
3318            "diagnostic must carry the offending byte count verbatim (got {msg:?})"
3319        );
3320        assert!(
3321            msg.contains("64 KiB") || msg.contains("65536") || msg.contains("page"),
3322            "diagnostic must name the page-size granularity (got {msg:?})"
3323        );
3324    }
3325
3326    #[test]
3327    fn sub_page_residue_value_still_round_trips_through_serde() {
3328        // The byte-size codec accepts the sub-page-residue value (the
3329        // page-multiple gate lives in validate, not in the codec) —
3330        // peer of `above_cap_value_still_round_trips_through_serde`
3331        // and `below_page_value_still_round_trips_through_serde`.
3332        // Pins that the structural property is "sub-page-residue is
3333        // rejected by validate" — not "sub-page-residue is
3334        // unparseable by the codec"; the latter would prevent the
3335        // diagnostic from naming the offending byte count at all,
3336        // since deserialize would fail first. The render-then-parse
3337        // round trip also pins the codec's flow-through-to-bytes
3338        // shape on non-power-of-1024 magnitudes: `render_byte_size`
3339        // falls through every `(mult, label)` arm whose `n % mult !=
3340        // 0` and emits the bare byte count.
3341        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
3342        let l = LimitsSpec {
3343            memory: Some(bytes),
3344            ..Default::default()
3345        };
3346        let json = serde_json::to_string(&l).unwrap();
3347        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
3348        assert_eq!(l, back);
3349        assert!(back.validate().is_err());
3350    }
3351
3352    #[test]
3353    fn validate_memory_axis_routes_through_quantum_multiple_bounded_helper() {
3354        // Byte-parity pin on the pre-lift `if self.memory() == Some(0)
3355        // { … } if let Some(m) = self.memory() { if m <
3356        // LIMITS_MEMORY_WASM32_PAGE_BYTES { … } } if let Some(m) =
3357        // self.memory() { if m > LIMITS_MEMORY_WASM32_MAX_BYTES { … } }
3358        // if let Some(m) = self.memory() && m %
3359        // LIMITS_MEMORY_WASM32_PAGE_BYTES != 0 { … }` four-sequential-
3360        // `if let` shape the `LimitsSpec::validate` `:memory` axis
3361        // routed through today via
3362        // `crate::render::require_positive_quantum_multiple_bounded_u64`.
3363        // Refuses a future accidental split between the helper's
3364        // four-arm ordering (zero → below-quantum → cap → not-multiple)
3365        // and the four typed `LimitsError::Memory*` variants each arm
3366        // threads its offending byte count into — a swap of any two
3367        // arms in the helper, or a partial widening (e.g. removing the
3368        // page-multiple arm), or a widening of the `on_below_quantum`
3369        // arm's closure to the `MemoryExceedsWasm32Cap` variant instead
3370        // of `MemoryBelowWasm32Page` — would break exactly one row of
3371        // this pin, matching the pre-lift shape the four consumer sites
3372        // route through today. Same shape as
3373        // `as_seq_body_partitions_the_same_arm_set_as_seq_delims` in
3374        // caixa-ast and the peer `require_positive_bounded_u64` tests
3375        // in the sibling render.rs test module.
3376        //
3377        // (Some(bytes) → expected LimitsError)
3378        let quantum = LIMITS_MEMORY_WASM32_PAGE_BYTES;
3379        let cap = LIMITS_MEMORY_WASM32_MAX_BYTES;
3380        let cases: &[(u64, LimitsError)] = &[
3381            (0, LimitsError::MemoryZero),
3382            (1, LimitsError::MemoryBelowWasm32Page { bytes: 1 }),
3383            (
3384                quantum - 1,
3385                LimitsError::MemoryBelowWasm32Page { bytes: quantum - 1 },
3386            ),
3387            (
3388                cap + 1,
3389                LimitsError::MemoryExceedsWasm32Cap { bytes: cap + 1 },
3390            ),
3391            (
3392                cap + quantum,
3393                LimitsError::MemoryExceedsWasm32Cap {
3394                    bytes: cap + quantum,
3395                },
3396            ),
3397            (
3398                quantum + 1,
3399                LimitsError::MemoryNotPageMultiple { bytes: quantum + 1 },
3400            ),
3401            (
3402                quantum + 12_345,
3403                LimitsError::MemoryNotPageMultiple {
3404                    bytes: quantum + 12_345,
3405                },
3406            ),
3407        ];
3408        for (bytes, expected) in cases {
3409            let l = LimitsSpec {
3410                memory: Some(*bytes),
3411                ..Default::default()
3412            };
3413            assert_eq!(
3414                l.validate().unwrap_err(),
3415                *expected,
3416                "memory={bytes} must surface the {expected:?} arm via the substrate helper",
3417            );
3418        }
3419        // Positive-control: every quantum-multiple in `quantum..=cap`
3420        // passes, closing the four-arm cascade with an `Ok(())` shape.
3421        for bytes in [quantum, quantum * 2, quantum * 100, cap] {
3422            let l = LimitsSpec {
3423                memory: Some(bytes),
3424                ..Default::default()
3425            };
3426            l.validate().unwrap();
3427        }
3428    }
3429
3430    // ── canonical-form: integer-magnitude byte-size codec gate ────────────
3431    //
3432    // Every magnitude `render_byte_size` emits is a non-negative integer
3433    // (no decimal point, no leading sign, no scientific notation). The
3434    // parser's accepted set must match for parse → render → parse to
3435    // round-trip without canonical-form drift. The tests below pin every
3436    // canonical-drift shape — fractional (`"1.5KiB"`), decimal-shaped-
3437    // integer (`"1.0MiB"`), half-unit (`"0.5GiB"`), leading-`+`
3438    // (`"+1024"`) — plus the scientific-notation dispatch path (caught
3439    // by `UnknownByteUnit` on a different arm), the two complement-side
3440    // pins (the integer happy paths the gate must continue to accept),
3441    // the round-trip convergence property (parse → render → parse must
3442    // converge on a single canonical form for every accepted input),
3443    // the BadByteMagnitude-precedence pin (genuinely unparseable inputs
3444    // keep their narrower diagnostic), the overflow-surface pin
3445    // (u64-overflow on magnitude × unit surfaces at parse time), and
3446    // the serde-path pin (the gate fires at deserialize, before any
3447    // validate gate runs).
3448
3449    #[test]
3450    fn parse_byte_size_rejects_fractional_kib() {
3451        // The fail-before-pass-after pin: `"1.5KiB"` parsed cleanly on
3452        // every pre-gate codebase (f64::parse accepts the decimal), the
3453        // codec produced 1536 bytes, and `render_byte_size(1536)`
3454        // emitted `"1536"` on the next serialize — silently drifting
3455        // the canonical form away from the author's intent. The new
3456        // gate surfaces the round-trip break at the parser layer with
3457        // a self-locating diagnostic (the offending magnitude verbatim,
3458        // the canonical-form remediation in the wording).
3459        let err = parse_byte_size("1.5KiB").unwrap_err();
3460        assert!(
3461            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "1.5"),
3462            "got {err:?}"
3463        );
3464    }
3465
3466    #[test]
3467    fn parse_byte_size_rejects_decimal_shaped_integer() {
3468        // The canonical-drift case where the *value* is integer but
3469        // the *form* carries a redundant decimal point — `"1.0MiB"`
3470        // parses to 1 MiB (integer), but the renderer emits `"1MiB"`
3471        // on the next serialize (no decimal point). The parse-shape
3472        // gate fires here too so the codec's accepted set is exactly
3473        // the renderer's emitted set — no `"1.0MiB"` ↔ `"1MiB"` drift
3474        // surviving a round-trip silently.
3475        let err = parse_byte_size("1.0MiB").unwrap_err();
3476        assert!(
3477            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "1.0"),
3478            "got {err:?}"
3479        );
3480    }
3481
3482    #[test]
3483    fn parse_byte_size_rejects_half_gib() {
3484        // `"0.5GiB"` parses to 536870912 bytes = 512MiB; the renderer
3485        // emits `"512MiB"` on the next serialize. Pin the round-trip
3486        // drift on the explicitly-fractional case sized to land on a
3487        // unit boundary, so the gate's coverage includes both the
3488        // "doesn't land on a boundary" (1.5KiB → 1536) and "lands on
3489        // a smaller-unit boundary" (0.5GiB → 512MiB) drift shapes.
3490        let err = parse_byte_size("0.5GiB").unwrap_err();
3491        assert!(
3492            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "0.5"),
3493            "got {err:?}"
3494        );
3495    }
3496
3497    #[test]
3498    fn parse_byte_size_rejects_scientific_notation_via_unit_arm() {
3499        // Scientific-notation magnitudes are canonical-form drift too
3500        // — the renderer never emits `"1e3KiB"` for any value. But
3501        // they're caught on a *different* arm than the fractional /
3502        // leading-`+` shapes: the parser's split-on-first-alphabetic-
3503        // byte heuristic reads the `e` as a unit prefix, so the input
3504        // falls into the existing `UnknownByteUnit { unit: "e3KiB" }`
3505        // diagnostic before the `NonIntegerByteMagnitude` gate is
3506        // consulted. Pin this dispatch path so a future relaxation of
3507        // the split heuristic (e.g. recognizing `e` as part of a
3508        // scientific-notation magnitude) surfaces here as a test
3509        // failure — at which point the `NonIntegerByteMagnitude` gate
3510        // would correctly take over, and this test would flip to that
3511        // arm with no other change required.
3512        let err = parse_byte_size("1e3KiB").unwrap_err();
3513        assert!(
3514            matches!(err, LimitsError::UnknownByteUnit { ref unit } if unit == "e3KiB"),
3515            "got {err:?}"
3516        );
3517    }
3518
3519    #[test]
3520    fn parse_byte_size_rejects_leading_plus() {
3521        // `"+1024"` parses through f64 as 1024 bytes; the renderer
3522        // emits `"1KiB"` on the next serialize. The leading `+` is
3523        // not a renderer-emitted shape, so it falls in the same
3524        // canonical-drift class as the fractional / scientific forms
3525        // — surfacing under the same diagnostic keeps the gate's
3526        // coverage uniform across every non-canonical-but-numeric
3527        // input shape the parser would otherwise accept.
3528        let err = parse_byte_size("+1024").unwrap_err();
3529        assert!(
3530            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "+1024"),
3531            "got {err:?}"
3532        );
3533    }
3534
3535    #[test]
3536    fn parse_byte_size_continues_to_accept_integer_magnitudes() {
3537        // The complement-side pin: every canonical integer-magnitude
3538        // form the renderer emits must continue to parse to the same
3539        // value the renderer produced. Sweep the five canonical
3540        // authoring shapes (unitless integer, KiB, MiB, GiB, KB) so a
3541        // future tightening of the parser surfaces here as a test
3542        // failure rather than a silent regression in the canonical
3543        // authoring set.
3544        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
3545        assert_eq!(parse_byte_size("1KiB").unwrap(), 1024);
3546        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
3547        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
3548        assert_eq!(parse_byte_size("1000KB").unwrap(), 1_000_000);
3549    }
3550
3551    #[test]
3552    fn parse_byte_size_round_trips_through_render_for_every_canonical_form() {
3553        // The structural property the gate makes load-bearing: every
3554        // value the parser accepts round-trips through `render_byte_size`
3555        // to a string the parser also accepts — and to the *same* value.
3556        // Sweep the values the renderer emits canonically (1024 / 1MiB
3557        // / 1GiB / 1536 / 64MiB) so a future codec change that breaks
3558        // round-trip convergence surfaces here, not at a downstream
3559        // renderer that double-emits a typed slot.
3560        for n in [1u64, 1023, 1024, 1536, 64 * 1024 * 1024, 1024 * 1024 * 1024] {
3561            let rendered = render_byte_size(n);
3562            let reparsed = parse_byte_size(&rendered)
3563                .unwrap_or_else(|e| panic!("render({n}) = {rendered:?} must reparse, got {e:?}"));
3564            assert_eq!(
3565                reparsed, n,
3566                "round-trip drift on {n}: rendered={rendered:?}, reparsed={reparsed}",
3567            );
3568        }
3569    }
3570
3571    #[test]
3572    fn parse_byte_size_keeps_bad_magnitude_for_unparseable_input() {
3573        // The precedence pin: the new `NonIntegerByteMagnitude` arm
3574        // distinguishes *non-canonical-but-numeric* (`"1.5"`, `"1.0"`,
3575        // `"+1024"`, `"-1"`) from *genuinely-unparseable* (`"abc"`,
3576        // `"--1"`) so the existing `BadByteMagnitude` diagnostic's
3577        // wording remains load-bearing for the latter class — the gate
3578        // is additive, not replacing. Pin both arms so a future
3579        // relaxation that collapses them surfaces here.
3580        let err = parse_byte_size("abc").unwrap_err();
3581        assert!(
3582            matches!(err, LimitsError::BadByteMagnitude(_)),
3583            "got {err:?}"
3584        );
3585        let err = parse_byte_size("--1").unwrap_err();
3586        assert!(
3587            matches!(err, LimitsError::BadByteMagnitude(_)),
3588            "got {err:?}"
3589        );
3590    }
3591
3592    #[test]
3593    fn parse_byte_size_overflow_surfaces_as_bad_magnitude() {
3594        // `u64::MAX KiB` overflows the u64 result; the parser surfaces
3595        // the overflow as a `BadByteMagnitude` (not as a saturated
3596        // `u64::MAX` value that the wasm32-cap validate gate then
3597        // catches), so the diagnostic names the offending magnitude ×
3598        // unit pair at parse time rather than as
3599        // `MemoryExceedsWasm32Cap { bytes: u64::MAX }` far from the
3600        // author's intent. (`u64::MAX` itself parses cleanly with no
3601        // unit since `u64::MAX × 1 = u64::MAX` fits.)
3602        let err = parse_byte_size("18446744073709551615KiB").unwrap_err();
3603        let LimitsError::BadByteMagnitude(reason) = err else {
3604            panic!("expected BadByteMagnitude(overflow), got other variant");
3605        };
3606        assert!(
3607            reason.contains("overflow"),
3608            "overflow diagnostic must mention overflow (got {reason:?})"
3609        );
3610    }
3611
3612    // ── canonical-form: leading-zero byte-size codec gate ─────────────────
3613    //
3614    // Direct successor to the `parse_duration` leading-zero arm (39762d7),
3615    // the `supervisor::duration_codec` leading-zero arm (9178904), and the
3616    // `rate_limit_codec` leading-zero arm (4f46830) — the same canonical-
3617    // form render-determinism axis applied to the last typed-numeric codec
3618    // that still admitted leading-zero magnitudes. The digit-only gate
3619    // immediately above accepts every `u64::from_str`-parseable magnitude
3620    // including leading-zero padding, but `render_byte_size` always emits
3621    // the stripped form (`64MiB`, never `064MiB`) — silently drifting the
3622    // canonical string across a parse/render round-trip. Pins each
3623    // canonical leading-zero shape across the unit-set the codec admits
3624    // (KB / MB / GB / KiB / MiB / GiB / bare-integer), the all-zero
3625    // degenerate case, the codec-vs-validate-layer partition (single-byte
3626    // `"0"` stays accepted at the codec because the typed-validate gate
3627    // `MemoryZero` refuses semantic-zero authoring), the complement-side
3628    // pin (`1`..=`9`-led magnitudes stay accepted), and the serde-path pin
3629    // (the gate fires at deserialize, before any validate gate runs).
3630
3631    #[test]
3632    fn parse_byte_size_rejects_leading_zero_magnitude() {
3633        // The fail-before-pass-after pin: `"064MiB"` parsed cleanly on
3634        // every pre-gate codebase (`u64::from_str` accepts the leading
3635        // zero), the codec produced 64 MiB, and
3636        // `render_byte_size(64*1024*1024)` emitted `"64MiB"` on the next
3637        // serialize — silently dropping the leading zero and drifting
3638        // the canonical form away from the author's intent. The new
3639        // gate surfaces the round-trip break at the parser layer with a
3640        // self-locating diagnostic, peer with
3641        // `parse_duration_rejects_leading_zero_magnitude` on the sibling
3642        // codec.
3643        let err = parse_byte_size("064MiB").unwrap_err();
3644        assert!(
3645            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "064"),
3646            "got {err:?}"
3647        );
3648    }
3649
3650    #[test]
3651    fn parse_byte_size_rejects_multi_digit_zero_magnitude() {
3652        // `"00MiB"` is the degenerate leading-zero case — every byte is
3653        // `0`. `u64::from_str("00")` = 0, and the codec produces 0;
3654        // `render_byte_size(0)` emits `"0"` on the next serialize —
3655        // drift from `"00MiB"` to `"0"`. The leading-zero arm refuses
3656        // the drift class at the codec layer while leaving the
3657        // canonical single-byte `"0"` accepted. Peer with
3658        // `parse_duration_rejects_multi_digit_zero_magnitude` on the
3659        // sibling codec.
3660        let err = parse_byte_size("00MiB").unwrap_err();
3661        assert!(
3662            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "00"),
3663            "got {err:?}"
3664        );
3665    }
3666
3667    #[test]
3668    fn parse_byte_size_rejects_leading_zero_in_gib_unit() {
3669        // `"01GiB"` parses to 1 GiB; the renderer emits `"1GiB"` on the
3670        // next serialize. The leading-zero class is a property of the
3671        // magnitude, not the unit — pin a per-GiB magnitude alongside
3672        // the per-MiB / per-KiB / bare-integer pins so the gate's
3673        // coverage is structural across every canonical unit suffix
3674        // the codec accepts. Mirrors the per-hour pin
3675        // `parse_duration_rejects_leading_zero_in_hour_window` carries
3676        // on the sibling codec.
3677        let err = parse_byte_size("01GiB").unwrap_err();
3678        assert!(
3679            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "01"),
3680            "got {err:?}"
3681        );
3682    }
3683
3684    #[test]
3685    fn parse_byte_size_rejects_leading_zero_in_kib_unit() {
3686        // `"0512KiB"` parses to 512 KiB; the renderer emits `"512KiB"`
3687        // on the next serialize. Pin the per-KiB magnitude alongside
3688        // the per-MiB / per-GiB pins so the gate's coverage extends to
3689        // the smallest-unit power-of-1024 suffix the codec admits.
3690        let err = parse_byte_size("0512KiB").unwrap_err();
3691        assert!(
3692            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "0512"),
3693            "got {err:?}"
3694        );
3695    }
3696
3697    #[test]
3698    fn parse_byte_size_rejects_leading_zero_in_decimal_units() {
3699        // `"0500MB"` parses to 500 MB (decimal-unit family — `KB` /
3700        // `MB` / `GB` powers of 1000, distinct from the `KiB` / `MiB` /
3701        // `GiB` powers-of-1024 family); the renderer emits the
3702        // appropriate canonical form on the next serialize. Pin the
3703        // decimal-unit family alongside the power-of-1024 family so the
3704        // gate's coverage is structural across both unit families the
3705        // codec admits.
3706        for (s, expected) in [("0500MB", "0500"), ("01KB", "01"), ("00GB", "00")] {
3707            let err = parse_byte_size(s).unwrap_err();
3708            assert!(
3709                matches!(err, LimitsError::LeadingZeroByteMagnitude { value: ref v } if v == expected),
3710                "got {err:?} for {s:?}"
3711            );
3712        }
3713    }
3714
3715    #[test]
3716    fn parse_byte_size_rejects_leading_zero_bare_integer() {
3717        // The bare-integer (no unit) shorthand inherits the leading-
3718        // zero arm: `"01024"` parses losslessly to 1024 bytes but
3719        // `render_byte_size(1024)` emits `"1KiB"` on the next serialize.
3720        // Pin the bare-integer path so a future relaxation that
3721        // special-cases the unitless shorthand surfaces here as a test
3722        // failure. Mirrors the bare-integer pin
3723        // `parse_duration_rejects_leading_zero_bare_integer_as_seconds`
3724        // carries on the sibling codec.
3725        let err = parse_byte_size("01024").unwrap_err();
3726        assert!(
3727            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "01024"),
3728            "got {err:?}"
3729        );
3730    }
3731
3732    #[test]
3733    fn parse_byte_size_accepts_single_zero_magnitude_at_codec_layer() {
3734        // The codec-layer / typed-validate-layer boundary pin: the
3735        // single-byte `"0"` magnitude round-trips losslessly through
3736        // `render_byte_size` (`render_byte_size(0)` emits `"0"`), so it
3737        // stays accepted at this codec layer across every canonical
3738        // unit suffix. The downstream `LimitsError::MemoryZero` gate is
3739        // what refuses zero-magnitude authoring at the typed-validate
3740        // layer above — the partition keeps the canonical-form-drift
3741        // diagnostic (this arm) and the semantic-zero diagnostic (the
3742        // validate gate) disjoint. Mirrors the
3743        // `parse_duration_accepts_single_zero_magnitude_at_codec_layer`
3744        // partition pin on the sibling codec.
3745        assert_eq!(parse_byte_size("0").unwrap(), 0);
3746        assert_eq!(parse_byte_size("0B").unwrap(), 0);
3747        assert_eq!(parse_byte_size("0KiB").unwrap(), 0);
3748        assert_eq!(parse_byte_size("0MiB").unwrap(), 0);
3749        assert_eq!(parse_byte_size("0GiB").unwrap(), 0);
3750        assert_eq!(parse_byte_size("0KB").unwrap(), 0);
3751    }
3752
3753    #[test]
3754    fn parse_byte_size_accepts_canonical_magnitude_with_leading_one() {
3755        // The complement-side pin on the leading-zero arm: magnitudes
3756        // beginning with `1`..=`9` stay accepted across every canonical
3757        // unit suffix the codec accepts. Pin this so a future
3758        // tightening cannot drift into rejecting valid canonical
3759        // magnitudes — peer with the
3760        // `parse_duration_accepts_canonical_magnitude_with_leading_one`
3761        // pin on the sibling codec.
3762        assert_eq!(parse_byte_size("1").unwrap(), 1);
3763        assert_eq!(parse_byte_size("1KiB").unwrap(), 1024);
3764        assert_eq!(parse_byte_size("1MiB").unwrap(), 1024 * 1024);
3765        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
3766        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
3767        assert_eq!(parse_byte_size("9").unwrap(), 9);
3768    }
3769
3770    #[test]
3771    fn de_byte_size_rejects_leading_zero_through_serde() {
3772        // The serde-path pin: a `:limits :memory` carrying a
3773        // leading-zero magnitude (`"064MiB"`) must fail at deserialize
3774        // time, not silently round-trip the value through the parser.
3775        // The gate fires at deserialize, before any validate gate runs
3776        // — peer with `de_duration_rejects_leading_zero_through_serde`
3777        // on the sibling codec.
3778        let json = r#"{"memory":"064MiB"}"#;
3779        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
3780        let msg = err.to_string();
3781        assert!(
3782            msg.contains("leading zero"),
3783            "serde diagnostic must surface the leading-zero reason verbatim (got {msg:?})"
3784        );
3785    }
3786
3787    // ── canonical-form: whitespace-rejection byte-size codec gate ─────────
3788    //
3789    // Direct successor to the `parse_duration` whitespace-rejection arm
3790    // (ebc3a75), the `supervisor::duration_codec` whitespace-rejection
3791    // arm (a7ae622), and the `rate_limit_codec` whitespace-rejection arm
3792    // (1ad7755) on the same canonical-form render-determinism axis. The
3793    // pre-gate top-level `s.trim()` at parse entry and the per-part
3794    // `num_part.trim()` / `unit.trim()` calls silently ate leading /
3795    // trailing / internal whitespace, so every whitespace-carrying
3796    // shape parsed to the same byte magnitude and round-tripped through
3797    // `render_byte_size` to a *different* canonical string on next
3798    // serialize — the same canonical-form-drift class the leading-`+` /
3799    // fractional / leading-zero arms already close on this codec.
3800    // `u8::is_ascii_whitespace` covers the five WhatWG-conformant ASCII
3801    // whitespace bytes (space `0x20`, tab `0x09`, LF `0x0A`, FF `0x0C`,
3802    // CR `0x0D`). Closes the whitespace-rejection axis across every
3803    // typed-magnitude codec in caixa-core.
3804
3805    #[test]
3806    fn parse_byte_size_rejects_leading_whitespace() {
3807        // The fail-before-pass-after pin: `" 64MiB"` — the canonical
3808        // paste-from-aligned-doc / paste-from-YAML-quoted-plain-scalar
3809        // footgun. Before this gate the top-level `s.trim()` at parse
3810        // entry silently ate the leading space and parsed the value to
3811        // 64 * 1024 * 1024 bytes, which then round-tripped through
3812        // `render_byte_size` to `"64MiB"` (a *different* canonical
3813        // string on the next emit) — the exact canonical-form-drift
3814        // class the leading-`+` / leading-zero arms already close,
3815        // extended to the whitespace-byte class. Peer with the sibling
3816        // `parse_duration_rejects_leading_whitespace` arm (ebc3a75) on
3817        // the shared canonical-form-drift trajectory.
3818        let err = parse_byte_size(" 64MiB").unwrap_err();
3819        assert!(
3820            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == " 64MiB" && byte == 0x20),
3821            "got {err:?}"
3822        );
3823        let msg = err.to_string();
3824        assert!(
3825            msg.contains("whitespace byte 0x20"),
3826            "diagnostic must surface the offending byte verbatim (got {msg:?})"
3827        );
3828        assert!(
3829            msg.contains("THEORY.md"),
3830            "diagnostic must cite the render-determinism contract (got {msg:?})"
3831        );
3832    }
3833
3834    #[test]
3835    fn parse_byte_size_rejects_trailing_whitespace() {
3836        // `"64MiB "` — the canonical shell-history / trailing-space
3837        // paste footgun. Before this gate the top-level `s.trim()`
3838        // silently ate the trailing space and parsed to 64 * 1024 *
3839        // 1024 bytes, round-tripping to `"64MiB"` on the next emit —
3840        // same canonical-form drift as the leading-space sibling,
3841        // closed on the same whitespace-byte arm.
3842        let err = parse_byte_size("64MiB ").unwrap_err();
3843        assert!(
3844            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "64MiB " && byte == 0x20),
3845            "got {err:?}"
3846        );
3847    }
3848
3849    #[test]
3850    fn parse_byte_size_rejects_internal_whitespace_between_magnitude_and_unit() {
3851        // `"64 MiB"` — the canonical typographically-spaced author
3852        // shape (the same idiom every prose reference to a byte-size
3853        // renders as, mistakenly retained when the value is pasted
3854        // into a codec-shaped slot). Before this gate the per-part
3855        // `num_part.trim()` / `unit.trim()` calls silently ate the
3856        // whitespace between the magnitude and the unit and parsed the
3857        // value to 64 * 1024 * 1024 bytes, round-tripping to `"64MiB"`
3858        // — the codec's *internal* whitespace-tolerance vector,
3859        // orthogonal to the leading / trailing surface but the same
3860        // canonical-form-drift class. Pins the arm as strictly
3861        // stronger than the pre-existing top-level `s.trim()`
3862        // behavior: it fires on whitespace anywhere in the value, not
3863        // just at the string boundary.
3864        let err = parse_byte_size("64 MiB").unwrap_err();
3865        assert!(
3866            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "64 MiB" && byte == 0x20),
3867            "got {err:?}"
3868        );
3869    }
3870
3871    #[test]
3872    fn parse_byte_size_rejects_tab_byte() {
3873        // `"\t64MiB"` — the canonical paste-from-indented-doc /
3874        // paste-from-YAML-block-scalar footgun where a tab byte leads
3875        // the magnitude. Pins that the gate covers tab (`0x09`) as
3876        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
3877        // members and both would be silently swallowed by `s.trim()`
3878        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
3879        // space alone to the full ASCII-whitespace set (space `0x20`,
3880        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
3881        // the tab arm as a representative of the non-space members.
3882        let err = parse_byte_size("\t64MiB").unwrap_err();
3883        assert!(
3884            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "\t64MiB" && byte == 0x09),
3885            "got {err:?}"
3886        );
3887    }
3888
3889    #[test]
3890    fn parse_byte_size_rejects_trailing_newline() {
3891        // `"64MiB\n"` — the canonical multi-line-paste footgun where
3892        // a trailing LF byte survives the paste. Pins the LF member
3893        // (`0x0A`) of the `is_ascii_whitespace` set as a peer to the
3894        // space and tab pins above — every non-space non-tab
3895        // whitespace byte the WhatWG ASCII-whitespace set covers is
3896        // refused by the same arm.
3897        let err = parse_byte_size("64MiB\n").unwrap_err();
3898        assert!(
3899            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "64MiB\n" && byte == 0x0a),
3900            "got {err:?}"
3901        );
3902    }
3903
3904    #[test]
3905    fn parse_byte_size_accepts_whitespace_free_canonical_forms() {
3906        // The complement-side pin: every canonical whitespace-free
3907        // authoring form the renderer emits stays accepted post-gate.
3908        // Sweep the canonical unit suffixes plus the bare-integer
3909        // shorthand so a future tightening of the whitespace arm that
3910        // over-fires on the accepted set surfaces here as a test
3911        // failure. Peer with the
3912        // `parse_duration_accepts_whitespace_free_canonical_forms` pin
3913        // on the sibling codec.
3914        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
3915        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
3916        assert_eq!(parse_byte_size("512KiB").unwrap(), 512 * 1024);
3917        assert_eq!(parse_byte_size("1KB").unwrap(), 1_000);
3918        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
3919        assert_eq!(parse_byte_size("0").unwrap(), 0);
3920    }
3921
3922    #[test]
3923    fn de_byte_size_rejects_whitespace_through_serde() {
3924        // The serde-path pin: a `:limits :memory` carrying a
3925        // whitespace-byte-carrying value (`" 64MiB"`) must fail at
3926        // deserialize time, not silently round-trip the value through
3927        // the pre-existing top-level `s.trim()`. The gate fires at
3928        // deserialize, before any validate gate runs — peer with the
3929        // existing `de_byte_size_rejects_leading_zero_through_serde` /
3930        // `de_duration_rejects_whitespace_through_serde` pins on the
3931        // same canonical-form-drift axis.
3932        let json = r#"{"memory":" 64MiB"}"#;
3933        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
3934        let msg = err.to_string();
3935        assert!(
3936            msg.contains("whitespace byte"),
3937            "serde diagnostic must surface the whitespace reason verbatim (got {msg:?})"
3938        );
3939        assert!(
3940            msg.contains("0x20"),
3941            "serde diagnostic must name the offending byte (got {msg:?})"
3942        );
3943
3944        // The whitespace-free complement — same author-side intent,
3945        // written in the canonical form the renderer would emit,
3946        // deserializes cleanly.
3947        let json = r#"{"memory":"64MiB"}"#;
3948        let l: LimitsSpec = serde_json::from_str(json).unwrap();
3949        assert_eq!(l.memory, Some(64 * 1024 * 1024));
3950    }
3951
3952    // ── canonical-form: non-ASCII Unicode `White_Space` byte-size gate ────
3953    //
3954    // Direct successor to the `parse_byte_size` ASCII-whitespace arm
3955    // (24a8ad4) — closes the strictly-complementary class the byte-scan
3956    // above cannot see. `str::trim` uses `char::is_whitespace` (Unicode
3957    // `White_Space`, strictly wider than the ASCII byte set); a leading /
3958    // trailing / internal NBSP (`\u{00A0}`) / LINE SEPARATOR (`\u{2028}`)
3959    // / EM-SPACE (`\u{2003}`) survives the byte-scan but is silently
3960    // stripped by the top-level trim, drifting to canonical `"64MiB"` on
3961    // round-trip. Pins the arm through the lifted
3962    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
3963
3964    #[test]
3965    fn parse_byte_size_rejects_leading_nbsp() {
3966        // NBSP (`\u{00A0}` = UTF-8 `0xC2 0xA0`) — the canonical
3967        // paste-from-typography / paste-from-word-processor footgun.
3968        // Before this arm landed the byte-scan missed it (neither `0xC2`
3969        // nor `0xA0` is `is_ascii_whitespace`) and `str::trim` at parse
3970        // entry silently stripped it, yielding the same `64 * 1024 *
3971        // 1024` bytes as the whitespace-free canonical form and drifting
3972        // to `"64MiB"` on next serialize.
3973        let s = "\u{00A0}64MiB";
3974        let err = parse_byte_size(s).unwrap_err();
3975        assert!(
3976            matches!(err, LimitsError::NonAsciiWhitespaceInByteSize { ref value, ch, codepoint } if value == s && ch == '\u{00A0}' && codepoint == 0x00A0),
3977            "got {err:?}"
3978        );
3979        let msg = err.to_string();
3980        assert!(
3981            msg.contains("U+00A0"),
3982            "diagnostic must surface the codepoint verbatim (got {msg:?})"
3983        );
3984        assert!(
3985            msg.contains("THEORY.md"),
3986            "diagnostic must cite the render-determinism contract (got {msg:?})"
3987        );
3988    }
3989
3990    #[test]
3991    fn parse_byte_size_rejects_internal_line_separator() {
3992        // LINE SEPARATOR (`\u{2028}`) between magnitude and unit — the
3993        // canonical paste-from-web-doc footgun (many rendering engines
3994        // insert `\u{2028}` at soft-wrap boundaries in RTF/HTML → plain
3995        // text conversion). Pins the arm on a non-space non-NBSP Unicode
3996        // `White_Space` member.
3997        let s = "64\u{2028}MiB";
3998        let err = parse_byte_size(s).unwrap_err();
3999        assert!(
4000            matches!(err, LimitsError::NonAsciiWhitespaceInByteSize { ref value, ch, codepoint } if value == s && ch == '\u{2028}' && codepoint == 0x2028),
4001            "got {err:?}"
4002        );
4003    }
4004
4005    #[test]
4006    fn parse_byte_size_rejects_trailing_ideographic_space() {
4007        // IDEOGRAPHIC SPACE (`\u{3000}`) — the CJK-typography paste
4008        // footgun (canonical U+3000 is the full-width space that
4009        // Japanese / Chinese IMEs emit when input is auto-widened). Pins
4010        // the arm at the top edge of the `char::is_whitespace` set.
4011        let s = "64MiB\u{3000}";
4012        let err = parse_byte_size(s).unwrap_err();
4013        assert!(
4014            matches!(err, LimitsError::NonAsciiWhitespaceInByteSize { ref value, ch, codepoint } if value == s && ch == '\u{3000}' && codepoint == 0x3000),
4015            "got {err:?}"
4016        );
4017    }
4018
4019    #[test]
4020    fn parse_byte_size_accepts_ascii_only_canonical_forms_after_unicode_arm() {
4021        // Positive-control pin: every ASCII-only canonical form the
4022        // renderer emits stays accepted through the new arm — the
4023        // lifted predicate is a strict no-op on ASCII input.
4024        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
4025        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
4026        assert_eq!(parse_byte_size("512KiB").unwrap(), 512 * 1024);
4027        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
4028    }
4029
4030    // ── canonical-form: integer-magnitude duration codec gate ─────────────
4031    //
4032    // Direct successor to the `parse_byte_size` integer-magnitude gate on
4033    // the peer `:limits :memory` codec — every magnitude `render_duration`
4034    // emits is a non-negative integer (no decimal point, no leading sign,
4035    // no scientific notation). The parser's accepted set must match for
4036    // parse → render → parse to round-trip without canonical-form drift.
4037    // Pins every canonical-drift shape — fractional (`"1.5s"`),
4038    // decimal-shaped-integer (`"1.0s"`), half-unit (`"0.5m"`),
4039    // leading-`+` (`"+30s"`), leading-`-` (`"-30s"`) — plus the
4040    // complement-side pin (integer happy paths), the round-trip
4041    // convergence property, the BadDurationMagnitude-precedence pin
4042    // (genuinely unparseable inputs keep their narrower diagnostic), the
4043    // overflow-surface pin (u64-overflow on magnitude × unit surfaces at
4044    // parse time), and the serde-path pin (the gate fires at deserialize,
4045    // before any validate gate runs).
4046
4047    #[test]
4048    fn parse_duration_rejects_fractional_seconds() {
4049        // The fail-before-pass-after pin: `"1.5s"` parsed cleanly on
4050        // every pre-gate codebase (f64::parse accepts the decimal), the
4051        // codec produced 1500ms, and `render_duration(1500ms)` emitted
4052        // `"1500ms"` on the next serialize — silently drifting the
4053        // canonical form away from the author's intent. The new gate
4054        // surfaces the round-trip break at the parser layer with a
4055        // self-locating diagnostic.
4056        let err = parse_duration("1.5s").unwrap_err();
4057        assert!(
4058            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "1.5"),
4059            "got {err:?}"
4060        );
4061    }
4062
4063    #[test]
4064    fn parse_duration_rejects_decimal_shaped_integer() {
4065        // The canonical-drift case where the *value* is integer but the
4066        // *form* carries a redundant decimal point — `"1.0s"` parses to
4067        // 1s (integer), but the renderer emits `"1s"` on the next
4068        // serialize (no decimal point). The parse-shape gate fires here
4069        // too so the codec's accepted set is exactly the renderer's
4070        // emitted set.
4071        let err = parse_duration("1.0s").unwrap_err();
4072        assert!(
4073            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "1.0"),
4074            "got {err:?}"
4075        );
4076    }
4077
4078    #[test]
4079    fn parse_duration_rejects_half_minute() {
4080        // `"0.5m"` parses to 30s; the renderer emits `"30s"` on the
4081        // next serialize. Pin the round-trip drift on the explicitly-
4082        // fractional case sized to land on a smaller-unit boundary, so
4083        // the gate's coverage includes both the "doesn't land on a
4084        // boundary" (1.5s → 1500ms) and "lands on a smaller-unit
4085        // boundary" (0.5m → 30s) drift shapes — the same two-shape
4086        // pattern the byte-size gate covers (1.5KiB → 1536, 0.5GiB →
4087        // 512MiB).
4088        let err = parse_duration("0.5m").unwrap_err();
4089        assert!(
4090            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "0.5"),
4091            "got {err:?}"
4092        );
4093    }
4094
4095    #[test]
4096    fn parse_duration_rejects_leading_plus() {
4097        // `"+30s"` parses through f64 as 30s; the renderer emits `"30s"`
4098        // on the next serialize. The leading `+` is not a renderer-
4099        // emitted shape, so it falls in the same canonical-drift class
4100        // as the fractional forms — surfacing under the same diagnostic
4101        // keeps the gate's coverage uniform across every non-canonical-
4102        // but-numeric input shape the parser would otherwise accept.
4103        let err = parse_duration("+30s").unwrap_err();
4104        assert!(
4105            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "+30"),
4106            "got {err:?}"
4107        );
4108    }
4109
4110    #[test]
4111    fn parse_duration_rejects_negative_seconds_via_integer_gate() {
4112        // The negative-magnitude class — pre-gate the parser routed
4113        // negatives through the `num < 0.0` check to `BadDurationMagnitude`;
4114        // the new digit-only gate fires earlier and routes the same
4115        // input to `NonIntegerDurationMagnitude` (negatives are not
4116        // digit-only). Pin the new diagnostic so a future relaxation
4117        // that re-routes negatives back to the old arm surfaces here.
4118        let err = parse_duration("-30s").unwrap_err();
4119        assert!(
4120            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "-30"),
4121            "got {err:?}"
4122        );
4123    }
4124
4125    #[test]
4126    fn parse_duration_continues_to_accept_integer_magnitudes() {
4127        // The complement-side pin: every canonical integer-magnitude
4128        // form the renderer emits must continue to parse to the same
4129        // value the renderer produced. Sweep the canonical authoring
4130        // shapes (ms, bare-s, s, m, h, and the bare-integer "0" zero-
4131        // shape) so a future tightening of the parser surfaces here as
4132        // a test failure rather than a silent regression.
4133        assert_eq!(parse_duration("0s").unwrap(), Duration::ZERO);
4134        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4135        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
4136        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
4137        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4138        assert_eq!(parse_duration("3600").unwrap(), Duration::from_secs(3600));
4139    }
4140
4141    #[test]
4142    fn parse_duration_round_trips_through_render_for_every_canonical_form() {
4143        // The structural property the gate makes load-bearing: every
4144        // value the parser accepts round-trips through the canonical
4145        // [`crate::supervisor::duration_codec::render`] primitive to a
4146        // string the parser also accepts — and to the *same* value.
4147        // Sweep the values the renderer emits canonically (ms / s / m /
4148        // h boundaries plus a non-aligned millisecond) so a future
4149        // codec change that breaks round-trip convergence surfaces here.
4150        for d in [
4151            Duration::from_millis(1),
4152            Duration::from_millis(500),
4153            Duration::from_millis(1500),
4154            Duration::from_secs(1),
4155            Duration::from_secs(30),
4156            Duration::from_secs(60),
4157            Duration::from_secs(120),
4158            Duration::from_secs(3600),
4159        ] {
4160            let rendered = crate::supervisor::duration_codec::render(d);
4161            let reparsed = parse_duration(&rendered)
4162                .unwrap_or_else(|e| panic!("render({d:?}) = {rendered:?} must reparse, got {e:?}"));
4163            assert_eq!(
4164                reparsed, d,
4165                "round-trip drift on {d:?}: rendered={rendered:?}, reparsed={reparsed:?}",
4166            );
4167        }
4168    }
4169
4170    #[test]
4171    fn parse_duration_keeps_bad_magnitude_for_unparseable_input() {
4172        // The precedence pin: the new `NonIntegerDurationMagnitude` arm
4173        // distinguishes *non-canonical-but-numeric* (`"1.5"`, `"+30"`,
4174        // `"-30"`) from *genuinely-unparseable* (`"abc"`, `"--1"`) so
4175        // the existing `BadDurationMagnitude` diagnostic's wording
4176        // remains load-bearing for the latter class — the gate is
4177        // additive, not replacing.
4178        let err = parse_duration("abcs").unwrap_err();
4179        assert!(
4180            matches!(err, LimitsError::BadDurationMagnitude(_)),
4181            "got {err:?}"
4182        );
4183        let err = parse_duration("--1s").unwrap_err();
4184        assert!(
4185            matches!(err, LimitsError::BadDurationMagnitude(_)),
4186            "got {err:?}"
4187        );
4188    }
4189
4190    #[test]
4191    fn parse_duration_overflow_surfaces_as_bad_magnitude() {
4192        // `u64::MAX h` overflows the seconds computation (magnitude ×
4193        // 3600); the parser surfaces the overflow as a
4194        // `BadDurationMagnitude` with an overflow-shaped wording so the
4195        // diagnostic names the offending magnitude × unit pair at parse
4196        // time. Matches `parse_byte_size`'s overflow-surface arm
4197        // structurally.
4198        let err = parse_duration("18446744073709551615h").unwrap_err();
4199        let LimitsError::BadDurationMagnitude(reason) = err else {
4200            panic!("expected BadDurationMagnitude(overflow), got other variant");
4201        };
4202        assert!(
4203            reason.contains("overflow"),
4204            "overflow diagnostic must mention overflow (got {reason:?})"
4205        );
4206    }
4207
4208    // ── canonical-form: leading-zero duration codec gate ─────────────────
4209    //
4210    // Direct successor to the `supervisor::duration_codec` leading-zero
4211    // arm (9178904) and the `rate_limit_codec` leading-zero arm (4f46830)
4212    // — closes the leading-zero canonical-form-drift class on the
4213    // `:limits :wall-clock` codec. Every magnitude `render_duration`
4214    // emits is a non-negative integer with no leading-zero padding; the
4215    // parser's accepted set must match for parse → render → parse to
4216    // round-trip without canonical-form drift. The single-byte `"0"`
4217    // round-trips losslessly (`render_duration(Duration::ZERO)` emits
4218    // `"0s"`) and the downstream [`LimitsError::WallClockZero`] gate
4219    // refuses zero-magnitude authoring at the typed-validate layer above
4220    // — the codec-layer / typed-validate-layer partition is what keeps
4221    // the diagnostic partitioning stable.
4222
4223    #[test]
4224    fn parse_duration_rejects_leading_zero_magnitude() {
4225        // The fail-before-pass-after pin: `"030s"` parsed cleanly on
4226        // every pre-gate codebase (`u64::from_str` accepts the leading
4227        // zero), the codec produced 30s, and `render_duration(30s)`
4228        // emitted `"30s"` on the next serialize — silently dropping
4229        // the leading zero and drifting the canonical form away from
4230        // the author's intent. The new gate surfaces the round-trip
4231        // break at the parser layer with a self-locating diagnostic.
4232        let err = parse_duration("030s").unwrap_err();
4233        assert!(
4234            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "030"),
4235            "got {err:?}"
4236        );
4237    }
4238
4239    #[test]
4240    fn parse_duration_rejects_multi_digit_zero_magnitude() {
4241        // `"00s"` is the degenerate leading-zero case — every byte is
4242        // `0`. `u64::from_str("00")` = 0, and the codec produces
4243        // `Duration::ZERO`; `render_duration(Duration::ZERO)` emits
4244        // `"0s"` on the next serialize — drift from `"00s"` to `"0s"`.
4245        // The leading-zero arm refuses the drift class at the codec
4246        // layer while leaving the canonical single-byte `"0s"` accepted.
4247        let err = parse_duration("00s").unwrap_err();
4248        assert!(
4249            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "00"),
4250            "got {err:?}"
4251        );
4252    }
4253
4254    #[test]
4255    fn parse_duration_rejects_leading_zero_in_hour_window() {
4256        // `"01h"` parses to 1h; the renderer emits `"1h"` on the next
4257        // serialize. The leading-zero class is a property of the
4258        // magnitude, not the unit — pin a per-hour magnitude alongside
4259        // the per-second / per-ms pins so the gate's coverage is
4260        // structural across every canonical unit suffix the codec
4261        // accepts. Mirrors the `_per_hour_window` pin the
4262        // `supervisor::duration_codec` and `rate_limit_codec` leading-
4263        // zero arms carry on the peer codecs.
4264        let err = parse_duration("01h").unwrap_err();
4265        assert!(
4266            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "01"),
4267            "got {err:?}"
4268        );
4269    }
4270
4271    #[test]
4272    fn parse_duration_rejects_leading_zero_bare_integer_as_seconds() {
4273        // The bare-integer-as-seconds shorthand (`"30"` → 30s, no unit
4274        // suffix because the parser routes the empty `unit` slot to
4275        // `Duration::from_secs`) inherits the leading-zero arm: `"030"`
4276        // parses losslessly to 30s but `render_duration(30s)` emits
4277        // `"30s"` on the next serialize. Pin the bare-integer path so a
4278        // future relaxation that special-cases the unitless shorthand
4279        // surfaces here as a test failure.
4280        let err = parse_duration("030").unwrap_err();
4281        assert!(
4282            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "030"),
4283            "got {err:?}"
4284        );
4285    }
4286
4287    #[test]
4288    fn parse_duration_accepts_single_zero_magnitude_at_codec_layer() {
4289        // The codec-layer / typed-validate-layer boundary pin: the
4290        // single-byte `"0"` magnitude round-trips losslessly through
4291        // `render_duration` (`render_duration(Duration::ZERO)` emits
4292        // `"0s"`), so it stays accepted at this codec layer across
4293        // every canonical unit suffix. The downstream
4294        // `LimitsError::WallClockZero` gate is what refuses
4295        // zero-magnitude authoring at the typed-validate layer above
4296        // — the partition keeps the canonical-form-drift diagnostic
4297        // (this arm) and the semantic-zero diagnostic (the validate
4298        // gate) disjoint.
4299        assert_eq!(parse_duration("0s").unwrap(), Duration::ZERO);
4300        assert_eq!(parse_duration("0ms").unwrap(), Duration::ZERO);
4301        assert_eq!(parse_duration("0m").unwrap(), Duration::ZERO);
4302        assert_eq!(parse_duration("0h").unwrap(), Duration::ZERO);
4303        assert_eq!(parse_duration("0").unwrap(), Duration::ZERO);
4304    }
4305
4306    #[test]
4307    fn parse_duration_accepts_canonical_magnitude_with_leading_one() {
4308        // The complement-side pin on the leading-zero arm: magnitudes
4309        // beginning with `1`..=`9` stay accepted across every canonical
4310        // unit suffix the codec accepts. Pin this so a future
4311        // tightening cannot drift into rejecting valid canonical
4312        // magnitudes — peer with the `_accepts_canonical_magnitude_with_leading_one`
4313        // pin the `supervisor::duration_codec` and `rate_limit_codec`
4314        // leading-zero arms carry.
4315        assert_eq!(parse_duration("1ms").unwrap(), Duration::from_millis(1));
4316        assert_eq!(parse_duration("1s").unwrap(), Duration::from_secs(1));
4317        assert_eq!(parse_duration("1m").unwrap(), Duration::from_secs(60));
4318        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4319        assert_eq!(parse_duration("100ms").unwrap(), Duration::from_millis(100));
4320        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4321    }
4322
4323    // ── canonical-form: whitespace-rejection duration codec gate ─────────
4324    //
4325    // Direct successor to the `supervisor::duration_codec` whitespace-
4326    // rejection arm (a7ae622) and the `rate_limit_codec` whitespace-
4327    // rejection arm (1ad7755) on the same canonical-form
4328    // render-determinism axis. The pre-gate top-level `s.trim()` at
4329    // parse entry and the per-part `num_part.trim()` / `unit.trim()`
4330    // calls silently ate leading / trailing / internal whitespace, so
4331    // every whitespace-carrying shape parsed to the same integer
4332    // magnitude and round-tripped through `render_duration` to a
4333    // *different* canonical string on next serialize — the same
4334    // canonical-form-drift class the leading-`+` / fractional /
4335    // leading-zero arms already close on this codec. `u8::is_ascii_whitespace`
4336    // covers the five WhatWG-conformant ASCII whitespace bytes
4337    // (space `0x20`, tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`).
4338
4339    #[test]
4340    fn parse_duration_rejects_leading_whitespace() {
4341        // The fail-before-pass-after pin: `" 30s"` — the canonical
4342        // paste-from-aligned-doc / paste-from-YAML-quoted-plain-scalar
4343        // footgun. Before this gate the top-level `s.trim()` at parse
4344        // entry silently ate the leading space and parsed the value to
4345        // `Duration::from_secs(30)`, which then round-tripped through
4346        // `render_duration` to `"30s"` (a *different* canonical string
4347        // on the next emit) — the exact canonical-form-drift class the
4348        // leading-`+` / leading-zero arms already close, extended to
4349        // the whitespace-byte class. Peer with the sibling
4350        // `supervisor::duration_codec` `parse_rejects_leading_whitespace`
4351        // arm (a7ae622) on the shared duration-codec trajectory.
4352        let err = parse_duration(" 30s").unwrap_err();
4353        assert!(
4354            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == " 30s" && byte == 0x20),
4355            "got {err:?}"
4356        );
4357        let msg = err.to_string();
4358        assert!(
4359            msg.contains("whitespace byte 0x20"),
4360            "diagnostic must surface the offending byte verbatim (got {msg:?})"
4361        );
4362        assert!(
4363            msg.contains("THEORY.md"),
4364            "diagnostic must cite the render-determinism contract (got {msg:?})"
4365        );
4366    }
4367
4368    #[test]
4369    fn parse_duration_rejects_trailing_whitespace() {
4370        // `"30s "` — the canonical shell-history / trailing-space paste
4371        // footgun. Before this gate the top-level `s.trim()` silently
4372        // ate the trailing space and parsed to `Duration::from_secs(30)`,
4373        // round-tripping to `"30s"` on the next emit — same canonical-
4374        // form drift as the leading-space sibling, closed on the same
4375        // whitespace-byte arm.
4376        let err = parse_duration("30s ").unwrap_err();
4377        assert!(
4378            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "30s " && byte == 0x20),
4379            "got {err:?}"
4380        );
4381    }
4382
4383    #[test]
4384    fn parse_duration_rejects_internal_whitespace_between_magnitude_and_unit() {
4385        // `"30 s"` — the canonical typographically-spaced author shape
4386        // (the same idiom every prose reference to a duration renders as,
4387        // mistakenly retained when the value is pasted into a codec-
4388        // shaped slot). Before this gate the per-part `num_part.trim()`
4389        // / `unit.trim()` calls silently ate the whitespace between the
4390        // magnitude and the unit and parsed the value to
4391        // `Duration::from_secs(30)`, round-tripping to `"30s"` — the
4392        // codec's *internal* whitespace-tolerance vector, orthogonal
4393        // to the leading / trailing surface but the same canonical-
4394        // form-drift class. Pins the arm as strictly stronger than the
4395        // pre-existing top-level `s.trim()` behavior: it fires on
4396        // whitespace anywhere in the value, not just at the string
4397        // boundary.
4398        let err = parse_duration("30 s").unwrap_err();
4399        assert!(
4400            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "30 s" && byte == 0x20),
4401            "got {err:?}"
4402        );
4403    }
4404
4405    #[test]
4406    fn parse_duration_rejects_tab_byte() {
4407        // `"\t30s"` — the canonical paste-from-indented-doc /
4408        // paste-from-YAML-block-scalar footgun where a tab byte leads
4409        // the magnitude. Pins that the gate covers tab (`0x09`) as well
4410        // as space (`0x20`) — both are `u8::is_ascii_whitespace` members
4411        // and both would be silently swallowed by `s.trim()` pre-gate.
4412        // The `is_ascii_whitespace` coverage extends beyond space alone
4413        // to the full ASCII-whitespace set (space `0x20`, tab `0x09`,
4414        // LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins the tab arm
4415        // as a representative of the non-space members.
4416        let err = parse_duration("\t30s").unwrap_err();
4417        assert!(
4418            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "\t30s" && byte == 0x09),
4419            "got {err:?}"
4420        );
4421    }
4422
4423    #[test]
4424    fn parse_duration_rejects_trailing_newline() {
4425        // `"30s\n"` — the canonical multi-line-paste footgun where a
4426        // trailing LF byte survives the paste. Pins the LF member
4427        // (`0x0A`) of the `is_ascii_whitespace` set as a peer to the
4428        // space and tab pins above — every non-space non-tab whitespace
4429        // byte the WhatWG ASCII-whitespace set covers is refused by
4430        // the same arm.
4431        let err = parse_duration("30s\n").unwrap_err();
4432        assert!(
4433            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "30s\n" && byte == 0x0a),
4434            "got {err:?}"
4435        );
4436    }
4437
4438    #[test]
4439    fn parse_duration_accepts_whitespace_free_canonical_forms() {
4440        // The complement-side pin: every canonical whitespace-free
4441        // authoring form the renderer emits stays accepted post-gate.
4442        // Sweep the canonical unit suffixes plus the bare-integer
4443        // shorthand so a future tightening of the whitespace arm that
4444        // over-fires on the accepted set surfaces here as a test
4445        // failure. Peer with the `parse_duration_continues_to_accept_integer_magnitudes`
4446        // pin the fractional / leading-`+` gate carries.
4447        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
4448        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4449        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
4450        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4451        assert_eq!(parse_duration("0s").unwrap(), Duration::ZERO);
4452        assert_eq!(parse_duration("3600").unwrap(), Duration::from_secs(3600));
4453    }
4454
4455    #[test]
4456    fn de_duration_rejects_whitespace_through_serde() {
4457        // The serde-path pin: a `:limits :wall-clock` carrying a
4458        // whitespace-byte-carrying value (`" 30s"`) must fail at
4459        // deserialize time, not silently round-trip the value through
4460        // the pre-existing top-level `s.trim()`. The gate fires at
4461        // deserialize, before any validate gate runs — peer with the
4462        // existing `de_duration_rejects_leading_zero_through_serde` /
4463        // `de_duration_rejects_fractional_value_through_serde` pins on
4464        // the same canonical-form-drift axis.
4465        let json = r#"{"wallClock":" 30s"}"#;
4466        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4467        let msg = err.to_string();
4468        assert!(
4469            msg.contains("whitespace byte"),
4470            "serde diagnostic must surface the whitespace reason verbatim (got {msg:?})"
4471        );
4472        assert!(
4473            msg.contains("0x20"),
4474            "serde diagnostic must name the offending byte (got {msg:?})"
4475        );
4476
4477        // The whitespace-free complement — same author-side intent,
4478        // written in the canonical form the renderer would emit,
4479        // deserializes cleanly.
4480        let json = r#"{"wallClock":"30s"}"#;
4481        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4482        assert_eq!(l.wall_clock, Some(Duration::from_secs(30)));
4483    }
4484
4485    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
4486    //
4487    // Successor to the `parse_duration` ASCII-whitespace arm (ebc3a75)
4488    // — closes the strictly-complementary class the byte-scan cannot
4489    // see, through the lifted
4490    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
4491
4492    #[test]
4493    fn parse_duration_rejects_leading_nbsp() {
4494        // NBSP prefix — paste-from-typography footgun. Byte-scan misses,
4495        // `str::trim` strips silently, drifting to `"30s"` on next
4496        // emit.
4497        let s = "\u{00A0}30s";
4498        let err = parse_duration(s).unwrap_err();
4499        assert!(
4500            matches!(err, LimitsError::NonAsciiWhitespaceInDuration { ref value, ch, codepoint } if value == s && ch == '\u{00A0}' && codepoint == 0x00A0),
4501            "got {err:?}"
4502        );
4503        let msg = err.to_string();
4504        assert!(
4505            msg.contains("U+00A0"),
4506            "diagnostic must name codepoint (got {msg:?})"
4507        );
4508    }
4509
4510    #[test]
4511    fn parse_duration_rejects_internal_em_space() {
4512        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
4513        // paste-from-typography footgun on the `<integer><unit>` shape.
4514        let s = "30\u{2003}s";
4515        let err = parse_duration(s).unwrap_err();
4516        assert!(
4517            matches!(err, LimitsError::NonAsciiWhitespaceInDuration { ref value, ch, codepoint } if value == s && ch == '\u{2003}' && codepoint == 0x2003),
4518            "got {err:?}"
4519        );
4520    }
4521
4522    #[test]
4523    fn parse_duration_accepts_ascii_only_canonical_forms_after_unicode_arm() {
4524        // Positive-control pin: every ASCII-only canonical form the
4525        // renderer emits stays accepted through the new arm.
4526        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
4527        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4528        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4529    }
4530
4531    #[test]
4532    fn de_duration_rejects_leading_zero_through_serde() {
4533        // The serde-path pin: a `:limits :wall-clock` carrying a
4534        // leading-zero magnitude (`"030s"`) must fail at deserialize
4535        // time, not silently round-trip the value through the parser.
4536        // The gate fires at deserialize, before any validate gate runs
4537        // — peer with the existing `de_duration_rejects_fractional_value_through_serde`
4538        // pin on the same canonical-form-drift axis.
4539        let json = r#"{"wallClock":"030s"}"#;
4540        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4541        let msg = err.to_string();
4542        assert!(
4543            msg.contains("leading zero"),
4544            "serde diagnostic must surface the leading-zero reason verbatim (got {msg:?})"
4545        );
4546
4547        let json = r#"{"wallClock":"30s"}"#;
4548        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4549        assert_eq!(l.wall_clock, Some(Duration::from_secs(30)));
4550    }
4551
4552    #[test]
4553    fn de_duration_rejects_fractional_value_through_serde() {
4554        // The serde-path pin: a `:limits :wall-clock` carrying a
4555        // fractional magnitude (`"1.5s"`) must fail at deserialize time,
4556        // not silently round-trip the value through the f64 parser. Pin
4557        // both the success-on-canonical path (the integer form
4558        // deserializes cleanly) and the failure-on-non-canonical path
4559        // (the fractional form is rejected by the codec before any
4560        // validate gate runs).
4561        let json = r#"{"wallClock":"1.5s"}"#;
4562        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4563        let msg = err.to_string();
4564        assert!(
4565            msg.contains("non-negative integer"),
4566            "serde diagnostic must surface the integer-magnitude reason verbatim \
4567             (got {msg:?})"
4568        );
4569
4570        // The integer-form complement — same author-side intent
4571        // (1.5s = 1500ms), written in the canonical form the renderer
4572        // would emit, deserializes cleanly.
4573        let json = r#"{"wallClock":"1500ms"}"#;
4574        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4575        assert_eq!(l.wall_clock, Some(Duration::from_millis(1500)));
4576    }
4577
4578    #[test]
4579    fn de_byte_size_rejects_fractional_value_through_serde() {
4580        // The serde-path pin: a `:limits :memory` carrying a fractional
4581        // magnitude (`"1.5KiB"`) must fail at deserialize time, not
4582        // silently round-trip the value through the f64 parser. Pin
4583        // both the success-on-canonical path (the integer form
4584        // deserializes cleanly) and the failure-on-non-canonical path
4585        // (the fractional form is rejected by the codec before any
4586        // validate gate runs).
4587        let json = r#"{"memory":"1.5KiB"}"#;
4588        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4589        let msg = err.to_string();
4590        assert!(
4591            msg.contains("non-negative integer"),
4592            "serde diagnostic must surface the integer-magnitude reason verbatim (got {msg:?})"
4593        );
4594
4595        // The integer-form complement — same author-side intent
4596        // (1.5KiB = 1536 bytes), written in the canonical form the
4597        // renderer would emit, deserializes cleanly.
4598        let json = r#"{"memory":"1536"}"#;
4599        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4600        assert_eq!(l.memory, Some(1536));
4601    }
4602
4603    // ── canonical-form: integer-magnitude millicores codec gate ───────────
4604    //
4605    // Direct successor to the `parse_byte_size` / `parse_duration` /
4606    // shared `supervisor::duration_codec` / `rate_limit_codec`
4607    // integer-magnitude gates on the four peer typed codecs in
4608    // caixa-core — closes the sixth (and last) typed-codec surface in
4609    // the crate. Every magnitude `render_millicores` emits is a
4610    // non-negative integer (`format!("{m}m")`) — no decimal point, no
4611    // leading sign, no scientific notation. The parser's accepted set
4612    // must match for parse → render → parse to round-trip without
4613    // canonical-form drift. Pins every canonical-drift shape —
4614    // leading-`+` (`"+500m"` / `"+2"`, the load-bearing class the
4615    // digit-only gate closes beyond `u32::from_str` strictness),
4616    // leading-`-` (`"-100m"`), fractional (`"1.5"`), decimal-shaped-
4617    // integer on both authoring paths (`"500.0m"` / `"2.0"`), the
4618    // bare-`m`-with-no-magnitude pin, the empty-string pin, the
4619    // garbage-precedence pin (genuinely unparseable inputs keep the
4620    // narrower `BadMillicores` diagnostic), the u32-overflow surface
4621    // pin on both the `m`-suffix and bare-core multiply paths, the
4622    // complement-side pin (every integer happy path the gate must
4623    // continue to accept), the round-trip convergence property, and
4624    // the serde-path pin (the gate fires at deserialize, before any
4625    // validate gate runs).
4626
4627    #[test]
4628    fn parse_millicores_rejects_fractional_magnitude() {
4629        // The fail-before-pass-after pin on the bare-core path:
4630        // `"1.5"` parsed cleanly on no pre-gate codebase (`u32::from_str`
4631        // rejects the decimal), but the diagnostic was value-laundered
4632        // (the bare `BadMillicores("1.5")` wording didn't name the
4633        // canonical-form remediation or the round-trip drift the next
4634        // emit would produce — `1.5 cores × 1000 = 1500 millicores` →
4635        // `"1500m"` on the renderer). The gate routes the same input to
4636        // `NonIntegerMillicoreMagnitude` with the canonical-form wording.
4637        let err = parse_millicores("1.5").unwrap_err();
4638        assert!(
4639            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "1.5"),
4640            "got {err:?}"
4641        );
4642    }
4643
4644    #[test]
4645    fn parse_millicores_rejects_decimal_shaped_integer_with_suffix() {
4646        // The canonical-drift case on the `m`-suffix path where the
4647        // *value* is integer but the *form* carries a redundant decimal
4648        // point — `"500.0m"` parses to 500 millicores (integer), but
4649        // the renderer emits `"500m"` on the next serialize (no decimal
4650        // point). The parse-shape gate fires here too so the codec's
4651        // accepted set is exactly the renderer's emitted set — same
4652        // shape as `parse_byte_size`'s `"1.0MiB"` case.
4653        let err = parse_millicores("500.0m").unwrap_err();
4654        assert!(
4655            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "500.0"),
4656            "got {err:?}"
4657        );
4658    }
4659
4660    #[test]
4661    fn parse_millicores_rejects_decimal_shaped_integer_bare_core() {
4662        // The decimal-shaped-integer pin on the bare-core path —
4663        // `"2.0"` would be 2000 millicores (the canonical `"2000m"`),
4664        // but the redundant decimal point is not a renderer-emitted
4665        // shape. Surfaces under the same diagnostic as the `m`-suffix
4666        // path so the gate's coverage is uniform across both authoring
4667        // paths.
4668        let err = parse_millicores("2.0").unwrap_err();
4669        assert!(
4670            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "2.0"),
4671            "got {err:?}"
4672        );
4673    }
4674
4675    #[test]
4676    fn parse_millicores_rejects_leading_plus_sign_with_suffix() {
4677        // The load-bearing class the digit-only gate closes beyond
4678        // `u32::from_str`'s strictness: current Rust `u32::from_str`
4679        // permissively accepts `"+500"` → 500, so `"+500m"` parsed
4680        // cleanly through the pre-gate codec to `RateLimit`-shaped
4681        // 500 millicores and serde silently round-tripped to `"500m"`
4682        // on the next emit — a *different* canonical string. Same
4683        // shape as `parse_byte_size`'s `"+1024"` (875 commit) and
4684        // `parse_duration`'s `"+30s"` (1027 commit) cases on the peer
4685        // codecs.
4686        let err = parse_millicores("+500m").unwrap_err();
4687        assert!(
4688            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "+500"),
4689            "got {err:?}"
4690        );
4691    }
4692
4693    #[test]
4694    fn parse_millicores_rejects_leading_plus_sign_bare_core() {
4695        // The leading-`+` pin on the bare-core path — `"+2"` parsed
4696        // through `u32::from_str` as 2 → 2000 millicores → `"2000m"`
4697        // on the renderer; canonical-drift. The digit-only gate routes
4698        // the same input to `NonIntegerMillicoreMagnitude`, peer with
4699        // the `m`-suffix path.
4700        let err = parse_millicores("+2").unwrap_err();
4701        assert!(
4702            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "+2"),
4703            "got {err:?}"
4704        );
4705    }
4706
4707    #[test]
4708    fn parse_millicores_rejects_leading_minus_sign() {
4709        // The negative-magnitude class — pre-gate `u32::from_str`
4710        // rejected negatives but the diagnostic collapsed onto the
4711        // opaque `BadMillicores("-100m")` wording. The digit-only gate
4712        // fires earlier and routes the same input to
4713        // `NonIntegerMillicoreMagnitude` (negatives are not digit-only,
4714        // and `i64::from_str` accepts the leading sign so the numeric
4715        // arm matches). Pin the new diagnostic so a future relaxation
4716        // that re-routes negatives back to the old arm surfaces here.
4717        let err = parse_millicores("-100m").unwrap_err();
4718        assert!(
4719            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "-100"),
4720            "got {err:?}"
4721        );
4722    }
4723
4724    #[test]
4725    fn parse_millicores_rejects_empty_string() {
4726        // The empty-input pin — `""` is not a magnitude at all. Pre-
4727        // gate this fell through to `s.parse::<u32>()` and surfaced as
4728        // a generic parse failure with the same `BadMillicores("")`
4729        // wording; the explicit empty-check at the top of the codec
4730        // surfaces the same diagnostic earlier and makes the empty-
4731        // input class structurally distinct from the digit-only /
4732        // numeric / garbage arms below.
4733        let err = parse_millicores("").unwrap_err();
4734        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4735    }
4736
4737    #[test]
4738    fn parse_millicores_rejects_bare_unit_with_no_magnitude() {
4739        // The bare-`m`-with-no-magnitude pin — `"m"` strips to `""`,
4740        // which is not a magnitude at all. The canonical millicores
4741        // authoring form requires a magnitude in front of the unit
4742        // (`"500m"`, not `"m"`). Surface as `BadMillicores` so the
4743        // narrower-arm wording stays load-bearing for this class.
4744        let err = parse_millicores("m").unwrap_err();
4745        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4746    }
4747
4748    #[test]
4749    fn parse_millicores_garbage_still_falls_through_to_bad_millicores() {
4750        // The precedence pin: the new `NonIntegerMillicoreMagnitude`
4751        // arm distinguishes *non-canonical-but-numeric* (`"1.5"`,
4752        // `"+500m"`, `"-100m"`, `"500.0m"`) from *genuinely-
4753        // unparseable* (`"abc"`, `"--1m"`, `"foo"`) so the existing
4754        // `BadMillicores` diagnostic's wording remains load-bearing
4755        // for the latter class — the gate is additive, not replacing.
4756        // Pin both arms so a future relaxation that collapses them
4757        // surfaces here.
4758        let err = parse_millicores("abc").unwrap_err();
4759        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4760        let err = parse_millicores("--1m").unwrap_err();
4761        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4762        let err = parse_millicores("foo").unwrap_err();
4763        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4764    }
4765
4766    #[test]
4767    fn parse_millicores_u32_overflow_with_suffix_surfaces_as_overflow() {
4768        // The u32-overflow surface pin on the `m`-suffix path: a
4769        // magnitude exceeding `u32::MAX` (4294967296 = u32::MAX + 1)
4770        // surfaces as `BadMillicores` with an overflow-shaped wording
4771        // naming the offending magnitude verbatim. The digit-only
4772        // guard guarantees every byte is `[0-9]`, so overflow is the
4773        // only remaining `u32::from_str` failure mode — the overflow
4774        // arm is no longer in unreachable-by-prior-gate territory.
4775        // Matches the overflow-arm shape on `parse_byte_size` /
4776        // `parse_duration` / `rate_limit_codec`.
4777        let err = parse_millicores("4294967296m").unwrap_err();
4778        let LimitsError::BadMillicores(reason) = err else {
4779            panic!("expected BadMillicores(overflow), got other variant");
4780        };
4781        assert!(
4782            reason.contains("overflow"),
4783            "overflow diagnostic must mention overflow (got {reason:?})"
4784        );
4785    }
4786
4787    #[test]
4788    fn parse_millicores_bare_core_overflow_surfaces_as_overflow() {
4789        // The u32-overflow surface pin on the bare-core path: a
4790        // magnitude that fits u32 on its own but overflows on the
4791        // `× 1000` conversion to millicores surfaces as
4792        // `BadMillicores` with an overflow-shaped wording. Pre-gate
4793        // the codec used `saturating_mul(1000)` which silently
4794        // saturated the result at `u32::MAX` — landing as the cap
4795        // value far from the author's intent and bypassing any
4796        // future validate-time upper-bound gate the `:cpu` axis
4797        // grows. The `checked_mul` rewrite surfaces the overflow at
4798        // parse time. (4294968 cores × 1000 = 4294968000 > u32::MAX
4799        // = 4294967295 — the smallest digit-string that overflows
4800        // u32 on the × 1000 multiply while fitting u32 on its own.)
4801        let err = parse_millicores("4294968").unwrap_err();
4802        let LimitsError::BadMillicores(reason) = err else {
4803            panic!("expected BadMillicores(× 1000 overflow), got other variant");
4804        };
4805        assert!(
4806            reason.contains("overflow"),
4807            "× 1000 overflow diagnostic must mention overflow (got {reason:?})"
4808        );
4809    }
4810
4811    #[test]
4812    fn parse_millicores_continues_to_accept_canonical_forms() {
4813        // The complement-side pin: every canonical integer-magnitude
4814        // form the renderer emits must continue to parse to the same
4815        // value the renderer produced. Sweep the canonical authoring
4816        // shapes on both paths (the `m`-suffix path: `"0m"`, `"500m"`,
4817        // `"2000m"`; the bare-core shorthand: `"0"`, `"2"`, `"4"`) so
4818        // a future tightening of the parser surfaces here as a test
4819        // failure rather than a silent regression. The `0` case is at
4820        // the codec layer only; `validate_rejects_zero_cpu` rejects
4821        // `Some(0)` one level up.
4822        assert_eq!(parse_millicores("0m").unwrap(), 0);
4823        assert_eq!(parse_millicores("500m").unwrap(), 500);
4824        assert_eq!(parse_millicores("1500m").unwrap(), 1500);
4825        assert_eq!(parse_millicores("2000m").unwrap(), 2000);
4826        assert_eq!(parse_millicores("0").unwrap(), 0);
4827        assert_eq!(parse_millicores("2").unwrap(), 2000);
4828        assert_eq!(parse_millicores("4").unwrap(), 4000);
4829    }
4830
4831    #[test]
4832    fn parse_millicores_round_trips_through_render_for_every_canonical_form() {
4833        // The structural property the gate makes load-bearing: every
4834        // value the parser accepts round-trips through
4835        // `render_millicores` to a string the parser also accepts —
4836        // and to the *same* value. Sweep the values the renderer emits
4837        // canonically (zero, sub-core, single-core boundary, multi-
4838        // core, and a non-1000-multiple millicore value) so a future
4839        // codec change that breaks round-trip convergence surfaces
4840        // here, not at a downstream renderer that double-emits a
4841        // typed slot.
4842        for m in [0u32, 1, 100, 500, 1000, 1500, 2000, 12345] {
4843            let rendered = render_millicores(m);
4844            let reparsed = parse_millicores(&rendered)
4845                .unwrap_or_else(|e| panic!("render({m}) = {rendered:?} must reparse, got {e:?}"));
4846            assert_eq!(
4847                reparsed, m,
4848                "round-trip drift on {m}: rendered={rendered:?}, reparsed={reparsed}",
4849            );
4850        }
4851    }
4852
4853    #[test]
4854    fn de_millicores_rejects_leading_plus_through_serde() {
4855        // The serde-path pin: a `:limits :cpu` carrying a leading-`+`
4856        // magnitude (`"+500m"`) must fail at deserialize time, not
4857        // silently round-trip the value through `u32::from_str`'s
4858        // permissive sign-acceptance. Pin both the success-on-canonical
4859        // path (the integer form deserializes cleanly) and the
4860        // failure-on-non-canonical path (the leading-`+` form is
4861        // rejected by the codec before any validate gate runs).
4862        let json = r#"{"cpu":"+500m"}"#;
4863        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4864        let msg = err.to_string();
4865        assert!(
4866            msg.contains("non-negative integer"),
4867            "serde diagnostic must surface the integer-magnitude reason verbatim \
4868             (got {msg:?})"
4869        );
4870
4871        // The integer-form complement — same author-side intent
4872        // (500 millicores), written in the canonical form the renderer
4873        // would emit, deserializes cleanly.
4874        let json = r#"{"cpu":"500m"}"#;
4875        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4876        assert_eq!(l.cpu, Some(500));
4877    }
4878
4879    // ── canonical-form: leading-zero millicores codec gate ────────────────
4880    //
4881    // Direct successor to the `parse_byte_size` / `parse_duration` /
4882    // `supervisor::duration_codec` / `rate_limit_codec` leading-zero
4883    // arms (cea9a78 / 39762d7 / 9178904 / 4f46830) — closes the sixth
4884    // (and last) typed numeric-codec surface in caixa-core on the
4885    // integer-magnitude leading-zero axis. Every magnitude
4886    // `render_millicores` emits is the leading-zero-stripped form
4887    // (`format!("{m}m")` — no leading-zero padding), so a digit-only-
4888    // but-leading-zero magnitude parses losslessly through `u32::from_str`
4889    // and serde silently round-trips the value to a *different*
4890    // canonical string on the next emit. Pins every canonical-drift
4891    // shape on the `m`-suffix and bare-core paths, the codec-vs-
4892    // typed-validate-layer boundary (the single-byte `"0"` stays in the
4893    // codec's accepted set; `CpuZero` refuses it at validate), the
4894    // complement-side pin (every canonical leading-`[1-9]` magnitude
4895    // continues to parse cleanly), and the serde-path pin.
4896
4897    #[test]
4898    fn parse_millicores_rejects_leading_zero_magnitude_with_suffix() {
4899        // The fail-before-pass-after pin on the `m`-suffix path:
4900        // `"0500m"` parsed cleanly on no pre-gate codebase
4901        // (`u32::from_str` accepts `"0500"` → 500), then `render_millicores`
4902        // emitted `"500m"` on the next serialize — canonical-form drift.
4903        // The leading-zero arm routes the same input to
4904        // `LeadingZeroMillicoreMagnitude` with the canonical-form
4905        // remediation wording. Peer with the `parse_byte_size` `"064MiB"`
4906        // case and the `parse_duration` `"030s"` case.
4907        let err = parse_millicores("0500m").unwrap_err();
4908        assert!(
4909            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "0500"),
4910            "got {err:?}"
4911        );
4912    }
4913
4914    #[test]
4915    fn parse_millicores_rejects_multi_digit_zero_magnitude_with_suffix() {
4916        // The multi-zero pin on the `m`-suffix path: `"00m"` parses to 0
4917        // millicores at the codec, but the renderer emits `"0m"` on the
4918        // next serialize — the single canonical zero form on this axis.
4919        // The leading-zero arm rejects multi-byte leading-zero shapes
4920        // even when the value is zero; the single-byte `"0m"` /
4921        // bare-`"0"` stays in the codec's accepted set per the boundary
4922        // pin below. Peer with the `parse_byte_size` `"00MiB"` case and
4923        // the `parse_duration` `"00s"` case.
4924        let err = parse_millicores("00m").unwrap_err();
4925        assert!(
4926            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "00"),
4927            "got {err:?}"
4928        );
4929    }
4930
4931    #[test]
4932    fn parse_millicores_rejects_leading_zero_bare_core() {
4933        // The leading-zero pin on the bare-core path: `"02"` parsed to
4934        // 2 cores → 2000 millicores at the codec, but `render_millicores`
4935        // emits `"2000m"` on the next serialize — canonical-form drift.
4936        // The bare-core shorthand carries the same leading-zero discipline
4937        // as the `m`-suffix path; both authoring paths converge to the
4938        // same gate. Peer with the `parse_byte_size` bare-integer
4939        // `"01024"` case.
4940        let err = parse_millicores("02").unwrap_err();
4941        assert!(
4942            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "02"),
4943            "got {err:?}"
4944        );
4945    }
4946
4947    #[test]
4948    fn parse_millicores_rejects_leading_zero_multi_digit_with_suffix() {
4949        // The multi-digit leading-zero pin on the `m`-suffix path:
4950        // `"01500m"` parses to 1500 millicores at the codec, but the
4951        // renderer emits `"1500m"` on the next serialize — canonical-form
4952        // drift on a non-zero magnitude. Sweeps a different magnitude
4953        // shape than the `"0500m"` case so a future tightening that
4954        // misses the multi-digit-leading-zero class surfaces here.
4955        let err = parse_millicores("01500m").unwrap_err();
4956        assert!(
4957            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "01500"),
4958            "got {err:?}"
4959        );
4960    }
4961
4962    #[test]
4963    fn parse_millicores_accepts_single_zero_magnitude_at_codec_layer() {
4964        // The codec-layer / typed-validate-layer boundary pin: the
4965        // single-byte magnitude `"0"` (bare) and `"0m"` (with suffix)
4966        // round-trip losslessly through `render_millicores` (which
4967        // emits `"0m"` for 0 millicores), so they stay in the codec's
4968        // accepted set. The downstream `CpuZero` gate refuses
4969        // semantic-zero authoring at the typed-validate layer above —
4970        // the diagnostic partitioning between canonical-form drift
4971        // (the leading-zero arm) and semantic-zero (the `CpuZero` gate)
4972        // remains stable. Same codec-layer / typed-validate-layer
4973        // partition the peer codecs preserve.
4974        assert_eq!(parse_millicores("0").unwrap(), 0);
4975        assert_eq!(parse_millicores("0m").unwrap(), 0);
4976    }
4977
4978    #[test]
4979    fn parse_millicores_accepts_canonical_magnitude_with_leading_one() {
4980        // The complement-side pin: every canonical leading-`[1-9]`
4981        // magnitude continues to parse cleanly through the leading-zero
4982        // arm, on both the `m`-suffix and bare-core paths. Sweep the
4983        // canonical values the renderer emits across the unit-multiplier
4984        // boundary (sub-core, single-core, multi-core) so a future
4985        // tightening cannot drift into rejecting valid canonical
4986        // magnitudes. Same complement-side discipline the peer
4987        // `parse_byte_size_accepts_canonical_magnitude_with_leading_one`
4988        // and `parse_duration_accepts_canonical_magnitude_with_leading_one`
4989        // pins enforce on the sibling codecs.
4990        assert_eq!(parse_millicores("1m").unwrap(), 1);
4991        assert_eq!(parse_millicores("500m").unwrap(), 500);
4992        assert_eq!(parse_millicores("1500m").unwrap(), 1500);
4993        assert_eq!(parse_millicores("9000m").unwrap(), 9000);
4994        assert_eq!(parse_millicores("1").unwrap(), 1000);
4995        assert_eq!(parse_millicores("2").unwrap(), 2000);
4996        assert_eq!(parse_millicores("9").unwrap(), 9000);
4997    }
4998
4999    #[test]
5000    fn de_millicores_rejects_leading_zero_through_serde() {
5001        // The serde-path pin: a `:limits :cpu` carrying a leading-zero
5002        // magnitude (`"0500m"`) must fail at deserialize time, not
5003        // silently round-trip the value through `u32::from_str`'s
5004        // leading-zero-permissive accepting. Pin both the success-on-
5005        // canonical path (the leading-zero-stripped form deserializes
5006        // cleanly) and the failure-on-non-canonical path (the leading-
5007        // zero form is rejected by the codec before any validate gate
5008        // runs). Peer with the
5009        // `de_byte_size_rejects_leading_zero_through_serde` and
5010        // `de_duration_rejects_leading_zero_through_serde` pins on the
5011        // sibling codecs.
5012        let json = r#"{"cpu":"0500m"}"#;
5013        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
5014        let msg = err.to_string();
5015        assert!(
5016            msg.contains("leading zero"),
5017            "serde diagnostic must surface the leading-zero reason verbatim \
5018             (got {msg:?})"
5019        );
5020
5021        // The integer-form complement — same author-side intent
5022        // (500 millicores), written in the canonical form the renderer
5023        // would emit, deserializes cleanly.
5024        let json = r#"{"cpu":"500m"}"#;
5025        let l: LimitsSpec = serde_json::from_str(json).unwrap();
5026        assert_eq!(l.cpu, Some(500));
5027    }
5028
5029    // ── canonical-form: whitespace-rejection millicores codec gate ────────
5030    //
5031    // Direct successor to the `parse_byte_size` (24a8ad4), `parse_duration`
5032    // (ebc3a75), `supervisor::duration_codec` (a7ae622), and
5033    // `rate_limit_codec` (1ad7755) whitespace-rejection arms — closes the
5034    // fifth (and last) typed-magnitude codec surface in caixa-core on the
5035    // ASCII-whitespace axis. The pre-gate top-level `s.trim()` at parse
5036    // entry and the per-part `magnitude.trim()` calls silently ate leading
5037    // / trailing / internal whitespace, so every whitespace-carrying shape
5038    // parsed to the same millicore value and round-tripped through
5039    // `render_millicores` to a *different* canonical string on next
5040    // serialize — the same canonical-form-drift class the leading-`+` /
5041    // fractional / leading-zero arms already close on this codec.
5042
5043    #[test]
5044    fn parse_millicores_rejects_leading_whitespace() {
5045        // `" 500m"` — the canonical paste-from-aligned-doc / YAML-quoted-
5046        // plain-scalar footgun. Before this gate the top-level `s.trim()`
5047        // at parse entry silently ate the leading space and parsed the
5048        // value to 500 millicores, round-tripping to `"500m"` on next
5049        // serialize.
5050        let err = parse_millicores(" 500m").unwrap_err();
5051        assert!(
5052            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == " 500m" && byte == 0x20),
5053            "got {err:?}"
5054        );
5055        let msg = err.to_string();
5056        assert!(
5057            msg.contains("whitespace byte 0x20"),
5058            "diagnostic must surface the offending byte verbatim (got {msg:?})"
5059        );
5060        assert!(
5061            msg.contains("THEORY.md"),
5062            "diagnostic must cite the render-determinism contract (got {msg:?})"
5063        );
5064    }
5065
5066    #[test]
5067    fn parse_millicores_rejects_trailing_whitespace() {
5068        // `"500m "` — the canonical shell-history trailing-space footgun.
5069        let err = parse_millicores("500m ").unwrap_err();
5070        assert!(
5071            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "500m " && byte == 0x20),
5072            "got {err:?}"
5073        );
5074    }
5075
5076    #[test]
5077    fn parse_millicores_rejects_internal_whitespace_between_magnitude_and_unit() {
5078        // `"500 m"` — the typographically-spaced author shape (the same
5079        // idiom every prose reference to millicores renders as). Before
5080        // this gate the per-part `magnitude.trim()` silently ate the
5081        // internal space and parsed the value to 500 millicores.
5082        let err = parse_millicores("500 m").unwrap_err();
5083        assert!(
5084            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "500 m" && byte == 0x20),
5085            "got {err:?}"
5086        );
5087    }
5088
5089    #[test]
5090    fn parse_millicores_rejects_tab_byte() {
5091        // `"\t500m"` — the paste-from-indented-doc / YAML-block-scalar tab
5092        // footgun. Pins the tab (`0x09`) arm alongside the space arm above.
5093        let err = parse_millicores("\t500m").unwrap_err();
5094        assert!(
5095            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "\t500m" && byte == 0x09),
5096            "got {err:?}"
5097        );
5098    }
5099
5100    #[test]
5101    fn parse_millicores_rejects_trailing_newline() {
5102        // `"500m\n"` — the multi-line-paste footgun where a trailing LF
5103        // byte survives the paste. Pins the LF member (`0x0A`) of the
5104        // `is_ascii_whitespace` set.
5105        let err = parse_millicores("500m\n").unwrap_err();
5106        assert!(
5107            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "500m\n" && byte == 0x0a),
5108            "got {err:?}"
5109        );
5110    }
5111
5112    #[test]
5113    fn parse_millicores_accepts_whitespace_free_canonical_forms() {
5114        // The complement-side pin: every canonical whitespace-free
5115        // authoring form the renderer emits stays accepted post-gate.
5116        // Sweep the canonical `m`-suffix path plus the bare-core shorthand
5117        // so a future tightening of the whitespace arm that over-fires on
5118        // the accepted set surfaces here as a test failure.
5119        assert_eq!(parse_millicores("500m").unwrap(), 500);
5120        assert_eq!(parse_millicores("2000m").unwrap(), 2000);
5121        assert_eq!(parse_millicores("1m").unwrap(), 1);
5122        assert_eq!(parse_millicores("0m").unwrap(), 0);
5123        assert_eq!(parse_millicores("2").unwrap(), 2000);
5124        assert_eq!(parse_millicores("0").unwrap(), 0);
5125    }
5126
5127    #[test]
5128    fn de_millicores_rejects_whitespace_through_serde() {
5129        // The serde-path pin: a `:limits :cpu` carrying a whitespace-byte-
5130        // carrying value (`" 500m"`) must fail at deserialize time, not
5131        // silently round-trip the value through the pre-existing top-level
5132        // `s.trim()`. Peer with the
5133        // `de_byte_size_rejects_whitespace_through_serde` and
5134        // `de_duration_rejects_whitespace_through_serde` pins on the
5135        // sibling codecs.
5136        let json = r#"{"cpu":" 500m"}"#;
5137        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
5138        let msg = err.to_string();
5139        assert!(
5140            msg.contains("whitespace byte"),
5141            "serde diagnostic must surface the whitespace reason verbatim (got {msg:?})"
5142        );
5143        assert!(
5144            msg.contains("0x20"),
5145            "serde diagnostic must name the offending byte (got {msg:?})"
5146        );
5147
5148        // The whitespace-free complement — same author-side intent,
5149        // written in the canonical form the renderer would emit,
5150        // deserializes cleanly.
5151        let json = r#"{"cpu":"500m"}"#;
5152        let l: LimitsSpec = serde_json::from_str(json).unwrap();
5153        assert_eq!(l.cpu, Some(500));
5154    }
5155
5156    // ── canonical-form: non-ASCII Unicode `White_Space` millicores gate ───
5157    //
5158    // Direct successor to the ASCII-whitespace arm above — closes the
5159    // strictly-complementary class the byte-scan cannot see. `str::trim`
5160    // uses `char::is_whitespace` (Unicode `White_Space`, strictly wider
5161    // than the ASCII byte set); a leading / trailing / internal NBSP
5162    // (`\u{00A0}`) / LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
5163    // survives the byte-scan but is silently stripped by the top-level
5164    // trim, drifting to canonical `"500m"` on round-trip. Pins the arm
5165    // through the lifted [`crate::render::find_non_ascii_whitespace_char`]
5166    // predicate — the same shared predicate 1b75b38 landed on the four
5167    // peer typed-magnitude codecs, extended here to the fifth.
5168
5169    #[test]
5170    fn parse_millicores_rejects_leading_nbsp() {
5171        // NBSP (`\u{00A0}` = UTF-8 `0xC2 0xA0`) — the paste-from-typography
5172        // / paste-from-word-processor footgun. Before this arm landed the
5173        // byte-scan missed it (neither `0xC2` nor `0xA0` is
5174        // `is_ascii_whitespace`) and `str::trim` at parse entry silently
5175        // stripped it, yielding the same 500 millicores as the whitespace-
5176        // free canonical form and drifting to `"500m"` on next serialize.
5177        let s = "\u{00A0}500m";
5178        let err = parse_millicores(s).unwrap_err();
5179        assert!(
5180            matches!(err, LimitsError::NonAsciiWhitespaceInMillicores { ref value, ch, codepoint } if value == s && ch == '\u{00A0}' && codepoint == 0x00A0),
5181            "got {err:?}"
5182        );
5183        let msg = err.to_string();
5184        assert!(
5185            msg.contains("U+00A0"),
5186            "diagnostic must surface the codepoint verbatim (got {msg:?})"
5187        );
5188        assert!(
5189            msg.contains("THEORY.md"),
5190            "diagnostic must cite the render-determinism contract (got {msg:?})"
5191        );
5192    }
5193
5194    #[test]
5195    fn parse_millicores_rejects_internal_em_space() {
5196        // EM-SPACE (`\u{2003}`) between magnitude and unit — pins the arm
5197        // on an internal-position non-NBSP Unicode `White_Space` member.
5198        let s = "500\u{2003}m";
5199        let err = parse_millicores(s).unwrap_err();
5200        assert!(
5201            matches!(err, LimitsError::NonAsciiWhitespaceInMillicores { ref value, ch, codepoint } if value == s && ch == '\u{2003}' && codepoint == 0x2003),
5202            "got {err:?}"
5203        );
5204    }
5205
5206    #[test]
5207    fn parse_millicores_rejects_trailing_line_separator() {
5208        // LINE SEPARATOR (`\u{2028}`) — the canonical paste-from-web-doc
5209        // footgun (many rendering engines insert `\u{2028}` at soft-wrap
5210        // boundaries in RTF/HTML → plain text conversion). Pins the arm on
5211        // a trailing-position Unicode `White_Space` member.
5212        let s = "500m\u{2028}";
5213        let err = parse_millicores(s).unwrap_err();
5214        assert!(
5215            matches!(err, LimitsError::NonAsciiWhitespaceInMillicores { ref value, ch, codepoint } if value == s && ch == '\u{2028}' && codepoint == 0x2028),
5216            "got {err:?}"
5217        );
5218    }
5219
5220    #[test]
5221    fn parse_millicores_accepts_ascii_only_canonical_forms_after_unicode_arm() {
5222        // Positive-control pin: every ASCII-only canonical form the
5223        // renderer emits stays accepted through the new arm — the lifted
5224        // predicate is a strict no-op on ASCII input.
5225        assert_eq!(parse_millicores("500m").unwrap(), 500);
5226        assert_eq!(parse_millicores("2000m").unwrap(), 2000);
5227        assert_eq!(parse_millicores("1m").unwrap(), 1);
5228        assert_eq!(parse_millicores("2").unwrap(), 2000);
5229    }
5230
5231    // ── canonical-form: integer-millisecond :wall-clock gate ──────────────
5232    //
5233    // The peer typed-`Duration` axes routed through
5234    // `supervisor::duration_codec` (`:politicas :timeout` a4ae535,
5235    // `:circuit-breaker :window` a4ae535) already gate on
5236    // `is_integer_millisecond_duration` because the codec's `render`
5237    // truncates to `as_millis()` and parses with integer-ms granularity;
5238    // this crate's in-module `render_duration` / `parse_duration` pair
5239    // carries the same `as_millis()`-truncation shape, so the same sub-
5240    // millisecond-residue footgun lived on this axis until this gate
5241    // landed. The tests below pin the fail-before-pass-after boundary,
5242    // the diagnostic shape, the cross-arm zero-then-canonical ordering
5243    // matching the `:politicas` peer, the integer-ms happy-path sweep,
5244    // and the codec round-trip property (every validated `wall_clock`
5245    // survives serialize → deserialize equality).
5246
5247    #[test]
5248    fn validate_rejects_sub_millisecond_wall_clock() {
5249        // The fail-before-pass-after pin: a programmatic
5250        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5251        // validate on every pre-gate codebase, then truncated to
5252        // `as_millis() == 1` on first serialize — `render_duration`
5253        // emits `"1ms"`, the codec parses it back to
5254        // `Duration::from_millis(1)` = 1_000_000 ns, the typed
5255        // `wall_clock` no longer matches its rendered form.
5256        let l = LimitsSpec {
5257            wall_clock: Some(Duration::from_micros(1500)),
5258            ..Default::default()
5259        };
5260        match l.validate().unwrap_err() {
5261            LimitsError::WallClockNotCanonical { wall_clock } => {
5262                assert_eq!(wall_clock, Duration::from_micros(1500));
5263            }
5264            other => panic!("expected WallClockNotCanonical, got {other:?}"),
5265        }
5266    }
5267
5268    #[test]
5269    fn validate_rejects_one_nanosecond_wall_clock() {
5270        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5271        // (so `WallClockZero` doesn't fire) but `as_millis() == 0`, so
5272        // `render_duration` emits the literal `"0s"` — the next serde
5273        // round-trip would parse back to `Duration::ZERO`, which the
5274        // `WallClockZero` arm then rejects on re-validate. The
5275        // canonical-form gate at this layer surfaces a self-locating
5276        // diagnostic naming the offending Duration verbatim rather
5277        // than a downstream `WallClockZero` whose remediation points
5278        // at omitting the slot.
5279        let l = LimitsSpec {
5280            wall_clock: Some(Duration::from_nanos(1)),
5281            ..Default::default()
5282        };
5283        match l.validate().unwrap_err() {
5284            LimitsError::WallClockNotCanonical { wall_clock } => {
5285                assert_eq!(wall_clock, Duration::from_nanos(1));
5286            }
5287            other => panic!("expected WallClockNotCanonical, got {other:?}"),
5288        }
5289    }
5290
5291    #[test]
5292    fn validate_rejects_nanosecond_past_canonical_boundary() {
5293        // The 1-ns-past-1ms boundary case: a `Duration` carrying
5294        // 1_000_001 ns is structurally past the integer-ms granularity
5295        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec
5296        // round-trip would truncate to `1ms` and the consumer would
5297        // observe a 1-ns drift on every emit. Same boundary the peer
5298        // `is_integer_millisecond_duration_predicate_tracks_codec` test
5299        // in aplicacao.rs pins for the `:politicas` axes.
5300        let w = Duration::from_nanos(1_000_001);
5301        let l = LimitsSpec {
5302            wall_clock: Some(w),
5303            ..Default::default()
5304        };
5305        assert_eq!(
5306            l.validate().unwrap_err(),
5307            LimitsError::WallClockNotCanonical { wall_clock: w }
5308        );
5309    }
5310
5311    #[test]
5312    fn validate_accepts_integer_millisecond_wall_clock_values() {
5313        // The positive-control sweep: every `Duration` the codec can
5314        // round-trip losslessly — the canonical `<integer>{ms,s,m,h}`
5315        // set the `render_duration` / `parse_duration` pair emits and
5316        // accepts — passes `validate` without surfacing the new
5317        // canonical-form arm. Mirrors
5318        // `accepts_policy_retries_typical_values` /
5319        // `accepts_circuit_breaker_max_failures_typical_values` on
5320        // sibling axes.
5321        for w in [
5322            Duration::from_millis(1),
5323            Duration::from_millis(500),
5324            Duration::from_millis(1500),
5325            Duration::from_secs(1),
5326            Duration::from_secs(30),
5327            Duration::from_secs(60),
5328            Duration::from_secs(120),
5329            Duration::from_secs(3600),
5330        ] {
5331            let l = LimitsSpec {
5332                wall_clock: Some(w),
5333                ..Default::default()
5334            };
5335            l.validate()
5336                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5337        }
5338    }
5339
5340    #[test]
5341    fn validate_wall_clock_zero_takes_precedence_over_canonical_gate() {
5342        // Cross-arm ordering pin: `Duration::ZERO` has
5343        // `subsec_nanos() == 0` and would otherwise pass the
5344        // canonical-form arm — the zero-floor arm must fire first so
5345        // the more self-locating `WallClockZero` diagnostic (with its
5346        // omit-axis remediation directly named) leads. Same posture
5347        // every peer zero-then-shape gate uses
5348        // (`PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5349        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5350        let l = LimitsSpec {
5351            wall_clock: Some(Duration::ZERO),
5352            ..Default::default()
5353        };
5354        assert_eq!(l.validate().unwrap_err(), LimitsError::WallClockZero);
5355    }
5356
5357    #[test]
5358    fn wall_clock_canonical_diagnostic_carries_offending_duration() {
5359        // Diagnostic-shape pin: the canonical-form arm names the
5360        // offending `Duration` verbatim so the author's grep lands on
5361        // the field's value, not a generic "duration not canonical"
5362        // message. Same shape every other typed-cap arm on this
5363        // surface carries (`MemoryExceedsWasm32Cap` carries the
5364        // offending byte count verbatim, `PolicyRetriesExceedsCap`
5365        // carries the offending retry count verbatim,
5366        // `PolicyBreakerMaxFailuresExceedsCap` carries the offending
5367        // u32 verbatim).
5368        let w = Duration::from_micros(500);
5369        let l = LimitsSpec {
5370            wall_clock: Some(w),
5371            ..Default::default()
5372        };
5373        let err = l.validate().unwrap_err();
5374        let msg = err.to_string();
5375        assert!(
5376            msg.contains("500"),
5377            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5378        );
5379    }
5380
5381    #[test]
5382    fn wall_clock_validated_value_round_trips_through_codec() {
5383        // The structural property the canonical-ms gate enforces:
5384        // every `LimitsSpec::wall_clock` past `LimitsSpec::validate`
5385        // round-trips losslessly through the in-module duration codec
5386        // (serialize → string → deserialize → equal value). Pin this
5387        // end-to-end so a future change to either side (the validate
5388        // gate's accepted granularity, the codec's parse/render unit
5389        // set) that breaks the alignment surfaces here. Peer of
5390        // `policy_timeout_validated_value_round_trips_through_codec` /
5391        // `circuit_breaker_window_validated_value_round_trips_through_codec`
5392        // on the sibling `:politicas` axes.
5393        for w in [
5394            Duration::from_millis(1),
5395            Duration::from_millis(1500),
5396            Duration::from_secs(30),
5397            Duration::from_secs(3600),
5398        ] {
5399            let l = LimitsSpec {
5400                wall_clock: Some(w),
5401                ..Default::default()
5402            };
5403            l.validate().unwrap();
5404            let json = serde_json::to_string(&l).unwrap();
5405            let back: LimitsSpec = serde_json::from_str(&json).unwrap();
5406            assert_eq!(
5407                back.wall_clock, l.wall_clock,
5408                "every validated :wall-clock must round-trip losslessly through the codec"
5409            );
5410        }
5411    }
5412
5413    // ── value-shape: :wall-clock upper bound — 1h ceiling ──────────────────
5414    //
5415    // The third typed-`Duration` axis brought to the uniform top edge
5416    // `LIMITS_WALL_CLOCK_MAX` = 1h established by the prior cap lifts
5417    // on `:politicas :timeout` (POLICY_TIMEOUT_MAX) and
5418    // `:politicas :circuit-breaker :window` (POLICY_BREAKER_WINDOW_MAX).
5419    // Mirrors the test discipline those peers carry: the
5420    // fail-before-pass-after pin, the 1ms-boundary pin, the
5421    // far-above-cap sweep (24h / 7d / ~11.5d — the values a
5422    // `(:wall-clock "24h")` typo or copy-paste typically lands), the
5423    // inclusive-at-cap positive control, the production-band positive-
5424    // control sweep, the cross-arm zero-then-cap and
5425    // canonical-then-cap ordering pins, the diagnostic-shape pin
5426    // carrying the offending `Duration` verbatim, and the cap-value
5427    // literal-identity + codec-round-trip pins anchoring the constant
5428    // to the codec's largest emitted unit and to its peer constants.
5429
5430    #[test]
5431    fn validate_rejects_wall_clock_above_cap() {
5432        // The fail-before-pass-after pin: 3601s = 1h + 1s is
5433        // structurally one canonical-tick past the
5434        // [`LIMITS_WALL_CLOCK_MAX`] ceiling (1h = 3600s) — an
5435        // integer-millisecond magnitude the canonical-form arm above
5436        // accepts cleanly, that the in-module duration codec
5437        // round-trips losslessly as `"3601s"`, and that silently
5438        // passed validate on every pre-gate codebase because the typed
5439        // slot's only checks were the zero-floor and canonical-form
5440        // arms. The wasm-engine consuming the value (the M2.5
5441        // `wasm-engine`'s epoch-deadline cancellation hook, the future
5442        // caixa-helm `pleme-computeunit` chart's `:limits` value
5443        // mapping) reaches for a `Duration` so long no realistic
5444        // synchronous wasm call hits it, far from the source
5445        // caixa.lisp.
5446        let w = LIMITS_WALL_CLOCK_MAX + Duration::from_secs(1);
5447        let l = LimitsSpec {
5448            wall_clock: Some(w),
5449            ..Default::default()
5450        };
5451        assert_eq!(
5452            l.validate().unwrap_err(),
5453            LimitsError::WallClockExceedsCap { wall_clock: w }
5454        );
5455    }
5456
5457    #[test]
5458    fn validate_rejects_wall_clock_one_millisecond_above_cap() {
5459        // Boundary case: exactly 1ms past the cap (the granularity the
5460        // canonical-form gate enforces). Catches a future "strictly
5461        // less than" half-measure and pins the diagnostic to name the
5462        // offending `Duration` verbatim. Peer of
5463        // `rejects_policy_timeout_one_millisecond_above_cap` /
5464        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5465        // on the sibling typed-`Duration` axes' top edges.
5466        let w = LIMITS_WALL_CLOCK_MAX + Duration::from_millis(1);
5467        let l = LimitsSpec {
5468            wall_clock: Some(w),
5469            ..Default::default()
5470        };
5471        assert_eq!(
5472            l.validate().unwrap_err(),
5473            LimitsError::WallClockExceedsCap { wall_clock: w }
5474        );
5475    }
5476
5477    #[test]
5478    fn validate_rejects_wall_clock_far_above_cap() {
5479        // The "obvious authoring footgun" case: a `(:wall-clock "24h")`
5480        // or `(:wall-clock "7d")` — values the canonical-form arm
5481        // accepts as integer-millisecond magnitudes, the codec
5482        // round-trips losslessly through serde, but the wasm-engine
5483        // cannot honor as a meaningful per-call deadline. Until this
5484        // gate landed validate accepted them. Pin the common
5485        // above-cap values (24h, 7d, ~11.5d) so a future relaxation
5486        // that drops the upper bound surfaces here.
5487        for w in [
5488            Duration::from_secs(86_400),    // 24h
5489            Duration::from_secs(604_800),   // 7d
5490            Duration::from_secs(1_000_000), // ~11.5 days
5491        ] {
5492            let l = LimitsSpec {
5493                wall_clock: Some(w),
5494                ..Default::default()
5495            };
5496            assert_eq!(
5497                l.validate().unwrap_err(),
5498                LimitsError::WallClockExceedsCap { wall_clock: w }
5499            );
5500        }
5501    }
5502
5503    #[test]
5504    fn validate_accepts_wall_clock_at_cap() {
5505        // The boundary value — exactly [`LIMITS_WALL_CLOCK_MAX`] (1h)
5506        // — must validate. The cap is inclusive on the top edge,
5507        // matching the [`crate::POLICY_TIMEOUT_MAX`] /
5508        // [`crate::POLICY_BREAKER_WINDOW_MAX`] /
5509        // [`LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the sibling
5510        // capped axes. Pin the boundary explicitly so a future
5511        // off-by-one tightening (`>= LIMITS_WALL_CLOCK_MAX` instead of
5512        // `>`) surfaces here as a test failure rather than a silent
5513        // contract narrowing.
5514        let l = LimitsSpec {
5515            wall_clock: Some(LIMITS_WALL_CLOCK_MAX),
5516            ..Default::default()
5517        };
5518        l.validate()
5519            .expect("wall_clock == LIMITS_WALL_CLOCK_MAX must validate");
5520    }
5521
5522    #[test]
5523    fn validate_accepts_wall_clock_typical_values() {
5524        // The documented per-request production-playbook band positive-
5525        // control sweep — every value Envoy / Istio / Linkerd / AWS
5526        // App Mesh / Kubernetes ingress-nginx recommend
5527        // (1ms..=3600s) must pass, plus a sweep through the
5528        // long-running-workflow band (5m, 15m, 30m, 1h) the cap
5529        // accepts. Mirrors `accepts_policy_timeout_typical_values` on
5530        // the sibling `:politicas :timeout` axis.
5531        for w in [
5532            Duration::from_millis(1),
5533            Duration::from_millis(500),
5534            Duration::from_secs(1),
5535            Duration::from_secs(10),
5536            Duration::from_secs(15), // Envoy default
5537            Duration::from_secs(30),
5538            Duration::from_secs(60),  // AWS App Mesh typical
5539            Duration::from_secs(300), // 5m
5540            Duration::from_secs(900), // 15m
5541            Duration::from_secs(1800),
5542            Duration::from_secs(3600), // exactly 1h, the cap
5543        ] {
5544            let l = LimitsSpec {
5545                wall_clock: Some(w),
5546                ..Default::default()
5547            };
5548            l.validate()
5549                .unwrap_or_else(|e| panic!("wall_clock={w:?} must validate; got {e:?}"));
5550        }
5551    }
5552
5553    #[test]
5554    fn wall_clock_zero_takes_precedence_over_cap() {
5555        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5556        // outside both `>= 1ms` (zero-floor) and `<= LIMITS_WALL_CLOCK_MAX`
5557        // (cap), but the zero-floor diagnostic is the more
5558        // self-locating one (it directly names the omit-axis
5559        // remediation), so the validate gate must fire on zero first.
5560        // Same shape every other zero-then-shape ordering on this
5561        // surface uses (`MemoryZero` then `MemoryExceedsWasm32Cap`,
5562        // `PolicyTimeoutZero` then `PolicyTimeoutExceedsCap`).
5563        let l = LimitsSpec {
5564            wall_clock: Some(Duration::ZERO),
5565            ..Default::default()
5566        };
5567        assert_eq!(
5568            l.validate().unwrap_err(),
5569            LimitsError::WallClockZero,
5570            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5571        );
5572    }
5573
5574    #[test]
5575    fn wall_clock_canonical_takes_precedence_over_cap() {
5576        // The cross-arm ordering pin: a `Duration` that is *both*
5577        // sub-millisecond (non-canonical-form) and structurally above
5578        // the cap surfaces the canonical-form diagnostic first,
5579        // because the round-trip-shape break is the more fundamental
5580        // issue (the value can't even round-trip through the codec, so
5581        // the cap diagnostic naming `1ms..=1h` would be misleading —
5582        // there's no integer-ms form of the offending value). Pin the
5583        // order so a future refactor that reorders the arms surfaces
5584        // here as a test failure rather than a silent diagnostic
5585        // regression. Peer of
5586        // `policy_timeout_canonical_takes_precedence_over_cap`.
5587        let w = LIMITS_WALL_CLOCK_MAX + Duration::from_nanos(1);
5588        let l = LimitsSpec {
5589            wall_clock: Some(w),
5590            ..Default::default()
5591        };
5592        assert_eq!(
5593            l.validate().unwrap_err(),
5594            LimitsError::WallClockNotCanonical { wall_clock: w },
5595            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5596        );
5597    }
5598
5599    #[test]
5600    fn wall_clock_cap_diagnostic_carries_offending_value() {
5601        // The diagnostic-shape pin: the offending `Duration` is
5602        // carried verbatim into the
5603        // [`LimitsError::WallClockExceedsCap`] variant so the surfaced
5604        // error message names the value the author wrote, not just
5605        // the cap. Same self-locating diagnostic shape every other
5606        // typed-cap arm on this surface carries
5607        // (`MemoryExceedsWasm32Cap` carries the offending byte count
5608        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5609        // `Duration` verbatim).
5610        let w = Duration::from_secs(7200); // 2h
5611        let l = LimitsSpec {
5612            wall_clock: Some(w),
5613            ..Default::default()
5614        };
5615        let err = l.validate().unwrap_err();
5616        assert!(
5617            matches!(err, LimitsError::WallClockExceedsCap { wall_clock } if wall_clock == w),
5618            "got {err:?}"
5619        );
5620        let msg = err.to_string();
5621        assert!(
5622            msg.contains("7200"),
5623            ":limits :wall-clock cap diagnostic must carry the offending value verbatim (got: {msg})"
5624        );
5625    }
5626
5627    #[test]
5628    fn wall_clock_cap_pins_canonical_value() {
5629        // The [`LIMITS_WALL_CLOCK_MAX`] constant pins the value at
5630        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5631        // shared duration codec emits as a clean canonical string
5632        // (`"<n>h"`). Pinning the literal value here surfaces a future
5633        // drift (a relaxation to 24h, a tightening to 5m) as a
5634        // deliberate test edit, not a silent contract narrowing.
5635        //
5636        // The three typed-`Duration` caps on the validation surface
5637        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5638        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker) share a
5639        // single uniform top edge at the codec's largest emitted unit
5640        // — a structural-property invariant the equality assertions
5641        // here enshrine, so a future drift on any of the three
5642        // surfaces as a deliberate test edit. Same shape every other
5643        // typed-cap value pin uses
5644        // (`policy_timeout_cap_pins_canonical_value`,
5645        // `circuit_breaker_window_cap_pins_canonical_value`).
5646        assert_eq!(LIMITS_WALL_CLOCK_MAX, Duration::from_secs(3600));
5647        assert_eq!(LIMITS_WALL_CLOCK_MAX.as_millis(), 3_600_000);
5648        assert_eq!(LIMITS_WALL_CLOCK_MAX, crate::POLICY_TIMEOUT_MAX);
5649        assert_eq!(LIMITS_WALL_CLOCK_MAX, crate::POLICY_BREAKER_WINDOW_MAX);
5650    }
5651
5652    #[test]
5653    fn wall_clock_cap_value_round_trips_through_codec() {
5654        // The codec round-trip property the cap arm preserves: the
5655        // [`LIMITS_WALL_CLOCK_MAX`] constant itself round-trips through
5656        // the in-module duration codec — every value at the cap
5657        // renders to a clean canonical string (`"1h"`) and parses back
5658        // to the same `Duration`. Pin this so a future drift between
5659        // the cap constant and the codec's largest emitted unit
5660        // surfaces here. Same shape every other typed boundary pin on
5661        // this surface uses
5662        // (`wasm32_memory_cap_matches_parsed_4_gib`,
5663        // `policy_timeout_cap_value_round_trips_through_codec`).
5664        let l = LimitsSpec {
5665            wall_clock: Some(LIMITS_WALL_CLOCK_MAX),
5666            ..Default::default()
5667        };
5668        let json = serde_json::to_string(&l).unwrap();
5669        assert!(
5670            json.contains("\"1h\""),
5671            "the LIMITS_WALL_CLOCK_MAX value must render to the canonical \"1h\" form (got: {json})"
5672        );
5673        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
5674        assert_eq!(back.wall_clock, Some(LIMITS_WALL_CLOCK_MAX));
5675        l.validate()
5676            .expect("LIMITS_WALL_CLOCK_MAX itself must pass validate");
5677    }
5678
5679    // ── value-shape: :cpu upper bound — 128-core schedulability ceiling ─────
5680    //
5681    // The third `LimitsSpec` axis brought to a top-edge cap, peer to
5682    // the `:memory` wasm32 ceiling and the `:wall-clock` 1h ceiling.
5683    // Mirrors the test discipline those peers carry: the
5684    // fail-before-pass-after pin, the one-millicore-boundary pin, the
5685    // far-above-cap sweep, the inclusive-at-cap positive control, the
5686    // production-band positive-control sweep, the cross-arm zero-then-
5687    // cap ordering pin, the diagnostic-shape pin carrying the offending
5688    // value verbatim, and the cap-value literal-identity + codec
5689    // round-trip pins anchoring the constant.
5690
5691    #[test]
5692    fn validate_rejects_cpu_above_cap() {
5693        // The fail-before-pass-after pin: 128_001m = 128 cores + 1
5694        // millicore is structurally one canonical-tick past the
5695        // [`LIMITS_CPU_MILLICORES_MAX`] ceiling — a `u32` magnitude the
5696        // millicore codec round-trips losslessly as `"128001m"`, and
5697        // that silently passed validate on every pre-gate codebase
5698        // because the typed slot's only check was the zero-floor arm.
5699        // The Kubernetes scheduler consuming the value (via the
5700        // `pleme-computeunit` chart's `resources.requests.cpu`
5701        // projection) cannot bind the pod to any node, far from the
5702        // source caixa.lisp.
5703        let m = LIMITS_CPU_MILLICORES_MAX + 1;
5704        let l = LimitsSpec {
5705            cpu: Some(m),
5706            ..Default::default()
5707        };
5708        assert_eq!(
5709            l.validate().unwrap_err(),
5710            LimitsError::CpuExceedsCap { millicores: m }
5711        );
5712    }
5713
5714    #[test]
5715    fn validate_rejects_cpu_far_above_cap() {
5716        // The "obvious authoring footgun" case: a `(:cpu "1000000m")`
5717        // (1000 cores) or `(:cpu "4294967295m")` (≈ u32::MAX) — values
5718        // the millicore codec accepts cleanly, the codec round-trips
5719        // losslessly through serde, but the Kubernetes scheduler
5720        // cannot bind to any node. Until this gate landed validate
5721        // accepted them. Pin the common above-cap values (1000 cores,
5722        // 10_000 cores, u32::MAX) so a future relaxation that drops
5723        // the upper bound surfaces here. Peer of
5724        // `validate_rejects_memory_8_gib` /
5725        // `validate_rejects_wall_clock_far_above_cap`.
5726        for m in [1_000_000_u32, 10_000_000, u32::MAX] {
5727            let l = LimitsSpec {
5728                cpu: Some(m),
5729                ..Default::default()
5730            };
5731            assert_eq!(
5732                l.validate().unwrap_err(),
5733                LimitsError::CpuExceedsCap { millicores: m }
5734            );
5735        }
5736    }
5737
5738    #[test]
5739    fn validate_accepts_cpu_at_cap() {
5740        // The boundary value — exactly [`LIMITS_CPU_MILLICORES_MAX`]
5741        // (128 cores = 128_000m) — must validate. The cap is inclusive
5742        // on the top edge, matching the discipline on every sibling
5743        // capped axis ([`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5744        // [`LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
5745        // [`crate::POLICY_BREAKER_WINDOW_MAX`],
5746        // [`crate::POLICY_RATE_LIMIT_MAX`]). Pin the boundary
5747        // explicitly so a future off-by-one tightening
5748        // (`>= LIMITS_CPU_MILLICORES_MAX` instead of `>`) surfaces here
5749        // as a test failure rather than a silent contract narrowing.
5750        let l = LimitsSpec {
5751            cpu: Some(LIMITS_CPU_MILLICORES_MAX),
5752            ..Default::default()
5753        };
5754        l.validate()
5755            .expect("cpu == LIMITS_CPU_MILLICORES_MAX must validate");
5756    }
5757
5758    #[test]
5759    fn validate_accepts_cpu_typical_values() {
5760        // The documented production-playbook band positive-control
5761        // sweep — every value the canonical caixa Servico runs in
5762        // (100m..=2000m) must pass, plus a sweep through the larger
5763        // burstable / multi-component-host band (4000m, 8000m, 16000m,
5764        // 32000m, 64000m, 128000m) the cap accepts. Mirrors
5765        // `accepts_wall_clock_typical_values` on the sibling
5766        // `:wall-clock` axis.
5767        for m in [
5768            1_u32,   // smallest non-zero
5769            100,     // typical small worker
5770            500,     // canonical test default (peer to limits/flux/helm)
5771            1_000,   // 1 core, single-threaded wasm32 saturation
5772            2_000,   // 2 cores
5773            4_000,   // typical burstable
5774            8_000,   // upper realistic per-Servico band
5775            16_000,  // documented heavy-Servico ceiling
5776            32_000,  // wide-node multi-component-host
5777            64_000,  // half the cap
5778            128_000, // exactly at cap
5779        ] {
5780            let l = LimitsSpec {
5781                cpu: Some(m),
5782                ..Default::default()
5783            };
5784            l.validate()
5785                .unwrap_or_else(|e| panic!("cpu={m}m must validate; got {e:?}"));
5786        }
5787    }
5788
5789    #[test]
5790    fn cpu_zero_takes_precedence_over_cap() {
5791        // The cross-arm ordering pin: `Some(0)` is structurally outside
5792        // both `>= 1` (zero-floor) and `<= LIMITS_CPU_MILLICORES_MAX`
5793        // (cap), but the zero-floor diagnostic is the more
5794        // self-locating one (it directly names the omit-axis
5795        // remediation), so the validate gate must fire on zero first.
5796        // Same shape every other zero-then-cap ordering on this surface
5797        // uses (`MemoryZero` then `MemoryExceedsWasm32Cap`,
5798        // `WallClockZero` then `WallClockExceedsCap`).
5799        let l = LimitsSpec {
5800            cpu: Some(0),
5801            ..Default::default()
5802        };
5803        assert_eq!(
5804            l.validate().unwrap_err(),
5805            LimitsError::CpuZero,
5806            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
5807        );
5808    }
5809
5810    #[test]
5811    fn validate_rejects_cpu_cap_after_earlier_axes() {
5812        // Cross-axis ordering: when both an above-cap `:cpu` and an
5813        // earlier-axis violation are present, the earlier axis must
5814        // fire first. The validate sequence is :memory → :fuel →
5815        // :wall-clock → :cpu, so a paired memory-zero + cpu-above-cap
5816        // input surfaces `MemoryZero`, never the cpu-cap diagnostic.
5817        // Pins the canonical axis order so a future refactor that
5818        // reorders the arms surfaces here as a test failure rather
5819        // than a silent diagnostic regression. Peer of
5820        // `validate_rejects_first_zero_axis_deterministically` and
5821        // `validate_rejects_memory_cap_before_other_axes`.
5822        let l = LimitsSpec {
5823            memory: Some(0),
5824            fuel: None,
5825            wall_clock: None,
5826            cpu: Some(LIMITS_CPU_MILLICORES_MAX + 1),
5827        };
5828        assert_eq!(
5829            l.validate().unwrap_err(),
5830            LimitsError::MemoryZero,
5831            "earlier-axis violation must take precedence over later-axis cap violation"
5832        );
5833    }
5834
5835    #[test]
5836    fn cpu_cap_diagnostic_carries_offending_value() {
5837        // The diagnostic-shape pin: the offending millicore count is
5838        // carried verbatim into the [`LimitsError::CpuExceedsCap`]
5839        // variant so the surfaced error message names the value the
5840        // author wrote, not just the cap. Same self-locating
5841        // diagnostic shape every other typed-cap arm on this surface
5842        // carries (`MemoryExceedsWasm32Cap` carries the offending byte
5843        // count verbatim, `WallClockExceedsCap` carries the offending
5844        // `Duration` verbatim).
5845        let m = 256_000_u32; // 256 cores — double the cap
5846        let l = LimitsSpec {
5847            cpu: Some(m),
5848            ..Default::default()
5849        };
5850        let err = l.validate().unwrap_err();
5851        assert!(
5852            matches!(err, LimitsError::CpuExceedsCap { millicores } if millicores == m),
5853            "got {err:?}"
5854        );
5855        let msg = err.to_string();
5856        assert!(
5857            msg.contains("256000"),
5858            ":limits :cpu cap diagnostic must carry the offending value verbatim (got: {msg})"
5859        );
5860    }
5861
5862    #[test]
5863    fn cpu_cap_pins_canonical_value() {
5864        // The [`LIMITS_CPU_MILLICORES_MAX`] constant pins the value at
5865        // exactly 128 cores (128_000 millicores) — the largest
5866        // commercially-common non-metal cloud Kubernetes node vCPU
5867        // count. Pinning the literal value here surfaces a future
5868        // drift (a relaxation to 256 cores, a tightening to 64 cores)
5869        // as a deliberate test edit, not a silent contract narrowing.
5870        // Same shape every other typed-cap value pin uses
5871        // (`wall_clock_cap_pins_canonical_value`,
5872        // `wasm32_memory_cap_matches_parsed_4_gib`).
5873        assert_eq!(LIMITS_CPU_MILLICORES_MAX, 128_000);
5874        assert_eq!(LIMITS_CPU_MILLICORES_MAX, 128 * 1000);
5875    }
5876
5877    #[test]
5878    fn cpu_cap_value_round_trips_through_codec() {
5879        // The codec round-trip property the cap arm preserves: the
5880        // [`LIMITS_CPU_MILLICORES_MAX`] constant itself round-trips
5881        // through the in-module millicore codec — the cap value
5882        // renders to a clean canonical string (`"128000m"`) and parses
5883        // back to the same `u32`. Pin this so a future drift between
5884        // the cap constant and the codec's accepted magnitude surfaces
5885        // here. Same shape every other typed boundary pin on this
5886        // surface uses (`wasm32_memory_cap_matches_parsed_4_gib`,
5887        // `wall_clock_cap_value_round_trips_through_codec`).
5888        let l = LimitsSpec {
5889            cpu: Some(LIMITS_CPU_MILLICORES_MAX),
5890            ..Default::default()
5891        };
5892        let json = serde_json::to_string(&l).unwrap();
5893        assert!(
5894            json.contains("\"128000m\""),
5895            "the LIMITS_CPU_MILLICORES_MAX value must render to the canonical \"128000m\" form (got: {json})"
5896        );
5897        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
5898        assert_eq!(back.cpu, Some(LIMITS_CPU_MILLICORES_MAX));
5899        l.validate()
5900            .expect("LIMITS_CPU_MILLICORES_MAX itself must pass validate");
5901    }
5902
5903    // ── value-shape: :fuel upper bound — 10^12 no-op-budget ceiling ────────
5904    //
5905    // The fourth and final `LimitsSpec` axis brought to a top-edge
5906    // cap, closing the open edge the 857dfcc CPU-cap commit body
5907    // explicitly named: "three of the four axes carry a top-and-bottom
5908    // edge gate; only `:fuel` remains with a zero-floor-only shape."
5909    // Mirrors the test discipline every sibling capped axis carries:
5910    // the fail-before-pass-after pin, the one-instruction-boundary
5911    // pin, the far-above-cap sweep, the inclusive-at-cap positive
5912    // control, the production-band positive-control sweep, the
5913    // cross-arm zero-then-cap ordering pin, the cross-axis
5914    // earlier-then-later precedence pin, the diagnostic-shape pin
5915    // carrying the offending value verbatim, and the cap-value
5916    // literal-identity + codec round-trip pins anchoring the
5917    // constant.
5918
5919    #[test]
5920    fn validate_rejects_fuel_above_cap() {
5921        // The fail-before-pass-after pin: `LIMITS_FUEL_MAX + 1` =
5922        // one wasm-instruction past the structural ceiling — a `u64`
5923        // magnitude the typed slot round-trips losslessly through
5924        // serde, and that silently passed validate on every pre-gate
5925        // codebase because the typed slot's only check was the
5926        // zero-floor arm. The wasm-engine consuming the value (via
5927        // `Store::set_fuel` projection in the M2.5 host runtime)
5928        // accepts the magnitude but the sibling `:wall-clock` 1h cap
5929        // fires before the fuel counter could ever drain — the typed
5930        // `:fuel` slot becomes a no-op budget far from the source
5931        // caixa.lisp.
5932        let f = LIMITS_FUEL_MAX + 1;
5933        let l = LimitsSpec {
5934            fuel: Some(f),
5935            ..Default::default()
5936        };
5937        assert_eq!(
5938            l.validate().unwrap_err(),
5939            LimitsError::FuelExceedsCap { fuel: f }
5940        );
5941    }
5942
5943    #[test]
5944    fn validate_rejects_fuel_far_above_cap() {
5945        // The "obvious authoring footgun" case: a `(:fuel
5946        // 1000000000000000)` (10^15 instructions), a paste-from-binary
5947        // `u64::MAX`, or a hex-literal-confused-for-decimal magnitude
5948        // — values the `u64` slot accepts cleanly, the codec
5949        // round-trips losslessly through serde, but the wasm-engine
5950        // can never honor as a meaningful counter. Until this gate
5951        // landed validate accepted them. Pin the common above-cap
5952        // values (10x cap, 1000x cap, `u64::MAX`) so a future
5953        // relaxation that drops the upper bound surfaces here. Peer
5954        // of `validate_rejects_cpu_far_above_cap` /
5955        // `validate_rejects_memory_8_gib` /
5956        // `validate_rejects_wall_clock_far_above_cap`.
5957        for f in [LIMITS_FUEL_MAX * 10, LIMITS_FUEL_MAX * 1_000, u64::MAX] {
5958            let l = LimitsSpec {
5959                fuel: Some(f),
5960                ..Default::default()
5961            };
5962            assert_eq!(
5963                l.validate().unwrap_err(),
5964                LimitsError::FuelExceedsCap { fuel: f }
5965            );
5966        }
5967    }
5968
5969    #[test]
5970    fn validate_accepts_fuel_at_cap() {
5971        // The boundary value — exactly [`LIMITS_FUEL_MAX`] (10^12
5972        // wasm instructions) — must validate. The cap is inclusive
5973        // on the top edge, matching the discipline on every sibling
5974        // capped axis ([`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5975        // [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5976        // [`crate::POLICY_TIMEOUT_MAX`],
5977        // [`crate::POLICY_BREAKER_WINDOW_MAX`],
5978        // [`crate::POLICY_RATE_LIMIT_MAX`]). Pin the boundary
5979        // explicitly so a future off-by-one tightening
5980        // (`>= LIMITS_FUEL_MAX` instead of `>`) surfaces here as a
5981        // test failure rather than a silent contract narrowing.
5982        let l = LimitsSpec {
5983            fuel: Some(LIMITS_FUEL_MAX),
5984            ..Default::default()
5985        };
5986        l.validate().expect("fuel == LIMITS_FUEL_MAX must validate");
5987    }
5988
5989    #[test]
5990    fn validate_accepts_fuel_typical_values() {
5991        // The documented production-playbook band positive-control
5992        // sweep — every value the canonical caixa Servico runs in
5993        // (10^6..=10^9 fuel-units) must pass, plus a sweep through
5994        // the larger compute-bound-Servico band (10^10, 10^11) the
5995        // cap accepts. The canonical fixture is `1_000_000` =
5996        // wasmtime's documented `Store::set_fuel(1_000_000)` example.
5997        // Mirrors `validate_accepts_cpu_typical_values` on the
5998        // sibling `:cpu` axis.
5999        for f in [
6000            1_u64,             // smallest non-zero
6001            1_000,             // tiny per-call budget
6002            1_000_000,         // canonical fixture (10^6) — wasmtime book example
6003            10_000_000,        // typical small-Servico (10^7)
6004            100_000_000,       // typical heavier-Servico (10^8)
6005            1_000_000_000,     // 1 billion — upper realistic per-call (10^9)
6006            100_000_000_000,   // 10^11 — heavy compute-bound (10x below cap)
6007            500_000_000_000,   // half the cap
6008            1_000_000_000_000, // exactly at cap (10^12)
6009        ] {
6010            let l = LimitsSpec {
6011                fuel: Some(f),
6012                ..Default::default()
6013            };
6014            l.validate()
6015                .unwrap_or_else(|e| panic!("fuel={f} must validate; got {e:?}"));
6016        }
6017    }
6018
6019    #[test]
6020    fn fuel_zero_takes_precedence_over_cap() {
6021        // The cross-arm ordering pin: `Some(0)` is structurally
6022        // outside both `>= 1` (zero-floor) and `<= LIMITS_FUEL_MAX`
6023        // (cap), but the zero-floor diagnostic is the more
6024        // self-locating one (it directly names the omit-axis
6025        // remediation and the wasmtime-traps-at-zero semantics), so
6026        // the validate gate must fire on zero first. Same shape every
6027        // other zero-then-cap ordering on this surface uses
6028        // (`MemoryZero` then `MemoryExceedsWasm32Cap`,
6029        // `WallClockZero` then `WallClockExceedsCap`, `CpuZero` then
6030        // `CpuExceedsCap`).
6031        let l = LimitsSpec {
6032            fuel: Some(0),
6033            ..Default::default()
6034        };
6035        assert_eq!(
6036            l.validate().unwrap_err(),
6037            LimitsError::FuelZero,
6038            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
6039        );
6040    }
6041
6042    #[test]
6043    fn validate_rejects_fuel_cap_after_earlier_axes() {
6044        // Cross-axis ordering: when both an above-cap `:fuel` and an
6045        // earlier-axis violation are present, the earlier axis must
6046        // fire first. The validate sequence is :memory → :fuel →
6047        // :wall-clock → :cpu, so a paired memory-zero + fuel-above-
6048        // cap input surfaces `MemoryZero`, never the fuel-cap
6049        // diagnostic. Pins the canonical axis order so a future
6050        // refactor that reorders the arms surfaces here as a test
6051        // failure rather than a silent diagnostic regression. Peer
6052        // of `validate_rejects_cpu_cap_after_earlier_axes`.
6053        let l = LimitsSpec {
6054            memory: Some(0),
6055            fuel: Some(LIMITS_FUEL_MAX + 1),
6056            wall_clock: None,
6057            cpu: None,
6058        };
6059        assert_eq!(
6060            l.validate().unwrap_err(),
6061            LimitsError::MemoryZero,
6062            "earlier-axis violation must take precedence over later-axis cap violation"
6063        );
6064    }
6065
6066    #[test]
6067    fn validate_rejects_fuel_cap_before_later_axes() {
6068        // Cross-axis ordering on the other side: when both an
6069        // above-cap `:fuel` and a later-axis violation are present,
6070        // the `:fuel` cap must fire before the `:wall-clock` /
6071        // `:cpu` zero-floor diagnostics. The validate sequence is
6072        // :memory → :fuel → :wall-clock → :cpu, so a paired
6073        // fuel-above-cap + wall-clock-zero input surfaces
6074        // `FuelExceedsCap`, not `WallClockZero`. Pins the canonical
6075        // axis order on the new arm's downstream side, peer to the
6076        // upstream pin `validate_rejects_fuel_cap_after_earlier_axes`.
6077        let l = LimitsSpec {
6078            memory: None,
6079            fuel: Some(LIMITS_FUEL_MAX + 1),
6080            wall_clock: Some(Duration::ZERO),
6081            cpu: Some(0),
6082        };
6083        assert_eq!(
6084            l.validate().unwrap_err(),
6085            LimitsError::FuelExceedsCap {
6086                fuel: LIMITS_FUEL_MAX + 1
6087            },
6088            ":fuel cap diagnostic must take precedence over later-axis zero-floor diagnostics"
6089        );
6090    }
6091
6092    #[test]
6093    fn fuel_cap_diagnostic_carries_offending_value() {
6094        // The diagnostic-shape pin: the offending fuel count is
6095        // carried verbatim into the [`LimitsError::FuelExceedsCap`]
6096        // variant so the surfaced error message names the value the
6097        // author wrote, not just the cap. Same self-locating
6098        // diagnostic shape every other typed-cap arm on this surface
6099        // carries (`MemoryExceedsWasm32Cap` carries the offending
6100        // byte count verbatim, `WallClockExceedsCap` carries the
6101        // offending `Duration` verbatim, `CpuExceedsCap` carries the
6102        // offending millicore count verbatim).
6103        let f = 5_000_000_000_000_u64; // 5 trillion — 5x the cap
6104        let l = LimitsSpec {
6105            fuel: Some(f),
6106            ..Default::default()
6107        };
6108        let err = l.validate().unwrap_err();
6109        assert!(
6110            matches!(err, LimitsError::FuelExceedsCap { fuel } if fuel == f),
6111            "got {err:?}"
6112        );
6113        let msg = err.to_string();
6114        assert!(
6115            msg.contains("5000000000000"),
6116            ":limits :fuel cap diagnostic must carry the offending value verbatim (got: {msg})"
6117        );
6118    }
6119
6120    #[test]
6121    fn fuel_cap_pins_canonical_value() {
6122        // The [`LIMITS_FUEL_MAX`] constant pins the value at exactly
6123        // 10^12 (1 trillion wasm instructions) — the round-number
6124        // ceiling above the operational envelope the sibling
6125        // [`LIMITS_WALL_CLOCK_MAX`] (1h) × wasmtime's fuel-tracked
6126        // execution rate (~10^9 fuel/sec) yields. Pinning the
6127        // literal value here surfaces a future drift (a relaxation
6128        // to 10^15, a tightening to 10^9) as a deliberate test edit,
6129        // not a silent contract narrowing. Same shape every other
6130        // typed-cap value pin uses (`cpu_cap_pins_canonical_value`,
6131        // `wall_clock_cap_pins_canonical_value`,
6132        // `wasm32_memory_cap_matches_parsed_4_gib`).
6133        assert_eq!(LIMITS_FUEL_MAX, 1_000_000_000_000);
6134        assert_eq!(LIMITS_FUEL_MAX, 10_u64.pow(12));
6135    }
6136
6137    #[test]
6138    fn fuel_cap_value_round_trips_through_serde() {
6139        // The serde round-trip property the cap arm preserves: the
6140        // [`LIMITS_FUEL_MAX`] constant itself round-trips through
6141        // the in-module `u64` serde codec — the cap value renders as
6142        // the bare integer literal and parses back to the same
6143        // `u64`. Pin this so a future drift between the cap constant
6144        // and the codec's accepted magnitude (a future custom u64
6145        // serializer that introduces lossy formatting) surfaces
6146        // here. Same shape every other typed boundary pin on this
6147        // surface uses (`wasm32_memory_cap_matches_parsed_4_gib`,
6148        // `wall_clock_cap_value_round_trips_through_codec`,
6149        // `cpu_cap_value_round_trips_through_codec`).
6150        let l = LimitsSpec {
6151            fuel: Some(LIMITS_FUEL_MAX),
6152            ..Default::default()
6153        };
6154        let json = serde_json::to_string(&l).unwrap();
6155        assert!(
6156            json.contains("1000000000000"),
6157            "the LIMITS_FUEL_MAX value must render verbatim as the bare integer 10^12 \
6158             (got: {json})"
6159        );
6160        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
6161        assert_eq!(back.fuel, Some(LIMITS_FUEL_MAX));
6162        l.validate()
6163            .expect("LIMITS_FUEL_MAX itself must pass validate");
6164    }
6165
6166    // ── per-`:limits :memory` accessor pins (LimitsSpec::memory) ─────────
6167
6168    #[test]
6169    fn limits_memory_returns_option_u64_byte_equal_across_permutations() {
6170        // The canonical per-`:limits` `:memory` Lunatic-per-process
6171        // wasm32-linear-memory byte-cap scalar pin: [`LimitsSpec::memory`]
6172        // must return the `:limits :memory` typed `u64` verbatim as an
6173        // `Option<u64>`, byte-equal to the raw field access across the
6174        // three canonical shape-arms — `None` (no cap declared —
6175        // engine-default applies), `Some(LIMITS_MEMORY_WASM32_PAGE_BYTES)`
6176        // (the structural minimum a validated `:limits :memory` may
6177        // carry, one wasm32 linear-memory page), `Some(64 * 1024 *
6178        // 1024)` (the canonical 64 MiB byte-cap the module-level
6179        // docstring names).
6180        //
6181        // Peer of the sibling per-`:politicas` [`crate::MeshPolicy::mtls_required`]
6182        // (c0110f1) / [`crate::MeshPolicy::retries`] (bdfb399) /
6183        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor pin trio on
6184        // the sibling `Option<Copy-T>`-return axis, extended to the
6185        // peer per-`:limits` typed-`u64` optional-scalar shape —
6186        // first `Option<Copy-T>`-return accessor on the M2 slot family.
6187        // Pins against a future silent detour that re-derived the cap
6188        // from a peer axis (an accidental `.fuel`-collapse that
6189        // assumed the two `Option<u64>` axes carry the same value), a
6190        // `None` → `Some(0)` "zero means unbounded" collapse (the
6191        // canonical `Option<u64>` → `u64` collapse footgun the
6192        // [`LimitsError::MemoryZero`] validate arm guards on the peer
6193        // zero-floor axis), or a per-arm variant swap that landed on
6194        // one consumer without the other.
6195        for memory in [
6196            None,
6197            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
6198            Some(64 * 1024 * 1024),
6199        ] {
6200            let l = LimitsSpec {
6201                memory,
6202                ..LimitsSpec::default()
6203            };
6204            assert_eq!(
6205                l.memory(),
6206                memory,
6207                "LimitsSpec::memory must return :limits :memory verbatim \
6208                 (got {:?}, expected {memory:?})",
6209                l.memory(),
6210            );
6211            assert_eq!(
6212                l.memory(),
6213                l.memory,
6214                "LimitsSpec::memory must byte-equal the raw .memory \
6215                 field access across every value in the accept-set",
6216            );
6217        }
6218    }
6219
6220    #[test]
6221    fn limits_is_empty_memory_arm_routes_through_accessor() {
6222        // Composition pin: [`LimitsSpec::is_empty`]'s `memory` arm
6223        // must key off [`LimitsSpec::memory`], not the raw `.memory`
6224        // field access. Structurally: setting ONLY the `memory` slot
6225        // on an otherwise-default LimitsSpec must flip `is_empty()`
6226        // from `true` (all-`None`) to `false` (one axis carries a
6227        // value); the flip must be observed across every value in the
6228        // accept-set since the emptiness semantic reads "any axis
6229        // carries a value" — not "any axis carries a value above a
6230        // threshold" — the same non-collapsing shape the sibling M3
6231        // [`crate::MeshPolicy::is_empty`] predicate carries on its
6232        // peer `Option<Copy-T>`-typed slot surfaces.
6233        //
6234        // Pins against a future silent detour that re-derived the
6235        // emptiness predicate off a peer axis (an accidental
6236        // `.fuel.is_none()`-only chain that dropped the `memory` arm
6237        // entirely), an accessor-side detour that no longer names the
6238        // substrate-primitive typed dispatch (an accidental
6239        // `self.memory.unwrap_or(0) == 0` fallback in the accessor
6240        // that would silently classify both `None` and `Some(0)` as
6241        // the same value), or a threshold collapse (a
6242        // `self.memory().is_some_and(|m| m > 0)` that would silently
6243        // classify `Some(0)` as unset).
6244        //
6245        // Peer of the sibling per-`:politicas`
6246        // [`crate::MeshPolicy::is_empty`] `mtls_required` arm
6247        // accessor-composition pin (c0110f1) on the sibling optional-
6248        // scalar axis — same "the emptiness / shape-gate predicate
6249        // must route through the substrate-primitive typed dispatch"
6250        // discipline extended onto the peer per-`:limits` emptiness
6251        // predicate.
6252        let empty = LimitsSpec::default();
6253        assert!(
6254            empty.is_empty(),
6255            "LimitsSpec::default() must be is_empty() — every axis \
6256             defaults to None",
6257        );
6258        for memory in [
6259            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
6260            Some(64 * 1024 * 1024),
6261            Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
6262        ] {
6263            let l = LimitsSpec {
6264                memory,
6265                ..LimitsSpec::default()
6266            };
6267            assert!(
6268                !l.is_empty(),
6269                "LimitsSpec::is_empty must return false when :memory \
6270                 is {memory:?} — the emptiness predicate reads \"any \
6271                 axis carries a value\", not \"any axis carries a \
6272                 value above a threshold\"",
6273            );
6274            assert_eq!(
6275                l.memory().is_none(),
6276                l.is_empty(),
6277                "when :memory is the only set axis, is_empty() must \
6278                 equal memory().is_none() — the accessor and the \
6279                 emptiness predicate must route through the same \
6280                 substrate-primitive typed dispatch on the :memory \
6281                 arm",
6282            );
6283        }
6284    }
6285
6286    #[test]
6287    fn limits_memory_projects_option_u64_by_copy() {
6288        // The by-copy pin: [`LimitsSpec::memory`] returns `Option<u64>`
6289        // by copy — `Option<u64>` is `Copy` and the accessor must
6290        // return by value, not by reference. Peer of the sibling per-
6291        // `:politicas` [`crate::MeshPolicy::mtls_required`] (c0110f1)
6292        // borrow-invariant pin on the peer `Option<bool>` shape,
6293        // extended onto the peer `Option<u64>` copy-invariant shape —
6294        // the accessor's returned `Option<u64>` must outlive `&self`
6295        // (multiple calls must return equal values from a dropped-
6296        // `&self` copy, since the returned Option carries no borrow),
6297        // and calling the accessor twice on the same LimitsSpec must
6298        // yield the same `Option<u64>` verbatim (idempotent, no side
6299        // effects on `&self`).
6300        //
6301        // Pins against a future silent detour that returned
6302        // `Option<&u64>` (which would type-check but silently break
6303        // every downstream caller — the future `wasmtime::Store::limiter`
6304        // wire path consumes `Option<u64>` by value and `&u64` would
6305        // fold to a detached copy at the call site), an accidental
6306        // `Option::as_ref()` projection (`self.memory.as_ref()` would
6307        // also type-check but return `Option<&u64>`), or a one-arm-
6308        // only accessor that reads `Some(*m)` in the Some arm but
6309        // reads a fresh `Default::default()` in the None arm.
6310        for memory in [
6311            None,
6312            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
6313            Some(64 * 1024 * 1024),
6314            Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
6315        ] {
6316            let l = LimitsSpec {
6317                memory,
6318                ..LimitsSpec::default()
6319            };
6320            let first = l.memory();
6321            let second = l.memory();
6322            assert_eq!(
6323                first, second,
6324                "LimitsSpec::memory must be idempotent — two \
6325                 successive calls on the same &self must return the \
6326                 same Option<u64>",
6327            );
6328            assert_eq!(
6329                first, memory,
6330                "LimitsSpec::memory must return :limits :memory \
6331                 verbatim by copy — got {first:?}, expected {memory:?}",
6332            );
6333        }
6334    }
6335
6336    #[test]
6337    #[allow(clippy::too_many_lines)]
6338    fn validate_memory_arms_route_through_lifted_memory_accessor() {
6339        // Composition pin: every value-shape gate in
6340        // [`LimitsSpec::validate`] on the `:memory` axis (the
6341        // zero-floor `MemoryZero` arm, the sub-page `MemoryBelowWasm32Page`
6342        // arm, the above-cap `MemoryExceedsWasm32Cap` arm, the
6343        // non-page-multiple `MemoryNotPageMultiple` arm) must key off
6344        // [`LimitsSpec::memory`], not the raw `self.memory` field
6345        // access. Peer of the sibling per-`:politicas`
6346        // [`crate::AplicacaoSpec::validate_politicas`] `:timeout` /
6347        // `:retries` arm converge pin (1017b9d) on the sibling M3
6348        // mesh-slot family, extended onto the M2 per-`:limits`
6349        // `:memory` axis; peer of the sibling per-`:limits` `:fuel` /
6350        // `:wall-clock` / `:cpu` arms in the same fan-out that
6351        // already route through `self.fuel()` / `self.wall_clock()`
6352        // / `self.cpu()` at :880 / :888 / :942.
6353        //
6354        // Assertion shape: for each memory value in the
6355        // accept-and-refuse set, `LimitsSpec::memory()` must byte-
6356        // equal the raw `.memory` field it borrows from, and the
6357        // validate call on a `LimitsSpec { memory: <v>, ..default() }`
6358        // fixture must surface the same variant/Ok discriminant the
6359        // accessor-composed spec surfaces. Together they catch any
6360        // future silent detour — an accessor drift that no longer
6361        // shipped the raw slot verbatim, a validate-branch rebrand to
6362        // a peer-axis field read, an accidental `Option`-collapse in
6363        // any of the four arms — at caixa-core build time rather than
6364        // at a downstream runtime declared-but-inert-limits divergence
6365        // at the wasmtime `Store::limiter` boundary.
6366        //
6367        // `#[allow(clippy::too_many_lines)]` per the same discipline
6368        // peer over-100-line composition pins in this module accept
6369        // (see e.g. `limits_is_empty_memory_arm_routes_through_accessor`,
6370        // `limits_memory_returns_option_u64_byte_equal_across_permutations`).
6371        for memory in [
6372            None,
6373            Some(0),                                   // → MemoryZero
6374            Some(1),                                   // → MemoryBelowWasm32Page (sub-page)
6375            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES - 1), // → MemoryBelowWasm32Page (at-under-page)
6376            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),     // → Ok (at-page-floor)
6377            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES + 1), // → MemoryNotPageMultiple (one-past-page)
6378            Some(2 * LIMITS_MEMORY_WASM32_PAGE_BYTES), // → Ok (multi-page)
6379            Some(LIMITS_MEMORY_WASM32_MAX_BYTES),      // → Ok (at-cap)
6380            Some(LIMITS_MEMORY_WASM32_MAX_BYTES + 1),  // → MemoryExceedsWasm32Cap (one-past-cap)
6381        ] {
6382            let l = LimitsSpec {
6383                memory,
6384                ..LimitsSpec::default()
6385            };
6386            // (1) The accessor must byte-equal the raw field it wraps.
6387            assert_eq!(
6388                l.memory(),
6389                l.memory,
6390                "LimitsSpec::memory() must byte-equal the raw \
6391                 .memory field for {memory:?} — an accessor detour \
6392                 that dropped the raw slot's Option<u64> verbatim \
6393                 would silently split validate's :memory arms from \
6394                 every peer emit-site consumer that also routes \
6395                 through the accessor (the future wasmtime \
6396                 Store::limiter wire path, the caixa-helm \
6397                 resources.limits.memory materializer)",
6398            );
6399            // (2) Two successive validate() calls must yield the same
6400            // variant/Ok discriminant — the accessor-projected reads
6401            // and the raw-projected reads must produce identical
6402            // validation outcomes.
6403            let first = l.validate();
6404            let second = l.validate();
6405            assert_eq!(
6406                first, second,
6407                "LimitsSpec::validate must be idempotent on :memory \
6408                 {memory:?} — two successive calls must surface the \
6409                 same variant/Ok discriminant, catching any accessor \
6410                 detour that would introduce a value-dependent side \
6411                 effect on the &self projection",
6412            );
6413        }
6414        // (3) The specific arm-order shape the four converged sites
6415        // encode: `MemoryZero` (raw-`Some(0)`) precedes the page-floor
6416        // arm, which precedes the cap arm, which precedes the page-
6417        // multiple arm. Each arm must fire off the accessor-projected
6418        // read on its specific fixture value.
6419        assert_eq!(
6420            LimitsSpec {
6421                memory: Some(0),
6422                ..LimitsSpec::default()
6423            }
6424            .validate(),
6425            Err(LimitsError::MemoryZero),
6426            "MemoryZero must fire on Some(0) via the accessor projection",
6427        );
6428        assert_eq!(
6429            LimitsSpec {
6430                memory: Some(1),
6431                ..LimitsSpec::default()
6432            }
6433            .validate(),
6434            Err(LimitsError::MemoryBelowWasm32Page { bytes: 1 }),
6435            "MemoryBelowWasm32Page must fire on Some(1) via the accessor projection",
6436        );
6437        assert_eq!(
6438            LimitsSpec {
6439                memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES + 1),
6440                ..LimitsSpec::default()
6441            }
6442            .validate(),
6443            Err(LimitsError::MemoryExceedsWasm32Cap {
6444                bytes: LIMITS_MEMORY_WASM32_MAX_BYTES + 1
6445            }),
6446            "MemoryExceedsWasm32Cap must fire on one-past-cap via the accessor projection",
6447        );
6448        assert_eq!(
6449            LimitsSpec {
6450                memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES + 1),
6451                ..LimitsSpec::default()
6452            }
6453            .validate(),
6454            Err(LimitsError::MemoryNotPageMultiple {
6455                bytes: LIMITS_MEMORY_WASM32_PAGE_BYTES + 1
6456            }),
6457            "MemoryNotPageMultiple must fire on one-past-page-floor via the accessor projection",
6458        );
6459        assert_eq!(
6460            LimitsSpec {
6461                memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
6462                ..LimitsSpec::default()
6463            }
6464            .validate(),
6465            Ok(()),
6466            "at-page-floor must pass validate via the accessor projection",
6467        );
6468        assert_eq!(
6469            LimitsSpec {
6470                memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
6471                ..LimitsSpec::default()
6472            }
6473            .validate(),
6474            Ok(()),
6475            "at-cap must pass validate via the accessor projection",
6476        );
6477    }
6478
6479    // ── per-`:limits :fuel` accessor pins (LimitsSpec::fuel) ─────────
6480
6481    #[test]
6482    fn limits_fuel_returns_option_u64_byte_equal_across_permutations() {
6483        // The canonical per-`:limits` `:fuel` wasmtime-per-call
6484        // wasm-instruction budget scalar pin: [`LimitsSpec::fuel`]
6485        // must return the `:limits :fuel` typed `u64` verbatim as an
6486        // `Option<u64>`, byte-equal to the raw field access across
6487        // the three canonical shape-arms — `None` (no fuel budget
6488        // declared — engine-default applies), `Some(1)` (the
6489        // structural minimum a validated `:limits :fuel` may carry,
6490        // one wasm instruction; wasmtime traps the first instruction
6491        // at `fuel=0`, so `Some(1)` is the smallest budget that
6492        // executes any code), `Some(1_000_000)` (the canonical 10⁶
6493        // fuel-unit budget the in-tree `Caixa::template` and the
6494        // wasmtime book's `Store::set_fuel(1_000_000)` example both
6495        // carry).
6496        //
6497        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6498        // (620c067) accessor byte-equality pin on the peer typed-`u64`
6499        // optional-scalar axis, extended to the wasm-instruction-budget
6500        // shape — second `Option<Copy-T>`-return accessor on the M2
6501        // slot family. Pins against a future silent detour that
6502        // re-derived the fuel budget from a peer axis (an accidental
6503        // `.memory`-collapse that assumed the two `Option<u64>` axes
6504        // carry the same value — the two axes share a shape but not
6505        // a semantic, `:memory` counts linear-memory bytes and `:fuel`
6506        // counts wasm instructions), a `None` → `Some(0)` "zero means
6507        // unbounded" collapse (the canonical `Option<u64>` → `u64`
6508        // collapse footgun the [`LimitsError::FuelZero`] validate arm
6509        // guards on the peer zero-floor axis; wasmtime interprets
6510        // `fuel=0` as "trap the first instruction" not "no bound"), or
6511        // a per-arm variant swap that landed on one consumer without
6512        // the other.
6513        for fuel in [None, Some(1_u64), Some(1_000_000_u64)] {
6514            let l = LimitsSpec {
6515                fuel,
6516                ..LimitsSpec::default()
6517            };
6518            assert_eq!(
6519                l.fuel(),
6520                fuel,
6521                "LimitsSpec::fuel must return :limits :fuel verbatim \
6522                 (got {:?}, expected {fuel:?})",
6523                l.fuel(),
6524            );
6525            assert_eq!(
6526                l.fuel(),
6527                l.fuel,
6528                "LimitsSpec::fuel must byte-equal the raw .fuel \
6529                 field access across every value in the accept-set",
6530            );
6531        }
6532    }
6533
6534    #[test]
6535    fn limits_is_empty_fuel_arm_routes_through_accessor() {
6536        // Composition pin: [`LimitsSpec::is_empty`]'s `fuel` arm
6537        // must key off [`LimitsSpec::fuel`], not the raw `.fuel`
6538        // field access. Structurally: setting ONLY the `fuel` slot
6539        // on an otherwise-default LimitsSpec must flip `is_empty()`
6540        // from `true` (all-`None`) to `false` (one axis carries a
6541        // value); the flip must be observed across every value in
6542        // the accept-set since the emptiness semantic reads "any
6543        // axis carries a value" — not "any axis carries a value
6544        // above a threshold" — the same non-collapsing shape the
6545        // sibling M3 [`crate::MeshPolicy::is_empty`] predicate
6546        // carries on its peer `Option<Copy-T>`-typed slot surfaces
6547        // and the sibling per-`:limits` [`LimitsSpec::memory`]
6548        // (620c067) `is_empty()` accessor-composition pin carries on
6549        // the peer `Option<u64>` axis.
6550        //
6551        // Pins against a future silent detour that re-derived the
6552        // emptiness predicate off a peer axis (an accidental
6553        // `.memory.is_none()`-only chain that dropped the `fuel` arm
6554        // entirely), an accessor-side detour that no longer names the
6555        // substrate-primitive typed dispatch (an accidental
6556        // `self.fuel.unwrap_or(0) == 0` fallback in the accessor
6557        // that would silently classify both `None` and `Some(0)` as
6558        // the same value — a footgun the [`LimitsError::FuelZero`]
6559        // validate arm explicitly closes since `fuel=0` traps rather
6560        // than expresses "unbounded"), or a threshold collapse (a
6561        // `self.fuel().is_some_and(|f| f > 0)` that would silently
6562        // classify `Some(0)` as unset).
6563        //
6564        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6565        // (620c067) `is_empty` composition pin on the peer
6566        // `Option<u64>` axis — same "the emptiness predicate must
6567        // route through the substrate-primitive typed dispatch"
6568        // discipline extended onto the peer per-`:limits` `:fuel`
6569        // arm.
6570        let empty = LimitsSpec::default();
6571        assert!(
6572            empty.is_empty(),
6573            "LimitsSpec::default() must be is_empty() — every axis \
6574             defaults to None",
6575        );
6576        for fuel in [Some(1_u64), Some(1_000_000_u64), Some(LIMITS_FUEL_MAX)] {
6577            let l = LimitsSpec {
6578                fuel,
6579                ..LimitsSpec::default()
6580            };
6581            assert!(
6582                !l.is_empty(),
6583                "LimitsSpec::is_empty must return false when :fuel \
6584                 is {fuel:?} — the emptiness predicate reads \"any \
6585                 axis carries a value\", not \"any axis carries a \
6586                 value above a threshold\"",
6587            );
6588            assert_eq!(
6589                l.fuel().is_none(),
6590                l.is_empty(),
6591                "when :fuel is the only set axis, is_empty() must \
6592                 equal fuel().is_none() — the accessor and the \
6593                 emptiness predicate must route through the same \
6594                 substrate-primitive typed dispatch on the :fuel \
6595                 arm",
6596            );
6597        }
6598    }
6599
6600    #[test]
6601    fn limits_fuel_projects_option_u64_by_copy() {
6602        // The by-copy pin: [`LimitsSpec::fuel`] returns `Option<u64>`
6603        // by copy — `Option<u64>` is `Copy` and the accessor must
6604        // return by value, not by reference. Peer of the sibling per-
6605        // `:limits` [`LimitsSpec::memory`] (620c067) copy-invariant
6606        // pin on the peer `Option<u64>` shape — the accessor's
6607        // returned `Option<u64>` must outlive `&self` (multiple calls
6608        // must return equal values from a dropped-`&self` copy, since
6609        // the returned Option carries no borrow), and calling the
6610        // accessor twice on the same LimitsSpec must yield the same
6611        // `Option<u64>` verbatim (idempotent, no side effects on
6612        // `&self`).
6613        //
6614        // Pins against a future silent detour that returned
6615        // `Option<&u64>` (which would type-check but silently break
6616        // every downstream caller — the future `wasmtime::Store::set_fuel`
6617        // wire path consumes `u64` by value and `&u64` would fold to
6618        // a detached copy at the call site), an accidental
6619        // `Option::as_ref()` projection (`self.fuel.as_ref()` would
6620        // also type-check but return `Option<&u64>`), or a one-arm-
6621        // only accessor that reads `Some(*f)` in the Some arm but
6622        // reads a fresh `Default::default()` in the None arm.
6623        for fuel in [
6624            None,
6625            Some(1_u64),
6626            Some(1_000_000_u64),
6627            Some(LIMITS_FUEL_MAX),
6628        ] {
6629            let l = LimitsSpec {
6630                fuel,
6631                ..LimitsSpec::default()
6632            };
6633            let first = l.fuel();
6634            let second = l.fuel();
6635            assert_eq!(
6636                first, second,
6637                "LimitsSpec::fuel must be idempotent — two \
6638                 successive calls on the same &self must return the \
6639                 same Option<u64>",
6640            );
6641            assert_eq!(
6642                first, fuel,
6643                "LimitsSpec::fuel must return :limits :fuel \
6644                 verbatim by copy — got {first:?}, expected {fuel:?}",
6645            );
6646        }
6647    }
6648
6649    // ── per-`:limits :wall-clock` accessor pins (LimitsSpec::wall_clock) ─
6650
6651    #[test]
6652    fn limits_wall_clock_returns_option_duration_byte_equal_across_permutations() {
6653        // The canonical per-`:limits` `:wall-clock` wasmtime-per-call
6654        // wall-clock deadline scalar pin: [`LimitsSpec::wall_clock`]
6655        // must return the `:limits :wall-clock` typed `Duration`
6656        // verbatim as an `Option<Duration>`, byte-equal to the raw
6657        // field access across the three canonical shape-arms — `None`
6658        // (no wall-clock deadline declared — engine-default applies),
6659        // `Some(Duration::from_millis(1))` (the structural minimum a
6660        // validated `:limits :wall-clock` may carry, the
6661        // integer-millisecond floor
6662        // [`LimitsError::WallClockNotCanonical`] rejects everything
6663        // sub-ms; `Duration::ZERO` is separately rejected by
6664        // [`LimitsError::WallClockZero`]), `Some(Duration::from_secs(30))`
6665        // (the canonical 30s deadline the module-level docstring
6666        // names).
6667        //
6668        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6669        // (620c067) / [`LimitsSpec::fuel`] (795dee7) accessor
6670        // byte-equality pins on the peer typed-`u64` optional-scalar
6671        // axes, extended to the wall-clock-deadline `Option<Duration>`
6672        // shape — third `Option<Copy-T>`-return accessor on the M2 slot
6673        // family. Sibling to [`crate::MeshPolicy::timeout`] (7073d0f) on
6674        // the M3 mesh-slot family's peer `Option<Duration>` accessor
6675        // axis — same typed-`Duration` shape extended from the M3
6676        // per-call-timeout axis to the M2 per-outermost-call-deadline
6677        // axis. Pins against a future silent detour that re-derived the
6678        // wall-clock deadline from a peer axis (an accidental
6679        // `.fuel`-collapse that assumed the wall-clock deadline and
6680        // the fuel budget carry the same value — the two axes serve
6681        // different sandboxing purposes, wall-clock tracks scheduler
6682        // real time and fuel tracks wasm instructions), a `None` →
6683        // `Some(Duration::ZERO)` "zero means unbounded" collapse (the
6684        // canonical `Option<Duration>` → `Duration` collapse footgun
6685        // the [`LimitsError::WallClockZero`] validate arm guards on the
6686        // peer zero-floor axis; a zero deadline traps the first
6687        // instruction), or a per-arm variant swap that landed on one
6688        // consumer without the other.
6689        for wall_clock in [
6690            None,
6691            Some(Duration::from_millis(1)),
6692            Some(Duration::from_secs(30)),
6693        ] {
6694            let l = LimitsSpec {
6695                wall_clock,
6696                ..LimitsSpec::default()
6697            };
6698            assert_eq!(
6699                l.wall_clock(),
6700                wall_clock,
6701                "LimitsSpec::wall_clock must return :limits :wall-clock verbatim \
6702                 (got {:?}, expected {wall_clock:?})",
6703                l.wall_clock(),
6704            );
6705            assert_eq!(
6706                l.wall_clock(),
6707                l.wall_clock,
6708                "LimitsSpec::wall_clock must byte-equal the raw .wall_clock \
6709                 field access across every value in the accept-set",
6710            );
6711        }
6712    }
6713
6714    #[test]
6715    fn limits_is_empty_wall_clock_arm_routes_through_accessor() {
6716        // Composition pin: [`LimitsSpec::is_empty`]'s `wall_clock` arm
6717        // must key off [`LimitsSpec::wall_clock`], not the raw
6718        // `.wall_clock` field access. Structurally: setting ONLY the
6719        // `wall_clock` slot on an otherwise-default LimitsSpec must
6720        // flip `is_empty()` from `true` (all-`None`) to `false` (one
6721        // axis carries a value); the flip must be observed across every
6722        // value in the accept-set since the emptiness semantic reads
6723        // "any axis carries a value" — not "any axis carries a value
6724        // above a threshold" — the same non-collapsing shape the
6725        // sibling M3 [`crate::MeshPolicy::is_empty`] predicate carries
6726        // on its peer `Option<Copy-T>`-typed slot surfaces and the
6727        // sibling per-`:limits` [`LimitsSpec::memory`] (620c067) /
6728        // [`LimitsSpec::fuel`] (795dee7) `is_empty()` accessor-
6729        // composition pins carry on the peer `Option<u64>` axes.
6730        //
6731        // Pins against a future silent detour that re-derived the
6732        // emptiness predicate off a peer axis (an accidental
6733        // `.memory.is_none()`-only chain that dropped the `wall_clock`
6734        // arm entirely), an accessor-side detour that no longer names
6735        // the substrate-primitive typed dispatch (an accidental
6736        // `self.wall_clock.unwrap_or(Duration::ZERO).is_zero()` fallback
6737        // in the accessor that would silently classify both `None` and
6738        // `Some(Duration::ZERO)` as the same value — a footgun the
6739        // [`LimitsError::WallClockZero`] validate arm explicitly closes
6740        // since a zero deadline traps rather than expresses
6741        // "unbounded"), or a threshold collapse (a
6742        // `self.wall_clock().is_some_and(|w| !w.is_zero())` that would
6743        // silently classify `Some(Duration::ZERO)` as unset).
6744        //
6745        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6746        // (620c067) / [`LimitsSpec::fuel`] (795dee7) `is_empty`
6747        // composition pins on the peer `Option<u64>` axes — same "the
6748        // emptiness predicate must route through the substrate-
6749        // primitive typed dispatch" discipline extended onto the peer
6750        // per-`:limits` `:wall-clock` arm.
6751        let empty = LimitsSpec::default();
6752        assert!(
6753            empty.is_empty(),
6754            "LimitsSpec::default() must be is_empty() — every axis \
6755             defaults to None",
6756        );
6757        for wall_clock in [
6758            Some(Duration::from_millis(1)),
6759            Some(Duration::from_secs(30)),
6760            Some(LIMITS_WALL_CLOCK_MAX),
6761        ] {
6762            let l = LimitsSpec {
6763                wall_clock,
6764                ..LimitsSpec::default()
6765            };
6766            assert!(
6767                !l.is_empty(),
6768                "LimitsSpec::is_empty must return false when :wall-clock \
6769                 is {wall_clock:?} — the emptiness predicate reads \"any \
6770                 axis carries a value\", not \"any axis carries a \
6771                 value above a threshold\"",
6772            );
6773            assert_eq!(
6774                l.wall_clock().is_none(),
6775                l.is_empty(),
6776                "when :wall-clock is the only set axis, is_empty() must \
6777                 equal wall_clock().is_none() — the accessor and the \
6778                 emptiness predicate must route through the same \
6779                 substrate-primitive typed dispatch on the :wall-clock \
6780                 arm",
6781            );
6782        }
6783    }
6784
6785    #[test]
6786    fn limits_wall_clock_projects_option_duration_by_copy() {
6787        // The by-copy pin: [`LimitsSpec::wall_clock`] returns
6788        // `Option<Duration>` by copy — `Duration` is `Copy` (so
6789        // `Option<Duration>` is `Copy`) and the accessor must return by
6790        // value, not by reference. Peer of the sibling per-`:limits`
6791        // [`LimitsSpec::memory`] (620c067) / [`LimitsSpec::fuel`]
6792        // (795dee7) copy-invariant pins on the peer `Option<u64>`
6793        // shape, extended onto the peer `Option<Duration>` shape — the
6794        // accessor's returned `Option<Duration>` must outlive `&self`
6795        // (multiple calls must return equal values from a dropped-
6796        // `&self` copy, since the returned Option carries no borrow),
6797        // and calling the accessor twice on the same LimitsSpec must
6798        // yield the same `Option<Duration>` verbatim (idempotent, no
6799        // side effects on `&self`).
6800        //
6801        // Pins against a future silent detour that returned
6802        // `Option<&Duration>` (which would type-check but silently
6803        // break every downstream caller — the future
6804        // `wasmtime::Store::epoch_deadline_*` wire path consumes
6805        // `Duration` by value and `&Duration` would fold to a detached
6806        // copy at the call site), an accidental `Option::as_ref()`
6807        // projection (`self.wall_clock.as_ref()` would also type-check
6808        // but return `Option<&Duration>`), or a one-arm-only accessor
6809        // that reads `Some(*w)` in the Some arm but reads a fresh
6810        // `Default::default()` (which would collapse to
6811        // `Duration::ZERO`, not `None`) in the None arm.
6812        for wall_clock in [
6813            None,
6814            Some(Duration::from_millis(1)),
6815            Some(Duration::from_secs(30)),
6816            Some(LIMITS_WALL_CLOCK_MAX),
6817        ] {
6818            let l = LimitsSpec {
6819                wall_clock,
6820                ..LimitsSpec::default()
6821            };
6822            let first = l.wall_clock();
6823            let second = l.wall_clock();
6824            assert_eq!(
6825                first, second,
6826                "LimitsSpec::wall_clock must be idempotent — two \
6827                 successive calls on the same &self must return the \
6828                 same Option<Duration>",
6829            );
6830            assert_eq!(
6831                first, wall_clock,
6832                "LimitsSpec::wall_clock must return :limits :wall-clock \
6833                 verbatim by copy — got {first:?}, expected {wall_clock:?}",
6834            );
6835        }
6836    }
6837
6838    // ── per-`:limits :cpu` accessor pins (LimitsSpec::cpu) ───────────
6839
6840    #[test]
6841    fn limits_cpu_returns_option_u32_byte_equal_across_permutations() {
6842        // The canonical per-`:limits` `:cpu` Kubernetes-millicore
6843        // soft cgroup-share scalar pin: [`LimitsSpec::cpu`] must return
6844        // the `:limits :cpu` typed `u32` verbatim as an `Option<u32>`,
6845        // byte-equal to the raw field access across the three canonical
6846        // shape-arms — `None` (no cgroup share declared —
6847        // scheduler-default applies), `Some(1)` (the structural minimum
6848        // a validated `:limits :cpu` may carry, one millicore; a zero
6849        // cgroup share is separately rejected by
6850        // [`LimitsError::CpuZero`]), `Some(500)` (the canonical 500m
6851        // half-a-core share the in-tree
6852        // `limits_slot_propagates_into_values_block` smoke test carries
6853        // as the load-bearing example, peer to the `caixa-flux`
6854        // projector's identical 500m default).
6855        //
6856        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6857        // (620c067) / [`LimitsSpec::fuel`] (795dee7) /
6858        // [`LimitsSpec::wall_clock`] (8cb717b) accessor byte-equality
6859        // pins on the peer typed-`u64` / `u64` / `Duration`
6860        // optional-scalar axes, extended to the cgroup-cpu-share
6861        // `Option<u32>` shape — fourth and final `Option<Copy-T>`-return
6862        // accessor on the M2 slot family, closing the M2 `:limits`
6863        // `Option<Copy-T>` accessor axis. Sibling to
6864        // [`crate::MeshPolicy::retries`] (bdfb399) on the M3 mesh-slot
6865        // family's peer `Option<u32>` accessor axis — same typed-`u32`
6866        // shape extended from the M3 per-edge-transient-failure-retry-
6867        // budget axis to the M2 per-process-cgroup-cpu-share axis.
6868        // Pins against a future silent detour that re-derived the cpu
6869        // share from a peer axis (an accidental `.retries`-collapse that
6870        // assumed the two `Option<u32>` axes carry the same value — the
6871        // two axes share a shape but not a semantic, M2 `:cpu` counts
6872        // millicores of soft cgroup share and M3 `:retries` counts
6873        // per-edge transient-failure retry budget), a `None` → `Some(0)`
6874        // "zero means unbounded" collapse (the canonical `Option<u32>` →
6875        // `u32` collapse footgun the [`LimitsError::CpuZero`] validate
6876        // arm guards on the peer zero-floor axis; a zero cgroup share
6877        // starves the process rather than expressing "unbounded"), or a
6878        // per-arm variant swap that landed on one consumer without the
6879        // other.
6880        for cpu in [None, Some(1_u32), Some(500_u32)] {
6881            let l = LimitsSpec {
6882                cpu,
6883                ..LimitsSpec::default()
6884            };
6885            assert_eq!(
6886                l.cpu(),
6887                cpu,
6888                "LimitsSpec::cpu must return :limits :cpu verbatim \
6889                 (got {:?}, expected {cpu:?})",
6890                l.cpu(),
6891            );
6892            assert_eq!(
6893                l.cpu(),
6894                l.cpu,
6895                "LimitsSpec::cpu must byte-equal the raw .cpu \
6896                 field access across every value in the accept-set",
6897            );
6898        }
6899    }
6900
6901    #[test]
6902    fn limits_is_empty_cpu_arm_routes_through_accessor() {
6903        // Composition pin: [`LimitsSpec::is_empty`]'s `cpu` arm must key
6904        // off [`LimitsSpec::cpu`], not the raw `.cpu` field access.
6905        // Structurally: setting ONLY the `cpu` slot on an
6906        // otherwise-default LimitsSpec must flip `is_empty()` from
6907        // `true` (all-`None`) to `false` (one axis carries a value);
6908        // the flip must be observed across every value in the
6909        // accept-set since the emptiness semantic reads "any axis
6910        // carries a value" — not "any axis carries a value above a
6911        // threshold" — the same non-collapsing shape the sibling M3
6912        // [`crate::MeshPolicy::is_empty`] predicate carries on its
6913        // peer `Option<Copy-T>`-typed slot surfaces and the sibling
6914        // per-`:limits` [`LimitsSpec::memory`] (620c067) /
6915        // [`LimitsSpec::fuel`] (795dee7) / [`LimitsSpec::wall_clock`]
6916        // (8cb717b) `is_empty()` accessor-composition pins carry on the
6917        // peer `Option<u64>` / `Option<u64>` / `Option<Duration>` axes.
6918        //
6919        // Pins against a future silent detour that re-derived the
6920        // emptiness predicate off a peer axis (an accidental
6921        // `.memory.is_none()`-only chain that dropped the `cpu` arm
6922        // entirely), an accessor-side detour that no longer names the
6923        // substrate-primitive typed dispatch (an accidental
6924        // `self.cpu.unwrap_or(0) == 0` fallback in the accessor that
6925        // would silently classify both `None` and `Some(0)` as the same
6926        // value — a footgun the [`LimitsError::CpuZero`] validate arm
6927        // explicitly closes since a zero cgroup share starves the
6928        // process rather than expressing "unbounded"), or a threshold
6929        // collapse (a `self.cpu().is_some_and(|m| m > 0)` that would
6930        // silently classify `Some(0)` as unset).
6931        //
6932        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6933        // (620c067) / [`LimitsSpec::fuel`] (795dee7) /
6934        // [`LimitsSpec::wall_clock`] (8cb717b) `is_empty` composition
6935        // pins on the peer `Option<u64>` / `Option<u64>` /
6936        // `Option<Duration>` axes — same "the emptiness predicate must
6937        // route through the substrate-primitive typed dispatch"
6938        // discipline extended onto the peer per-`:limits` `:cpu` arm.
6939        // Closes the M2 `:limits` `is_empty`-composition family — every
6940        // arm now routes through its typed accessor, no open-coded
6941        // field access remains.
6942        let empty = LimitsSpec::default();
6943        assert!(
6944            empty.is_empty(),
6945            "LimitsSpec::default() must be is_empty() — every axis \
6946             defaults to None",
6947        );
6948        for cpu in [Some(1_u32), Some(500_u32), Some(LIMITS_CPU_MILLICORES_MAX)] {
6949            let l = LimitsSpec {
6950                cpu,
6951                ..LimitsSpec::default()
6952            };
6953            assert!(
6954                !l.is_empty(),
6955                "LimitsSpec::is_empty must return false when :cpu \
6956                 is {cpu:?} — the emptiness predicate reads \"any \
6957                 axis carries a value\", not \"any axis carries a \
6958                 value above a threshold\"",
6959            );
6960            assert_eq!(
6961                l.cpu().is_none(),
6962                l.is_empty(),
6963                "when :cpu is the only set axis, is_empty() must \
6964                 equal cpu().is_none() — the accessor and the \
6965                 emptiness predicate must route through the same \
6966                 substrate-primitive typed dispatch on the :cpu \
6967                 arm",
6968            );
6969        }
6970    }
6971
6972    #[test]
6973    fn limits_cpu_projects_option_u32_by_copy() {
6974        // The by-copy pin: [`LimitsSpec::cpu`] returns `Option<u32>` by
6975        // copy — `Option<u32>` is `Copy` and the accessor must return
6976        // by value, not by reference. Peer of the sibling per-`:limits`
6977        // [`LimitsSpec::memory`] (620c067) / [`LimitsSpec::fuel`]
6978        // (795dee7) / [`LimitsSpec::wall_clock`] (8cb717b)
6979        // copy-invariant pins on the peer `Option<u64>` / `Option<u64>`
6980        // / `Option<Duration>` shapes, extended onto the peer
6981        // `Option<u32>` copy-invariant shape — the accessor's returned
6982        // `Option<u32>` must outlive `&self` (multiple calls must
6983        // return equal values from a dropped-`&self` copy, since the
6984        // returned Option carries no borrow), and calling the accessor
6985        // twice on the same LimitsSpec must yield the same
6986        // `Option<u32>` verbatim (idempotent, no side effects on
6987        // `&self`).
6988        //
6989        // Pins against a future silent detour that returned
6990        // `Option<&u32>` (which would type-check but silently break
6991        // every downstream caller — the future K8s pod-spec
6992        // `resources.requests.cpu` wire path consumes `u32` by value
6993        // and `&u32` would fold to a detached copy at the call site),
6994        // an accidental `Option::as_ref()` projection
6995        // (`self.cpu.as_ref()` would also type-check but return
6996        // `Option<&u32>`), or a one-arm-only accessor that reads
6997        // `Some(*m)` in the Some arm but reads a fresh
6998        // `Default::default()` in the None arm.
6999        for cpu in [
7000            None,
7001            Some(1_u32),
7002            Some(500_u32),
7003            Some(LIMITS_CPU_MILLICORES_MAX),
7004        ] {
7005            let l = LimitsSpec {
7006                cpu,
7007                ..LimitsSpec::default()
7008            };
7009            let first = l.cpu();
7010            let second = l.cpu();
7011            assert_eq!(
7012                first, second,
7013                "LimitsSpec::cpu must be idempotent — two \
7014                 successive calls on the same &self must return the \
7015                 same Option<u32>",
7016            );
7017            assert_eq!(
7018                first, cpu,
7019                "LimitsSpec::cpu must return :limits :cpu \
7020                 verbatim by copy — got {first:?}, expected {cpu:?}",
7021            );
7022        }
7023    }
7024
7025    // ── LimitsError ctor macro-family equivalence pins ───────────────
7026    //
7027    // Peer discipline of the sibling `layout_violation_ctors!`
7028    // `*_ctor_matches_struct_literal_wrap` pin family (131ca0d) on
7029    // [`LayoutError`], and the sibling `aplicacao_field_reason_ctors!`
7030    // / `contrato_target_ctors!` / `contrato_empty_pair_ctors!` /
7031    // `contrato_pair_value_reason_ctors!` `*_ctor_matches_struct_literal_wrap`
7032    // pin families (981060b / 14b81d5 / 8580068 / 14e13f1) on
7033    // [`AplicacaoError`]. A silent regression that de-folded one variant
7034    // and re-inlined the pre-lift struct-literal at one wire-up site
7035    // (or dropped a field, or diverged the string conversion on one
7036    // arm) trips the affected variant's pin first, so every future edit
7037    // to a variant on the three shared envelopes lands in exactly one
7038    // place.
7039
7040    #[test]
7041    fn non_integer_byte_magnitude_ctor_matches_struct_literal_wrap() {
7042        let value = "1.5KiB";
7043        assert_eq!(
7044            LimitsError::non_integer_byte_magnitude(value),
7045            LimitsError::NonIntegerByteMagnitude {
7046                value: value.to_string(),
7047            },
7048        );
7049    }
7050
7051    #[test]
7052    fn leading_zero_byte_magnitude_ctor_matches_struct_literal_wrap() {
7053        let value = "064MiB";
7054        assert_eq!(
7055            LimitsError::leading_zero_byte_magnitude(value),
7056            LimitsError::LeadingZeroByteMagnitude {
7057                value: value.to_string(),
7058            },
7059        );
7060    }
7061
7062    #[test]
7063    fn non_integer_duration_magnitude_ctor_matches_struct_literal_wrap() {
7064        let value = "1.5s";
7065        assert_eq!(
7066            LimitsError::non_integer_duration_magnitude(value),
7067            LimitsError::NonIntegerDurationMagnitude {
7068                value: value.to_string(),
7069            },
7070        );
7071    }
7072
7073    #[test]
7074    fn leading_zero_duration_magnitude_ctor_matches_struct_literal_wrap() {
7075        let value = "030s";
7076        assert_eq!(
7077            LimitsError::leading_zero_duration_magnitude(value),
7078            LimitsError::LeadingZeroDurationMagnitude {
7079                value: value.to_string(),
7080            },
7081        );
7082    }
7083
7084    #[test]
7085    fn non_integer_millicore_magnitude_ctor_matches_struct_literal_wrap() {
7086        let value = "1.5";
7087        assert_eq!(
7088            LimitsError::non_integer_millicore_magnitude(value),
7089            LimitsError::NonIntegerMillicoreMagnitude {
7090                value: value.to_string(),
7091            },
7092        );
7093    }
7094
7095    #[test]
7096    fn leading_zero_millicore_magnitude_ctor_matches_struct_literal_wrap() {
7097        let value = "0500m";
7098        assert_eq!(
7099            LimitsError::leading_zero_millicore_magnitude(value),
7100            LimitsError::LeadingZeroMillicoreMagnitude {
7101                value: value.to_string(),
7102            },
7103        );
7104    }
7105
7106    #[test]
7107    fn unknown_byte_unit_ctor_matches_struct_literal_wrap() {
7108        // Per-variant byte-equality pin on the `limits_codec_unit_only_ctors!`
7109        // macro's `unknown_byte_unit => UnknownByteUnit` arm. Pins the ctor's
7110        // byte-identity against the open-coded pre-lift struct-literal on the
7111        // same `unit: &str` fixture (the `parse_byte_size` unit-dispatch
7112        // fallthrough hits this arm on any authored unit outside the
7113        // `KB | MB | GB | KiB | MiB | GiB | "" | B` alphabet — pick a
7114        // typography-space suffix so the pin exercises the same Unicode-
7115        // whitespace-in-alpha class the two codecs share). A silent regression
7116        // that de-folded the variant and re-inlined the struct-literal at the
7117        // wire-up (or swapped `.to_string()` for a different `String`
7118        // conversion, or dropped the field) trips the assertion under
7119        // `PartialEq`.
7120        let unit = "TiB";
7121        assert_eq!(
7122            LimitsError::unknown_byte_unit(unit),
7123            LimitsError::UnknownByteUnit {
7124                unit: unit.to_string(),
7125            },
7126        );
7127    }
7128
7129    #[test]
7130    fn unknown_duration_unit_ctor_matches_struct_literal_wrap() {
7131        // Per-variant byte-equality pin on the `limits_codec_unit_only_ctors!`
7132        // macro's `unknown_duration_unit => UnknownDurationUnit` arm. Pins the
7133        // ctor's byte-identity against the open-coded pre-lift struct-literal
7134        // on the same `unit: &str` fixture (the `parse_duration` reverse-map
7135        // arm on [`crate::render::DurationUnitError::UnknownUnit`] hits this
7136        // arm on any authored unit outside the `ms | s | "" | m | h`
7137        // alphabet). Peer of the sibling `unknown_byte_unit` pin above on the
7138        // same shared `{ unit: String }` envelope.
7139        let unit = "d";
7140        assert_eq!(
7141            LimitsError::unknown_duration_unit(unit),
7142            LimitsError::UnknownDurationUnit {
7143                unit: unit.to_string(),
7144            },
7145        );
7146    }
7147
7148    #[test]
7149    fn limits_codec_unit_only_ctors_route_unit_verbatim_across_every_variant() {
7150        // Cross-variant sweep: routes each per-variant `unit: &str` scalar
7151        // through the sole `$ctor => $variant` axis the
7152        // `limits_codec_unit_only_ctors!` macro exposes across a boundary-
7153        // covering fixture set (empty string; the ASCII fallthrough shape the
7154        // two codec wire-up sites actually raise; a Unicode-whitespace-in-
7155        // alpha shape covered by the sibling `parse_*` reject-whitespace
7156        // primitive but plausibly reachable from a future consumer that
7157        // pre-strips whitespace before invoking the ctor directly; a
7158        // multi-byte non-ASCII unit alphabet extension). Any wrapper-side
7159        // truncation, silent `.into()` divergence, per-arm constant
7160        // substitution, or accidental cross-variant field swap on either
7161        // ctor surfaces here on the first fixture the two implementations
7162        // disagree on rather than at a downstream diagnostic-shape drift
7163        // (`LimitsError::to_string()` embeds the offending unit verbatim
7164        // through the `Display`/`Error` derive — a divergence at the ctor
7165        // layer flows straight to the surface diagnostic).
7166        for unit in ["", "TiB", "\u{00A0}", "μs"] {
7167            assert_eq!(
7168                LimitsError::unknown_byte_unit(unit),
7169                LimitsError::UnknownByteUnit {
7170                    unit: unit.to_string(),
7171                },
7172            );
7173            assert_eq!(
7174                LimitsError::unknown_duration_unit(unit),
7175                LimitsError::UnknownDurationUnit {
7176                    unit: unit.to_string(),
7177                },
7178            );
7179        }
7180    }
7181
7182    #[test]
7183    fn whitespace_in_byte_size_ctor_matches_struct_literal_wrap() {
7184        let value = " 64MiB";
7185        let byte: u8 = 0x20;
7186        assert_eq!(
7187            LimitsError::whitespace_in_byte_size(value, byte),
7188            LimitsError::WhitespaceInByteSize {
7189                value: value.to_string(),
7190                byte,
7191            },
7192        );
7193    }
7194
7195    #[test]
7196    fn whitespace_in_duration_ctor_matches_struct_literal_wrap() {
7197        let value = " 30s";
7198        let byte: u8 = 0x09;
7199        assert_eq!(
7200            LimitsError::whitespace_in_duration(value, byte),
7201            LimitsError::WhitespaceInDuration {
7202                value: value.to_string(),
7203                byte,
7204            },
7205        );
7206    }
7207
7208    #[test]
7209    fn whitespace_in_millicores_ctor_matches_struct_literal_wrap() {
7210        let value = " 500m";
7211        let byte: u8 = 0x0A;
7212        assert_eq!(
7213            LimitsError::whitespace_in_millicores(value, byte),
7214            LimitsError::WhitespaceInMillicores {
7215                value: value.to_string(),
7216                byte,
7217            },
7218        );
7219    }
7220
7221    #[test]
7222    fn non_ascii_whitespace_in_byte_size_ctor_matches_struct_literal_wrap() {
7223        let value = "\u{00A0}64MiB";
7224        let ch = '\u{00A0}';
7225        assert_eq!(
7226            LimitsError::non_ascii_whitespace_in_byte_size(value, ch),
7227            LimitsError::NonAsciiWhitespaceInByteSize {
7228                value: value.to_string(),
7229                ch,
7230                codepoint: ch as u32,
7231            },
7232        );
7233    }
7234
7235    #[test]
7236    fn non_ascii_whitespace_in_duration_ctor_matches_struct_literal_wrap() {
7237        let value = "30s\u{2028}";
7238        let ch = '\u{2028}';
7239        assert_eq!(
7240            LimitsError::non_ascii_whitespace_in_duration(value, ch),
7241            LimitsError::NonAsciiWhitespaceInDuration {
7242                value: value.to_string(),
7243                ch,
7244                codepoint: ch as u32,
7245            },
7246        );
7247    }
7248
7249    #[test]
7250    fn non_ascii_whitespace_in_millicores_ctor_matches_struct_literal_wrap() {
7251        let value = "500\u{2003}m";
7252        let ch = '\u{2003}';
7253        assert_eq!(
7254            LimitsError::non_ascii_whitespace_in_millicores(value, ch),
7255            LimitsError::NonAsciiWhitespaceInMillicores {
7256                value: value.to_string(),
7257                ch,
7258                codepoint: ch as u32,
7259            },
7260        );
7261    }
7262
7263    #[test]
7264    fn limits_codec_value_char_ctors_route_codepoint_through_ch_as_u32_uniformly() {
7265        // Cross-family sweep: the load-bearing `codepoint = ch as u32`
7266        // derivation is now spelled once — inside the
7267        // `limits_codec_value_char_ctors!` macro body — rather than
7268        // three times at each wire-up. A silent regression that
7269        // de-folded one variant and re-inlined the derivation with a
7270        // different width (`ch as u16`, `ch as i32`) or dropped it
7271        // entirely trips here on the very first codepoint the two
7272        // implementations disagree on. Every non-ASCII Unicode
7273        // whitespace codepoint the sibling
7274        // `crate::render::find_non_ascii_whitespace_char` predicate
7275        // yields is a valid `char`, so `ch as u32` covers the full
7276        // domain the wire-ups reach.
7277        for ch in [
7278            '\u{00A0}', // NBSP
7279            '\u{2028}', // LINE SEPARATOR
7280            '\u{2003}', // EM SPACE
7281            '\u{202F}', // NARROW NO-BREAK SPACE
7282            '\u{3000}', // IDEOGRAPHIC SPACE
7283        ] {
7284            let value = format!("prefix{ch}suffix");
7285            let expected_codepoint = ch as u32;
7286            assert!(matches!(
7287                LimitsError::non_ascii_whitespace_in_byte_size(&value, ch),
7288                LimitsError::NonAsciiWhitespaceInByteSize { codepoint, .. } if codepoint == expected_codepoint,
7289            ));
7290            assert!(matches!(
7291                LimitsError::non_ascii_whitespace_in_duration(&value, ch),
7292                LimitsError::NonAsciiWhitespaceInDuration { codepoint, .. } if codepoint == expected_codepoint,
7293            ));
7294            assert!(matches!(
7295                LimitsError::non_ascii_whitespace_in_millicores(&value, ch),
7296                LimitsError::NonAsciiWhitespaceInMillicores { codepoint, .. } if codepoint == expected_codepoint,
7297            ));
7298        }
7299    }
7300
7301    // ── limits_scalar_ctors! per-variant + cross-axis pins ──────────────────
7302    //
7303    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
7304    // the [`limits_scalar_ctors!`] macro produces a `LimitsError` structurally
7305    // identical to the pre-lift `Self::<variant> { <field>: <val> }` one-line
7306    // struct-literal on the same `Copy`-`u64 | u32 | Duration` fixture, plus
7307    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
7308    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
7309    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
7310    // substitution on any one variant surfaces here rather than at a
7311    // downstream per-`:limits` diagnostic-shape drift, plus one `const`-eval
7312    // pin that fires at compile time if any future edit silently drops the
7313    // `const` qualifier from the macro body. Peer of the sibling per-variant
7314    // pins on [`crate::supervisor::supervisor_scalar_ctors!`] (f0f77a2, the
7315    // 4-variant `SupervisorError` `{ <field>: RestartStrategy | u32 |
7316    // Duration }` fold on the per-`:supervisor` scalar axis) and the peer
7317    // [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] (7ef425e, the
7318    // 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
7319    // per-`:politicas` per-axis cap / canonical-form arms).
7320    #[test]
7321    fn memory_below_wasm32_page_ctor_matches_struct_literal_wrap() {
7322        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES - 1;
7323        assert_eq!(
7324            LimitsError::memory_below_wasm32_page(bytes),
7325            LimitsError::MemoryBelowWasm32Page { bytes },
7326            "generated memory_below_wasm32_page ctor must produce byte-equal \
7327             `LimitsError::MemoryBelowWasm32Page` to the pre-lift struct-literal \
7328             wrap on the same `Copy`-`u64` fixture",
7329        );
7330    }
7331
7332    #[test]
7333    fn memory_exceeds_wasm32_cap_ctor_matches_struct_literal_wrap() {
7334        let bytes = LIMITS_MEMORY_WASM32_MAX_BYTES + LIMITS_MEMORY_WASM32_PAGE_BYTES;
7335        assert_eq!(
7336            LimitsError::memory_exceeds_wasm32_cap(bytes),
7337            LimitsError::MemoryExceedsWasm32Cap { bytes },
7338            "generated memory_exceeds_wasm32_cap ctor must produce byte-equal \
7339             `LimitsError::MemoryExceedsWasm32Cap` to the pre-lift struct-literal \
7340             wrap on the same `Copy`-`u64` fixture",
7341        );
7342    }
7343
7344    #[test]
7345    fn memory_not_page_multiple_ctor_matches_struct_literal_wrap() {
7346        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
7347        assert_eq!(
7348            LimitsError::memory_not_page_multiple(bytes),
7349            LimitsError::MemoryNotPageMultiple { bytes },
7350            "generated memory_not_page_multiple ctor must produce byte-equal \
7351             `LimitsError::MemoryNotPageMultiple` to the pre-lift struct-literal \
7352             wrap on the same `Copy`-`u64` fixture",
7353        );
7354    }
7355
7356    #[test]
7357    fn fuel_exceeds_cap_ctor_matches_struct_literal_wrap() {
7358        let fuel = LIMITS_FUEL_MAX + 1;
7359        assert_eq!(
7360            LimitsError::fuel_exceeds_cap(fuel),
7361            LimitsError::FuelExceedsCap { fuel },
7362            "generated fuel_exceeds_cap ctor must produce byte-equal \
7363             `LimitsError::FuelExceedsCap` to the pre-lift struct-literal wrap \
7364             on the same `Copy`-`u64` fixture",
7365        );
7366    }
7367
7368    #[test]
7369    fn wall_clock_not_canonical_ctor_matches_struct_literal_wrap() {
7370        let wall_clock = Duration::from_micros(1_500);
7371        assert_eq!(
7372            LimitsError::wall_clock_not_canonical(wall_clock),
7373            LimitsError::WallClockNotCanonical { wall_clock },
7374            "generated wall_clock_not_canonical ctor must produce byte-equal \
7375             `LimitsError::WallClockNotCanonical` to the pre-lift struct-literal \
7376             wrap on the same `Copy`-`Duration` fixture",
7377        );
7378    }
7379
7380    #[test]
7381    fn wall_clock_exceeds_cap_ctor_matches_struct_literal_wrap() {
7382        let wall_clock = LIMITS_WALL_CLOCK_MAX + Duration::from_millis(1);
7383        assert_eq!(
7384            LimitsError::wall_clock_exceeds_cap(wall_clock),
7385            LimitsError::WallClockExceedsCap { wall_clock },
7386            "generated wall_clock_exceeds_cap ctor must produce byte-equal \
7387             `LimitsError::WallClockExceedsCap` to the pre-lift struct-literal \
7388             wrap on the same `Copy`-`Duration` fixture",
7389        );
7390    }
7391
7392    #[test]
7393    fn cpu_exceeds_cap_ctor_matches_struct_literal_wrap() {
7394        let millicores = LIMITS_CPU_MILLICORES_MAX + 1;
7395        assert_eq!(
7396            LimitsError::cpu_exceeds_cap(millicores),
7397            LimitsError::CpuExceedsCap { millicores },
7398            "generated cpu_exceeds_cap ctor must produce byte-equal \
7399             `LimitsError::CpuExceedsCap` to the pre-lift struct-literal wrap \
7400             on the same `Copy`-`u32` fixture",
7401        );
7402    }
7403
7404    #[test]
7405    fn limits_scalar_ctors_route_field_through_copy_uniformly() {
7406        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
7407        // constructor input axis through a non-default `Copy` fixture against
7408        // every arm in the [`limits_scalar_ctors!`] macro, so any wrapper-
7409        // side silent `.into()` / silent constant-substitution / silent field
7410        // re-name away from the canonical `bytes | fuel | wall_clock |
7411        // millicores` axes on any one variant, or a `u64 | u32 | Duration`
7412        // axis silently rerouted through some other `Copy` coercion, surfaces
7413        // here rather than at a downstream per-`:limits` diagnostic-shape
7414        // drift. Peer of the sibling
7415        // `supervisor_scalar_ctors_route_field_through_copy_uniformly`
7416        // (f0f77a2) and
7417        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
7418        // (7ef425e) cross-axis routing pins on the sibling `SupervisorError`
7419        // / `AplicacaoError` envelopes' per-axis ctor families.
7420        //
7421        // Fixtures picked out of each variant's accept-set boundary rather
7422        // than the default value so a silent constant-substitution to a
7423        // per-variant sentinel surfaces here on the structural-equality
7424        // assertion: the three `:memory` axes pick the below-page / above-cap
7425        // / page-plus-one shapes; the `:fuel` cap picks the above-cap shape;
7426        // the two `:wall-clock` axes pick sub-millisecond and above-cap
7427        // `Duration` shapes; the `:cpu` cap picks the above-cap millicore
7428        // shape.
7429        let below_page = LIMITS_MEMORY_WASM32_PAGE_BYTES - 137;
7430        let above_mem_cap = LIMITS_MEMORY_WASM32_MAX_BYTES + LIMITS_MEMORY_WASM32_PAGE_BYTES;
7431        let page_plus_one = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
7432        let above_fuel_cap = LIMITS_FUEL_MAX + 137;
7433        let sub_ms = Duration::from_micros(1_500);
7434        let above_hour = LIMITS_WALL_CLOCK_MAX + Duration::from_secs(1);
7435        let above_cpu_cap = LIMITS_CPU_MILLICORES_MAX + 137;
7436        assert_eq!(
7437            LimitsError::memory_below_wasm32_page(below_page),
7438            LimitsError::MemoryBelowWasm32Page { bytes: below_page },
7439        );
7440        assert_eq!(
7441            LimitsError::memory_exceeds_wasm32_cap(above_mem_cap),
7442            LimitsError::MemoryExceedsWasm32Cap {
7443                bytes: above_mem_cap,
7444            },
7445        );
7446        assert_eq!(
7447            LimitsError::memory_not_page_multiple(page_plus_one),
7448            LimitsError::MemoryNotPageMultiple {
7449                bytes: page_plus_one,
7450            },
7451        );
7452        assert_eq!(
7453            LimitsError::fuel_exceeds_cap(above_fuel_cap),
7454            LimitsError::FuelExceedsCap {
7455                fuel: above_fuel_cap,
7456            },
7457        );
7458        assert_eq!(
7459            LimitsError::wall_clock_not_canonical(sub_ms),
7460            LimitsError::WallClockNotCanonical { wall_clock: sub_ms },
7461        );
7462        assert_eq!(
7463            LimitsError::wall_clock_exceeds_cap(above_hour),
7464            LimitsError::WallClockExceedsCap {
7465                wall_clock: above_hour,
7466            },
7467        );
7468        assert_eq!(
7469            LimitsError::cpu_exceeds_cap(above_cpu_cap),
7470            LimitsError::CpuExceedsCap {
7471                millicores: above_cpu_cap,
7472            },
7473        );
7474    }
7475
7476    #[test]
7477    fn limits_scalar_ctors_are_const_zero_runtime_work() {
7478        // Const-eval pin: the [`limits_scalar_ctors!`] macro spells every
7479        // generated ctor `const fn` so a caller can pin a `LimitsError` at
7480        // compile time — the same zero-runtime-work property the pre-lift
7481        // `|<field>| LimitsError::<Variant> { <field> }` closure carried on
7482        // its `Copy`-pass-through construction path (no `.to_string()` /
7483        // `.into()` allocation, no branching). If any future edit silently
7484        // drops the `const` qualifier from the macro body the per-arm `const`
7485        // bindings below fail to compile, which surfaces the regression at
7486        // the substrate-primitive definition rather than at some downstream
7487        // consumer that had come to rely on the `const`-constructibility.
7488        // Peer of the sibling
7489        // `supervisor_scalar_ctors_are_const_zero_runtime_work` (f0f77a2) and
7490        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
7491        // (7ef425e) const-eval pins on the sibling `SupervisorError` /
7492        // `AplicacaoError` envelopes' per-axis ctor families.
7493        const MEM_BELOW: LimitsError = LimitsError::memory_below_wasm32_page(1);
7494        const MEM_CAP: LimitsError =
7495            LimitsError::memory_exceeds_wasm32_cap(LIMITS_MEMORY_WASM32_MAX_BYTES + 1);
7496        const MEM_NOT_MULTIPLE: LimitsError =
7497            LimitsError::memory_not_page_multiple(LIMITS_MEMORY_WASM32_PAGE_BYTES + 1);
7498        const FUEL_CAP: LimitsError = LimitsError::fuel_exceeds_cap(LIMITS_FUEL_MAX + 1);
7499        const WALL_NC: LimitsError =
7500            LimitsError::wall_clock_not_canonical(Duration::from_micros(1));
7501        const WALL_CAP: LimitsError =
7502            LimitsError::wall_clock_exceeds_cap(Duration::from_secs(3_601));
7503        const CPU_CAP: LimitsError = LimitsError::cpu_exceeds_cap(LIMITS_CPU_MILLICORES_MAX + 1);
7504        assert!(matches!(
7505            MEM_BELOW,
7506            LimitsError::MemoryBelowWasm32Page { .. }
7507        ));
7508        assert!(matches!(
7509            MEM_CAP,
7510            LimitsError::MemoryExceedsWasm32Cap { .. }
7511        ));
7512        assert!(matches!(
7513            MEM_NOT_MULTIPLE,
7514            LimitsError::MemoryNotPageMultiple { .. }
7515        ));
7516        assert!(matches!(FUEL_CAP, LimitsError::FuelExceedsCap { .. }));
7517        assert!(matches!(WALL_NC, LimitsError::WallClockNotCanonical { .. }));
7518        assert!(matches!(WALL_CAP, LimitsError::WallClockExceedsCap { .. }));
7519        assert!(matches!(CPU_CAP, LimitsError::CpuExceedsCap { .. }));
7520    }
7521
7522    #[test]
7523    fn bad_millicores_ctor_matches_tuple_literal_wrap_on_str_binding() {
7524        // Per-variant byte-equality pin on the newly lifted
7525        // [`LimitsError::bad_millicores`] tuple-newtype ctor over its `&str`
7526        // wire-up shape — the three [`parse_millicores`] sites that opened
7527        // the pre-lift `LimitsError::BadMillicores(s.into())` block against
7528        // the codec-scoped `s: &str` binding (empty-`:cpu`, bare-`m`-
7529        // magnitude fallthrough, non-digit-only garbage fallthrough). A
7530        // silent regression that de-folded the variant and re-inlined the
7531        // tuple-newtype block at one of the three wire-ups (or swapped
7532        // `.into()` for a divergent `String` conversion, or routed one arm
7533        // through a peer variant) trips the assertion under `PartialEq`.
7534        // Peer of the sibling `*_ctor_matches_struct_literal_wrap` pin
7535        // family on the same [`LimitsError`] envelope.
7536        let value = "500x";
7537        assert_eq!(
7538            LimitsError::bad_millicores(value),
7539            LimitsError::BadMillicores(value.to_string()),
7540            "generated bad_millicores ctor over a `&str` binding must \
7541             produce byte-equal `LimitsError::BadMillicores` to the \
7542             pre-lift tuple-newtype wrap on the same `&str` fixture",
7543        );
7544    }
7545
7546    #[test]
7547    fn bad_millicores_ctor_matches_tuple_literal_wrap_on_string_binding() {
7548        // Peer to the sibling `&str`-binding pin above, on the
7549        // `String` wire-up shape — the two [`parse_millicores`] sites that
7550        // opened the pre-lift `LimitsError::BadMillicores(format!(...))`
7551        // block against a codec-scoped `String` binding (digit-only
7552        // magnitude overflows u32, bare-core-shorthand × 1000 overflow).
7553        // Pins that the `impl Into<String>` bound routes both wire-up
7554        // shapes through the same substrate primitive without silently
7555        // rerouting one arm through a divergent conversion. A silent
7556        // regression that de-folded one of the two sites trips this pin
7557        // under `PartialEq`.
7558        let value: String = format!("{} (digit-only magnitude overflows u32)", u32::MAX);
7559        assert_eq!(
7560            LimitsError::bad_millicores(value.clone()),
7561            LimitsError::BadMillicores(value.clone()),
7562            "generated bad_millicores ctor over a `String` binding must \
7563             produce byte-equal `LimitsError::BadMillicores` to the \
7564             pre-lift tuple-newtype wrap on the same `String` fixture",
7565        );
7566    }
7567
7568    #[test]
7569    fn bad_byte_magnitude_ctor_matches_tuple_literal_wrap_on_str_binding() {
7570        // Per-variant byte-equality pin on the newly lifted
7571        // [`LimitsError::bad_byte_magnitude`] tuple-newtype ctor over its
7572        // `&str` wire-up shape — the sole [`parse_byte_size`] site that
7573        // opened the pre-lift `LimitsError::BadByteMagnitude(num_part.into())`
7574        // block against a codec-scoped `&str` binding (non-digit-only garbage
7575        // fallthrough after the numeric-shape gate). A silent regression
7576        // that de-folded the variant and re-inlined the tuple-newtype block
7577        // at the wire-up (or swapped `.into()` for a divergent `String`
7578        // conversion, or routed one arm through a peer variant) trips the
7579        // assertion under `PartialEq`. Direct sibling to the peer
7580        // `bad_millicores_ctor_matches_tuple_literal_wrap_on_str_binding`
7581        // pin on the [`parse_millicores`] codec surface.
7582        let value = "abc";
7583        assert_eq!(
7584            LimitsError::bad_byte_magnitude(value),
7585            LimitsError::BadByteMagnitude(value.to_string()),
7586            "generated bad_byte_magnitude ctor over a `&str` binding must \
7587             produce byte-equal `LimitsError::BadByteMagnitude` to the \
7588             pre-lift tuple-newtype wrap on the same `&str` fixture",
7589        );
7590    }
7591
7592    #[test]
7593    fn bad_byte_magnitude_ctor_matches_tuple_literal_wrap_on_string_binding() {
7594        // Peer to the sibling `&str`-binding pin above, on the
7595        // `String` wire-up shape — the two [`parse_byte_size`] sites that
7596        // opened the pre-lift `LimitsError::BadByteMagnitude(format!(...))`
7597        // block against a codec-scoped `String` binding (digit-only
7598        // magnitude overflows u64, magnitude × unit overflows u64). Pins
7599        // that the `impl Into<String>` bound routes both wire-up shapes
7600        // through the same substrate primitive without silently rerouting
7601        // one arm through a divergent conversion. A silent regression
7602        // that de-folded one of the two sites trips this pin under
7603        // `PartialEq`. Direct sibling to the peer
7604        // `bad_millicores_ctor_matches_tuple_literal_wrap_on_string_binding`
7605        // pin on the [`parse_millicores`] codec surface.
7606        let value: String = format!("{} (digit-only magnitude overflows u64)", u64::MAX);
7607        assert_eq!(
7608            LimitsError::bad_byte_magnitude(value.clone()),
7609            LimitsError::BadByteMagnitude(value.clone()),
7610            "generated bad_byte_magnitude ctor over a `String` binding must \
7611             produce byte-equal `LimitsError::BadByteMagnitude` to the \
7612             pre-lift tuple-newtype wrap on the same `String` fixture",
7613        );
7614    }
7615
7616    #[test]
7617    fn bad_duration_magnitude_ctor_matches_tuple_literal_wrap_on_str_binding() {
7618        // Per-variant byte-equality pin on the newly lifted
7619        // [`LimitsError::bad_duration_magnitude`] tuple-newtype ctor over its
7620        // `&str` wire-up shape — the sole [`parse_duration`] site that opened
7621        // the pre-lift `LimitsError::BadDurationMagnitude(num_part.into())`
7622        // block against a codec-scoped `&str` binding (non-digit-only garbage
7623        // fallthrough after the numeric-shape gate). A silent regression that
7624        // de-folded the variant and re-inlined the tuple-newtype block at the
7625        // wire-up (or swapped `.into()` for a divergent `String` conversion,
7626        // or routed one arm through a peer variant) trips the assertion under
7627        // `PartialEq`. Direct sibling to the peer
7628        // `bad_millicores_ctor_matches_tuple_literal_wrap_on_str_binding` /
7629        // `bad_byte_magnitude_ctor_matches_tuple_literal_wrap_on_str_binding`
7630        // pins on the [`parse_millicores`] / [`parse_byte_size`] codec
7631        // surfaces — closes the last un-lifted `(String)` tuple-newtype
7632        // variant on the paired codec-magnitude family.
7633        let value = "abc";
7634        assert_eq!(
7635            LimitsError::bad_duration_magnitude(value),
7636            LimitsError::BadDurationMagnitude(value.to_string()),
7637            "generated bad_duration_magnitude ctor over a `&str` binding must \
7638             produce byte-equal `LimitsError::BadDurationMagnitude` to the \
7639             pre-lift tuple-newtype wrap on the same `&str` fixture",
7640        );
7641    }
7642
7643    #[test]
7644    fn bad_duration_magnitude_ctor_matches_tuple_literal_wrap_on_string_binding() {
7645        // Peer to the sibling `&str`-binding pin above, on the
7646        // `String` wire-up shape — the two [`parse_duration`] sites that
7647        // opened the pre-lift `LimitsError::BadDurationMagnitude(format!(...))`
7648        // block against a codec-scoped `String` binding (digit-only magnitude
7649        // overflows u64, magnitude × unit overflows u64). Pins that the
7650        // `impl Into<String>` bound routes both wire-up shapes through the
7651        // same substrate primitive without silently rerouting one arm through
7652        // a divergent conversion. A silent regression that de-folded one of
7653        // the two sites trips this pin under `PartialEq`. Direct sibling to
7654        // the peer `bad_millicores_ctor_matches_tuple_literal_wrap_on_string_binding`
7655        // / `bad_byte_magnitude_ctor_matches_tuple_literal_wrap_on_string_binding`
7656        // pins on the [`parse_millicores`] / [`parse_byte_size`] codec
7657        // surfaces.
7658        let value: String = format!("{} (digit-only magnitude overflows u64)", u64::MAX);
7659        assert_eq!(
7660            LimitsError::bad_duration_magnitude(value.clone()),
7661            LimitsError::BadDurationMagnitude(value.clone()),
7662            "generated bad_duration_magnitude ctor over a `String` binding must \
7663             produce byte-equal `LimitsError::BadDurationMagnitude` to the \
7664             pre-lift tuple-newtype wrap on the same `String` fixture",
7665        );
7666    }
7667}