@ultimat3/testing 31.16.0 → 31.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -52,6 +52,7 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
52
52
  | Fixtures | the preload registers the framework bag — an app registers only what it alone knows: `seed` as `seedFixture({ seeds, driver })` (`fixture-seed.ts`: once per test per name, rows captured on the way in, picked by label), `actorFor` |
53
53
  | Every `e2eTest` is audited | `e2e-a11y*.ts`, `ax-node.ts`; no switch, `allow` needs a `because` † |
54
54
  | The exercise pass runs what is registered | `exercise.ts` (`runExercisePass`): every action, query, job once, own tenant pair; overrides only via `defineExercise` † |
55
+ | A route `load` is exercised like a read | `exercise-route-loads.ts`: after the primitives, own tenant pair, swept and planned with them; its record is `RouteLoadRecord`, never in `records`; the crash proof's runs pace on the frozen clock (`exercise-crash.ts`) |
55
56
  | An override `input` is awaited, as the call's actor | `exercise-override-input.ts`: inside the call's own request — the one way to a signed input † |
56
57
  | A passkey test signs for real | `softAuthenticator` is `@ultimat3/auth/soft-authenticator`'s, never re-exported here (one value, one path: `flight-copies`) and never a second one (auth's own suites need it, and auth cannot import testing) |
57
58
  | A reached job is crash-proven | `exercise-crash.ts`: only `diverged` is red (`X_JOB_CRASH_DIVERGED`) † |
@@ -123,6 +124,12 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
123
124
  | Globals install in layers | `island-globals.ts`: a key's real DESCRIPTOR is saved by the first live mount, restored by the last, in any dispose order |
124
125
  | Which command shards | `bun test` is one process on one database — what a scaffolded app's `test` script runs |
125
126
 
127
+ ## Properties and the soak never read ambient randomness
128
+
129
+ `property()` draws from its own `seededRandom(seed)`, never the preload's `Math.random`; `soak()`
130
+ reads `bun:jsc`'s `heapStats()` after `Bun.gc(true)` twice. The eight framework properties live in
131
+ `src/property-*.test.ts`, not beside their sources: a tier ≤ 4 test cannot import this package.
132
+
126
133
  ## The frozen instant and the seed are screened
127
134
 
128
135
  Through one `instantMs` and core's `finiteOption`/`finiteCount` (`determinism-bounds.test.ts`). Full rule: `docs/history/testing.md`.
package/README.md CHANGED
@@ -38,6 +38,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
38
38
  | `seed-graph-error.ts` | `X_SEED_GRAPH_UNSATISFIED`, its fix naming the `defineFactory` to write; `X_SEED_GRAPH_ENTITY_UNKNOWN`, a plan and a writer built from two entity sets |
39
39
  | `seed-writer.ts` | `entitySeedWriter({ entities, client })` or `({ entities, driver? })` — the `SeedWriter` that writes a graph through each entity's own repository: Postgres or PGlite through a client, or a driver. `@ultimat3/entity` loads on the first write. `snapshot(rows)`, required on every `SeedWriter`, reads rows back as one digest each (`md5(t::text)` over a client), `null` for a row gone |
40
40
  | `exercise.ts` | `runExercisePass({ entities, writer, roles, seed?, overrides?, only? })` — every registered action, query and job once, each on its own committed tenant pair, one `ExerciseRecord` per primitive, the tenant proof's verdict on its `tenant`. What `x exercise` runs |
