# Work-budget property verification

The complete `node scripts/verify.mjs` command builds a test-only executable
and runs this suite in debug and release. It also tests the independent model,
failure handling and replay evidence. Production CLI options are unchanged.

For a focused run, build the matching artifact first:

```sh
moon build test_support/work_budget --target js
node scripts/work-budget-properties.mjs
moon build test_support/work_budget --target js --release
node scripts/work-budget-properties.mjs --release
```

The deterministic seed is `0x20261206`. There are 11,264 generated scenarios
and 186 explicit reference cases. Each checks one step below, at and above its
required budget: **34,350 boundary queries per mode**. Summaries record the
actual batch count and two valid before/after neighbors for each batch.
Every corpus scenario needs at least two steps, so its lower probe is a valid
positive budget. A bare field/current node or a zero-argument function call
can cost one step. Such models can be probed at budget one, but budget zero
is invalid configuration.

Canonical JSON independently determines equality. A recursive visit model
determines work, without using the library's cursor implementation:

| Operation | Work |
| --- | --- |
| Each visited AST node | 1 |
| Each compared value pair | 1 |
| Two compared strings | Additional maximum of their UTF-16 lengths |
| Equal-length arrays | Children until the first mismatch |
| Same-size objects | Left keys in transmitted order; key UTF-16 length before right lookup; child work only for existing keys |
| `==`, `!=` | Evaluate left, then right, then comparison work |
| Array `contains` | Evaluate arguments; each candidate adds 1 plus comparison work, stopping on a match |
| String `contains` or invalid types | Evaluate arguments before result/type checking |
| `&&`, `\|\|` | Evaluate left and right only when needed; preserve the selected JSON value |
| `!` | Evaluate its operand, then negate its JMESPath truth value |
| `\|` | Evaluate left, then right with the left result as current data |
| Ordinary functions | Visit the function node, then evaluate every argument left to right, stopping on the first error |
| `not_null` | Select the first non-null argument value after all arguments succeed; no additional work |
| `type` | Return the JSON type label after argument evaluation; no additional work |
| `join` | One extra step per visited array element, including the first invalid one; no character work |
| String `length` | One extra step per Unicode scalar, without normalization |
| Array/object `length` | Return the immediate member count; no per-child work |
| String `reverse` | Charge the UTF-16 length before copying; reverse Unicode scalars |
| Array `reverse` | No extra work steps; copy the immediate elements in reverse order and charge `max_results` |
| String `to_number` | One extra step per scanned Unicode scalar, including the first rejected scalar |
| Other `to_number` inputs | Numbers keep their numeric value; other JSON types return null; no additional work |

The bounded grammar supports `a`, `b`, `@`, parentheses, `!`, `==`, `!=`, `&&`, `||`, `|`
and calls to `contains`, `not_null`, `type`, `length`, `reverse`, `to_number` and `join`.
An independent precedence-layer parser validates the whole expression,
including skipped branches. Expressions are bounded to 512 characters,
128 tokens, 96 AST nodes and 64 nested grammar entries. This remains a
verification subset, not a second complete query-language implementation.

Function arity is checked after arguments succeed. `contains` and `join` expect two;
`type`, `length`, `reverse` and `to_number` expect one; `not_null` expects
at least one. Validly parsed calls with a wrong count produce `invalid_arity`
only if execution reaches that check. An inner argument error can precede an
outer arity error. For example, `length(a,length(b))` with null `b` fails at
the inner type check after four AST visits, before the outer count is checked.
With a smaller budget, work exhaustion must be reported first.

