# Resource contract

The library targets MoonBit's JS backend. Resource errors are reported as
`JmesPathError`. These limits are not a wall-clock deadline or OS memory sandbox.

| Boundary | Default / hard cap | Behavior |
| --- | --- | --- |
| Expression length | 16,384 Unicode scalar values by default | Check UTF-16 length as a fast bound, then count scalars if needed before allocation; configurable in Limits |
| Parser recursion and AST depth | 256 maximum | Checked while parsing and constructing nodes; configurable downward |
| Active evaluator calls | 128 hard cap | Separate from AST depth because function evaluation uses multiple host frames |
| Logical evaluation work | 1,000,000 by default | AST visits, equality visits/string comparisons, reductions, array membership, join/merge iterations, non-string to_string output estimates, and one step per JSON node on the first copy of each container literal per search |
| Materialized result elements | 100,000 by default | Query-operator/function array elements and unique object keys, including intermediate results; JSON shape guards also apply |
| In-memory JSON input/result | Depth 256, root at 0; 1,000,000 expanded nodes | Iterative traversal; shared references count per occurrence |
| Output estimate | 16,777,216 UTF-16 units | Conservative estimate includes escaping and pretty indentation; checked before serialization |
| join intermediate string | 16,777,216 UTF-16 units | Length checked before allocation; final escaping may cause a stricter rejection |
| search_json text | 16,777,216 UTF-16 units | Checked before JSON parsing |
| JSON string token source | 8,388,608 UTF-16 units, excluding quotes | Checked before decoding; escape sequences count as written, not decoded |
| JSON lexical tokens | 1,000,000 per text | Containers, keys and scalar values counted before construction; duplicate keys also count |
| JSON text nesting | 1,024 open containers | Checked before recursive parsing; strings/escapes do not affect depth |
| CLI input | 16 MiB of bytes | Bounded read, strict UTF-8, optional BOM |
| Batch requests | 10,000 | Exceeding this rejects the whole batch |
| Batch compile reuse | One expression, at most 1,024 UTF-16 units | Batch-local, successful compilations only. Longer expressions are compiled normally under the same parser limits |
| Successful batch responses combined | 500,000 nodes / 8,388,608 estimated UTF-16 units | Includes pretty formatting and wrapping; excess becomes an individual item error |
| Batch error messages | 128 UTF-16 units plus ... if truncated | Bounded errors remain possible after the success budget is exhausted |

JSON text parsing now preflights the budgets above in constant extra space,
then normalizes valid long numeric tokens before the pinned core parser
checks document grammar and decoding. The extra normalization pass is linear
in bounded text size and allocates a replacement document only when a long
number changes; the lexical allocation preflight itself remains constant-space. The same path
serves search_json, CLI batch input and expression JSON literals/quoted identifiers.
The public parse_json_bounded API applies transport budgets, not the per-query
depth/node limits. Thus a valid batch retains independent item checks.
Expression JSON literals are subject to both checks. Errors from either check
report the opening backtick's Unicode scalar offset.
Invalid or excessively nested **whole batch
text** cannot be split reliably and fails at the CLI transport boundary. In a
valid parsed batch, requests are checked independently. The outer response
array and `{ok,result}` count toward depth: a too-deep result becomes an item
error before printing the batch.

The result-element budget accumulates entries constructed by query operators
and functions, including intermediate collections. For example,
`[::2] | length(@)` on four array items consumes four entries: two in
the slice and two in its projection. Overwriting a key in the same object
keeps one key entry, while collections evaluated for each value add their
own entries. A projection omitting every null result can succeed with a zero
result budget. Returning an existing input collection also succeeds without
constructing entries. Container literal copies charge their visited nodes to
the work budget; input, literal and result shape checks limit expanded JSON
regardless of result-element counting.