41
+ | `exercise-route-subjects.ts` · `exercise-route-loads.ts` | `routeLoadSubjects()` — every `app/`/`site/` file route with a `load`; handed to `runExercisePass({ …, routes, onRoutes })`, each load runs after the primitives in a tenant pair of its own (an `:id` bound to a seeded row, else the route's `prerender()` sample), one `RouteLoadRecord` each with the statement ceiling, scale and plan proofs |
41
42
  | `define-exercise.ts` | `defineExercise({ <name>: { actor, input?, runs? } \| { off: '<why>' } }, { actor?: <entity>, factories?: { <entity name>: defineFactory(…) }, setup?: () => mockFetch(…) \| cassette(…) })` — an app's overrides (the second argument names the entity whose rows are the actors, and the factories that build a table no generated row satisfies — a cross-column `satisfies` — keyed by entity name, unknown ones `X_DECLARATION_UNKNOWN`), `apps/web/exercise.ts`'s one export; a blank `off` is `X_CONTRACT_EXERCISE_UNDECLARED`, an unknown name `X_DECLARATION_UNKNOWN` when the pass runs. An entry's `statements: { max, why }` moves that primitive's statement ceiling (a blank `why` is `X_CONTRACT_EXERCISE_UNDECLARED`, `max` a whole count ≥ 1) |
42
43
  | `exercise-setup.ts` | `withExerciseSetup(room, setup)`: the app's `setup` run inside the sealed room before the first row, its handle disposed before the room restores the network; an `allowHost` in it is `X_EXERCISE_SETUP_UNSEALED`. Types `ExerciseSetup`, `ExerciseSetupHandle` |
43
44
  | `exercise-actor.ts` · `exercise-input.ts` · `exercise-report.ts` | the first `x policy explain` actor the policy allows, minted in the primitive's tenant · the input: override, then a seeded id by field stem, then the minimal draw (`@ultimat3/schema/sample`, loaded dynamically) · the room one run executes in (network sealed, mail captured, clock frozen) and its record |
@@ -1247,6 +1248,44 @@ still stored, is `X_SUBJECT_ERASE_INCOMPLETE` naming the table and column. A dec
1247
1248
  refuses comes back as its own problems, nothing seeded. `x exercise` runs it for every
1248
1249
  `defineSubject()`, on a scratch database of its own.
1249
1250
 
1251
+ ## A claim over generated inputs
1252
+
1253
+ `property(gen, fn, { runs, seed, maxShrinks })` checks `fn` against `runs` (200) seeded draws. A
1254
+ throw or a `false` fails it as `X_TEST_PROPERTY_FAILED`: the input shrunk by halving to the
1255
+ smallest that still fails, the seed, and a `fix:` whose `{ seed, runs }` replay exactly that draw.
1256
+
1257
+ ```ts
1258
+ import { decodeCursor, encodeCursor } from '@ultimat3/core';
1259
+ import { expect, gen, property, unitTest } from '@ultimat3/testing';
1260
+
1261
+ const position = gen.map(
1262
+ gen.tuple(gen.string({ maxLength: 24 }), gen.string(), gen.array(gen.int(-100, 100))),
1263
+ ([scope, id, key]) => ({ scope, id, key }),
1264
+ );
1265
+
1266
+ unitTest('a cursor round-trips any position', () => {
1267
+ property(position, (payload) => {
1268
+ expect(decodeCursor(encodeCursor(payload), payload.scope)).toEqual(payload);
1269
+ });
1270
+ });
1271
+ ```
1272
+
1273
+ | Fact | Why |
1274
+ |---|---|
1275
+ | the default seed is fixed | the gate never flakes; pass another `seed` to explore |
1276
+ | draw *n*'s size never depends on `runs` | so `{ runs: n }` replays draw *n* |
1277
+ | a promise back is refused (`PropertyAsyncError`) | every draw would pass before its assertion ran |
1278
+ | `gen`: `int` `oneOf` `union` `map` `constant` `array` `tuple` `string` `bytes` `json` | each draw carries its shrinks, so a mapped value shrinks through its source |
1279
+ | the framework's own: `src/property-*.test.ts` | cursor, canonical JSON, money, byte range, cookie, pgoutput, interpolate, `estimateBytes` |
1280
+
1281
+ ## The heap canary
1282
+
1283
+ `soak({ fetch, requests, total, warmup, maxGrowthBytes })` sends `total` (20,000) requests
1284
+ round-robin through an in-process handler after `warmup` (2,000), then compares the live heap after
1285
+ `Bun.gc(true)`: growth past `maxGrowthBytes` is `X_TEST_SOAK_HEAP_GROWTH`. The bound is a
1286
+ measurement — three runs, the largest × 1.5, written beside it. `measureSoak` reports without a
1287
+ verdict. The framework's canary: `src/soak.live.test.ts` (SSR, action, query, 404, 400).
1288
+
1250
1289
  ## Errors
1251
1290
 
1252
1291
  `X_TEST_NETWORK_SEALED` `X_TEST_DB_UNAVAILABLE` `X_TEST_NONDETERMINISTIC` `X_TEST_FIXTURE_UNKNOWN`
@@ -1257,7 +1296,8 @@ refuses comes back as its own problems, nothing seeded. `x exercise` runs it for
1257
1296
  `X_TEST_ISLAND_STATES_AMBIGUOUS` `X_TEST_ISLAND_STATE_ID_INVALID` `X_TEST_ISLAND_STATE_DUPLICATE`
1258
1297
  `X_TEST_ISLAND_STATE_JSON_INVALID` `X_TEST_ISLAND_STATE_CLOCK_INVALID`
1259
1298
  `X_TEST_ISLAND_STATE_STUB_INVALID` `X_SEED_GRAPH_UNSATISFIED` `X_E2E_A11Y_VIOLATION`
1260
- `X_SEED_GRAPH_ENTITY_UNKNOWN` `X_TENANT_LEAK` `X_TENANT_WRITE_CROSSED` — the last two are findings
1299
+ `X_SEED_GRAPH_ENTITY_UNKNOWN` `X_TEST_PROPERTY_FAILED` `X_TEST_SOAK_HEAP_GROWTH`
1300
+ `X_TENANT_LEAK` `X_TENANT_WRITE_CROSSED` — the last two are findings
1261
1301
  `x exercise` returns, never thrown
1262
1302
 
1263
1303
  ### Error classes
@@ -1275,8 +1315,11 @@ a job boundary the class is gone and the `code` is what survives — match on th
1275
1315
  | `NetworkOfflineError` | `X_TEST_NETWORK_OFFLINE` | `src/errors.ts` |
1276
1316
  | `NetworkSealedError` | `X_TEST_NETWORK_SEALED` | `src/errors.ts` |
1277
1317
  | `NondeterministicError` | `X_TEST_NONDETERMINISTIC` | `src/errors.ts` |
1318
+ | `PropertyAsyncError` | `X_TEST_PROPERTY_FAILED` | `src/property.ts` |
1319
+ | `PropertyFailedError` | `X_TEST_PROPERTY_FAILED` | `src/property.ts` |
1278
1320
  | `RegistryLeakError` | `X_TEST_REGISTRY_LEAK` | `src/errors.ts` |
1279
1321
  | `SeedGraphUnsatisfiedError` | `X_SEED_GRAPH_UNSATISFIED` | `src/seed-graph-error.ts` |
1322
+ | `SoakHeapGrowthError` | `X_TEST_SOAK_HEAP_GROWTH` | `src/soak.ts` |
1280
1323
  | `TestDatabaseUnavailableError` | `X_TEST_DB_UNAVAILABLE` | `src/errors.ts` |
1281
1324
 
1282
1325
  ## Log lines under test
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.16.0",
3
+ "version": "31.18.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,26 +47,26 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.16.0",
51
- "@ultimat3/ai": "31.16.0",
52
- "@ultimat3/auth": "31.16.0",
53
- "@ultimat3/cache": "31.16.0",
54
- "@ultimat3/core": "31.16.0",
55
- "@ultimat3/db": "31.16.0",
56
- "@ultimat3/entity": "31.16.0",
57
- "@ultimat3/http": "31.16.0",
58
- "@ultimat3/i18n": "31.16.0",
59
- "@ultimat3/jobs": "31.16.0",
60
- "@ultimat3/mail": "31.16.0",
61
- "@ultimat3/notify": "31.16.0",
62
- "@ultimat3/policy": "31.16.0",
63
- "@ultimat3/pwa": "31.16.0",
64
- "@ultimat3/query": "31.16.0",
65
- "@ultimat3/realtime": "31.16.0",
66
- "@ultimat3/render": "31.16.0",
67
- "@ultimat3/schema": "31.16.0",
68
- "@ultimat3/scraping": "31.16.0",
69
- "@ultimat3/seo": "31.16.0",
70
- "@ultimat3/time": "31.16.0"
50
+ "@ultimat3/action": "31.18.0",
51
+ "@ultimat3/ai": "31.18.0",
52
+ "@ultimat3/auth": "31.18.0",
53
+ "@ultimat3/cache": "31.18.0",
54
+ "@ultimat3/core": "31.18.0",
55
+ "@ultimat3/db": "31.18.0",
56
+ "@ultimat3/entity": "31.18.0",
57
+ "@ultimat3/http": "31.18.0",
58
+ "@ultimat3/i18n": "31.18.0",
59
+ "@ultimat3/jobs": "31.18.0",
60
+ "@ultimat3/mail": "31.18.0",
61
+ "@ultimat3/notify": "31.18.0",
62
+ "@ultimat3/policy": "31.18.0",
63
+ "@ultimat3/pwa": "31.18.0",
64
+ "@ultimat3/query": "31.18.0",
65
+ "@ultimat3/realtime": "31.18.0",
66
+ "@ultimat3/render": "31.18.0",
67
+ "@ultimat3/schema": "31.18.0",
68
+ "@ultimat3/scraping": "31.18.0",
69
+ "@ultimat3/seo": "31.18.0",
70
+ "@ultimat3/time": "31.18.0"
71
71
  }
72
72
  }
package/src/errors.ts CHANGED
@@ -78,6 +78,9 @@ export const TESTING_ERROR_CODES = [
78
78
  'X_TEST_FACTORY_INVALID',
79
79
  'X_EXERCISE_SEED_FAILED',
80
80
  'X_STATEMENTS_OVER_BUDGET',
81
+ 'X_EXERCISE_EMPTY_REACH',
82
+ 'X_TEST_PROPERTY_FAILED',
83
+ 'X_TEST_SOAK_HEAP_GROWTH',
81
84
  ] as const;
82
85
 
83
86
  export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
@@ -158,6 +161,10 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
158
161
  X_TEST_FACTORY_INVALID: 'a factory builds a row its own entity refuses',
159
162
  X_EXERCISE_SEED_FAILED: 'The scale sweep could not write the sized rows of one entity',
160
163
  X_STATEMENTS_OVER_BUDGET: 'One primitive call sent more statements than its ceiling',
164
+ X_EXERCISE_EMPTY_REACH:
165
+ 'an exercised primitive was reached and sent no statement and had no effect',
166
+ X_TEST_PROPERTY_FAILED: 'a property() run found an input its claim refuses',
167
+ X_TEST_SOAK_HEAP_GROWTH: 'a soak() run grew the live heap past its stated bound',
161
168
  };
162
169
 
163
170
  // Titles must be registered for `format()` to render the contract's first line. Every code above is
@@ -6,6 +6,7 @@ import type { Actor } from '@ultimat3/core';
6
6
  import { ctxOf, isUltimateError, renderThrowable } from '@ultimat3/core';
7
7
  import type { AnyJobHandle } from '@ultimat3/jobs';
8
8
  import type { CrashFinding, CrashProof } from './exercise-report';
9
+ import { PRELOAD_CLOCK } from './fixture-jobs';
9
10
  import type { CrashDivergence } from './job-crash-proof';
10
11
  import { crashProof } from './job-crash-proof';
11
12
 
