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