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                |bytes| LimitsError::MemoryBelowWasm32Page { bytes },
759                |bytes| LimitsError::MemoryExceedsWasm32Cap { bytes },
760                |bytes| LimitsError::MemoryNotPageMultiple { bytes },
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                |fuel| LimitsError::FuelExceedsCap { fuel },
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                |wall_clock| LimitsError::WallClockNotCanonical { wall_clock },
823                |wall_clock| LimitsError::WallClockExceedsCap { wall_clock },
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                |millicores| LimitsError::CpuExceedsCap { millicores },
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::WhitespaceInByteSize {
1198            value: s.into(),
1199            byte,
1200        },
1201        |ch| LimitsError::NonAsciiWhitespaceInByteSize {
1202            value: s.into(),
1203            ch,
1204            codepoint: ch as u32,
1205        },
1206    )?;
1207    let s = s.trim();
1208    if s.is_empty() {
1209        return Err(LimitsError::EmptyByteSize(s.into()));
1210    }
1211    // Route the `<integer><ASCII-alphabetic-unit>` split through the
1212    // lifted [`crate::render::split_magnitude_and_alpha_unit`] primitive
1213    // — the substrate-side single-owner split every ASCII-alphabetic-unit
1214    // typed-magnitude codec in caixa-core (`parse_byte_size` /
1215    // `parse_duration` / `supervisor::duration_codec::parse`) shares.
1216    // Drift between any two codec sites' magnitude/unit split rule
1217    // becomes a single-edit fix at the composed helper rather than three
1218    // independent `s.find(|c: char| c.is_ascii_alphabetic())` re-inlines
1219    // diverging over time.
1220    let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
1221    let num_trim = num_part.trim();
1222    // The canonical authoring form for `:limits :memory` is
1223    // `<integer><unit>` — every magnitude `render_byte_size` emits is a
1224    // non-negative integer with no decimal point and no leading sign,
1225    // so the parser's accepted set must match for serialize/deserialize
1226    // to round-trip without canonical-form drift. Until this gate
1227    // landed the parser accepted any `f64`-shaped magnitude
1228    // (`"1.5KiB"` → 1536 bytes, `"1.0MiB"` → 1MiB, `"0.5GiB"` → 512MiB,
1229    // `"+1024"` → 1024) and serde silently round-tripped the value to
1230    // a *different* canonical string on the next emit (`"1.5KiB"` →
1231    // 1536 → `"1536"`, `"1.0MiB"` → 1048576 → `"1MiB"`, `"0.5GiB"` →
1232    // 536870912 → `"512MiB"`, `"+1024"` → 1024 → `"1KiB"`) — breaking
1233    // the THEORY.md §V.2.7 render-determinism contract every typed slot
1234    // carries.
1235    //
1236    // Strict canonical form: every byte of the magnitude is an ASCII
1237    // digit (no `.`, no `+`, no `-`). On current Rust `u64::from_str`
1238    // permissively accepts a leading `+` (`"+1024"` → 1024) — that's a
1239    // canonical-drift shape `render_byte_size` never emits, so the
1240    // digit-only check is what closes the leading-sign class; relying
1241    // on `u64::from_str`'s strictness alone would silently admit it.
1242    // On non-digit-only inputs the gate distinguishes "non-canonical-
1243    // but-numeric" (parses as f64 or i64, so it's an authoring-shape
1244    // footgun) from "garbage" (parses as neither, so it's not a
1245    // numeric input at all) — the diagnostic names the offending
1246    // magnitude shape verbatim rather than collapsing both authoring
1247    // footguns into a single opaque `BadByteMagnitude`.
1248    //
1249    // Same canonical-form discipline
1250    // [`crate::AplicacaoSpec::validate_politicas`]'s
1251    // [`is_canonical_rate_limit_window`] gate (808017c) applies to the
1252    // rate-limit `:window` axis — the codec's accepted set matches its
1253    // emitted set, structurally.
1254    //
1255    // (Scientific-notation magnitudes like `"1e3KiB"` are also rejected,
1256    // but on a different arm: the parser splits on the first ASCII-
1257    // alphabetic byte, so the `e` is read as a unit prefix and the
1258    // input falls into the `UnknownByteUnit { unit: "e3KiB" }` branch
1259    // before this gate is consulted — that's the existing diagnostic
1260    // for the scientific-shape footgun, and this gate is additive to
1261    // it.)
1262    //
1263    // Routed through the lifted
1264    // [`crate::render::is_digit_only_magnitude`] predicate — the
1265    // single source of truth every typed-magnitude codec in
1266    // caixa-core (`parse_byte_size` / `parse_duration` /
1267    // `parse_millicores` / `supervisor::duration_codec` /
1268    // `rate_limit_codec`) shares. Drift between any two codec sites'
1269    // digit-only rejection set becomes a single-edit fix at the
1270    // shared predicate rather than five independent
1271    // `!<var>.is_empty() && <var>.bytes().all(|b| b.is_ascii_digit())`
1272    // scans diverging over time — same "single lifted source of truth"
1273    // discipline the peer canonical-form predicates
1274    // ([`crate::render::find_ascii_whitespace_byte`] /
1275    // [`crate::render::find_non_ascii_whitespace_char`] /
1276    // [`crate::render::is_leading_zero_padded_magnitude`]) carry on
1277    // the whitespace and leading-zero-padding drift-class axes.
1278    let digit_only = crate::render::is_digit_only_magnitude(num_trim);
1279    if !digit_only {
1280        // Distinguish "non-canonical-but-numeric" (`"1.5"`, `"1.0"`,
1281        // `"+1024"`, `"-1"`) from "garbage" (`"abc"`, `"--1"`) so the
1282        // diagnostic names the offending magnitude shape verbatim.
1283        // Use f64 + i64 fallbacks for the "numeric" detection so every
1284        // non-digit-only-but-parseable input lands on
1285        // `NonIntegerByteMagnitude` regardless of sign or fractionality.
1286        let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
1287        if numeric {
1288            return Err(LimitsError::NonIntegerByteMagnitude {
1289                value: num_trim.into(),
1290            });
1291        }
1292        return Err(LimitsError::BadByteMagnitude(num_part.into()));
1293    }
1294    // Leading-zero arm — peer with the `parse_duration` leading-zero
1295    // arm (39762d7), the `supervisor::duration_codec` leading-zero arm
1296    // (9178904) and the `rate_limit_codec` leading-zero arm (4f46830)
1297    // on the same canonical-form render-determinism axis. The
1298    // digit-only gate accepts `"0064MiB"`, `"01024"`, `"00KiB"`,
1299    // `"0500MB"` as `u64::from_str` parses them losslessly (= 64, 1024,
1300    // 0, 500), but `render_byte_size` emits the leading-zero-stripped
1301    // form (`"64MiB"`, `"1KiB"`, `"0"`, `"500MB"`) — a *different*
1302    // canonical string on the next emit, breaking the THEORY.md Part V
1303    // render-determinism contract the same way `"+1024"` did before the
1304    // leading-`+` arm landed. The single-byte magnitude `"0"` (or
1305    // `"0B"` / `"0KiB"`) round-trips losslessly through
1306    // `render_byte_size` (`render_byte_size(0)` emits `"0"`) — the
1307    // downstream semantic-zero gate [`LimitsError::MemoryZero`] refuses
1308    // zero-magnitude authoring at the typed-validate layer above, so
1309    // the single-byte `"0"` stays in the accepted set at this codec
1310    // layer and the diagnostic partitioning between canonical-form
1311    // drift (this arm) and semantic-zero (the downstream gate) remains
1312    // stable. Same codec-layer / typed-validate-layer partition the
1313    // peer codecs preserve.
1314    //
1315    // Routed through the lifted
1316    // [`crate::render::is_leading_zero_padded_magnitude`] predicate —
1317    // the single source of truth every typed-magnitude codec in
1318    // caixa-core (`parse_byte_size` / `parse_duration` /
1319    // `parse_millicores` / `supervisor::duration_codec` /
1320    // `rate_limit_codec`) shares. Drift between any two codec sites'
1321    // leading-zero rejection set becomes a single-edit fix at the
1322    // shared predicate rather than five independent
1323    // `s.len() > 1 && s.as_bytes()[0] == b'0'` scans diverging over
1324    // time — same "single lifted source of truth" discipline the
1325    // peer whitespace predicates
1326    // ([`crate::render::find_ascii_whitespace_byte`] /
1327    // [`crate::render::find_non_ascii_whitespace_char`]) carry on
1328    // their strictly-complementary axes.
1329    if crate::render::is_leading_zero_padded_magnitude(num_trim) {
1330        return Err(LimitsError::LeadingZeroByteMagnitude {
1331            value: num_trim.into(),
1332        });
1333    }
1334    // `digit_only` guarantees every byte is `[0-9]`, so the only way
1335    // u64::from_str can fail here is overflow (the magnitude exceeds
1336    // u64::MAX). Surface that as `BadByteMagnitude` with an overflow-
1337    // shaped wording so the diagnostic names the offending magnitude
1338    // verbatim rather than collapsing onto the non-canonical arm.
1339    let num: u64 = num_trim.parse::<u64>().map_err(|_| {
1340        LimitsError::BadByteMagnitude(format!("{num_trim} (digit-only magnitude overflows u64)"))
1341    })?;
1342    let multiplier: u64 = match unit.trim() {
1343        "" | "B" => 1,
1344        "KB" => 1_000,
1345        "MB" => 1_000_000,
1346        "GB" => 1_000_000_000,
1347        "KiB" => 1024,
1348        "MiB" => 1024 * 1024,
1349        "GiB" => 1024 * 1024 * 1024,
1350        other => {
1351            return Err(LimitsError::UnknownByteUnit { unit: other.into() });
1352        }
1353    };
1354    // Overflow surfaces as `BadByteMagnitude` (a u64-saturating
1355    // multiply would silently truncate to `u64::MAX` and then the
1356    // wasm32-cap gate at validate time would catch it — but a u64
1357    // overflow is a parse-shaped failure on the author's input, not a
1358    // domain-cap rejection on a well-formed value, so it surfaces here
1359    // as a parser diagnostic naming the offending magnitude × unit
1360    // pair rather than as `MemoryExceedsWasm32Cap { bytes: u64::MAX }`
1361    // far from the author's intent).
1362    num.checked_mul(multiplier).ok_or_else(|| {
1363        LimitsError::BadByteMagnitude(format!(
1364            "{num_trim}{unit_trim} overflows u64 (magnitude × unit > 2^64-1)",
1365            unit_trim = unit.trim()
1366        ))
1367    })
1368}
1369
1370fn render_byte_size(n: u64) -> String {
1371    // Prefer the largest power-of-1024 unit that divides cleanly; fall
1372    // back to bytes if nothing matches.
1373    const UNITS: &[(u64, &str)] = &[
1374        (1024 * 1024 * 1024, "GiB"),
1375        (1024 * 1024, "MiB"),
1376        (1024, "KiB"),
1377    ];
1378    for (mult, label) in UNITS {
1379        if n >= *mult && n.is_multiple_of(*mult) {
1380            return format!("{}{label}", n / mult);
1381        }
1382    }
1383    format!("{n}")
1384}
1385
1386fn ser_byte_size<S: Serializer>(v: &Option<u64>, s: S) -> Result<S::Ok, S::Error> {
1387    // Route through the canonical [`crate::render::serialize_option_via_str`]
1388    // — the substrate-side single-owner primitive for the forward arm
1389    // of the typed-magnitude codec family. See its docstring for the
1390    // full sibling roster and the compounding rationale that pins this
1391    // lift; load-bearing pinned by
1392    // `tests::ser_byte_size_routes_through_render_serialize_option_via_str_canonical`.
1393    crate::render::serialize_option_via_str(v, s, render_byte_size)
1394}
1395
1396fn de_byte_size<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
1397    // Route through the canonical [`crate::render::deserialize_option_via_str`]
1398    // — the substrate-side single-owner primitive for the reverse arm
1399    // of the typed-magnitude codec family. See its docstring for the
1400    // full sibling roster and the compounding rationale that pins this
1401    // lift; load-bearing pinned by
1402    // `tests::de_byte_size_routes_through_render_deserialize_option_via_str_canonical`.
1403    crate::render::deserialize_option_via_str(d, parse_byte_size)
1404}
1405
1406// ── duration codec ─────────────────────────────────────────────────────
1407
1408fn parse_duration(s: &str) -> Result<Duration, LimitsError> {
1409    // Paired whitespace-rejection arm — same canonical-form
1410    // render-determinism discipline as the peer `parse_byte_size` /
1411    // `parse_millicores` / `supervisor::duration_codec::parse` /
1412    // `rate_limit_codec::parse` sites: the ASCII byte-scan closes the
1413    // WhatWG-conformant whitespace bytes every downstream YAML / JSON /
1414    // TOML parser can feed through a quoted-scalar value verbatim
1415    // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
1416    // `char::is_whitespace` scan closes the strictly-complementary
1417    // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
1418    // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
1419    // codepoints) that `str::trim` at parse entry silently strips.
1420    // Either drift class would round-trip through `render_duration` to
1421    // a *different* canonical form on next emit — breaking the
1422    // THEORY.md Part V render-determinism contract. Diagnostics stay
1423    // typed at `WhitespaceInDuration` / `NonAsciiWhitespaceInDuration`.
1424    //
1425    // Routed through the lifted [`crate::render::reject_whitespace`]
1426    // primitive — the substrate-side single-owner paired-arm gate every
1427    // typed-magnitude codec in caixa-core shares.
1428    crate::render::reject_whitespace(
1429        s,
1430        |byte| LimitsError::WhitespaceInDuration {
1431            value: s.into(),
1432            byte,
1433        },
1434        |ch| LimitsError::NonAsciiWhitespaceInDuration {
1435            value: s.into(),
1436            ch,
1437            codepoint: ch as u32,
1438        },
1439    )?;
1440    let s = s.trim();
1441    if s.is_empty() {
1442        return Err(LimitsError::EmptyDuration(s.into()));
1443    }
1444    // Routed through the lifted
1445    // [`crate::render::split_magnitude_and_alpha_unit`] primitive — the
1446    // single-owner split every ASCII-alphabetic-unit typed-magnitude
1447    // codec in caixa-core shares. See its docstring for the full
1448    // sibling roster on the same primitive altitude.
1449    let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
1450    let num_trim = num_part.trim();
1451    // The canonical authoring form for `:limits :wall-clock` is
1452    // `<integer><unit>` — every magnitude `render_duration` emits is a
1453    // non-negative integer with no decimal point and no leading sign,
1454    // so the parser's accepted set must match for serialize/deserialize
1455    // to round-trip without canonical-form drift. Until this gate
1456    // landed the parser accepted any `f64`-shaped magnitude
1457    // (`"1.5s"` → 1500ms, `"1.0s"` → 1s, `"0.5m"` → 30s, `"+30s"` →
1458    // 30s) and serde silently round-tripped the value to a *different*
1459    // canonical string on the next emit (`"1.5s"` → 1500ms →
1460    // `"1500ms"`, `"1.0s"` → 1s → `"1s"`, `"0.5m"` → 30s → `"30s"`,
1461    // `"+30s"` → 30s → `"30s"`) — breaking the THEORY.md Part V
1462    // render-determinism contract every typed slot carries. The same
1463    // canonical-form discipline `parse_byte_size`'s integer-magnitude
1464    // gate (the immediate predecessor on the peer `:limits :memory`
1465    // codec) applies; this gate is the direct successor on the
1466    // `:limits :wall-clock` codec.
1467    //
1468    // Strict canonical form: every byte of the magnitude is an ASCII
1469    // digit (no `.`, no `+`, no `-`). On current Rust `u64::from_str`
1470    // permissively accepts a leading `+` (`"+30"` → 30) — that's a
1471    // canonical-drift shape `render_duration` never emits, so the
1472    // digit-only check is what closes the leading-sign class; relying
1473    // on `u64::from_str`'s strictness alone would silently admit it.
1474    // On non-digit-only inputs the gate distinguishes "non-canonical-
1475    // but-numeric" (parses as f64 or i64 — surfaced as the new
1476    // `NonIntegerDurationMagnitude` variant with a self-locating
1477    // diagnostic) from "garbage" (parses as neither — surfaced as the
1478    // existing `BadDurationMagnitude` so its narrower diagnostic
1479    // remains load-bearing).
1480    //
1481    // Routed through the lifted
1482    // [`crate::render::is_digit_only_magnitude`] predicate — the same
1483    // source of truth the four peer typed-magnitude codec sites share.
1484    let digit_only = crate::render::is_digit_only_magnitude(num_trim);
1485    if !digit_only {
1486        let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
1487        if numeric {
1488            return Err(LimitsError::NonIntegerDurationMagnitude {
1489                value: num_trim.into(),
1490            });
1491        }
1492        return Err(LimitsError::BadDurationMagnitude(num_part.into()));
1493    }
1494    // Leading-zero arm — peer with the `supervisor::duration_codec`
1495    // leading-zero arm (9178904) and the `rate_limit_codec`
1496    // leading-zero arm (4f46830) on the same canonical-form
1497    // render-determinism axis. The digit-only gate accepts `"030s"`,
1498    // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
1499    // losslessly (= 30, 0, 1, 500), but `render_duration` emits the
1500    // leading-zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`)
1501    // — a *different* canonical string on the next emit, breaking the
1502    // THEORY.md Part V render-determinism contract the same way
1503    // `"+30s"` did before the leading-`+` arm landed. The single-byte
1504    // magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips losslessly
1505    // through `render_duration` (`render_duration(Duration::ZERO)`
1506    // emits `"0s"`) — the downstream semantic-zero gate
1507    // [`LimitsError::WallClockZero`] refuses zero-magnitude authoring
1508    // at the typed-validate layer above, so the single-byte `"0"`
1509    // stays in the accepted set at this codec layer and the
1510    // diagnostic partitioning between canonical-form drift (this arm)
1511    // and semantic-zero (the downstream gate) remains stable. Same
1512    // codec-layer / typed-validate-layer partition the peer codecs
1513    // preserve.
1514    //
1515    // Routed through the lifted
1516    // [`crate::render::is_leading_zero_padded_magnitude`] predicate —
1517    // the same source of truth the four peer typed-magnitude codec
1518    // sites share.
1519    if crate::render::is_leading_zero_padded_magnitude(num_trim) {
1520        return Err(LimitsError::LeadingZeroDurationMagnitude {
1521            value: num_trim.into(),
1522        });
1523    }
1524    // The digit-only gate guarantees every byte is `[0-9]`, and the
1525    // leading-zero arm above guarantees the magnitude is either the
1526    // single byte `"0"` or starts with `[1-9]`, so the only way
1527    // `u64::from_str` can fail here is overflow.
1528    let num: u64 = num_trim.parse::<u64>().map_err(|_| {
1529        LimitsError::BadDurationMagnitude(format!(
1530            "{num_trim} (digit-only magnitude overflows u64)"
1531        ))
1532    })?;
1533    // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration` unit-arm
1534    // dispatch through the canonical
1535    // [`crate::render::duration_from_integer_magnitude_and_unit`]
1536    // primitive — the substrate-side single-owner unit-dispatch table
1537    // every typed-duration codec in caixa-core routes through
1538    // (peer: `supervisor::duration_codec::parse` backing the shared
1539    // `:supervisor :restart-window` / `:politicas :timeout` /
1540    // `:politicas :circuit-breaker :window` slots). Every unit
1541    // conversion is integer-exact for an integer magnitude; overflow
1542    // surfaces via the typed `DurationUnitError::Overflow { multiplier }`
1543    // discriminant so this arm reconstructs the pre-lift
1544    // `"…overflows u64 (magnitude × 60 > 2^64-1)"` /
1545    // `"…overflows u64 (magnitude × 3600 > 2^64-1)"` wording verbatim
1546    // from `num_trim` / `unit_trim` / the returned `multiplier`, and
1547    // the unknown-unit arm reconstructs the pre-lift
1548    // `LimitsError::UnknownDurationUnit { unit }` variant from the
1549    // caller-scoped `unit_trim`. Load-bearing pinned by
1550    // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
1551    let unit_trim = unit.trim();
1552    let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
1553        |e| match e {
1554            crate::render::DurationUnitError::Overflow { multiplier } => {
1555                LimitsError::BadDurationMagnitude(format!(
1556                    "{num_trim}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
1557                ))
1558            }
1559            crate::render::DurationUnitError::UnknownUnit => LimitsError::UnknownDurationUnit {
1560                unit: unit_trim.into(),
1561            },
1562        },
1563    )?;
1564    Ok(dur)
1565}
1566
1567fn ser_duration<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
1568    // Route through the canonical [`crate::render::serialize_option_via_str`]
1569    // — the substrate-side single-owner primitive for the forward arm
1570    // of the typed-magnitude codec family — around the canonical
1571    // [`crate::supervisor::duration_codec::render`] duration-byte
1572    // dispatch. The `render` dispatch is itself the load-bearing
1573    // single-owner primitive for duration bytes across every caixa
1574    // typed-duration surface (`:limits :wall-clock`,
1575    // `:politicas :timeout`, `:circuit-breaker :window`, future OTP
1576    // `gen_server` per-call timeouts); the outer
1577    // `serialize_option_via_str` closes the `Some(_) => serialize_str`
1578    // / `None => serialize_none` `Option`-arm dispatch every peer
1579    // typed-magnitude serializer shares. Load-bearing pinned by
1580    // `tests::ser_duration_routes_through_supervisor_duration_codec_render_canonical`.
1581    crate::render::serialize_option_via_str(v, s, crate::supervisor::duration_codec::render)
1582}
1583
1584fn de_duration<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
1585    // Route through the canonical [`crate::render::deserialize_option_via_str`]
1586    // — the substrate-side single-owner primitive for the reverse arm
1587    // of the typed-magnitude codec family. See its docstring for the
1588    // full sibling roster and the compounding rationale that pins this
1589    // lift.
1590    crate::render::deserialize_option_via_str(d, parse_duration)
1591}
1592
1593// ── millicores codec ───────────────────────────────────────────────────
1594
1595fn parse_millicores(s: &str) -> Result<u32, LimitsError> {
1596    // Paired whitespace-rejection arm — same canonical-form
1597    // render-determinism discipline as the peer `parse_byte_size` /
1598    // `parse_duration` / `supervisor::duration_codec::parse` /
1599    // `rate_limit_codec::parse` sites: the ASCII byte-scan closes the
1600    // WhatWG-conformant whitespace bytes (`0x20`, `0x09`, `0x0A`,
1601    // `0x0C`, `0x0D`), the non-ASCII `char::is_whitespace` scan closes
1602    // the strictly-complementary Unicode `White_Space` class (NBSP
1603    // `\u{00A0}`, LINE SEPARATOR `\u{2028}`, EM-SPACE `\u{2003}`, and
1604    // the peer typography codepoints) that `str::trim` at parse entry
1605    // silently strips. Either drift class would round-trip through
1606    // `render_millicores` to a *different* canonical form on next emit
1607    // — breaking the THEORY.md Part V render-determinism contract.
1608    // Diagnostics stay typed at `WhitespaceInMillicores` /
1609    // `NonAsciiWhitespaceInMillicores` — peer with every prior
1610    // canonical-form-drift arm on this codec
1611    // (`NonIntegerMillicoreMagnitude`, `LeadingZeroMillicoreMagnitude`).
1612    //
1613    // Routed through the lifted [`crate::render::reject_whitespace`]
1614    // primitive — the substrate-side single-owner paired-arm gate every
1615    // typed-magnitude codec in caixa-core shares.
1616    crate::render::reject_whitespace(
1617        s,
1618        |byte| LimitsError::WhitespaceInMillicores {
1619            value: s.into(),
1620            byte,
1621        },
1622        |ch| LimitsError::NonAsciiWhitespaceInMillicores {
1623            value: s.into(),
1624            ch,
1625            codepoint: ch as u32,
1626        },
1627    )?;
1628    let s_trim = s.trim();
1629    if s_trim.is_empty() {
1630        return Err(LimitsError::BadMillicores(s.into()));
1631    }
1632    let (magnitude, has_m_suffix) = match s_trim.strip_suffix('m') {
1633        Some(stripped) => (stripped.trim(), true),
1634        None => (s_trim, false),
1635    };
1636    if magnitude.is_empty() {
1637        // Bare `"m"` (or `" m "`) — no magnitude was authored. The
1638        // canonical millicores authoring form requires a magnitude in
1639        // front of the unit (`"500m"`, not `"m"`). Surface as
1640        // `BadMillicores` so the existing narrower-arm wording stays
1641        // load-bearing for "no recognizable magnitude" inputs.
1642        return Err(LimitsError::BadMillicores(s.into()));
1643    }
1644    // The canonical authoring form for `:limits :cpu` is `<integer>m`
1645    // (Kubernetes millicores) or the bare-core shorthand `<integer>`
1646    // (`"2"` = 2000 millicores). Every magnitude `render_millicores`
1647    // emits is a non-negative integer (`format!("{m}m")`) — no decimal
1648    // point, no leading sign — so the parser's accepted set must match
1649    // for serialize/deserialize to round-trip without canonical-form
1650    // drift. Until this gate landed the parser accepted any
1651    // `u32::from_str`-shaped magnitude (`"+500m"` → 500, `"+2"` →
1652    // 2000) and serde silently round-tripped the value to a *different*
1653    // canonical string on the next emit (`"+500m"` → `"500m"`, `"+2"`
1654    // → `"2000m"`) — breaking the THEORY.md Part V render-determinism
1655    // contract every typed slot carries. Closes the sixth (and last)
1656    // typed-codec surface in caixa-core on the integer-magnitude
1657    // canonical-form axis, peer with the five duration / byte-size /
1658    // rate-limit codecs the prior trajectory (1c55a2a / 818dd38 /
1659    // d1fd67b / f479c41 / d53c922) covered.
1660    //
1661    // Strict canonical form: every byte of the magnitude is an ASCII
1662    // digit (no `.`, no `+`, no `-`). On current Rust `u32::from_str`
1663    // permissively accepts a leading `+` (`"+500"` → 500) — that's a
1664    // canonical-drift shape `render_millicores` never emits, so the
1665    // digit-only check is what closes the leading-sign class; relying
1666    // on `u32::from_str`'s strictness alone would silently admit it.
1667    // On non-digit-only inputs the gate distinguishes "non-canonical-
1668    // but-numeric" (parses as f64 or i64 — surfaced as the new
1669    // `NonIntegerMillicoreMagnitude` variant naming the offending
1670    // magnitude verbatim with the canonical-form remediation) from
1671    // "garbage" (parses as neither — surfaced as the existing
1672    // `BadMillicores` so its narrower diagnostic shape remains
1673    // load-bearing for the not-a-numeric-input class).
1674    //
1675    // Routed through the lifted
1676    // [`crate::render::is_digit_only_magnitude`] predicate — the same
1677    // source of truth the four peer typed-magnitude codec sites share.
1678    // The predicate carries a `!<var>.is_empty()` gate that is
1679    // strictly no-op here (the `magnitude.is_empty()` arm above
1680    // already surfaces an empty magnitude as
1681    // [`LimitsError::BadMillicores`] before this line is reached), so
1682    // the semantics are preserved verbatim: on every reachable input
1683    // the predicate returns `magnitude.bytes().all(|b|
1684    // b.is_ascii_digit())`, byte-for-byte what the removed inline
1685    // expression computed.
1686    let digit_only = crate::render::is_digit_only_magnitude(magnitude);
1687    if !digit_only {
1688        let numeric = magnitude.parse::<f64>().is_ok() || magnitude.parse::<i64>().is_ok();
1689        if numeric {
1690            return Err(LimitsError::NonIntegerMillicoreMagnitude {
1691                value: magnitude.into(),
1692            });
1693        }
1694        return Err(LimitsError::BadMillicores(s.into()));
1695    }
1696    // Leading-zero arm — peer with the `parse_byte_size` leading-zero
1697    // arm (cea9a78), the `parse_duration` leading-zero arm (39762d7),
1698    // the `supervisor::duration_codec` leading-zero arm (9178904) and
1699    // the `rate_limit_codec` leading-zero arm (4f46830) on the same
1700    // canonical-form render-determinism axis. The digit-only gate
1701    // accepts `"0500m"`, `"00m"`, `"02"`, `"01500m"` as `u32::from_str`
1702    // parses them losslessly (= 500, 0, 2, 1500), but `render_millicores`
1703    // emits the leading-zero-stripped form (`"500m"`, `"0m"`, `"2000m"`,
1704    // `"1500m"`) — a *different* canonical string on the next emit,
1705    // breaking the THEORY.md Part V render-determinism contract the
1706    // same way `"+500m"` did before the leading-`+` arm landed. The
1707    // single-byte magnitude `"0"` (or `"0m"`) round-trips losslessly
1708    // through `render_millicores` (`render_millicores(0)` emits `"0m"`)
1709    // — the downstream semantic-zero gate [`LimitsError::CpuZero`]
1710    // refuses zero-magnitude authoring at the typed-validate layer
1711    // above, so the single-byte `"0"` stays in the accepted set at this
1712    // codec layer and the diagnostic partitioning between canonical-
1713    // form drift (this arm) and semantic-zero (the downstream gate)
1714    // remains stable. Same codec-layer / typed-validate-layer partition
1715    // the peer codecs preserve. Closes the sixth (and last) typed
1716    // numeric-codec surface in caixa-core on the integer-magnitude
1717    // leading-zero axis — the trajectory the prior `parse_byte_size`
1718    // arm (cea9a78) explicitly named.
1719    //
1720    // Routed through the lifted
1721    // [`crate::render::is_leading_zero_padded_magnitude`] predicate —
1722    // the same source of truth the four peer typed-magnitude codec
1723    // sites share.
1724    if crate::render::is_leading_zero_padded_magnitude(magnitude) {
1725        return Err(LimitsError::LeadingZeroMillicoreMagnitude {
1726            value: magnitude.into(),
1727        });
1728    }
1729    // The digit-only gate guarantees every byte is `[0-9]`, and the
1730    // leading-zero arm above guarantees the magnitude is either the
1731    // single byte `"0"` or starts with `[1-9]`, so the only way
1732    // `u32::from_str` can fail here is overflow (the magnitude exceeds
1733    // `u32::MAX`). Surface that as `BadMillicores` with an overflow-
1734    // shaped wording so the diagnostic names the offending magnitude
1735    // verbatim rather than collapsing onto the non-canonical arm —
1736    // matches `parse_byte_size` / `parse_duration` / `rate_limit_codec`
1737    // overflow-arm shape on the peer typed codecs.
1738    let num: u32 = magnitude.parse::<u32>().map_err(|_| {
1739        LimitsError::BadMillicores(format!("{magnitude} (digit-only magnitude overflows u32)"))
1740    })?;
1741    if has_m_suffix {
1742        Ok(num)
1743    } else {
1744        // Bare-core shorthand: `"2"` = 2000 millicores. Use
1745        // `checked_mul` (not the prior `saturating_mul`) so a
1746        // magnitude that overflows u32 on the × 1000 conversion
1747        // surfaces a parser-shaped diagnostic at parse time rather
1748        // than silently saturating to `u32::MAX` (which would land
1749        // as the cap value far from the author's intent and bypass
1750        // any future validate-time upper-bound gate the `:cpu` axis
1751        // grows). Matches `parse_byte_size`'s overflow-arm shape on
1752        // the magnitude × unit multiply.
1753        num.checked_mul(1000).ok_or_else(|| {
1754            LimitsError::BadMillicores(format!(
1755                "{magnitude} cores × 1000 overflows u32 (write the value in millicores: max \"{}m\")",
1756                u32::MAX
1757            ))
1758        })
1759    }
1760}
1761
1762fn render_millicores(m: u32) -> String {
1763    format!("{m}m")
1764}
1765
1766fn ser_millicores<S: Serializer>(v: &Option<u32>, s: S) -> Result<S::Ok, S::Error> {
1767    // Route through the canonical [`crate::render::serialize_option_via_str`]
1768    // — see peer `ser_byte_size` / `ser_duration` routing notes above.
1769    crate::render::serialize_option_via_str(v, s, render_millicores)
1770}
1771
1772fn de_millicores<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u32>, D::Error> {
1773    // Route through the canonical [`crate::render::deserialize_option_via_str`]
1774    // — see peer `de_byte_size` / `de_duration` routing notes above.
1775    crate::render::deserialize_option_via_str(d, parse_millicores)
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780    use super::*;
1781
1782    #[test]
1783    fn parse_byte_size_known_units() {
1784        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
1785        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
1786        assert_eq!(parse_byte_size("512KiB").unwrap(), 512 * 1024);
1787        assert_eq!(parse_byte_size("1KB").unwrap(), 1_000);
1788        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
1789    }
1790
1791    #[test]
1792    fn parse_byte_size_rejects_unknown() {
1793        assert!(matches!(
1794            parse_byte_size("1YiB"),
1795            Err(LimitsError::UnknownByteUnit { .. })
1796        ));
1797        assert!(matches!(
1798            parse_byte_size("not-a-number"),
1799            Err(LimitsError::BadByteMagnitude(_))
1800        ));
1801    }
1802
1803    #[test]
1804    fn parse_duration_known_units() {
1805        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
1806        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
1807        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
1808        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
1809    }
1810
1811    #[test]
1812    fn parse_millicores_both_forms() {
1813        assert_eq!(parse_millicores("500m").unwrap(), 500);
1814        assert_eq!(parse_millicores("2").unwrap(), 2000);
1815    }
1816
1817    #[test]
1818    fn render_byte_size_canonical() {
1819        assert_eq!(render_byte_size(64 * 1024 * 1024), "64MiB");
1820        assert_eq!(render_byte_size(1024 * 1024 * 1024), "1GiB");
1821        assert_eq!(render_byte_size(1024), "1KiB");
1822        assert_eq!(render_byte_size(123), "123");
1823    }
1824
1825    #[test]
1826    fn ser_byte_size_routes_through_render_serialize_option_via_str_canonical() {
1827        // Routing pin: `ser_byte_size` (the `#[serde(serialize_with = …)]`
1828        // hook on `LimitsSpec::memory`) MUST emit exactly the bytes the
1829        // canonical `crate::render::serialize_option_via_str` primitive
1830        // produces when threaded through the peer `render_byte_size`
1831        // dispatch. Any future accidental re-inline of a bespoke
1832        // `match v { Some(_) => s.serialize_str(_), None =>
1833        // s.serialize_none() }` block inside this module — the shape
1834        // this lift removed — surfaces here as a byte-value drift on
1835        // the very first canonical form the two implementations
1836        // disagree on. Peer of
1837        // `ser_duration_routes_through_supervisor_duration_codec_render_canonical`
1838        // on the sibling `LimitsSpec::wall_clock` axis; same "one
1839        // canonical dispatch per axis, thin projections at each
1840        // consumer" discipline the sibling caixa-core substrate
1841        // primitives already carry.
1842        for n in [
1843            0u64,
1844            1,
1845            1023,
1846            1024,
1847            64 * 1024 * 1024,
1848            4 * 1024 * 1024 * 1024,
1849        ] {
1850            let limits = LimitsSpec {
1851                memory: Some(n),
1852                fuel: None,
1853                wall_clock: None,
1854                cpu: None,
1855            };
1856            let json: serde_json::Value =
1857                serde_json::from_str(&serde_json::to_string(&limits).unwrap()).unwrap();
1858            let emitted = json[crate::render::M2_LIMITS_KEY_MEMORY]
1859                .as_str()
1860                .expect("memory must serialize to a string");
1861            let canonical = render_byte_size(n);
1862            assert_eq!(
1863                emitted, canonical,
1864                "ser_byte_size drifted from render_byte_size via \
1865                 serialize_option_via_str on {n} bytes",
1866            );
1867        }
1868    }
1869
1870    #[test]
1871    fn de_byte_size_routes_through_render_deserialize_option_via_str_canonical() {
1872        // Routing pin: `de_byte_size` (the
1873        // `#[serde(deserialize_with = …)]` hook on
1874        // `LimitsSpec::memory`) MUST accept exactly the canonical
1875        // string set the peer `parse_byte_size` function accepts, and
1876        // reject everything else with the parser's typed `LimitsError`
1877        // surfaced through `serde::de::Error::custom` — the shape the
1878        // lifted `crate::render::deserialize_option_via_str` primitive
1879        // enforces. A future accidental re-inline of a bespoke `let
1880        // opt: Option<String> = Option::deserialize(d)?; match opt {
1881        // … }` block inside this module — the shape this lift removed
1882        // — that drifted on either arm (silently accepting a value the
1883        // parser rejects, or swallowing a parser error as `Ok(None)`)
1884        // surfaces here.
1885        for raw in ["64MiB", "1024", "0", "4GiB"] {
1886            let field = crate::render::M2_LIMITS_KEY_MEMORY;
1887            let payload = format!("{{\"{field}\":\"{raw}\"}}");
1888            let limits: LimitsSpec =
1889                serde_json::from_str(&payload).expect("canonical memory string must round-trip");
1890            let canonical = parse_byte_size(raw).expect("parse_byte_size accepts canonical form");
1891            assert_eq!(
1892                limits.memory,
1893                Some(canonical),
1894                "de_byte_size drifted from parse_byte_size via \
1895                 deserialize_option_via_str on {raw:?}",
1896            );
1897        }
1898        // Null-arm pin: `null` folds to `None` without invoking the
1899        // parser — the exact contract the lifted primitive's null-arm
1900        // test pins.
1901        let field = crate::render::M2_LIMITS_KEY_MEMORY;
1902        let null_payload = format!("{{\"{field}\":null}}");
1903        let empty: LimitsSpec = serde_json::from_str(&null_payload)
1904            .expect("null memory field must fold to LimitsSpec::memory = None");
1905        assert_eq!(
1906            empty.memory, None,
1907            "de_byte_size must fold null → None via \
1908             deserialize_option_via_str's null-arm",
1909        );
1910        // Reject-arm pin: a bogus string surfaces the parser's error
1911        // through `serde::de::Error::custom` — not `Ok(None)`.
1912        let bad_payload = format!("{{\"{field}\":\"64XiB\"}}");
1913        let err = serde_json::from_str::<LimitsSpec>(&bad_payload)
1914            .expect_err("bogus memory string must surface the parser's error");
1915        let err_text = err.to_string();
1916        assert!(
1917            err_text.contains("64XiB") || err_text.contains("XiB"),
1918            "de_byte_size must surface parse_byte_size's typed \
1919             LimitsError through serde::de::Error::custom — got \
1920             {err_text:?}",
1921        );
1922    }
1923
1924    #[test]
1925    fn ser_duration_routes_through_supervisor_duration_codec_render_canonical() {
1926        // Routing pin: `ser_duration` (the `#[serde(serialize_with = …)]`
1927        // hook on `LimitsSpec::wall_clock`) MUST emit exactly the bytes
1928        // the canonical `crate::supervisor::duration_codec::render`
1929        // primitive produces. Any future accidental re-introduction of a
1930        // sibling free-function `render_duration` shadow inside this
1931        // module — or a per-slot `serialize_with` closure that inlines
1932        // its own magnitude/unit decision tree — surfaces here as a
1933        // byte-value drift on the very first canonical form the two
1934        // implementations disagree on, well before the drift reaches any
1935        // downstream renderer's `wall_clock:` overlay. Same "one
1936        // canonical dispatch per axis, thin projections at each consumer"
1937        // discipline the sibling caixa-core substrate primitives already
1938        // carry on the peer WIT-shape / M2 supervisor-strategy / M3
1939        // mesh-slot free-function classifier families.
1940        for d in [
1941            Duration::from_secs(30),
1942            Duration::from_millis(500),
1943            Duration::from_secs(120),
1944            Duration::from_secs(3600),
1945            Duration::from_millis(0),
1946            Duration::from_millis(1500),
1947        ] {
1948            let limits = LimitsSpec {
1949                memory: None,
1950                fuel: None,
1951                wall_clock: Some(d),
1952                cpu: None,
1953            };
1954            let json: serde_json::Value =
1955                serde_json::from_str(&serde_json::to_string(&limits).unwrap()).unwrap();
1956            let emitted = json[crate::render::M2_LIMITS_KEY_WALL_CLOCK]
1957                .as_str()
1958                .expect("wall_clock must serialize to a string");
1959            let canonical = crate::supervisor::duration_codec::render(d);
1960            assert_eq!(
1961                emitted, canonical,
1962                "ser_duration drifted from supervisor::duration_codec::render on {d:?}",
1963            );
1964        }
1965    }
1966
1967    #[test]
1968    fn parse_byte_size_routes_whitespace_through_render_reject_whitespace_canonical() {
1969        // Routing pin: the paired whitespace-rejection block at the
1970        // top of `parse_byte_size` MUST route through the substrate-
1971        // side [`crate::render::reject_whitespace`] primitive — the
1972        // single-owner paired-arm gate every typed-magnitude codec
1973        // in caixa-core shares. Any future accidental re-inline of a
1974        // bespoke
1975        //
1976        // ```ignore
1977        // if let Some(byte) = find_ascii_whitespace_byte(s) { … }
1978        // if let Some(ch)   = find_non_ascii_whitespace_char(s)  { … }
1979        // ```
1980        //
1981        // block inside this module — the shape this lift removed —
1982        // that drifted on either arm surfaces here as a variant-shape
1983        // drift on the very first canonical form the two
1984        // implementations disagree on. Byte-shape pins cover the
1985        // ASCII WhatWG-conformant set (space / tab / LF / FF / CR)
1986        // and the strictly-complementary non-ASCII Unicode
1987        // `White_Space` class (NBSP / LINE SEPARATOR / EM-SPACE /
1988        // IDEOGRAPHIC SPACE) on the exemplar `:limits :memory` axis
1989        // — peer of the pre-existing `ser_byte_size_routes_through_
1990        // render_serialize_option_via_str_canonical` /
1991        // `de_byte_size_routes_through_render_deserialize_option_
1992        // via_str_canonical` pins on the sibling codec-hook axis.
1993        for (raw, byte) in [
1994            (" 64MiB", 0x20u8),
1995            ("64MiB ", 0x20u8),
1996            ("64 MiB", 0x20u8),
1997            ("\t64MiB", 0x09u8),
1998            ("64MiB\n", 0x0Au8),
1999        ] {
2000            let err = parse_byte_size(raw)
2001                .expect_err("ASCII-whitespace-carrying byte-size input must be rejected");
2002            let via_primitive = crate::render::reject_whitespace::<LimitsError, _, _>(
2003                raw,
2004                |b| LimitsError::WhitespaceInByteSize {
2005                    value: raw.into(),
2006                    byte: b,
2007                },
2008                |ch| LimitsError::NonAsciiWhitespaceInByteSize {
2009                    value: raw.into(),
2010                    ch,
2011                    codepoint: ch as u32,
2012                },
2013            )
2014            .expect_err("primitive must reject the same ASCII-whitespace shape");
2015            assert_eq!(
2016                err, via_primitive,
2017                "parse_byte_size drifted from crate::render::reject_whitespace \
2018                 on ASCII-whitespace input {raw:?}"
2019            );
2020            assert!(
2021                matches!(
2022                    err,
2023                    LimitsError::WhitespaceInByteSize { value: ref v, byte: b } if v == raw && b == byte
2024                ),
2025                "parse_byte_size must surface WhitespaceInByteSize {{ value: {raw:?}, byte: 0x{byte:02x} }}"
2026            );
2027        }
2028        for (raw, expected_ch) in [
2029            ("\u{00A0}64MiB", '\u{00A0}'),
2030            ("64\u{2003}MiB", '\u{2003}'),
2031            ("64MiB\u{2028}", '\u{2028}'),
2032            ("\u{3000}64MiB", '\u{3000}'),
2033        ] {
2034            let err = parse_byte_size(raw)
2035                .expect_err("non-ASCII-whitespace-carrying byte-size input must be rejected");
2036            let via_primitive = crate::render::reject_whitespace::<LimitsError, _, _>(
2037                raw,
2038                |b| LimitsError::WhitespaceInByteSize {
2039                    value: raw.into(),
2040                    byte: b,
2041                },
2042                |ch| LimitsError::NonAsciiWhitespaceInByteSize {
2043                    value: raw.into(),
2044                    ch,
2045                    codepoint: ch as u32,
2046                },
2047            )
2048            .expect_err("primitive must reject the same non-ASCII-whitespace shape");
2049            assert_eq!(
2050                err, via_primitive,
2051                "parse_byte_size drifted from crate::render::reject_whitespace \
2052                 on non-ASCII-whitespace input {raw:?}"
2053            );
2054            assert!(
2055                matches!(
2056                    err,
2057                    LimitsError::NonAsciiWhitespaceInByteSize { value: ref v, ch, codepoint }
2058                        if v == raw && ch == expected_ch && codepoint == expected_ch as u32
2059                ),
2060                "parse_byte_size must surface NonAsciiWhitespaceInByteSize \
2061                 {{ value: {raw:?}, ch: {expected_ch:?}, codepoint: {cp:#06X} }}",
2062                cp = expected_ch as u32
2063            );
2064        }
2065    }
2066
2067    #[test]
2068    fn limits_round_trip_through_json() {
2069        let limits = LimitsSpec {
2070            memory: Some(64 * 1024 * 1024),
2071            fuel: Some(1_000_000),
2072            wall_clock: Some(Duration::from_secs(30)),
2073            cpu: Some(500),
2074        };
2075        let json = serde_json::to_string(&limits).unwrap();
2076        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
2077        assert_eq!(limits, back);
2078    }
2079
2080    #[test]
2081    fn empty_limits_serialises_to_empty_object() {
2082        let limits = LimitsSpec::default();
2083        assert!(limits.is_empty());
2084        let json = serde_json::to_string(&limits).unwrap();
2085        assert_eq!(json, "{}");
2086    }
2087
2088    // ── drift-detection: serde-derive-to-M2_LIMITS_KEY_* identity ────────
2089
2090    #[test]
2091    fn limits_spec_serde_keys_match_lifted_m2_limits_key_consts() {
2092        // Load-bearing invariant: the four `M2_LIMITS_KEY_*` consts
2093        // (`M2_LIMITS_KEY_MEMORY` / `M2_LIMITS_KEY_FUEL` /
2094        // `M2_LIMITS_KEY_WALL_CLOCK` / `M2_LIMITS_KEY_CPU`) name the
2095        // exact camelCase JSON keys the `#[serde(rename_all = "camelCase")]`
2096        // attribute on `LimitsSpec` emits, and every test-side probe
2097        // across the caixa-core / caixa-flux / caixa-helm renderer test
2098        // fixtures navigates into the rendered `:limits` overlay
2099        // sub-block by consulting one of these four `&'static str`s.
2100        // Serialize a fully-populated LimitsSpec and pin that each
2101        // canonical byte-sequence appears verbatim in the JSON — a
2102        // future accidental `rename_all = "snake_case"` /
2103        // `"kebab-case"` / verbatim-field-name flip at the derive
2104        // attribute (any of which would silently break every test-side
2105        // probe that reaches for one of the four consts) surfaces here
2106        // as a build-time test failure at `limits.rs`, not as an
2107        // apply-time `.get(<stale-canonical-const>)` returning `None`
2108        // far from the derive-attr drift's commit. Same discipline the
2109        // sibling M3 `PlacementStrategy::as_str` lift (0a2f653)
2110        // established on the peer per-`:placement :estrategia` axis:
2111        // one canonical byte-string per typed sub-key axis, pinned to
2112        // the load-bearing serde derivation at the type itself.
2113        let limits = LimitsSpec {
2114            memory: Some(64 * 1024 * 1024),
2115            fuel: Some(1_000_000),
2116            wall_clock: Some(Duration::from_secs(30)),
2117            cpu: Some(500),
2118        };
2119        let json = serde_json::to_string(&limits).unwrap();
2120        for key in [
2121            crate::render::M2_LIMITS_KEY_MEMORY,
2122            crate::render::M2_LIMITS_KEY_FUEL,
2123            crate::render::M2_LIMITS_KEY_WALL_CLOCK,
2124            crate::render::M2_LIMITS_KEY_CPU,
2125        ] {
2126            let quoted = format!("\"{key}\"");
2127            assert!(
2128                json.contains(&quoted),
2129                "serialized LimitsSpec must carry the lifted \
2130                 M2_LIMITS_KEY_* byte-sequence {quoted} verbatim in \
2131                 the JSON emission (got: {json})",
2132            );
2133        }
2134    }
2135
2136    #[test]
2137    fn m2_limits_key_consts_are_pairwise_distinct() {
2138        // Cross-axis drift-detection pin: a future collapse of two
2139        // canonical sub-key byte-strings onto the same value (e.g. an
2140        // accidental copy-paste flip of `M2_LIMITS_KEY_CPU` to also
2141        // read `"memory"`) would silently reroute every test-side
2142        // probe on one axis onto the sibling axis's overlay entry and
2143        // pass every propagation-probe test that expected only the
2144        // stale axis's value. Peer of the sibling three-way distinct
2145        // pin on the `FLUX_GITREPOSITORY_REF_KEY_*` trio (7d40380).
2146        let all = [
2147            crate::render::M2_LIMITS_KEY_MEMORY,
2148            crate::render::M2_LIMITS_KEY_FUEL,
2149            crate::render::M2_LIMITS_KEY_WALL_CLOCK,
2150            crate::render::M2_LIMITS_KEY_CPU,
2151        ];
2152        for (i, a) in all.iter().enumerate() {
2153            for b in all.iter().skip(i + 1) {
2154                assert_ne!(
2155                    a, b,
2156                    "M2_LIMITS_KEY_* consts must be pairwise-distinct \
2157                     canonical byte-sequences — got `{a}` == `{b}`",
2158                );
2159            }
2160        }
2161    }
2162
2163    #[test]
2164    fn m2_limits_key_consts_are_lower_camel_case_shape() {
2165        // Shape-pin: every `M2_LIMITS_KEY_*` const must be a
2166        // lowerCamelCase byte-sequence (no `snake_case` underscores,
2167        // no `kebab-case` hyphens, no `PascalCase` leading capital, no
2168        // whitespace / colons / dots) — the canonical shape the
2169        // `#[serde(rename_all = "camelCase")]` derive produces on
2170        // `LimitsSpec`. A future flip to a non-camelCase attribute at
2171        // the derive surfaces both here (this test fails on the
2172        // stale-constant shape) and at
2173        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
2174        // (that test fails on the mismatch between const and derive).
2175        for key in [
2176            crate::render::M2_LIMITS_KEY_MEMORY,
2177            crate::render::M2_LIMITS_KEY_FUEL,
2178            crate::render::M2_LIMITS_KEY_WALL_CLOCK,
2179            crate::render::M2_LIMITS_KEY_CPU,
2180        ] {
2181            assert!(
2182                !key.is_empty(),
2183                "M2_LIMITS_KEY_* must be non-empty (got {key:?})"
2184            );
2185            let first = key.chars().next().unwrap();
2186            assert!(
2187                first.is_ascii_lowercase(),
2188                "M2_LIMITS_KEY_* must lead with an ASCII-lowercase byte \
2189                 (got {key:?}, leads with {first:?})",
2190            );
2191            assert!(
2192                key.chars().all(|c| c.is_ascii_alphanumeric()),
2193                "M2_LIMITS_KEY_* must be ASCII-alphanumeric only \
2194                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
2195            );
2196        }
2197    }
2198
2199    // ── value-shape: zero on any declared axis is rejected ────────────────
2200
2201    #[test]
2202    fn validate_accepts_default_unbounded_limits() {
2203        // Every axis None → "no bound declared" is the omit-the-slot
2204        // shape and stays valid. This is the pre-M2 default behaviour.
2205        LimitsSpec::default().validate().unwrap();
2206    }
2207
2208    #[test]
2209    fn validate_accepts_full_nonzero_limits() {
2210        let l = LimitsSpec {
2211            memory: Some(64 * 1024 * 1024),
2212            fuel: Some(1_000_000),
2213            wall_clock: Some(Duration::from_secs(30)),
2214            cpu: Some(500),
2215        };
2216        l.validate().unwrap();
2217    }
2218
2219    #[test]
2220    fn validate_rejects_zero_memory() {
2221        let l = LimitsSpec {
2222            memory: Some(0),
2223            ..Default::default()
2224        };
2225        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
2226    }
2227
2228    #[test]
2229    fn validate_rejects_zero_fuel() {
2230        let l = LimitsSpec {
2231            fuel: Some(0),
2232            ..Default::default()
2233        };
2234        assert_eq!(l.validate().unwrap_err(), LimitsError::FuelZero);
2235    }
2236
2237    #[test]
2238    fn validate_rejects_zero_wall_clock() {
2239        let l = LimitsSpec {
2240            wall_clock: Some(Duration::ZERO),
2241            ..Default::default()
2242        };
2243        assert_eq!(l.validate().unwrap_err(), LimitsError::WallClockZero);
2244    }
2245
2246    #[test]
2247    fn validate_rejects_zero_cpu() {
2248        let l = LimitsSpec {
2249            cpu: Some(0),
2250            ..Default::default()
2251        };
2252        assert_eq!(l.validate().unwrap_err(), LimitsError::CpuZero);
2253    }
2254
2255    #[test]
2256    fn validate_rejects_first_zero_axis_deterministically() {
2257        // Memory is checked first; with multiple zero axes, the
2258        // diagnostic names :memory rather than reporting some other
2259        // axis non-deterministically.
2260        let l = LimitsSpec {
2261            memory: Some(0),
2262            fuel: Some(0),
2263            wall_clock: Some(Duration::ZERO),
2264            cpu: Some(0),
2265        };
2266        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
2267    }
2268
2269    // ── value-shape: :memory upper bound — wasm32-wasip2 4 GiB ceiling ────
2270
2271    #[test]
2272    fn wasm32_memory_cap_matches_parsed_4_gib() {
2273        // The cap constant tracks the canonical "4 GiB" byte-size
2274        // codec output structurally — drift between the codec's
2275        // accepted magnitude for `"4GiB"` and the validate gate's
2276        // accepted upper bound would surface here, not as a silent
2277        // round-trip break at the renderer layer. Same single-source-
2278        // of-truth shape the is_canonical_rate_limit_window predicate
2279        // gives the rate-limit window set.
2280        assert_eq!(
2281            parse_byte_size("4GiB").unwrap(),
2282            LIMITS_MEMORY_WASM32_MAX_BYTES
2283        );
2284        assert_eq!(LIMITS_MEMORY_WASM32_MAX_BYTES, 4 * 1024 * 1024 * 1024);
2285        assert_eq!(LIMITS_MEMORY_WASM32_MAX_BYTES, 1u64 << 32);
2286    }
2287
2288    #[test]
2289    fn validate_accepts_memory_at_wasm32_cap() {
2290        // 4 GiB exactly is the wasm32 in-spec maximum — `2^16 pages ×
2291        // 2^16 bytes/page`. The validate gate is inclusive on the
2292        // upper end (mirrors the inclusive lower-end rejection: zero
2293        // is *out*, one is *in*; 4 GiB+1 is *out*, 4 GiB is *in*).
2294        let l = LimitsSpec {
2295            memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
2296            ..Default::default()
2297        };
2298        l.validate().unwrap();
2299    }
2300
2301    #[test]
2302    fn validate_rejects_memory_one_byte_above_wasm32_cap() {
2303        // Boundary case: exactly 1 byte past the cap. Catches a
2304        // future "strictly less than" half-measure and pins the
2305        // diagnostic to name the offending byte count verbatim.
2306        let bytes = LIMITS_MEMORY_WASM32_MAX_BYTES + 1;
2307        let l = LimitsSpec {
2308            memory: Some(bytes),
2309            ..Default::default()
2310        };
2311        assert_eq!(
2312            l.validate().unwrap_err(),
2313            LimitsError::MemoryExceedsWasm32Cap { bytes }
2314        );
2315    }
2316
2317    #[test]
2318    fn validate_rejects_memory_8_gib() {
2319        // The "obvious authoring footgun" case: a value the byte-size
2320        // codec accepts cleanly (`"8GiB"` → 8 * 1024^3 bytes) and
2321        // serde round-trips silently, but no wasm32 component can
2322        // honor. Until this gate landed `validate` accepted it.
2323        let bytes = parse_byte_size("8GiB").unwrap();
2324        let l = LimitsSpec {
2325            memory: Some(bytes),
2326            ..Default::default()
2327        };
2328        assert_eq!(
2329            l.validate().unwrap_err(),
2330            LimitsError::MemoryExceedsWasm32Cap { bytes }
2331        );
2332    }
2333
2334    #[test]
2335    fn validate_memory_zero_takes_precedence_over_cap_check() {
2336        // Memory zero is structurally meaningless under *any* wasm
2337        // engine (zero-cap traps the first allocation); above-cap is
2338        // wasm32-specific. The zero arm fires first so the canonical
2339        // "omit the slot for unbounded" remediation in the existing
2340        // MemoryZero diagnostic still leads — pinning this precedence
2341        // guards against a future re-ordering that would surface the
2342        // wasm32-specific message in the case where the simpler
2343        // zero-floor message is more actionable.
2344        let l = LimitsSpec {
2345            memory: Some(0),
2346            ..Default::default()
2347        };
2348        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
2349    }
2350
2351    #[test]
2352    fn validate_rejects_memory_cap_before_other_axes() {
2353        // With both an above-cap :memory and a zero :fuel, the
2354        // diagnostic names :memory rather than :fuel — peer of the
2355        // existing `validate_rejects_first_zero_axis_deterministically`
2356        // ordering pin.
2357        let bytes = LIMITS_MEMORY_WASM32_MAX_BYTES + 1024;
2358        let l = LimitsSpec {
2359            memory: Some(bytes),
2360            fuel: Some(0),
2361            wall_clock: Some(Duration::ZERO),
2362            cpu: Some(0),
2363        };
2364        assert_eq!(
2365            l.validate().unwrap_err(),
2366            LimitsError::MemoryExceedsWasm32Cap { bytes }
2367        );
2368    }
2369
2370    #[test]
2371    fn above_cap_value_still_round_trips_through_serde() {
2372        // The byte-size codec accepts the above-cap value (the cap
2373        // lives in the validate gate, not the codec). This pins that
2374        // the structural property is "above-cap is rejected by
2375        // validate" — not "above-cap is unparseable by the codec";
2376        // the latter would prevent the diagnostic from naming the
2377        // offending byte count at all, since deserialize would fail
2378        // first.
2379        let l = LimitsSpec {
2380            memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES + 1),
2381            ..Default::default()
2382        };
2383        let json = serde_json::to_string(&l).unwrap();
2384        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
2385        assert_eq!(l, back);
2386        assert!(back.validate().is_err());
2387    }
2388
2389    // ── value-shape: :memory lower bound — wasm32-wasip2 64 KiB page floor ─
2390
2391    #[test]
2392    fn wasm32_memory_page_matches_parsed_64_kib() {
2393        // The page-floor constant tracks the canonical "64 KiB"
2394        // byte-size codec output structurally — drift between the
2395        // codec's accepted magnitude for `"64KiB"` and the validate
2396        // gate's accepted lower bound would surface here, not as a
2397        // silent round-trip break at the renderer layer. Same single-
2398        // source-of-truth shape `wasm32_memory_cap_matches_parsed_4_gib`
2399        // pins on the peer upper-cap bound and
2400        // `is_canonical_rate_limit_window` gives the rate-limit window
2401        // set. The page-size identities (2^16, integer-divides the
2402        // upper cap exactly 2^16 times) are pinned alongside so a
2403        // future memory64-target opt-in raising one bound surfaces
2404        // here if the other bound's relationship to it drifts.
2405        assert_eq!(
2406            parse_byte_size("64KiB").unwrap(),
2407            LIMITS_MEMORY_WASM32_PAGE_BYTES
2408        );
2409        assert_eq!(LIMITS_MEMORY_WASM32_PAGE_BYTES, 64 * 1024);
2410        assert_eq!(LIMITS_MEMORY_WASM32_PAGE_BYTES, 1u64 << 16);
2411        assert_eq!(
2412            LIMITS_MEMORY_WASM32_MAX_BYTES / LIMITS_MEMORY_WASM32_PAGE_BYTES,
2413            1u64 << 16,
2414            "the wasm32 page count cap is 2^16 pages exactly",
2415        );
2416        assert_eq!(
2417            LIMITS_MEMORY_WASM32_MAX_BYTES % LIMITS_MEMORY_WASM32_PAGE_BYTES,
2418            0
2419        );
2420    }
2421
2422    #[test]
2423    fn validate_rejects_memory_below_wasm32_page() {
2424        // The fail-before-pass-after pin: until this gate landed a
2425        // `(:memory "32KiB")` (or any programmatic struct literal with
2426        // a sub-page byte count — `LimitsSpec { memory: Some(50000),
2427        // .. }`) silently passed validate, the byte-size codec
2428        // round-tripped cleanly through serde, and the wasm-engine
2429        // either refused instantiation (`memory minimum size of 1
2430        // pages exceeds memory limits` on any cdylib-shaped component
2431        // declaring `(memory 1)`) or trapped the first `memory.grow(1)`
2432        // far from the source caixa.lisp.
2433        let bytes = parse_byte_size("32KiB").unwrap();
2434        let l = LimitsSpec {
2435            memory: Some(bytes),
2436            ..Default::default()
2437        };
2438        assert_eq!(
2439            l.validate().unwrap_err(),
2440            LimitsError::MemoryBelowWasm32Page { bytes }
2441        );
2442    }
2443
2444    #[test]
2445    fn validate_rejects_memory_one_byte_below_page() {
2446        // Boundary case: exactly 1 byte below the page-size floor
2447        // (`LIMITS_MEMORY_WASM32_PAGE_BYTES - 1` = 65535 bytes). Pins
2448        // the inclusive-upper-end / strict-lower-end relationship on
2449        // the page-floor arm: 65535 is *out*, 65536 is *in*. Catches a
2450        // future "strictly greater than" half-measure and matches the
2451        // peer `validate_rejects_memory_one_byte_above_wasm32_cap`
2452        // shape on the top edge.
2453        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES - 1;
2454        let l = LimitsSpec {
2455            memory: Some(bytes),
2456            ..Default::default()
2457        };
2458        assert_eq!(
2459            l.validate().unwrap_err(),
2460            LimitsError::MemoryBelowWasm32Page { bytes }
2461        );
2462    }
2463
2464    #[test]
2465    fn validate_rejects_memory_one_byte() {
2466        // The far-floor case: a `(:memory "1")` cap is non-zero (so
2467        // `MemoryZero` doesn't fire) but structurally cannot hold any
2468        // wasm linear memory page. The page-floor gate at this layer
2469        // surfaces a self-locating diagnostic naming the offending
2470        // byte count verbatim rather than a downstream wasm-engine
2471        // instantiation failure whose error message points at the
2472        // engine's internals, not the caixa.lisp `:memory` slot.
2473        let l = LimitsSpec {
2474            memory: Some(1),
2475            ..Default::default()
2476        };
2477        assert_eq!(
2478            l.validate().unwrap_err(),
2479            LimitsError::MemoryBelowWasm32Page { bytes: 1 }
2480        );
2481    }
2482
2483    #[test]
2484    fn validate_accepts_memory_at_wasm32_page() {
2485        // 64 KiB exactly is the wasm32 linear-memory page size — the
2486        // smallest cap that admits one wasm `(memory 1)` page. The
2487        // page-floor gate is inclusive on the lower end (mirrors the
2488        // inclusive upper-end acceptance: 4 GiB is *in*, 4 GiB+1 is
2489        // *out*; 64 KiB is *in*, 64 KiB-1 is *out*).
2490        let l = LimitsSpec {
2491            memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
2492            ..Default::default()
2493        };
2494        l.validate().unwrap();
2495    }
2496
2497    #[test]
2498    fn validate_accepts_multi_page_memory() {
2499        // The positive-control sweep: every typed `:memory` cap that
2500        // admits at least one wasm linear memory page (i.e. ≥
2501        // `LIMITS_MEMORY_WASM32_PAGE_BYTES`) passes `validate`. Sweeps
2502        // single-page, two-page, the canonical 64 MiB / 1 GiB / 4 GiB
2503        // upper-bound boundary so a future tightening of either edge
2504        // surfaces here. Peer of
2505        // `validate_accepts_integer_millisecond_wall_clock_values` on
2506        // the sibling `:wall-clock` axis.
2507        for bytes in [
2508            LIMITS_MEMORY_WASM32_PAGE_BYTES,
2509            2 * LIMITS_MEMORY_WASM32_PAGE_BYTES,
2510            64 * 1024 * 1024,
2511            1024 * 1024 * 1024,
2512            LIMITS_MEMORY_WASM32_MAX_BYTES,
2513        ] {
2514            let l = LimitsSpec {
2515                memory: Some(bytes),
2516                ..Default::default()
2517            };
2518            l.validate()
2519                .unwrap_or_else(|e| panic!("multi-page {bytes} must validate, got {e:?}"));
2520        }
2521    }
2522
2523    #[test]
2524    fn validate_memory_zero_takes_precedence_over_page_floor() {
2525        // Cross-arm ordering pin: `Some(0)` would otherwise pass the
2526        // page-floor arm's `m < PAGE_BYTES` check (0 < 65536), but the
2527        // zero-floor arm strictly precedes the page-floor arm so the
2528        // more self-locating `MemoryZero` diagnostic (with its omit-
2529        // axis remediation directly named, applicable under *any* wasm
2530        // engine not just wasm32) leads. Same posture every peer
2531        // zero-then-shape gate uses on this surface
2532        // (`PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
2533        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`,
2534        // `WallClockZero` → `WallClockNotCanonical`).
2535        let l = LimitsSpec {
2536            memory: Some(0),
2537            ..Default::default()
2538        };
2539        assert_eq!(l.validate().unwrap_err(), LimitsError::MemoryZero);
2540    }
2541
2542    #[test]
2543    fn validate_memory_page_floor_takes_precedence_over_other_axes() {
2544        // With a sub-page `:memory` and zero values on every other
2545        // axis, the diagnostic names `:memory` rather than `:fuel` /
2546        // `:wall-clock` / `:cpu` — peer of the existing
2547        // `validate_rejects_first_zero_axis_deterministically` and
2548        // `validate_rejects_memory_cap_before_other_axes` ordering
2549        // pins. Memory is the first axis the validate cascade checks,
2550        // so a sub-page value surfaces before any other-axis
2551        // diagnostic regardless of how many other axes are
2552        // simultaneously invalid.
2553        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES / 2;
2554        let l = LimitsSpec {
2555            memory: Some(bytes),
2556            fuel: Some(0),
2557            wall_clock: Some(Duration::ZERO),
2558            cpu: Some(0),
2559        };
2560        assert_eq!(
2561            l.validate().unwrap_err(),
2562            LimitsError::MemoryBelowWasm32Page { bytes }
2563        );
2564    }
2565
2566    #[test]
2567    fn memory_page_floor_diagnostic_carries_offending_bytes() {
2568        // Diagnostic-shape pin: the page-floor arm names the
2569        // offending byte count verbatim so the author's grep lands on
2570        // the field's value, not a generic "memory too small" message.
2571        // Same shape every other typed-cap arm on this surface
2572        // carries (`MemoryExceedsWasm32Cap` carries the offending byte
2573        // count verbatim, `WallClockNotCanonical` carries the
2574        // offending `Duration` verbatim, `PolicyRetriesExceedsCap`
2575        // carries the offending retry count verbatim).
2576        let l = LimitsSpec {
2577            memory: Some(50_000),
2578            ..Default::default()
2579        };
2580        let err = l.validate().unwrap_err();
2581        let msg = err.to_string();
2582        assert!(
2583            msg.contains("50000"),
2584            "diagnostic must carry the offending byte count verbatim (got {msg:?})"
2585        );
2586        assert!(
2587            msg.contains("64 KiB") || msg.contains("65536"),
2588            "diagnostic must name the page-size floor (got {msg:?})"
2589        );
2590    }
2591
2592    #[test]
2593    fn below_page_value_still_round_trips_through_serde() {
2594        // The byte-size codec accepts the sub-page value (the floor
2595        // lives in the validate gate, not the codec) — peer of
2596        // `above_cap_value_still_round_trips_through_serde` on the top
2597        // edge. Pins that the structural property is "sub-page is
2598        // rejected by validate" — not "sub-page is unparseable by the
2599        // codec"; the latter would prevent the diagnostic from naming
2600        // the offending byte count at all, since deserialize would
2601        // fail first.
2602        let l = LimitsSpec {
2603            memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES - 1),
2604            ..Default::default()
2605        };
2606        let json = serde_json::to_string(&l).unwrap();
2607        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
2608        assert_eq!(l, back);
2609        assert!(back.validate().is_err());
2610    }
2611
2612    // ── value-shape: :memory page-multiple granularity gate ───────────────
2613
2614    #[test]
2615    fn validate_rejects_memory_one_byte_above_page() {
2616        // The fail-before-pass-after pin: until this gate landed a
2617        // `LimitsSpec { memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES +
2618        // 1), .. }` (65537 bytes — one wasm32 page plus a 1-byte
2619        // unreachable residue) silently passed validate, the byte-size
2620        // codec round-tripped cleanly through serde (`render_byte_size`
2621        // falls through to `"65537"` on any non-power-of-1024 magnitude),
2622        // and wasmtime's `StoreLimits::memory_size` consumed the value
2623        // verbatim as a page-quantized ceiling — the engine grew at
2624        // most floor(65537 / 65536) = 1 page, and the byte at offset
2625        // 65536 became structural dead space the runtime cannot honor.
2626        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
2627        let l = LimitsSpec {
2628            memory: Some(bytes),
2629            ..Default::default()
2630        };
2631        assert_eq!(
2632            l.validate().unwrap_err(),
2633            LimitsError::MemoryNotPageMultiple { bytes }
2634        );
2635    }
2636
2637    #[test]
2638    fn validate_rejects_memory_just_below_two_pages() {
2639        // Boundary case: exactly 1 byte below two pages (`2 *
2640        // LIMITS_MEMORY_WASM32_PAGE_BYTES - 1` = 131071 bytes). Pins
2641        // the inclusive-page-boundary / strict-sub-page-residue
2642        // relationship on the page-multiple arm: 131071 is *out*
2643        // (sub-page residue), 131072 is *in* (exactly two pages).
2644        // Matches the peer `validate_rejects_memory_one_byte_below_page`
2645        // / `validate_rejects_memory_one_byte_above_wasm32_cap` shape
2646        // on the surrounding edges.
2647        let bytes = 2 * LIMITS_MEMORY_WASM32_PAGE_BYTES - 1;
2648        let l = LimitsSpec {
2649            memory: Some(bytes),
2650            ..Default::default()
2651        };
2652        assert_eq!(
2653            l.validate().unwrap_err(),
2654            LimitsError::MemoryNotPageMultiple { bytes }
2655        );
2656    }
2657
2658    #[test]
2659    fn validate_rejects_memory_100000_bytes() {
2660        // The "obvious authoring footgun" case: a magnitude the
2661        // byte-size codec accepts cleanly (`"100000"` → 100000 bytes
2662        // ≈ 97.65 KiB) and serde round-trips silently, but no wasm32
2663        // engine can honor as a meaningful ceiling — the engine grows
2664        // at most floor(100000 / 65536) = 1 page, and the 34464 bytes
2665        // between offsets 65536 and 100000 are structural dead space.
2666        // Until this gate landed `validate` accepted it. Peer of
2667        // `validate_rejects_memory_8_gib` on the cap arm.
2668        let bytes = parse_byte_size("100000").unwrap();
2669        let l = LimitsSpec {
2670            memory: Some(bytes),
2671            ..Default::default()
2672        };
2673        assert_eq!(
2674            l.validate().unwrap_err(),
2675            LimitsError::MemoryNotPageMultiple { bytes }
2676        );
2677    }
2678
2679    #[test]
2680    fn validate_accepts_every_page_aligned_value_through_serde() {
2681        // Positive-control sweep through the byte-size codec: every
2682        // canonical magnitude `render_byte_size` emits at or above
2683        // the page floor divides cleanly by the page size, so the
2684        // page-multiple gate accepts the entire canonical-output
2685        // domain at and above the page floor. The sweep walks
2686        // single-page (`"64KiB"`), two-page (`"128KiB"`), every
2687        // power-of-1024 unit (`"1MiB"`, `"64MiB"`, `"1GiB"`, `"4GiB"`),
2688        // and the cap (`"4GiB"`) — pinning that the codec's
2689        // emitted-canonical-form set is a structural subset of the
2690        // validate gate's accepted set. Drift between the codec's
2691        // emit alphabet and the validate gate would surface here
2692        // rather than at a future serializer round trip.
2693        for s in ["64KiB", "128KiB", "1MiB", "64MiB", "1GiB", "4GiB"] {
2694            let bytes = parse_byte_size(s).unwrap();
2695            assert_eq!(
2696                bytes % LIMITS_MEMORY_WASM32_PAGE_BYTES,
2697                0,
2698                "canonical byte-size codec output {s:?} ({bytes}) must be page-aligned",
2699            );
2700            let l = LimitsSpec {
2701                memory: Some(bytes),
2702                ..Default::default()
2703            };
2704            l.validate()
2705                .unwrap_or_else(|e| panic!("canonical {s:?} = {bytes} must validate, got {e:?}"));
2706        }
2707    }
2708
2709    #[test]
2710    fn validate_memory_below_page_takes_precedence_over_page_multiple() {
2711        // Cross-arm ordering pin: `Some(1)` would otherwise pass the
2712        // page-multiple arm's `m % PAGE_BYTES != 0` check (1 % 65536
2713        // == 1 ≠ 0), but the page-floor arm strictly precedes the
2714        // page-multiple arm so the more self-locating
2715        // `MemoryBelowWasm32Page` diagnostic (with its "single page
2716        // cannot fit" remediation, applicable to every sub-page
2717        // value uniformly) leads. Peer of `MemoryZero` →
2718        // `MemoryBelowWasm32Page` precedence on the zero edge:
2719        // every value `m` in the range `1..=PAGE_BYTES-1` satisfies
2720        // both `m < PAGE_BYTES` and `m % PAGE_BYTES != 0`, but the
2721        // structurally-narrower diagnostic (page-floor) leads.
2722        let l = LimitsSpec {
2723            memory: Some(1),
2724            ..Default::default()
2725        };
2726        assert_eq!(
2727            l.validate().unwrap_err(),
2728            LimitsError::MemoryBelowWasm32Page { bytes: 1 }
2729        );
2730    }
2731
2732    #[test]
2733    fn validate_memory_cap_takes_precedence_over_page_multiple() {
2734        // Cross-arm ordering pin: `LIMITS_MEMORY_WASM32_MAX_BYTES + 1`
2735        // (4 GiB + 1 byte) is *both* above-cap and not page-aligned.
2736        // The cap arm strictly precedes the page-multiple arm so the
2737        // more aggressive cap-shape diagnostic leads (the page-multiple
2738        // remediation would be misleading when the offending value
2739        // exceeds the wasm32 address-space ceiling anyway — the
2740        // canonical fix collapses both into "pin a page-aligned value
2741        // ≤ 4 GiB"). Peer of `WallClockNotCanonical` →
2742        // `WallClockExceedsCap` ordering on the sibling `:wall-clock`
2743        // axis (with the inverse polarity — there the granularity
2744        // gate leads because sub-millisecond residue breaks serde
2745        // round-trip; here the cap leads because both gates' offending
2746        // values round-trip cleanly through serde and the broader
2747        // magnitude constraint is the more aggressive one).
2748        let bytes = LIMITS_MEMORY_WASM32_MAX_BYTES + 1;
2749        let l = LimitsSpec {
2750            memory: Some(bytes),
2751            ..Default::default()
2752        };
2753        assert_eq!(
2754            l.validate().unwrap_err(),
2755            LimitsError::MemoryExceedsWasm32Cap { bytes }
2756        );
2757    }
2758
2759    #[test]
2760    fn validate_rejects_memory_page_multiple_before_other_axes() {
2761        // With a sub-page-residue `:memory` and zero values on every
2762        // other axis, the diagnostic names `:memory` rather than
2763        // `:fuel` / `:wall-clock` / `:cpu` — peer of the existing
2764        // `validate_memory_page_floor_takes_precedence_over_other_axes`
2765        // and `validate_rejects_memory_cap_before_other_axes` ordering
2766        // pins. Memory is the first axis the validate cascade checks,
2767        // so a sub-page-residue value surfaces before any other-axis
2768        // diagnostic regardless of how many other axes are
2769        // simultaneously invalid.
2770        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
2771        let l = LimitsSpec {
2772            memory: Some(bytes),
2773            fuel: Some(0),
2774            wall_clock: Some(Duration::ZERO),
2775            cpu: Some(0),
2776        };
2777        assert_eq!(
2778            l.validate().unwrap_err(),
2779            LimitsError::MemoryNotPageMultiple { bytes }
2780        );
2781    }
2782
2783    #[test]
2784    fn memory_page_multiple_diagnostic_carries_offending_bytes() {
2785        // Diagnostic-shape pin: the page-multiple arm names the
2786        // offending byte count verbatim so the author's grep lands on
2787        // the field's value, not a generic "memory not aligned"
2788        // message. Same shape every other typed-cap arm on this
2789        // surface carries (`MemoryExceedsWasm32Cap` carries the
2790        // offending byte count verbatim, `WallClockNotCanonical`
2791        // carries the offending `Duration` verbatim).
2792        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 12345;
2793        let l = LimitsSpec {
2794            memory: Some(bytes),
2795            ..Default::default()
2796        };
2797        let err = l.validate().unwrap_err();
2798        let msg = err.to_string();
2799        assert!(
2800            msg.contains(&bytes.to_string()),
2801            "diagnostic must carry the offending byte count verbatim (got {msg:?})"
2802        );
2803        assert!(
2804            msg.contains("64 KiB") || msg.contains("65536") || msg.contains("page"),
2805            "diagnostic must name the page-size granularity (got {msg:?})"
2806        );
2807    }
2808
2809    #[test]
2810    fn sub_page_residue_value_still_round_trips_through_serde() {
2811        // The byte-size codec accepts the sub-page-residue value (the
2812        // page-multiple gate lives in validate, not in the codec) —
2813        // peer of `above_cap_value_still_round_trips_through_serde`
2814        // and `below_page_value_still_round_trips_through_serde`.
2815        // Pins that the structural property is "sub-page-residue is
2816        // rejected by validate" — not "sub-page-residue is
2817        // unparseable by the codec"; the latter would prevent the
2818        // diagnostic from naming the offending byte count at all,
2819        // since deserialize would fail first. The render-then-parse
2820        // round trip also pins the codec's flow-through-to-bytes
2821        // shape on non-power-of-1024 magnitudes: `render_byte_size`
2822        // falls through every `(mult, label)` arm whose `n % mult !=
2823        // 0` and emits the bare byte count.
2824        let bytes = LIMITS_MEMORY_WASM32_PAGE_BYTES + 1;
2825        let l = LimitsSpec {
2826            memory: Some(bytes),
2827            ..Default::default()
2828        };
2829        let json = serde_json::to_string(&l).unwrap();
2830        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
2831        assert_eq!(l, back);
2832        assert!(back.validate().is_err());
2833    }
2834
2835    #[test]
2836    fn validate_memory_axis_routes_through_quantum_multiple_bounded_helper() {
2837        // Byte-parity pin on the pre-lift `if self.memory() == Some(0)
2838        // { … } if let Some(m) = self.memory() { if m <
2839        // LIMITS_MEMORY_WASM32_PAGE_BYTES { … } } if let Some(m) =
2840        // self.memory() { if m > LIMITS_MEMORY_WASM32_MAX_BYTES { … } }
2841        // if let Some(m) = self.memory() && m %
2842        // LIMITS_MEMORY_WASM32_PAGE_BYTES != 0 { … }` four-sequential-
2843        // `if let` shape the `LimitsSpec::validate` `:memory` axis
2844        // routed through today via
2845        // `crate::render::require_positive_quantum_multiple_bounded_u64`.
2846        // Refuses a future accidental split between the helper's
2847        // four-arm ordering (zero → below-quantum → cap → not-multiple)
2848        // and the four typed `LimitsError::Memory*` variants each arm
2849        // threads its offending byte count into — a swap of any two
2850        // arms in the helper, or a partial widening (e.g. removing the
2851        // page-multiple arm), or a widening of the `on_below_quantum`
2852        // arm's closure to the `MemoryExceedsWasm32Cap` variant instead
2853        // of `MemoryBelowWasm32Page` — would break exactly one row of
2854        // this pin, matching the pre-lift shape the four consumer sites
2855        // route through today. Same shape as
2856        // `as_seq_body_partitions_the_same_arm_set_as_seq_delims` in
2857        // caixa-ast and the peer `require_positive_bounded_u64` tests
2858        // in the sibling render.rs test module.
2859        //
2860        // (Some(bytes) → expected LimitsError)
2861        let quantum = LIMITS_MEMORY_WASM32_PAGE_BYTES;
2862        let cap = LIMITS_MEMORY_WASM32_MAX_BYTES;
2863        let cases: &[(u64, LimitsError)] = &[
2864            (0, LimitsError::MemoryZero),
2865            (1, LimitsError::MemoryBelowWasm32Page { bytes: 1 }),
2866            (
2867                quantum - 1,
2868                LimitsError::MemoryBelowWasm32Page { bytes: quantum - 1 },
2869            ),
2870            (
2871                cap + 1,
2872                LimitsError::MemoryExceedsWasm32Cap { bytes: cap + 1 },
2873            ),
2874            (
2875                cap + quantum,
2876                LimitsError::MemoryExceedsWasm32Cap {
2877                    bytes: cap + quantum,
2878                },
2879            ),
2880            (
2881                quantum + 1,
2882                LimitsError::MemoryNotPageMultiple { bytes: quantum + 1 },
2883            ),
2884            (
2885                quantum + 12_345,
2886                LimitsError::MemoryNotPageMultiple {
2887                    bytes: quantum + 12_345,
2888                },
2889            ),
2890        ];
2891        for (bytes, expected) in cases {
2892            let l = LimitsSpec {
2893                memory: Some(*bytes),
2894                ..Default::default()
2895            };
2896            assert_eq!(
2897                l.validate().unwrap_err(),
2898                *expected,
2899                "memory={bytes} must surface the {expected:?} arm via the substrate helper",
2900            );
2901        }
2902        // Positive-control: every quantum-multiple in `quantum..=cap`
2903        // passes, closing the four-arm cascade with an `Ok(())` shape.
2904        for bytes in [quantum, quantum * 2, quantum * 100, cap] {
2905            let l = LimitsSpec {
2906                memory: Some(bytes),
2907                ..Default::default()
2908            };
2909            l.validate().unwrap();
2910        }
2911    }
2912
2913    // ── canonical-form: integer-magnitude byte-size codec gate ────────────
2914    //
2915    // Every magnitude `render_byte_size` emits is a non-negative integer
2916    // (no decimal point, no leading sign, no scientific notation). The
2917    // parser's accepted set must match for parse → render → parse to
2918    // round-trip without canonical-form drift. The tests below pin every
2919    // canonical-drift shape — fractional (`"1.5KiB"`), decimal-shaped-
2920    // integer (`"1.0MiB"`), half-unit (`"0.5GiB"`), leading-`+`
2921    // (`"+1024"`) — plus the scientific-notation dispatch path (caught
2922    // by `UnknownByteUnit` on a different arm), the two complement-side
2923    // pins (the integer happy paths the gate must continue to accept),
2924    // the round-trip convergence property (parse → render → parse must
2925    // converge on a single canonical form for every accepted input),
2926    // the BadByteMagnitude-precedence pin (genuinely unparseable inputs
2927    // keep their narrower diagnostic), the overflow-surface pin
2928    // (u64-overflow on magnitude × unit surfaces at parse time), and
2929    // the serde-path pin (the gate fires at deserialize, before any
2930    // validate gate runs).
2931
2932    #[test]
2933    fn parse_byte_size_rejects_fractional_kib() {
2934        // The fail-before-pass-after pin: `"1.5KiB"` parsed cleanly on
2935        // every pre-gate codebase (f64::parse accepts the decimal), the
2936        // codec produced 1536 bytes, and `render_byte_size(1536)`
2937        // emitted `"1536"` on the next serialize — silently drifting
2938        // the canonical form away from the author's intent. The new
2939        // gate surfaces the round-trip break at the parser layer with
2940        // a self-locating diagnostic (the offending magnitude verbatim,
2941        // the canonical-form remediation in the wording).
2942        let err = parse_byte_size("1.5KiB").unwrap_err();
2943        assert!(
2944            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "1.5"),
2945            "got {err:?}"
2946        );
2947    }
2948
2949    #[test]
2950    fn parse_byte_size_rejects_decimal_shaped_integer() {
2951        // The canonical-drift case where the *value* is integer but
2952        // the *form* carries a redundant decimal point — `"1.0MiB"`
2953        // parses to 1 MiB (integer), but the renderer emits `"1MiB"`
2954        // on the next serialize (no decimal point). The parse-shape
2955        // gate fires here too so the codec's accepted set is exactly
2956        // the renderer's emitted set — no `"1.0MiB"` ↔ `"1MiB"` drift
2957        // surviving a round-trip silently.
2958        let err = parse_byte_size("1.0MiB").unwrap_err();
2959        assert!(
2960            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "1.0"),
2961            "got {err:?}"
2962        );
2963    }
2964
2965    #[test]
2966    fn parse_byte_size_rejects_half_gib() {
2967        // `"0.5GiB"` parses to 536870912 bytes = 512MiB; the renderer
2968        // emits `"512MiB"` on the next serialize. Pin the round-trip
2969        // drift on the explicitly-fractional case sized to land on a
2970        // unit boundary, so the gate's coverage includes both the
2971        // "doesn't land on a boundary" (1.5KiB → 1536) and "lands on
2972        // a smaller-unit boundary" (0.5GiB → 512MiB) drift shapes.
2973        let err = parse_byte_size("0.5GiB").unwrap_err();
2974        assert!(
2975            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "0.5"),
2976            "got {err:?}"
2977        );
2978    }
2979
2980    #[test]
2981    fn parse_byte_size_rejects_scientific_notation_via_unit_arm() {
2982        // Scientific-notation magnitudes are canonical-form drift too
2983        // — the renderer never emits `"1e3KiB"` for any value. But
2984        // they're caught on a *different* arm than the fractional /
2985        // leading-`+` shapes: the parser's split-on-first-alphabetic-
2986        // byte heuristic reads the `e` as a unit prefix, so the input
2987        // falls into the existing `UnknownByteUnit { unit: "e3KiB" }`
2988        // diagnostic before the `NonIntegerByteMagnitude` gate is
2989        // consulted. Pin this dispatch path so a future relaxation of
2990        // the split heuristic (e.g. recognizing `e` as part of a
2991        // scientific-notation magnitude) surfaces here as a test
2992        // failure — at which point the `NonIntegerByteMagnitude` gate
2993        // would correctly take over, and this test would flip to that
2994        // arm with no other change required.
2995        let err = parse_byte_size("1e3KiB").unwrap_err();
2996        assert!(
2997            matches!(err, LimitsError::UnknownByteUnit { ref unit } if unit == "e3KiB"),
2998            "got {err:?}"
2999        );
3000    }
3001
3002    #[test]
3003    fn parse_byte_size_rejects_leading_plus() {
3004        // `"+1024"` parses through f64 as 1024 bytes; the renderer
3005        // emits `"1KiB"` on the next serialize. The leading `+` is
3006        // not a renderer-emitted shape, so it falls in the same
3007        // canonical-drift class as the fractional / scientific forms
3008        // — surfacing under the same diagnostic keeps the gate's
3009        // coverage uniform across every non-canonical-but-numeric
3010        // input shape the parser would otherwise accept.
3011        let err = parse_byte_size("+1024").unwrap_err();
3012        assert!(
3013            matches!(err, LimitsError::NonIntegerByteMagnitude { ref value } if value == "+1024"),
3014            "got {err:?}"
3015        );
3016    }
3017
3018    #[test]
3019    fn parse_byte_size_continues_to_accept_integer_magnitudes() {
3020        // The complement-side pin: every canonical integer-magnitude
3021        // form the renderer emits must continue to parse to the same
3022        // value the renderer produced. Sweep the five canonical
3023        // authoring shapes (unitless integer, KiB, MiB, GiB, KB) so a
3024        // future tightening of the parser surfaces here as a test
3025        // failure rather than a silent regression in the canonical
3026        // authoring set.
3027        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
3028        assert_eq!(parse_byte_size("1KiB").unwrap(), 1024);
3029        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
3030        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
3031        assert_eq!(parse_byte_size("1000KB").unwrap(), 1_000_000);
3032    }
3033
3034    #[test]
3035    fn parse_byte_size_round_trips_through_render_for_every_canonical_form() {
3036        // The structural property the gate makes load-bearing: every
3037        // value the parser accepts round-trips through `render_byte_size`
3038        // to a string the parser also accepts — and to the *same* value.
3039        // Sweep the values the renderer emits canonically (1024 / 1MiB
3040        // / 1GiB / 1536 / 64MiB) so a future codec change that breaks
3041        // round-trip convergence surfaces here, not at a downstream
3042        // renderer that double-emits a typed slot.
3043        for n in [1u64, 1023, 1024, 1536, 64 * 1024 * 1024, 1024 * 1024 * 1024] {
3044            let rendered = render_byte_size(n);
3045            let reparsed = parse_byte_size(&rendered)
3046                .unwrap_or_else(|e| panic!("render({n}) = {rendered:?} must reparse, got {e:?}"));
3047            assert_eq!(
3048                reparsed, n,
3049                "round-trip drift on {n}: rendered={rendered:?}, reparsed={reparsed}",
3050            );
3051        }
3052    }
3053
3054    #[test]
3055    fn parse_byte_size_keeps_bad_magnitude_for_unparseable_input() {
3056        // The precedence pin: the new `NonIntegerByteMagnitude` arm
3057        // distinguishes *non-canonical-but-numeric* (`"1.5"`, `"1.0"`,
3058        // `"+1024"`, `"-1"`) from *genuinely-unparseable* (`"abc"`,
3059        // `"--1"`) so the existing `BadByteMagnitude` diagnostic's
3060        // wording remains load-bearing for the latter class — the gate
3061        // is additive, not replacing. Pin both arms so a future
3062        // relaxation that collapses them surfaces here.
3063        let err = parse_byte_size("abc").unwrap_err();
3064        assert!(
3065            matches!(err, LimitsError::BadByteMagnitude(_)),
3066            "got {err:?}"
3067        );
3068        let err = parse_byte_size("--1").unwrap_err();
3069        assert!(
3070            matches!(err, LimitsError::BadByteMagnitude(_)),
3071            "got {err:?}"
3072        );
3073    }
3074
3075    #[test]
3076    fn parse_byte_size_overflow_surfaces_as_bad_magnitude() {
3077        // `u64::MAX KiB` overflows the u64 result; the parser surfaces
3078        // the overflow as a `BadByteMagnitude` (not as a saturated
3079        // `u64::MAX` value that the wasm32-cap validate gate then
3080        // catches), so the diagnostic names the offending magnitude ×
3081        // unit pair at parse time rather than as
3082        // `MemoryExceedsWasm32Cap { bytes: u64::MAX }` far from the
3083        // author's intent. (`u64::MAX` itself parses cleanly with no
3084        // unit since `u64::MAX × 1 = u64::MAX` fits.)
3085        let err = parse_byte_size("18446744073709551615KiB").unwrap_err();
3086        let LimitsError::BadByteMagnitude(reason) = err else {
3087            panic!("expected BadByteMagnitude(overflow), got other variant");
3088        };
3089        assert!(
3090            reason.contains("overflow"),
3091            "overflow diagnostic must mention overflow (got {reason:?})"
3092        );
3093    }
3094
3095    // ── canonical-form: leading-zero byte-size codec gate ─────────────────
3096    //
3097    // Direct successor to the `parse_duration` leading-zero arm (39762d7),
3098    // the `supervisor::duration_codec` leading-zero arm (9178904), and the
3099    // `rate_limit_codec` leading-zero arm (4f46830) — the same canonical-
3100    // form render-determinism axis applied to the last typed-numeric codec
3101    // that still admitted leading-zero magnitudes. The digit-only gate
3102    // immediately above accepts every `u64::from_str`-parseable magnitude
3103    // including leading-zero padding, but `render_byte_size` always emits
3104    // the stripped form (`64MiB`, never `064MiB`) — silently drifting the
3105    // canonical string across a parse/render round-trip. Pins each
3106    // canonical leading-zero shape across the unit-set the codec admits
3107    // (KB / MB / GB / KiB / MiB / GiB / bare-integer), the all-zero
3108    // degenerate case, the codec-vs-validate-layer partition (single-byte
3109    // `"0"` stays accepted at the codec because the typed-validate gate
3110    // `MemoryZero` refuses semantic-zero authoring), the complement-side
3111    // pin (`1`..=`9`-led magnitudes stay accepted), and the serde-path pin
3112    // (the gate fires at deserialize, before any validate gate runs).
3113
3114    #[test]
3115    fn parse_byte_size_rejects_leading_zero_magnitude() {
3116        // The fail-before-pass-after pin: `"064MiB"` parsed cleanly on
3117        // every pre-gate codebase (`u64::from_str` accepts the leading
3118        // zero), the codec produced 64 MiB, and
3119        // `render_byte_size(64*1024*1024)` emitted `"64MiB"` on the next
3120        // serialize — silently dropping the leading zero and drifting
3121        // the canonical form away from the author's intent. The new
3122        // gate surfaces the round-trip break at the parser layer with a
3123        // self-locating diagnostic, peer with
3124        // `parse_duration_rejects_leading_zero_magnitude` on the sibling
3125        // codec.
3126        let err = parse_byte_size("064MiB").unwrap_err();
3127        assert!(
3128            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "064"),
3129            "got {err:?}"
3130        );
3131    }
3132
3133    #[test]
3134    fn parse_byte_size_rejects_multi_digit_zero_magnitude() {
3135        // `"00MiB"` is the degenerate leading-zero case — every byte is
3136        // `0`. `u64::from_str("00")` = 0, and the codec produces 0;
3137        // `render_byte_size(0)` emits `"0"` on the next serialize —
3138        // drift from `"00MiB"` to `"0"`. The leading-zero arm refuses
3139        // the drift class at the codec layer while leaving the
3140        // canonical single-byte `"0"` accepted. Peer with
3141        // `parse_duration_rejects_multi_digit_zero_magnitude` on the
3142        // sibling codec.
3143        let err = parse_byte_size("00MiB").unwrap_err();
3144        assert!(
3145            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "00"),
3146            "got {err:?}"
3147        );
3148    }
3149
3150    #[test]
3151    fn parse_byte_size_rejects_leading_zero_in_gib_unit() {
3152        // `"01GiB"` parses to 1 GiB; the renderer emits `"1GiB"` on the
3153        // next serialize. The leading-zero class is a property of the
3154        // magnitude, not the unit — pin a per-GiB magnitude alongside
3155        // the per-MiB / per-KiB / bare-integer pins so the gate's
3156        // coverage is structural across every canonical unit suffix
3157        // the codec accepts. Mirrors the per-hour pin
3158        // `parse_duration_rejects_leading_zero_in_hour_window` carries
3159        // on the sibling codec.
3160        let err = parse_byte_size("01GiB").unwrap_err();
3161        assert!(
3162            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "01"),
3163            "got {err:?}"
3164        );
3165    }
3166
3167    #[test]
3168    fn parse_byte_size_rejects_leading_zero_in_kib_unit() {
3169        // `"0512KiB"` parses to 512 KiB; the renderer emits `"512KiB"`
3170        // on the next serialize. Pin the per-KiB magnitude alongside
3171        // the per-MiB / per-GiB pins so the gate's coverage extends to
3172        // the smallest-unit power-of-1024 suffix the codec admits.
3173        let err = parse_byte_size("0512KiB").unwrap_err();
3174        assert!(
3175            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "0512"),
3176            "got {err:?}"
3177        );
3178    }
3179
3180    #[test]
3181    fn parse_byte_size_rejects_leading_zero_in_decimal_units() {
3182        // `"0500MB"` parses to 500 MB (decimal-unit family — `KB` /
3183        // `MB` / `GB` powers of 1000, distinct from the `KiB` / `MiB` /
3184        // `GiB` powers-of-1024 family); the renderer emits the
3185        // appropriate canonical form on the next serialize. Pin the
3186        // decimal-unit family alongside the power-of-1024 family so the
3187        // gate's coverage is structural across both unit families the
3188        // codec admits.
3189        for (s, expected) in [("0500MB", "0500"), ("01KB", "01"), ("00GB", "00")] {
3190            let err = parse_byte_size(s).unwrap_err();
3191            assert!(
3192                matches!(err, LimitsError::LeadingZeroByteMagnitude { value: ref v } if v == expected),
3193                "got {err:?} for {s:?}"
3194            );
3195        }
3196    }
3197
3198    #[test]
3199    fn parse_byte_size_rejects_leading_zero_bare_integer() {
3200        // The bare-integer (no unit) shorthand inherits the leading-
3201        // zero arm: `"01024"` parses losslessly to 1024 bytes but
3202        // `render_byte_size(1024)` emits `"1KiB"` on the next serialize.
3203        // Pin the bare-integer path so a future relaxation that
3204        // special-cases the unitless shorthand surfaces here as a test
3205        // failure. Mirrors the bare-integer pin
3206        // `parse_duration_rejects_leading_zero_bare_integer_as_seconds`
3207        // carries on the sibling codec.
3208        let err = parse_byte_size("01024").unwrap_err();
3209        assert!(
3210            matches!(err, LimitsError::LeadingZeroByteMagnitude { ref value } if value == "01024"),
3211            "got {err:?}"
3212        );
3213    }
3214
3215    #[test]
3216    fn parse_byte_size_accepts_single_zero_magnitude_at_codec_layer() {
3217        // The codec-layer / typed-validate-layer boundary pin: the
3218        // single-byte `"0"` magnitude round-trips losslessly through
3219        // `render_byte_size` (`render_byte_size(0)` emits `"0"`), so it
3220        // stays accepted at this codec layer across every canonical
3221        // unit suffix. The downstream `LimitsError::MemoryZero` gate is
3222        // what refuses zero-magnitude authoring at the typed-validate
3223        // layer above — the partition keeps the canonical-form-drift
3224        // diagnostic (this arm) and the semantic-zero diagnostic (the
3225        // validate gate) disjoint. Mirrors the
3226        // `parse_duration_accepts_single_zero_magnitude_at_codec_layer`
3227        // partition pin on the sibling codec.
3228        assert_eq!(parse_byte_size("0").unwrap(), 0);
3229        assert_eq!(parse_byte_size("0B").unwrap(), 0);
3230        assert_eq!(parse_byte_size("0KiB").unwrap(), 0);
3231        assert_eq!(parse_byte_size("0MiB").unwrap(), 0);
3232        assert_eq!(parse_byte_size("0GiB").unwrap(), 0);
3233        assert_eq!(parse_byte_size("0KB").unwrap(), 0);
3234    }
3235
3236    #[test]
3237    fn parse_byte_size_accepts_canonical_magnitude_with_leading_one() {
3238        // The complement-side pin on the leading-zero arm: magnitudes
3239        // beginning with `1`..=`9` stay accepted across every canonical
3240        // unit suffix the codec accepts. Pin this so a future
3241        // tightening cannot drift into rejecting valid canonical
3242        // magnitudes — peer with the
3243        // `parse_duration_accepts_canonical_magnitude_with_leading_one`
3244        // pin on the sibling codec.
3245        assert_eq!(parse_byte_size("1").unwrap(), 1);
3246        assert_eq!(parse_byte_size("1KiB").unwrap(), 1024);
3247        assert_eq!(parse_byte_size("1MiB").unwrap(), 1024 * 1024);
3248        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
3249        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
3250        assert_eq!(parse_byte_size("9").unwrap(), 9);
3251    }
3252
3253    #[test]
3254    fn de_byte_size_rejects_leading_zero_through_serde() {
3255        // The serde-path pin: a `:limits :memory` carrying a
3256        // leading-zero magnitude (`"064MiB"`) must fail at deserialize
3257        // time, not silently round-trip the value through the parser.
3258        // The gate fires at deserialize, before any validate gate runs
3259        // — peer with `de_duration_rejects_leading_zero_through_serde`
3260        // on the sibling codec.
3261        let json = r#"{"memory":"064MiB"}"#;
3262        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
3263        let msg = err.to_string();
3264        assert!(
3265            msg.contains("leading zero"),
3266            "serde diagnostic must surface the leading-zero reason verbatim (got {msg:?})"
3267        );
3268    }
3269
3270    // ── canonical-form: whitespace-rejection byte-size codec gate ─────────
3271    //
3272    // Direct successor to the `parse_duration` whitespace-rejection arm
3273    // (ebc3a75), the `supervisor::duration_codec` whitespace-rejection
3274    // arm (a7ae622), and the `rate_limit_codec` whitespace-rejection arm
3275    // (1ad7755) on the same canonical-form render-determinism axis. The
3276    // pre-gate top-level `s.trim()` at parse entry and the per-part
3277    // `num_part.trim()` / `unit.trim()` calls silently ate leading /
3278    // trailing / internal whitespace, so every whitespace-carrying
3279    // shape parsed to the same byte magnitude and round-tripped through
3280    // `render_byte_size` to a *different* canonical string on next
3281    // serialize — the same canonical-form-drift class the leading-`+` /
3282    // fractional / leading-zero arms already close on this codec.
3283    // `u8::is_ascii_whitespace` covers the five WhatWG-conformant ASCII
3284    // whitespace bytes (space `0x20`, tab `0x09`, LF `0x0A`, FF `0x0C`,
3285    // CR `0x0D`). Closes the whitespace-rejection axis across every
3286    // typed-magnitude codec in caixa-core.
3287
3288    #[test]
3289    fn parse_byte_size_rejects_leading_whitespace() {
3290        // The fail-before-pass-after pin: `" 64MiB"` — the canonical
3291        // paste-from-aligned-doc / paste-from-YAML-quoted-plain-scalar
3292        // footgun. Before this gate the top-level `s.trim()` at parse
3293        // entry silently ate the leading space and parsed the value to
3294        // 64 * 1024 * 1024 bytes, which then round-tripped through
3295        // `render_byte_size` to `"64MiB"` (a *different* canonical
3296        // string on the next emit) — the exact canonical-form-drift
3297        // class the leading-`+` / leading-zero arms already close,
3298        // extended to the whitespace-byte class. Peer with the sibling
3299        // `parse_duration_rejects_leading_whitespace` arm (ebc3a75) on
3300        // the shared canonical-form-drift trajectory.
3301        let err = parse_byte_size(" 64MiB").unwrap_err();
3302        assert!(
3303            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == " 64MiB" && byte == 0x20),
3304            "got {err:?}"
3305        );
3306        let msg = err.to_string();
3307        assert!(
3308            msg.contains("whitespace byte 0x20"),
3309            "diagnostic must surface the offending byte verbatim (got {msg:?})"
3310        );
3311        assert!(
3312            msg.contains("THEORY.md"),
3313            "diagnostic must cite the render-determinism contract (got {msg:?})"
3314        );
3315    }
3316
3317    #[test]
3318    fn parse_byte_size_rejects_trailing_whitespace() {
3319        // `"64MiB "` — the canonical shell-history / trailing-space
3320        // paste footgun. Before this gate the top-level `s.trim()`
3321        // silently ate the trailing space and parsed to 64 * 1024 *
3322        // 1024 bytes, round-tripping to `"64MiB"` on the next emit —
3323        // same canonical-form drift as the leading-space sibling,
3324        // closed on the same whitespace-byte arm.
3325        let err = parse_byte_size("64MiB ").unwrap_err();
3326        assert!(
3327            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "64MiB " && byte == 0x20),
3328            "got {err:?}"
3329        );
3330    }
3331
3332    #[test]
3333    fn parse_byte_size_rejects_internal_whitespace_between_magnitude_and_unit() {
3334        // `"64 MiB"` — the canonical typographically-spaced author
3335        // shape (the same idiom every prose reference to a byte-size
3336        // renders as, mistakenly retained when the value is pasted
3337        // into a codec-shaped slot). Before this gate the per-part
3338        // `num_part.trim()` / `unit.trim()` calls silently ate the
3339        // whitespace between the magnitude and the unit and parsed the
3340        // value to 64 * 1024 * 1024 bytes, round-tripping to `"64MiB"`
3341        // — the codec's *internal* whitespace-tolerance vector,
3342        // orthogonal to the leading / trailing surface but the same
3343        // canonical-form-drift class. Pins the arm as strictly
3344        // stronger than the pre-existing top-level `s.trim()`
3345        // behavior: it fires on whitespace anywhere in the value, not
3346        // just at the string boundary.
3347        let err = parse_byte_size("64 MiB").unwrap_err();
3348        assert!(
3349            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "64 MiB" && byte == 0x20),
3350            "got {err:?}"
3351        );
3352    }
3353
3354    #[test]
3355    fn parse_byte_size_rejects_tab_byte() {
3356        // `"\t64MiB"` — the canonical paste-from-indented-doc /
3357        // paste-from-YAML-block-scalar footgun where a tab byte leads
3358        // the magnitude. Pins that the gate covers tab (`0x09`) as
3359        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
3360        // members and both would be silently swallowed by `s.trim()`
3361        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
3362        // space alone to the full ASCII-whitespace set (space `0x20`,
3363        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
3364        // the tab arm as a representative of the non-space members.
3365        let err = parse_byte_size("\t64MiB").unwrap_err();
3366        assert!(
3367            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "\t64MiB" && byte == 0x09),
3368            "got {err:?}"
3369        );
3370    }
3371
3372    #[test]
3373    fn parse_byte_size_rejects_trailing_newline() {
3374        // `"64MiB\n"` — the canonical multi-line-paste footgun where
3375        // a trailing LF byte survives the paste. Pins the LF member
3376        // (`0x0A`) of the `is_ascii_whitespace` set as a peer to the
3377        // space and tab pins above — every non-space non-tab
3378        // whitespace byte the WhatWG ASCII-whitespace set covers is
3379        // refused by the same arm.
3380        let err = parse_byte_size("64MiB\n").unwrap_err();
3381        assert!(
3382            matches!(err, LimitsError::WhitespaceInByteSize { ref value, byte } if value == "64MiB\n" && byte == 0x0a),
3383            "got {err:?}"
3384        );
3385    }
3386
3387    #[test]
3388    fn parse_byte_size_accepts_whitespace_free_canonical_forms() {
3389        // The complement-side pin: every canonical whitespace-free
3390        // authoring form the renderer emits stays accepted post-gate.
3391        // Sweep the canonical unit suffixes plus the bare-integer
3392        // shorthand so a future tightening of the whitespace arm that
3393        // over-fires on the accepted set surfaces here as a test
3394        // failure. Peer with the
3395        // `parse_duration_accepts_whitespace_free_canonical_forms` pin
3396        // on the sibling codec.
3397        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
3398        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
3399        assert_eq!(parse_byte_size("512KiB").unwrap(), 512 * 1024);
3400        assert_eq!(parse_byte_size("1KB").unwrap(), 1_000);
3401        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
3402        assert_eq!(parse_byte_size("0").unwrap(), 0);
3403    }
3404
3405    #[test]
3406    fn de_byte_size_rejects_whitespace_through_serde() {
3407        // The serde-path pin: a `:limits :memory` carrying a
3408        // whitespace-byte-carrying value (`" 64MiB"`) must fail at
3409        // deserialize time, not silently round-trip the value through
3410        // the pre-existing top-level `s.trim()`. The gate fires at
3411        // deserialize, before any validate gate runs — peer with the
3412        // existing `de_byte_size_rejects_leading_zero_through_serde` /
3413        // `de_duration_rejects_whitespace_through_serde` pins on the
3414        // same canonical-form-drift axis.
3415        let json = r#"{"memory":" 64MiB"}"#;
3416        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
3417        let msg = err.to_string();
3418        assert!(
3419            msg.contains("whitespace byte"),
3420            "serde diagnostic must surface the whitespace reason verbatim (got {msg:?})"
3421        );
3422        assert!(
3423            msg.contains("0x20"),
3424            "serde diagnostic must name the offending byte (got {msg:?})"
3425        );
3426
3427        // The whitespace-free complement — same author-side intent,
3428        // written in the canonical form the renderer would emit,
3429        // deserializes cleanly.
3430        let json = r#"{"memory":"64MiB"}"#;
3431        let l: LimitsSpec = serde_json::from_str(json).unwrap();
3432        assert_eq!(l.memory, Some(64 * 1024 * 1024));
3433    }
3434
3435    // ── canonical-form: non-ASCII Unicode `White_Space` byte-size gate ────
3436    //
3437    // Direct successor to the `parse_byte_size` ASCII-whitespace arm
3438    // (24a8ad4) — closes the strictly-complementary class the byte-scan
3439    // above cannot see. `str::trim` uses `char::is_whitespace` (Unicode
3440    // `White_Space`, strictly wider than the ASCII byte set); a leading /
3441    // trailing / internal NBSP (`\u{00A0}`) / LINE SEPARATOR (`\u{2028}`)
3442    // / EM-SPACE (`\u{2003}`) survives the byte-scan but is silently
3443    // stripped by the top-level trim, drifting to canonical `"64MiB"` on
3444    // round-trip. Pins the arm through the lifted
3445    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
3446
3447    #[test]
3448    fn parse_byte_size_rejects_leading_nbsp() {
3449        // NBSP (`\u{00A0}` = UTF-8 `0xC2 0xA0`) — the canonical
3450        // paste-from-typography / paste-from-word-processor footgun.
3451        // Before this arm landed the byte-scan missed it (neither `0xC2`
3452        // nor `0xA0` is `is_ascii_whitespace`) and `str::trim` at parse
3453        // entry silently stripped it, yielding the same `64 * 1024 *
3454        // 1024` bytes as the whitespace-free canonical form and drifting
3455        // to `"64MiB"` on next serialize.
3456        let s = "\u{00A0}64MiB";
3457        let err = parse_byte_size(s).unwrap_err();
3458        assert!(
3459            matches!(err, LimitsError::NonAsciiWhitespaceInByteSize { ref value, ch, codepoint } if value == s && ch == '\u{00A0}' && codepoint == 0x00A0),
3460            "got {err:?}"
3461        );
3462        let msg = err.to_string();
3463        assert!(
3464            msg.contains("U+00A0"),
3465            "diagnostic must surface the codepoint verbatim (got {msg:?})"
3466        );
3467        assert!(
3468            msg.contains("THEORY.md"),
3469            "diagnostic must cite the render-determinism contract (got {msg:?})"
3470        );
3471    }
3472
3473    #[test]
3474    fn parse_byte_size_rejects_internal_line_separator() {
3475        // LINE SEPARATOR (`\u{2028}`) between magnitude and unit — the
3476        // canonical paste-from-web-doc footgun (many rendering engines
3477        // insert `\u{2028}` at soft-wrap boundaries in RTF/HTML → plain
3478        // text conversion). Pins the arm on a non-space non-NBSP Unicode
3479        // `White_Space` member.
3480        let s = "64\u{2028}MiB";
3481        let err = parse_byte_size(s).unwrap_err();
3482        assert!(
3483            matches!(err, LimitsError::NonAsciiWhitespaceInByteSize { ref value, ch, codepoint } if value == s && ch == '\u{2028}' && codepoint == 0x2028),
3484            "got {err:?}"
3485        );
3486    }
3487
3488    #[test]
3489    fn parse_byte_size_rejects_trailing_ideographic_space() {
3490        // IDEOGRAPHIC SPACE (`\u{3000}`) — the CJK-typography paste
3491        // footgun (canonical U+3000 is the full-width space that
3492        // Japanese / Chinese IMEs emit when input is auto-widened). Pins
3493        // the arm at the top edge of the `char::is_whitespace` set.
3494        let s = "64MiB\u{3000}";
3495        let err = parse_byte_size(s).unwrap_err();
3496        assert!(
3497            matches!(err, LimitsError::NonAsciiWhitespaceInByteSize { ref value, ch, codepoint } if value == s && ch == '\u{3000}' && codepoint == 0x3000),
3498            "got {err:?}"
3499        );
3500    }
3501
3502    #[test]
3503    fn parse_byte_size_accepts_ascii_only_canonical_forms_after_unicode_arm() {
3504        // Positive-control pin: every ASCII-only canonical form the
3505        // renderer emits stays accepted through the new arm — the
3506        // lifted predicate is a strict no-op on ASCII input.
3507        assert_eq!(parse_byte_size("64MiB").unwrap(), 64 * 1024 * 1024);
3508        assert_eq!(parse_byte_size("1GiB").unwrap(), 1024 * 1024 * 1024);
3509        assert_eq!(parse_byte_size("512KiB").unwrap(), 512 * 1024);
3510        assert_eq!(parse_byte_size("1024").unwrap(), 1024);
3511    }
3512
3513    // ── canonical-form: integer-magnitude duration codec gate ─────────────
3514    //
3515    // Direct successor to the `parse_byte_size` integer-magnitude gate on
3516    // the peer `:limits :memory` codec — every magnitude `render_duration`
3517    // emits is a non-negative integer (no decimal point, no leading sign,
3518    // no scientific notation). The parser's accepted set must match for
3519    // parse → render → parse to round-trip without canonical-form drift.
3520    // Pins every canonical-drift shape — fractional (`"1.5s"`),
3521    // decimal-shaped-integer (`"1.0s"`), half-unit (`"0.5m"`),
3522    // leading-`+` (`"+30s"`), leading-`-` (`"-30s"`) — plus the
3523    // complement-side pin (integer happy paths), the round-trip
3524    // convergence property, the BadDurationMagnitude-precedence pin
3525    // (genuinely unparseable inputs keep their narrower diagnostic), the
3526    // overflow-surface pin (u64-overflow on magnitude × unit surfaces at
3527    // parse time), and the serde-path pin (the gate fires at deserialize,
3528    // before any validate gate runs).
3529
3530    #[test]
3531    fn parse_duration_rejects_fractional_seconds() {
3532        // The fail-before-pass-after pin: `"1.5s"` parsed cleanly on
3533        // every pre-gate codebase (f64::parse accepts the decimal), the
3534        // codec produced 1500ms, and `render_duration(1500ms)` emitted
3535        // `"1500ms"` on the next serialize — silently drifting the
3536        // canonical form away from the author's intent. The new gate
3537        // surfaces the round-trip break at the parser layer with a
3538        // self-locating diagnostic.
3539        let err = parse_duration("1.5s").unwrap_err();
3540        assert!(
3541            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "1.5"),
3542            "got {err:?}"
3543        );
3544    }
3545
3546    #[test]
3547    fn parse_duration_rejects_decimal_shaped_integer() {
3548        // The canonical-drift case where the *value* is integer but the
3549        // *form* carries a redundant decimal point — `"1.0s"` parses to
3550        // 1s (integer), but the renderer emits `"1s"` on the next
3551        // serialize (no decimal point). The parse-shape gate fires here
3552        // too so the codec's accepted set is exactly the renderer's
3553        // emitted set.
3554        let err = parse_duration("1.0s").unwrap_err();
3555        assert!(
3556            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "1.0"),
3557            "got {err:?}"
3558        );
3559    }
3560
3561    #[test]
3562    fn parse_duration_rejects_half_minute() {
3563        // `"0.5m"` parses to 30s; the renderer emits `"30s"` on the
3564        // next serialize. Pin the round-trip drift on the explicitly-
3565        // fractional case sized to land on a smaller-unit boundary, so
3566        // the gate's coverage includes both the "doesn't land on a
3567        // boundary" (1.5s → 1500ms) and "lands on a smaller-unit
3568        // boundary" (0.5m → 30s) drift shapes — the same two-shape
3569        // pattern the byte-size gate covers (1.5KiB → 1536, 0.5GiB →
3570        // 512MiB).
3571        let err = parse_duration("0.5m").unwrap_err();
3572        assert!(
3573            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "0.5"),
3574            "got {err:?}"
3575        );
3576    }
3577
3578    #[test]
3579    fn parse_duration_rejects_leading_plus() {
3580        // `"+30s"` parses through f64 as 30s; the renderer emits `"30s"`
3581        // on the next serialize. The leading `+` is not a renderer-
3582        // emitted shape, so it falls in the same canonical-drift class
3583        // as the fractional forms — surfacing under the same diagnostic
3584        // keeps the gate's coverage uniform across every non-canonical-
3585        // but-numeric input shape the parser would otherwise accept.
3586        let err = parse_duration("+30s").unwrap_err();
3587        assert!(
3588            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "+30"),
3589            "got {err:?}"
3590        );
3591    }
3592
3593    #[test]
3594    fn parse_duration_rejects_negative_seconds_via_integer_gate() {
3595        // The negative-magnitude class — pre-gate the parser routed
3596        // negatives through the `num < 0.0` check to `BadDurationMagnitude`;
3597        // the new digit-only gate fires earlier and routes the same
3598        // input to `NonIntegerDurationMagnitude` (negatives are not
3599        // digit-only). Pin the new diagnostic so a future relaxation
3600        // that re-routes negatives back to the old arm surfaces here.
3601        let err = parse_duration("-30s").unwrap_err();
3602        assert!(
3603            matches!(err, LimitsError::NonIntegerDurationMagnitude { ref value } if value == "-30"),
3604            "got {err:?}"
3605        );
3606    }
3607
3608    #[test]
3609    fn parse_duration_continues_to_accept_integer_magnitudes() {
3610        // The complement-side pin: every canonical integer-magnitude
3611        // form the renderer emits must continue to parse to the same
3612        // value the renderer produced. Sweep the canonical authoring
3613        // shapes (ms, bare-s, s, m, h, and the bare-integer "0" zero-
3614        // shape) so a future tightening of the parser surfaces here as
3615        // a test failure rather than a silent regression.
3616        assert_eq!(parse_duration("0s").unwrap(), Duration::ZERO);
3617        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
3618        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
3619        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
3620        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
3621        assert_eq!(parse_duration("3600").unwrap(), Duration::from_secs(3600));
3622    }
3623
3624    #[test]
3625    fn parse_duration_round_trips_through_render_for_every_canonical_form() {
3626        // The structural property the gate makes load-bearing: every
3627        // value the parser accepts round-trips through the canonical
3628        // [`crate::supervisor::duration_codec::render`] primitive to a
3629        // string the parser also accepts — and to the *same* value.
3630        // Sweep the values the renderer emits canonically (ms / s / m /
3631        // h boundaries plus a non-aligned millisecond) so a future
3632        // codec change that breaks round-trip convergence surfaces here.
3633        for d in [
3634            Duration::from_millis(1),
3635            Duration::from_millis(500),
3636            Duration::from_millis(1500),
3637            Duration::from_secs(1),
3638            Duration::from_secs(30),
3639            Duration::from_secs(60),
3640            Duration::from_secs(120),
3641            Duration::from_secs(3600),
3642        ] {
3643            let rendered = crate::supervisor::duration_codec::render(d);
3644            let reparsed = parse_duration(&rendered)
3645                .unwrap_or_else(|e| panic!("render({d:?}) = {rendered:?} must reparse, got {e:?}"));
3646            assert_eq!(
3647                reparsed, d,
3648                "round-trip drift on {d:?}: rendered={rendered:?}, reparsed={reparsed:?}",
3649            );
3650        }
3651    }
3652
3653    #[test]
3654    fn parse_duration_keeps_bad_magnitude_for_unparseable_input() {
3655        // The precedence pin: the new `NonIntegerDurationMagnitude` arm
3656        // distinguishes *non-canonical-but-numeric* (`"1.5"`, `"+30"`,
3657        // `"-30"`) from *genuinely-unparseable* (`"abc"`, `"--1"`) so
3658        // the existing `BadDurationMagnitude` diagnostic's wording
3659        // remains load-bearing for the latter class — the gate is
3660        // additive, not replacing.
3661        let err = parse_duration("abcs").unwrap_err();
3662        assert!(
3663            matches!(err, LimitsError::BadDurationMagnitude(_)),
3664            "got {err:?}"
3665        );
3666        let err = parse_duration("--1s").unwrap_err();
3667        assert!(
3668            matches!(err, LimitsError::BadDurationMagnitude(_)),
3669            "got {err:?}"
3670        );
3671    }
3672
3673    #[test]
3674    fn parse_duration_overflow_surfaces_as_bad_magnitude() {
3675        // `u64::MAX h` overflows the seconds computation (magnitude ×
3676        // 3600); the parser surfaces the overflow as a
3677        // `BadDurationMagnitude` with an overflow-shaped wording so the
3678        // diagnostic names the offending magnitude × unit pair at parse
3679        // time. Matches `parse_byte_size`'s overflow-surface arm
3680        // structurally.
3681        let err = parse_duration("18446744073709551615h").unwrap_err();
3682        let LimitsError::BadDurationMagnitude(reason) = err else {
3683            panic!("expected BadDurationMagnitude(overflow), got other variant");
3684        };
3685        assert!(
3686            reason.contains("overflow"),
3687            "overflow diagnostic must mention overflow (got {reason:?})"
3688        );
3689    }
3690
3691    // ── canonical-form: leading-zero duration codec gate ─────────────────
3692    //
3693    // Direct successor to the `supervisor::duration_codec` leading-zero
3694    // arm (9178904) and the `rate_limit_codec` leading-zero arm (4f46830)
3695    // — closes the leading-zero canonical-form-drift class on the
3696    // `:limits :wall-clock` codec. Every magnitude `render_duration`
3697    // emits is a non-negative integer with no leading-zero padding; the
3698    // parser's accepted set must match for parse → render → parse to
3699    // round-trip without canonical-form drift. The single-byte `"0"`
3700    // round-trips losslessly (`render_duration(Duration::ZERO)` emits
3701    // `"0s"`) and the downstream [`LimitsError::WallClockZero`] gate
3702    // refuses zero-magnitude authoring at the typed-validate layer above
3703    // — the codec-layer / typed-validate-layer partition is what keeps
3704    // the diagnostic partitioning stable.
3705
3706    #[test]
3707    fn parse_duration_rejects_leading_zero_magnitude() {
3708        // The fail-before-pass-after pin: `"030s"` parsed cleanly on
3709        // every pre-gate codebase (`u64::from_str` accepts the leading
3710        // zero), the codec produced 30s, and `render_duration(30s)`
3711        // emitted `"30s"` on the next serialize — silently dropping
3712        // the leading zero and drifting the canonical form away from
3713        // the author's intent. The new gate surfaces the round-trip
3714        // break at the parser layer with a self-locating diagnostic.
3715        let err = parse_duration("030s").unwrap_err();
3716        assert!(
3717            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "030"),
3718            "got {err:?}"
3719        );
3720    }
3721
3722    #[test]
3723    fn parse_duration_rejects_multi_digit_zero_magnitude() {
3724        // `"00s"` is the degenerate leading-zero case — every byte is
3725        // `0`. `u64::from_str("00")` = 0, and the codec produces
3726        // `Duration::ZERO`; `render_duration(Duration::ZERO)` emits
3727        // `"0s"` on the next serialize — drift from `"00s"` to `"0s"`.
3728        // The leading-zero arm refuses the drift class at the codec
3729        // layer while leaving the canonical single-byte `"0s"` accepted.
3730        let err = parse_duration("00s").unwrap_err();
3731        assert!(
3732            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "00"),
3733            "got {err:?}"
3734        );
3735    }
3736
3737    #[test]
3738    fn parse_duration_rejects_leading_zero_in_hour_window() {
3739        // `"01h"` parses to 1h; the renderer emits `"1h"` on the next
3740        // serialize. The leading-zero class is a property of the
3741        // magnitude, not the unit — pin a per-hour magnitude alongside
3742        // the per-second / per-ms pins so the gate's coverage is
3743        // structural across every canonical unit suffix the codec
3744        // accepts. Mirrors the `_per_hour_window` pin the
3745        // `supervisor::duration_codec` and `rate_limit_codec` leading-
3746        // zero arms carry on the peer codecs.
3747        let err = parse_duration("01h").unwrap_err();
3748        assert!(
3749            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "01"),
3750            "got {err:?}"
3751        );
3752    }
3753
3754    #[test]
3755    fn parse_duration_rejects_leading_zero_bare_integer_as_seconds() {
3756        // The bare-integer-as-seconds shorthand (`"30"` → 30s, no unit
3757        // suffix because the parser routes the empty `unit` slot to
3758        // `Duration::from_secs`) inherits the leading-zero arm: `"030"`
3759        // parses losslessly to 30s but `render_duration(30s)` emits
3760        // `"30s"` on the next serialize. Pin the bare-integer path so a
3761        // future relaxation that special-cases the unitless shorthand
3762        // surfaces here as a test failure.
3763        let err = parse_duration("030").unwrap_err();
3764        assert!(
3765            matches!(err, LimitsError::LeadingZeroDurationMagnitude { ref value } if value == "030"),
3766            "got {err:?}"
3767        );
3768    }
3769
3770    #[test]
3771    fn parse_duration_accepts_single_zero_magnitude_at_codec_layer() {
3772        // The codec-layer / typed-validate-layer boundary pin: the
3773        // single-byte `"0"` magnitude round-trips losslessly through
3774        // `render_duration` (`render_duration(Duration::ZERO)` emits
3775        // `"0s"`), so it stays accepted at this codec layer across
3776        // every canonical unit suffix. The downstream
3777        // `LimitsError::WallClockZero` gate is what refuses
3778        // zero-magnitude authoring at the typed-validate layer above
3779        // — the partition keeps the canonical-form-drift diagnostic
3780        // (this arm) and the semantic-zero diagnostic (the validate
3781        // gate) disjoint.
3782        assert_eq!(parse_duration("0s").unwrap(), Duration::ZERO);
3783        assert_eq!(parse_duration("0ms").unwrap(), Duration::ZERO);
3784        assert_eq!(parse_duration("0m").unwrap(), Duration::ZERO);
3785        assert_eq!(parse_duration("0h").unwrap(), Duration::ZERO);
3786        assert_eq!(parse_duration("0").unwrap(), Duration::ZERO);
3787    }
3788
3789    #[test]
3790    fn parse_duration_accepts_canonical_magnitude_with_leading_one() {
3791        // The complement-side pin on the leading-zero arm: magnitudes
3792        // beginning with `1`..=`9` stay accepted across every canonical
3793        // unit suffix the codec accepts. Pin this so a future
3794        // tightening cannot drift into rejecting valid canonical
3795        // magnitudes — peer with the `_accepts_canonical_magnitude_with_leading_one`
3796        // pin the `supervisor::duration_codec` and `rate_limit_codec`
3797        // leading-zero arms carry.
3798        assert_eq!(parse_duration("1ms").unwrap(), Duration::from_millis(1));
3799        assert_eq!(parse_duration("1s").unwrap(), Duration::from_secs(1));
3800        assert_eq!(parse_duration("1m").unwrap(), Duration::from_secs(60));
3801        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
3802        assert_eq!(parse_duration("100ms").unwrap(), Duration::from_millis(100));
3803        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
3804    }
3805
3806    // ── canonical-form: whitespace-rejection duration codec gate ─────────
3807    //
3808    // Direct successor to the `supervisor::duration_codec` whitespace-
3809    // rejection arm (a7ae622) and the `rate_limit_codec` whitespace-
3810    // rejection arm (1ad7755) on the same canonical-form
3811    // render-determinism axis. The pre-gate top-level `s.trim()` at
3812    // parse entry and the per-part `num_part.trim()` / `unit.trim()`
3813    // calls silently ate leading / trailing / internal whitespace, so
3814    // every whitespace-carrying shape parsed to the same integer
3815    // magnitude and round-tripped through `render_duration` to a
3816    // *different* canonical string on next serialize — the same
3817    // canonical-form-drift class the leading-`+` / fractional /
3818    // leading-zero arms already close on this codec. `u8::is_ascii_whitespace`
3819    // covers the five WhatWG-conformant ASCII whitespace bytes
3820    // (space `0x20`, tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`).
3821
3822    #[test]
3823    fn parse_duration_rejects_leading_whitespace() {
3824        // The fail-before-pass-after pin: `" 30s"` — the canonical
3825        // paste-from-aligned-doc / paste-from-YAML-quoted-plain-scalar
3826        // footgun. Before this gate the top-level `s.trim()` at parse
3827        // entry silently ate the leading space and parsed the value to
3828        // `Duration::from_secs(30)`, which then round-tripped through
3829        // `render_duration` to `"30s"` (a *different* canonical string
3830        // on the next emit) — the exact canonical-form-drift class the
3831        // leading-`+` / leading-zero arms already close, extended to
3832        // the whitespace-byte class. Peer with the sibling
3833        // `supervisor::duration_codec` `parse_rejects_leading_whitespace`
3834        // arm (a7ae622) on the shared duration-codec trajectory.
3835        let err = parse_duration(" 30s").unwrap_err();
3836        assert!(
3837            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == " 30s" && byte == 0x20),
3838            "got {err:?}"
3839        );
3840        let msg = err.to_string();
3841        assert!(
3842            msg.contains("whitespace byte 0x20"),
3843            "diagnostic must surface the offending byte verbatim (got {msg:?})"
3844        );
3845        assert!(
3846            msg.contains("THEORY.md"),
3847            "diagnostic must cite the render-determinism contract (got {msg:?})"
3848        );
3849    }
3850
3851    #[test]
3852    fn parse_duration_rejects_trailing_whitespace() {
3853        // `"30s "` — the canonical shell-history / trailing-space paste
3854        // footgun. Before this gate the top-level `s.trim()` silently
3855        // ate the trailing space and parsed to `Duration::from_secs(30)`,
3856        // round-tripping to `"30s"` on the next emit — same canonical-
3857        // form drift as the leading-space sibling, closed on the same
3858        // whitespace-byte arm.
3859        let err = parse_duration("30s ").unwrap_err();
3860        assert!(
3861            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "30s " && byte == 0x20),
3862            "got {err:?}"
3863        );
3864    }
3865
3866    #[test]
3867    fn parse_duration_rejects_internal_whitespace_between_magnitude_and_unit() {
3868        // `"30 s"` — the canonical typographically-spaced author shape
3869        // (the same idiom every prose reference to a duration renders as,
3870        // mistakenly retained when the value is pasted into a codec-
3871        // shaped slot). Before this gate the per-part `num_part.trim()`
3872        // / `unit.trim()` calls silently ate the whitespace between the
3873        // magnitude and the unit and parsed the value to
3874        // `Duration::from_secs(30)`, round-tripping to `"30s"` — the
3875        // codec's *internal* whitespace-tolerance vector, orthogonal
3876        // to the leading / trailing surface but the same canonical-
3877        // form-drift class. Pins the arm as strictly stronger than the
3878        // pre-existing top-level `s.trim()` behavior: it fires on
3879        // whitespace anywhere in the value, not just at the string
3880        // boundary.
3881        let err = parse_duration("30 s").unwrap_err();
3882        assert!(
3883            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "30 s" && byte == 0x20),
3884            "got {err:?}"
3885        );
3886    }
3887
3888    #[test]
3889    fn parse_duration_rejects_tab_byte() {
3890        // `"\t30s"` — the canonical paste-from-indented-doc /
3891        // paste-from-YAML-block-scalar footgun where a tab byte leads
3892        // the magnitude. Pins that the gate covers tab (`0x09`) as well
3893        // as space (`0x20`) — both are `u8::is_ascii_whitespace` members
3894        // and both would be silently swallowed by `s.trim()` pre-gate.
3895        // The `is_ascii_whitespace` coverage extends beyond space alone
3896        // to the full ASCII-whitespace set (space `0x20`, tab `0x09`,
3897        // LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins the tab arm
3898        // as a representative of the non-space members.
3899        let err = parse_duration("\t30s").unwrap_err();
3900        assert!(
3901            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "\t30s" && byte == 0x09),
3902            "got {err:?}"
3903        );
3904    }
3905
3906    #[test]
3907    fn parse_duration_rejects_trailing_newline() {
3908        // `"30s\n"` — the canonical multi-line-paste footgun where a
3909        // trailing LF byte survives the paste. Pins the LF member
3910        // (`0x0A`) of the `is_ascii_whitespace` set as a peer to the
3911        // space and tab pins above — every non-space non-tab whitespace
3912        // byte the WhatWG ASCII-whitespace set covers is refused by
3913        // the same arm.
3914        let err = parse_duration("30s\n").unwrap_err();
3915        assert!(
3916            matches!(err, LimitsError::WhitespaceInDuration { ref value, byte } if value == "30s\n" && byte == 0x0a),
3917            "got {err:?}"
3918        );
3919    }
3920
3921    #[test]
3922    fn parse_duration_accepts_whitespace_free_canonical_forms() {
3923        // The complement-side pin: every canonical whitespace-free
3924        // authoring form the renderer emits stays accepted post-gate.
3925        // Sweep the canonical unit suffixes plus the bare-integer
3926        // shorthand so a future tightening of the whitespace arm that
3927        // over-fires on the accepted set surfaces here as a test
3928        // failure. Peer with the `parse_duration_continues_to_accept_integer_magnitudes`
3929        // pin the fractional / leading-`+` gate carries.
3930        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
3931        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
3932        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
3933        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
3934        assert_eq!(parse_duration("0s").unwrap(), Duration::ZERO);
3935        assert_eq!(parse_duration("3600").unwrap(), Duration::from_secs(3600));
3936    }
3937
3938    #[test]
3939    fn de_duration_rejects_whitespace_through_serde() {
3940        // The serde-path pin: a `:limits :wall-clock` carrying a
3941        // whitespace-byte-carrying value (`" 30s"`) must fail at
3942        // deserialize time, not silently round-trip the value through
3943        // the pre-existing top-level `s.trim()`. The gate fires at
3944        // deserialize, before any validate gate runs — peer with the
3945        // existing `de_duration_rejects_leading_zero_through_serde` /
3946        // `de_duration_rejects_fractional_value_through_serde` pins on
3947        // the same canonical-form-drift axis.
3948        let json = r#"{"wallClock":" 30s"}"#;
3949        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
3950        let msg = err.to_string();
3951        assert!(
3952            msg.contains("whitespace byte"),
3953            "serde diagnostic must surface the whitespace reason verbatim (got {msg:?})"
3954        );
3955        assert!(
3956            msg.contains("0x20"),
3957            "serde diagnostic must name the offending byte (got {msg:?})"
3958        );
3959
3960        // The whitespace-free complement — same author-side intent,
3961        // written in the canonical form the renderer would emit,
3962        // deserializes cleanly.
3963        let json = r#"{"wallClock":"30s"}"#;
3964        let l: LimitsSpec = serde_json::from_str(json).unwrap();
3965        assert_eq!(l.wall_clock, Some(Duration::from_secs(30)));
3966    }
3967
3968    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
3969    //
3970    // Successor to the `parse_duration` ASCII-whitespace arm (ebc3a75)
3971    // — closes the strictly-complementary class the byte-scan cannot
3972    // see, through the lifted
3973    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
3974
3975    #[test]
3976    fn parse_duration_rejects_leading_nbsp() {
3977        // NBSP prefix — paste-from-typography footgun. Byte-scan misses,
3978        // `str::trim` strips silently, drifting to `"30s"` on next
3979        // emit.
3980        let s = "\u{00A0}30s";
3981        let err = parse_duration(s).unwrap_err();
3982        assert!(
3983            matches!(err, LimitsError::NonAsciiWhitespaceInDuration { ref value, ch, codepoint } if value == s && ch == '\u{00A0}' && codepoint == 0x00A0),
3984            "got {err:?}"
3985        );
3986        let msg = err.to_string();
3987        assert!(
3988            msg.contains("U+00A0"),
3989            "diagnostic must name codepoint (got {msg:?})"
3990        );
3991    }
3992
3993    #[test]
3994    fn parse_duration_rejects_internal_em_space() {
3995        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
3996        // paste-from-typography footgun on the `<integer><unit>` shape.
3997        let s = "30\u{2003}s";
3998        let err = parse_duration(s).unwrap_err();
3999        assert!(
4000            matches!(err, LimitsError::NonAsciiWhitespaceInDuration { ref value, ch, codepoint } if value == s && ch == '\u{2003}' && codepoint == 0x2003),
4001            "got {err:?}"
4002        );
4003    }
4004
4005    #[test]
4006    fn parse_duration_accepts_ascii_only_canonical_forms_after_unicode_arm() {
4007        // Positive-control pin: every ASCII-only canonical form the
4008        // renderer emits stays accepted through the new arm.
4009        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
4010        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4011        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4012    }
4013
4014    #[test]
4015    fn de_duration_rejects_leading_zero_through_serde() {
4016        // The serde-path pin: a `:limits :wall-clock` carrying a
4017        // leading-zero magnitude (`"030s"`) must fail at deserialize
4018        // time, not silently round-trip the value through the parser.
4019        // The gate fires at deserialize, before any validate gate runs
4020        // — peer with the existing `de_duration_rejects_fractional_value_through_serde`
4021        // pin on the same canonical-form-drift axis.
4022        let json = r#"{"wallClock":"030s"}"#;
4023        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4024        let msg = err.to_string();
4025        assert!(
4026            msg.contains("leading zero"),
4027            "serde diagnostic must surface the leading-zero reason verbatim (got {msg:?})"
4028        );
4029
4030        let json = r#"{"wallClock":"30s"}"#;
4031        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4032        assert_eq!(l.wall_clock, Some(Duration::from_secs(30)));
4033    }
4034
4035    #[test]
4036    fn de_duration_rejects_fractional_value_through_serde() {
4037        // The serde-path pin: a `:limits :wall-clock` carrying a
4038        // fractional magnitude (`"1.5s"`) must fail at deserialize time,
4039        // not silently round-trip the value through the f64 parser. Pin
4040        // both the success-on-canonical path (the integer form
4041        // deserializes cleanly) and the failure-on-non-canonical path
4042        // (the fractional form is rejected by the codec before any
4043        // validate gate runs).
4044        let json = r#"{"wallClock":"1.5s"}"#;
4045        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4046        let msg = err.to_string();
4047        assert!(
4048            msg.contains("non-negative integer"),
4049            "serde diagnostic must surface the integer-magnitude reason verbatim \
4050             (got {msg:?})"
4051        );
4052
4053        // The integer-form complement — same author-side intent
4054        // (1.5s = 1500ms), written in the canonical form the renderer
4055        // would emit, deserializes cleanly.
4056        let json = r#"{"wallClock":"1500ms"}"#;
4057        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4058        assert_eq!(l.wall_clock, Some(Duration::from_millis(1500)));
4059    }
4060
4061    #[test]
4062    fn de_byte_size_rejects_fractional_value_through_serde() {
4063        // The serde-path pin: a `:limits :memory` carrying a fractional
4064        // magnitude (`"1.5KiB"`) must fail at deserialize time, not
4065        // silently round-trip the value through the f64 parser. Pin
4066        // both the success-on-canonical path (the integer form
4067        // deserializes cleanly) and the failure-on-non-canonical path
4068        // (the fractional form is rejected by the codec before any
4069        // validate gate runs).
4070        let json = r#"{"memory":"1.5KiB"}"#;
4071        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4072        let msg = err.to_string();
4073        assert!(
4074            msg.contains("non-negative integer"),
4075            "serde diagnostic must surface the integer-magnitude reason verbatim (got {msg:?})"
4076        );
4077
4078        // The integer-form complement — same author-side intent
4079        // (1.5KiB = 1536 bytes), written in the canonical form the
4080        // renderer would emit, deserializes cleanly.
4081        let json = r#"{"memory":"1536"}"#;
4082        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4083        assert_eq!(l.memory, Some(1536));
4084    }
4085
4086    // ── canonical-form: integer-magnitude millicores codec gate ───────────
4087    //
4088    // Direct successor to the `parse_byte_size` / `parse_duration` /
4089    // shared `supervisor::duration_codec` / `rate_limit_codec`
4090    // integer-magnitude gates on the four peer typed codecs in
4091    // caixa-core — closes the sixth (and last) typed-codec surface in
4092    // the crate. Every magnitude `render_millicores` emits is a
4093    // non-negative integer (`format!("{m}m")`) — no decimal point, no
4094    // leading sign, no scientific notation. The parser's accepted set
4095    // must match for parse → render → parse to round-trip without
4096    // canonical-form drift. Pins every canonical-drift shape —
4097    // leading-`+` (`"+500m"` / `"+2"`, the load-bearing class the
4098    // digit-only gate closes beyond `u32::from_str` strictness),
4099    // leading-`-` (`"-100m"`), fractional (`"1.5"`), decimal-shaped-
4100    // integer on both authoring paths (`"500.0m"` / `"2.0"`), the
4101    // bare-`m`-with-no-magnitude pin, the empty-string pin, the
4102    // garbage-precedence pin (genuinely unparseable inputs keep the
4103    // narrower `BadMillicores` diagnostic), the u32-overflow surface
4104    // pin on both the `m`-suffix and bare-core multiply paths, the
4105    // complement-side pin (every integer happy path the gate must
4106    // continue to accept), the round-trip convergence property, and
4107    // the serde-path pin (the gate fires at deserialize, before any
4108    // validate gate runs).
4109
4110    #[test]
4111    fn parse_millicores_rejects_fractional_magnitude() {
4112        // The fail-before-pass-after pin on the bare-core path:
4113        // `"1.5"` parsed cleanly on no pre-gate codebase (`u32::from_str`
4114        // rejects the decimal), but the diagnostic was value-laundered
4115        // (the bare `BadMillicores("1.5")` wording didn't name the
4116        // canonical-form remediation or the round-trip drift the next
4117        // emit would produce — `1.5 cores × 1000 = 1500 millicores` →
4118        // `"1500m"` on the renderer). The gate routes the same input to
4119        // `NonIntegerMillicoreMagnitude` with the canonical-form wording.
4120        let err = parse_millicores("1.5").unwrap_err();
4121        assert!(
4122            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "1.5"),
4123            "got {err:?}"
4124        );
4125    }
4126
4127    #[test]
4128    fn parse_millicores_rejects_decimal_shaped_integer_with_suffix() {
4129        // The canonical-drift case on the `m`-suffix path where the
4130        // *value* is integer but the *form* carries a redundant decimal
4131        // point — `"500.0m"` parses to 500 millicores (integer), but
4132        // the renderer emits `"500m"` on the next serialize (no decimal
4133        // point). The parse-shape gate fires here too so the codec's
4134        // accepted set is exactly the renderer's emitted set — same
4135        // shape as `parse_byte_size`'s `"1.0MiB"` case.
4136        let err = parse_millicores("500.0m").unwrap_err();
4137        assert!(
4138            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "500.0"),
4139            "got {err:?}"
4140        );
4141    }
4142
4143    #[test]
4144    fn parse_millicores_rejects_decimal_shaped_integer_bare_core() {
4145        // The decimal-shaped-integer pin on the bare-core path —
4146        // `"2.0"` would be 2000 millicores (the canonical `"2000m"`),
4147        // but the redundant decimal point is not a renderer-emitted
4148        // shape. Surfaces under the same diagnostic as the `m`-suffix
4149        // path so the gate's coverage is uniform across both authoring
4150        // paths.
4151        let err = parse_millicores("2.0").unwrap_err();
4152        assert!(
4153            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "2.0"),
4154            "got {err:?}"
4155        );
4156    }
4157
4158    #[test]
4159    fn parse_millicores_rejects_leading_plus_sign_with_suffix() {
4160        // The load-bearing class the digit-only gate closes beyond
4161        // `u32::from_str`'s strictness: current Rust `u32::from_str`
4162        // permissively accepts `"+500"` → 500, so `"+500m"` parsed
4163        // cleanly through the pre-gate codec to `RateLimit`-shaped
4164        // 500 millicores and serde silently round-tripped to `"500m"`
4165        // on the next emit — a *different* canonical string. Same
4166        // shape as `parse_byte_size`'s `"+1024"` (875 commit) and
4167        // `parse_duration`'s `"+30s"` (1027 commit) cases on the peer
4168        // codecs.
4169        let err = parse_millicores("+500m").unwrap_err();
4170        assert!(
4171            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "+500"),
4172            "got {err:?}"
4173        );
4174    }
4175
4176    #[test]
4177    fn parse_millicores_rejects_leading_plus_sign_bare_core() {
4178        // The leading-`+` pin on the bare-core path — `"+2"` parsed
4179        // through `u32::from_str` as 2 → 2000 millicores → `"2000m"`
4180        // on the renderer; canonical-drift. The digit-only gate routes
4181        // the same input to `NonIntegerMillicoreMagnitude`, peer with
4182        // the `m`-suffix path.
4183        let err = parse_millicores("+2").unwrap_err();
4184        assert!(
4185            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "+2"),
4186            "got {err:?}"
4187        );
4188    }
4189
4190    #[test]
4191    fn parse_millicores_rejects_leading_minus_sign() {
4192        // The negative-magnitude class — pre-gate `u32::from_str`
4193        // rejected negatives but the diagnostic collapsed onto the
4194        // opaque `BadMillicores("-100m")` wording. The digit-only gate
4195        // fires earlier and routes the same input to
4196        // `NonIntegerMillicoreMagnitude` (negatives are not digit-only,
4197        // and `i64::from_str` accepts the leading sign so the numeric
4198        // arm matches). Pin the new diagnostic so a future relaxation
4199        // that re-routes negatives back to the old arm surfaces here.
4200        let err = parse_millicores("-100m").unwrap_err();
4201        assert!(
4202            matches!(err, LimitsError::NonIntegerMillicoreMagnitude { ref value } if value == "-100"),
4203            "got {err:?}"
4204        );
4205    }
4206
4207    #[test]
4208    fn parse_millicores_rejects_empty_string() {
4209        // The empty-input pin — `""` is not a magnitude at all. Pre-
4210        // gate this fell through to `s.parse::<u32>()` and surfaced as
4211        // a generic parse failure with the same `BadMillicores("")`
4212        // wording; the explicit empty-check at the top of the codec
4213        // surfaces the same diagnostic earlier and makes the empty-
4214        // input class structurally distinct from the digit-only /
4215        // numeric / garbage arms below.
4216        let err = parse_millicores("").unwrap_err();
4217        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4218    }
4219
4220    #[test]
4221    fn parse_millicores_rejects_bare_unit_with_no_magnitude() {
4222        // The bare-`m`-with-no-magnitude pin — `"m"` strips to `""`,
4223        // which is not a magnitude at all. The canonical millicores
4224        // authoring form requires a magnitude in front of the unit
4225        // (`"500m"`, not `"m"`). Surface as `BadMillicores` so the
4226        // narrower-arm wording stays load-bearing for this class.
4227        let err = parse_millicores("m").unwrap_err();
4228        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4229    }
4230
4231    #[test]
4232    fn parse_millicores_garbage_still_falls_through_to_bad_millicores() {
4233        // The precedence pin: the new `NonIntegerMillicoreMagnitude`
4234        // arm distinguishes *non-canonical-but-numeric* (`"1.5"`,
4235        // `"+500m"`, `"-100m"`, `"500.0m"`) from *genuinely-
4236        // unparseable* (`"abc"`, `"--1m"`, `"foo"`) so the existing
4237        // `BadMillicores` diagnostic's wording remains load-bearing
4238        // for the latter class — the gate is additive, not replacing.
4239        // Pin both arms so a future relaxation that collapses them
4240        // surfaces here.
4241        let err = parse_millicores("abc").unwrap_err();
4242        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4243        let err = parse_millicores("--1m").unwrap_err();
4244        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4245        let err = parse_millicores("foo").unwrap_err();
4246        assert!(matches!(err, LimitsError::BadMillicores(_)), "got {err:?}");
4247    }
4248
4249    #[test]
4250    fn parse_millicores_u32_overflow_with_suffix_surfaces_as_overflow() {
4251        // The u32-overflow surface pin on the `m`-suffix path: a
4252        // magnitude exceeding `u32::MAX` (4294967296 = u32::MAX + 1)
4253        // surfaces as `BadMillicores` with an overflow-shaped wording
4254        // naming the offending magnitude verbatim. The digit-only
4255        // guard guarantees every byte is `[0-9]`, so overflow is the
4256        // only remaining `u32::from_str` failure mode — the overflow
4257        // arm is no longer in unreachable-by-prior-gate territory.
4258        // Matches the overflow-arm shape on `parse_byte_size` /
4259        // `parse_duration` / `rate_limit_codec`.
4260        let err = parse_millicores("4294967296m").unwrap_err();
4261        let LimitsError::BadMillicores(reason) = err else {
4262            panic!("expected BadMillicores(overflow), got other variant");
4263        };
4264        assert!(
4265            reason.contains("overflow"),
4266            "overflow diagnostic must mention overflow (got {reason:?})"
4267        );
4268    }
4269
4270    #[test]
4271    fn parse_millicores_bare_core_overflow_surfaces_as_overflow() {
4272        // The u32-overflow surface pin on the bare-core path: a
4273        // magnitude that fits u32 on its own but overflows on the
4274        // `× 1000` conversion to millicores surfaces as
4275        // `BadMillicores` with an overflow-shaped wording. Pre-gate
4276        // the codec used `saturating_mul(1000)` which silently
4277        // saturated the result at `u32::MAX` — landing as the cap
4278        // value far from the author's intent and bypassing any
4279        // future validate-time upper-bound gate the `:cpu` axis
4280        // grows. The `checked_mul` rewrite surfaces the overflow at
4281        // parse time. (4294968 cores × 1000 = 4294968000 > u32::MAX
4282        // = 4294967295 — the smallest digit-string that overflows
4283        // u32 on the × 1000 multiply while fitting u32 on its own.)
4284        let err = parse_millicores("4294968").unwrap_err();
4285        let LimitsError::BadMillicores(reason) = err else {
4286            panic!("expected BadMillicores(× 1000 overflow), got other variant");
4287        };
4288        assert!(
4289            reason.contains("overflow"),
4290            "× 1000 overflow diagnostic must mention overflow (got {reason:?})"
4291        );
4292    }
4293
4294    #[test]
4295    fn parse_millicores_continues_to_accept_canonical_forms() {
4296        // The complement-side pin: every canonical integer-magnitude
4297        // form the renderer emits must continue to parse to the same
4298        // value the renderer produced. Sweep the canonical authoring
4299        // shapes on both paths (the `m`-suffix path: `"0m"`, `"500m"`,
4300        // `"2000m"`; the bare-core shorthand: `"0"`, `"2"`, `"4"`) so
4301        // a future tightening of the parser surfaces here as a test
4302        // failure rather than a silent regression. The `0` case is at
4303        // the codec layer only; `validate_rejects_zero_cpu` rejects
4304        // `Some(0)` one level up.
4305        assert_eq!(parse_millicores("0m").unwrap(), 0);
4306        assert_eq!(parse_millicores("500m").unwrap(), 500);
4307        assert_eq!(parse_millicores("1500m").unwrap(), 1500);
4308        assert_eq!(parse_millicores("2000m").unwrap(), 2000);
4309        assert_eq!(parse_millicores("0").unwrap(), 0);
4310        assert_eq!(parse_millicores("2").unwrap(), 2000);
4311        assert_eq!(parse_millicores("4").unwrap(), 4000);
4312    }
4313
4314    #[test]
4315    fn parse_millicores_round_trips_through_render_for_every_canonical_form() {
4316        // The structural property the gate makes load-bearing: every
4317        // value the parser accepts round-trips through
4318        // `render_millicores` to a string the parser also accepts —
4319        // and to the *same* value. Sweep the values the renderer emits
4320        // canonically (zero, sub-core, single-core boundary, multi-
4321        // core, and a non-1000-multiple millicore value) so a future
4322        // codec change that breaks round-trip convergence surfaces
4323        // here, not at a downstream renderer that double-emits a
4324        // typed slot.
4325        for m in [0u32, 1, 100, 500, 1000, 1500, 2000, 12345] {
4326            let rendered = render_millicores(m);
4327            let reparsed = parse_millicores(&rendered)
4328                .unwrap_or_else(|e| panic!("render({m}) = {rendered:?} must reparse, got {e:?}"));
4329            assert_eq!(
4330                reparsed, m,
4331                "round-trip drift on {m}: rendered={rendered:?}, reparsed={reparsed}",
4332            );
4333        }
4334    }
4335
4336    #[test]
4337    fn de_millicores_rejects_leading_plus_through_serde() {
4338        // The serde-path pin: a `:limits :cpu` carrying a leading-`+`
4339        // magnitude (`"+500m"`) must fail at deserialize time, not
4340        // silently round-trip the value through `u32::from_str`'s
4341        // permissive sign-acceptance. Pin both the success-on-canonical
4342        // path (the integer form deserializes cleanly) and the
4343        // failure-on-non-canonical path (the leading-`+` form is
4344        // rejected by the codec before any validate gate runs).
4345        let json = r#"{"cpu":"+500m"}"#;
4346        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4347        let msg = err.to_string();
4348        assert!(
4349            msg.contains("non-negative integer"),
4350            "serde diagnostic must surface the integer-magnitude reason verbatim \
4351             (got {msg:?})"
4352        );
4353
4354        // The integer-form complement — same author-side intent
4355        // (500 millicores), written in the canonical form the renderer
4356        // would emit, deserializes cleanly.
4357        let json = r#"{"cpu":"500m"}"#;
4358        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4359        assert_eq!(l.cpu, Some(500));
4360    }
4361
4362    // ── canonical-form: leading-zero millicores codec gate ────────────────
4363    //
4364    // Direct successor to the `parse_byte_size` / `parse_duration` /
4365    // `supervisor::duration_codec` / `rate_limit_codec` leading-zero
4366    // arms (cea9a78 / 39762d7 / 9178904 / 4f46830) — closes the sixth
4367    // (and last) typed numeric-codec surface in caixa-core on the
4368    // integer-magnitude leading-zero axis. Every magnitude
4369    // `render_millicores` emits is the leading-zero-stripped form
4370    // (`format!("{m}m")` — no leading-zero padding), so a digit-only-
4371    // but-leading-zero magnitude parses losslessly through `u32::from_str`
4372    // and serde silently round-trips the value to a *different*
4373    // canonical string on the next emit. Pins every canonical-drift
4374    // shape on the `m`-suffix and bare-core paths, the codec-vs-
4375    // typed-validate-layer boundary (the single-byte `"0"` stays in the
4376    // codec's accepted set; `CpuZero` refuses it at validate), the
4377    // complement-side pin (every canonical leading-`[1-9]` magnitude
4378    // continues to parse cleanly), and the serde-path pin.
4379
4380    #[test]
4381    fn parse_millicores_rejects_leading_zero_magnitude_with_suffix() {
4382        // The fail-before-pass-after pin on the `m`-suffix path:
4383        // `"0500m"` parsed cleanly on no pre-gate codebase
4384        // (`u32::from_str` accepts `"0500"` → 500), then `render_millicores`
4385        // emitted `"500m"` on the next serialize — canonical-form drift.
4386        // The leading-zero arm routes the same input to
4387        // `LeadingZeroMillicoreMagnitude` with the canonical-form
4388        // remediation wording. Peer with the `parse_byte_size` `"064MiB"`
4389        // case and the `parse_duration` `"030s"` case.
4390        let err = parse_millicores("0500m").unwrap_err();
4391        assert!(
4392            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "0500"),
4393            "got {err:?}"
4394        );
4395    }
4396
4397    #[test]
4398    fn parse_millicores_rejects_multi_digit_zero_magnitude_with_suffix() {
4399        // The multi-zero pin on the `m`-suffix path: `"00m"` parses to 0
4400        // millicores at the codec, but the renderer emits `"0m"` on the
4401        // next serialize — the single canonical zero form on this axis.
4402        // The leading-zero arm rejects multi-byte leading-zero shapes
4403        // even when the value is zero; the single-byte `"0m"` /
4404        // bare-`"0"` stays in the codec's accepted set per the boundary
4405        // pin below. Peer with the `parse_byte_size` `"00MiB"` case and
4406        // the `parse_duration` `"00s"` case.
4407        let err = parse_millicores("00m").unwrap_err();
4408        assert!(
4409            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "00"),
4410            "got {err:?}"
4411        );
4412    }
4413
4414    #[test]
4415    fn parse_millicores_rejects_leading_zero_bare_core() {
4416        // The leading-zero pin on the bare-core path: `"02"` parsed to
4417        // 2 cores → 2000 millicores at the codec, but `render_millicores`
4418        // emits `"2000m"` on the next serialize — canonical-form drift.
4419        // The bare-core shorthand carries the same leading-zero discipline
4420        // as the `m`-suffix path; both authoring paths converge to the
4421        // same gate. Peer with the `parse_byte_size` bare-integer
4422        // `"01024"` case.
4423        let err = parse_millicores("02").unwrap_err();
4424        assert!(
4425            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "02"),
4426            "got {err:?}"
4427        );
4428    }
4429
4430    #[test]
4431    fn parse_millicores_rejects_leading_zero_multi_digit_with_suffix() {
4432        // The multi-digit leading-zero pin on the `m`-suffix path:
4433        // `"01500m"` parses to 1500 millicores at the codec, but the
4434        // renderer emits `"1500m"` on the next serialize — canonical-form
4435        // drift on a non-zero magnitude. Sweeps a different magnitude
4436        // shape than the `"0500m"` case so a future tightening that
4437        // misses the multi-digit-leading-zero class surfaces here.
4438        let err = parse_millicores("01500m").unwrap_err();
4439        assert!(
4440            matches!(err, LimitsError::LeadingZeroMillicoreMagnitude { ref value } if value == "01500"),
4441            "got {err:?}"
4442        );
4443    }
4444
4445    #[test]
4446    fn parse_millicores_accepts_single_zero_magnitude_at_codec_layer() {
4447        // The codec-layer / typed-validate-layer boundary pin: the
4448        // single-byte magnitude `"0"` (bare) and `"0m"` (with suffix)
4449        // round-trip losslessly through `render_millicores` (which
4450        // emits `"0m"` for 0 millicores), so they stay in the codec's
4451        // accepted set. The downstream `CpuZero` gate refuses
4452        // semantic-zero authoring at the typed-validate layer above —
4453        // the diagnostic partitioning between canonical-form drift
4454        // (the leading-zero arm) and semantic-zero (the `CpuZero` gate)
4455        // remains stable. Same codec-layer / typed-validate-layer
4456        // partition the peer codecs preserve.
4457        assert_eq!(parse_millicores("0").unwrap(), 0);
4458        assert_eq!(parse_millicores("0m").unwrap(), 0);
4459    }
4460
4461    #[test]
4462    fn parse_millicores_accepts_canonical_magnitude_with_leading_one() {
4463        // The complement-side pin: every canonical leading-`[1-9]`
4464        // magnitude continues to parse cleanly through the leading-zero
4465        // arm, on both the `m`-suffix and bare-core paths. Sweep the
4466        // canonical values the renderer emits across the unit-multiplier
4467        // boundary (sub-core, single-core, multi-core) so a future
4468        // tightening cannot drift into rejecting valid canonical
4469        // magnitudes. Same complement-side discipline the peer
4470        // `parse_byte_size_accepts_canonical_magnitude_with_leading_one`
4471        // and `parse_duration_accepts_canonical_magnitude_with_leading_one`
4472        // pins enforce on the sibling codecs.
4473        assert_eq!(parse_millicores("1m").unwrap(), 1);
4474        assert_eq!(parse_millicores("500m").unwrap(), 500);
4475        assert_eq!(parse_millicores("1500m").unwrap(), 1500);
4476        assert_eq!(parse_millicores("9000m").unwrap(), 9000);
4477        assert_eq!(parse_millicores("1").unwrap(), 1000);
4478        assert_eq!(parse_millicores("2").unwrap(), 2000);
4479        assert_eq!(parse_millicores("9").unwrap(), 9000);
4480    }
4481
4482    #[test]
4483    fn de_millicores_rejects_leading_zero_through_serde() {
4484        // The serde-path pin: a `:limits :cpu` carrying a leading-zero
4485        // magnitude (`"0500m"`) must fail at deserialize time, not
4486        // silently round-trip the value through `u32::from_str`'s
4487        // leading-zero-permissive accepting. Pin both the success-on-
4488        // canonical path (the leading-zero-stripped form deserializes
4489        // cleanly) and the failure-on-non-canonical path (the leading-
4490        // zero form is rejected by the codec before any validate gate
4491        // runs). Peer with the
4492        // `de_byte_size_rejects_leading_zero_through_serde` and
4493        // `de_duration_rejects_leading_zero_through_serde` pins on the
4494        // sibling codecs.
4495        let json = r#"{"cpu":"0500m"}"#;
4496        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4497        let msg = err.to_string();
4498        assert!(
4499            msg.contains("leading zero"),
4500            "serde diagnostic must surface the leading-zero reason verbatim \
4501             (got {msg:?})"
4502        );
4503
4504        // The integer-form complement — same author-side intent
4505        // (500 millicores), written in the canonical form the renderer
4506        // would emit, deserializes cleanly.
4507        let json = r#"{"cpu":"500m"}"#;
4508        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4509        assert_eq!(l.cpu, Some(500));
4510    }
4511
4512    // ── canonical-form: whitespace-rejection millicores codec gate ────────
4513    //
4514    // Direct successor to the `parse_byte_size` (24a8ad4), `parse_duration`
4515    // (ebc3a75), `supervisor::duration_codec` (a7ae622), and
4516    // `rate_limit_codec` (1ad7755) whitespace-rejection arms — closes the
4517    // fifth (and last) typed-magnitude codec surface in caixa-core on the
4518    // ASCII-whitespace axis. The pre-gate top-level `s.trim()` at parse
4519    // entry and the per-part `magnitude.trim()` calls silently ate leading
4520    // / trailing / internal whitespace, so every whitespace-carrying shape
4521    // parsed to the same millicore value and round-tripped through
4522    // `render_millicores` to a *different* canonical string on next
4523    // serialize — the same canonical-form-drift class the leading-`+` /
4524    // fractional / leading-zero arms already close on this codec.
4525
4526    #[test]
4527    fn parse_millicores_rejects_leading_whitespace() {
4528        // `" 500m"` — the canonical paste-from-aligned-doc / YAML-quoted-
4529        // plain-scalar footgun. Before this gate the top-level `s.trim()`
4530        // at parse entry silently ate the leading space and parsed the
4531        // value to 500 millicores, round-tripping to `"500m"` on next
4532        // serialize.
4533        let err = parse_millicores(" 500m").unwrap_err();
4534        assert!(
4535            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == " 500m" && byte == 0x20),
4536            "got {err:?}"
4537        );
4538        let msg = err.to_string();
4539        assert!(
4540            msg.contains("whitespace byte 0x20"),
4541            "diagnostic must surface the offending byte verbatim (got {msg:?})"
4542        );
4543        assert!(
4544            msg.contains("THEORY.md"),
4545            "diagnostic must cite the render-determinism contract (got {msg:?})"
4546        );
4547    }
4548
4549    #[test]
4550    fn parse_millicores_rejects_trailing_whitespace() {
4551        // `"500m "` — the canonical shell-history trailing-space footgun.
4552        let err = parse_millicores("500m ").unwrap_err();
4553        assert!(
4554            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "500m " && byte == 0x20),
4555            "got {err:?}"
4556        );
4557    }
4558
4559    #[test]
4560    fn parse_millicores_rejects_internal_whitespace_between_magnitude_and_unit() {
4561        // `"500 m"` — the typographically-spaced author shape (the same
4562        // idiom every prose reference to millicores renders as). Before
4563        // this gate the per-part `magnitude.trim()` silently ate the
4564        // internal space and parsed the value to 500 millicores.
4565        let err = parse_millicores("500 m").unwrap_err();
4566        assert!(
4567            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "500 m" && byte == 0x20),
4568            "got {err:?}"
4569        );
4570    }
4571
4572    #[test]
4573    fn parse_millicores_rejects_tab_byte() {
4574        // `"\t500m"` — the paste-from-indented-doc / YAML-block-scalar tab
4575        // footgun. Pins the tab (`0x09`) arm alongside the space arm above.
4576        let err = parse_millicores("\t500m").unwrap_err();
4577        assert!(
4578            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "\t500m" && byte == 0x09),
4579            "got {err:?}"
4580        );
4581    }
4582
4583    #[test]
4584    fn parse_millicores_rejects_trailing_newline() {
4585        // `"500m\n"` — the multi-line-paste footgun where a trailing LF
4586        // byte survives the paste. Pins the LF member (`0x0A`) of the
4587        // `is_ascii_whitespace` set.
4588        let err = parse_millicores("500m\n").unwrap_err();
4589        assert!(
4590            matches!(err, LimitsError::WhitespaceInMillicores { ref value, byte } if value == "500m\n" && byte == 0x0a),
4591            "got {err:?}"
4592        );
4593    }
4594
4595    #[test]
4596    fn parse_millicores_accepts_whitespace_free_canonical_forms() {
4597        // The complement-side pin: every canonical whitespace-free
4598        // authoring form the renderer emits stays accepted post-gate.
4599        // Sweep the canonical `m`-suffix path plus the bare-core shorthand
4600        // so a future tightening of the whitespace arm that over-fires on
4601        // the accepted set surfaces here as a test failure.
4602        assert_eq!(parse_millicores("500m").unwrap(), 500);
4603        assert_eq!(parse_millicores("2000m").unwrap(), 2000);
4604        assert_eq!(parse_millicores("1m").unwrap(), 1);
4605        assert_eq!(parse_millicores("0m").unwrap(), 0);
4606        assert_eq!(parse_millicores("2").unwrap(), 2000);
4607        assert_eq!(parse_millicores("0").unwrap(), 0);
4608    }
4609
4610    #[test]
4611    fn de_millicores_rejects_whitespace_through_serde() {
4612        // The serde-path pin: a `:limits :cpu` carrying a whitespace-byte-
4613        // carrying value (`" 500m"`) must fail at deserialize time, not
4614        // silently round-trip the value through the pre-existing top-level
4615        // `s.trim()`. Peer with the
4616        // `de_byte_size_rejects_whitespace_through_serde` and
4617        // `de_duration_rejects_whitespace_through_serde` pins on the
4618        // sibling codecs.
4619        let json = r#"{"cpu":" 500m"}"#;
4620        let err = serde_json::from_str::<LimitsSpec>(json).unwrap_err();
4621        let msg = err.to_string();
4622        assert!(
4623            msg.contains("whitespace byte"),
4624            "serde diagnostic must surface the whitespace reason verbatim (got {msg:?})"
4625        );
4626        assert!(
4627            msg.contains("0x20"),
4628            "serde diagnostic must name the offending byte (got {msg:?})"
4629        );
4630
4631        // The whitespace-free complement — same author-side intent,
4632        // written in the canonical form the renderer would emit,
4633        // deserializes cleanly.
4634        let json = r#"{"cpu":"500m"}"#;
4635        let l: LimitsSpec = serde_json::from_str(json).unwrap();
4636        assert_eq!(l.cpu, Some(500));
4637    }
4638
4639    // ── canonical-form: non-ASCII Unicode `White_Space` millicores gate ───
4640    //
4641    // Direct successor to the ASCII-whitespace arm above — closes the
4642    // strictly-complementary class the byte-scan cannot see. `str::trim`
4643    // uses `char::is_whitespace` (Unicode `White_Space`, strictly wider
4644    // than the ASCII byte set); a leading / trailing / internal NBSP
4645    // (`\u{00A0}`) / LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4646    // survives the byte-scan but is silently stripped by the top-level
4647    // trim, drifting to canonical `"500m"` on round-trip. Pins the arm
4648    // through the lifted [`crate::render::find_non_ascii_whitespace_char`]
4649    // predicate — the same shared predicate 1b75b38 landed on the four
4650    // peer typed-magnitude codecs, extended here to the fifth.
4651
4652    #[test]
4653    fn parse_millicores_rejects_leading_nbsp() {
4654        // NBSP (`\u{00A0}` = UTF-8 `0xC2 0xA0`) — the paste-from-typography
4655        // / paste-from-word-processor footgun. Before this arm landed the
4656        // byte-scan missed it (neither `0xC2` nor `0xA0` is
4657        // `is_ascii_whitespace`) and `str::trim` at parse entry silently
4658        // stripped it, yielding the same 500 millicores as the whitespace-
4659        // free canonical form and drifting to `"500m"` on next serialize.
4660        let s = "\u{00A0}500m";
4661        let err = parse_millicores(s).unwrap_err();
4662        assert!(
4663            matches!(err, LimitsError::NonAsciiWhitespaceInMillicores { ref value, ch, codepoint } if value == s && ch == '\u{00A0}' && codepoint == 0x00A0),
4664            "got {err:?}"
4665        );
4666        let msg = err.to_string();
4667        assert!(
4668            msg.contains("U+00A0"),
4669            "diagnostic must surface the codepoint verbatim (got {msg:?})"
4670        );
4671        assert!(
4672            msg.contains("THEORY.md"),
4673            "diagnostic must cite the render-determinism contract (got {msg:?})"
4674        );
4675    }
4676
4677    #[test]
4678    fn parse_millicores_rejects_internal_em_space() {
4679        // EM-SPACE (`\u{2003}`) between magnitude and unit — pins the arm
4680        // on an internal-position non-NBSP Unicode `White_Space` member.
4681        let s = "500\u{2003}m";
4682        let err = parse_millicores(s).unwrap_err();
4683        assert!(
4684            matches!(err, LimitsError::NonAsciiWhitespaceInMillicores { ref value, ch, codepoint } if value == s && ch == '\u{2003}' && codepoint == 0x2003),
4685            "got {err:?}"
4686        );
4687    }
4688
4689    #[test]
4690    fn parse_millicores_rejects_trailing_line_separator() {
4691        // LINE SEPARATOR (`\u{2028}`) — the canonical paste-from-web-doc
4692        // footgun (many rendering engines insert `\u{2028}` at soft-wrap
4693        // boundaries in RTF/HTML → plain text conversion). Pins the arm on
4694        // a trailing-position Unicode `White_Space` member.
4695        let s = "500m\u{2028}";
4696        let err = parse_millicores(s).unwrap_err();
4697        assert!(
4698            matches!(err, LimitsError::NonAsciiWhitespaceInMillicores { ref value, ch, codepoint } if value == s && ch == '\u{2028}' && codepoint == 0x2028),
4699            "got {err:?}"
4700        );
4701    }
4702
4703    #[test]
4704    fn parse_millicores_accepts_ascii_only_canonical_forms_after_unicode_arm() {
4705        // Positive-control pin: every ASCII-only canonical form the
4706        // renderer emits stays accepted through the new arm — the lifted
4707        // predicate is a strict no-op on ASCII input.
4708        assert_eq!(parse_millicores("500m").unwrap(), 500);
4709        assert_eq!(parse_millicores("2000m").unwrap(), 2000);
4710        assert_eq!(parse_millicores("1m").unwrap(), 1);
4711        assert_eq!(parse_millicores("2").unwrap(), 2000);
4712    }
4713
4714    // ── canonical-form: integer-millisecond :wall-clock gate ──────────────
4715    //
4716    // The peer typed-`Duration` axes routed through
4717    // `supervisor::duration_codec` (`:politicas :timeout` a4ae535,
4718    // `:circuit-breaker :window` a4ae535) already gate on
4719    // `is_integer_millisecond_duration` because the codec's `render`
4720    // truncates to `as_millis()` and parses with integer-ms granularity;
4721    // this crate's in-module `render_duration` / `parse_duration` pair
4722    // carries the same `as_millis()`-truncation shape, so the same sub-
4723    // millisecond-residue footgun lived on this axis until this gate
4724    // landed. The tests below pin the fail-before-pass-after boundary,
4725    // the diagnostic shape, the cross-arm zero-then-canonical ordering
4726    // matching the `:politicas` peer, the integer-ms happy-path sweep,
4727    // and the codec round-trip property (every validated `wall_clock`
4728    // survives serialize → deserialize equality).
4729
4730    #[test]
4731    fn validate_rejects_sub_millisecond_wall_clock() {
4732        // The fail-before-pass-after pin: a programmatic
4733        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4734        // validate on every pre-gate codebase, then truncated to
4735        // `as_millis() == 1` on first serialize — `render_duration`
4736        // emits `"1ms"`, the codec parses it back to
4737        // `Duration::from_millis(1)` = 1_000_000 ns, the typed
4738        // `wall_clock` no longer matches its rendered form.
4739        let l = LimitsSpec {
4740            wall_clock: Some(Duration::from_micros(1500)),
4741            ..Default::default()
4742        };
4743        match l.validate().unwrap_err() {
4744            LimitsError::WallClockNotCanonical { wall_clock } => {
4745                assert_eq!(wall_clock, Duration::from_micros(1500));
4746            }
4747            other => panic!("expected WallClockNotCanonical, got {other:?}"),
4748        }
4749    }
4750
4751    #[test]
4752    fn validate_rejects_one_nanosecond_wall_clock() {
4753        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4754        // (so `WallClockZero` doesn't fire) but `as_millis() == 0`, so
4755        // `render_duration` emits the literal `"0s"` — the next serde
4756        // round-trip would parse back to `Duration::ZERO`, which the
4757        // `WallClockZero` arm then rejects on re-validate. The
4758        // canonical-form gate at this layer surfaces a self-locating
4759        // diagnostic naming the offending Duration verbatim rather
4760        // than a downstream `WallClockZero` whose remediation points
4761        // at omitting the slot.
4762        let l = LimitsSpec {
4763            wall_clock: Some(Duration::from_nanos(1)),
4764            ..Default::default()
4765        };
4766        match l.validate().unwrap_err() {
4767            LimitsError::WallClockNotCanonical { wall_clock } => {
4768                assert_eq!(wall_clock, Duration::from_nanos(1));
4769            }
4770            other => panic!("expected WallClockNotCanonical, got {other:?}"),
4771        }
4772    }
4773
4774    #[test]
4775    fn validate_rejects_nanosecond_past_canonical_boundary() {
4776        // The 1-ns-past-1ms boundary case: a `Duration` carrying
4777        // 1_000_001 ns is structurally past the integer-ms granularity
4778        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec
4779        // round-trip would truncate to `1ms` and the consumer would
4780        // observe a 1-ns drift on every emit. Same boundary the peer
4781        // `is_integer_millisecond_duration_predicate_tracks_codec` test
4782        // in aplicacao.rs pins for the `:politicas` axes.
4783        let w = Duration::from_nanos(1_000_001);
4784        let l = LimitsSpec {
4785            wall_clock: Some(w),
4786            ..Default::default()
4787        };
4788        assert_eq!(
4789            l.validate().unwrap_err(),
4790            LimitsError::WallClockNotCanonical { wall_clock: w }
4791        );
4792    }
4793
4794    #[test]
4795    fn validate_accepts_integer_millisecond_wall_clock_values() {
4796        // The positive-control sweep: every `Duration` the codec can
4797        // round-trip losslessly — the canonical `<integer>{ms,s,m,h}`
4798        // set the `render_duration` / `parse_duration` pair emits and
4799        // accepts — passes `validate` without surfacing the new
4800        // canonical-form arm. Mirrors
4801        // `accepts_policy_retries_typical_values` /
4802        // `accepts_circuit_breaker_max_failures_typical_values` on
4803        // sibling axes.
4804        for w in [
4805            Duration::from_millis(1),
4806            Duration::from_millis(500),
4807            Duration::from_millis(1500),
4808            Duration::from_secs(1),
4809            Duration::from_secs(30),
4810            Duration::from_secs(60),
4811            Duration::from_secs(120),
4812            Duration::from_secs(3600),
4813        ] {
4814            let l = LimitsSpec {
4815                wall_clock: Some(w),
4816                ..Default::default()
4817            };
4818            l.validate()
4819                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4820        }
4821    }
4822
4823    #[test]
4824    fn validate_wall_clock_zero_takes_precedence_over_canonical_gate() {
4825        // Cross-arm ordering pin: `Duration::ZERO` has
4826        // `subsec_nanos() == 0` and would otherwise pass the
4827        // canonical-form arm — the zero-floor arm must fire first so
4828        // the more self-locating `WallClockZero` diagnostic (with its
4829        // omit-axis remediation directly named) leads. Same posture
4830        // every peer zero-then-shape gate uses
4831        // (`PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4832        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4833        let l = LimitsSpec {
4834            wall_clock: Some(Duration::ZERO),
4835            ..Default::default()
4836        };
4837        assert_eq!(l.validate().unwrap_err(), LimitsError::WallClockZero);
4838    }
4839
4840    #[test]
4841    fn wall_clock_canonical_diagnostic_carries_offending_duration() {
4842        // Diagnostic-shape pin: the canonical-form arm names the
4843        // offending `Duration` verbatim so the author's grep lands on
4844        // the field's value, not a generic "duration not canonical"
4845        // message. Same shape every other typed-cap arm on this
4846        // surface carries (`MemoryExceedsWasm32Cap` carries the
4847        // offending byte count verbatim, `PolicyRetriesExceedsCap`
4848        // carries the offending retry count verbatim,
4849        // `PolicyBreakerMaxFailuresExceedsCap` carries the offending
4850        // u32 verbatim).
4851        let w = Duration::from_micros(500);
4852        let l = LimitsSpec {
4853            wall_clock: Some(w),
4854            ..Default::default()
4855        };
4856        let err = l.validate().unwrap_err();
4857        let msg = err.to_string();
4858        assert!(
4859            msg.contains("500"),
4860            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4861        );
4862    }
4863
4864    #[test]
4865    fn wall_clock_validated_value_round_trips_through_codec() {
4866        // The structural property the canonical-ms gate enforces:
4867        // every `LimitsSpec::wall_clock` past `LimitsSpec::validate`
4868        // round-trips losslessly through the in-module duration codec
4869        // (serialize → string → deserialize → equal value). Pin this
4870        // end-to-end so a future change to either side (the validate
4871        // gate's accepted granularity, the codec's parse/render unit
4872        // set) that breaks the alignment surfaces here. Peer of
4873        // `policy_timeout_validated_value_round_trips_through_codec` /
4874        // `circuit_breaker_window_validated_value_round_trips_through_codec`
4875        // on the sibling `:politicas` axes.
4876        for w in [
4877            Duration::from_millis(1),
4878            Duration::from_millis(1500),
4879            Duration::from_secs(30),
4880            Duration::from_secs(3600),
4881        ] {
4882            let l = LimitsSpec {
4883                wall_clock: Some(w),
4884                ..Default::default()
4885            };
4886            l.validate().unwrap();
4887            let json = serde_json::to_string(&l).unwrap();
4888            let back: LimitsSpec = serde_json::from_str(&json).unwrap();
4889            assert_eq!(
4890                back.wall_clock, l.wall_clock,
4891                "every validated :wall-clock must round-trip losslessly through the codec"
4892            );
4893        }
4894    }
4895
4896    // ── value-shape: :wall-clock upper bound — 1h ceiling ──────────────────
4897    //
4898    // The third typed-`Duration` axis brought to the uniform top edge
4899    // `LIMITS_WALL_CLOCK_MAX` = 1h established by the prior cap lifts
4900    // on `:politicas :timeout` (POLICY_TIMEOUT_MAX) and
4901    // `:politicas :circuit-breaker :window` (POLICY_BREAKER_WINDOW_MAX).
4902    // Mirrors the test discipline those peers carry: the
4903    // fail-before-pass-after pin, the 1ms-boundary pin, the
4904    // far-above-cap sweep (24h / 7d / ~11.5d — the values a
4905    // `(:wall-clock "24h")` typo or copy-paste typically lands), the
4906    // inclusive-at-cap positive control, the production-band positive-
4907    // control sweep, the cross-arm zero-then-cap and
4908    // canonical-then-cap ordering pins, the diagnostic-shape pin
4909    // carrying the offending `Duration` verbatim, and the cap-value
4910    // literal-identity + codec-round-trip pins anchoring the constant
4911    // to the codec's largest emitted unit and to its peer constants.
4912
4913    #[test]
4914    fn validate_rejects_wall_clock_above_cap() {
4915        // The fail-before-pass-after pin: 3601s = 1h + 1s is
4916        // structurally one canonical-tick past the
4917        // [`LIMITS_WALL_CLOCK_MAX`] ceiling (1h = 3600s) — an
4918        // integer-millisecond magnitude the canonical-form arm above
4919        // accepts cleanly, that the in-module duration codec
4920        // round-trips losslessly as `"3601s"`, and that silently
4921        // passed validate on every pre-gate codebase because the typed
4922        // slot's only checks were the zero-floor and canonical-form
4923        // arms. The wasm-engine consuming the value (the M2.5
4924        // `wasm-engine`'s epoch-deadline cancellation hook, the future
4925        // caixa-helm `pleme-computeunit` chart's `:limits` value
4926        // mapping) reaches for a `Duration` so long no realistic
4927        // synchronous wasm call hits it, far from the source
4928        // caixa.lisp.
4929        let w = LIMITS_WALL_CLOCK_MAX + Duration::from_secs(1);
4930        let l = LimitsSpec {
4931            wall_clock: Some(w),
4932            ..Default::default()
4933        };
4934        assert_eq!(
4935            l.validate().unwrap_err(),
4936            LimitsError::WallClockExceedsCap { wall_clock: w }
4937        );
4938    }
4939
4940    #[test]
4941    fn validate_rejects_wall_clock_one_millisecond_above_cap() {
4942        // Boundary case: exactly 1ms past the cap (the granularity the
4943        // canonical-form gate enforces). Catches a future "strictly
4944        // less than" half-measure and pins the diagnostic to name the
4945        // offending `Duration` verbatim. Peer of
4946        // `rejects_policy_timeout_one_millisecond_above_cap` /
4947        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4948        // on the sibling typed-`Duration` axes' top edges.
4949        let w = LIMITS_WALL_CLOCK_MAX + Duration::from_millis(1);
4950        let l = LimitsSpec {
4951            wall_clock: Some(w),
4952            ..Default::default()
4953        };
4954        assert_eq!(
4955            l.validate().unwrap_err(),
4956            LimitsError::WallClockExceedsCap { wall_clock: w }
4957        );
4958    }
4959
4960    #[test]
4961    fn validate_rejects_wall_clock_far_above_cap() {
4962        // The "obvious authoring footgun" case: a `(:wall-clock "24h")`
4963        // or `(:wall-clock "7d")` — values the canonical-form arm
4964        // accepts as integer-millisecond magnitudes, the codec
4965        // round-trips losslessly through serde, but the wasm-engine
4966        // cannot honor as a meaningful per-call deadline. Until this
4967        // gate landed validate accepted them. Pin the common
4968        // above-cap values (24h, 7d, ~11.5d) so a future relaxation
4969        // that drops the upper bound surfaces here.
4970        for w in [
4971            Duration::from_secs(86_400),    // 24h
4972            Duration::from_secs(604_800),   // 7d
4973            Duration::from_secs(1_000_000), // ~11.5 days
4974        ] {
4975            let l = LimitsSpec {
4976                wall_clock: Some(w),
4977                ..Default::default()
4978            };
4979            assert_eq!(
4980                l.validate().unwrap_err(),
4981                LimitsError::WallClockExceedsCap { wall_clock: w }
4982            );
4983        }
4984    }
4985
4986    #[test]
4987    fn validate_accepts_wall_clock_at_cap() {
4988        // The boundary value — exactly [`LIMITS_WALL_CLOCK_MAX`] (1h)
4989        // — must validate. The cap is inclusive on the top edge,
4990        // matching the [`crate::POLICY_TIMEOUT_MAX`] /
4991        // [`crate::POLICY_BREAKER_WINDOW_MAX`] /
4992        // [`LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the sibling
4993        // capped axes. Pin the boundary explicitly so a future
4994        // off-by-one tightening (`>= LIMITS_WALL_CLOCK_MAX` instead of
4995        // `>`) surfaces here as a test failure rather than a silent
4996        // contract narrowing.
4997        let l = LimitsSpec {
4998            wall_clock: Some(LIMITS_WALL_CLOCK_MAX),
4999            ..Default::default()
5000        };
5001        l.validate()
5002            .expect("wall_clock == LIMITS_WALL_CLOCK_MAX must validate");
5003    }
5004
5005    #[test]
5006    fn validate_accepts_wall_clock_typical_values() {
5007        // The documented per-request production-playbook band positive-
5008        // control sweep — every value Envoy / Istio / Linkerd / AWS
5009        // App Mesh / Kubernetes ingress-nginx recommend
5010        // (1ms..=3600s) must pass, plus a sweep through the
5011        // long-running-workflow band (5m, 15m, 30m, 1h) the cap
5012        // accepts. Mirrors `accepts_policy_timeout_typical_values` on
5013        // the sibling `:politicas :timeout` axis.
5014        for w in [
5015            Duration::from_millis(1),
5016            Duration::from_millis(500),
5017            Duration::from_secs(1),
5018            Duration::from_secs(10),
5019            Duration::from_secs(15), // Envoy default
5020            Duration::from_secs(30),
5021            Duration::from_secs(60),  // AWS App Mesh typical
5022            Duration::from_secs(300), // 5m
5023            Duration::from_secs(900), // 15m
5024            Duration::from_secs(1800),
5025            Duration::from_secs(3600), // exactly 1h, the cap
5026        ] {
5027            let l = LimitsSpec {
5028                wall_clock: Some(w),
5029                ..Default::default()
5030            };
5031            l.validate()
5032                .unwrap_or_else(|e| panic!("wall_clock={w:?} must validate; got {e:?}"));
5033        }
5034    }
5035
5036    #[test]
5037    fn wall_clock_zero_takes_precedence_over_cap() {
5038        // The cross-arm ordering pin: `Duration::ZERO` is structurally
5039        // outside both `>= 1ms` (zero-floor) and `<= LIMITS_WALL_CLOCK_MAX`
5040        // (cap), but the zero-floor diagnostic is the more
5041        // self-locating one (it directly names the omit-axis
5042        // remediation), so the validate gate must fire on zero first.
5043        // Same shape every other zero-then-shape ordering on this
5044        // surface uses (`MemoryZero` then `MemoryExceedsWasm32Cap`,
5045        // `PolicyTimeoutZero` then `PolicyTimeoutExceedsCap`).
5046        let l = LimitsSpec {
5047            wall_clock: Some(Duration::ZERO),
5048            ..Default::default()
5049        };
5050        assert_eq!(
5051            l.validate().unwrap_err(),
5052            LimitsError::WallClockZero,
5053            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5054        );
5055    }
5056
5057    #[test]
5058    fn wall_clock_canonical_takes_precedence_over_cap() {
5059        // The cross-arm ordering pin: a `Duration` that is *both*
5060        // sub-millisecond (non-canonical-form) and structurally above
5061        // the cap surfaces the canonical-form diagnostic first,
5062        // because the round-trip-shape break is the more fundamental
5063        // issue (the value can't even round-trip through the codec, so
5064        // the cap diagnostic naming `1ms..=1h` would be misleading —
5065        // there's no integer-ms form of the offending value). Pin the
5066        // order so a future refactor that reorders the arms surfaces
5067        // here as a test failure rather than a silent diagnostic
5068        // regression. Peer of
5069        // `policy_timeout_canonical_takes_precedence_over_cap`.
5070        let w = LIMITS_WALL_CLOCK_MAX + Duration::from_nanos(1);
5071        let l = LimitsSpec {
5072            wall_clock: Some(w),
5073            ..Default::default()
5074        };
5075        assert_eq!(
5076            l.validate().unwrap_err(),
5077            LimitsError::WallClockNotCanonical { wall_clock: w },
5078            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5079        );
5080    }
5081
5082    #[test]
5083    fn wall_clock_cap_diagnostic_carries_offending_value() {
5084        // The diagnostic-shape pin: the offending `Duration` is
5085        // carried verbatim into the
5086        // [`LimitsError::WallClockExceedsCap`] variant so the surfaced
5087        // error message names the value the author wrote, not just
5088        // the cap. Same self-locating diagnostic shape every other
5089        // typed-cap arm on this surface carries
5090        // (`MemoryExceedsWasm32Cap` carries the offending byte count
5091        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5092        // `Duration` verbatim).
5093        let w = Duration::from_secs(7200); // 2h
5094        let l = LimitsSpec {
5095            wall_clock: Some(w),
5096            ..Default::default()
5097        };
5098        let err = l.validate().unwrap_err();
5099        assert!(
5100            matches!(err, LimitsError::WallClockExceedsCap { wall_clock } if wall_clock == w),
5101            "got {err:?}"
5102        );
5103        let msg = err.to_string();
5104        assert!(
5105            msg.contains("7200"),
5106            ":limits :wall-clock cap diagnostic must carry the offending value verbatim (got: {msg})"
5107        );
5108    }
5109
5110    #[test]
5111    fn wall_clock_cap_pins_canonical_value() {
5112        // The [`LIMITS_WALL_CLOCK_MAX`] constant pins the value at
5113        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5114        // shared duration codec emits as a clean canonical string
5115        // (`"<n>h"`). Pinning the literal value here surfaces a future
5116        // drift (a relaxation to 24h, a tightening to 5m) as a
5117        // deliberate test edit, not a silent contract narrowing.
5118        //
5119        // The three typed-`Duration` caps on the validation surface
5120        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5121        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker) share a
5122        // single uniform top edge at the codec's largest emitted unit
5123        // — a structural-property invariant the equality assertions
5124        // here enshrine, so a future drift on any of the three
5125        // surfaces as a deliberate test edit. Same shape every other
5126        // typed-cap value pin uses
5127        // (`policy_timeout_cap_pins_canonical_value`,
5128        // `circuit_breaker_window_cap_pins_canonical_value`).
5129        assert_eq!(LIMITS_WALL_CLOCK_MAX, Duration::from_secs(3600));
5130        assert_eq!(LIMITS_WALL_CLOCK_MAX.as_millis(), 3_600_000);
5131        assert_eq!(LIMITS_WALL_CLOCK_MAX, crate::POLICY_TIMEOUT_MAX);
5132        assert_eq!(LIMITS_WALL_CLOCK_MAX, crate::POLICY_BREAKER_WINDOW_MAX);
5133    }
5134
5135    #[test]
5136    fn wall_clock_cap_value_round_trips_through_codec() {
5137        // The codec round-trip property the cap arm preserves: the
5138        // [`LIMITS_WALL_CLOCK_MAX`] constant itself round-trips through
5139        // the in-module duration codec — every value at the cap
5140        // renders to a clean canonical string (`"1h"`) and parses back
5141        // to the same `Duration`. Pin this so a future drift between
5142        // the cap constant and the codec's largest emitted unit
5143        // surfaces here. Same shape every other typed boundary pin on
5144        // this surface uses
5145        // (`wasm32_memory_cap_matches_parsed_4_gib`,
5146        // `policy_timeout_cap_value_round_trips_through_codec`).
5147        let l = LimitsSpec {
5148            wall_clock: Some(LIMITS_WALL_CLOCK_MAX),
5149            ..Default::default()
5150        };
5151        let json = serde_json::to_string(&l).unwrap();
5152        assert!(
5153            json.contains("\"1h\""),
5154            "the LIMITS_WALL_CLOCK_MAX value must render to the canonical \"1h\" form (got: {json})"
5155        );
5156        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
5157        assert_eq!(back.wall_clock, Some(LIMITS_WALL_CLOCK_MAX));
5158        l.validate()
5159            .expect("LIMITS_WALL_CLOCK_MAX itself must pass validate");
5160    }
5161
5162    // ── value-shape: :cpu upper bound — 128-core schedulability ceiling ─────
5163    //
5164    // The third `LimitsSpec` axis brought to a top-edge cap, peer to
5165    // the `:memory` wasm32 ceiling and the `:wall-clock` 1h ceiling.
5166    // Mirrors the test discipline those peers carry: the
5167    // fail-before-pass-after pin, the one-millicore-boundary pin, the
5168    // far-above-cap sweep, the inclusive-at-cap positive control, the
5169    // production-band positive-control sweep, the cross-arm zero-then-
5170    // cap ordering pin, the diagnostic-shape pin carrying the offending
5171    // value verbatim, and the cap-value literal-identity + codec
5172    // round-trip pins anchoring the constant.
5173
5174    #[test]
5175    fn validate_rejects_cpu_above_cap() {
5176        // The fail-before-pass-after pin: 128_001m = 128 cores + 1
5177        // millicore is structurally one canonical-tick past the
5178        // [`LIMITS_CPU_MILLICORES_MAX`] ceiling — a `u32` magnitude the
5179        // millicore codec round-trips losslessly as `"128001m"`, and
5180        // that silently passed validate on every pre-gate codebase
5181        // because the typed slot's only check was the zero-floor arm.
5182        // The Kubernetes scheduler consuming the value (via the
5183        // `pleme-computeunit` chart's `resources.requests.cpu`
5184        // projection) cannot bind the pod to any node, far from the
5185        // source caixa.lisp.
5186        let m = LIMITS_CPU_MILLICORES_MAX + 1;
5187        let l = LimitsSpec {
5188            cpu: Some(m),
5189            ..Default::default()
5190        };
5191        assert_eq!(
5192            l.validate().unwrap_err(),
5193            LimitsError::CpuExceedsCap { millicores: m }
5194        );
5195    }
5196
5197    #[test]
5198    fn validate_rejects_cpu_far_above_cap() {
5199        // The "obvious authoring footgun" case: a `(:cpu "1000000m")`
5200        // (1000 cores) or `(:cpu "4294967295m")` (≈ u32::MAX) — values
5201        // the millicore codec accepts cleanly, the codec round-trips
5202        // losslessly through serde, but the Kubernetes scheduler
5203        // cannot bind to any node. Until this gate landed validate
5204        // accepted them. Pin the common above-cap values (1000 cores,
5205        // 10_000 cores, u32::MAX) so a future relaxation that drops
5206        // the upper bound surfaces here. Peer of
5207        // `validate_rejects_memory_8_gib` /
5208        // `validate_rejects_wall_clock_far_above_cap`.
5209        for m in [1_000_000_u32, 10_000_000, u32::MAX] {
5210            let l = LimitsSpec {
5211                cpu: Some(m),
5212                ..Default::default()
5213            };
5214            assert_eq!(
5215                l.validate().unwrap_err(),
5216                LimitsError::CpuExceedsCap { millicores: m }
5217            );
5218        }
5219    }
5220
5221    #[test]
5222    fn validate_accepts_cpu_at_cap() {
5223        // The boundary value — exactly [`LIMITS_CPU_MILLICORES_MAX`]
5224        // (128 cores = 128_000m) — must validate. The cap is inclusive
5225        // on the top edge, matching the discipline on every sibling
5226        // capped axis ([`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5227        // [`LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
5228        // [`crate::POLICY_BREAKER_WINDOW_MAX`],
5229        // [`crate::POLICY_RATE_LIMIT_MAX`]). Pin the boundary
5230        // explicitly so a future off-by-one tightening
5231        // (`>= LIMITS_CPU_MILLICORES_MAX` instead of `>`) surfaces here
5232        // as a test failure rather than a silent contract narrowing.
5233        let l = LimitsSpec {
5234            cpu: Some(LIMITS_CPU_MILLICORES_MAX),
5235            ..Default::default()
5236        };
5237        l.validate()
5238            .expect("cpu == LIMITS_CPU_MILLICORES_MAX must validate");
5239    }
5240
5241    #[test]
5242    fn validate_accepts_cpu_typical_values() {
5243        // The documented production-playbook band positive-control
5244        // sweep — every value the canonical caixa Servico runs in
5245        // (100m..=2000m) must pass, plus a sweep through the larger
5246        // burstable / multi-component-host band (4000m, 8000m, 16000m,
5247        // 32000m, 64000m, 128000m) the cap accepts. Mirrors
5248        // `accepts_wall_clock_typical_values` on the sibling
5249        // `:wall-clock` axis.
5250        for m in [
5251            1_u32,   // smallest non-zero
5252            100,     // typical small worker
5253            500,     // canonical test default (peer to limits/flux/helm)
5254            1_000,   // 1 core, single-threaded wasm32 saturation
5255            2_000,   // 2 cores
5256            4_000,   // typical burstable
5257            8_000,   // upper realistic per-Servico band
5258            16_000,  // documented heavy-Servico ceiling
5259            32_000,  // wide-node multi-component-host
5260            64_000,  // half the cap
5261            128_000, // exactly at cap
5262        ] {
5263            let l = LimitsSpec {
5264                cpu: Some(m),
5265                ..Default::default()
5266            };
5267            l.validate()
5268                .unwrap_or_else(|e| panic!("cpu={m}m must validate; got {e:?}"));
5269        }
5270    }
5271
5272    #[test]
5273    fn cpu_zero_takes_precedence_over_cap() {
5274        // The cross-arm ordering pin: `Some(0)` is structurally outside
5275        // both `>= 1` (zero-floor) and `<= LIMITS_CPU_MILLICORES_MAX`
5276        // (cap), but the zero-floor diagnostic is the more
5277        // self-locating one (it directly names the omit-axis
5278        // remediation), so the validate gate must fire on zero first.
5279        // Same shape every other zero-then-cap ordering on this surface
5280        // uses (`MemoryZero` then `MemoryExceedsWasm32Cap`,
5281        // `WallClockZero` then `WallClockExceedsCap`).
5282        let l = LimitsSpec {
5283            cpu: Some(0),
5284            ..Default::default()
5285        };
5286        assert_eq!(
5287            l.validate().unwrap_err(),
5288            LimitsError::CpuZero,
5289            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
5290        );
5291    }
5292
5293    #[test]
5294    fn validate_rejects_cpu_cap_after_earlier_axes() {
5295        // Cross-axis ordering: when both an above-cap `:cpu` and an
5296        // earlier-axis violation are present, the earlier axis must
5297        // fire first. The validate sequence is :memory → :fuel →
5298        // :wall-clock → :cpu, so a paired memory-zero + cpu-above-cap
5299        // input surfaces `MemoryZero`, never the cpu-cap diagnostic.
5300        // Pins the canonical axis order so a future refactor that
5301        // reorders the arms surfaces here as a test failure rather
5302        // than a silent diagnostic regression. Peer of
5303        // `validate_rejects_first_zero_axis_deterministically` and
5304        // `validate_rejects_memory_cap_before_other_axes`.
5305        let l = LimitsSpec {
5306            memory: Some(0),
5307            fuel: None,
5308            wall_clock: None,
5309            cpu: Some(LIMITS_CPU_MILLICORES_MAX + 1),
5310        };
5311        assert_eq!(
5312            l.validate().unwrap_err(),
5313            LimitsError::MemoryZero,
5314            "earlier-axis violation must take precedence over later-axis cap violation"
5315        );
5316    }
5317
5318    #[test]
5319    fn cpu_cap_diagnostic_carries_offending_value() {
5320        // The diagnostic-shape pin: the offending millicore count is
5321        // carried verbatim into the [`LimitsError::CpuExceedsCap`]
5322        // variant so the surfaced error message names the value the
5323        // author wrote, not just the cap. Same self-locating
5324        // diagnostic shape every other typed-cap arm on this surface
5325        // carries (`MemoryExceedsWasm32Cap` carries the offending byte
5326        // count verbatim, `WallClockExceedsCap` carries the offending
5327        // `Duration` verbatim).
5328        let m = 256_000_u32; // 256 cores — double the cap
5329        let l = LimitsSpec {
5330            cpu: Some(m),
5331            ..Default::default()
5332        };
5333        let err = l.validate().unwrap_err();
5334        assert!(
5335            matches!(err, LimitsError::CpuExceedsCap { millicores } if millicores == m),
5336            "got {err:?}"
5337        );
5338        let msg = err.to_string();
5339        assert!(
5340            msg.contains("256000"),
5341            ":limits :cpu cap diagnostic must carry the offending value verbatim (got: {msg})"
5342        );
5343    }
5344
5345    #[test]
5346    fn cpu_cap_pins_canonical_value() {
5347        // The [`LIMITS_CPU_MILLICORES_MAX`] constant pins the value at
5348        // exactly 128 cores (128_000 millicores) — the largest
5349        // commercially-common non-metal cloud Kubernetes node vCPU
5350        // count. Pinning the literal value here surfaces a future
5351        // drift (a relaxation to 256 cores, a tightening to 64 cores)
5352        // as a deliberate test edit, not a silent contract narrowing.
5353        // Same shape every other typed-cap value pin uses
5354        // (`wall_clock_cap_pins_canonical_value`,
5355        // `wasm32_memory_cap_matches_parsed_4_gib`).
5356        assert_eq!(LIMITS_CPU_MILLICORES_MAX, 128_000);
5357        assert_eq!(LIMITS_CPU_MILLICORES_MAX, 128 * 1000);
5358    }
5359
5360    #[test]
5361    fn cpu_cap_value_round_trips_through_codec() {
5362        // The codec round-trip property the cap arm preserves: the
5363        // [`LIMITS_CPU_MILLICORES_MAX`] constant itself round-trips
5364        // through the in-module millicore codec — the cap value
5365        // renders to a clean canonical string (`"128000m"`) and parses
5366        // back to the same `u32`. Pin this so a future drift between
5367        // the cap constant and the codec's accepted magnitude surfaces
5368        // here. Same shape every other typed boundary pin on this
5369        // surface uses (`wasm32_memory_cap_matches_parsed_4_gib`,
5370        // `wall_clock_cap_value_round_trips_through_codec`).
5371        let l = LimitsSpec {
5372            cpu: Some(LIMITS_CPU_MILLICORES_MAX),
5373            ..Default::default()
5374        };
5375        let json = serde_json::to_string(&l).unwrap();
5376        assert!(
5377            json.contains("\"128000m\""),
5378            "the LIMITS_CPU_MILLICORES_MAX value must render to the canonical \"128000m\" form (got: {json})"
5379        );
5380        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
5381        assert_eq!(back.cpu, Some(LIMITS_CPU_MILLICORES_MAX));
5382        l.validate()
5383            .expect("LIMITS_CPU_MILLICORES_MAX itself must pass validate");
5384    }
5385
5386    // ── value-shape: :fuel upper bound — 10^12 no-op-budget ceiling ────────
5387    //
5388    // The fourth and final `LimitsSpec` axis brought to a top-edge
5389    // cap, closing the open edge the 857dfcc CPU-cap commit body
5390    // explicitly named: "three of the four axes carry a top-and-bottom
5391    // edge gate; only `:fuel` remains with a zero-floor-only shape."
5392    // Mirrors the test discipline every sibling capped axis carries:
5393    // the fail-before-pass-after pin, the one-instruction-boundary
5394    // pin, the far-above-cap sweep, the inclusive-at-cap positive
5395    // control, the production-band positive-control sweep, the
5396    // cross-arm zero-then-cap ordering pin, the cross-axis
5397    // earlier-then-later precedence pin, the diagnostic-shape pin
5398    // carrying the offending value verbatim, and the cap-value
5399    // literal-identity + codec round-trip pins anchoring the
5400    // constant.
5401
5402    #[test]
5403    fn validate_rejects_fuel_above_cap() {
5404        // The fail-before-pass-after pin: `LIMITS_FUEL_MAX + 1` =
5405        // one wasm-instruction past the structural ceiling — a `u64`
5406        // magnitude the typed slot round-trips losslessly through
5407        // serde, and that silently passed validate on every pre-gate
5408        // codebase because the typed slot's only check was the
5409        // zero-floor arm. The wasm-engine consuming the value (via
5410        // `Store::set_fuel` projection in the M2.5 host runtime)
5411        // accepts the magnitude but the sibling `:wall-clock` 1h cap
5412        // fires before the fuel counter could ever drain — the typed
5413        // `:fuel` slot becomes a no-op budget far from the source
5414        // caixa.lisp.
5415        let f = LIMITS_FUEL_MAX + 1;
5416        let l = LimitsSpec {
5417            fuel: Some(f),
5418            ..Default::default()
5419        };
5420        assert_eq!(
5421            l.validate().unwrap_err(),
5422            LimitsError::FuelExceedsCap { fuel: f }
5423        );
5424    }
5425
5426    #[test]
5427    fn validate_rejects_fuel_far_above_cap() {
5428        // The "obvious authoring footgun" case: a `(:fuel
5429        // 1000000000000000)` (10^15 instructions), a paste-from-binary
5430        // `u64::MAX`, or a hex-literal-confused-for-decimal magnitude
5431        // — values the `u64` slot accepts cleanly, the codec
5432        // round-trips losslessly through serde, but the wasm-engine
5433        // can never honor as a meaningful counter. Until this gate
5434        // landed validate accepted them. Pin the common above-cap
5435        // values (10x cap, 1000x cap, `u64::MAX`) so a future
5436        // relaxation that drops the upper bound surfaces here. Peer
5437        // of `validate_rejects_cpu_far_above_cap` /
5438        // `validate_rejects_memory_8_gib` /
5439        // `validate_rejects_wall_clock_far_above_cap`.
5440        for f in [LIMITS_FUEL_MAX * 10, LIMITS_FUEL_MAX * 1_000, u64::MAX] {
5441            let l = LimitsSpec {
5442                fuel: Some(f),
5443                ..Default::default()
5444            };
5445            assert_eq!(
5446                l.validate().unwrap_err(),
5447                LimitsError::FuelExceedsCap { fuel: f }
5448            );
5449        }
5450    }
5451
5452    #[test]
5453    fn validate_accepts_fuel_at_cap() {
5454        // The boundary value — exactly [`LIMITS_FUEL_MAX`] (10^12
5455        // wasm instructions) — must validate. The cap is inclusive
5456        // on the top edge, matching the discipline on every sibling
5457        // capped axis ([`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5458        // [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5459        // [`crate::POLICY_TIMEOUT_MAX`],
5460        // [`crate::POLICY_BREAKER_WINDOW_MAX`],
5461        // [`crate::POLICY_RATE_LIMIT_MAX`]). Pin the boundary
5462        // explicitly so a future off-by-one tightening
5463        // (`>= LIMITS_FUEL_MAX` instead of `>`) surfaces here as a
5464        // test failure rather than a silent contract narrowing.
5465        let l = LimitsSpec {
5466            fuel: Some(LIMITS_FUEL_MAX),
5467            ..Default::default()
5468        };
5469        l.validate().expect("fuel == LIMITS_FUEL_MAX must validate");
5470    }
5471
5472    #[test]
5473    fn validate_accepts_fuel_typical_values() {
5474        // The documented production-playbook band positive-control
5475        // sweep — every value the canonical caixa Servico runs in
5476        // (10^6..=10^9 fuel-units) must pass, plus a sweep through
5477        // the larger compute-bound-Servico band (10^10, 10^11) the
5478        // cap accepts. The canonical fixture is `1_000_000` =
5479        // wasmtime's documented `Store::set_fuel(1_000_000)` example.
5480        // Mirrors `validate_accepts_cpu_typical_values` on the
5481        // sibling `:cpu` axis.
5482        for f in [
5483            1_u64,             // smallest non-zero
5484            1_000,             // tiny per-call budget
5485            1_000_000,         // canonical fixture (10^6) — wasmtime book example
5486            10_000_000,        // typical small-Servico (10^7)
5487            100_000_000,       // typical heavier-Servico (10^8)
5488            1_000_000_000,     // 1 billion — upper realistic per-call (10^9)
5489            100_000_000_000,   // 10^11 — heavy compute-bound (10x below cap)
5490            500_000_000_000,   // half the cap
5491            1_000_000_000_000, // exactly at cap (10^12)
5492        ] {
5493            let l = LimitsSpec {
5494                fuel: Some(f),
5495                ..Default::default()
5496            };
5497            l.validate()
5498                .unwrap_or_else(|e| panic!("fuel={f} must validate; got {e:?}"));
5499        }
5500    }
5501
5502    #[test]
5503    fn fuel_zero_takes_precedence_over_cap() {
5504        // The cross-arm ordering pin: `Some(0)` is structurally
5505        // outside both `>= 1` (zero-floor) and `<= LIMITS_FUEL_MAX`
5506        // (cap), but the zero-floor diagnostic is the more
5507        // self-locating one (it directly names the omit-axis
5508        // remediation and the wasmtime-traps-at-zero semantics), so
5509        // the validate gate must fire on zero first. Same shape every
5510        // other zero-then-cap ordering on this surface uses
5511        // (`MemoryZero` then `MemoryExceedsWasm32Cap`,
5512        // `WallClockZero` then `WallClockExceedsCap`, `CpuZero` then
5513        // `CpuExceedsCap`).
5514        let l = LimitsSpec {
5515            fuel: Some(0),
5516            ..Default::default()
5517        };
5518        assert_eq!(
5519            l.validate().unwrap_err(),
5520            LimitsError::FuelZero,
5521            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
5522        );
5523    }
5524
5525    #[test]
5526    fn validate_rejects_fuel_cap_after_earlier_axes() {
5527        // Cross-axis ordering: when both an above-cap `:fuel` and an
5528        // earlier-axis violation are present, the earlier axis must
5529        // fire first. The validate sequence is :memory → :fuel →
5530        // :wall-clock → :cpu, so a paired memory-zero + fuel-above-
5531        // cap input surfaces `MemoryZero`, never the fuel-cap
5532        // diagnostic. Pins the canonical axis order so a future
5533        // refactor that reorders the arms surfaces here as a test
5534        // failure rather than a silent diagnostic regression. Peer
5535        // of `validate_rejects_cpu_cap_after_earlier_axes`.
5536        let l = LimitsSpec {
5537            memory: Some(0),
5538            fuel: Some(LIMITS_FUEL_MAX + 1),
5539            wall_clock: None,
5540            cpu: None,
5541        };
5542        assert_eq!(
5543            l.validate().unwrap_err(),
5544            LimitsError::MemoryZero,
5545            "earlier-axis violation must take precedence over later-axis cap violation"
5546        );
5547    }
5548
5549    #[test]
5550    fn validate_rejects_fuel_cap_before_later_axes() {
5551        // Cross-axis ordering on the other side: when both an
5552        // above-cap `:fuel` and a later-axis violation are present,
5553        // the `:fuel` cap must fire before the `:wall-clock` /
5554        // `:cpu` zero-floor diagnostics. The validate sequence is
5555        // :memory → :fuel → :wall-clock → :cpu, so a paired
5556        // fuel-above-cap + wall-clock-zero input surfaces
5557        // `FuelExceedsCap`, not `WallClockZero`. Pins the canonical
5558        // axis order on the new arm's downstream side, peer to the
5559        // upstream pin `validate_rejects_fuel_cap_after_earlier_axes`.
5560        let l = LimitsSpec {
5561            memory: None,
5562            fuel: Some(LIMITS_FUEL_MAX + 1),
5563            wall_clock: Some(Duration::ZERO),
5564            cpu: Some(0),
5565        };
5566        assert_eq!(
5567            l.validate().unwrap_err(),
5568            LimitsError::FuelExceedsCap {
5569                fuel: LIMITS_FUEL_MAX + 1
5570            },
5571            ":fuel cap diagnostic must take precedence over later-axis zero-floor diagnostics"
5572        );
5573    }
5574
5575    #[test]
5576    fn fuel_cap_diagnostic_carries_offending_value() {
5577        // The diagnostic-shape pin: the offending fuel count is
5578        // carried verbatim into the [`LimitsError::FuelExceedsCap`]
5579        // variant so the surfaced error message names the value the
5580        // author wrote, not just the cap. Same self-locating
5581        // diagnostic shape every other typed-cap arm on this surface
5582        // carries (`MemoryExceedsWasm32Cap` carries the offending
5583        // byte count verbatim, `WallClockExceedsCap` carries the
5584        // offending `Duration` verbatim, `CpuExceedsCap` carries the
5585        // offending millicore count verbatim).
5586        let f = 5_000_000_000_000_u64; // 5 trillion — 5x the cap
5587        let l = LimitsSpec {
5588            fuel: Some(f),
5589            ..Default::default()
5590        };
5591        let err = l.validate().unwrap_err();
5592        assert!(
5593            matches!(err, LimitsError::FuelExceedsCap { fuel } if fuel == f),
5594            "got {err:?}"
5595        );
5596        let msg = err.to_string();
5597        assert!(
5598            msg.contains("5000000000000"),
5599            ":limits :fuel cap diagnostic must carry the offending value verbatim (got: {msg})"
5600        );
5601    }
5602
5603    #[test]
5604    fn fuel_cap_pins_canonical_value() {
5605        // The [`LIMITS_FUEL_MAX`] constant pins the value at exactly
5606        // 10^12 (1 trillion wasm instructions) — the round-number
5607        // ceiling above the operational envelope the sibling
5608        // [`LIMITS_WALL_CLOCK_MAX`] (1h) × wasmtime's fuel-tracked
5609        // execution rate (~10^9 fuel/sec) yields. Pinning the
5610        // literal value here surfaces a future drift (a relaxation
5611        // to 10^15, a tightening to 10^9) as a deliberate test edit,
5612        // not a silent contract narrowing. Same shape every other
5613        // typed-cap value pin uses (`cpu_cap_pins_canonical_value`,
5614        // `wall_clock_cap_pins_canonical_value`,
5615        // `wasm32_memory_cap_matches_parsed_4_gib`).
5616        assert_eq!(LIMITS_FUEL_MAX, 1_000_000_000_000);
5617        assert_eq!(LIMITS_FUEL_MAX, 10_u64.pow(12));
5618    }
5619
5620    #[test]
5621    fn fuel_cap_value_round_trips_through_serde() {
5622        // The serde round-trip property the cap arm preserves: the
5623        // [`LIMITS_FUEL_MAX`] constant itself round-trips through
5624        // the in-module `u64` serde codec — the cap value renders as
5625        // the bare integer literal and parses back to the same
5626        // `u64`. Pin this so a future drift between the cap constant
5627        // and the codec's accepted magnitude (a future custom u64
5628        // serializer that introduces lossy formatting) surfaces
5629        // here. Same shape every other typed boundary pin on this
5630        // surface uses (`wasm32_memory_cap_matches_parsed_4_gib`,
5631        // `wall_clock_cap_value_round_trips_through_codec`,
5632        // `cpu_cap_value_round_trips_through_codec`).
5633        let l = LimitsSpec {
5634            fuel: Some(LIMITS_FUEL_MAX),
5635            ..Default::default()
5636        };
5637        let json = serde_json::to_string(&l).unwrap();
5638        assert!(
5639            json.contains("1000000000000"),
5640            "the LIMITS_FUEL_MAX value must render verbatim as the bare integer 10^12 \
5641             (got: {json})"
5642        );
5643        let back: LimitsSpec = serde_json::from_str(&json).unwrap();
5644        assert_eq!(back.fuel, Some(LIMITS_FUEL_MAX));
5645        l.validate()
5646            .expect("LIMITS_FUEL_MAX itself must pass validate");
5647    }
5648
5649    // ── per-`:limits :memory` accessor pins (LimitsSpec::memory) ─────────
5650
5651    #[test]
5652    fn limits_memory_returns_option_u64_byte_equal_across_permutations() {
5653        // The canonical per-`:limits` `:memory` Lunatic-per-process
5654        // wasm32-linear-memory byte-cap scalar pin: [`LimitsSpec::memory`]
5655        // must return the `:limits :memory` typed `u64` verbatim as an
5656        // `Option<u64>`, byte-equal to the raw field access across the
5657        // three canonical shape-arms — `None` (no cap declared —
5658        // engine-default applies), `Some(LIMITS_MEMORY_WASM32_PAGE_BYTES)`
5659        // (the structural minimum a validated `:limits :memory` may
5660        // carry, one wasm32 linear-memory page), `Some(64 * 1024 *
5661        // 1024)` (the canonical 64 MiB byte-cap the module-level
5662        // docstring names).
5663        //
5664        // Peer of the sibling per-`:politicas` [`crate::MeshPolicy::mtls_required`]
5665        // (c0110f1) / [`crate::MeshPolicy::retries`] (bdfb399) /
5666        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor pin trio on
5667        // the sibling `Option<Copy-T>`-return axis, extended to the
5668        // peer per-`:limits` typed-`u64` optional-scalar shape —
5669        // first `Option<Copy-T>`-return accessor on the M2 slot family.
5670        // Pins against a future silent detour that re-derived the cap
5671        // from a peer axis (an accidental `.fuel`-collapse that
5672        // assumed the two `Option<u64>` axes carry the same value), a
5673        // `None` → `Some(0)` "zero means unbounded" collapse (the
5674        // canonical `Option<u64>` → `u64` collapse footgun the
5675        // [`LimitsError::MemoryZero`] validate arm guards on the peer
5676        // zero-floor axis), or a per-arm variant swap that landed on
5677        // one consumer without the other.
5678        for memory in [
5679            None,
5680            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
5681            Some(64 * 1024 * 1024),
5682        ] {
5683            let l = LimitsSpec {
5684                memory,
5685                ..LimitsSpec::default()
5686            };
5687            assert_eq!(
5688                l.memory(),
5689                memory,
5690                "LimitsSpec::memory must return :limits :memory verbatim \
5691                 (got {:?}, expected {memory:?})",
5692                l.memory(),
5693            );
5694            assert_eq!(
5695                l.memory(),
5696                l.memory,
5697                "LimitsSpec::memory must byte-equal the raw .memory \
5698                 field access across every value in the accept-set",
5699            );
5700        }
5701    }
5702
5703    #[test]
5704    fn limits_is_empty_memory_arm_routes_through_accessor() {
5705        // Composition pin: [`LimitsSpec::is_empty`]'s `memory` arm
5706        // must key off [`LimitsSpec::memory`], not the raw `.memory`
5707        // field access. Structurally: setting ONLY the `memory` slot
5708        // on an otherwise-default LimitsSpec must flip `is_empty()`
5709        // from `true` (all-`None`) to `false` (one axis carries a
5710        // value); the flip must be observed across every value in the
5711        // accept-set since the emptiness semantic reads "any axis
5712        // carries a value" — not "any axis carries a value above a
5713        // threshold" — the same non-collapsing shape the sibling M3
5714        // [`crate::MeshPolicy::is_empty`] predicate carries on its
5715        // peer `Option<Copy-T>`-typed slot surfaces.
5716        //
5717        // Pins against a future silent detour that re-derived the
5718        // emptiness predicate off a peer axis (an accidental
5719        // `.fuel.is_none()`-only chain that dropped the `memory` arm
5720        // entirely), an accessor-side detour that no longer names the
5721        // substrate-primitive typed dispatch (an accidental
5722        // `self.memory.unwrap_or(0) == 0` fallback in the accessor
5723        // that would silently classify both `None` and `Some(0)` as
5724        // the same value), or a threshold collapse (a
5725        // `self.memory().is_some_and(|m| m > 0)` that would silently
5726        // classify `Some(0)` as unset).
5727        //
5728        // Peer of the sibling per-`:politicas`
5729        // [`crate::MeshPolicy::is_empty`] `mtls_required` arm
5730        // accessor-composition pin (c0110f1) on the sibling optional-
5731        // scalar axis — same "the emptiness / shape-gate predicate
5732        // must route through the substrate-primitive typed dispatch"
5733        // discipline extended onto the peer per-`:limits` emptiness
5734        // predicate.
5735        let empty = LimitsSpec::default();
5736        assert!(
5737            empty.is_empty(),
5738            "LimitsSpec::default() must be is_empty() — every axis \
5739             defaults to None",
5740        );
5741        for memory in [
5742            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
5743            Some(64 * 1024 * 1024),
5744            Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
5745        ] {
5746            let l = LimitsSpec {
5747                memory,
5748                ..LimitsSpec::default()
5749            };
5750            assert!(
5751                !l.is_empty(),
5752                "LimitsSpec::is_empty must return false when :memory \
5753                 is {memory:?} — the emptiness predicate reads \"any \
5754                 axis carries a value\", not \"any axis carries a \
5755                 value above a threshold\"",
5756            );
5757            assert_eq!(
5758                l.memory().is_none(),
5759                l.is_empty(),
5760                "when :memory is the only set axis, is_empty() must \
5761                 equal memory().is_none() — the accessor and the \
5762                 emptiness predicate must route through the same \
5763                 substrate-primitive typed dispatch on the :memory \
5764                 arm",
5765            );
5766        }
5767    }
5768
5769    #[test]
5770    fn limits_memory_projects_option_u64_by_copy() {
5771        // The by-copy pin: [`LimitsSpec::memory`] returns `Option<u64>`
5772        // by copy — `Option<u64>` is `Copy` and the accessor must
5773        // return by value, not by reference. Peer of the sibling per-
5774        // `:politicas` [`crate::MeshPolicy::mtls_required`] (c0110f1)
5775        // borrow-invariant pin on the peer `Option<bool>` shape,
5776        // extended onto the peer `Option<u64>` copy-invariant shape —
5777        // the accessor's returned `Option<u64>` must outlive `&self`
5778        // (multiple calls must return equal values from a dropped-
5779        // `&self` copy, since the returned Option carries no borrow),
5780        // and calling the accessor twice on the same LimitsSpec must
5781        // yield the same `Option<u64>` verbatim (idempotent, no side
5782        // effects on `&self`).
5783        //
5784        // Pins against a future silent detour that returned
5785        // `Option<&u64>` (which would type-check but silently break
5786        // every downstream caller — the future `wasmtime::Store::limiter`
5787        // wire path consumes `Option<u64>` by value and `&u64` would
5788        // fold to a detached copy at the call site), an accidental
5789        // `Option::as_ref()` projection (`self.memory.as_ref()` would
5790        // also type-check but return `Option<&u64>`), or a one-arm-
5791        // only accessor that reads `Some(*m)` in the Some arm but
5792        // reads a fresh `Default::default()` in the None arm.
5793        for memory in [
5794            None,
5795            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
5796            Some(64 * 1024 * 1024),
5797            Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
5798        ] {
5799            let l = LimitsSpec {
5800                memory,
5801                ..LimitsSpec::default()
5802            };
5803            let first = l.memory();
5804            let second = l.memory();
5805            assert_eq!(
5806                first, second,
5807                "LimitsSpec::memory must be idempotent — two \
5808                 successive calls on the same &self must return the \
5809                 same Option<u64>",
5810            );
5811            assert_eq!(
5812                first, memory,
5813                "LimitsSpec::memory must return :limits :memory \
5814                 verbatim by copy — got {first:?}, expected {memory:?}",
5815            );
5816        }
5817    }
5818
5819    #[test]
5820    #[allow(clippy::too_many_lines)]
5821    fn validate_memory_arms_route_through_lifted_memory_accessor() {
5822        // Composition pin: every value-shape gate in
5823        // [`LimitsSpec::validate`] on the `:memory` axis (the
5824        // zero-floor `MemoryZero` arm, the sub-page `MemoryBelowWasm32Page`
5825        // arm, the above-cap `MemoryExceedsWasm32Cap` arm, the
5826        // non-page-multiple `MemoryNotPageMultiple` arm) must key off
5827        // [`LimitsSpec::memory`], not the raw `self.memory` field
5828        // access. Peer of the sibling per-`:politicas`
5829        // [`crate::AplicacaoSpec::validate_politicas`] `:timeout` /
5830        // `:retries` arm converge pin (1017b9d) on the sibling M3
5831        // mesh-slot family, extended onto the M2 per-`:limits`
5832        // `:memory` axis; peer of the sibling per-`:limits` `:fuel` /
5833        // `:wall-clock` / `:cpu` arms in the same fan-out that
5834        // already route through `self.fuel()` / `self.wall_clock()`
5835        // / `self.cpu()` at :880 / :888 / :942.
5836        //
5837        // Assertion shape: for each memory value in the
5838        // accept-and-refuse set, `LimitsSpec::memory()` must byte-
5839        // equal the raw `.memory` field it borrows from, and the
5840        // validate call on a `LimitsSpec { memory: <v>, ..default() }`
5841        // fixture must surface the same variant/Ok discriminant the
5842        // accessor-composed spec surfaces. Together they catch any
5843        // future silent detour — an accessor drift that no longer
5844        // shipped the raw slot verbatim, a validate-branch rebrand to
5845        // a peer-axis field read, an accidental `Option`-collapse in
5846        // any of the four arms — at caixa-core build time rather than
5847        // at a downstream runtime declared-but-inert-limits divergence
5848        // at the wasmtime `Store::limiter` boundary.
5849        //
5850        // `#[allow(clippy::too_many_lines)]` per the same discipline
5851        // peer over-100-line composition pins in this module accept
5852        // (see e.g. `limits_is_empty_memory_arm_routes_through_accessor`,
5853        // `limits_memory_returns_option_u64_byte_equal_across_permutations`).
5854        for memory in [
5855            None,
5856            Some(0),                                   // → MemoryZero
5857            Some(1),                                   // → MemoryBelowWasm32Page (sub-page)
5858            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES - 1), // → MemoryBelowWasm32Page (at-under-page)
5859            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),     // → Ok (at-page-floor)
5860            Some(LIMITS_MEMORY_WASM32_PAGE_BYTES + 1), // → MemoryNotPageMultiple (one-past-page)
5861            Some(2 * LIMITS_MEMORY_WASM32_PAGE_BYTES), // → Ok (multi-page)
5862            Some(LIMITS_MEMORY_WASM32_MAX_BYTES),      // → Ok (at-cap)
5863            Some(LIMITS_MEMORY_WASM32_MAX_BYTES + 1),  // → MemoryExceedsWasm32Cap (one-past-cap)
5864        ] {
5865            let l = LimitsSpec {
5866                memory,
5867                ..LimitsSpec::default()
5868            };
5869            // (1) The accessor must byte-equal the raw field it wraps.
5870            assert_eq!(
5871                l.memory(),
5872                l.memory,
5873                "LimitsSpec::memory() must byte-equal the raw \
5874                 .memory field for {memory:?} — an accessor detour \
5875                 that dropped the raw slot's Option<u64> verbatim \
5876                 would silently split validate's :memory arms from \
5877                 every peer emit-site consumer that also routes \
5878                 through the accessor (the future wasmtime \
5879                 Store::limiter wire path, the caixa-helm \
5880                 resources.limits.memory materializer)",
5881            );
5882            // (2) Two successive validate() calls must yield the same
5883            // variant/Ok discriminant — the accessor-projected reads
5884            // and the raw-projected reads must produce identical
5885            // validation outcomes.
5886            let first = l.validate();
5887            let second = l.validate();
5888            assert_eq!(
5889                first, second,
5890                "LimitsSpec::validate must be idempotent on :memory \
5891                 {memory:?} — two successive calls must surface the \
5892                 same variant/Ok discriminant, catching any accessor \
5893                 detour that would introduce a value-dependent side \
5894                 effect on the &self projection",
5895            );
5896        }
5897        // (3) The specific arm-order shape the four converged sites
5898        // encode: `MemoryZero` (raw-`Some(0)`) precedes the page-floor
5899        // arm, which precedes the cap arm, which precedes the page-
5900        // multiple arm. Each arm must fire off the accessor-projected
5901        // read on its specific fixture value.
5902        assert_eq!(
5903            LimitsSpec {
5904                memory: Some(0),
5905                ..LimitsSpec::default()
5906            }
5907            .validate(),
5908            Err(LimitsError::MemoryZero),
5909            "MemoryZero must fire on Some(0) via the accessor projection",
5910        );
5911        assert_eq!(
5912            LimitsSpec {
5913                memory: Some(1),
5914                ..LimitsSpec::default()
5915            }
5916            .validate(),
5917            Err(LimitsError::MemoryBelowWasm32Page { bytes: 1 }),
5918            "MemoryBelowWasm32Page must fire on Some(1) via the accessor projection",
5919        );
5920        assert_eq!(
5921            LimitsSpec {
5922                memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES + 1),
5923                ..LimitsSpec::default()
5924            }
5925            .validate(),
5926            Err(LimitsError::MemoryExceedsWasm32Cap {
5927                bytes: LIMITS_MEMORY_WASM32_MAX_BYTES + 1
5928            }),
5929            "MemoryExceedsWasm32Cap must fire on one-past-cap via the accessor projection",
5930        );
5931        assert_eq!(
5932            LimitsSpec {
5933                memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES + 1),
5934                ..LimitsSpec::default()
5935            }
5936            .validate(),
5937            Err(LimitsError::MemoryNotPageMultiple {
5938                bytes: LIMITS_MEMORY_WASM32_PAGE_BYTES + 1
5939            }),
5940            "MemoryNotPageMultiple must fire on one-past-page-floor via the accessor projection",
5941        );
5942        assert_eq!(
5943            LimitsSpec {
5944                memory: Some(LIMITS_MEMORY_WASM32_PAGE_BYTES),
5945                ..LimitsSpec::default()
5946            }
5947            .validate(),
5948            Ok(()),
5949            "at-page-floor must pass validate via the accessor projection",
5950        );
5951        assert_eq!(
5952            LimitsSpec {
5953                memory: Some(LIMITS_MEMORY_WASM32_MAX_BYTES),
5954                ..LimitsSpec::default()
5955            }
5956            .validate(),
5957            Ok(()),
5958            "at-cap must pass validate via the accessor projection",
5959        );
5960    }
5961
5962    // ── per-`:limits :fuel` accessor pins (LimitsSpec::fuel) ─────────
5963
5964    #[test]
5965    fn limits_fuel_returns_option_u64_byte_equal_across_permutations() {
5966        // The canonical per-`:limits` `:fuel` wasmtime-per-call
5967        // wasm-instruction budget scalar pin: [`LimitsSpec::fuel`]
5968        // must return the `:limits :fuel` typed `u64` verbatim as an
5969        // `Option<u64>`, byte-equal to the raw field access across
5970        // the three canonical shape-arms — `None` (no fuel budget
5971        // declared — engine-default applies), `Some(1)` (the
5972        // structural minimum a validated `:limits :fuel` may carry,
5973        // one wasm instruction; wasmtime traps the first instruction
5974        // at `fuel=0`, so `Some(1)` is the smallest budget that
5975        // executes any code), `Some(1_000_000)` (the canonical 10⁶
5976        // fuel-unit budget the in-tree `Caixa::template` and the
5977        // wasmtime book's `Store::set_fuel(1_000_000)` example both
5978        // carry).
5979        //
5980        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
5981        // (620c067) accessor byte-equality pin on the peer typed-`u64`
5982        // optional-scalar axis, extended to the wasm-instruction-budget
5983        // shape — second `Option<Copy-T>`-return accessor on the M2
5984        // slot family. Pins against a future silent detour that
5985        // re-derived the fuel budget from a peer axis (an accidental
5986        // `.memory`-collapse that assumed the two `Option<u64>` axes
5987        // carry the same value — the two axes share a shape but not
5988        // a semantic, `:memory` counts linear-memory bytes and `:fuel`
5989        // counts wasm instructions), a `None` → `Some(0)` "zero means
5990        // unbounded" collapse (the canonical `Option<u64>` → `u64`
5991        // collapse footgun the [`LimitsError::FuelZero`] validate arm
5992        // guards on the peer zero-floor axis; wasmtime interprets
5993        // `fuel=0` as "trap the first instruction" not "no bound"), or
5994        // a per-arm variant swap that landed on one consumer without
5995        // the other.
5996        for fuel in [None, Some(1_u64), Some(1_000_000_u64)] {
5997            let l = LimitsSpec {
5998                fuel,
5999                ..LimitsSpec::default()
6000            };
6001            assert_eq!(
6002                l.fuel(),
6003                fuel,
6004                "LimitsSpec::fuel must return :limits :fuel verbatim \
6005                 (got {:?}, expected {fuel:?})",
6006                l.fuel(),
6007            );
6008            assert_eq!(
6009                l.fuel(),
6010                l.fuel,
6011                "LimitsSpec::fuel must byte-equal the raw .fuel \
6012                 field access across every value in the accept-set",
6013            );
6014        }
6015    }
6016
6017    #[test]
6018    fn limits_is_empty_fuel_arm_routes_through_accessor() {
6019        // Composition pin: [`LimitsSpec::is_empty`]'s `fuel` arm
6020        // must key off [`LimitsSpec::fuel`], not the raw `.fuel`
6021        // field access. Structurally: setting ONLY the `fuel` slot
6022        // on an otherwise-default LimitsSpec must flip `is_empty()`
6023        // from `true` (all-`None`) to `false` (one axis carries a
6024        // value); the flip must be observed across every value in
6025        // the accept-set since the emptiness semantic reads "any
6026        // axis carries a value" — not "any axis carries a value
6027        // above a threshold" — the same non-collapsing shape the
6028        // sibling M3 [`crate::MeshPolicy::is_empty`] predicate
6029        // carries on its peer `Option<Copy-T>`-typed slot surfaces
6030        // and the sibling per-`:limits` [`LimitsSpec::memory`]
6031        // (620c067) `is_empty()` accessor-composition pin carries on
6032        // the peer `Option<u64>` axis.
6033        //
6034        // Pins against a future silent detour that re-derived the
6035        // emptiness predicate off a peer axis (an accidental
6036        // `.memory.is_none()`-only chain that dropped the `fuel` arm
6037        // entirely), an accessor-side detour that no longer names the
6038        // substrate-primitive typed dispatch (an accidental
6039        // `self.fuel.unwrap_or(0) == 0` fallback in the accessor
6040        // that would silently classify both `None` and `Some(0)` as
6041        // the same value — a footgun the [`LimitsError::FuelZero`]
6042        // validate arm explicitly closes since `fuel=0` traps rather
6043        // than expresses "unbounded"), or a threshold collapse (a
6044        // `self.fuel().is_some_and(|f| f > 0)` that would silently
6045        // classify `Some(0)` as unset).
6046        //
6047        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6048        // (620c067) `is_empty` composition pin on the peer
6049        // `Option<u64>` axis — same "the emptiness predicate must
6050        // route through the substrate-primitive typed dispatch"
6051        // discipline extended onto the peer per-`:limits` `:fuel`
6052        // arm.
6053        let empty = LimitsSpec::default();
6054        assert!(
6055            empty.is_empty(),
6056            "LimitsSpec::default() must be is_empty() — every axis \
6057             defaults to None",
6058        );
6059        for fuel in [Some(1_u64), Some(1_000_000_u64), Some(LIMITS_FUEL_MAX)] {
6060            let l = LimitsSpec {
6061                fuel,
6062                ..LimitsSpec::default()
6063            };
6064            assert!(
6065                !l.is_empty(),
6066                "LimitsSpec::is_empty must return false when :fuel \
6067                 is {fuel:?} — the emptiness predicate reads \"any \
6068                 axis carries a value\", not \"any axis carries a \
6069                 value above a threshold\"",
6070            );
6071            assert_eq!(
6072                l.fuel().is_none(),
6073                l.is_empty(),
6074                "when :fuel is the only set axis, is_empty() must \
6075                 equal fuel().is_none() — the accessor and the \
6076                 emptiness predicate must route through the same \
6077                 substrate-primitive typed dispatch on the :fuel \
6078                 arm",
6079            );
6080        }
6081    }
6082
6083    #[test]
6084    fn limits_fuel_projects_option_u64_by_copy() {
6085        // The by-copy pin: [`LimitsSpec::fuel`] returns `Option<u64>`
6086        // by copy — `Option<u64>` is `Copy` and the accessor must
6087        // return by value, not by reference. Peer of the sibling per-
6088        // `:limits` [`LimitsSpec::memory`] (620c067) copy-invariant
6089        // pin on the peer `Option<u64>` shape — the accessor's
6090        // returned `Option<u64>` must outlive `&self` (multiple calls
6091        // must return equal values from a dropped-`&self` copy, since
6092        // the returned Option carries no borrow), and calling the
6093        // accessor twice on the same LimitsSpec must yield the same
6094        // `Option<u64>` verbatim (idempotent, no side effects on
6095        // `&self`).
6096        //
6097        // Pins against a future silent detour that returned
6098        // `Option<&u64>` (which would type-check but silently break
6099        // every downstream caller — the future `wasmtime::Store::set_fuel`
6100        // wire path consumes `u64` by value and `&u64` would fold to
6101        // a detached copy at the call site), an accidental
6102        // `Option::as_ref()` projection (`self.fuel.as_ref()` would
6103        // also type-check but return `Option<&u64>`), or a one-arm-
6104        // only accessor that reads `Some(*f)` in the Some arm but
6105        // reads a fresh `Default::default()` in the None arm.
6106        for fuel in [
6107            None,
6108            Some(1_u64),
6109            Some(1_000_000_u64),
6110            Some(LIMITS_FUEL_MAX),
6111        ] {
6112            let l = LimitsSpec {
6113                fuel,
6114                ..LimitsSpec::default()
6115            };
6116            let first = l.fuel();
6117            let second = l.fuel();
6118            assert_eq!(
6119                first, second,
6120                "LimitsSpec::fuel must be idempotent — two \
6121                 successive calls on the same &self must return the \
6122                 same Option<u64>",
6123            );
6124            assert_eq!(
6125                first, fuel,
6126                "LimitsSpec::fuel must return :limits :fuel \
6127                 verbatim by copy — got {first:?}, expected {fuel:?}",
6128            );
6129        }
6130    }
6131
6132    // ── per-`:limits :wall-clock` accessor pins (LimitsSpec::wall_clock) ─
6133
6134    #[test]
6135    fn limits_wall_clock_returns_option_duration_byte_equal_across_permutations() {
6136        // The canonical per-`:limits` `:wall-clock` wasmtime-per-call
6137        // wall-clock deadline scalar pin: [`LimitsSpec::wall_clock`]
6138        // must return the `:limits :wall-clock` typed `Duration`
6139        // verbatim as an `Option<Duration>`, byte-equal to the raw
6140        // field access across the three canonical shape-arms — `None`
6141        // (no wall-clock deadline declared — engine-default applies),
6142        // `Some(Duration::from_millis(1))` (the structural minimum a
6143        // validated `:limits :wall-clock` may carry, the
6144        // integer-millisecond floor
6145        // [`LimitsError::WallClockNotCanonical`] rejects everything
6146        // sub-ms; `Duration::ZERO` is separately rejected by
6147        // [`LimitsError::WallClockZero`]), `Some(Duration::from_secs(30))`
6148        // (the canonical 30s deadline the module-level docstring
6149        // names).
6150        //
6151        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6152        // (620c067) / [`LimitsSpec::fuel`] (795dee7) accessor
6153        // byte-equality pins on the peer typed-`u64` optional-scalar
6154        // axes, extended to the wall-clock-deadline `Option<Duration>`
6155        // shape — third `Option<Copy-T>`-return accessor on the M2 slot
6156        // family. Sibling to [`crate::MeshPolicy::timeout`] (7073d0f) on
6157        // the M3 mesh-slot family's peer `Option<Duration>` accessor
6158        // axis — same typed-`Duration` shape extended from the M3
6159        // per-call-timeout axis to the M2 per-outermost-call-deadline
6160        // axis. Pins against a future silent detour that re-derived the
6161        // wall-clock deadline from a peer axis (an accidental
6162        // `.fuel`-collapse that assumed the wall-clock deadline and
6163        // the fuel budget carry the same value — the two axes serve
6164        // different sandboxing purposes, wall-clock tracks scheduler
6165        // real time and fuel tracks wasm instructions), a `None` →
6166        // `Some(Duration::ZERO)` "zero means unbounded" collapse (the
6167        // canonical `Option<Duration>` → `Duration` collapse footgun
6168        // the [`LimitsError::WallClockZero`] validate arm guards on the
6169        // peer zero-floor axis; a zero deadline traps the first
6170        // instruction), or a per-arm variant swap that landed on one
6171        // consumer without the other.
6172        for wall_clock in [
6173            None,
6174            Some(Duration::from_millis(1)),
6175            Some(Duration::from_secs(30)),
6176        ] {
6177            let l = LimitsSpec {
6178                wall_clock,
6179                ..LimitsSpec::default()
6180            };
6181            assert_eq!(
6182                l.wall_clock(),
6183                wall_clock,
6184                "LimitsSpec::wall_clock must return :limits :wall-clock verbatim \
6185                 (got {:?}, expected {wall_clock:?})",
6186                l.wall_clock(),
6187            );
6188            assert_eq!(
6189                l.wall_clock(),
6190                l.wall_clock,
6191                "LimitsSpec::wall_clock must byte-equal the raw .wall_clock \
6192                 field access across every value in the accept-set",
6193            );
6194        }
6195    }
6196
6197    #[test]
6198    fn limits_is_empty_wall_clock_arm_routes_through_accessor() {
6199        // Composition pin: [`LimitsSpec::is_empty`]'s `wall_clock` arm
6200        // must key off [`LimitsSpec::wall_clock`], not the raw
6201        // `.wall_clock` field access. Structurally: setting ONLY the
6202        // `wall_clock` slot on an otherwise-default LimitsSpec must
6203        // flip `is_empty()` from `true` (all-`None`) to `false` (one
6204        // axis carries a value); the flip must be observed across every
6205        // value in the accept-set since the emptiness semantic reads
6206        // "any axis carries a value" — not "any axis carries a value
6207        // above a threshold" — the same non-collapsing shape the
6208        // sibling M3 [`crate::MeshPolicy::is_empty`] predicate carries
6209        // on its peer `Option<Copy-T>`-typed slot surfaces and the
6210        // sibling per-`:limits` [`LimitsSpec::memory`] (620c067) /
6211        // [`LimitsSpec::fuel`] (795dee7) `is_empty()` accessor-
6212        // composition pins carry on the peer `Option<u64>` axes.
6213        //
6214        // Pins against a future silent detour that re-derived the
6215        // emptiness predicate off a peer axis (an accidental
6216        // `.memory.is_none()`-only chain that dropped the `wall_clock`
6217        // arm entirely), an accessor-side detour that no longer names
6218        // the substrate-primitive typed dispatch (an accidental
6219        // `self.wall_clock.unwrap_or(Duration::ZERO).is_zero()` fallback
6220        // in the accessor that would silently classify both `None` and
6221        // `Some(Duration::ZERO)` as the same value — a footgun the
6222        // [`LimitsError::WallClockZero`] validate arm explicitly closes
6223        // since a zero deadline traps rather than expresses
6224        // "unbounded"), or a threshold collapse (a
6225        // `self.wall_clock().is_some_and(|w| !w.is_zero())` that would
6226        // silently classify `Some(Duration::ZERO)` as unset).
6227        //
6228        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6229        // (620c067) / [`LimitsSpec::fuel`] (795dee7) `is_empty`
6230        // composition pins on the peer `Option<u64>` axes — same "the
6231        // emptiness predicate must route through the substrate-
6232        // primitive typed dispatch" discipline extended onto the peer
6233        // per-`:limits` `:wall-clock` arm.
6234        let empty = LimitsSpec::default();
6235        assert!(
6236            empty.is_empty(),
6237            "LimitsSpec::default() must be is_empty() — every axis \
6238             defaults to None",
6239        );
6240        for wall_clock in [
6241            Some(Duration::from_millis(1)),
6242            Some(Duration::from_secs(30)),
6243            Some(LIMITS_WALL_CLOCK_MAX),
6244        ] {
6245            let l = LimitsSpec {
6246                wall_clock,
6247                ..LimitsSpec::default()
6248            };
6249            assert!(
6250                !l.is_empty(),
6251                "LimitsSpec::is_empty must return false when :wall-clock \
6252                 is {wall_clock:?} — the emptiness predicate reads \"any \
6253                 axis carries a value\", not \"any axis carries a \
6254                 value above a threshold\"",
6255            );
6256            assert_eq!(
6257                l.wall_clock().is_none(),
6258                l.is_empty(),
6259                "when :wall-clock is the only set axis, is_empty() must \
6260                 equal wall_clock().is_none() — the accessor and the \
6261                 emptiness predicate must route through the same \
6262                 substrate-primitive typed dispatch on the :wall-clock \
6263                 arm",
6264            );
6265        }
6266    }
6267
6268    #[test]
6269    fn limits_wall_clock_projects_option_duration_by_copy() {
6270        // The by-copy pin: [`LimitsSpec::wall_clock`] returns
6271        // `Option<Duration>` by copy — `Duration` is `Copy` (so
6272        // `Option<Duration>` is `Copy`) and the accessor must return by
6273        // value, not by reference. Peer of the sibling per-`:limits`
6274        // [`LimitsSpec::memory`] (620c067) / [`LimitsSpec::fuel`]
6275        // (795dee7) copy-invariant pins on the peer `Option<u64>`
6276        // shape, extended onto the peer `Option<Duration>` shape — the
6277        // accessor's returned `Option<Duration>` must outlive `&self`
6278        // (multiple calls must return equal values from a dropped-
6279        // `&self` copy, since the returned Option carries no borrow),
6280        // and calling the accessor twice on the same LimitsSpec must
6281        // yield the same `Option<Duration>` verbatim (idempotent, no
6282        // side effects on `&self`).
6283        //
6284        // Pins against a future silent detour that returned
6285        // `Option<&Duration>` (which would type-check but silently
6286        // break every downstream caller — the future
6287        // `wasmtime::Store::epoch_deadline_*` wire path consumes
6288        // `Duration` by value and `&Duration` would fold to a detached
6289        // copy at the call site), an accidental `Option::as_ref()`
6290        // projection (`self.wall_clock.as_ref()` would also type-check
6291        // but return `Option<&Duration>`), or a one-arm-only accessor
6292        // that reads `Some(*w)` in the Some arm but reads a fresh
6293        // `Default::default()` (which would collapse to
6294        // `Duration::ZERO`, not `None`) in the None arm.
6295        for wall_clock in [
6296            None,
6297            Some(Duration::from_millis(1)),
6298            Some(Duration::from_secs(30)),
6299            Some(LIMITS_WALL_CLOCK_MAX),
6300        ] {
6301            let l = LimitsSpec {
6302                wall_clock,
6303                ..LimitsSpec::default()
6304            };
6305            let first = l.wall_clock();
6306            let second = l.wall_clock();
6307            assert_eq!(
6308                first, second,
6309                "LimitsSpec::wall_clock must be idempotent — two \
6310                 successive calls on the same &self must return the \
6311                 same Option<Duration>",
6312            );
6313            assert_eq!(
6314                first, wall_clock,
6315                "LimitsSpec::wall_clock must return :limits :wall-clock \
6316                 verbatim by copy — got {first:?}, expected {wall_clock:?}",
6317            );
6318        }
6319    }
6320
6321    // ── per-`:limits :cpu` accessor pins (LimitsSpec::cpu) ───────────
6322
6323    #[test]
6324    fn limits_cpu_returns_option_u32_byte_equal_across_permutations() {
6325        // The canonical per-`:limits` `:cpu` Kubernetes-millicore
6326        // soft cgroup-share scalar pin: [`LimitsSpec::cpu`] must return
6327        // the `:limits :cpu` typed `u32` verbatim as an `Option<u32>`,
6328        // byte-equal to the raw field access across the three canonical
6329        // shape-arms — `None` (no cgroup share declared —
6330        // scheduler-default applies), `Some(1)` (the structural minimum
6331        // a validated `:limits :cpu` may carry, one millicore; a zero
6332        // cgroup share is separately rejected by
6333        // [`LimitsError::CpuZero`]), `Some(500)` (the canonical 500m
6334        // half-a-core share the in-tree
6335        // `limits_slot_propagates_into_values_block` smoke test carries
6336        // as the load-bearing example, peer to the `caixa-flux`
6337        // projector's identical 500m default).
6338        //
6339        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6340        // (620c067) / [`LimitsSpec::fuel`] (795dee7) /
6341        // [`LimitsSpec::wall_clock`] (8cb717b) accessor byte-equality
6342        // pins on the peer typed-`u64` / `u64` / `Duration`
6343        // optional-scalar axes, extended to the cgroup-cpu-share
6344        // `Option<u32>` shape — fourth and final `Option<Copy-T>`-return
6345        // accessor on the M2 slot family, closing the M2 `:limits`
6346        // `Option<Copy-T>` accessor axis. Sibling to
6347        // [`crate::MeshPolicy::retries`] (bdfb399) on the M3 mesh-slot
6348        // family's peer `Option<u32>` accessor axis — same typed-`u32`
6349        // shape extended from the M3 per-edge-transient-failure-retry-
6350        // budget axis to the M2 per-process-cgroup-cpu-share axis.
6351        // Pins against a future silent detour that re-derived the cpu
6352        // share from a peer axis (an accidental `.retries`-collapse that
6353        // assumed the two `Option<u32>` axes carry the same value — the
6354        // two axes share a shape but not a semantic, M2 `:cpu` counts
6355        // millicores of soft cgroup share and M3 `:retries` counts
6356        // per-edge transient-failure retry budget), a `None` → `Some(0)`
6357        // "zero means unbounded" collapse (the canonical `Option<u32>` →
6358        // `u32` collapse footgun the [`LimitsError::CpuZero`] validate
6359        // arm guards on the peer zero-floor axis; a zero cgroup share
6360        // starves the process rather than expressing "unbounded"), or a
6361        // per-arm variant swap that landed on one consumer without the
6362        // other.
6363        for cpu in [None, Some(1_u32), Some(500_u32)] {
6364            let l = LimitsSpec {
6365                cpu,
6366                ..LimitsSpec::default()
6367            };
6368            assert_eq!(
6369                l.cpu(),
6370                cpu,
6371                "LimitsSpec::cpu must return :limits :cpu verbatim \
6372                 (got {:?}, expected {cpu:?})",
6373                l.cpu(),
6374            );
6375            assert_eq!(
6376                l.cpu(),
6377                l.cpu,
6378                "LimitsSpec::cpu must byte-equal the raw .cpu \
6379                 field access across every value in the accept-set",
6380            );
6381        }
6382    }
6383
6384    #[test]
6385    fn limits_is_empty_cpu_arm_routes_through_accessor() {
6386        // Composition pin: [`LimitsSpec::is_empty`]'s `cpu` arm must key
6387        // off [`LimitsSpec::cpu`], not the raw `.cpu` field access.
6388        // Structurally: setting ONLY the `cpu` slot on an
6389        // otherwise-default LimitsSpec must flip `is_empty()` from
6390        // `true` (all-`None`) to `false` (one axis carries a value);
6391        // the flip must be observed across every value in the
6392        // accept-set since the emptiness semantic reads "any axis
6393        // carries a value" — not "any axis carries a value above a
6394        // threshold" — the same non-collapsing shape the sibling M3
6395        // [`crate::MeshPolicy::is_empty`] predicate carries on its
6396        // peer `Option<Copy-T>`-typed slot surfaces and the sibling
6397        // per-`:limits` [`LimitsSpec::memory`] (620c067) /
6398        // [`LimitsSpec::fuel`] (795dee7) / [`LimitsSpec::wall_clock`]
6399        // (8cb717b) `is_empty()` accessor-composition pins carry on the
6400        // peer `Option<u64>` / `Option<u64>` / `Option<Duration>` axes.
6401        //
6402        // Pins against a future silent detour that re-derived the
6403        // emptiness predicate off a peer axis (an accidental
6404        // `.memory.is_none()`-only chain that dropped the `cpu` arm
6405        // entirely), an accessor-side detour that no longer names the
6406        // substrate-primitive typed dispatch (an accidental
6407        // `self.cpu.unwrap_or(0) == 0` fallback in the accessor that
6408        // would silently classify both `None` and `Some(0)` as the same
6409        // value — a footgun the [`LimitsError::CpuZero`] validate arm
6410        // explicitly closes since a zero cgroup share starves the
6411        // process rather than expressing "unbounded"), or a threshold
6412        // collapse (a `self.cpu().is_some_and(|m| m > 0)` that would
6413        // silently classify `Some(0)` as unset).
6414        //
6415        // Peer of the sibling per-`:limits` [`LimitsSpec::memory`]
6416        // (620c067) / [`LimitsSpec::fuel`] (795dee7) /
6417        // [`LimitsSpec::wall_clock`] (8cb717b) `is_empty` composition
6418        // pins on the peer `Option<u64>` / `Option<u64>` /
6419        // `Option<Duration>` axes — same "the emptiness predicate must
6420        // route through the substrate-primitive typed dispatch"
6421        // discipline extended onto the peer per-`:limits` `:cpu` arm.
6422        // Closes the M2 `:limits` `is_empty`-composition family — every
6423        // arm now routes through its typed accessor, no open-coded
6424        // field access remains.
6425        let empty = LimitsSpec::default();
6426        assert!(
6427            empty.is_empty(),
6428            "LimitsSpec::default() must be is_empty() — every axis \
6429             defaults to None",
6430        );
6431        for cpu in [Some(1_u32), Some(500_u32), Some(LIMITS_CPU_MILLICORES_MAX)] {
6432            let l = LimitsSpec {
6433                cpu,
6434                ..LimitsSpec::default()
6435            };
6436            assert!(
6437                !l.is_empty(),
6438                "LimitsSpec::is_empty must return false when :cpu \
6439                 is {cpu:?} — the emptiness predicate reads \"any \
6440                 axis carries a value\", not \"any axis carries a \
6441                 value above a threshold\"",
6442            );
6443            assert_eq!(
6444                l.cpu().is_none(),
6445                l.is_empty(),
6446                "when :cpu is the only set axis, is_empty() must \
6447                 equal cpu().is_none() — the accessor and the \
6448                 emptiness predicate must route through the same \
6449                 substrate-primitive typed dispatch on the :cpu \
6450                 arm",
6451            );
6452        }
6453    }
6454
6455    #[test]
6456    fn limits_cpu_projects_option_u32_by_copy() {
6457        // The by-copy pin: [`LimitsSpec::cpu`] returns `Option<u32>` by
6458        // copy — `Option<u32>` is `Copy` and the accessor must return
6459        // by value, not by reference. Peer of the sibling per-`:limits`
6460        // [`LimitsSpec::memory`] (620c067) / [`LimitsSpec::fuel`]
6461        // (795dee7) / [`LimitsSpec::wall_clock`] (8cb717b)
6462        // copy-invariant pins on the peer `Option<u64>` / `Option<u64>`
6463        // / `Option<Duration>` shapes, extended onto the peer
6464        // `Option<u32>` copy-invariant shape — the accessor's returned
6465        // `Option<u32>` must outlive `&self` (multiple calls must
6466        // return equal values from a dropped-`&self` copy, since the
6467        // returned Option carries no borrow), and calling the accessor
6468        // twice on the same LimitsSpec must yield the same
6469        // `Option<u32>` verbatim (idempotent, no side effects on
6470        // `&self`).
6471        //
6472        // Pins against a future silent detour that returned
6473        // `Option<&u32>` (which would type-check but silently break
6474        // every downstream caller — the future K8s pod-spec
6475        // `resources.requests.cpu` wire path consumes `u32` by value
6476        // and `&u32` would fold to a detached copy at the call site),
6477        // an accidental `Option::as_ref()` projection
6478        // (`self.cpu.as_ref()` would also type-check but return
6479        // `Option<&u32>`), or a one-arm-only accessor that reads
6480        // `Some(*m)` in the Some arm but reads a fresh
6481        // `Default::default()` in the None arm.
6482        for cpu in [
6483            None,
6484            Some(1_u32),
6485            Some(500_u32),
6486            Some(LIMITS_CPU_MILLICORES_MAX),
6487        ] {
6488            let l = LimitsSpec {
6489                cpu,
6490                ..LimitsSpec::default()
6491            };
6492            let first = l.cpu();
6493            let second = l.cpu();
6494            assert_eq!(
6495                first, second,
6496                "LimitsSpec::cpu must be idempotent — two \
6497                 successive calls on the same &self must return the \
6498                 same Option<u32>",
6499            );
6500            assert_eq!(
6501                first, cpu,
6502                "LimitsSpec::cpu must return :limits :cpu \
6503                 verbatim by copy — got {first:?}, expected {cpu:?}",
6504            );
6505        }
6506    }
6507}