@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,65 @@
|
|
|
1
|
+
// A Sort node's key, read as an index would have to hold it: which table each part belongs to,
|
|
2
|
+
// whether it is a plain column, and which way it runs. An index serves a sort only when every part
|
|
3
|
+
// is a plain column of ONE table, all running one way — anything else no `indexes:` entry ends.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Why no index an entity declares can serve a sort: its key is an expression (`entity()` declares
|
|
7
|
+
* no expression index), a value an aggregate or window computed, a value a subquery derived, the
|
|
8
|
+
* columns of more than one table, or columns running in different directions.
|
|
9
|
+
*/
|
|
10
|
+
export type PlanUnservable = 'expression' | 'aggregate' | 'derived' | 'tables' | 'directions';
|
|
11
|
+
|
|
12
|
+
/** A column a sort key names, as the plan prints it: `p.created_at`, or `title` alone. */
|
|
13
|
+
export interface SortKeyRef {
|
|
14
|
+
readonly qualifier: string | undefined;
|
|
15
|
+
readonly name: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SortKeyPart {
|
|
19
|
+
/** The column, when the part is one column and nothing else. */
|
|
20
|
+
readonly column: SortKeyRef | undefined;
|
|
21
|
+
/** Every column the part names: the expression's too. */
|
|
22
|
+
readonly refs: readonly SortKeyRef[];
|
|
23
|
+
/** `up` is an ascending walk (nulls last), `down` the same walk backwards; `mixed` is neither. */
|
|
24
|
+
readonly way: 'up' | 'down' | 'mixed';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const NAME = '"?([A-Za-z_][\\w$]*)"?';
|
|
28
|
+
const PLAIN = new RegExp(`^(?:${NAME}\\.)?${NAME}$`);
|
|
29
|
+
const REF = new RegExp(`(?:${NAME}\\.)?${NAME}`, 'g');
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* One part of a `Sort Key`. Postgres prints `DESC` and a `NULLS` that differs from the direction's
|
|
33
|
+
* default; ascending nulls last and descending nulls first are the two walks of one btree.
|
|
34
|
+
*/
|
|
35
|
+
export function sortKeyPart(key: string): SortKeyPart {
|
|
36
|
+
let rest = key.trim();
|
|
37
|
+
const nulls = /\s+NULLS\s+(FIRST|LAST)$/i.exec(rest);
|
|
38
|
+
if (nulls !== null) rest = rest.slice(0, nulls.index);
|
|
39
|
+
const desc = /\s+DESC$/i.test(rest);
|
|
40
|
+
rest = rest.replace(/\s+(?:DESC|ASC)$/i, '');
|
|
41
|
+
const nullsFirst = nulls === null ? desc : nulls[1]?.toUpperCase() === 'FIRST';
|
|
42
|
+
const way = desc === nullsFirst ? (desc ? 'down' : 'up') : 'mixed';
|
|
43
|
+
const plain = PLAIN.exec(rest);
|
|
44
|
+
const refs = [...rest.replace(/'[^']*'/g, '').matchAll(REF)].flatMap(([, qualifier, name]) =>
|
|
45
|
+
name === undefined ? [] : [{ qualifier, name }],
|
|
46
|
+
);
|
|
47
|
+
const column = plain?.[2] === undefined ? undefined : { qualifier: plain[1], name: plain[2] };
|
|
48
|
+
return { column, refs, way };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Why an index cannot serve these parts, given the table each column belongs to (`undefined` for
|
|
53
|
+
* one the judged tables do not hold), or `undefined` when one index on one table could.
|
|
54
|
+
*/
|
|
55
|
+
export function sortUnservable(
|
|
56
|
+
parts: readonly SortKeyPart[],
|
|
57
|
+
tableOf: (ref: SortKeyRef) => string | undefined,
|
|
58
|
+
): PlanUnservable | undefined {
|
|
59
|
+
if (parts.some((part) => part.column === undefined)) return 'expression';
|
|
60
|
+
const tables = new Set(parts.flatMap((part) => (part.column ? [tableOf(part.column)] : [])));
|
|
61
|
+
if (tables.size > 1) return 'tables';
|
|
62
|
+
const ways = new Set(parts.map((part) => part.way));
|
|
63
|
+
if (ways.has('mixed') || ways.size > 1) return 'directions';
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
package/src/plan-sweep-fix.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// From the oracle's red nodes to what an author pastes: the entity, and the `indexes: [{ on }]`
|
|
2
2
|
// entry by property. Pure. Also where a red node is argued away by the declaration itself: a
|
|
3
|
-
// lookup that pins a unique key reads one row whatever the planner walked to find it
|
|
3
|
+
// lookup that pins a unique key reads one row whatever the planner walked to find it, and a whole
|
|
4
|
+
// read a keyed join side could probe by a declared index is one the planner declined on cost.
|
|
4
5
|
|
|
5
6
|
import type { PlanVerdict, PlanVerdictCode } from './plan-oracle';
|
|
7
|
+
import type { PlanUnservable } from './plan-sort-key';
|
|
8
|
+
import { sortKeyPart } from './plan-sort-key';
|
|
6
9
|
import type { SeedEntity } from './seed-graph-shape';
|
|
7
10
|
|
|
8
11
|
export interface PlanFinding {
|
|
@@ -15,6 +18,12 @@ export interface PlanFinding {
|
|
|
15
18
|
readonly table: string;
|
|
16
19
|
/** The `indexes: [{ on }]` entry, by property: tenant, equality, order, range. */
|
|
17
20
|
readonly index: readonly string[];
|
|
21
|
+
/**
|
|
22
|
+
* Why no index is the fix: a sort no declarable index serves, or `declared` — the index the node
|
|
23
|
+
* asks for is one the entity already holds, so declaring it again changes no plan. `index` is
|
|
24
|
+
* empty with it.
|
|
25
|
+
*/
|
|
26
|
+
readonly unserved?: PlanUnservable | 'declared';
|
|
18
27
|
}
|
|
19
28
|
|
|
20
29
|
/** Every column set the table holds unique: the primary key, unique columns, total unique rules. */
|
|
@@ -110,24 +119,83 @@ function servedByPartial(entity: SeedEntity, verdict: PlanVerdict, order: readon
|
|
|
110
119
|
|
|
111
120
|
const ORDER_BY = /\border by\s+(.+?)(?:\s+limit\b|\s+offset\b|\s+for\b|$)/gi;
|
|
112
121
|
|
|
122
|
+
/** `a, f(b, c), d` → its three items: commas outside parentheses only. */
|
|
123
|
+
function items(list: string): string[] {
|
|
124
|
+
const found: string[] = [];
|
|
125
|
+
let depth = 0;
|
|
126
|
+
let start = 0;
|
|
127
|
+
for (let at = 0; at < list.length; at += 1) {
|
|
128
|
+
if (list[at] === '(') depth += 1;
|
|
129
|
+
else if (list[at] === ')') depth -= 1;
|
|
130
|
+
else if (list[at] === ',' && depth === 0) {
|
|
131
|
+
found.push(list.slice(start, at));
|
|
132
|
+
start = at + 1;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return [...found, list.slice(start)];
|
|
136
|
+
}
|
|
137
|
+
|
|
113
138
|
/**
|
|
114
|
-
* The outermost `order by`'s columns, read off the text: an index walk
|
|
115
|
-
* sort key of its own, yet the index that ends the walk has to hold
|
|
139
|
+
* The outermost `order by`'s leading columns of the walked table, read off the text: an index walk
|
|
140
|
+
* avoids a sort and carries no sort key of its own, yet the index that ends the walk has to hold
|
|
141
|
+
* the order too. Only as far as one index can: plain columns of this table, one direction — past
|
|
142
|
+
* them the rows arrive presorted and Postgres finishes with an incremental sort.
|
|
116
143
|
*/
|
|
117
|
-
function orderOf(statement: string, columns: ReadonlySet<string
|
|
144
|
+
function orderOf(statement: string, columns: ReadonlySet<string>, verdict: PlanVerdict) {
|
|
118
145
|
const clauses = [...statement.matchAll(ORDER_BY)];
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
146
|
+
const order: string[] = [];
|
|
147
|
+
let way: string | undefined;
|
|
148
|
+
for (const item of items(clauses[clauses.length - 1]?.[1] ?? '')) {
|
|
149
|
+
const part = sortKeyPart(item);
|
|
150
|
+
const own =
|
|
151
|
+
part.column !== undefined &&
|
|
152
|
+
columns.has(part.column.name) &&
|
|
153
|
+
[undefined, verdict.table, verdict.alias].includes(part.column.qualifier);
|
|
154
|
+
if (!own || part.way === 'mixed' || (way !== undefined && part.way !== way)) break;
|
|
155
|
+
way = part.way;
|
|
156
|
+
if (part.column !== undefined) order.push(part.column.name);
|
|
157
|
+
}
|
|
158
|
+
return order;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* An OR the read is bounded by and nothing else: one index per arm answers it, as a BitmapOr. An
|
|
163
|
+
* arm whose column leads a declared index is answered already — the sweep's settings discourage
|
|
164
|
+
* the BitmapOr, so the plan alone cannot say; credited, never re-proven.
|
|
165
|
+
*/
|
|
166
|
+
function armFindings(
|
|
167
|
+
verdict: PlanVerdict,
|
|
168
|
+
declared: readonly (readonly string[])[],
|
|
169
|
+
property: (column: string) => string | undefined,
|
|
170
|
+
): readonly (readonly string[])[] {
|
|
171
|
+
const arms = new Map((verdict.arms ?? []).map((arm) => [arm.join('\u0000'), arm]));
|
|
172
|
+
return [...arms.values()]
|
|
173
|
+
.filter((arm) => !declared.some((key) => key[0] !== undefined && arm.includes(key[0])))
|
|
174
|
+
.map((arm) => arm.flatMap((column) => property(column) ?? []));
|
|
124
175
|
}
|
|
125
176
|
|
|
177
|
+
/**
|
|
178
|
+
* A whole read a keyed side could probe: a column it is joined by leads a declared index. On empty
|
|
179
|
+
* tables the planner may walk a small-looking index (a partial one the statement implies) rather
|
|
180
|
+
* than probe it per row; at size it probes. Credited, never re-proven, as a range index is.
|
|
181
|
+
*/
|
|
182
|
+
const probed = (keys: readonly (readonly string[])[], verdict: PlanVerdict): boolean =>
|
|
183
|
+
verdict.code === 'X_QUERY_UNINDEXED' &&
|
|
184
|
+
(verdict.probes ?? []).some((column) => keys.some((key) => key[0] === column));
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The plan was taken with every declared index in place: one that leads with exactly these
|
|
188
|
+
* columns is already there, and printing it as the fix would change nothing.
|
|
189
|
+
*/
|
|
190
|
+
const held = (keys: readonly (readonly string[])[], columns: readonly string[]): boolean =>
|
|
191
|
+
columns.length > 0 && keys.some((key) => columns.every((column, at) => key[at] === column));
|
|
192
|
+
|
|
126
193
|
/**
|
|
127
194
|
* The findings one statement's verdicts make. A verdict whose equality columns pin a unique key is
|
|
128
195
|
* dropped: one row at most. A table's sort verdict makes its scan verdict redundant — the index it
|
|
129
196
|
* names leads with the same equality columns. The tenant column leads the index only when the
|
|
130
|
-
* statement compares it: a read across tenants is served by no index that leads with one.
|
|
197
|
+
* statement compares it: a read across tenants is served by no index that leads with one. A sort
|
|
198
|
+
* no declarable index serves, or an index the entity already holds, is red with no index to paste.
|
|
131
199
|
*/
|
|
132
200
|
export function planFindings(
|
|
133
201
|
statement: string,
|
|
@@ -145,31 +213,40 @@ export function planFindings(
|
|
|
145
213
|
key.every((column) => verdict.equality.includes(column)),
|
|
146
214
|
);
|
|
147
215
|
if (pinned) return [];
|
|
216
|
+
const finding = {
|
|
217
|
+
code: verdict.code,
|
|
218
|
+
statement,
|
|
219
|
+
node: verdict.node,
|
|
220
|
+
entity: entity.$name,
|
|
221
|
+
table: verdict.table,
|
|
222
|
+
};
|
|
223
|
+
if (verdict.unservable !== undefined) {
|
|
224
|
+
return [{ ...finding, index: [], unserved: verdict.unservable }];
|
|
225
|
+
}
|
|
148
226
|
const description = entity.$describe();
|
|
149
227
|
const byColumn = new Map(description.columns.map((c) => [c.column, c.property]));
|
|
150
228
|
const walked = verdict.code === 'X_QUERY_UNINDEXED' && verdict.node !== 'Seq Scan';
|
|
151
229
|
// A walk filtered by a range already has its order: what it lacks is the bound. A btree serves
|
|
152
230
|
// no order after a range column, so the index is the equality columns, then the range.
|
|
153
231
|
const ranged = walked && verdict.range.length > 0;
|
|
154
|
-
|
|
232
|
+
const declared = declaredIndexes(entity, statement);
|
|
233
|
+
if (probed(declared, verdict)) return [];
|
|
234
|
+
const bounded = verdict.equality.length > 0 || verdict.range.length > 0;
|
|
235
|
+
if (!bounded && verdict.arms !== undefined && verdict.code === 'X_QUERY_UNINDEXED') {
|
|
236
|
+
const arms = armFindings(verdict, declared, (column) => byColumn.get(column));
|
|
237
|
+
return arms.map((index) => ({ ...finding, index }));
|
|
238
|
+
}
|
|
239
|
+
if (ranged && servedByRange(declared, verdict)) return [];
|
|
155
240
|
const order = ranged
|
|
156
241
|
? []
|
|
157
242
|
: walked
|
|
158
|
-
? orderOf(statement, new Set(description.columns.map((c) => c.column)))
|
|
243
|
+
? orderOf(statement, new Set(description.columns.map((c) => c.column)), verdict)
|
|
159
244
|
: verdict.order;
|
|
160
245
|
if (servedByPartial(entity, verdict, order)) return [];
|
|
161
246
|
const tenant = description.columns.find((c) => c.property === entity.$tenantColumn)?.column;
|
|
162
247
|
const lead = tenant !== undefined && verdict.equality.includes(tenant) ? [tenant] : [];
|
|
163
248
|
const columns = [...new Set([...lead, ...verdict.equality, ...order, ...verdict.range])];
|
|
164
|
-
return [
|
|
165
|
-
|
|
166
|
-
code: verdict.code,
|
|
167
|
-
statement,
|
|
168
|
-
node: verdict.node,
|
|
169
|
-
entity: entity.$name,
|
|
170
|
-
table: verdict.table,
|
|
171
|
-
index: columns.flatMap((column) => byColumn.get(column) ?? []),
|
|
172
|
-
},
|
|
173
|
-
];
|
|
249
|
+
if (held(declared, columns)) return [{ ...finding, index: [], unserved: 'declared' }];
|
|
250
|
+
return [{ ...finding, index: columns.flatMap((column) => byColumn.get(column) ?? []) }];
|
|
174
251
|
});
|
|
175
252
|
}
|
package/src/plan-sweep-report.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { renderCauseValue, renderFixLiteral, renderFixShellArg } from '@ultimat3/core';
|
|
6
6
|
import type { ExerciseRecord } from './exercise-report';
|
|
7
|
+
import type { PlanUnservable } from './plan-sort-key';
|
|
7
8
|
import type { PlanFinding } from './plan-sweep-fix';
|
|
8
9
|
|
|
9
10
|
export interface SweepFinding {
|
|
@@ -41,7 +42,47 @@ function wholeRead(finding: PlanFinding, senders: readonly ExerciseRecord[]): Sw
|
|
|
41
42
|
};
|
|
42
43
|
}
|
|
43
44
|
|
|
45
|
+
/** Why no index serves a sort, as the cause says it. */
|
|
46
|
+
const UNSERVED_SORT: Readonly<Record<PlanUnservable, string>> = {
|
|
47
|
+
expression: 'an expression over its columns, and entity() declares no expression index',
|
|
48
|
+
aggregate: 'a value an aggregate or window computes, which no stored order holds',
|
|
49
|
+
derived: 'a value a subquery or CTE derives, which no index on a table holds',
|
|
50
|
+
tables: 'columns of more than one table, and one index holds one table',
|
|
51
|
+
directions: 'columns in different directions, and an index declares one order for all of them',
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A red node no `indexes:` entry ends: a sort no declarable index holds, or one whose index the
|
|
56
|
+
* entity already declares. Printing an index would change no plan, so the fix is the rewrite that
|
|
57
|
+
* lets one apply, or the stated reason the rows stay few.
|
|
58
|
+
*/
|
|
59
|
+
function unservedRead(
|
|
60
|
+
finding: PlanFinding,
|
|
61
|
+
unserved: PlanUnservable | 'declared',
|
|
62
|
+
senders: readonly ExerciseRecord[],
|
|
63
|
+
): SweepFinding {
|
|
64
|
+
const by = senders.map(primitive).join(', ');
|
|
65
|
+
const entity = renderFixLiteral(finding.entity, '<entity>');
|
|
66
|
+
const rerun = renderFixShellArg(senders[0]?.name ?? '', '<primitive>');
|
|
67
|
+
const sent = `${by} sent ${renderCauseValue(excerpt(finding.statement))}`;
|
|
68
|
+
const cause =
|
|
69
|
+
unserved === 'declared'
|
|
70
|
+
? `${sent}, which reads ${finding.table} unbounded (${finding.node}) though entity(${entity}) already declares the index that would bound it: declaring it again changes no plan, the statement as written cannot use it`
|
|
71
|
+
: `${sent}, which sorts its rows to answer a limited read (${finding.node} under Limit) by ${UNSERVED_SORT[unserved]}: no index on ${finding.table} serves that sort, so it slows with every row the table gains`;
|
|
72
|
+
const rewrite =
|
|
73
|
+
unserved === 'declared'
|
|
74
|
+
? "the read compares the index's leading column by = or a range, no function around it"
|
|
75
|
+
: `an order by of plain ${finding.table} columns, all one direction (the rerun names their index)`;
|
|
76
|
+
return {
|
|
77
|
+
code: finding.code,
|
|
78
|
+
cause,
|
|
79
|
+
fix: `x exercise ${rerun} --json # after ${rewrite}, or expectedSeqScan('<why the rows stay few>', fn) around the read`,
|
|
80
|
+
at: senders[0] === undefined ? finding.entity : primitive(senders[0]),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
44
84
|
function planFinding(finding: PlanFinding, senders: readonly ExerciseRecord[]): SweepFinding {
|
|
85
|
+
if (finding.unserved !== undefined) return unservedRead(finding, finding.unserved, senders);
|
|
45
86
|
if (finding.index.length === 0) return wholeRead(finding, senders);
|
|
46
87
|
const by = senders.map(primitive).join(', ');
|
|
47
88
|
const entity = renderFixLiteral(finding.entity, '<entity>');
|
|
@@ -67,7 +108,8 @@ export function planSweepFindings(records: readonly ExerciseRecord[]): readonly
|
|
|
67
108
|
const groups = new Map<string, { finding: PlanFinding; senders: ExerciseRecord[] }>();
|
|
68
109
|
for (const record of records) {
|
|
69
110
|
for (const finding of record.plans?.findings ?? []) {
|
|
70
|
-
|
|
111
|
+
// An OR's arms are one finding each, on one statement: the index is part of what is red.
|
|
112
|
+
const key = [finding.code, finding.table, finding.statement, ...finding.index].join('\u0000');
|
|
71
113
|
const group = groups.get(key) ?? { finding, senders: [] };
|
|
72
114
|
group.senders.push(record);
|
|
73
115
|
groups.set(key, group);
|
|
@@ -91,9 +133,11 @@ export function planSweepFindings(records: readonly ExerciseRecord[]): readonly
|
|
|
91
133
|
export function planSweepLines(records: readonly ExerciseRecord[]): readonly string[] {
|
|
92
134
|
return records.flatMap((record) => [
|
|
93
135
|
...(record.plans?.findings ?? []).map((finding) =>
|
|
94
|
-
finding.
|
|
95
|
-
? `${primitive(record)} · ${finding.code} ${finding.table},
|
|
96
|
-
:
|
|
136
|
+
finding.unserved !== undefined
|
|
137
|
+
? `${primitive(record)} · ${finding.code} ${finding.table}, no index serves it (${finding.unserved})`
|
|
138
|
+
: finding.index.length === 0
|
|
139
|
+
? `${primitive(record)} · ${finding.code} ${finding.table}, every row (no column to index)`
|
|
140
|
+
: `${primitive(record)} · ${finding.code} ${finding.table} on [${finding.index.join(', ')}]`,
|
|
97
141
|
),
|
|
98
142
|
...(record.scale?.verdict === 'grows' ? record.scale.shapes : []).map(
|
|
99
143
|
(shape) =>
|
package/src/scale-sweep-graph.ts
CHANGED
|
@@ -28,12 +28,15 @@ export function scaleGraph(
|
|
|
28
28
|
readonly seed: number;
|
|
29
29
|
/** The app's `defineExercise` factories: a table only they satisfy is built by them here too. */
|
|
30
30
|
readonly factories?: Readonly<Record<string, SeedFactory>> | undefined;
|
|
31
|
+
/** The last graph written to the database before this one; `main` when omitted. */
|
|
32
|
+
readonly beside?: SeedGraph | undefined;
|
|
31
33
|
},
|
|
32
34
|
): ScaleGraph {
|
|
33
35
|
const sized = seedGraph(Object.fromEntries(entities.map((entity) => [entity.$name, entity])), {
|
|
34
36
|
tenants: 1,
|
|
35
37
|
perTable: options.perTable,
|
|
36
38
|
seed: options.seed,
|
|
39
|
+
beside: options.beside ?? main,
|
|
37
40
|
...(options.factories === undefined ? {} : { factories: options.factories }),
|
|
38
41
|
});
|
|
39
42
|
const shared = (graph: SeedGraph) => graph.inserts.filter((insert) => insert.tenant === null);
|
package/src/scale-sweep-run.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { RunJobs } from './fixture-jobs';
|
|
|
9
9
|
import { testJobs } from './fixture-jobs';
|
|
10
10
|
import type { ScaleProof, StatementTally } from './scale-sweep';
|
|
11
11
|
import { judgeScale, SCALE_SIZES } from './scale-sweep';
|
|
12
|
+
import type { ScaleGraph } from './scale-sweep-graph';
|
|
12
13
|
import { scaleGraph } from './scale-sweep-graph';
|
|
13
14
|
import type { SeedFactory, SeedGraph, SeedWriter } from './seed-graph-plan';
|
|
14
15
|
import { insertSeedGraph } from './seed-graph-plan';
|
|
@@ -85,14 +86,20 @@ export async function scaleSweep(
|
|
|
85
86
|
): Promise<ReadonlyMap<string, ScaleProof>> {
|
|
86
87
|
const proofs = new Map<string, ScaleProof>();
|
|
87
88
|
if (options.subjects.length === 0) return proofs;
|
|
88
|
-
const sizes = [
|
|
89
|
+
const sizes: ScaleGraph[] = [];
|
|
90
|
+
for (const [i, perTable] of [SCALE_SIZES.small, SCALE_SIZES.large].entries()) {
|
|
89
91
|
// Hashed, never `seed + 1`: a later pass on the same database may be seeded with that number.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
92
|
+
// Each beside the one written before it, so no row position — and no value built from one —
|
|
93
|
+
// repeats across the three graphs in the database.
|
|
94
|
+
sizes.push(
|
|
95
|
+
scaleGraph(options.main, options.entities, {
|
|
96
|
+
perTable,
|
|
97
|
+
seed: fnv1a(`scale:${options.seed}:${i}`) || 1,
|
|
98
|
+
factories: options.factories,
|
|
99
|
+
beside: sizes[i - 1]?.write ?? options.main,
|
|
100
|
+
}),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
96
103
|
try {
|
|
97
104
|
for (const size of sizes) await insertSeedGraph(size.write, options.writer);
|
|
98
105
|
} catch (error) {
|
package/src/seed-graph-plan.ts
CHANGED
|
@@ -23,6 +23,12 @@ export interface SeedGraphOptions {
|
|
|
23
23
|
readonly seed?: number;
|
|
24
24
|
/** By entity name. A column the factory builds takes its value; keys stay the graph's. */
|
|
25
25
|
readonly factories?: Readonly<Record<string, SeedFactory>>;
|
|
26
|
+
/**
|
|
27
|
+
* A graph already written to the same database. Each table's row positions — the ordinal a
|
|
28
|
+
* generated value is built from, a factory's `index` — continue past its `next`, so a value built
|
|
29
|
+
* from a position (`code: \`c${index}\``) never repeats one of its rows on a unique column.
|
|
30
|
+
*/
|
|
31
|
+
readonly beside?: SeedGraph;
|
|
26
32
|
}
|
|
27
33
|
|
|
28
34
|
export interface SeedRow {
|
|
@@ -67,6 +73,11 @@ export interface SeedGraph {
|
|
|
67
73
|
readonly updates: readonly SeedUpdate[];
|
|
68
74
|
/** One per insert, in the same order: `canaries[i]` is `inserts[i]`'s. */
|
|
69
75
|
readonly canaries: readonly SeedCanary[];
|
|
76
|
+
/**
|
|
77
|
+
* Per table, the row position a graph written `beside` this one starts at: its own `beside`'s
|
|
78
|
+
* plus every row this graph built. Absent on a hand-written graph: positions then start at 0.
|
|
79
|
+
*/
|
|
80
|
+
readonly next?: Readonly<Record<string, number>>;
|
|
70
81
|
}
|
|
71
82
|
|
|
72
83
|
/** Where `insertSeedGraph` writes. One insert per row, in order, then one update per deferred key. */
|
package/src/seed-graph-values.ts
CHANGED
|
@@ -6,7 +6,6 @@
|
|
|
6
6
|
import { fnv1a } from '@ultimat3/core';
|
|
7
7
|
import type { ColumnMeta } from '@ultimat3/entity';
|
|
8
8
|
import type * as Sample from '@ultimat3/schema/sample';
|
|
9
|
-
import { patternSamples } from './seed-pattern-sample';
|
|
10
9
|
|
|
11
10
|
/** A column as `entity()` declares it, structurally: this barrel never loads `@ultimat3/entity`. */
|
|
12
11
|
export interface SeedColumn {
|
|
@@ -72,19 +71,11 @@ const textCandidates = (property: string, meta: ColumnMeta, ctx: ValueContext):
|
|
|
72
71
|
return [...sized, ...fromPatterns(property, ctx)];
|
|
73
72
|
};
|
|
74
73
|
|
|
75
|
-
/** Strings drawn from each declared pattern, kept only where every other pattern agrees. */
|
|
76
|
-
const fromPatterns = (property: string, ctx: ValueContext): string[] => {
|
|
77
|
-
const patterns = ctx.patterns ?? [];
|
|
78
|
-
return patterns
|
|
79
|
-
.flatMap((pattern) => patternSamples(pattern, `${property}:${ctx.canary}`))
|
|
80
|
-
.filter((sample) => patterns.every((pattern) => pattern.test(sample)));
|
|
81
|
-
};
|
|
82
|
-
|
|
83
74
|
let loadedSampler: typeof Sample | undefined;
|
|
84
75
|
|
|
85
76
|
/**
|
|
86
|
-
* `@ultimat3/schema/sample`, loaded on the first `json(schema)` column
|
|
87
|
-
* module is on the barrel, and the walker is a dynamic-only dependency there (`CLAUDE.md`).
|
|
77
|
+
* `@ultimat3/schema/sample`, loaded on the first pattern or `json(schema)` column, never at import:
|
|
78
|
+
* this module is on the barrel, and the walker is a dynamic-only dependency there (`CLAUDE.md`).
|
|
88
79
|
* `require` and not `import()` because every caller of `candidatesFor` is synchronous.
|
|
89
80
|
*/
|
|
90
81
|
const sampler = (): typeof Sample => {
|
|
@@ -92,6 +83,24 @@ const sampler = (): typeof Sample => {
|
|
|
92
83
|
return loadedSampler;
|
|
93
84
|
};
|
|
94
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Strings drawn from each declared pattern by schema's one generator (`patternSamples`), kept only
|
|
88
|
+
* where every other pattern agrees. The text seed hashes with the pattern, so two columns differ.
|
|
89
|
+
*/
|
|
90
|
+
const fromPatterns = (property: string, ctx: ValueContext): string[] => {
|
|
91
|
+
const patterns = ctx.patterns ?? [];
|
|
92
|
+
if (patterns.length === 0) return [];
|
|
93
|
+
const { patternSamples } = sampler();
|
|
94
|
+
return patterns
|
|
95
|
+
.flatMap((pattern) =>
|
|
96
|
+
patternSamples(
|
|
97
|
+
pattern,
|
|
98
|
+
fnv1a(`${pattern.source}/${pattern.flags}:${property}:${ctx.canary}`) || 1,
|
|
99
|
+
),
|
|
100
|
+
)
|
|
101
|
+
.filter((sample) => patterns.every((pattern) => pattern.test(sample)));
|
|
102
|
+
};
|
|
103
|
+
|
|
95
104
|
/**
|
|
96
105
|
* Values the column's own schema accepts, seeded by the row so two rows differ and a rerun does
|
|
97
106
|
* not; then the bare `{}`/`[]`, which a schema-less `jsonb` column stores.
|
package/src/seed-graph.ts
CHANGED
|
@@ -63,6 +63,33 @@ function ownedByTenant(
|
|
|
63
63
|
return owned;
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
/**
|
|
67
|
+
* Every untenanted entity (`shared`, or of no tenant) a tenant-owned table points at through a key
|
|
68
|
+
* unique across the TABLE — a unique set holding the reference and not the tenant column. Each
|
|
69
|
+
* tenant's children then take parent rows no other tenant may reuse, so the parent seeds
|
|
70
|
+
* `perTable` rows per tenant: `perTable` alone ran out before tenant 2 (`X_SEED_GRAPH_UNSATISFIED`).
|
|
71
|
+
*/
|
|
72
|
+
function fannedOut(
|
|
73
|
+
shapes: ReadonlyMap<string, EntityShape>,
|
|
74
|
+
scoped: (name: string) => boolean,
|
|
75
|
+
): ReadonlySet<string> {
|
|
76
|
+
const out = new Set<string>();
|
|
77
|
+
for (const shape of shapes.values()) {
|
|
78
|
+
if (!scoped(shape.name)) continue;
|
|
79
|
+
const tenantColumn = shape.entity.$tenantColumn;
|
|
80
|
+
const tableWide = [...shape.uniques, ...shape.partialUniques].filter(
|
|
81
|
+
(set) => tenantColumn === null || !set.includes(tenantColumn),
|
|
82
|
+
);
|
|
83
|
+
for (const reference of shape.references.values()) {
|
|
84
|
+
if (scoped(reference.targetEntity) || reference.targetEntity === shape.name) continue;
|
|
85
|
+
if (tableWide.some((set) => set.includes(reference.property))) {
|
|
86
|
+
out.add(reference.targetEntity);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
66
93
|
export function seedGraph(
|
|
67
94
|
entities: Readonly<Record<string, SeedEntity>>,
|
|
68
95
|
options: SeedGraphOptions = {},
|
|
@@ -108,7 +135,10 @@ export function seedGraph(
|
|
|
108
135
|
}
|
|
109
136
|
const owned = ownedByTenant(shapes, roots);
|
|
110
137
|
const scoped = (name: string): boolean => owned.has(name);
|
|
138
|
+
const fanned = fannedOut(shapes, scoped);
|
|
111
139
|
for (const factory of Object.values(options.factories ?? {})) factory.reset();
|
|
140
|
+
const besideNext = options.beside?.next ?? {};
|
|
141
|
+
const next: Record<string, number> = { ...besideNext };
|
|
112
142
|
|
|
113
143
|
const placed = new Map<string, Placed[]>();
|
|
114
144
|
// The same rows by tenant: a pool read per row was a filter of the whole parent table, so a pass
|
|
@@ -168,11 +198,17 @@ export function seedGraph(
|
|
|
168
198
|
// Read once per table: each `matches(/…/)` an invariant holds a column to, sampled from.
|
|
169
199
|
const patterns = declaredPatterns(entity);
|
|
170
200
|
const buckets: readonly (string | null)[] = scoped(name) ? tenants : [null];
|
|
171
|
-
|
|
201
|
+
// Positions continue past the graph written before this one: a reset factory rebuilt that
|
|
202
|
+
// graph's first values, and a unique column refused the second copy.
|
|
203
|
+
const start = besideNext[name] ?? 0;
|
|
204
|
+
for (let skipped = 0; factory !== undefined && skipped < start; skipped += 1) factory.build();
|
|
205
|
+
let ordinal = start;
|
|
172
206
|
for (const [bucket, tenant] of buckets.entries()) {
|
|
173
|
-
const size =
|
|
207
|
+
const size =
|
|
208
|
+
rootProperty !== undefined ? 1 : fanned.has(name) ? perTable * tenantCount : perTable;
|
|
174
209
|
for (let index = 0; index < size; index += 1) {
|
|
175
210
|
ordinal += 1;
|
|
211
|
+
next[name] = ordinal;
|
|
176
212
|
const canary = stream().replace(/-/g, '').slice(0, 10);
|
|
177
213
|
const built: Readonly<Record<string, unknown>> =
|
|
178
214
|
factory === undefined ? {} : { ...factory.build() };
|
|
@@ -291,5 +327,5 @@ export function seedGraph(
|
|
|
291
327
|
updates.push({ entity: name, tenant, key: keyOf(shape.entity, row), patch });
|
|
292
328
|
}
|
|
293
329
|
}
|
|
294
|
-
return { seed, tenants, order, inserts, updates, canaries };
|
|
330
|
+
return { seed, tenants, order, inserts, updates, canaries, next };
|
|
295
331
|
}
|
package/src/subject-proof.ts
CHANGED
|
@@ -25,6 +25,11 @@ export interface SubjectProofOptions {
|
|
|
25
25
|
readonly seed?: number;
|
|
26
26
|
/** `defineExercise`'s factories: a table only they satisfy is built by them for the proof too. */
|
|
27
27
|
readonly factories?: Readonly<Record<string, SeedFactory>> | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* The graph already written to this database — the previous subject's `graph`. Row positions
|
|
30
|
+
* continue past it, so a factory value built from the index never repeats one on a unique column.
|
|
31
|
+
*/
|
|
32
|
+
readonly beside?: SeedGraph | undefined;
|
|
28
33
|
}
|
|
29
34
|
|
|
30
35
|
export interface SubjectProofResult {
|
|
@@ -32,6 +37,8 @@ export interface SubjectProofResult {
|
|
|
32
37
|
/** The person erased, by key; absent when the plan refused before a row was seeded. */
|
|
33
38
|
readonly key?: string;
|
|
34
39
|
readonly problems: readonly UltimateError[];
|
|
40
|
+
/** What it wrote: the next proof on the same database is seeded `beside` it. */
|
|
41
|
+
readonly graph?: SeedGraph;
|
|
35
42
|
}
|
|
36
43
|
|
|
37
44
|
interface Reached {
|
|
@@ -111,6 +118,7 @@ export async function subjectProof<I>(
|
|
|
111
118
|
seed: finiteOption('subjectProof', 'seed', options.seed ?? 1),
|
|
112
119
|
tenants: 2,
|
|
113
120
|
...(options.factories === undefined ? {} : { factories: options.factories }),
|
|
121
|
+
...(options.beside === undefined ? {} : { beside: options.beside }),
|
|
114
122
|
});
|
|
115
123
|
// The pass's rule: a nullable cycle key the database refuses to set stays null.
|
|
116
124
|
await insertSeedGraph(graph, deferredMayStayNull(options.writer));
|
|
@@ -119,7 +127,9 @@ export async function subjectProof<I>(
|
|
|
119
127
|
(i) => i.entity === subject.entity && (i.tenant === tenant || i.tenant === null),
|
|
120
128
|
);
|
|
121
129
|
const root = entities.get(subject.entity);
|
|
122
|
-
if (person === undefined || root === undefined)
|
|
130
|
+
if (person === undefined || root === undefined) {
|
|
131
|
+
return { subject: subject.entity, problems: [], graph };
|
|
132
|
+
}
|
|
123
133
|
const key = String(person.row[plan.key]);
|
|
124
134
|
const reached = reachedRows(graph, plan, entities, person.row);
|
|
125
135
|
|
|
@@ -181,5 +191,5 @@ export async function subjectProof<I>(
|
|
|
181
191
|
}
|
|
182
192
|
}
|
|
183
193
|
}
|
|
184
|
-
return { subject: subject.entity, key, problems: found };
|
|
194
|
+
return { subject: subject.entity, key, problems: found, graph };
|
|
185
195
|
}
|