@ultimat3/testing 30.6.0 → 30.8.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 +3 -3
- package/README.md +1 -1
- package/package.json +17 -17
- package/src/define-exercise.ts +53 -17
- package/src/drill-writes.ts +3 -1
- package/src/errors.ts +9 -90
- package/src/exercise-actor-user.ts +63 -0
- package/src/exercise-actor.ts +64 -11
- package/src/exercise-crash.ts +7 -3
- package/src/exercise-drift-hint.ts +28 -0
- package/src/exercise-input.ts +3 -0
- package/src/exercise-job-tenant.ts +10 -5
- package/src/exercise-judge.ts +78 -0
- package/src/exercise-observed.ts +93 -0
- package/src/exercise-override-input.ts +56 -6
- package/src/exercise-report.ts +43 -2
- package/src/exercise-request.ts +7 -24
- package/src/exercise-setup.ts +34 -17
- package/src/exercise-subjects.ts +20 -5
- package/src/exercise-sweeps.ts +57 -12
- package/src/exercise.ts +141 -109
- package/src/fixture-island.ts +1 -1
- package/src/index.ts +4 -0
- package/src/island-errors.ts +82 -0
- package/src/job-crash-points.ts +36 -0
- package/src/job-crash-proof.ts +23 -6
- package/src/job-sim-errors.ts +24 -0
- package/src/plan-conditions.ts +106 -0
- package/src/plan-oracle.ts +93 -57
- package/src/plan-probes.ts +94 -0
- package/src/plan-sort-key.ts +65 -0
- package/src/plan-sweep-fix.ts +99 -22
- package/src/plan-sweep-report.ts +48 -4
- package/src/scale-sweep-graph.ts +3 -0
- package/src/scale-sweep-run.ts +14 -7
- package/src/seed-graph-plan.ts +11 -0
- package/src/seed-graph-values.ts +20 -11
- package/src/seed-graph.ts +39 -3
- package/src/subject-proof.ts +12 -2
- package/src/tenant-proof-report.ts +84 -25
- package/src/tenant-proof.ts +39 -6
- package/src/seed-pattern-sample.ts +0 -216
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The two refusals `mountIsland` gives before any island code runs: the file the test named was
|
|
2
|
+
// not built, or its chunk exports no `mount`. Codes registered with the rest in `errors.ts`.
|
|
3
|
+
|
|
4
|
+
import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
|
|
5
|
+
|
|
6
|
+
/** Neither path is controlled by the framework: both arrive from the test's own call. */
|
|
7
|
+
const ISLAND_PLACEHOLDER = '<the island path the cause names>';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The builder produced no chunk for the file the test named. Listing what it DID build is the
|
|
11
|
+
* whole value: a path relative to the test file instead of to the app root, a typo, and an island
|
|
12
|
+
* outside the discovery glob are one symptom and three different edits, and only the list tells
|
|
13
|
+
* them apart. An empty list is its own answer — the glob found nothing at all under this root.
|
|
14
|
+
*/
|
|
15
|
+
export class IslandNotBuiltError extends UltimateError {
|
|
16
|
+
constructor(input: { file: string; root: string; built: readonly string[] }) {
|
|
17
|
+
const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
|
|
18
|
+
super({
|
|
19
|
+
code: 'X_TEST_ISLAND_NOT_BUILT',
|
|
20
|
+
cause:
|
|
21
|
+
input.built.length === 0
|
|
22
|
+
? `no island was built under ${renderCauseValue(input.root)}, so ${renderCauseValue(input.file)} cannot be mounted`
|
|
23
|
+
: `${renderCauseValue(input.file)} is not in the bundle built from ${renderCauseValue(input.root)}; it built ${input.built.join(', ')}`,
|
|
24
|
+
fix:
|
|
25
|
+
input.built.length === 0
|
|
26
|
+
? 'x g island <name> --at apps/web/site — then set root to the directory holding apps/'
|
|
27
|
+
: `mountIsland({ build, root, file: ${renderFixLiteral(input.built[0], ISLAND_PLACEHOLDER)} }) — the path is app-root-relative, not relative to the test, and ${file} is not one of them`,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const islandNotBuilt = (
|
|
33
|
+
file: string,
|
|
34
|
+
root: string,
|
|
35
|
+
built: readonly string[],
|
|
36
|
+
): UltimateError => new IslandNotBuiltError({ file, root, built });
|
|
37
|
+
|
|
38
|
+
/** A name that can be written as a JSX tag. `export default` and `export { x as 'a b' }` are both
|
|
39
|
+
* legal ES and neither can — a paste emitting one is a syntax error in the reader's own file. */
|
|
40
|
+
const JSX_NAME = /^[A-Za-z_$][\w$]*$/;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The export the paste renders. A component first — an initial capital that is not the whole name,
|
|
44
|
+
* which is what separates `Counter` from a `PROPS` constant — and any other usable identifier
|
|
45
|
+
* after it, because a lowercase component still compiles and beats a name the reader must invent.
|
|
46
|
+
*/
|
|
47
|
+
const componentOf = (exported: readonly string[]): string | undefined => {
|
|
48
|
+
const usable = exported.filter((name) => JSX_NAME.test(name) && name !== 'default');
|
|
49
|
+
return usable.find((name) => /^[A-Z]/.test(name) && name !== name.toUpperCase()) ?? usable[0];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The chunk built and imported, and exports no `mount`. Distinct from a build failure: the island
|
|
54
|
+
* compiles, ships and is served — the hydration runtime calls `m.mount(el, props)` and the browser
|
|
55
|
+
* throws on a page that passed every gate. Naming the exports it DOES have is what separates a
|
|
56
|
+
* renamed export from a file that exports only its component.
|
|
57
|
+
*
|
|
58
|
+
* The paste is built from THOSE exports rather than from a sketch. It read
|
|
59
|
+
* `render(() => <Island {...props} />, el)` with `props: Props` until 2026-08-21, and none of
|
|
60
|
+
* `Island`, `Props` or `render` exists in the file the reader was told to paste it into — three
|
|
61
|
+
* compile errors handed out as the remedy for one. Two of them the error already knew the answer
|
|
62
|
+
* to, from its own cause; the third is an import, so the import is in the line.
|
|
63
|
+
*/
|
|
64
|
+
export class IslandMountMissingError extends UltimateError {
|
|
65
|
+
constructor(input: { file: string; exported: readonly string[] }) {
|
|
66
|
+
const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
|
|
67
|
+
const component = componentOf(input.exported);
|
|
68
|
+
super({
|
|
69
|
+
code: 'X_TEST_ISLAND_NO_MOUNT',
|
|
70
|
+
cause: `the chunk built from ${renderCauseValue(input.file)} exports ${
|
|
71
|
+
input.exported.length === 0 ? 'nothing' : input.exported.join(', ')
|
|
72
|
+
} — the hydration runtime calls m.mount(el, props)`,
|
|
73
|
+
fix:
|
|
74
|
+
component === undefined
|
|
75
|
+
? `${file} exports nothing a mount could render — x g island <name> --at apps/web/site writes an island whose mount() is already there, and its shape is the one to copy`
|
|
76
|
+
: `in ${file} add: import { render } from 'solid-js/web'; export function mount(el: HTMLElement, props: Parameters<typeof ${component}>[0]): () => void { el.textContent = ''; return render(() => <${component} {...props} />, el); }`,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const islandMountMissing = (file: string, exported: readonly string[]): UltimateError =>
|
|
82
|
+
new IslandMountMissingError({ file, exported });
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Which boundaries a crash proof kills at. A loop's steps named by row id are one point of the
|
|
2
|
+
// code, not one per row: each boundary shape is killed at its first and its last occurrence, so the
|
|
3
|
+
// proof costs what the job's code has, never what the database holds. Pure: labels in, indexes out.
|
|
4
|
+
|
|
5
|
+
/** Kill points one mode of a proof may cost; past it the proof refuses, `X_JOB_CRASH_UNBOUNDED`. */
|
|
6
|
+
export const CRASH_POINT_BOUND = 32;
|
|
7
|
+
|
|
8
|
+
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
|
|
9
|
+
/** A ULID, a hex digest, a cuid: eight or more letters and digits with a digit among them. */
|
|
10
|
+
const TOKEN = /\b(?=[A-Za-z]*\d)[A-Za-z0-9]{8,}\b/g;
|
|
11
|
+
const DIGITS = /\d+/g;
|
|
12
|
+
|
|
13
|
+
/** `fanout:<id>`, `page-<n>`, `sleep:<n>h (sleeping)`: a boundary label with its ids taken out. */
|
|
14
|
+
export const boundaryShape = (label: string): string =>
|
|
15
|
+
label.replace(UUID, '<id>').replace(TOKEN, '<id>').replace(DIGITS, '<n>');
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The 1-based positions to kill at, in order: the first and the last boundary of every shape.
|
|
19
|
+
* The first proves the code before the loop and the loop's own body; the last, every row before it
|
|
20
|
+
* replayed and the code after it — an effect between any two rows is made again at the last.
|
|
21
|
+
*/
|
|
22
|
+
export function crashPoints(labels: readonly string[]): readonly number[] {
|
|
23
|
+
const first = new Map<string, number>();
|
|
24
|
+
const last = new Map<string, number>();
|
|
25
|
+
labels.forEach((label, i) => {
|
|
26
|
+
const shape = boundaryShape(label);
|
|
27
|
+
if (!first.has(shape)) first.set(shape, i + 1);
|
|
28
|
+
last.set(shape, i + 1);
|
|
29
|
+
});
|
|
30
|
+
return [...new Set([...first.values(), ...last.values()])].sort((a, b) => a - b);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The distinct shapes of `labels`, first seen first — what an unbounded refusal names. */
|
|
34
|
+
export const boundaryShapes = (labels: readonly string[]): readonly string[] => [
|
|
35
|
+
...new Set(labels.map(boundaryShape)),
|
|
36
|
+
];
|
package/src/job-crash-proof.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// `crashProof(handle, input)`: one clean run, then one run killed at each boundary the
|
|
2
|
-
// crossed —
|
|
3
|
-
// lost. Judged by the effect log: a killed run that makes an effect more often than the clean one
|
|
1
|
+
// `crashProof(handle, input)`: one clean run, then one run killed at each distinct boundary the
|
|
2
|
+
// clean run crossed — a step write landing, a settle; a loop's rows one point (`job-crash-points.ts`)
|
|
3
|
+
// — and one more where that write's answer is lost. Judged by the effect log: a killed run that makes an effect more often than the clean one
|
|
4
4
|
// is `X_JOB_CRASH_DIVERGED`; a lost answer rerunning a step is at-least-once, reported, never red.
|
|
5
5
|
|
|
6
6
|
import type { Ctx } from '@ultimat3/core';
|
|
@@ -8,11 +8,12 @@ import { finiteCount } from '@ultimat3/core';
|
|
|
8
8
|
import type { JobHandle } from '@ultimat3/jobs';
|
|
9
9
|
import { COMPENSATE_PREFIX, UNWINDING_STEP } from '@ultimat3/jobs';
|
|
10
10
|
import { advanceClock, frozenNow } from './determinism';
|
|
11
|
+
import { boundaryShapes, CRASH_POINT_BOUND, crashPoints } from './job-crash-points';
|
|
11
12
|
import type { SimDecision, SimOp } from './job-sim-driver';
|
|
12
13
|
import { SEND_AND_ANSWER } from './job-sim-driver';
|
|
13
14
|
import type { SimEffect } from './job-sim-effects';
|
|
14
15
|
import { effectCounts } from './job-sim-effects';
|
|
15
|
-
import { JobCrashDivergedError } from './job-sim-errors';
|
|
16
|
+
import { JobCrashDivergedError, JobCrashUnboundedError } from './job-sim-errors';
|
|
16
17
|
import type { SimWorld } from './job-sim-world';
|
|
17
18
|
import { openSimWorld } from './job-sim-world';
|
|
18
19
|
|
|
@@ -47,7 +48,10 @@ export interface CrashRerun {
|
|
|
47
48
|
}
|
|
48
49
|
|
|
49
50
|
export interface CrashReport {
|
|
51
|
+
/** The boundaries killed at: each distinct one the clean run crossed, a loop's rows as one. */
|
|
50
52
|
readonly boundaries: readonly CrashBoundary[];
|
|
53
|
+
/** Every boundary the clean run crossed, the forced-fail run's included: what the kills stand for. */
|
|
54
|
+
readonly crossed: number;
|
|
51
55
|
readonly divergences: readonly CrashDivergence[];
|
|
52
56
|
readonly reruns: readonly CrashRerun[];
|
|
53
57
|
}
|
|
@@ -212,6 +216,7 @@ export async function crashProof<I>(
|
|
|
212
216
|
const boundaries: CrashBoundary[] = [];
|
|
213
217
|
const divergences: CrashDivergence[] = [];
|
|
214
218
|
const reruns: CrashRerun[] = [];
|
|
219
|
+
let crossed = 0;
|
|
215
220
|
const modes: readonly CrashBoundary['mode'][] = handle.compensates
|
|
216
221
|
? ['clean', 'forced-fail']
|
|
217
222
|
: ['clean'];
|
|
@@ -228,7 +233,19 @@ export async function crashProof<I>(
|
|
|
228
233
|
: await runOnce(handle, input, { forceFail }, options);
|
|
229
234
|
const afterOf = (key: string): string | undefined =>
|
|
230
235
|
clean.effects.find((effect) => effect.key === key)?.after;
|
|
231
|
-
|
|
236
|
+
// Judged before the first kill: a proof past its bound costs one clean run, then refuses.
|
|
237
|
+
const points = crashPoints(clean.boundaries);
|
|
238
|
+
crossed += clean.boundaries.length;
|
|
239
|
+
if (points.length > CRASH_POINT_BOUND) {
|
|
240
|
+
throw new JobCrashUnboundedError({
|
|
241
|
+
job: handle.name,
|
|
242
|
+
points: points.length,
|
|
243
|
+
bound: CRASH_POINT_BOUND,
|
|
244
|
+
crossed: clean.boundaries.length,
|
|
245
|
+
shapes: boundaryShapes(clean.boundaries),
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
for (const at of points) {
|
|
232
249
|
const label = clean.boundaries[at - 1] ?? '?';
|
|
233
250
|
const killed = await runOnce(handle, input, { at, fault: 'kill', forceFail }, options);
|
|
234
251
|
boundaries.push({
|
|
@@ -272,5 +289,5 @@ export async function crashProof<I>(
|
|
|
272
289
|
}
|
|
273
290
|
}
|
|
274
291
|
}
|
|
275
|
-
return { boundaries, divergences, reruns };
|
|
292
|
+
return { boundaries, crossed, divergences, reruns };
|
|
276
293
|
}
|
package/src/job-sim-errors.ts
CHANGED
|
@@ -101,3 +101,27 @@ export class JobSimNondeterministicError extends UltimateError {
|
|
|
101
101
|
});
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
|
+
|
|
105
|
+
export interface CrashUnboundedInput {
|
|
106
|
+
readonly job: string;
|
|
107
|
+
/** Kill points the clean run's boundaries asked for, after a loop's rows were taken as one. */
|
|
108
|
+
readonly points: number;
|
|
109
|
+
readonly bound: number;
|
|
110
|
+
/** Boundaries the clean run crossed. */
|
|
111
|
+
readonly crossed: number;
|
|
112
|
+
/** The first distinct boundary shapes, in order: where the names that did not collapse are. */
|
|
113
|
+
readonly shapes: readonly string[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Refused before the first kill: a proof that grows with the rows is one no gate can wait for. */
|
|
117
|
+
export class JobCrashUnboundedError extends UltimateError {
|
|
118
|
+
constructor(input: CrashUnboundedInput) {
|
|
119
|
+
const shown = input.shapes.slice(0, 5).join(', ');
|
|
120
|
+
super({
|
|
121
|
+
code: 'X_JOB_CRASH_UNBOUNDED',
|
|
122
|
+
cause: `job ${renderCauseValue(input.job)} crossed ${input.crossed} step boundaries, ${input.points} distinct kill points against a bound of ${input.bound} — its steps are named so a loop's rows do not read as one point (first: ${renderCauseValue(shown)})`,
|
|
123
|
+
fix: `step.run(\`<name>:\${row.id}\`, async () => …) # in job(${renderFixLiteral(input.job, '<job>')}): name a per-row step by the row's id, so its loop is one kill point; then: x test job --filter <the test file>`,
|
|
124
|
+
meta: { ...input, shapes: [...input.shapes] },
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// A plan node's conditions, read as the columns one scanned table compares: by equality, by any
|
|
2
|
+
// other way, and per arm of an OR. An OR is served by one index per arm (a BitmapOr), never by one
|
|
3
|
+
// index over every column it names, so its arms are kept apart from the conjuncts around it.
|
|
4
|
+
|
|
5
|
+
/** The scan whose columns are read: its table and the alias the plan qualifies it by. */
|
|
6
|
+
export interface ConditionScan {
|
|
7
|
+
readonly table: string | undefined;
|
|
8
|
+
readonly alias: string | undefined;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ConditionColumns {
|
|
12
|
+
readonly equality: string[];
|
|
13
|
+
readonly range: string[];
|
|
14
|
+
/** The first OR whose every arm compares a column of the table: each arm's columns. */
|
|
15
|
+
readonly arms?: readonly (readonly string[])[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const IDENT = /(?:"?([A-Za-z_][\w$]*)"?\.)?"?([A-Za-z_][\w$]*)"?/g;
|
|
19
|
+
const EQUALITY = /(?<![<>!])=(?!>)/;
|
|
20
|
+
/** `IS NULL` pins one value as `=` does, and a btree serves it as an index condition. */
|
|
21
|
+
const IS_NULL = /\bIS\s+NULL\b/i;
|
|
22
|
+
|
|
23
|
+
/** The parts of `text` between `word`s that stand outside every parenthesis and literal. */
|
|
24
|
+
export function splitTop(text: string, word: 'AND' | 'OR'): string[] {
|
|
25
|
+
const parts: string[] = [];
|
|
26
|
+
let depth = 0;
|
|
27
|
+
let quoted = false;
|
|
28
|
+
let start = 0;
|
|
29
|
+
for (let at = 0; at < text.length; at += 1) {
|
|
30
|
+
const char = text[at];
|
|
31
|
+
if (char === "'") quoted = !quoted;
|
|
32
|
+
if (quoted) continue;
|
|
33
|
+
if (char === '(') depth += 1;
|
|
34
|
+
else if (char === ')') depth -= 1;
|
|
35
|
+
else if (depth === 0 && text.startsWith(` ${word} `, at)) {
|
|
36
|
+
parts.push(text.slice(start, at));
|
|
37
|
+
start = at + word.length + 2;
|
|
38
|
+
at = start - 1;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
parts.push(text.slice(start));
|
|
42
|
+
return parts.map(unwrap);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** `((a = $1))` → `a = $1`: parentheses that wrap the whole text, and only those. */
|
|
46
|
+
export function unwrap(text: string): string {
|
|
47
|
+
let rest = text.trim();
|
|
48
|
+
for (;;) {
|
|
49
|
+
if (!rest.startsWith('(') || !rest.endsWith(')')) return rest;
|
|
50
|
+
let depth = 0;
|
|
51
|
+
for (let at = 0; at < rest.length; at += 1) {
|
|
52
|
+
if (rest[at] === '(') depth += 1;
|
|
53
|
+
else if (rest[at] === ')') depth -= 1;
|
|
54
|
+
if (depth === 0 && at < rest.length - 1) return rest;
|
|
55
|
+
}
|
|
56
|
+
rest = rest.slice(1, -1).trim();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The columns of the table a conjunct names; a name qualified by another alias is not its. */
|
|
61
|
+
function namesIn(conjunct: string, scan: ConditionScan, columns: ReadonlySet<string>): string[] {
|
|
62
|
+
const names: string[] = [];
|
|
63
|
+
for (const [, qualifier, name] of conjunct.replace(/'[^']*'/g, '').matchAll(IDENT)) {
|
|
64
|
+
if (name === undefined || !columns.has(name)) continue;
|
|
65
|
+
if (qualifier !== undefined && qualifier !== scan.alias && qualifier !== scan.table) continue;
|
|
66
|
+
if (!names.includes(name)) names.push(name);
|
|
67
|
+
}
|
|
68
|
+
return names;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The columns of `scan` the conditions name, split by how they are compared: `=` and `IS NULL`
|
|
73
|
+
* are equality, anything else a range. A conjunct qualified by another alias is a join's other
|
|
74
|
+
* side; an unqualified name counts when the table has the column. An OR is no conjunct of either.
|
|
75
|
+
*/
|
|
76
|
+
export function columnsIn(
|
|
77
|
+
conditions: readonly string[],
|
|
78
|
+
scan: ConditionScan,
|
|
79
|
+
columns: ReadonlySet<string>,
|
|
80
|
+
): ConditionColumns {
|
|
81
|
+
const equality: string[] = [];
|
|
82
|
+
const range: string[] = [];
|
|
83
|
+
let arms: string[][] | undefined;
|
|
84
|
+
for (const condition of conditions) {
|
|
85
|
+
for (const conjunct of splitTop(unwrap(condition), 'AND')) {
|
|
86
|
+
const alternatives = splitTop(conjunct, 'OR');
|
|
87
|
+
if (alternatives.length > 1) {
|
|
88
|
+
const each = alternatives.map((arm) => {
|
|
89
|
+
const found = columnsIn([arm], scan, columns);
|
|
90
|
+
return [...found.equality, ...found.range];
|
|
91
|
+
});
|
|
92
|
+
if (arms === undefined && each.every((arm) => arm.length > 0)) arms = each;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const into = EQUALITY.test(conjunct) || IS_NULL.test(conjunct) ? equality : range;
|
|
96
|
+
for (const name of namesIn(conjunct, scan, columns)) {
|
|
97
|
+
if (!equality.includes(name) && !range.includes(name)) into.push(name);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
equality,
|
|
103
|
+
range: range.filter((name) => !equality.includes(name)),
|
|
104
|
+
...(arms === undefined ? {} : { arms }),
|
|
105
|
+
};
|
|
106
|
+
}
|
package/src/plan-oracle.ts
CHANGED
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
// a scan or a sort only when nothing else answers, so the verdict reads the schema, not the rows.
|
|
4
4
|
// Pure: JSON in, verdicts out (plan 101, 40-next-query-plans).
|
|
5
5
|
|
|
6
|
+
import { columnsIn } from './plan-conditions';
|
|
7
|
+
import type { ProbeScan } from './plan-probes';
|
|
8
|
+
import { probesOf } from './plan-probes';
|
|
9
|
+
import type { PlanUnservable, SortKeyRef } from './plan-sort-key';
|
|
10
|
+
import { sortKeyPart, sortUnservable } from './plan-sort-key';
|
|
11
|
+
|
|
6
12
|
/** What a red node is: a whole-table read, or rows sorted for a limited read. */
|
|
7
13
|
export type PlanVerdictCode = 'X_QUERY_UNINDEXED' | 'X_QUERY_SORT_UNSERVED';
|
|
8
14
|
|
|
@@ -16,8 +22,19 @@ export interface PlanVerdict {
|
|
|
16
22
|
readonly equality: readonly string[];
|
|
17
23
|
/** Physical columns it compares any other way (a range, a pattern). */
|
|
18
24
|
readonly range: readonly string[];
|
|
19
|
-
/** The sort's columns on that table, in order. Empty for a scan. */
|
|
25
|
+
/** The sort's columns on that table, in order. Empty for a scan, or a sort no index serves. */
|
|
20
26
|
readonly order: readonly string[];
|
|
27
|
+
/** A sort no declarable index serves: why (`plan-sort-key.ts`). */
|
|
28
|
+
readonly unservable?: PlanUnservable;
|
|
29
|
+
/** The arms of an OR the read is bounded by, each its columns: one index answers each arm. */
|
|
30
|
+
readonly arms?: readonly (readonly string[])[];
|
|
31
|
+
/** The alias the plan reads the table by, when it is not the table's own name. */
|
|
32
|
+
readonly alias?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Columns a join ties this whole read to a scan bound by its own key (`plan-probes.ts`): one
|
|
35
|
+
* that leads an index is a probe the planner had and declined on an empty table's costs.
|
|
36
|
+
*/
|
|
37
|
+
readonly probes?: readonly string[];
|
|
21
38
|
}
|
|
22
39
|
|
|
23
40
|
interface PlanNode {
|
|
@@ -26,12 +43,14 @@ interface PlanNode {
|
|
|
26
43
|
readonly alias: string | undefined;
|
|
27
44
|
readonly conditions: readonly string[];
|
|
28
45
|
readonly sortKey: readonly string[];
|
|
29
|
-
readonly indexCond:
|
|
46
|
+
readonly indexCond: string | undefined;
|
|
30
47
|
readonly filter: boolean;
|
|
31
48
|
readonly children: readonly PlanNode[];
|
|
32
49
|
}
|
|
33
50
|
|
|
34
51
|
const SCANS: ReadonlySet<string> = new Set(['Seq Scan', 'Index Scan', 'Index Only Scan']);
|
|
52
|
+
/** Nodes that hold their child's rows for a join: the join's conditions are the child's still. */
|
|
53
|
+
const HOLDS: ReadonlySet<string> = new Set(['Hash', 'Materialize', 'Memoize']);
|
|
35
54
|
/** Conditions a join or a recheck carries for the scans beneath it. */
|
|
36
55
|
const CONDITION_KEYS = ['Index Cond', 'Filter', 'Hash Cond', 'Merge Cond', 'Join Filter'] as const;
|
|
37
56
|
|
|
@@ -57,7 +76,7 @@ function nodeOf(value: unknown): PlanNode | undefined {
|
|
|
57
76
|
alias: text(raw['Alias']),
|
|
58
77
|
conditions: CONDITION_KEYS.flatMap((key) => text(raw[key]) ?? []),
|
|
59
78
|
sortKey,
|
|
60
|
-
indexCond: text(raw['Index Cond'])
|
|
79
|
+
indexCond: text(raw['Index Cond']),
|
|
61
80
|
filter: text(raw['Filter']) !== undefined,
|
|
62
81
|
children: plans.flatMap((child) => nodeOf(child) ?? []),
|
|
63
82
|
};
|
|
@@ -70,64 +89,85 @@ export function planRoot(answer: unknown): unknown {
|
|
|
70
89
|
return record(first)?.['Plan'] ?? first;
|
|
71
90
|
}
|
|
72
91
|
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
92
|
+
/** Every scan beneath `node` (the node itself included), of any table. */
|
|
93
|
+
const scansBeneath = (node: PlanNode): readonly PlanNode[] => [
|
|
94
|
+
...(node.table !== undefined && SCANS.has(node.type) ? [node] : []),
|
|
95
|
+
...node.children.flatMap(scansBeneath),
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
/** Nodes that compute what is sorted: past one, the sort key is no table's stored order. */
|
|
99
|
+
const COMPUTED: ReadonlySet<string> = new Set(['Aggregate', 'WindowAgg', 'Group']);
|
|
100
|
+
const computedBeneath = (node: PlanNode): boolean =>
|
|
101
|
+
node.children.some((child) => COMPUTED.has(child.type) || computedBeneath(child));
|
|
77
102
|
|
|
78
103
|
/**
|
|
79
|
-
* The
|
|
80
|
-
*
|
|
81
|
-
*
|
|
104
|
+
* The verdict of a `Sort` under a `Limit`. It belongs to the table its key names — a join lists
|
|
105
|
+
* its other side first, and that side's columns are not what is sorted. A key no index can hold
|
|
106
|
+
* still names a table, with no order to index; a key on a table the sweep does not judge (a
|
|
107
|
+
* declared `scan:`, a framework table) is that table's, and no verdict.
|
|
82
108
|
*/
|
|
83
|
-
function
|
|
109
|
+
function sortVerdict(
|
|
110
|
+
node: PlanNode,
|
|
84
111
|
conditions: readonly string[],
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
112
|
+
tables: PlanTableColumns,
|
|
113
|
+
): PlanVerdict | undefined {
|
|
114
|
+
const scans = scansBeneath(node);
|
|
115
|
+
const judged = scans.filter((scan) => scan.table !== undefined && tables.has(scan.table));
|
|
116
|
+
const scanOf = (ref: SortKeyRef): PlanNode | undefined =>
|
|
117
|
+
scans.find((scan) =>
|
|
118
|
+
ref.qualifier === undefined
|
|
119
|
+
? scan.table !== undefined && tables.get(scan.table)?.has(ref.name) === true
|
|
120
|
+
: ref.qualifier === scan.alias || ref.qualifier === scan.table,
|
|
121
|
+
);
|
|
122
|
+
const parts = node.sortKey.map(sortKeyPart);
|
|
123
|
+
const owners = parts.flatMap((part) => part.refs).flatMap((ref) => scanOf(ref) ?? []);
|
|
124
|
+
const owner = owners[0];
|
|
125
|
+
if (owner?.table !== undefined && !tables.has(owner.table)) return undefined;
|
|
126
|
+
const scan = owner ?? judged[0];
|
|
127
|
+
const columns = scan?.table === undefined ? undefined : tables.get(scan.table);
|
|
128
|
+
if (scan?.table === undefined || columns === undefined) return undefined;
|
|
129
|
+
const plainUnowned = parts.some((part) => part.column && scanOf(part.column) === undefined);
|
|
130
|
+
const unservable: PlanUnservable | undefined =
|
|
131
|
+
parts.some((part) => part.column === undefined) && computedBeneath(node)
|
|
132
|
+
? 'aggregate'
|
|
133
|
+
: plainUnowned
|
|
134
|
+
? 'derived'
|
|
135
|
+
: sortUnservable(parts, (ref) => scanOf(ref)?.table);
|
|
136
|
+
const found = columnsIn([...conditions, ...scan.conditions], scan, columns);
|
|
137
|
+
const order = columnsIn(node.sortKey, scan, columns);
|
|
138
|
+
return {
|
|
139
|
+
code: 'X_QUERY_SORT_UNSERVED',
|
|
140
|
+
node: node.type,
|
|
141
|
+
table: scan.table,
|
|
142
|
+
equality: found.equality,
|
|
143
|
+
range: [],
|
|
144
|
+
order: unservable === undefined ? [...order.equality, ...order.range] : [],
|
|
145
|
+
...(unservable === undefined ? {} : { unservable }),
|
|
146
|
+
};
|
|
102
147
|
}
|
|
103
148
|
|
|
104
|
-
/** The first scan beneath `node` (the node itself included) that reads one of `tables`. */
|
|
105
|
-
const scanBeneath = (node: PlanNode, tables: PlanTableColumns): PlanNode | undefined =>
|
|
106
|
-
node.table !== undefined && SCANS.has(node.type) && tables.has(node.table)
|
|
107
|
-
? node
|
|
108
|
-
: node.children.reduce<PlanNode | undefined>(
|
|
109
|
-
(found, child) => found ?? scanBeneath(child, tables),
|
|
110
|
-
undefined,
|
|
111
|
-
);
|
|
112
|
-
|
|
113
149
|
/** Physical table → its physical columns: only these tables are judged. */
|
|
114
150
|
export type PlanTableColumns = ReadonlyMap<string, ReadonlySet<string>>;
|
|
115
151
|
|
|
116
152
|
/**
|
|
117
153
|
* Every red node of one plan. `Seq Scan` on a judged table; an index scan with no `Index Cond`,
|
|
118
154
|
* unless a `Limit` above it stops it early and no `Filter` makes it walk on; a `Sort` under a
|
|
119
|
-
* `Limit`. A join's conditions are handed down,
|
|
155
|
+
* `Limit`. A join's conditions are handed down, through the nodes that only hold rows for it, so
|
|
156
|
+
* the scan of its inner side names its key — and a whole read tied to a keyed side, its probe.
|
|
120
157
|
*/
|
|
121
158
|
export function judgePlan(answer: unknown, tables: PlanTableColumns): readonly PlanVerdict[] {
|
|
122
159
|
const root = nodeOf(planRoot(answer));
|
|
123
160
|
if (root === undefined) return [];
|
|
124
161
|
const verdicts: PlanVerdict[] = [];
|
|
162
|
+
const scans: (ProbeScan & { readonly verdict: number | undefined })[] = [];
|
|
125
163
|
const walk = (node: PlanNode, limited: boolean, inherited: readonly string[]): void => {
|
|
126
164
|
const conditions = [...inherited, ...node.conditions];
|
|
127
165
|
const columns = node.table === undefined ? undefined : tables.get(node.table);
|
|
128
|
-
if (node.table !== undefined &&
|
|
129
|
-
const
|
|
130
|
-
|
|
166
|
+
if (node.table !== undefined && SCANS.has(node.type)) {
|
|
167
|
+
const judged = columns !== undefined;
|
|
168
|
+
const unbounded =
|
|
169
|
+
node.type === 'Seq Scan' || (node.indexCond === undefined && (!limited || node.filter));
|
|
170
|
+
if (judged && unbounded) {
|
|
131
171
|
const found = columnsIn(conditions, node, columns);
|
|
132
172
|
verdicts.push({
|
|
133
173
|
code: 'X_QUERY_UNINDEXED',
|
|
@@ -135,33 +175,29 @@ export function judgePlan(answer: unknown, tables: PlanTableColumns): readonly P
|
|
|
135
175
|
table: node.table,
|
|
136
176
|
...found,
|
|
137
177
|
order: [],
|
|
178
|
+
...(node.alias === undefined || node.alias === node.table ? {} : { alias: node.alias }),
|
|
138
179
|
});
|
|
139
180
|
}
|
|
181
|
+
const { table, alias, indexCond } = node;
|
|
182
|
+
const verdict = judged && unbounded ? verdicts.length - 1 : undefined;
|
|
183
|
+
scans.push({ table, alias, indexCond, conditions, verdict });
|
|
140
184
|
}
|
|
141
185
|
if (node.type === 'Sort' && limited) {
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
if (scan?.table !== undefined && scanColumns !== undefined) {
|
|
145
|
-
const found = columnsIn([...conditions, ...scan.conditions], scan, scanColumns);
|
|
146
|
-
const order = columnsIn(node.sortKey, scan, scanColumns);
|
|
147
|
-
verdicts.push({
|
|
148
|
-
code: 'X_QUERY_SORT_UNSERVED',
|
|
149
|
-
node: node.type,
|
|
150
|
-
table: scan.table,
|
|
151
|
-
equality: found.equality,
|
|
152
|
-
range: [],
|
|
153
|
-
order: [...order.equality, ...order.range],
|
|
154
|
-
});
|
|
155
|
-
}
|
|
186
|
+
const sorted = sortVerdict(node, conditions, tables);
|
|
187
|
+
if (sorted !== undefined) verdicts.push(sorted);
|
|
156
188
|
}
|
|
157
189
|
const below = limited || node.type === 'Limit';
|
|
158
190
|
// A join's conditions name both sides: each child keeps only the conjuncts about itself.
|
|
159
191
|
const handed =
|
|
160
|
-
node.type.includes('Join') || node.type === 'Nested Loop' || node.type
|
|
192
|
+
node.type.includes('Join') || node.type === 'Nested Loop' || HOLDS.has(node.type)
|
|
161
193
|
? conditions
|
|
162
194
|
: [];
|
|
163
195
|
for (const child of node.children) walk(child, below, handed);
|
|
164
196
|
};
|
|
165
197
|
walk(root, false, []);
|
|
166
|
-
|
|
198
|
+
const probes = probesOf(scans);
|
|
199
|
+
return verdicts.map((verdict, at) => {
|
|
200
|
+
const found = probes[scans.findIndex((scan) => scan.verdict === at)] ?? [];
|
|
201
|
+
return found.length === 0 ? verdict : { ...verdict, probes: found };
|
|
202
|
+
});
|
|
167
203
|
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Which whole reads in one plan a keyed scan could have probed instead: the join columns that tie
|
|
2
|
+
// a scan to a side bound by its own key. On empty tables the planner may walk a small-looking
|
|
3
|
+
// index beside a join rather than probe it per row; the probe exists when such a column leads an
|
|
4
|
+
// index, which `plan-sweep-fix.ts` reads off the declaration. Pure.
|
|
5
|
+
|
|
6
|
+
import { splitTop, unwrap } from './plan-conditions';
|
|
7
|
+
|
|
8
|
+
/** One scan of the plan, with every condition it was handed and its own `Index Cond`. */
|
|
9
|
+
export interface ProbeScan {
|
|
10
|
+
readonly table: string;
|
|
11
|
+
readonly alias: string | undefined;
|
|
12
|
+
readonly indexCond: string | undefined;
|
|
13
|
+
readonly conditions: readonly string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const SIDE = String.raw`(?:"?([A-Za-z_][\w$]*)"?\.)?"?([A-Za-z_][\w$]*)"?`;
|
|
17
|
+
/** `a.x = b.y`: one column against another, the only shape a probe answers. */
|
|
18
|
+
const COLUMN_EQUALITY = new RegExp(`^${SIDE}\\s*=\\s*${SIDE}$`);
|
|
19
|
+
const QUALIFIER = /"?([A-Za-z_][\w$]*)"?\.(?="?[A-Za-z_])/g;
|
|
20
|
+
|
|
21
|
+
const nameOf = (scan: ProbeScan): string => scan.alias ?? scan.table;
|
|
22
|
+
|
|
23
|
+
const conjuncts = (conditions: readonly string[]): string[] =>
|
|
24
|
+
conditions.flatMap((condition) => splitTop(unwrap(condition), 'AND'));
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Bound by its own key: an `Index Cond` conjunct that names no other scan. A parameterized inner
|
|
28
|
+
* scan's condition is the join itself, so it keys nothing on its own.
|
|
29
|
+
*/
|
|
30
|
+
function selfKeyed(scan: ProbeScan, others: ReadonlySet<string>): boolean {
|
|
31
|
+
if (scan.indexCond === undefined) return false;
|
|
32
|
+
return conjuncts([scan.indexCond]).some((conjunct) =>
|
|
33
|
+
[...conjunct.replace(/'[^']*'/g, '').matchAll(QUALIFIER)].every(
|
|
34
|
+
([, qualifier]) => qualifier === undefined || !others.has(qualifier),
|
|
35
|
+
),
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface Tie {
|
|
40
|
+
readonly scan: string;
|
|
41
|
+
readonly column: string;
|
|
42
|
+
readonly other: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Every `a.x = b.y` between two scans, both ways round, wherever the plan states it: a join's
|
|
47
|
+
* filter, or a parameterized scan's own `Index Cond`, where its columns go unqualified.
|
|
48
|
+
*/
|
|
49
|
+
function tiesOf(scans: readonly ProbeScan[], names: ReadonlySet<string>): readonly Tie[] {
|
|
50
|
+
const ties: Tie[] = [];
|
|
51
|
+
for (const scan of scans) {
|
|
52
|
+
for (const conjunct of conjuncts([...scan.conditions, scan.indexCond ?? ''])) {
|
|
53
|
+
const match = COLUMN_EQUALITY.exec(conjunct);
|
|
54
|
+
if (match === null) continue;
|
|
55
|
+
const [, leftOf = nameOf(scan), left, rightOf = nameOf(scan), right] = match;
|
|
56
|
+
if (left === undefined || right === undefined || leftOf === rightOf) continue;
|
|
57
|
+
if (!names.has(leftOf) || !names.has(rightOf)) continue;
|
|
58
|
+
ties.push({ scan: leftOf, column: left, other: rightOf });
|
|
59
|
+
ties.push({ scan: rightOf, column: right, other: leftOf });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return ties;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Each scan's probe columns, in plan order: the columns it is tied to a keyed scan by. A scan
|
|
67
|
+
* that has any is keyed in turn, so the probe carries along a chain of joins; two scans tied only
|
|
68
|
+
* to each other probe nothing — one of them is read whole either way.
|
|
69
|
+
*/
|
|
70
|
+
export function probesOf(scans: readonly ProbeScan[]): readonly (readonly string[])[] {
|
|
71
|
+
const names = new Set(scans.map(nameOf));
|
|
72
|
+
const keyed = new Set(
|
|
73
|
+
scans
|
|
74
|
+
.filter((scan) => selfKeyed(scan, new Set([...names].filter((n) => n !== nameOf(scan)))))
|
|
75
|
+
.map(nameOf),
|
|
76
|
+
);
|
|
77
|
+
const ties = tiesOf(scans, names);
|
|
78
|
+
const probes = scans.map((): string[] => []);
|
|
79
|
+
for (let grew = true; grew; ) {
|
|
80
|
+
grew = false;
|
|
81
|
+
scans.forEach((scan, at) => {
|
|
82
|
+
const own = nameOf(scan);
|
|
83
|
+
if (keyed.has(own)) return;
|
|
84
|
+
const found = ties.flatMap((tie) =>
|
|
85
|
+
tie.scan === own && keyed.has(tie.other) ? [tie.column] : [],
|
|
86
|
+
);
|
|
87
|
+
if (found.length === 0) return;
|
|
88
|
+
probes[at] = [...new Set(found)];
|
|
89
|
+
keyed.add(own);
|
|
90
|
+
grew = true;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return probes;
|
|
94
|
+
}
|