@ultimat3/testing 31.50.0 → 31.52.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 +1 -1
- package/README.md +12 -0
- package/package.json +22 -22
- package/src/entity-conformance-chain-writes.ts +57 -4
- package/src/errors.ts +2 -0
- package/src/fixture-subscribe.ts +19 -13
- package/src/index.ts +12 -0
- package/src/plan-budget-error.ts +58 -0
- package/src/plan-budget-read.ts +75 -0
- package/src/plan-budget.ts +76 -0
- package/src/race-actions.ts +112 -0
package/CLAUDE.md
CHANGED
|
@@ -6,7 +6,7 @@ A row marked `†` has its full text in [`docs/history/testing-rules.md`](../../
|
|
|
6
6
|
Deps (21): `core` `schema`; `cache` `db` `i18n` `seo` `time`; `auth` `entity` `http` `policy`; `action`
|
|
7
7
|
`jobs` `query` `realtime`; `ai` `mail` `notify` `pwa` `render` `scraping` (`ai`, `auth`, `notify`, `scraping` for `swapAdapter`, dynamic-only). Static in `.`: `scraping/cdp`, `cache`
|
|
8
8
|
(`registry-leak-guard.ts:7`), `i18n`, `jobs`, `policy` (`registry-snapshot.ts:29-38`), `db`
|
|
9
|
-
(`reusable-database.ts:20`), `realtime/server` (`fixture-subscribe.ts:
|
|
9
|
+
(`reusable-database.ts:20`), `realtime/server` (`fixture-subscribe.ts:14`). Dynamic-only:
|
|
10
10
|
`action`, `http`, `mail`, `pwa`, `query`, `render`, `schema` (`exercise-input.ts:16`), `time` — no `mail` destructure, no mail
|
|
11
11
|
package; a `packages/core` import never loads `@ultimat3/entity`. `entity` is reached by `await import` only
|
|
12
12
|
(seed writer, tenant witness, `nPlusOne()`, repro, subject proof, the row observer); static only in
|
package/README.md
CHANGED
|
@@ -302,6 +302,18 @@ What a stub replaces is the BODY, and nothing else:
|
|
|
302
302
|
`toHaveBeenCalledWith` keeps bun's meaning for a `mock()` or a `spyOn`: only a `stub()` receiver is
|
|
303
303
|
schema-checked. `As of 2026-11`.
|
|
304
304
|
|
|
305
|
+
## A plan budget, and a race
|
|
306
|
+
|
|
307
|
+
`expectPlanWithin(sql\`…\`, { maxCost, maxSortRows }, { client?, entities? })` plans a statement with its
|
|
308
|
+
real parameters, read-only, never `analyze`, and throws `X_QUERY_PLAN_OVER_BUDGET` past either
|
|
309
|
+
number (both required, no defaults). With `entities` the fix names the `indexes:` entry. Analyze
|
|
310
|
+
after seeding; one budget per engine (PGlite and Postgres cost plans differently).
|
|
311
|
+
|
|
312
|
+
`raceActions(calls, { rounds })` runs the calls concurrently and returns `{ settled,
|
|
313
|
+
serializationFailures }` (`40P01` / `40001`, as `X_DB_SERIALIZATION_FAILURE`).
|
|
314
|
+
`expectPartial(result, { allowed, denied })` states a `decide()` answer.
|
|
315
|
+
See [`wiki/Testing.md`](../../wiki/Testing.md#a-plan-budget-and-a-race).
|
|
316
|
+
|
|
305
317
|
## An N+1 fails the test it happened in
|
|
306
318
|
|
|
307
319
|
```ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.52.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,27 +47,27 @@
|
|
|
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.52.0",
|
|
51
|
+
"@ultimat3/ai": "31.52.0",
|
|
52
|
+
"@ultimat3/auth": "31.52.0",
|
|
53
|
+
"@ultimat3/cache": "31.52.0",
|
|
54
|
+
"@ultimat3/core": "31.52.0",
|
|
55
|
+
"@ultimat3/db": "31.52.0",
|
|
56
|
+
"@ultimat3/entity": "31.52.0",
|
|
57
|
+
"@ultimat3/http": "31.52.0",
|
|
58
|
+
"@ultimat3/i18n": "31.52.0",
|
|
59
|
+
"@ultimat3/jobs": "31.52.0",
|
|
60
|
+
"@ultimat3/mail": "31.52.0",
|
|
61
|
+
"@ultimat3/notify": "31.52.0",
|
|
62
|
+
"@ultimat3/policy": "31.52.0",
|
|
63
|
+
"@ultimat3/pwa": "31.52.0",
|
|
64
|
+
"@ultimat3/query": "31.52.0",
|
|
65
|
+
"@ultimat3/realtime": "31.52.0",
|
|
66
|
+
"@ultimat3/render": "31.52.0",
|
|
67
|
+
"@ultimat3/schema": "31.52.0",
|
|
68
|
+
"@ultimat3/scraping": "31.52.0",
|
|
69
|
+
"@ultimat3/seo": "31.52.0",
|
|
70
|
+
"@ultimat3/time": "31.52.0"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
73
|
"solid-js": "^1.9.18"
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// Entity conformance · the WRITE TERMINALS of the read chain
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Entity conformance · the WRITE TERMINALS of the read chain (`updateAll`, `deleteAll`) and
|
|
2
|
+
// `updateWhereReturning`: exactly the rows the same filter reads — tenant-scoped, soft delete and
|
|
3
|
+
// append-only honoured, a JS-only rule judged before anything stays, sealed values sealed, the change
|
|
4
|
+
// reported, history recorded — and an empty predicate is refused, never every row.
|
|
5
5
|
|
|
6
6
|
import { expect } from 'bun:test';
|
|
7
7
|
import type { Database } from '@ultimat3/entity';
|
|
@@ -342,9 +342,62 @@ const reported: readonly EntityDriverCheck[] = [
|
|
|
342
342
|
),
|
|
343
343
|
];
|
|
344
344
|
|
|
345
|
+
const returning: readonly EntityDriverCheck[] = [
|
|
346
|
+
checkOver(
|
|
347
|
+
{ notes },
|
|
348
|
+
'updateWhereReturning answers the rows it wrote, as stored; a second claim answers []',
|
|
349
|
+
async (db, { driver }) => {
|
|
350
|
+
// Optional on `Repo`: a hand-written driver without it has no rows to answer, and is refused.
|
|
351
|
+
if (driver.repo(notes).updateWhereReturning === undefined) return;
|
|
352
|
+
await seedNotes(db);
|
|
353
|
+
const claim = () => db.notes.updateWhereReturning({ kind: 'a' }, { kind: 'claimed' });
|
|
354
|
+
const rows = await claim();
|
|
355
|
+
expect(rows.map((row) => [row.id, row.kind, row.title]).sort()).toEqual([
|
|
356
|
+
[ONE, 'claimed', 'one'],
|
|
357
|
+
[TWO, 'claimed', 'two'],
|
|
358
|
+
]);
|
|
359
|
+
expect(rows.every((row) => row.updatedAt > WHEN)).toBe(true);
|
|
360
|
+
expect(await claim()).toEqual([]);
|
|
361
|
+
expect(await db.notes.where({ kind: 'b' }).count()).toBe(1);
|
|
362
|
+
const one = await db.notes.updateWhereReturning({ id: ONE, kind: 'claimed' }, { kind: 'x' });
|
|
363
|
+
expect(one.map((row) => row.id)).toEqual([ONE]);
|
|
364
|
+
expect(await codeOf(() => db.notes.updateWhereReturning({}, { kind: 'y' }))).toBe(UNFILTERED);
|
|
365
|
+
},
|
|
366
|
+
),
|
|
367
|
+
checkOver(
|
|
368
|
+
{ swept },
|
|
369
|
+
'updateWhereReturning breaking a JS-only rule on one row is refused as one; no row moves',
|
|
370
|
+
async (db, { driver }) => {
|
|
371
|
+
if (driver.repo(swept).updateWhereReturning === undefined) return;
|
|
372
|
+
await db.swept.insertAll([
|
|
373
|
+
{ id: ONE, kind: 'k', reason: 'fine', deletedAt: null },
|
|
374
|
+
{ id: TWO, kind: 'k', reason: null, deletedAt: null },
|
|
375
|
+
]);
|
|
376
|
+
const stamp = () => db.swept.updateWhereReturning({ kind: 'k' }, { deletedAt: WHEN });
|
|
377
|
+
expect(await codeOf(stamp)).toBe('X_INVARIANT_VIOLATED');
|
|
378
|
+
expect((await db.swept.orderBy('id').all()).map((row) => row.reason)).toEqual(['fine', null]);
|
|
379
|
+
},
|
|
380
|
+
),
|
|
381
|
+
checkOver(
|
|
382
|
+
{ vault },
|
|
383
|
+
'updateWhereReturning answers a sealed value by name only, and refuses a sealed filter',
|
|
384
|
+
async (db, { driver }) => {
|
|
385
|
+
if (driver.repo(vault).updateWhereReturning === undefined) return;
|
|
386
|
+
await db.vault.insert({ id: ONE, label: 'a', secret: null, email: 'a@example.com' });
|
|
387
|
+
const [row] = await db.vault.updateWhereReturning({ label: 'a' }, { secret: 'hunter2' });
|
|
388
|
+
expect([row?.secret, row?.email]).toEqual(['hunter2', 'a@example.com']);
|
|
389
|
+
expect(JSON.stringify(row)).not.toMatch(/secret|hunter2|email/);
|
|
390
|
+
const named = () =>
|
|
391
|
+
db.vault.updateWhereReturning({ email: 'a@example.com' } as never, { label: 'x' });
|
|
392
|
+
expect(await codeOf(named)).toBe('X_ENTITY_SEALED_PREDICATE');
|
|
393
|
+
},
|
|
394
|
+
),
|
|
395
|
+
];
|
|
396
|
+
|
|
345
397
|
export const CHAIN_WRITE_CHECKS: readonly EntityDriverCheck[] = [
|
|
346
398
|
...terminals,
|
|
347
399
|
...tenancy,
|
|
348
400
|
...semantics,
|
|
349
401
|
...reported,
|
|
402
|
+
...returning,
|
|
350
403
|
];
|
package/src/errors.ts
CHANGED
|
@@ -84,6 +84,7 @@ export const TESTING_ERROR_CODES = [
|
|
|
84
84
|
'X_TEST_TEMP_TREE_LEFT',
|
|
85
85
|
'X_TEST_ISLAND_BUILD_REUSED',
|
|
86
86
|
'X_DRILL_TEARDOWN_FAILED',
|
|
87
|
+
'X_QUERY_PLAN_OVER_BUDGET',
|
|
87
88
|
] as const;
|
|
88
89
|
|
|
89
90
|
export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
|
|
@@ -171,6 +172,7 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
|
|
|
171
172
|
X_TEST_TEMP_TREE_LEFT: 'a temp tree survived its own remove',
|
|
172
173
|
X_TEST_ISLAND_BUILD_REUSED: 'an island builder answered the shipped build with the coverage one',
|
|
173
174
|
X_DRILL_TEARDOWN_FAILED: 'a fault drill could not drop its scratch database',
|
|
175
|
+
X_QUERY_PLAN_OVER_BUDGET: 'a query plan exceeds the budget the test set',
|
|
174
176
|
};
|
|
175
177
|
|
|
176
178
|
// Titles must be registered for `format()` to render the contract's first line. Every code above is
|
package/src/fixture-subscribe.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import type { Actor } from '@ultimat3/core';
|
|
11
11
|
import { UltimateError } from '@ultimat3/core';
|
|
12
|
+
import type { LiveCursor, RowPatch } from '@ultimat3/realtime';
|
|
12
13
|
import type { LiveReplicator } from '@ultimat3/realtime/server';
|
|
13
14
|
import { startLiveReplicator } from '@ultimat3/realtime/server';
|
|
14
15
|
import type { LiveFeed, LiveFeedPatch, LiveTarget } from './fixture-drivers';
|
|
@@ -24,20 +25,17 @@ interface SnapshotFrameLike {
|
|
|
24
25
|
readonly type: 'snapshot';
|
|
25
26
|
readonly sid: string;
|
|
26
27
|
readonly rows: readonly Row[];
|
|
27
|
-
/**
|
|
28
|
-
readonly cursor:
|
|
28
|
+
/** The node's cursor, signed for this subscriber; its `sig` is never computed here. */
|
|
29
|
+
readonly cursor: LiveCursor;
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
interface PatchFrameLike {
|
|
32
33
|
readonly type: 'patch';
|
|
33
34
|
readonly sid: string;
|
|
34
|
-
readonly patches: readonly
|
|
35
|
-
readonly op: 'insert' | 'update' | 'delete';
|
|
36
|
-
readonly id: string;
|
|
37
|
-
readonly row: Record<string, unknown> | null;
|
|
38
|
-
readonly lsn: string;
|
|
39
|
-
}[];
|
|
35
|
+
readonly patches: readonly RowPatch[];
|
|
40
36
|
readonly lsn: string;
|
|
37
|
+
/** The node's signature of the cursor these patches leave the subscriber on. */
|
|
38
|
+
readonly sig?: string;
|
|
41
39
|
}
|
|
42
40
|
|
|
43
41
|
export interface SubscribeDriver {
|
|
@@ -123,7 +121,7 @@ export async function subscribeDriver(): Promise<SubscribeDriver> {
|
|
|
123
121
|
let rows: readonly Row[] = [];
|
|
124
122
|
let snapshots = 0;
|
|
125
123
|
let lsn = '';
|
|
126
|
-
let cursor:
|
|
124
|
+
let cursor: LiveCursor | null = null;
|
|
127
125
|
const patches: LiveFeedPatch<R>[] = [];
|
|
128
126
|
const frames = mine();
|
|
129
127
|
for (const frame of frames) {
|
|
@@ -142,6 +140,13 @@ export async function subscribeDriver(): Promise<SubscribeDriver> {
|
|
|
142
140
|
patches.push({ op: one.op, row: { id: one.id, ...(one.row ?? {}) } as unknown as R });
|
|
143
141
|
}
|
|
144
142
|
lsn = patch.lsn;
|
|
143
|
+
// The cursor moves with every patch, as a browser's does (`client-frames.ts`): the ids
|
|
144
|
+
// through realtime's own `advance`, and the sig THIS frame carried — the snapshot's sig
|
|
145
|
+
// covers the snapshot's position, and beside a later lsn it reads as a tampered cursor.
|
|
146
|
+
if (cursor !== null && patch.lsn !== '') {
|
|
147
|
+
const next: LiveCursor = realtime.advance(cursor, patch.patches, patch.lsn, cursor.at);
|
|
148
|
+
cursor = patch.sig === undefined ? next : { ...next, sig: patch.sig };
|
|
149
|
+
}
|
|
145
150
|
}
|
|
146
151
|
const last = marks[marks.length - 1];
|
|
147
152
|
const resumedFrom =
|
|
@@ -169,9 +174,10 @@ export async function subscribeDriver(): Promise<SubscribeDriver> {
|
|
|
169
174
|
reconnect: async () => {
|
|
170
175
|
const held = state();
|
|
171
176
|
if (held.cursor === null) return;
|
|
172
|
-
// The cursor the client holds: the snapshot's, advanced
|
|
173
|
-
// is what a real client
|
|
174
|
-
|
|
177
|
+
// The cursor the client holds: the snapshot's, advanced over every patch it applied and
|
|
178
|
+
// carrying the last frame's sig. That is what a real client sends back, verbatim, and what
|
|
179
|
+
// the node verifies before `resumeFrom` compares it against the retained window.
|
|
180
|
+
const askedLsn = held.cursor.lsn;
|
|
175
181
|
marks.push({ at: held.frames.length, askedLsn });
|
|
176
182
|
connection.send({
|
|
177
183
|
type: 'subscribe',
|
|
@@ -190,7 +196,7 @@ export async function subscribeDriver(): Promise<SubscribeDriver> {
|
|
|
190
196
|
kind: 'query',
|
|
191
197
|
qid: target.name,
|
|
192
198
|
input,
|
|
193
|
-
cursor:
|
|
199
|
+
cursor: held.cursor,
|
|
194
200
|
},
|
|
195
201
|
});
|
|
196
202
|
await replicator.settled();
|
package/src/index.ts
CHANGED
|
@@ -388,6 +388,8 @@ export { recordSteps } from './matchers';
|
|
|
388
388
|
export type { MockHandler, MockRoute } from './mock-route';
|
|
389
389
|
// The plan and scale sweeps (plan 101 / 40-next-query-plans): every statement the pass sent planned
|
|
390
390
|
// with no index but the declared ones, every reached primitive again at 2 and 8 rows a table.
|
|
391
|
+
export type { ExpectPlanOptions, PlanBudget } from './plan-budget';
|
|
392
|
+
export { expectPlanWithin } from './plan-budget';
|
|
391
393
|
export type { PlanVerdictCode } from './plan-oracle';
|
|
392
394
|
export type { PlanExempt, PlanProof, SentStatement } from './plan-sweep';
|
|
393
395
|
export { QueryPlanUnavailableError, sweepPlans } from './plan-sweep';
|
|
@@ -405,6 +407,16 @@ export { gen, HOSTILE_CHARS } from './property-gen';
|
|
|
405
407
|
// registry into every test in the framework. Every other package this harness touches is imported
|
|
406
408
|
// dynamically inside the fixture that needs it; a helper that must stay synchronous cannot do that,
|
|
407
409
|
// so it gets its own entry point instead.
|
|
410
|
+
// A concurrency test: calls fired together, every lost serialization race listed; a `decide()`
|
|
411
|
+
// answer stated as one split.
|
|
412
|
+
export type {
|
|
413
|
+
PartialAnswer,
|
|
414
|
+
PartialExpectation,
|
|
415
|
+
RaceOptions,
|
|
416
|
+
RaceReport,
|
|
417
|
+
SerializationFailure,
|
|
418
|
+
} from './race-actions';
|
|
419
|
+
export { expectPartial, raceActions } from './race-actions';
|
|
408
420
|
export type { RegistryLeak } from './registry-leak-guard';
|
|
409
421
|
export { installRegistryLeakGuard } from './registry-leak-guard';
|
|
410
422
|
export type { ProcessRegistrySnapshot } from './registry-snapshot';
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The two refusals of `expectPlanWithin`: a plan over the budget the test set (the code is
|
|
2
|
+
// registered in `errors.ts`), and an answer that is no plan, which is never read as a free one.
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
renderCauseValue,
|
|
6
|
+
renderFixLiteral,
|
|
7
|
+
renderFixShellArg,
|
|
8
|
+
UltimateError,
|
|
9
|
+
} from '@ultimat3/core';
|
|
10
|
+
import type { PlanBudget, PlanRead } from './plan-budget-read';
|
|
11
|
+
|
|
12
|
+
/** The index `planFindings` named for the red node: the entity, and the properties it leads with. */
|
|
13
|
+
export interface PlanIndexFix {
|
|
14
|
+
readonly entity: string;
|
|
15
|
+
readonly property: readonly string[];
|
|
16
|
+
/** The whole `indexes:` entry when a bare `on:` would not serve it (a trigram index). */
|
|
17
|
+
readonly declaration?: string | undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class PlanOverBudgetError extends UltimateError {
|
|
21
|
+
constructor(input: {
|
|
22
|
+
readonly read: PlanRead;
|
|
23
|
+
readonly budget: PlanBudget;
|
|
24
|
+
readonly index?: PlanIndexFix | undefined;
|
|
25
|
+
}) {
|
|
26
|
+
const { read, budget, index } = input;
|
|
27
|
+
const table = renderFixShellArg(read.table, '<table>');
|
|
28
|
+
const entry =
|
|
29
|
+
index?.declaration ??
|
|
30
|
+
`indexes: [{ on: [${index?.property.map((p) => `'${p}'`).join(', ')}] }]`;
|
|
31
|
+
super({
|
|
32
|
+
code: 'X_QUERY_PLAN_OVER_BUDGET',
|
|
33
|
+
cause: `the planner estimates total cost ${String(read.totalCost)} (budget ${String(budget.maxCost)}) and ${String(read.sortRows)} rows sorted (budget ${String(budget.maxSortRows)}), at ${renderCauseValue(read.node)} on ${renderCauseValue(read.table)}`,
|
|
34
|
+
fix:
|
|
35
|
+
index === undefined
|
|
36
|
+
? `x db gen "index ${table} <columns>" — after indexes: [{ on: ['<columns>'] }] in the entity of ${table}; or analyze ${table} after seeding, and raise the budget only by the measured number`
|
|
37
|
+
: `x db gen "index ${table}" — after ${entry} in entity(${renderFixLiteral(index.entity, '<entity>')})`,
|
|
38
|
+
meta: {
|
|
39
|
+
totalCost: read.totalCost,
|
|
40
|
+
sortRows: read.sortRows,
|
|
41
|
+
node: read.node,
|
|
42
|
+
table: read.table,
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The answer handed to the budget reader holds no `Total Cost`: it is not `explain (format json)`. */
|
|
49
|
+
export class PlanUnreadableError extends UltimateError {
|
|
50
|
+
constructor() {
|
|
51
|
+
super({
|
|
52
|
+
code: 'X_QUERY_PLAN_UNAVAILABLE',
|
|
53
|
+
cause:
|
|
54
|
+
'expectPlanWithin read an explain answer with no plan root and no Total Cost, so no budget was judged',
|
|
55
|
+
fix: 'expectPlanWithin(sql`select …`, { maxCost: 500, maxSortRows: 1000 }) # a select the database can plan',
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Reads one `explain (format json)` answer for a budget: the root's `Total Cost` and the largest
|
|
2
|
+
// `Plan Rows` on any `Sort`. Pure; the judge of which index would end it is `plan-oracle.ts`'s.
|
|
3
|
+
|
|
4
|
+
import { PlanUnreadableError } from './plan-budget-error';
|
|
5
|
+
import { planRoot } from './plan-oracle';
|
|
6
|
+
|
|
7
|
+
export interface PlanBudget {
|
|
8
|
+
readonly maxCost: number;
|
|
9
|
+
readonly maxSortRows: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface PlanRead {
|
|
13
|
+
readonly totalCost: number;
|
|
14
|
+
/** The largest estimated row count under any `Sort`; 0 when the plan sorts nothing. */
|
|
15
|
+
readonly sortRows: number;
|
|
16
|
+
/** The node the budget broke on: the largest `Sort`, else the root. */
|
|
17
|
+
readonly node: string;
|
|
18
|
+
/** The first physical table read beneath that node, or `''`. */
|
|
19
|
+
readonly table: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type Raw = Readonly<Record<string, unknown>>;
|
|
23
|
+
|
|
24
|
+
const record = (value: unknown): Raw | undefined =>
|
|
25
|
+
typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Raw) : undefined;
|
|
26
|
+
const num = (value: unknown): number | undefined =>
|
|
27
|
+
typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
28
|
+
const children = (node: Raw): readonly Raw[] =>
|
|
29
|
+
Array.isArray(node['Plans'])
|
|
30
|
+
? node['Plans'].flatMap((c: unknown): Raw[] => {
|
|
31
|
+
const child = record(c);
|
|
32
|
+
return child === undefined ? [] : [child];
|
|
33
|
+
})
|
|
34
|
+
: [];
|
|
35
|
+
|
|
36
|
+
const tableBeneath = (node: Raw): string => {
|
|
37
|
+
if (typeof node['Relation Name'] === 'string') return node['Relation Name'];
|
|
38
|
+
for (const child of children(node)) {
|
|
39
|
+
const found = tableBeneath(child);
|
|
40
|
+
if (found !== '') return found;
|
|
41
|
+
}
|
|
42
|
+
return '';
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Both nodes hold rows to order them: an incremental sort is a sort with a presorted prefix. */
|
|
46
|
+
const SORTS: ReadonlySet<string> = new Set(['Sort', 'Incremental Sort']);
|
|
47
|
+
|
|
48
|
+
const sortsIn = (node: Raw): readonly Raw[] => [
|
|
49
|
+
...(SORTS.has(String(node['Node Type'])) ? [node] : []),
|
|
50
|
+
...children(node).flatMap(sortsIn),
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
/** The numbers a budget judges. A plan with no root `Total Cost` is refused, never read as free. */
|
|
54
|
+
export function readPlanBudget(answer: unknown): PlanRead {
|
|
55
|
+
const root = record(planRoot(answer));
|
|
56
|
+
const totalCost = num(root?.['Total Cost']);
|
|
57
|
+
if (root === undefined || totalCost === undefined) {
|
|
58
|
+
throw new PlanUnreadableError();
|
|
59
|
+
}
|
|
60
|
+
const largest = sortsIn(root).reduce<Raw | undefined>(
|
|
61
|
+
(best, sort) =>
|
|
62
|
+
(num(sort['Plan Rows']) ?? 0) > (num(best?.['Plan Rows']) ?? -1) ? sort : best,
|
|
63
|
+
undefined,
|
|
64
|
+
);
|
|
65
|
+
const at = largest ?? root;
|
|
66
|
+
return {
|
|
67
|
+
totalCost,
|
|
68
|
+
sortRows: num(largest?.['Plan Rows']) ?? 0,
|
|
69
|
+
node: typeof at['Node Type'] === 'string' ? at['Node Type'] : 'unknown',
|
|
70
|
+
table: tableBeneath(at),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export const overBudget = (read: PlanRead, budget: PlanBudget): boolean =>
|
|
75
|
+
read.totalCost > budget.maxCost || read.sortRows > budget.maxSortRows;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// `expectPlanWithin(fragment, { maxCost, maxSortRows })`: the app test's plan budget. Both numbers
|
|
2
|
+
// are the caller's — there is no default, because a budget is a measurement of that app's schema
|
|
3
|
+
// on that engine. Plans only: `explain (format json)` in a read-only transaction, never `analyze`,
|
|
4
|
+
// so the statement is not executed.
|
|
5
|
+
|
|
6
|
+
import { finiteCount, finiteOption } from '@ultimat3/core';
|
|
7
|
+
import type { DbClient, SqlFragment } from '@ultimat3/db';
|
|
8
|
+
import { db, sql, withReadTransaction } from '@ultimat3/db';
|
|
9
|
+
import './errors';
|
|
10
|
+
import { type PlanIndexFix, PlanOverBudgetError } from './plan-budget-error';
|
|
11
|
+
import { overBudget, type PlanBudget, readPlanBudget } from './plan-budget-read';
|
|
12
|
+
import { judgeStatement } from './plan-sweep';
|
|
13
|
+
import { planFindings } from './plan-sweep-fix';
|
|
14
|
+
import type { SeedEntity } from './seed-graph-shape';
|
|
15
|
+
|
|
16
|
+
export type { PlanBudget } from './plan-budget-read';
|
|
17
|
+
|
|
18
|
+
export interface ExpectPlanOptions {
|
|
19
|
+
/** Default: the installed db client. */
|
|
20
|
+
readonly client?: DbClient | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* The app's entities. Given, an over-budget plan is judged once more and the error names the
|
|
23
|
+
* `indexes:` entry that answers it; absent, the fix is `analyze`.
|
|
24
|
+
*/
|
|
25
|
+
readonly entities?: readonly SeedEntity[] | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function explainJson(fragment: SqlFragment, client: DbClient | undefined): Promise<unknown> {
|
|
29
|
+
const rows = await withReadTransaction(
|
|
30
|
+
(tx) => tx.query<Record<string, unknown>>(sql`explain (format json) ${fragment}`),
|
|
31
|
+
{ client },
|
|
32
|
+
);
|
|
33
|
+
return rows[0]?.['QUERY PLAN'];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function indexFor(
|
|
37
|
+
fragment: SqlFragment,
|
|
38
|
+
client: DbClient,
|
|
39
|
+
entities: readonly SeedEntity[],
|
|
40
|
+
): Promise<PlanIndexFix | undefined> {
|
|
41
|
+
const tables = entities.filter((entity) => entity.$describe().view === undefined);
|
|
42
|
+
const judged = new Map(
|
|
43
|
+
tables.map((entity) => [
|
|
44
|
+
entity.$table,
|
|
45
|
+
new Set(entity.$describe().columns.map((c) => c.column)),
|
|
46
|
+
]),
|
|
47
|
+
);
|
|
48
|
+
const { verdicts } = await judgeStatement(client, fragment.text, judged);
|
|
49
|
+
if (verdicts === undefined || verdicts.length === 0) return undefined;
|
|
50
|
+
const byTable = new Map(tables.map((entity) => [entity.$table, entity]));
|
|
51
|
+
const found = planFindings(fragment.text, verdicts, byTable).find((f) => f.index.length > 0);
|
|
52
|
+
return found === undefined
|
|
53
|
+
? undefined
|
|
54
|
+
: { entity: found.entity, property: found.index, declaration: found.declaration };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Plan `fragment` with its real parameters and refuse past `maxCost` (the root's `Total Cost`) or
|
|
59
|
+
* `maxSortRows` (the largest `Plan Rows` on any `Sort`). Analyze after seeding, and set one budget
|
|
60
|
+
* per engine: PGlite and Postgres cost the same plan differently.
|
|
61
|
+
*/
|
|
62
|
+
export async function expectPlanWithin(
|
|
63
|
+
fragment: SqlFragment,
|
|
64
|
+
budget: PlanBudget,
|
|
65
|
+
options: ExpectPlanOptions = {},
|
|
66
|
+
): Promise<void> {
|
|
67
|
+
finiteOption('expectPlanWithin', 'maxCost', budget.maxCost);
|
|
68
|
+
finiteCount('expectPlanWithin', 'maxSortRows', budget.maxSortRows, 0);
|
|
69
|
+
const read = readPlanBudget(await explainJson(fragment, options.client));
|
|
70
|
+
if (!overBudget(read, budget)) return;
|
|
71
|
+
const index =
|
|
72
|
+
options.entities === undefined
|
|
73
|
+
? undefined
|
|
74
|
+
: await indexFor(fragment, options.client ?? db(), options.entities);
|
|
75
|
+
throw new PlanOverBudgetError({ read, budget, index });
|
|
76
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Concurrency helpers for an app test: `raceActions` fires calls at once, round after round, and
|
|
2
|
+
// reports every deadlock or lost serialization race (SQLSTATE 40P01 / 40001, both
|
|
3
|
+
// `X_DB_SERIALIZATION_FAILURE`); `expectPartial` states a `decide()` answer in one call.
|
|
4
|
+
|
|
5
|
+
import { expect } from 'bun:test';
|
|
6
|
+
import { assertCoded } from '@ultimat3/core';
|
|
7
|
+
import { DB_SQLSTATE_CODES, sqlState } from '@ultimat3/db';
|
|
8
|
+
|
|
9
|
+
export interface RaceOptions {
|
|
10
|
+
/** How many times the whole set is fired. Required: how hard to race is the test's decision. */
|
|
11
|
+
readonly rounds: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SerializationFailure {
|
|
15
|
+
readonly round: number;
|
|
16
|
+
readonly call: number;
|
|
17
|
+
readonly code: 'X_DB_SERIALIZATION_FAILURE';
|
|
18
|
+
/** The SQLSTATE: `40P01` (deadlock) or `40001` (serialization failure). */
|
|
19
|
+
readonly sqlState: string;
|
|
20
|
+
readonly error: unknown;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface RaceReport<T> {
|
|
24
|
+
readonly rounds: number;
|
|
25
|
+
/** Per round, per call, in the order the calls were given. */
|
|
26
|
+
readonly settled: readonly (readonly PromiseSettledResult<T>[])[];
|
|
27
|
+
/** Every rejection that is a lost race. Empty is the property the test asserts. */
|
|
28
|
+
readonly serializationFailures: readonly SerializationFailure[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function lostRace(error: unknown): string | undefined {
|
|
32
|
+
const state = sqlState(error);
|
|
33
|
+
return state !== undefined && DB_SQLSTATE_CODES[state] === 'X_DB_SERIALIZATION_FAILURE'
|
|
34
|
+
? state
|
|
35
|
+
: undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Run `calls` concurrently, `rounds` times, each round after the last has settled. Never throws
|
|
40
|
+
* for a call's own failure: a rejection is in `settled`, and a lost race is also listed in
|
|
41
|
+
* `serializationFailures`, so a test can assert it is empty (or, for a retry test, not).
|
|
42
|
+
*/
|
|
43
|
+
export async function raceActions<T>(
|
|
44
|
+
calls: readonly (() => Promise<T>)[],
|
|
45
|
+
options: RaceOptions,
|
|
46
|
+
): Promise<RaceReport<T>> {
|
|
47
|
+
assertCoded(
|
|
48
|
+
calls.length >= 2,
|
|
49
|
+
'X_INVARIANT',
|
|
50
|
+
`raceActions got ${String(calls.length)} call(s): one call races nothing, so a green result would prove nothing`,
|
|
51
|
+
'raceActions([() => a(), () => b()], { rounds: 20 }) # at least two calls',
|
|
52
|
+
);
|
|
53
|
+
assertCoded(
|
|
54
|
+
Number.isInteger(options.rounds) && options.rounds >= 1,
|
|
55
|
+
'X_INVARIANT',
|
|
56
|
+
'raceActions({ rounds }) needs a whole number of rounds, 1 or more',
|
|
57
|
+
'raceActions([() => a(), () => b()], { rounds: 20 })',
|
|
58
|
+
);
|
|
59
|
+
const settled: PromiseSettledResult<T>[][] = [];
|
|
60
|
+
const serializationFailures: SerializationFailure[] = [];
|
|
61
|
+
for (let round = 0; round < options.rounds; round += 1) {
|
|
62
|
+
const results = await Promise.allSettled(calls.map((call) => Promise.try(call)));
|
|
63
|
+
results.forEach((result, call) => {
|
|
64
|
+
if (result.status !== 'rejected') return;
|
|
65
|
+
const state = lostRace(result.reason);
|
|
66
|
+
if (state === undefined) return;
|
|
67
|
+
serializationFailures.push({
|
|
68
|
+
round,
|
|
69
|
+
call,
|
|
70
|
+
code: 'X_DB_SERIALIZATION_FAILURE',
|
|
71
|
+
sqlState: state,
|
|
72
|
+
error: result.reason,
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
settled.push(results);
|
|
76
|
+
}
|
|
77
|
+
return { rounds: options.rounds, settled, serializationFailures };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The shape of an action's `decide()` answer, typed structurally: no import from `action`. */
|
|
81
|
+
export interface PartialAnswer<TRow> {
|
|
82
|
+
readonly allowed: readonly TRow[];
|
|
83
|
+
readonly denied: readonly {
|
|
84
|
+
readonly row: TRow;
|
|
85
|
+
readonly code: string;
|
|
86
|
+
readonly reason: string;
|
|
87
|
+
}[];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface PartialExpectation<TRow> {
|
|
91
|
+
readonly allowed: readonly TRow[];
|
|
92
|
+
/** A denied row, and optionally the `code` / `reason` it must carry. */
|
|
93
|
+
readonly denied: readonly {
|
|
94
|
+
readonly row: TRow;
|
|
95
|
+
readonly code?: string | undefined;
|
|
96
|
+
readonly reason?: string | undefined;
|
|
97
|
+
}[];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The answer's allowed rows, and its denied rows with the code and reason stated, are exactly these. */
|
|
101
|
+
export function expectPartial<TRow>(
|
|
102
|
+
result: PartialAnswer<TRow>,
|
|
103
|
+
expected: PartialExpectation<TRow>,
|
|
104
|
+
): void {
|
|
105
|
+
expect(result.allowed).toEqual(expected.allowed as TRow[]);
|
|
106
|
+
expect(result.denied.map((d) => d.row)).toEqual(expected.denied.map((d) => d.row));
|
|
107
|
+
expected.denied.forEach((want, at) => {
|
|
108
|
+
const got = result.denied[at];
|
|
109
|
+
if (want.code !== undefined) expect(got?.code).toBe(want.code);
|
|
110
|
+
if (want.reason !== undefined) expect(got?.reason).toBe(want.reason);
|
|
111
|
+
});
|
|
112
|
+
}
|