Only null, false, empty string, empty array and empty object are false.
Numbers including zero are true. Logical operators return the selected
operand and keep the original input on their right side. Pipes change that
input, including to null. Ordinary functions evaluate their arguments before
dispatch; `not_null(a,length(b))` therefore evaluates the second argument
even when `a` is non-null. A string such as `月😀` has two scalar length
steps, while equality and string reversal charge three UTF-16 units.
Reversal preserves surrogate pairs, but reverses combining marks and joiners
as separate scalars; it does not preserve grapheme clusters or normalize text.
Array reversal creates a new outer array, preserving later uses of the
original operand and results selected before another argument is evaluated.
See [function evaluation](https://jmespath.org/specification.html#function-expressions),
[the reference evaluator](https://github.com/jmespath/jmespath.py/blob/develop/jmespath/visitor.py)
and [length semantics](https://jmespath.org/specification.html#length).

Numeric conversion scans only ASCII digits, space, tab, line feed, carriage
return, `+`, `-`, `.`, `e` and `E`. It charges and returns null at the first
other scalar, leaving the remaining suffix unvisited. A numeric-looking
prefix such as `1e309` followed by `x` therefore returns null rather than
overflowing. If every scalar passes, a complete JSON-number grammar check
precedes numeric conversion: leading/trailing ASCII whitespace is accepted,
while `+1`, `01`, incomplete exponents and embedded whitespace return null.
Unicode whitespace is rejected by the scanner. The independent model uses
that grammar and host binary64 conversion, rather than the MoonBit JSON
parser's conversion implementation.

A parsed non-finite numeric result raises `invalid_value` at the conversion
node, before an outer `type`, `not_null` or wrong-arity call can hide it.
The fixed corpus includes `"0." + "0".repeat(65227) + "1e655360"`: its
65,237 scanned ASCII scalars require 65,239 steps, then produce `invalid_value`.
It remains inside the model's string bounds. Budget 65,238 must fail with
work exhaustion first. Conversion-produced negative zero is kept internally;
the final modeled numeric result is positive zero, matching the harness's
JSON output. This differs from comparing a raw JS `JSON.parse("-0")` result.

Model-side coverage has 38 counters. It records both decisions of logical
branches, pipes, negations, null selection, function entry/type branches,
argument and arity failures, reversal copies, numeric scan outcomes,
scanned scalars and join outcomes/visited elements/output units. Final scenario outcomes are Boolean results, other JSON
results, `invalid_type`, `invalid_arity` or `invalid_value` errors. Their
five counts must sum to the scenario count. Arity errors must match final
invalid-arity outcomes, and numeric overflows must match final invalid-value
outcomes. These counters describe model traces, not instrumented production
coverage. Full verification requires every category and matching debug/release
counts and corpus hashes. Only executed argument visits and string scans
count; errors stop later arguments.

## join semantics and model domain

The model evaluates all ordinary arguments from left to right before checking
join's two-argument count, separator String type and array type. It adds one
step for every visited array element, including the first non-string element.
A bad element does not add a separator or output text. Empty arrays add no
element work; separators and text lengths do not add character work.

Semantic concatenation uses the host string-array join after an independent
type/prefix-length calculation. It preserves empty strings, NUL, quotes,
backslashes, combining marks and supplementary characters. Nested reversal,
length, numeric conversion, eager functions, logical branches and pipes
check composition and error priority.

For this verification subset, each **executed** join's valid string prefix
must fit 65,536 UTF-16 units, including separators between valid items.
The model rejects a larger prefix even if a later array element is invalid,
so another size limit cannot replace the modeled work/type outcome. It does
not inspect skipped branches. Unused separators on empty/single-item arrays
do not increase output size. A rejected domain input fails verification;
it is not counted as a successful SUT check.

This is a conservative model bound, not a new library limit. Public-API
regressions accept join outputs of 65,535, 65,536 and 65,537 UTF-16 units at
their exact work fee, with zero materialized-result budget. Another regression
uses type(join(a,b)) to observe an inclusive 16,777,216-unit intermediate
without serializing it. One more separator triggers the existing join size
guard; an invalid next element keeps type-error priority, while lower work
budgets fail before either check. Production resource limits are unchanged.

Six counters trace join entry, success, argument-type failure, element-type
failure, visited elements and output UTF-16 units. Their totals describe the
corpus, not one query's limit or instrumented production coverage.

The root data object must contain exactly its own `a` and `b` fields.
Their finite JSON values share an 8,192-node bound, with depth at most 128
and at most 65,536 UTF-16 units per string/key. Strings and keys must contain
well-formed UTF-16, matching the harness's strict JSON decoding.
Extra root fields are rejected instead of being sent without modeling
their shape. Inputs are validated before the JSON wire round trip;
the round trip normalizes input negative zero and fixes member order.
Canonical key sorting is used only for semantic equality; comparison work
uses transmitted key order and own-key lookups for special names.
Shared references cannot survive JSON transport; the MoonBit mutation
and shared-reference regressions remain.

Within one modeled query, executed array reversals may copy at most 100,000
elements cumulatively. The model explicitly rejects inputs exceeding this
bound, keeping work-budget probes independent of the library's default
`max_results` limit; the harness does not raise that limit. Empty arrays add
zero, skipped branches add nothing, and evaluated arguments add their copies
even when an earlier non-null value will be selected. The accumulated count
resets for every interpretation. For example, twenty reversals of a
5,000-element array are allowed, while twenty-one are outside the model domain.
`arrayElementsCopied` in a corpus summary totals copies across its scenarios;
the 100,000 bound applies separately to each query.

The harness receives only expressions, data and budgets; expectations stay
in the controller. Full verification removes the prior executable, requires
a nonempty rebuilt artifact and records its SHA-256. It overrides inherited
`JMES_WORK_BUDGET_PATH`; standalone runs require the matching prebuilt artifact.

Summaries and failure inputs are stored under `_build/`. A failure saves
the active cases; use its path to replay:

```sh
node scripts/work-budget-properties.mjs --replay _build/work-budget-debug-failure.json
```

Replay recomputes expectations and compares complete JSON results. Its report
uses a new directory under `_build/replays/` so full-run evidence remains
intact. `baseCorpusHash` identifies the fixed generated corpus;
`corpusHash` identifies the modeled cases selected for that run.
Replay files are limited to 8 MiB; the runner splits by at most 200 modeled
requests plus neighbors, input bytes and a conservative 1 MiB response estimate.
A single request/result exceeding harness bounds is explicitly rejected.
Invalid inputs, protocol or results fail verification rather than producing
a passing report.