Each request starts with fresh evaluation state. A rejected large response
does not consume the success budget, allowing later smaller responses to fit.
Identical shared results are charged again for each successful response,
including their wrapper, escaped keys and pretty-format estimate. At the
inclusive cumulative limit the current response succeeds; a rejected response
leaves both success counters available for later smaller results. Bounded error
replies use the reserved space outside the success budget.
If no success budget remains, later requests may also get `limit_exceeded`.
Logical work is not a CPU instruction counter: other core string routines and
shape preflight have bounded inputs but are not charged per machine instruction.

Ordinary functions evaluate arguments from left to right before checking their
count or types. Each visited function/argument AST node costs one step. Thus
`not_null(a,length(b))` still evaluates `length(b)` when `a` is non-null;
an argument error stops later arguments and can precede an outer arity error.
Logical operators charge only branches they execute. String `length` charges
one step per Unicode scalar; array/object length uses the immediate member
count without traversing child values. `type` and `not_null` add no work beyond
their AST/argument visits. These existing rules have independent boundary
checks described in [work-budget verification](work-budget-checks.md).

Since 0.1.10 ordering type scans charge one step per element; comparisons charge
one step plus one per Unicode iterator advance for strings. Sorting charges
two steps per element before allocating scratch copies and one per merge write.
The stable bottom-up merge sort propagates comparison errors immediately and
does not mutate caller data. sort/min/max and their _by variants share the
budget. The current repository source caches one key per input item. `sort_by`
sorts input indexes, while `min_by` and `max_by` track the selected index.
Scratch storage is O(n); this is not a wall-clock or memory sandbox.
Long common prefixes or large legitimate sorts may now exceed max_steps where
earlier versions succeeded. Trusted callers may choose a higher valid budget;
untrusted callers should retain bounded operation. Exhaustion remains an
isolated per-item limit_exceeded error in a decoded batch.

Since 0.1.5, `to_number` scans string characters against a scalar-number alphabet
before calling the JSON parser and charges each scanned character to max_steps.
The first forbidden Unicode scalar is also charged before returning null;
only fully valid JSON-number grammar can produce a numeric value. Since
0.1.33, tokens at least 1,024 UTF-16 units long are normalized before numeric
conversion, using an exponent cap based on the entire token length. This fixes
fixed-cap exponent cancellation in the pinned core without changing short
number representations or dropping significant digits. Overflow still reaches
the existing invalid_value guard; order -324 and 308 still use exact binary64
rounding. The same repair protects bounded JSON input and numeric repr checks.
Non-numeric arrays/objects encoded as strings return null without materializing
their contents. Extremely long numeric strings can now return limit_exceeded.

The roughly 12 MB escaped-string crash left open in 0.1.5 is now rejected before
decoding by the string-token budget. Very wide texts are rejected by the lexical
token budget, including duplicate object keys. These additional restrictions can
reject some inputs previously accepted within the overall 16 MiB byte cap.
They intentionally bound decoder work; they do **not** guarantee a universal
192 MiB peak heap. Host memory exhaustion remains uncatchable as a per-item error.
Applications still need appropriate ingress and worker memory/time controls.
An oversized transport returns limit_exceeded for the whole command (exit 2,
empty stdout), rather than pretending to preserve undecoded batch items.

Use `stringify_bounded` to serialize library results. It validates and renders
the same value. Mutating returned JSON and invoking a different serializer is
outside that guarantee. Non-finite numbers fail with `invalid_value` rather
than becoming invalid JSON text. These are resource/representation limits,
not JMESPath syntax extensions.

Since 0.1.9 each evaluated scalar result must be finite before its parent runs.
Previously `type(sum(@))` or a comparison could conceal an overflow that direct
`sum(@)` correctly rejected. Such queries now consistently return invalid_value.
The check does not evaluate skipped boolean branches. Floating-point operations
remain IEEE binary64. Since 0.1.21, `avg` rescans the array
using scaled addition with rounding residuals if the running sum overflows.
The additional pass charges for each element and each residual visited.
`sum` still reports a non-finite result as `invalid_value`.

