@ultimat3/testing 31.17.0 → 31.18.1
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 +6 -0
- package/README.md +43 -1
- package/package.json +22 -22
- package/src/determinism.ts +4 -0
- package/src/errors.ts +4 -0
- package/src/index.ts +8 -0
- package/src/job-sim-names.ts +41 -0
- package/src/job-sim-world.ts +6 -7
- package/src/property-gen.ts +189 -0
- package/src/property.ts +137 -0
- package/src/scale-sweep-run.ts +3 -3
- package/src/scale-sweep-seed.ts +17 -13
- package/src/seed-graph-row.ts +106 -6
- package/src/seed-graph.ts +28 -6
- package/src/soak.ts +91 -0
package/CLAUDE.md
CHANGED
|
@@ -124,6 +124,12 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
|
|
|
124
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 |
|
|
125
125
|
| Which command shards | `bun test` is one process on one database — what a scaffolded app's `test` script runs |
|
|
126
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
|
+
|
|
127
133
|
## The frozen instant and the seed are screened
|
|
128
134
|
|
|
129
135
|
Through one `instantMs` and core's `finiteOption`/`finiteCount` (`determinism-bounds.test.ts`). Full rule: `docs/history/testing.md`.
|
package/README.md
CHANGED
|
@@ -1248,6 +1248,44 @@ still stored, is `X_SUBJECT_ERASE_INCOMPLETE` naming the table and column. A dec
|
|
|
1248
1248
|
refuses comes back as its own problems, nothing seeded. `x exercise` runs it for every
|
|
1249
1249
|
`defineSubject()`, on a scratch database of its own.
|
|
1250
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
|
+
|
|
1251
1289
|
## Errors
|
|
1252
1290
|
|
|
1253
1291
|
`X_TEST_NETWORK_SEALED` `X_TEST_DB_UNAVAILABLE` `X_TEST_NONDETERMINISTIC` `X_TEST_FIXTURE_UNKNOWN`
|
|
@@ -1258,7 +1296,8 @@ refuses comes back as its own problems, nothing seeded. `x exercise` runs it for
|
|
|
1258
1296
|
`X_TEST_ISLAND_STATES_AMBIGUOUS` `X_TEST_ISLAND_STATE_ID_INVALID` `X_TEST_ISLAND_STATE_DUPLICATE`
|
|
1259
1297
|
`X_TEST_ISLAND_STATE_JSON_INVALID` `X_TEST_ISLAND_STATE_CLOCK_INVALID`
|
|
1260
1298
|
`X_TEST_ISLAND_STATE_STUB_INVALID` `X_SEED_GRAPH_UNSATISFIED` `X_E2E_A11Y_VIOLATION`
|
|
1261
|
-
`X_SEED_GRAPH_ENTITY_UNKNOWN` `
|
|
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
|
|
1262
1301
|
`x exercise` returns, never thrown
|
|
1263
1302
|
|
|
1264
1303
|
### Error classes
|
|
@@ -1276,8 +1315,11 @@ a job boundary the class is gone and the `code` is what survives — match on th
|
|
|
1276
1315
|
| `NetworkOfflineError` | `X_TEST_NETWORK_OFFLINE` | `src/errors.ts` |
|
|
1277
1316
|
| `NetworkSealedError` | `X_TEST_NETWORK_SEALED` | `src/errors.ts` |
|
|
1278
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` |
|
|
1279
1320
|
| `RegistryLeakError` | `X_TEST_REGISTRY_LEAK` | `src/errors.ts` |
|
|
1280
1321
|
| `SeedGraphUnsatisfiedError` | `X_SEED_GRAPH_UNSATISFIED` | `src/seed-graph-error.ts` |
|
|
1322
|
+
| `SoakHeapGrowthError` | `X_TEST_SOAK_HEAP_GROWTH` | `src/soak.ts` |
|
|
1281
1323
|
| `TestDatabaseUnavailableError` | `X_TEST_DB_UNAVAILABLE` | `src/errors.ts` |
|
|
1282
1324
|
|
|
1283
1325
|
## Log lines under test
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.18.1",
|
|
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.
|
|
51
|
-
"@ultimat3/ai": "31.
|
|
52
|
-
"@ultimat3/auth": "31.
|
|
53
|
-
"@ultimat3/cache": "31.
|
|
54
|
-
"@ultimat3/core": "31.
|
|
55
|
-
"@ultimat3/db": "31.
|
|
56
|
-
"@ultimat3/entity": "31.
|
|
57
|
-
"@ultimat3/http": "31.
|
|
58
|
-
"@ultimat3/i18n": "31.
|
|
59
|
-
"@ultimat3/jobs": "31.
|
|
60
|
-
"@ultimat3/mail": "31.
|
|
61
|
-
"@ultimat3/notify": "31.
|
|
62
|
-
"@ultimat3/policy": "31.
|
|
63
|
-
"@ultimat3/pwa": "31.
|
|
64
|
-
"@ultimat3/query": "31.
|
|
65
|
-
"@ultimat3/realtime": "31.
|
|
66
|
-
"@ultimat3/render": "31.
|
|
67
|
-
"@ultimat3/schema": "31.
|
|
68
|
-
"@ultimat3/scraping": "31.
|
|
69
|
-
"@ultimat3/seo": "31.
|
|
70
|
-
"@ultimat3/time": "31.
|
|
50
|
+
"@ultimat3/action": "31.18.1",
|
|
51
|
+
"@ultimat3/ai": "31.18.1",
|
|
52
|
+
"@ultimat3/auth": "31.18.1",
|
|
53
|
+
"@ultimat3/cache": "31.18.1",
|
|
54
|
+
"@ultimat3/core": "31.18.1",
|
|
55
|
+
"@ultimat3/db": "31.18.1",
|
|
56
|
+
"@ultimat3/entity": "31.18.1",
|
|
57
|
+
"@ultimat3/http": "31.18.1",
|
|
58
|
+
"@ultimat3/i18n": "31.18.1",
|
|
59
|
+
"@ultimat3/jobs": "31.18.1",
|
|
60
|
+
"@ultimat3/mail": "31.18.1",
|
|
61
|
+
"@ultimat3/notify": "31.18.1",
|
|
62
|
+
"@ultimat3/policy": "31.18.1",
|
|
63
|
+
"@ultimat3/pwa": "31.18.1",
|
|
64
|
+
"@ultimat3/query": "31.18.1",
|
|
65
|
+
"@ultimat3/realtime": "31.18.1",
|
|
66
|
+
"@ultimat3/render": "31.18.1",
|
|
67
|
+
"@ultimat3/schema": "31.18.1",
|
|
68
|
+
"@ultimat3/scraping": "31.18.1",
|
|
69
|
+
"@ultimat3/seo": "31.18.1",
|
|
70
|
+
"@ultimat3/time": "31.18.1"
|
|
71
71
|
}
|
|
72
72
|
}
|
package/src/determinism.ts
CHANGED
|
@@ -82,6 +82,10 @@ class FrozenDate extends RealDate {
|
|
|
82
82
|
* `[[DateValue]]` slot, and that slot is the one thing neither a fake nor a realm can hide.
|
|
83
83
|
*/
|
|
84
84
|
static override [Symbol.hasInstance](value: unknown): boolean {
|
|
85
|
+
// Only an object holds the slot. A string, a number or null answers here, never by a throw
|
|
86
|
+
// caught: `instanceof Date` guards every bound SQL parameter, and the throws were 13 s of an
|
|
87
|
+
// adopter's `x exercise`.
|
|
88
|
+
if (typeof value !== 'object' || value === null) return false;
|
|
85
89
|
try {
|
|
86
90
|
dateGetTime.call(value);
|
|
87
91
|
return true;
|
package/src/errors.ts
CHANGED
|
@@ -79,6 +79,8 @@ export const TESTING_ERROR_CODES = [
|
|
|
79
79
|
'X_EXERCISE_SEED_FAILED',
|
|
80
80
|
'X_STATEMENTS_OVER_BUDGET',
|
|
81
81
|
'X_EXERCISE_EMPTY_REACH',
|
|
82
|
+
'X_TEST_PROPERTY_FAILED',
|
|
83
|
+
'X_TEST_SOAK_HEAP_GROWTH',
|
|
82
84
|
] as const;
|
|
83
85
|
|
|
84
86
|
export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
|
|
@@ -161,6 +163,8 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
|
|
|
161
163
|
X_STATEMENTS_OVER_BUDGET: 'One primitive call sent more statements than its ceiling',
|
|
162
164
|
X_EXERCISE_EMPTY_REACH:
|
|
163
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',
|
|
164
168
|
};
|
|
165
169
|
|
|
166
170
|
// Titles must be registered for `format()` to render the contract's first line. Every code above is
|
package/src/index.ts
CHANGED
|
@@ -359,6 +359,11 @@ export { QueryPlanUnavailableError, sweepPlans } from './plan-sweep';
|
|
|
359
359
|
export type { PlanFinding } from './plan-sweep-fix';
|
|
360
360
|
export type { SweepFinding } from './plan-sweep-report';
|
|
361
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';
|
|
362
367
|
// `isolateEntityRegistry` is deliberately NOT here — it is `@ultimat3/testing/registry-isolation`.
|
|
363
368
|
// This barrel is what a `packages/core` test imports for `expect` alone, and a static re-export
|
|
364
369
|
// evaluates the module it names: that one would load `@ultimat3/entity` and its process-global
|
|
@@ -421,6 +426,9 @@ export type { EntitySeedWriterOptions, SeedWriterTarget } from './seed-writer';
|
|
|
421
426
|
export { entitySeedWriter } from './seed-writer';
|
|
422
427
|
export type { SharedExamples } from './shared-examples';
|
|
423
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';
|
|
424
432
|
// One SQL table scan for the sweep's lost-table reader and `x doctor`'s raw tenant SQL probe.
|
|
425
433
|
export { statementTables } from './sql-tables';
|
|
426
434
|
// Test doubles: `stub(primitive)` replaces an action's, an llm()'s or a job's body, `swapAdapter`
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// The effect log's queue ids, named by ordinal: `row:posts:delete:<uuid>` → `row:posts:delete:job#1`.
|
|
2
|
+
// Linear in the log: the ids are read once and each key once — never every id against every key,
|
|
3
|
+
// which a job enqueueing 500 others made 50 s of an adopter's crash proof.
|
|
4
|
+
|
|
5
|
+
/** A queue id as the memory driver mints it (`uuidV7`): 36 of lower-case hex and dashes. */
|
|
6
|
+
const ID = /^[0-9a-f-]{36}$/;
|
|
7
|
+
/** A maximal run of the characters an id is made of: any id in a key lies inside one. */
|
|
8
|
+
const RUN = /[0-9a-f-]+/g;
|
|
9
|
+
|
|
10
|
+
/** The one-id-at-a-time replacement, in insertion order: the answer, and the slow way to it. */
|
|
11
|
+
const eachInTurn = (ordinals: ReadonlyMap<string, string>, key: string): string => {
|
|
12
|
+
let out = key;
|
|
13
|
+
for (const [id, ordinal] of ordinals) out = out.split(id).join(ordinal);
|
|
14
|
+
return out;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Names `key`'s ids by `ordinals`, as replacing each id in turn would. When every id has the
|
|
19
|
+
* minted shape, a run of exactly 36 is an id or no id, and an ordinal (`job#1`) holds a `#` no run
|
|
20
|
+
* crosses — so one pass over the runs is that answer. A longer run may hold an id a turn-by-turn
|
|
21
|
+
* replacement would split differently: that key, and any map with another id shape, takes the turns.
|
|
22
|
+
*/
|
|
23
|
+
export function ordinalNamer(ordinals: ReadonlyMap<string, string>): (key: string) => string {
|
|
24
|
+
let uniform = true;
|
|
25
|
+
for (const id of ordinals.keys()) {
|
|
26
|
+
if (!ID.test(id)) {
|
|
27
|
+
uniform = false;
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (ordinals.size === 0) return (key) => key;
|
|
32
|
+
if (!uniform) return (key) => eachInTurn(ordinals, key);
|
|
33
|
+
return (key) => {
|
|
34
|
+
let long = false;
|
|
35
|
+
const named = key.replace(RUN, (run) => {
|
|
36
|
+
if (run.length > 36) long = true;
|
|
37
|
+
return run.length === 36 ? (ordinals.get(run) ?? run) : run;
|
|
38
|
+
});
|
|
39
|
+
return long ? eachInTurn(ordinals, key) : named;
|
|
40
|
+
};
|
|
41
|
+
}
|
package/src/job-sim-world.ts
CHANGED
|
@@ -17,6 +17,7 @@ import type { SimDecision, SimDriver, SimOp } from './job-sim-driver';
|
|
|
17
17
|
import { isSimFault, simDriver } from './job-sim-driver';
|
|
18
18
|
import type { EffectLog, SimEffect } from './job-sim-effects';
|
|
19
19
|
import { openEffectLog } from './job-sim-effects';
|
|
20
|
+
import { ordinalNamer } from './job-sim-names';
|
|
20
21
|
|
|
21
22
|
/** A lease short enough that a lapse is one clock jump, long enough that no renewal misses it. */
|
|
22
23
|
export const SIM_VISIBILITY_MS = 30_000;
|
|
@@ -135,12 +136,6 @@ export async function openSimWorld(options: SimWorldOptions): Promise<SimWorld>
|
|
|
135
136
|
}
|
|
136
137
|
};
|
|
137
138
|
|
|
138
|
-
const normalise = (key: string): string => {
|
|
139
|
-
let out = key;
|
|
140
|
-
for (const [id, ordinal] of ordinals) out = out.split(id).join(ordinal);
|
|
141
|
-
return out;
|
|
142
|
-
};
|
|
143
|
-
|
|
144
139
|
return {
|
|
145
140
|
sim,
|
|
146
141
|
log: effectLog,
|
|
@@ -187,7 +182,11 @@ export async function openSimWorld(options: SimWorldOptions): Promise<SimWorld>
|
|
|
187
182
|
return due.length === 0 ? undefined : Math.min(...due);
|
|
188
183
|
},
|
|
189
184
|
name: (id) => ordinals.get(id) ?? id,
|
|
190
|
-
effects: () =>
|
|
185
|
+
effects: () => {
|
|
186
|
+
// One namer per read: the ids are read once, never once per effect (`job-sim-names.ts`).
|
|
187
|
+
const name = ordinalNamer(ordinals);
|
|
188
|
+
return effectLog.effects().map((effect) => ({ ...effect, key: name(effect.key) }));
|
|
189
|
+
},
|
|
191
190
|
[Symbol.asyncDispose]: async (): Promise<void> => {
|
|
192
191
|
try {
|
|
193
192
|
await effectLog[Symbol.asyncDispose]();
|
|
@@ -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;
|
package/src/property.ts
ADDED
|
@@ -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/scale-sweep-run.ts
CHANGED
|
@@ -11,7 +11,7 @@ import type { ScaleProof, StatementTally } from './scale-sweep';
|
|
|
11
11
|
import { judgeScale, SCALE_SIZES } from './scale-sweep';
|
|
12
12
|
import type { ScaleGraph } from './scale-sweep-graph';
|
|
13
13
|
import { scaleGraph } from './scale-sweep-graph';
|
|
14
|
-
import {
|
|
14
|
+
import { lostReaders, writeSizedSeeds } from './scale-sweep-seed';
|
|
15
15
|
import type { SeedFactory, SeedGraph, SeedWriter } from './seed-graph-plan';
|
|
16
16
|
import type { SeedEntity } from './seed-graph-shape';
|
|
17
17
|
|
|
@@ -107,9 +107,9 @@ export async function scaleSweep(
|
|
|
107
107
|
options.entities,
|
|
108
108
|
options.writer,
|
|
109
109
|
);
|
|
110
|
-
const
|
|
110
|
+
const readers = lostReaders(options.room.sent(), loss, options.entities);
|
|
111
111
|
const subjects = options.subjects.filter((subject) => {
|
|
112
|
-
const seed =
|
|
112
|
+
const seed = readers.get(subject.name);
|
|
113
113
|
if (seed === undefined) return true;
|
|
114
114
|
const reason = `the sized seed did not write ${seed.entity}, which it reads: ${seed.cause}`;
|
|
115
115
|
proofs.set(subject.name, { verdict: 'unproven', reason, seed });
|
package/src/scale-sweep-seed.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The scale sweep's sized seed, written entity by entity: one table's refusal (a unique key, a check)
|
|
2
2
|
// is that table's, never the sweep's. Its rows, and every table that points at it, are skipped; the
|
|
3
|
-
// rest are written, so only a primitive that reads a lost table goes `unproven` (`
|
|
3
|
+
// rest are written, so only a primitive that reads a lost table goes `unproven` (`lostReaders`).
|
|
4
4
|
|
|
5
5
|
import { renderThrowable } from '@ultimat3/core';
|
|
6
6
|
import type { SentStatement } from './plan-sweep';
|
|
@@ -111,17 +111,19 @@ const derivedLoss = (
|
|
|
111
111
|
};
|
|
112
112
|
|
|
113
113
|
/**
|
|
114
|
-
*
|
|
115
|
-
* (`statementTables`: a column spelled like one is no read of it)
|
|
116
|
-
* `sent()
|
|
114
|
+
* Each subject that read a lost table in the pass, and the first such table: any statement it sent
|
|
115
|
+
* naming one in a table position (`statementTables`: a column spelled like one is no read of it),
|
|
116
|
+
* in the order the room saw them. Read off the room's `sent()` — what a primitive's own call sent
|
|
117
|
+
* is what its sized call sends again — in one pass for the whole sweep: per subject, the lost set
|
|
118
|
+
* was re-derived and every statement re-read, subjects × (entities + statements).
|
|
117
119
|
*/
|
|
118
|
-
export function
|
|
119
|
-
subject: string,
|
|
120
|
+
export function lostReaders(
|
|
120
121
|
sent: ReadonlyMap<string, SentStatement>,
|
|
121
122
|
loss: ScaleSeedLoss,
|
|
122
123
|
entities: readonly SeedEntity[],
|
|
123
|
-
): ScaleSeedFailure
|
|
124
|
-
|
|
124
|
+
): ReadonlyMap<string, ScaleSeedFailure> {
|
|
125
|
+
const readers = new Map<string, ScaleSeedFailure>();
|
|
126
|
+
if (loss.lost.size === 0) return readers;
|
|
125
127
|
const lost = derivedLoss(entities, loss.lost);
|
|
126
128
|
const tables = new Map(
|
|
127
129
|
entities.flatMap((entity) => {
|
|
@@ -130,11 +132,13 @@ export function readsLost(
|
|
|
130
132
|
}),
|
|
131
133
|
);
|
|
132
134
|
for (const [text, statement] of sent) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
const failure = statementTables(text)
|
|
136
|
+
.map((table) => tables.get(table))
|
|
137
|
+
.find((one) => one !== undefined);
|
|
138
|
+
if (failure === undefined) continue;
|
|
139
|
+
for (const subject of statement.primitives) {
|
|
140
|
+
if (!readers.has(subject)) readers.set(subject, failure);
|
|
137
141
|
}
|
|
138
142
|
}
|
|
139
|
-
return
|
|
143
|
+
return readers;
|
|
140
144
|
}
|
package/src/seed-graph-row.ts
CHANGED
|
@@ -17,6 +17,12 @@ export interface RowProblem {
|
|
|
17
17
|
readonly uniques: readonly (readonly string[])[];
|
|
18
18
|
/** Per entry of `uniques`, the keys earlier rows already hold. */
|
|
19
19
|
readonly taken: readonly ReadonlySet<string>[];
|
|
20
|
+
/**
|
|
21
|
+
* Per entry of `uniques`: for a one-property set, the string values earlier rows hold in it —
|
|
22
|
+
* `taken`'s answer for a string candidate without building its key. With it the solver steps
|
|
23
|
+
* over a candidate no row can keep instead of building and judging that row (`searchPruned`).
|
|
24
|
+
*/
|
|
25
|
+
readonly takenStrings?: readonly (ReadonlySet<string> | undefined)[];
|
|
20
26
|
/** A factory's `derive`: columns that follow from the picked ones, applied before any rule. */
|
|
21
27
|
readonly derive?: ((row: Readonly<Record<string, unknown>>) => object) | undefined;
|
|
22
28
|
}
|
|
@@ -98,6 +104,102 @@ function* combinations(problem: RowProblem, vary: readonly number[]): Generator<
|
|
|
98
104
|
}
|
|
99
105
|
}
|
|
100
106
|
|
|
107
|
+
/** The columns worth varying: the ones a broken rule reads, with more than one candidate. */
|
|
108
|
+
const variable = (problem: RowProblem, properties: ReadonlySet<string>): number[] =>
|
|
109
|
+
problem.columns.flatMap(([property, candidates], index) =>
|
|
110
|
+
properties.has(property) && candidates.length > 1 ? [index] : [],
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
/** Each property under a one-property unique set, and the strings earlier rows hold in it. */
|
|
114
|
+
const takenByProperty = (problem: RowProblem): ReadonlyMap<string, ReadonlySet<string>[]> => {
|
|
115
|
+
const byProperty = new Map<string, ReadonlySet<string>[]>();
|
|
116
|
+
problem.uniques.forEach((set, i) => {
|
|
117
|
+
const values = problem.takenStrings?.[i];
|
|
118
|
+
const [property] = set;
|
|
119
|
+
if (set.length !== 1 || property === undefined || values === undefined) return;
|
|
120
|
+
byProperty.set(property, [...(byProperty.get(property) ?? []), values]);
|
|
121
|
+
});
|
|
122
|
+
return byProperty;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** `brokenBy`'s verdict on the one-property sets for a string value, without building its key. */
|
|
126
|
+
const isTaken = (sets: readonly ReadonlySet<string>[] | undefined, value: unknown): boolean =>
|
|
127
|
+
typeof value === 'string' && sets !== undefined && sets.some((values) => values.has(value));
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Per column, the candidate positions a row could keep — `undefined` for every one: a taken string
|
|
131
|
+
* is dropped, as `brokenBy` refuses every row built on it. Under a `derive` nothing is dropped — it
|
|
132
|
+
* may rewrite the very column a candidate was refused on — and each built row meets `isTaken` first.
|
|
133
|
+
*/
|
|
134
|
+
const keptPositions = (
|
|
135
|
+
problem: RowProblem,
|
|
136
|
+
byProperty: ReadonlyMap<string, ReadonlySet<string>[]>,
|
|
137
|
+
): { readonly kept: (readonly number[] | undefined)[]; readonly dropped: boolean } => {
|
|
138
|
+
let dropped = false;
|
|
139
|
+
const kept = problem.columns.map(([property, candidates]) => {
|
|
140
|
+
const sets = byProperty.get(property);
|
|
141
|
+
if (sets === undefined || problem.derive !== undefined) return undefined;
|
|
142
|
+
const free: number[] = [];
|
|
143
|
+
candidates.forEach((value, position) => {
|
|
144
|
+
if (!isTaken(sets, value)) free.push(position);
|
|
145
|
+
});
|
|
146
|
+
if (free.length === candidates.length) return undefined;
|
|
147
|
+
dropped = true;
|
|
148
|
+
return free;
|
|
149
|
+
});
|
|
150
|
+
return { kept, dropped };
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* `search`'s first round, stepping over rows a taken string refuses, or undefined to run `search`
|
|
155
|
+
* itself. The odometer visits the kept combinations in the order `combinations` visits all of them
|
|
156
|
+
* and each one stepped over breaks a unique key, so the first row that holds is `search`'s own —
|
|
157
|
+
* unless `search` would stop at `MAX_TRIES` before reaching it, or find none and widen: both are
|
|
158
|
+
* answered by `search`. The stepping over is the point: a tenant child of a shared parent under a
|
|
159
|
+
* table-wide unique key walked past every parent earlier tenants took, a judged row each —
|
|
160
|
+
* quadratic in tenants (an adopter's pass seed: 98 s of 106).
|
|
161
|
+
*/
|
|
162
|
+
const searchPruned = (problem: RowProblem): RowSolution | undefined => {
|
|
163
|
+
const byProperty = takenByProperty(problem);
|
|
164
|
+
if (byProperty.size === 0) return undefined;
|
|
165
|
+
const { kept, dropped } = keptPositions(problem, byProperty);
|
|
166
|
+
// Nothing dropped and no `derive` to judge cheaply: the plain search is this search.
|
|
167
|
+
if (!dropped && problem.derive === undefined) return undefined;
|
|
168
|
+
const picks = problem.columns.map(() => 0);
|
|
169
|
+
const first = brokenBy(problem, build(problem, picks), true);
|
|
170
|
+
if (first.names.length === 0) return { ok: true, row: build(problem, picks) };
|
|
171
|
+
const vary = variable(problem, first.properties);
|
|
172
|
+
const radix = vary.map((column) => problem.columns[column]?.[1].length ?? 1);
|
|
173
|
+
const sizes = vary.map((column, slot) => kept[column]?.length ?? radix[slot] ?? 1);
|
|
174
|
+
if (vary.length === 0 || sizes.some((size) => size === 0)) return undefined;
|
|
175
|
+
const refusing = [...byProperty];
|
|
176
|
+
const at = vary.map(() => 0);
|
|
177
|
+
for (;;) {
|
|
178
|
+
// Where `combinations` yields this one: the same odometer, over every candidate.
|
|
179
|
+
let ordinal = 0;
|
|
180
|
+
for (let slot = 0; slot < vary.length; slot += 1) {
|
|
181
|
+
const column = vary[slot] as number;
|
|
182
|
+
const step = at[slot] ?? 0;
|
|
183
|
+
const position = kept[column]?.[step] ?? step;
|
|
184
|
+
ordinal = ordinal * (radix[slot] ?? 1) + position;
|
|
185
|
+
picks[column] = position;
|
|
186
|
+
}
|
|
187
|
+
if (ordinal >= MAX_TRIES) return undefined;
|
|
188
|
+
const row = build(problem, picks);
|
|
189
|
+
// Own properties only, as `uniqueKey` reads them: a column named `constructor` is no prototype.
|
|
190
|
+
const refused = refusing.some(
|
|
191
|
+
([property, sets]) => Object.hasOwn(row, property) && isTaken(sets, row[property]),
|
|
192
|
+
);
|
|
193
|
+
if (!refused && brokenBy(problem, row, true).names.length === 0) return { ok: true, row };
|
|
194
|
+
let slot = vary.length - 1;
|
|
195
|
+
for (; slot >= 0; slot -= 1) {
|
|
196
|
+
at[slot] = ((at[slot] ?? 0) + 1) % (sizes[slot] ?? 1);
|
|
197
|
+
if (at[slot] !== 0) break;
|
|
198
|
+
}
|
|
199
|
+
if (slot < 0) return undefined;
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
101
203
|
const search = (problem: RowProblem, unique: boolean): RowSolution => {
|
|
102
204
|
const zero = problem.columns.map(() => 0);
|
|
103
205
|
const first = brokenBy(problem, build(problem, zero), unique);
|
|
@@ -108,13 +210,9 @@ const search = (problem: RowProblem, unique: boolean): RowSolution => {
|
|
|
108
210
|
capacity: false,
|
|
109
211
|
};
|
|
110
212
|
if (first.names.length === 0) return { ok: true, row: build(problem, zero) };
|
|
111
|
-
const variable = (properties: ReadonlySet<string>): number[] =>
|
|
112
|
-
problem.columns.flatMap(([property, candidates], index) =>
|
|
113
|
-
properties.has(property) && candidates.length > 1 ? [index] : [],
|
|
114
|
-
);
|
|
115
213
|
let wanted = new Set(first.properties);
|
|
116
214
|
for (let round = 0; round < ROUNDS; round += 1) {
|
|
117
|
-
const vary = variable(wanted);
|
|
215
|
+
const vary = variable(problem, wanted);
|
|
118
216
|
const grown = new Set(wanted);
|
|
119
217
|
for (const picks of combinations(problem, vary)) {
|
|
120
218
|
const row = build(problem, picks);
|
|
@@ -122,7 +220,7 @@ const search = (problem: RowProblem, unique: boolean): RowSolution => {
|
|
|
122
220
|
if (broken.names.length === 0) return { ok: true, row };
|
|
123
221
|
for (const property of broken.properties) grown.add(property);
|
|
124
222
|
}
|
|
125
|
-
if (variable(grown).length === vary.length) return failed;
|
|
223
|
+
if (variable(problem, grown).length === vary.length) return failed;
|
|
126
224
|
wanted = grown;
|
|
127
225
|
}
|
|
128
226
|
return failed;
|
|
@@ -130,6 +228,8 @@ const search = (problem: RowProblem, unique: boolean): RowSolution => {
|
|
|
130
228
|
|
|
131
229
|
/** The first row that keeps every rule; failing that, whether only uniqueness stood in the way. */
|
|
132
230
|
export function solveRow(problem: RowProblem): RowSolution {
|
|
231
|
+
const pruned = searchPruned(problem);
|
|
232
|
+
if (pruned !== undefined) return pruned;
|
|
133
233
|
const found = search(problem, true);
|
|
134
234
|
if (found.ok) return found;
|
|
135
235
|
return search(problem, false).ok ? { ...found, capacity: true } : found;
|
package/src/seed-graph.ts
CHANGED
|
@@ -146,19 +146,32 @@ export function seedGraph(
|
|
|
146
146
|
// The same rows by tenant: a pool read per row was a filter of the whole parent table, so a pass
|
|
147
147
|
// seeding a tenant pair per primitive planned in primitives² time.
|
|
148
148
|
const placedIn = new Map<string, Map<string | null, Placed[]>>();
|
|
149
|
+
/**
|
|
150
|
+
* `memo`: one table's insert loop, where no placed row changes. A shared pool's rotation is the
|
|
151
|
+
* same for every tenant's row at one index, and copying the whole pool per row was the second
|
|
152
|
+
* quadratic of a pass seed (6 s of an adopter's 36 at 1,188 tenants).
|
|
153
|
+
*/
|
|
149
154
|
const parentValues = (
|
|
150
155
|
reference: ReferenceDescription,
|
|
151
156
|
tenant: string | null,
|
|
152
157
|
index: number,
|
|
158
|
+
memo?: Map<string, unknown[]>,
|
|
153
159
|
): unknown[] => {
|
|
154
160
|
if (!shapes.has(reference.targetEntity)) return reference.nullable ? [null] : [];
|
|
161
|
+
const own = tenant === null || !scoped(reference.targetEntity) ? null : tenant;
|
|
155
162
|
const pool =
|
|
156
|
-
|
|
163
|
+
own === null
|
|
157
164
|
? (placed.get(reference.targetEntity) ?? [])
|
|
158
|
-
: (placedIn.get(reference.targetEntity)?.get(
|
|
165
|
+
: (placedIn.get(reference.targetEntity)?.get(own) ?? []);
|
|
166
|
+
// The length too: a table's own pool grows under its own loop.
|
|
167
|
+
const key = `${reference.targetEntity}\u0000${reference.targetProperty}\u0000${String(reference.nullable)}\u0000${own ?? ''}\u0000${index}\u0000${pool.length}`;
|
|
168
|
+
const known = memo?.get(key);
|
|
169
|
+
if (known !== undefined) return known;
|
|
159
170
|
const values =
|
|
160
171
|
pool.length === 0 ? [] : rotate(pool, index).map((p) => p.row[reference.targetProperty]);
|
|
161
|
-
|
|
172
|
+
const answer = reference.nullable ? [...values, null] : values;
|
|
173
|
+
memo?.set(key, answer);
|
|
174
|
+
return answer;
|
|
162
175
|
};
|
|
163
176
|
const refuseEmpty = (shape: EntityShape, property: string, tenant: string | null): never => {
|
|
164
177
|
const reference = shape.references.get(property);
|
|
@@ -196,6 +209,10 @@ export function seedGraph(
|
|
|
196
209
|
placedIn.set(name, byTenant);
|
|
197
210
|
const allUniques = [...shape.uniques, ...shape.partialUniques];
|
|
198
211
|
const taken = allUniques.map(() => new Set<string>());
|
|
212
|
+
// A one-property set's string values beside its keys: the solver's skip list (`takenStrings`).
|
|
213
|
+
const takenStrings = allUniques.map((set) =>
|
|
214
|
+
set.length === 1 ? new Set<string>() : undefined,
|
|
215
|
+
);
|
|
199
216
|
const rootProperty = roots.get(name);
|
|
200
217
|
// Read once per table: each `matches(/…/)` an invariant holds a column to, sampled from.
|
|
201
218
|
const patterns = declaredPatterns(entity);
|
|
@@ -213,6 +230,7 @@ export function seedGraph(
|
|
|
213
230
|
// place in THIS graph, so the scale sweep's 8-row graph opens on the 2-row graph's values and a
|
|
214
231
|
// branch on the handed row takes one path at both sizes (`scale-sweep-branch.test.ts`).
|
|
215
232
|
const uniqueColumns = new Set(allUniques.flat());
|
|
233
|
+
const pools = new Map<string, unknown[]>();
|
|
216
234
|
for (let skipped = 0; factory !== undefined && skipped < start; skipped += 1) factory.build();
|
|
217
235
|
let ordinal = start;
|
|
218
236
|
for (const [bucket, tenant] of buckets.entries()) {
|
|
@@ -240,7 +258,7 @@ export function seedGraph(
|
|
|
240
258
|
: reference !== undefined
|
|
241
259
|
? deferred.has(edgeKey(name, property))
|
|
242
260
|
? [null]
|
|
243
|
-
: parentValues(reference, tenant, index)
|
|
261
|
+
: parentValues(reference, tenant, index, pools)
|
|
244
262
|
: Object.hasOwn(built, property)
|
|
245
263
|
? storable(column, [built[property]])
|
|
246
264
|
: window !== null && property === partitioned?.property
|
|
@@ -262,7 +280,7 @@ export function seedGraph(
|
|
|
262
280
|
});
|
|
263
281
|
// A partial unique whose every column the factory built is the database's to judge.
|
|
264
282
|
const held = allUniques
|
|
265
|
-
.map((set, i) => [set, taken[i] as Set<string
|
|
283
|
+
.map((set, i) => [set, taken[i] as Set<string>, takenStrings[i]] as const)
|
|
266
284
|
.filter(
|
|
267
285
|
([set], i) =>
|
|
268
286
|
i < shape.uniques.length || !set.every((property) => Object.hasOwn(built, property)),
|
|
@@ -272,6 +290,7 @@ export function seedGraph(
|
|
|
272
290
|
checks: shape.checks,
|
|
273
291
|
uniques: held.map(([set]) => set),
|
|
274
292
|
taken: held.map(([, set]) => set),
|
|
293
|
+
takenStrings: held.map(([, , values]) => values),
|
|
275
294
|
derive: factory?.derive?.bind(factory),
|
|
276
295
|
};
|
|
277
296
|
const solved = solveRow(problem);
|
|
@@ -291,7 +310,10 @@ export function seedGraph(
|
|
|
291
310
|
const row = { ...solved.row };
|
|
292
311
|
allUniques.forEach((set, i) => {
|
|
293
312
|
const key = uniqueKey(row, set);
|
|
294
|
-
if (key
|
|
313
|
+
if (key === undefined) return;
|
|
314
|
+
taken[i]?.add(key);
|
|
315
|
+
const value = row[set[0] as string];
|
|
316
|
+
if (typeof value === 'string') takenStrings[i]?.add(value);
|
|
295
317
|
});
|
|
296
318
|
const one = { tenant, row, index };
|
|
297
319
|
rows.push(one);
|
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
|
+
}
|