std: arbitrary<T>() test data from types, and check() with shrinking #15

Merged
sionzee merged 3 commits from std-arbitrary into main 2026-11-04 21:28:36 +01:00
Owner

What

arbitrary<T>() from a new std module, @evobug/safe-ts-std/arbitrary, is rewritten at build time into a generator for T. It uses the type model parseJson<T> already has (crates/safe_ts_core/src/json.rs). check(arb, property, { runs, seed, maxShrinks }) runs a property and returns a Result: { runs, seed }, or an Err with the first failing value (shrunk), the original value, the seed, the run, the cause and a readable message for assert.fail.

  • Transform: a third call kind next to parseJson/validate. arbitrary<User>() becomes __arbitraryWith<User>(__g0), and the generator functions are added at the end of the file. As with validators, line numbers don't move, the type argument is kept (so tsc checks that the generated type fits), and the __T types are shared when one file uses both.
  • Types: the ones json-type accepts: primitives, literals, objects/interfaces (including extends), optional keys, readonly arrays and tuples, unions, Option, Enum (every variant), SafeInt, bigint, and generic and recursive aliases. Unsupported types get the same json-type diagnostics with an `arbitrary<T>`: prefix. One new error: a type whose every value contains another one (type Loop = { next: Loop }).
  • Edge values come up often: "", 4000-character strings, non-ASCII, astral and ZWJ characters, 0, -0, ±MAX_SAFE_INTEGER, MAX_VALUE/MIN_VALUE, 64-bit bigint limits, empty arrays, missing optional keys. Numbers are always finite. Strings never contain lone surrogates. An optional key is either absent or holds a value, as in parseJson output.
  • Deterministic per seed: uses the existing Rng.seeded (mulberry32). If no seed is given, check picks a random one and reports it.
  • Recursion: union members are ordered by how fast they finish (a fixpoint "height" over named types). Past a depth limit, a union takes member 0, arrays are empty and optional keys absent, so recursive types always end.
  • Shrinking is implemented. It works on the recorded choice sequence, in the style of Hypothesis: every value is recorded in one canonical form (magnitude+sign, decimal digits, code-point ranks, item flags). The edge-value bias is generation-only and not recorded. Shrinking cuts the tail, deletes and zeroes runs of choices, and lowers single choices (0, then an upward probe, then binary search). It is bounded by maxShrinks property calls (default 1000), and the choice list only gets shortlex-smaller.

Tests

  • packages/std/test/arbitrary.test.ts (14 tests):
    • Self-test: generated values pass parseJson<T> for the same T and come back equal (-0 normalised), for Person, Admin, Shape, Tree, Page<Point>, Contact, a large Account type and a recursive JSON-like Enum.
    • Determinism per seed, and that every edge value, variant and literal comes up.
    • Shrinking to exact boundaries across 20 seeds each: 10, -3, 1e6, 10n**20n, "aaaaa", [true], { tag: "Rect", w: 0, h: 0 }, and the simplest Account.
    • Thrown, Err and async properties; maxShrinks: 0; the code-point rank bijection.
  • crates/safe_ts_core/tests/transform.rs: the exact generated code for a small recursive type, union ordering, sharing types with parseJson, and all the rejections.
  • tests/fixtures/json/main.ts: arbitrary lines for the checker path, including that a discarded arbitrary<T>() is not must-use-result.
  • typecheck:emit now also emits arbitrary.test.ts and runs tsc on the generated code.
  • I ran the four ts good examples in the new guide as real node:test files. The buggy average fails as the page describes, and the others pass.

Results, after rebasing onto main at 1fe2d1d (head below):

  • cargo nextest run --workspace: 108/108 pass.
  • npm run test:std: 145/145 pass. That includes arbitrary.test.ts under the Node loader's dev checks (on by default), and the new dev-checks test. arbitrary.test.ts also passes 14/14 with SAFE_TS_DEV_CHECKS=1 and =0.
  • npm run test:vite, npm run typecheck, npm run test:docs (docs examples, wasm, VitePress build): pass.
  • node scripts/verify-packages.mjs (packs .release/, installs the tarballs into a fresh project from the npm registry): all checks pass, including the new arbitrary ones.
  • npm run bench:check: passed in 2 of 4 runs. In the other two, bench: match / switch, through the transform was 2.01x against an allowed 1.92x. That ratio measures match rewriting, which this PR doesn't touch: the new code only runs when arbitrary is imported from the arbitrary module, and match.bench.ts doesn't import it. The machine was under heavy load at the time (load average 37–46, other builds running). I didn't update the baseline.