## JSON conversion work

Since 0.1.35, each non-string `to_string` call validates its input with the
existing compact JSON preflight, then charges the resulting conservative
UTF-16 output estimate to max_steps **before** constructing the serialized
string. Reusing the same object or array pays again on every conversion.
This prevents cheap repeated conversion of shared escaped input from
allocating many large strings before the final result-size check.

Existing String arguments are returned directly and pay only their visited
AST nodes. The separate `stringify_bounded` API keeps its shape/output
preflight; it does not run inside an evaluator work state.

These are estimate units, not exact output characters:

| JSON value | Additional conversion work |
| --- | --- |
| Number without repr | 32 |
| Number with validated repr | repr UTF-16 length |
| Null or Boolean | 5 |
| String nested in a container | length + 2; add 5 per control unit, 1 per quote/backslash/slash |
| Array | 2 + one separator unit per member + each member estimate |
| Object | 2 + each key string estimate + 3 per member + each value estimate |

For `to_string(@)`, add two AST visits to these estimates. Thus null costs
7 steps, an ordinary number 34, an empty array 4, `[null]` 10 and
`{"x":1}` 42. A top-level String remains a two-step identity call. Function
arguments are still evaluated eagerly before arity checks; preflight size,
depth and representation errors precede this new serialization fee.
The preflight remains a bounded traversal, rather than a step-by-step CPU
deadline. Resource budgets do not guarantee a universal heap bound.

Large non-string conversions that formerly fit the same max_steps may now
return limit_exceeded. Trusted callers can set a larger valid work limit;
that does not replace host memory/time controls. The reproduced regression
maps 64 copies of a 512 Ki-unit NUL payload through to_string. Under the
default budget it now reports max_steps before allocating the first escaped
copy, preserving the valid neighboring batch replies.

`join` keeps its existing fee: one step for each visited array element,
including the first invalid element, after argument/type/arity checks.
It performs its complete type, size and work preflight before constructing
output; the construction pass is covered by that fee. It does not charge
max_results for a string result. Separator and text size checks use UTF-16
units, and final output escaping can impose a stricter size limit.

## Regression inputs

- 4,000 exclamation marks plus @: the September parser failure.
- 255 nested to_array calls: the separately reproduced October evaluator crash.
- Thirty [@,@] stages: exponential output expansion despite a small syntax tree.
- Expanded results passed to to_string, equality and contains.
- 64 repeated escaped to_string conversions of a 512 Ki-unit NUL payload,
  preserving batch neighbors under a 192 MiB test old-space limit.
- A large join separator, deep JSON data/literals, non-finite arithmetic, and
  cumulative large batch results followed by a small normal request.

`node scripts/verify.mjs` runs both debug and release subprocesses. The
adversarial harness uses a 15-second timeout and a 192 MiB V8 old-space cap.
Those are harness safeguards, not implied runtime features of the CLI.

Since 0.1.11 string length charges one step per Unicode scalar and uses constant
extra space. String reverse charges its UTF-16 length before allocating output
and builds it using reverse Unicode iteration, avoiding character arrays.
Supplementary characters cost two units for reversal but count as one for length.
Arrays/objects retain their existing length semantics. Large valid strings can
now exhaust max_steps; increasing it for trusted input does not guarantee peak
memory safety. The 8-million-character reverse heap regression is checked in
both modes with valid batch neighbors.

Since 0.1.14 caller-supplied numeric repr must be a standalone JSON numeric
lexeme whose parsed binary64 value matches the stored finite Double. Non-numeric
characters (including surrounding whitespace), invalid grammar and mismatches
return invalid_value. The output budget is charged before scanning/parsing.
Validation uses the existing shape-preflight budget, not max_steps; matching
large-integer spelling is retained, without promising exact decimal arithmetic.
This protects direct library construction; normal parsed JSON cannot attach an
arbitrary separate repr.
