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