@@ -31,7 +32,14 @@ export async function proveCrash(
31
32
  input: unknown,
32
33
  actor: Actor | null,
33
34
  ): Promise<CrashProof> {
34
- const worker = ctxOf(actor === null ? { role: 'worker' } : { role: 'worker', actor });
35
+ // The control's worker clock (`fixture-jobs.ts`): `ctxOf`'s default read the frozen `Date` but
36
+ // had no `advance`, so a `backfill()` pacer slept its whole `rate` interval in WALL time on every
37
+ // killed rerun — 8 of the reference app's 23 s pass.
38
+ const worker = ctxOf(
39
+ actor === null
40
+ ? { role: 'worker', clock: PRELOAD_CLOCK }
41
+ : { role: 'worker', actor, clock: PRELOAD_CLOCK },
42
+ );
35
43
  try {
36
44
  const report = await crashProof(handle, input, { context: () => worker });
37
45
  const counted = {
@@ -0,0 +1,205 @@
1
+ // One route `load` in the exercise pass: called once in its own seeded tenant, inside the room, as
2
+ // the runtime calls it (`routeDataFor` in a request as the chosen actor) — its statements counted,
3
+ // its busiest call held to the statement ceiling, then swept at 2 and 8 rows a table and planned
4
+ // beside the primitives. A page read is a read like a query's: an N+1 in it is the same red.
5
+
6
+ import type { Actor } from '@ultimat3/core';
7
+ import { isUltimateError, renderThrowable } from '@ultimat3/core';
8
+ import type { ExerciseOverrides } from './define-exercise';
9
+ import type { RoleGrants } from './exercise-actor';
10
+ import { seatActorUsers } from './exercise-actor-user';
11
+ import type {
12
+ ExerciseEffect,
13
+ ExerciseRecord,
14
+ ExerciseRoom,
15
+ Observation,
16
+ ProofMs,
17
+ } from './exercise-report';
18
+ import { withExerciseRequest } from './exercise-request';
19
+ import type { RouteLoadSubject, RouteParamsValue } from './exercise-route-subjects';
20
+ import { chooseRouteActor, routeParams, routeUrl } from './exercise-route-subjects';
21
+ import type { StatementCeilingProof } from './exercise-statement-ceiling';
22
+ import { judgeStatementCeiling } from './exercise-statement-ceiling';
23
+ import { actorRowsOf, seated } from './exercise-sweeps';
24
+ import type { PlanProof } from './plan-sweep';
25
+ import type { ScaleProof } from './scale-sweep';
26
+ import type { ScaleSubject } from './scale-sweep-run';
27
+ import type { SeedGraph } from './seed-graph-plan';
28
+ import type { SeedEntity } from './seed-graph-shape';
29
+
30
+ /** What one route's `load` did in the pass. `name` is the URL pattern; `file` the route file. */
31
+ export interface RouteLoadRecord {
32
+ readonly kind: 'route';
33
+ readonly name: string;
34
+ readonly file: string;
35
+ readonly outcome: 'reached' | 'refused' | 'unreached';
36
+ readonly code?: string;
37
+ readonly reason?: string;
38
+ readonly statements: number;
39
+ readonly effects: readonly ExerciseEffect[];
40
+ readonly ms: number;
41
+ readonly statementCeiling?: StatementCeilingProof;
42
+ readonly plans?: PlanProof;
43
+ readonly scale?: ScaleProof;
44
+ readonly proofMs?: ProofMs;
45
+ }
46
+
47
+ /** The room's and the sweeps' key: never a primitive's, whose names are identifiers. */
48
+ export const routeLabel = (path: string): string => `route:${path}`;
49
+
50
+ /** The pass's options, as far as choosing who loads a page goes. */
51
+ export interface RouteCallOptions {
52
+ readonly entities: readonly SeedEntity[];
53
+ readonly overrides?: ExerciseOverrides;
54
+ readonly roles: RoleGrants;
55
+ }
56
+
57
+ /** The page's data, resolved as a render resolves it, in a request as `actor`. */
58
+ export const callRoute = (
59
+ route: RouteLoadSubject,
60
+ params: RouteParamsValue,
61
+ actor: Actor | null,
62
+ ): Promise<unknown> =>
63
+ withExerciseRequest(routeLabel(route.path), actor, () =>
64
+ route.load({ params, url: routeUrl(route.path, params) }),
65
+ );
66
+
67
+ /** Who loads `route` in `tenant` of `graph`, and with which params — or none. */
68
+ export async function routeCall(
69
+ route: RouteLoadSubject,
70
+ options: RouteCallOptions,
71
+ graph: SeedGraph,
72
+ tenant: string,
73
+ ): Promise<
74
+ | { readonly actor: Actor | null; readonly params: RouteParamsValue }
75
+ | { readonly refused?: true; readonly reason: string }
76
+ > {
77
+ const chosen = chooseRouteActor(route.permission, options.roles, tenant);
78
+ if (chosen.kind === 'refused') return { refused: true, reason: chosen.reason };
79
+ const actor = seated(chosen.actor, tenant, actorRowsOf(options, graph));
80
+ const params = await routeParams(route, graph, options.entities, { tenant, actorId: actor?.id });
81
+ if (params.kind === 'none') return { reason: params.reason };
82
+ // A user, as a request's actor always is: its `x_users` row before the call.
83
+ await seatActorUsers([actor]);
84
+ return { actor, params: params.params };
85
+ }
86
+
87
+ const unreachedBy = (seen: Observation<unknown>) => {
88
+ if ('error' in seen) {
89
+ const { error } = seen;
90
+ return {
91
+ outcome: 'unreached' as const,
92
+ ...(isUltimateError(error) ? { code: error.code } : {}),
93
+ reason: `its load threw: ${renderThrowable(error)}`,
94
+ };
95
+ }
96
+ const [host] = seen.observed.refusedHosts;
97
+ return host === undefined
98
+ ? undefined
99
+ : { outcome: 'unreached' as const, reason: `its load called ${host}, which the pass seals` };
100
+ };
101
+
102
+ /** `route`'s load once, in `tenant`: the record before the sweeps add their proofs. */
103
+ export async function exerciseRouteLoad(
104
+ route: RouteLoadSubject,
105
+ options: RouteCallOptions,
106
+ at: { readonly graph: SeedGraph; readonly tenant: string; readonly room: ExerciseRoom },
107
+ ): Promise<RouteLoadRecord> {
108
+ const none = { kind: 'route' as const, name: route.path, file: route.file };
109
+ const empty = { ...none, statements: 0, effects: [], ms: 0 };
110
+ const call = await routeCall(route, options, at.graph, at.tenant);
111
+ if ('reason' in call) {
112
+ return {
113
+ ...empty,
114
+ outcome: call.refused === true ? 'refused' : 'unreached',
115
+ reason: call.reason,
116
+ };
117
+ }
118
+ const started = performance.now();
119
+ const seen = await at.room.observe(routeLabel(route.path), () =>
120
+ callRoute(route, call.params, call.actor),
121
+ );
122
+ const ms = Math.round(performance.now() - started);
123
+ const { observed } = seen;
124
+ const ran = { ...none, statements: observed.statements, effects: observed.effects, ms };
125
+ const statementCeiling = judgeStatementCeiling([observed]);
126
+ const failed = unreachedBy(seen);
127
+ return {
128
+ ...ran,
129
+ ...(failed ?? { outcome: 'reached' as const }),
130
+ ...(statementCeiling === undefined ? {} : { statementCeiling }),
131
+ };
132
+ }
133
+
134
+ /** The route as the scale sweep calls it: `input` is the params `routeCall` bound at each size. */
135
+ export const routeScaleSubject = (route: RouteLoadSubject): ScaleSubject => ({
136
+ name: routeLabel(route.path),
137
+ call: async (input, actor) => {
138
+ await callRoute(route, input as RouteParamsValue, actor);
139
+ return {};
140
+ },
141
+ });
142
+
143
+ /**
144
+ * Every route after the primitives, each in the tenant pair after theirs (`pairGraph`'s rule: its
145
+ * cost is its pair's), and the sweep's view of them: a scale subject and its sized-call recipe.
146
+ */
147
+ export async function runRouteLoads(
148
+ routes: readonly RouteLoadSubject[],
149
+ options: RouteCallOptions,
150
+ at: {
151
+ readonly view: (index: number) => SeedGraph;
152
+ readonly tenant: (index: number) => string;
153
+ readonly room: ExerciseRoom;
154
+ },
155
+ ): Promise<readonly RouteLoadRecord[]> {
156
+ const records: RouteLoadRecord[] = [];
157
+ for (const [i, route] of routes.entries()) {
158
+ const graph = at.view(i);
159
+ records.push(
160
+ await exerciseRouteLoad(route, options, { graph, tenant: at.tenant(i), room: at.room }),
161
+ );
162
+ }
163
+ return records;
164
+ }
165
+
166
+ /** The sized-call recipe for a route label, or `undefined` when the label is not a route's. */
167
+ export async function routeSizedCall(
168
+ routes: readonly RouteLoadSubject[],
169
+ options: RouteCallOptions,
170
+ at: { readonly label: string; readonly graph: SeedGraph; readonly tenant: string },
171
+ ): Promise<{ readonly actor: Actor | null; readonly input: unknown } | undefined> {
172
+ const route = routes.find((one) => routeLabel(one.path) === at.label);
173
+ if (route === undefined) return undefined;
174
+ const call = await routeCall(route, options, at.graph, at.tenant);
175
+ return 'reason' in call ? undefined : { actor: call.actor, input: call.params };
176
+ }
177
+
178
+ /** The sweeps' key for a record of either kind: a route's label, else the primitive's own. */
179
+ export const sweepLabel =
180
+ (label: (record: ExerciseRecord) => string) =>
181
+ (record: ExerciseRecord | RouteLoadRecord): string =>
182
+ record.kind === 'route' ? routeLabel(record.name) : label(record);
183
+
184
+ /** The routes whose load answered, as the scale sweep calls them. */
185
+ export const reachedRouteSubjects = (
186
+ routes: readonly RouteLoadSubject[],
187
+ records: readonly RouteLoadRecord[],
188
+ ): readonly ScaleSubject[] =>
189
+ routes
190
+ .filter((route) => records.some((r) => r.name === route.path && r.outcome === 'reached'))
191
+ .map(routeScaleSubject);
192
+
193
+ /** The swept records apart again: the primitives' list stays what the pass always returned. */
194
+ export function splitRouteRecords(records: readonly (ExerciseRecord | RouteLoadRecord)[]): {
195
+ readonly primitives: readonly ExerciseRecord[];
196
+ readonly routes: readonly RouteLoadRecord[];
197
+ } {
198
+ const primitives: ExerciseRecord[] = [];
199
+ const routes: RouteLoadRecord[] = [];
200
+ for (const record of records) {
201
+ if (record.kind === 'route') routes.push(record);
202
+ else primitives.push(record);
203
+ }
204
+ return { primitives, routes };
205
+ }
@@ -0,0 +1,162 @@
1
+ // The route `load`s an exercise pass drives: every `app/` and `site/` file route that declares one,
2
+ // read off `@ultimat3/render`'s route table — the one list `x routes` and the manifest print. Who
3
+ // loads it (the route's permission, else a signed-in actor) and with which params (a seeded row's
4
+ // id, else the route's own `prerender()` sample) are decided here; the call is the runtime's own.
5
+
6
+ import type { Actor } from '@ultimat3/core';
7
+ import { renderThrowable } from '@ultimat3/core';
8
+ import { rolesGranting } from '@ultimat3/policy';
9
+ import type { RoleGrants } from './exercise-actor';
10
+ import { exerciseActorId } from './exercise-actor';
11
+ import { seededIds } from './exercise-input';
12
+ import type { SeedGraph } from './seed-graph-plan';
13
+ import type { SeedEntity } from './seed-graph-shape';
14
+
15
+ export type RouteParamsValue = Readonly<Record<string, string>>;
16
+
17
+ /** One route as the pass drives it: what `load` is called with, by whom, and the call. */
18
+ export interface RouteLoadSubject {
19
+ /** The URL pattern, `/posts/:id` — the record's name. */
20
+ readonly path: string;
21
+ /** The route file, relative to the app: what a finding points at. */
22
+ readonly file: string;
23
+ /** The pattern's params, in order. */
24
+ readonly params: readonly string[];
25
+ /** The route's `policy.permission`, when it declares one. */
26
+ readonly permission?: string;
27
+ /** `routeDataFor(config, ctx)`: the runtime's one way to resolve a page's data. */
28
+ load(ctx: { readonly params: RouteParamsValue; readonly url: string }): Promise<unknown>;
29
+ /** The route's `prerender()`, when it declares one: a sample of params it knows exist. */
30
+ samples?(): Promise<readonly unknown[]>;
31
+ }
32
+
33
+ /** Each file route with a `load`, in the table's order. Loaded on demand: the barrel stays lean. */
34
+ export async function routeLoadSubjects(): Promise<readonly RouteLoadSubject[]> {
35
+ const { routeDataFor, routeEntries } = await import('@ultimat3/render');
36
+ return routeEntries()
37
+ .filter((entry) => entry.config.load !== undefined)
38
+ .map((entry): RouteLoadSubject => {
39
+ const { prerender, policy } = entry.config;
40
+ return {
41
+ path: entry.path,
42
+ file: entry.file,
43
+ params: entry.pattern.keys,
44
+ ...(policy === undefined ? {} : { permission: policy.permission }),
45
+ load: (ctx) => routeDataFor(entry.config, ctx),
46
+ ...(prerender === undefined ? {} : { samples: async () => prerender() }),
47
+ };
48
+ });
49
+ }
50
+
51
+ export type RouteActorChoice =
52
+ | { readonly kind: 'actor'; readonly actor: Actor | null }
53
+ | { readonly kind: 'refused'; readonly reason: string };
54
+
55
+ const holds = (actor: Actor, permission: string): boolean =>
56
+ (actor.permissions ?? []).includes(permission) ||
57
+ rolesGranting(permission).some((role) => (actor.roles ?? []).includes(role));
58
+
59
+ /**
60
+ * The route's guard is a permission, never a policy: the first role holding it. With none, a
61
+ * signed-in actor before the anonymous one — a page that branches on the viewer reads more rows.
62
+ */
63
+ export function chooseRouteActor(
64
+ permission: string | undefined,
65
+ grants: RoleGrants,
66
+ tenant: string,
67
+ ): RouteActorChoice {
68
+ const candidates = grants(tenant);
69
+ const signedIn = candidates.filter((c) => c.actor !== null);
70
+ const pick =
71
+ permission === undefined
72
+ ? (signedIn[0] ?? candidates[0])
73
+ : signedIn.find((c) => c.actor !== null && holds(c.actor, permission));
74
+ if (pick === undefined) {
75
+ return {
76
+ kind: 'refused',
77
+ reason: `none of ${candidates.map((c) => c.name).join(', ') || 'the role grants'} holds ${permission ?? 'a role'}`,
78
+ };
79
+ }
80
+ const { actor, name } = pick;
81
+ return {
82
+ kind: 'actor',
83
+ actor: actor === null ? null : Object.freeze({ ...actor, id: exerciseActorId(name, tenant) }),
84
+ };
85
+ }
86
+
87
+ /** A `prerender()` item as params: a bare string fills the one param, an entry carries its own. */
88
+ const sampleParams = (item: unknown, keys: readonly string[]): RouteParamsValue | undefined => {
89
+ if (typeof item === 'string')
90
+ return keys.length === 1 ? { [keys[0] as string]: item } : undefined;
91
+ if (typeof item !== 'object' || item === null) return undefined;
92
+ const nested = (item as { readonly params?: unknown }).params;
93
+ const record = (typeof nested === 'object' && nested !== null ? nested : item) as Record<
94
+ string,
95
+ unknown
96
+ >;
97
+ const out: Record<string, string> = {};
98
+ for (const key of keys) {
99
+ // Own keys only: a param named `constructor` must never read the prototype's.
100
+ const value = Object.hasOwn(record, key) ? record[key] : undefined;
101
+ if (typeof value !== 'string') return undefined;
102
+ out[key] = value;
103
+ }
104
+ return out;
105
+ };
106
+
107
+ export type RouteParamsChoice =
108
+ | { readonly kind: 'params'; readonly params: RouteParamsValue }
109
+ | { readonly kind: 'none'; readonly reason: string };
110
+
111
+ /**
112
+ * Each param bound to a seeded row's id the tenant sees (`:id` on `/posts/:id` is a `posts` key,
113
+ * by the rule an input's `id` is bound by), else the route's first `prerender()` item.
114
+ */
115
+ export async function routeParams(
116
+ route: RouteLoadSubject,
117
+ graph: SeedGraph,
118
+ entities: readonly SeedEntity[],
119
+ scope: { readonly tenant: string; readonly actorId?: string | undefined },
120
+ ): Promise<RouteParamsChoice> {
121
+ if (route.params.length === 0) return { kind: 'params', params: {} };
122
+ const lookup = seededIds(graph, entities, { ...scope, subject: route.path });
123
+ const bound: Record<string, string> = {};
124
+ for (const key of route.params) {
125
+ const hit = lookup(key);
126
+ if (hit === undefined || typeof hit.value !== 'string') break;
127
+ bound[key] = hit.value;
128
+ }
129
+ if (Object.keys(bound).length === route.params.length) return { kind: 'params', params: bound };
130
+ const unbound = route.params.map((key) => `:${key}`).join(', ');
131
+ if (route.samples === undefined) {
132
+ return {
133
+ kind: 'none',
134
+ reason: `${unbound} names no seeded entity's key and the route declares no prerender() sample`,
135
+ };
136
+ }
137
+ let items: readonly unknown[];
138
+ try {
139
+ items = await route.samples();
140
+ } catch (error) {
141
+ return { kind: 'none', reason: `its prerender() threw: ${renderThrowable(error)}` };
142
+ }
143
+ const sample = items.map((item) => sampleParams(item, route.params)).find(Boolean);
144
+ return sample === undefined
145
+ ? { kind: 'none', reason: `${unbound} is not filled by any item its prerender() answered` }
146
+ : { kind: 'params', params: sample };
147
+ }
148
+
149
+ /** This machine: the origin a load is told, as a served request's `href` is absolute. */
150
+ const EXERCISE_ORIGIN = 'http://localhost';
151
+
152
+ /** The URL the load is told — absolute, as the runtime's `at.href` is: the pattern, params in. */
153
+ export const routeUrl = (path: string, params: RouteParamsValue): string =>
154
+ EXERCISE_ORIGIN +
155
+ path.replace(/[:*]([A-Za-z0-9_]+)/g, (whole, key: string) => {
156
+ const value = Object.hasOwn(params, key) ? params[key] : undefined;
157
+ if (value === undefined) return whole;
158
+ // A catch-all keeps its slashes: `/docs/*path` with `a/b` is `/docs/a/b`.
159
+ return whole.startsWith('*')
160
+ ? value.split('/').map(encodeURIComponent).join('/')
161
+ : encodeURIComponent(value);
162
+ });
@@ -75,9 +75,12 @@ export async function sizedCall(
75
75
  return { actor, input: seatIn(subject, given, tenant) };
76
76
  }
77
77
 
78
+ /** What the sweeps write on a record: a primitive's, or a route load's (`exercise-route-loads.ts`). */
79
+ type SweptFields = Pick<ExerciseRecord, 'plans' | 'scale' | 'proofMs'>;
80
+
78
81
  /** The records with both sweeps' verdicts and scale time on them, and each sweep's whole time. */
79
- export interface Swept {
80
- readonly records: readonly ExerciseRecord[];
82
+ export interface Swept<R extends SweptFields = ExerciseRecord> {
83
+ readonly records: readonly R[];
81
84
  readonly ms: Pick<ExercisePhaseMs, 'scale' | 'plans'>;
82
85
  }
83
86
 
@@ -99,11 +102,11 @@ const timed = (subject: ScaleSubject, spent: Map<string, number>): ScaleSubject
99
102
  * only: with none, the pass ran on a driver that sends no SQL and there is no plan to read. Each
100
103
  * proof is found under `label(record)`, the name its primitive ran under in the room.
101
104
  */
102
- export async function attachSweeps(
103
- records: readonly ExerciseRecord[],
104
- label: (record: ExerciseRecord) => string,
105
+ export async function attachSweeps<R extends SweptFields>(
106
+ records: readonly R[],
107
+ label: (record: R) => string,
105
108
  options: ScaleSweepOptions,
106
- ): Promise<Swept> {
109
+ ): Promise<Swept<R>> {
107
110
  const spent = new Map<string, number>();
108
111
  let scale: Awaited<ReturnType<typeof scaleSweep>>;
109
112
  const scaleStarted = performance.now();
package/src/exercise.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // `runExercisePass`: every registered action, query and job, run once with no test written. Each
2
2
  // gets its own pair of committed tenants from the pass's one seed graph, an actor its policy allows,
3
- // and the input 39's minimal draw gives with seeded ids bound in; the verdict is 39's loop.
3
+ // and the input 39's minimal draw gives with seeded ids bound in; the verdict is 39's loop. Each
4
+ // route `load` it is handed runs after them, in a pair of its own (`exercise-route-loads.ts`).
4
5
  //
5
6
  // Committed, never rolled back. Around that call the tenant proof runs: the pair's other tenant
6
7
  // calls with the first one's ids before and after it (`tenant-proof.ts`, plan 101, 40). A reached
@@ -36,6 +37,15 @@ import type {
36
37
  Observed,
37
38
  } from './exercise-report';
38
39
  import { openExerciseRoom } from './exercise-report';
40
+ import type { RouteLoadRecord } from './exercise-route-loads';
41
+ import {
42
+ reachedRouteSubjects,
43
+ routeSizedCall,
44
+ runRouteLoads,
45
+ splitRouteRecords,
46
+ sweepLabel,
47
+ } from './exercise-route-loads';
48
+ import type { RouteLoadSubject } from './exercise-route-subjects';
39
49
  import { withExerciseSetup } from './exercise-setup';
40
50
  import type { ExerciseStatementCeiling } from './exercise-statement-ceiling';
41
51
  import { judgeStatementCeiling } from './exercise-statement-ceiling';
@@ -65,6 +75,13 @@ export interface ExercisePassOptions {
65
75
  readonly roles: RoleGrants;
66
76
  /** Told once, as the pass returns: how long each phase took, so a slow pass names its slow part. */
67
77
  readonly onPhases?: (ms: ExercisePhaseMs) => void;
78
+ /**
79
+ * Route `load`s run after the primitives (`routeLoadSubjects()`), each in a tenant pair of its
80
+ * own, swept and planned with them. Omitted, and on an `only` run: none.
81
+ */
82
+ readonly routes?: readonly RouteLoadSubject[];
83
+ /** Told once, as the pass returns: each route load's record, the sweeps' proofs on it. */
84
+ readonly onRoutes?: (records: readonly RouteLoadRecord[]) => void;
68
85
  }
69
86
 
70
87
  const isOff = (overrides: ExerciseOverrides | undefined, subject: Subject): boolean => {
@@ -391,14 +408,17 @@ export async function runExercisePass(
391
408
  // The app's setup runs inside the seal, before the first row: its routes answer every call.
392
409
  const room = await withExerciseSetup(await openExerciseRoom(), options.overrides?.setup);
393
410
  const live = chosen.filter((subject) => !isOff(options.overrides, subject));
411
+ const routes = options.only === undefined ? (options.routes ?? []) : [];
394
412
  const records: ExerciseRecord[] = [];
413
+ let routeRecords: readonly RouteLoadRecord[] = [];
395
414
  let graph: SeedGraph;
396
415
  const seedStarted = performance.now();
397
416
  let primitivesStarted = seedStarted;
398
417
  try {
399
418
  // Seeded before the first primitive runs: a failure here is the pass's, never one primitive's.
400
419
  graph = await seedPass(options.entities, options.writer, {
401
- primitives: live.length,
420
+ // A route's pair after every primitive's: a run with no routes seeds what it always did.
421
+ primitives: live.length + routes.length,
402
422
  seed: passSeed,
403
423
  ...(options.overrides?.factories === undefined
404
424
  ? {}
@@ -413,6 +433,11 @@ export async function runExercisePass(
413
433
  const pair = tenantPair(graph, at);
414
434
  records.push(await exerciseOne(subject, label(subject), options, pair, view, room, sampler));
415
435
  }
436
+ routeRecords = await runRouteLoads(routes, options, {
437
+ view: (i) => pairGraph(graph, live.length + i),
438
+ tenant: (i) => tenantPair(graph, live.length + i)[0],
439
+ room,
440
+ });
416
441
  } catch (error) {
417
442
  await room[Symbol.asyncDispose]();
418
443
  throw error;
@@ -421,11 +446,14 @@ export async function runExercisePass(
421
446
  const primitives = Math.round(performance.now() - primitivesStarted);
422
447
  // The sweeps: every reached primitive again at two sizes, then every statement planned.
423
448
  const reached = new Set(records.filter((r) => r.outcome === 'reached').map(label));
424
- const swept = await attachSweeps(records, label, {
449
+ const swept = await attachSweeps([...records, ...routeRecords], sweepLabel(label), {
425
450
  // Named by label: the sweeps key their proofs by name, and a shared name is two primitives.
426
- subjects: chosen
427
- .filter((subject) => reached.has(label(subject)))
428
- .map((subject) => ({ ...subject, name: label(subject) })),
451
+ subjects: [
452
+ ...chosen
453
+ .filter((subject) => reached.has(label(subject)))
454
+ .map((subject) => ({ ...subject, name: label(subject) })),
455
+ ...reachedRouteSubjects(routes, routeRecords),
456
+ ],
429
457
  entities: options.entities,
430
458
  // The sized graphs close their cycles as the pass's did: a refused deferred key stays null.
431
459
  writer: deferredMayStayNull(options.writer),
@@ -435,7 +463,9 @@ export async function runExercisePass(
435
463
  factories: options.overrides?.factories,
436
464
  setup: async (subject, sized, tenant, self) => {
437
465
  const full = chosen.find((one) => label(one) === subject.name);
438
- if (full === undefined) return undefined;
466
+ if (full === undefined) {
467
+ return routeSizedCall(routes, options, { label: subject.name, graph: sized, tenant });
468
+ }
439
469
  const call = await sizedCall(full, options, sampler, { graph: sized, tenant, self });
440
470
  // Before the sweep's room opens: the sized tenant's actor is a user too.
441
471
  if (call !== undefined) await seatActorUsers([call.actor]);
@@ -443,5 +473,7 @@ export async function runExercisePass(
443
473
  },
444
474
  });
445
475
  options.onPhases?.({ seed, primitives, ...swept.ms });
446
- return swept.records;
476
+ const split = splitRouteRecords(swept.records);
477
+ options.onRoutes?.(split.routes);
478
+ return split.primitives;
447
479
  }
@@ -103,7 +103,7 @@ const RENEW_MS = 1;
103
103
  * and slept its whole `rate` interval in WALL time. Moving the instant is the wait now, and it is
104
104
  * a move the frozen scheduler hears, so the renewals see exactly the time the throttle spent.
105
105
  */
106
- const PRELOAD_CLOCK: FrozenClock = Object.freeze({
106
+ export const PRELOAD_CLOCK: FrozenClock = Object.freeze({
107
107
  now: frozenNow,
108
108
  monotonic: () => frozenNow().getTime(),
109
109
  advance: (ms: number): void => {
package/src/index.ts CHANGED
@@ -152,6 +152,9 @@ export type {
152
152
  TenantLeg,
153
153
  TenantProof,
154
154
  } from './exercise-report';
155
+ export type { RouteLoadRecord } from './exercise-route-loads';
156
+ export type { RouteLoadSubject } from './exercise-route-subjects';
157
+ export { routeLoadSubjects } from './exercise-route-subjects';
155
158
  export type { ExerciseSetup, ExerciseSetupHandle } from './exercise-setup';
156
159
  export type {
157
160
  CeilingShape,
@@ -356,6 +359,11 @@ export { QueryPlanUnavailableError, sweepPlans } from './plan-sweep';
356
359
  export type { PlanFinding } from './plan-sweep-fix';
357
360
  export type { SweepFinding } from './plan-sweep-report';
358
361
  export { planSweepFindings, planSweepLines } from './plan-sweep-report';
362
+ // Seeded property checks: a claim over generated inputs, failing as the shrunk counterexample.
363
+ export type { PropertyOptions } from './property';
364
+ export { PropertyAsyncError, PropertyFailedError, property } from './property';
365
+ export type { Gen, LengthOptions, Shrinkable } from './property-gen';
366
+ export { gen, HOSTILE_CHARS } from './property-gen';
359
367
  // `isolateEntityRegistry` is deliberately NOT here — it is `@ultimat3/testing/registry-isolation`.
360
368
  // This barrel is what a `packages/core` test imports for `expect` alone, and a static re-export
361
369
  // evaluates the module it names: that one would load `@ultimat3/entity` and its process-global
@@ -418,6 +426,9 @@ export type { EntitySeedWriterOptions, SeedWriterTarget } from './seed-writer';
418
426
  export { entitySeedWriter } from './seed-writer';
419
427
  export type { SharedExamples } from './shared-examples';
420
428
  export { behavesLike, sharedExamples } from './shared-examples';
429
+ // The heap canary: many in-process requests, and the live heap after a full GC under a bound.
430
+ export type { SoakOptions, SoakReport } from './soak';
431
+ export { measureSoak, SoakHeapGrowthError, soak } from './soak';
421
432
  // One SQL table scan for the sweep's lost-table reader and `x doctor`'s raw tenant SQL probe.
422
433
  export { statementTables } from './sql-tables';
423
434
  // Test doubles: `stub(primitive)` replaces an action's, an llm()'s or a job's body, `swapAdapter`
@@ -0,0 +1,189 @@
1
+ // The generators `property()` draws from: each draw is a value AND its shrinks, so a mapped or
2
+ // nested generator shrinks through its source instead of guessing at its output. Seeded only —
3
+ // the caller hands the random source in — and every shrink halves the distance to the smallest
4
+ // value, so a counterexample of a million arrives in twenty steps. The runner is `property.ts`.
5
+
6
+ import { finiteCount } from '@ultimat3/core';
7
+
8
+ /** One drawn value and, lazily, the smaller values a failure is retried with — closest first. */
9
+ export interface Shrinkable<T> {
10
+ readonly value: T;
11
+ readonly shrinks: () => Iterable<Shrinkable<T>>;
12
+ }
13
+
14
+ /** `size` grows from 0 to 1 over a run, so the first draws are the small edge cases. */
15
+ export interface Gen<T> {
16
+ readonly draw: (random: () => number, size: number) => Shrinkable<T>;
17
+ }
18
+
19
+ const mapTree = <A, B>(tree: Shrinkable<A>, f: (value: A) => B): Shrinkable<B> => ({
20
+ value: f(tree.value),
21
+ *shrinks() {
22
+ for (const smaller of tree.shrinks()) yield mapTree(smaller, f);
23
+ },
24
+ });
25
+
26
+ /**
27
+ * `target` first, then the distance halved again and again — `v - d/2`, `v - d/4`, … `v - 1` —
28
+ * so a failure that holds at a boundary is found by bisection, never by counting down to it.
29
+ */
30
+ const intTree = (value: number, target: number): Shrinkable<number> => ({
31
+ value,
32
+ *shrinks() {
33
+ if (value === target) return;
34
+ yield intTree(target, target);
35
+ for (let gap = Math.trunc((value - target) / 2); gap !== 0; gap = Math.trunc(gap / 2)) {
36
+ yield intTree(value - gap, target);
37
+ }
38
+ },
39
+ });
40
+
41
+ /** Every position shrunk in turn, the others held: a tuple's failure is one field's. */
42
+ const tupleTree = <T>(items: readonly Shrinkable<T>[]): Shrinkable<readonly T[]> => ({
43
+ value: items.map((item) => item.value),
44
+ *shrinks() {
45
+ for (let at = 0; at < items.length; at += 1) {
46
+ for (const smaller of items[at]?.shrinks() ?? []) {
47
+ yield tupleTree(items.map((item, index) => (index === at ? smaller : item)));
48
+ }
49
+ }
50
+ },
51
+ });
52
+
53
+ /** Halves first (drop the back, drop the front), then one item out, then each item smaller. */
54
+ const listTree = <T>(items: readonly Shrinkable<T>[], min: number): Shrinkable<readonly T[]> => ({
55
+ value: items.map((item) => item.value),
56
+ *shrinks() {
57
+ const half = Math.floor(items.length / 2);
58
+ if (half >= min && half < items.length) {
59
+ yield listTree(items.slice(0, half), min);
60
+ yield listTree(items.slice(items.length - half), min);
61
+ }
62
+ if (items.length - 1 >= min) {
63
+ for (let at = 0; at < items.length; at += 1) {
64
+ yield listTree([...items.slice(0, at), ...items.slice(at + 1)], min);
65
+ }
66
+ }
67
+ yield* tupleTree(items).shrinks();
68
+ },
69
+ });
70
+
71
+ const pick = (random: () => number, low: number, high: number): number =>
72
+ low + Math.floor(random() * (high - low + 1));
73
+
74
+ /** A whole number in `[min, max]`, shrinking toward the one nearest zero. Bounds drawn 1 in 8. */
75
+ const int = (min: number, max: number): Gen<number> => ({
76
+ draw(random) {
77
+ const target = Math.min(Math.max(0, min), max);
78
+ const roll = random();
79
+ const value = roll < 1 / 16 ? min : roll < 1 / 8 ? max : pick(random, min, max);
80
+ return intTree(value, target);
81
+ },
82
+ });
83
+
84
+ /** One of `values`, shrinking toward the first: list the simplest value first. */
85
+ const oneOf = <T>(values: readonly [T, ...T[]]): Gen<T> =>
86
+ map(int(0, values.length - 1), (at) => values[at] ?? values[0]);
87
+
88
+ /** One of `gens`, shrinking inside the one drawn: a union never jumps branch while shrinking. */
89
+ const union = <T>(gens: readonly [Gen<T>, ...Gen<T>[]]): Gen<T> => ({
90
+ draw: (random, size) => (gens[pick(random, 0, gens.length - 1)] ?? gens[0]).draw(random, size),
91
+ });
92
+
93
+ const map = <A, B>(gen: Gen<A>, f: (value: A) => B): Gen<B> => ({
94
+ draw: (random, size) => mapTree(gen.draw(random, size), f),
95
+ });
96
+
97
+ const constant = <T>(value: T): Gen<T> => ({ draw: () => ({ value, shrinks: () => [] }) });
98
+
99
+ /** At most `maxLength` items, fewer while `size` is small. Default 16. */
100
+ export interface LengthOptions {
101
+ readonly minLength?: number;
102
+ readonly maxLength?: number;
103
+ }
104
+
105
+ const lengthOf = (random: () => number, size: number, options: LengthOptions): [number, number] => {
106
+ const min = finiteCount('gen', 'minLength', options.minLength ?? 0);
107
+ const max = Math.max(finiteCount('gen', 'maxLength', options.maxLength ?? 16), min);
108
+ return [pick(random, min, min + Math.ceil((max - min) * size)), min];
109
+ };
110
+
111
+ const array = <T>(item: Gen<T>, options: LengthOptions = {}): Gen<readonly T[]> => ({
112
+ draw(random, size) {
113
+ const [length, min] = lengthOf(random, size, options);
114
+ return listTree(
115
+ Array.from({ length }, () => item.draw(random, size)),
116
+ min,
117
+ );
118
+ },
119
+ });
120
+
121
+ const tuple = <T extends readonly unknown[]>(
122
+ ...gens: { readonly [K in keyof T]: Gen<T[K]> }
123
+ ): Gen<T> => ({
124
+ draw: (random, size) =>
125
+ tupleTree(gens.map((gen: Gen<unknown>) => gen.draw(random, size))) as Shrinkable<T>,
126
+ });
127
+
128
+ /** Code points a codec mishandles: separators, quotes, `%`, a combining mark, CJK, an astral emoji. */
129
+ export const HOSTILE_CHARS: readonly [string, ...string[]] = [
130
+ 'a',
131
+ 'Z',
132
+ '0',
133
+ ' ',
134
+ '-',
135
+ '_',
136
+ '.',
137
+ ',',
138
+ ';',
139
+ '=',
140
+ '%',
141
+ '"',
142
+ "'",
143
+ '\\',
144
+ '/',
145
+ '{',
146
+ '}',
147
+ '\n',
148
+ '\t',
149
+ '\u0000',
150
+ 'é',
151
+ '́',
152
+ 'ß',
153
+ 'ж',
154
+ 'ع',
155
+ '漢',
156
+ ' ',
157
+ ' ',
158
+ '🙂',
159
+ '👍🏽',
160
+ ];
161
+
162
+ const string = (options: LengthOptions & { readonly chars?: Gen<string> } = {}): Gen<string> =>
163
+ map(array(options.chars ?? oneOf(HOSTILE_CHARS), options), (chars) => chars.join(''));
164
+
165
+ const bytes = (options: LengthOptions = {}): Gen<Uint8Array> =>
166
+ map(array(int(0, 255), options), (list) => Uint8Array.from(list));
167
+
168
+ /** Plain JSON: `null`, booleans, safe integers, finite fractions, strings, arrays, objects. */
169
+ const json = (depth = 3): Gen<unknown> => {
170
+ const leaves: [Gen<unknown>, ...Gen<unknown>[]] = [
171
+ constant(null),
172
+ oneOf([false, true]),
173
+ int(-(2 ** 53) + 1, 2 ** 53 - 1),
174
+ map(int(-1_000_000, 1_000_000), (n) => n / 64),
175
+ string({ maxLength: 8 }),
176
+ ];
177
+ if (depth <= 0) return union(leaves);
178
+ const inner = json(depth - 1);
179
+ return union([
180
+ ...leaves,
181
+ array(inner, { maxLength: 4 }),
182
+ map(array(tuple(string({ maxLength: 6 }), inner), { maxLength: 4 }), (entries) =>
183
+ Object.fromEntries(entries),
184
+ ),
185
+ ]);
186
+ };
187
+
188
+ /** The generators. Compose them; a generator is a value, never a class to extend. */
189
+ export const gen = { int, oneOf, union, map, constant, array, tuple, string, bytes, json } as const;
@@ -0,0 +1,137 @@
1
+ // `property(gen, fn, { runs, seed })`: a claim checked against `runs` seeded draws, and a failure
2
+ // told as the smallest input that still breaks it, with the seed that replays it. No dependency
3
+ // and no ambient randomness — the preload's `Math.random` is never read — so a red run is the same
4
+ // red run on every machine. Generators: `property-gen.ts`.
5
+
6
+ import { finiteCount, renderCauseValue, UltimateError } from '@ultimat3/core';
7
+ import { DEFAULT_SEED, seededRandom } from './determinism';
8
+ import type { Gen, Shrinkable } from './property-gen';
9
+
10
+ export interface PropertyOptions {
11
+ /** Draws to check. Default 200. */
12
+ readonly runs?: number;
13
+ /** Default `DEFAULT_SEED`: the gate never flakes; pass another to explore further. */
14
+ readonly seed?: number;
15
+ /** Shrink attempts before the smallest failure so far is reported. Default 2000. */
16
+ readonly maxShrinks?: number;
17
+ }
18
+
19
+ /**
20
+ * Draws grow to full size over this many runs, whatever `runs` is: the size of draw `n` never
21
+ * depends on the total, so `{ runs: n }` replays draw `n` exactly.
22
+ */
23
+ const SIZE_RAMP = 100;
24
+
25
+ /** What one failing call said: a throw's message, or that it answered `false`. */
26
+ type Verdict = { readonly reason: string } | undefined;
27
+
28
+ const isThenable = (value: unknown): boolean =>
29
+ typeof value === 'object' && value !== null && typeof Reflect.get(value, 'then') === 'function';
30
+
31
+ /** A claim that did not hold. `input` is the shrunk counterexample, for a test to assert on. */
32
+ export class PropertyFailedError extends UltimateError {
33
+ override readonly name = 'PropertyFailedError';
34
+ readonly input: unknown;
35
+
36
+ constructor(init: {
37
+ readonly seed: number;
38
+ readonly run: number;
39
+ readonly runs: number;
40
+ readonly reason: string;
41
+ readonly input: unknown;
42
+ readonly original: unknown;
43
+ readonly shrinkSteps: number;
44
+ }) {
45
+ super({
46
+ code: 'X_TEST_PROPERTY_FAILED',
47
+ cause: `the property failed on draw ${init.run} of ${init.runs} (seed ${init.seed}): ${init.reason}; shrunk in ${init.shrinkSteps} steps to ${renderCauseValue(init.input)} from ${renderCauseValue(init.original)}`,
48
+ fix: `property(gen, fn, { seed: ${init.seed}, runs: ${init.run} }) # replays exactly this failure; fix the code under test, then put runs back`,
49
+ meta: { seed: init.seed, run: init.run, shrinkSteps: init.shrinkSteps },
50
+ });
51
+ this.input = init.input;
52
+ }
53
+ }
54
+
55
+ /** `fn` handed back a promise: every draw would "pass" before its assertion ran. */
56
+ export class PropertyAsyncError extends UltimateError {
57
+ override readonly name = 'PropertyAsyncError';
58
+
59
+ constructor() {
60
+ super({
61
+ code: 'X_TEST_PROPERTY_FAILED',
62
+ cause:
63
+ 'the property returned a promise, so its assertions would run after property() had already passed every draw',
64
+ fix: 'property(gen, (value) => { expect(decode(encode(value))).toEqual(value); }) # synchronous: await outside, draw values inside',
65
+ });
66
+ }
67
+ }
68
+
69
+ const verdictOf = <T>(fn: (value: T) => unknown, value: T): Verdict => {
70
+ let answer: unknown;
71
+ try {
72
+ answer = fn(value);
73
+ } catch (error) {
74
+ return { reason: renderCauseValue(error instanceof Error ? error.message : error) };
75
+ }
76
+ if (isThenable(answer)) throw new PropertyAsyncError();
77
+ return answer === false ? { reason: 'it returned false' } : undefined;
78
+ };
79
+
80
+ /** Greedy: the first smaller value that still fails is taken, and its shrinks are tried next. */
81
+ const shrink = <T>(
82
+ failing: Shrinkable<T>,
83
+ first: Verdict & object,
84
+ fn: (value: T) => unknown,
85
+ budget: number,
86
+ ): { readonly tree: Shrinkable<T>; readonly verdict: Verdict & object; readonly steps: number } => {
87
+ let tree = failing;
88
+ let verdict = first;
89
+ let steps = 0;
90
+ let progressed = true;
91
+ while (progressed && steps < budget) {
92
+ progressed = false;
93
+ for (const candidate of tree.shrinks()) {
94
+ steps += 1;
95
+ const next = verdictOf(fn, candidate.value);
96
+ if (next !== undefined) {
97
+ tree = candidate;
98
+ verdict = next;
99
+ progressed = true;
100
+ break;
101
+ }
102
+ if (steps >= budget) break;
103
+ }
104
+ }
105
+ return { tree, verdict, steps };
106
+ };
107
+
108
+ /**
109
+ * Check `fn` against `runs` draws of `gen`. `fn` fails by throwing (an `expect`) or returning
110
+ * `false`; the first failure is shrunk and thrown as `X_TEST_PROPERTY_FAILED`, naming the seed and
111
+ * the draw that replay it.
112
+ */
113
+ export function property<T>(
114
+ gen: Gen<T>,
115
+ fn: (value: T) => unknown,
116
+ options: PropertyOptions = {},
117
+ ): void {
118
+ const runs = finiteCount('property()', 'runs', options.runs ?? 200, 1);
119
+ const seed = finiteCount('property()', 'seed', options.seed ?? DEFAULT_SEED);
120
+ const budget = finiteCount('property()', 'maxShrinks', options.maxShrinks ?? 2000);
121
+ const random = seededRandom(seed);
122
+ for (let run = 1; run <= runs; run += 1) {
123
+ const drawn = gen.draw(random, Math.min(1, (run - 1) / SIZE_RAMP));
124
+ const verdict = verdictOf(fn, drawn.value);
125
+ if (verdict === undefined) continue;
126
+ const shrunk = shrink(drawn, verdict, fn, budget);
127
+ throw new PropertyFailedError({
128
+ seed,
129
+ run,
130
+ runs,
131
+ reason: shrunk.verdict.reason,
132
+ input: shrunk.tree.value,
133
+ original: drawn.value,
134
+ shrinkSteps: shrunk.steps,
135
+ });
136
+ }
137
+ }
package/src/soak.ts ADDED
@@ -0,0 +1,91 @@
1
+ // `soak()`: many requests through one in-process handler, and the live heap after a full GC
2
+ // compared with the heap after the warm-up — the regression class (a cache with no bound, a
3
+ // listener per request) no point test sees until a pod is killed. The bound is the caller's
4
+ // MEASUREMENT: raise it with the measured figures and the reason, never to make it pass.
5
+
6
+ import { heapStats } from 'bun:jsc';
7
+ import { finiteCount, renderCauseValue, UltimateError } from '@ultimat3/core';
8
+
9
+ export interface SoakOptions {
10
+ /** The app's request handler: `httpServer(...).fetch`, `BootedApp.fetch`, a pipeline's. */
11
+ readonly fetch: (request: Request) => Response | Promise<Response>;
12
+ /** One request per call, taken round-robin: a fresh `Request` every time, as a socket would. */
13
+ readonly requests: readonly [() => Request, ...(() => Request)[]];
14
+ /** Requests measured. Default 20,000. */
15
+ readonly total?: number;
16
+ /** Requests sent before the baseline, so lazy caches, JIT and pools are already full. Default 2,000. */
17
+ readonly warmup?: number;
18
+ /** Live-heap growth allowed across `total`, in bytes — a measurement, stated where it is passed. */
19
+ readonly maxGrowthBytes: number;
20
+ }
21
+
22
+ export interface SoakReport {
23
+ readonly requests: number;
24
+ readonly baselineBytes: number;
25
+ readonly finalBytes: number;
26
+ readonly growthBytes: number;
27
+ /** How many responses each status answered with: a soak that only ever 500s soaked nothing. */
28
+ readonly statuses: ReadonlyMap<number, number>;
29
+ }
30
+
31
+ /** The heap grew past the stated bound: something holds a reference per request. */
32
+ export class SoakHeapGrowthError extends UltimateError {
33
+ override readonly name = 'SoakHeapGrowthError';
34
+
35
+ constructor(report: SoakReport, bound: number) {
36
+ super({
37
+ code: 'X_TEST_SOAK_HEAP_GROWTH',
38
+ cause: `the live heap grew ${report.growthBytes} bytes over ${report.requests} requests (from ${report.baselineBytes} to ${report.finalBytes}), past the stated bound of ${bound}: something keeps a reference per request — a Map with no bound, a listener never removed, a closure held by a module-level array; statuses ${renderCauseValue([...report.statuses])}`,
39
+ fix: "await Bun.write('soak-heap.json', JSON.stringify(Bun.generateHeapSnapshot())) # after the soak: the type whose count is about the request count is the leak; raise maxGrowthBytes only with three measured runs written beside it",
40
+ meta: { growthBytes: report.growthBytes, bound, requests: report.requests },
41
+ });
42
+ }
43
+ }
44
+
45
+ /** The live heap after two full collections: one frees, the second frees what finalizers let go. */
46
+ const liveHeap = (): number => {
47
+ Bun.gc(true);
48
+ Bun.gc(true);
49
+ return heapStats().heapSize;
50
+ };
51
+
52
+ const send = async (
53
+ options: SoakOptions,
54
+ count: number,
55
+ offset: number,
56
+ statuses: Map<number, number>,
57
+ ): Promise<void> => {
58
+ for (let at = 0; at < count; at += 1) {
59
+ const make = options.requests[(offset + at) % options.requests.length] ?? options.requests[0];
60
+ const response = await options.fetch(make());
61
+ // Drained: an unread body is a stream the handler's side still holds.
62
+ await response.arrayBuffer();
63
+ statuses.set(response.status, (statuses.get(response.status) ?? 0) + 1);
64
+ }
65
+ };
66
+
67
+ /** Run the soak and report it, whatever the growth. `soak` is the verdict. */
68
+ export async function measureSoak(options: SoakOptions): Promise<SoakReport> {
69
+ const total = finiteCount('soak()', 'total', options.total ?? 20_000, 1);
70
+ const warmup = finiteCount('soak()', 'warmup', options.warmup ?? 2_000);
71
+ await send(options, warmup, 0, new Map());
72
+ const baselineBytes = liveHeap();
73
+ const statuses = new Map<number, number>();
74
+ await send(options, total, warmup, statuses);
75
+ const finalBytes = liveHeap();
76
+ return {
77
+ requests: total,
78
+ baselineBytes,
79
+ finalBytes,
80
+ growthBytes: finalBytes - baselineBytes,
81
+ statuses,
82
+ };
83
+ }
84
+
85
+ /** The soak, refused as `X_TEST_SOAK_HEAP_GROWTH` when the heap grew past `maxGrowthBytes`. */
86
+ export async function soak(options: SoakOptions): Promise<SoakReport> {
87
+ const bound = finiteCount('soak()', 'maxGrowthBytes', options.maxGrowthBytes);
88
+ const report = await measureSoak(options);
89
+ if (report.growthBytes > bound) throw new SoakHeapGrowthError(report, bound);
90
+ return report;
91
+ }