What changed in the rebase

  • Two conflicts. In packages/std/package.json, ./arbitrary was added after ./array next to #12's files/publishConfig. In tests/transform.rs, #10's dev-check tests and the arbitrary tests are now both kept.
  • npm build (#12): scripts/build-packages.mjs compiles std from its exports, so ./arbitrary is built into .release/std/dist/arbitrary.{js,d.ts} with no change to the script. scripts/verify-packages.mjs now checks arbitrary the way a user gets it:
    • the built JavaScript without the transform: check() runs, and an untransformed arbitrary<T>() throws "was not compiled";
    • tsc against the published declarations;
    • the Vite build with check: "error": the bundle contains no "was not compiled", and check(arbitrary<Status>(), ...) runs;
    • the Node loader, which has dev checks on.
  • Dev checks (#10): they skip std files, and the generated generators contain nothing they wrap (no q, match or comparators). A dev check that fails inside a property is caught by check() like any throw, so it becomes a counterexample and is shrunk. A new test in packages/std/test/dev-checks.test.ts covers this: a comparator that returns NaN for a missing price fails check() across 5 seeds and shrinks to [{ name: "" }, { name: "" }]. With SAFE_TS_DEV_CHECKS=0 the same property passes. The testing guide now says so.
  • docs/guide/std-helpers.md (new on main with #6) now lists the module, linking to the testing guide.

Docs

  • New guide docs/guide/testing.md, with checked examples (good, bad must-use-result, bad json-type), in the sidebar under "Everyday code" and in docs/README.md.
  • The README std table, the rule table row, and a short paragraph after the JSON section.
  • docs/rules/json-type.md and docs/guide/json.md link to the new guide.

Left out / uncertain

  • No records or dicts: json-type doesn't accept Record or index signatures yet ("index signatures are not supported yet"), so arbitrary doesn't either. It will follow when parseJson gains them.
  • No combinators (map/filter/oneOf), no custom generators, no async properties (a property that returns a promise fails with a message saying so), and no stateful testing.
  • Shrinking finds a local minimum. For example, a string of astral characters can stay astral when replacing one with a would change its UTF-16 length and make the property pass. The guide says so.
  • Reproducing a failure needs both seed and runs, because the size of each run depends on runs.
  • arbitrary is not in the prelude.

🤖 Generated with Claude Code

## What `arbitrary<T>()` from a new std module, `@evobug/safe-ts-std/arbitrary`, is rewritten at build time into a generator for `T`. It uses the type model `parseJson<T>` already has (`crates/safe_ts_core/src/json.rs`). `check(arb, property, { runs, seed, maxShrinks })` runs a property and returns a `Result`: `{ runs, seed }`, or an `Err` with the first failing value (shrunk), the original value, the seed, the run, the cause and a readable `message` for `assert.fail`. - **Transform:** a third call kind next to `parseJson`/`validate`. `arbitrary<User>()` becomes `__arbitraryWith<User>(__g0)`, and the generator functions are added at the end of the file. As with validators, line numbers don't move, the type argument is kept (so tsc checks that the generated type fits), and the `__T` types are shared when one file uses both. - **Types:** the ones `json-type` accepts: primitives, literals, objects/interfaces (including `extends`), optional keys, readonly arrays and tuples, unions, `Option`, `Enum` (every variant), `SafeInt`, `bigint`, and generic and recursive aliases. Unsupported types get the same `json-type` diagnostics with an `` `arbitrary<T>`: `` prefix. One new error: a type whose every value contains another one (`type Loop = { next: Loop }`). - **Edge values come up often:** `""`, 4000-character strings, non-ASCII, astral and ZWJ characters, `0`, `-0`, ±`MAX_SAFE_INTEGER`, `MAX_VALUE`/`MIN_VALUE`, 64-bit bigint limits, empty arrays, missing optional keys. Numbers are always finite. Strings never contain lone surrogates. An optional key is either absent or holds a value, as in `parseJson` output. - **Deterministic per seed:** uses the existing `Rng.seeded` (mulberry32). If no seed is given, `check` picks a random one and reports it. - **Recursion:** union members are ordered by how fast they finish (a fixpoint "height" over named types). Past a depth limit, a union takes member 0, arrays are empty and optional keys absent, so recursive types always end. - **Shrinking is implemented.** It works on the recorded choice sequence, in the style of Hypothesis: every value is recorded in one canonical form (magnitude+sign, decimal digits, code-point ranks, item flags). The edge-value bias is generation-only and not recorded. Shrinking cuts the tail, deletes and zeroes runs of choices, and lowers single choices (0, then an upward probe, then binary search). It is bounded by `maxShrinks` property calls (default 1000), and the choice list only gets shortlex-smaller. ## Tests - `packages/std/test/arbitrary.test.ts` (14 tests): - **Self-test:** generated values pass `parseJson<T>` for the same `T` and come back equal (`-0` normalised), for `Person`, `Admin`, `Shape`, `Tree`, `Page<Point>`, `Contact`, a large `Account` type and a recursive JSON-like `Enum`. - Determinism per seed, and that every edge value, variant and literal comes up. - Shrinking to exact boundaries across 20 seeds each: `10`, `-3`, `1e6`, `10n**20n`, `"aaaaa"`, `[true]`, `{ tag: "Rect", w: 0, h: 0 }`, and the simplest `Account`. - Thrown, `Err` and async properties; `maxShrinks: 0`; the code-point rank bijection. - `crates/safe_ts_core/tests/transform.rs`: the exact generated code for a small recursive type, union ordering, sharing types with `parseJson`, and all the rejections. - `tests/fixtures/json/main.ts`: `arbitrary` lines for the checker path, including that a discarded `arbitrary<T>()` is not `must-use-result`. - `typecheck:emit` now also emits `arbitrary.test.ts` and runs tsc on the generated code. - I ran the four `ts good` examples in the new guide as real `node:test` files. The buggy `average` fails as the page describes, and the others pass. Results, after rebasing onto main at 1fe2d1d (head below): - `cargo nextest run --workspace`: 108/108 pass. - `npm run test:std`: 145/145 pass. That includes `arbitrary.test.ts` under the Node loader's dev checks (on by default), and the new dev-checks test. `arbitrary.test.ts` also passes 14/14 with `SAFE_TS_DEV_CHECKS=1` and `=0`. - `npm run test:vite`, `npm run typecheck`, `npm run test:docs` (docs examples, wasm, VitePress build): pass. - `node scripts/verify-packages.mjs` (packs `.release/`, installs the tarballs into a fresh project from the npm registry): all checks pass, including the new arbitrary ones. - `npm run bench:check`: passed in 2 of 4 runs. In the other two, `bench: match / switch, through the transform` was 2.01x against an allowed 1.92x. That ratio measures `match` rewriting, which this PR doesn't touch: the new code only runs when `arbitrary` is imported from the arbitrary module, and `match.bench.ts` doesn't import it. The machine was under heavy load at the time (load average 37–46, other builds running). I didn't update the baseline. ### What changed in the rebase - Two conflicts. In `packages/std/package.json`, `./arbitrary` was added after `./array` next to #12's `files`/`publishConfig`. In `tests/transform.rs`, #10's dev-check tests and the arbitrary tests are now both kept. - **npm build (#12):** `scripts/build-packages.mjs` compiles std from its `exports`, so `./arbitrary` is built into `.release/std/dist/arbitrary.{js,d.ts}` with no change to the script. `scripts/verify-packages.mjs` now checks arbitrary the way a user gets it: - the built JavaScript without the transform: `check()` runs, and an untransformed `arbitrary<T>()` throws "was not compiled"; - tsc against the published declarations; - the Vite build with `check: "error"`: the bundle contains no "was not compiled", and `check(arbitrary<Status>(), ...)` runs; - the Node loader, which has dev checks on. - **Dev checks (#10):** they skip std files, and the generated generators contain nothing they wrap (no `q`, `match` or comparators). A dev check that fails inside a property is caught by `check()` like any throw, so it becomes a counterexample and is shrunk. A new test in `packages/std/test/dev-checks.test.ts` covers this: a comparator that returns `NaN` for a missing `price` fails `check()` across 5 seeds and shrinks to `[{ name: "" }, { name: "" }]`. With `SAFE_TS_DEV_CHECKS=0` the same property passes. The testing guide now says so. - `docs/guide/std-helpers.md` (new on main with #6) now lists the module, linking to the testing guide. ## Docs - New guide `docs/guide/testing.md`, with checked examples (good, `bad must-use-result`, `bad json-type`), in the sidebar under "Everyday code" and in `docs/README.md`. - The README std table, the rule table row, and a short paragraph after the JSON section. - `docs/rules/json-type.md` and `docs/guide/json.md` link to the new guide. ## Left out / uncertain - **No records or dicts:** `json-type` doesn't accept `Record` or index signatures yet ("index signatures are not supported yet"), so `arbitrary` doesn't either. It will follow when `parseJson` gains them. - No combinators (`map`/`filter`/`oneOf`), no custom generators, no async properties (a property that returns a promise fails with a message saying so), and no stateful testing. - **Shrinking finds a local minimum.** For example, a string of astral characters can stay astral when replacing one with `a` would change its UTF-16 length and make the property pass. The guide says so. - **Reproducing a failure needs both `seed` and `runs`,** because the size of each run depends on `runs`. - `arbitrary` is not in the prelude. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
sionzee force-pushed std-arbitrary from d15ebdf77d to ab18627dd2
All checks were successful
Benchmarks / bench (pull_request) Successful in 1m46s
2026-11-03 23:43:44 +01:00
Compare
Merge main into std-arbitrary
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m39s
7cf57af9c1
Resolve conflicts with the PRs merged before this one: both sides kept
(rule lists, std exports, package checks, CLI usage, README).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch std-arbitrary 2026-11-04 21:28:36 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!15
No description provided.