@ultimat3/testing 31.14.0 → 31.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -58,6 +58,9 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
58
58
  | The tenant proof is taint only | `tenant-proof.ts`: B, A, B; B is A's role minus `tenancy:cross`. Leak = seeded canary or unhanded id (`tenant-canary.ts`); write = moved digest. Only `crossed` is red |
59
59
  | Every statement the pass sent is planned | `plan-sweep.ts` + `plan-oracle.ts`: `X_QUERY_UNINDEXED` / `X_QUERY_SORT_UNSERVED` with the `indexes:` fix; no generic plan is `X_QUERY_PLAN_UNAVAILABLE`, never a pass † |
60
60
  | A shape that grows with the rows is red | `scale-sweep-run.ts` + pure `judgeScale`: `X_QUERY_SCALES_WITH_ROWS` † |
61
+ | A sized-seed refusal is one finding, not N `unproven` | `scale-sweep-seed.ts`: table by table; only a primitive that read the lost table is `unproven`, `scaleSeedFindings` → `X_EXERCISE_SEED_FAILED` (`scale-sweep-run.test.ts`) |
62
+ | A lost table is read where a table is named | `sql-tables.ts` `statementTables`: `from`/`join`/`update`/`into`/`using` and their comma lists, never a column spelled like one; a view or history table over a lost table is lost too (`scale-sweep-seed.test.ts`). `x doctor`'s raw tenant SQL probe reads tables by the same function |
63
+ | One call has a statement ceiling | `exercise-statement-ceiling.ts`: `STATEMENTS_MAX` 100 per call, `statements: { max, why }` per entry; `X_STATEMENTS_OVER_BUDGET` (`exercise-statement-ceiling.test.ts`) |
61
64
  | An erase is PROVED, not asserted | `subject-proof.ts`: a survivor outside `retain` is `X_SUBJECT_ERASE_INCOMPLETE`, never the value † |
62
65
  | A captured failure replays as a test | `repro.ts`: `reproduce(bundle, { driver })`, `reproJob(runJobs, failure)` — what `x repro --write` emits † |
63
66
  | A vendor's answers are a cassette | `cassette.ts`: replay = `mockFetch` routes, seal kept; record refused under `CI`, secrets scanned before disk; written by action's `stableStringify`, loaded dynamically (`serializeCassette`) † |
package/README.md CHANGED
@@ -38,7 +38,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
38
38
  | `seed-graph-error.ts` | `X_SEED_GRAPH_UNSATISFIED`, its fix naming the `defineFactory` to write; `X_SEED_GRAPH_ENTITY_UNKNOWN`, a plan and a writer built from two entity sets |
39
39
  | `seed-writer.ts` | `entitySeedWriter({ entities, client })` or `({ entities, driver? })` — the `SeedWriter` that writes a graph through each entity's own repository: Postgres or PGlite through a client, or a driver. `@ultimat3/entity` loads on the first write. `snapshot(rows)`, required on every `SeedWriter`, reads rows back as one digest each (`md5(t::text)` over a client), `null` for a row gone |
40
40
  | `exercise.ts` | `runExercisePass({ entities, writer, roles, seed?, overrides?, only? })` — every registered action, query and job once, each on its own committed tenant pair, one `ExerciseRecord` per primitive, the tenant proof's verdict on its `tenant`. What `x exercise` runs |
41
- | `define-exercise.ts` | `defineExercise({ <name>: { actor, input?, runs? } \| { off: '<why>' } }, { actor?: <entity>, factories?: { <entity name>: defineFactory(…) }, setup?: () => mockFetch(…) \| cassette(…) })` — an app's overrides (the second argument names the entity whose rows are the actors, and the factories that build a table no generated row satisfies — a cross-column `satisfies` — keyed by entity name, unknown ones `X_DECLARATION_UNKNOWN`), `apps/web/exercise.ts`'s one export; a blank `off` is `X_CONTRACT_EXERCISE_UNDECLARED`, an unknown name `X_DECLARATION_UNKNOWN` when the pass runs |
41
+ | `define-exercise.ts` | `defineExercise({ <name>: { actor, input?, runs? } \| { off: '<why>' } }, { actor?: <entity>, factories?: { <entity name>: defineFactory(…) }, setup?: () => mockFetch(…) \| cassette(…) })` — an app's overrides (the second argument names the entity whose rows are the actors, and the factories that build a table no generated row satisfies — a cross-column `satisfies` — keyed by entity name, unknown ones `X_DECLARATION_UNKNOWN`), `apps/web/exercise.ts`'s one export; a blank `off` is `X_CONTRACT_EXERCISE_UNDECLARED`, an unknown name `X_DECLARATION_UNKNOWN` when the pass runs. An entry's `statements: { max, why }` moves that primitive's statement ceiling (a blank `why` is `X_CONTRACT_EXERCISE_UNDECLARED`, `max` a whole count ≥ 1) |
42
42
  | `exercise-setup.ts` | `withExerciseSetup(room, setup)`: the app's `setup` run inside the sealed room before the first row, its handle disposed before the room restores the network; an `allowHost` in it is `X_EXERCISE_SETUP_UNSEALED`. Types `ExerciseSetup`, `ExerciseSetupHandle` |
43
43
  | `exercise-actor.ts` · `exercise-input.ts` · `exercise-report.ts` | the first `x policy explain` actor the policy allows, minted in the primitive's tenant · the input: override, then a seeded id by field stem, then the minimal draw (`@ultimat3/schema/sample`, loaded dynamically) · the room one run executes in (network sealed, mail captured, clock frozen) and its record |
44
44
  | `exercise-override-line.ts` | `overrideLine`, the entry an unreached record says to paste: valid TS — the actor the pass ran as (`testActor(name, { roles, permissions }).actor`, `null` signed out, left out when the entry declares one) and each id field bound to the seeded row the pass used; an id it could not bind is the string `UNBOUND_ID` |
@@ -46,6 +46,9 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
46
46
  | `tenant-canary.ts` | internal: `tenantTaint` — one tenant's rows, ids and marks (row canaries, key parts of `MIN_TAINT_ID_LENGTH` 8 or more no other tenant shares); `findTaint` — every path holding one |
47
47
  | `exercise-crash.ts` | internal: `proveCrash` — a job the pass reached, run through `crashProof` with its control's input and actor, after the tenant proof; the `CrashProof` on `ExerciseRecord.crash` |
48
48
  | `scale-sweep.ts` · `scale-sweep-graph.ts` · `scale-sweep-run.ts` · `exercise-sweeps.ts` | `judgeScale(small, large)`, pure · one tenant at a size, its rows of no tenant pointed at the pass's own · the two sized runs · both sweeps after the pass, onto each record's `scale` and `plans` |
49
+ | `scale-sweep-seed.ts` · `scale-sweep-findings.ts` | the sized seed written table by table: a refusal loses that table and the tables pointing at it, and leaves `unproven` (with `seed: ScaleSeedFailure`) only the primitives whose own statements read one · `scaleSeedFindings(records)`: one `X_EXERCISE_SEED_FAILED` per lost table, every reader named |
50
+ | `sql-tables.ts` | `statementTables(sql)`, pure: every table one statement names after `from` / `join` / `update` / `into` / `using`, each name of a comma list there too (`from orgs o, posts p`), last part of a qualified or quoted name, lowercased. The sweep's lost-table reader and `x doctor`'s raw tenant SQL probe read tables by it |
51
+ | `exercise-statement-ceiling.ts` | `judgeStatementCeiling(calls, declared?)`, pure: the busiest call's statements no `expectedQueryLoop` declared (`expected` counts the rest) against `STATEMENTS_MAX` (100) or the entry's `statements.max`, onto `ExerciseRecord.statementCeiling` · `statementCeilingFindings(records)`: `X_STATEMENTS_OVER_BUDGET`, the three busiest shapes named. Whether either finding is red is the caller's (`x exercise`) |
49
52
  | `plan-oracle.ts` · `plan-sweep.ts` · `plan-sweep-fix.ts` · `plan-sweep-report.ts` | `judgePlan(answer, tables)`, pure: the red nodes · `sweepPlans(client, sent, entities)`: `PREPARE` + `explain execute` in a read-only transaction · verdict to `indexes:` line · the coded findings `x exercise` prints |
50
53
  | `job-crash-proof.ts` | `crashProof(handle, input, { context?, seed? })` — one clean run, then the worker killed at every step boundary it crossed, then each answer lost; `{ boundaries, divergences, reruns }`, a divergence carrying its `X_JOB_CRASH_DIVERGED` |
51
54
  | `job-simulate.ts` | `simulateJobs({ seed?, seeds, jobs, workers, faults, invariant })` — seeded races on the shared simulated driver; `X_JOB_SIM_INVARIANT`, `X_JOB_SIM_NONDETERMINISTIC`; `x test job --seed <n>` replays one |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.14.0",
3
+ "version": "31.16.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,26 +47,26 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.14.0",
51
- "@ultimat3/ai": "31.14.0",
52
- "@ultimat3/auth": "31.14.0",
53
- "@ultimat3/cache": "31.14.0",
54
- "@ultimat3/core": "31.14.0",
55
- "@ultimat3/db": "31.14.0",
56
- "@ultimat3/entity": "31.14.0",
57
- "@ultimat3/http": "31.14.0",
58
- "@ultimat3/i18n": "31.14.0",
59
- "@ultimat3/jobs": "31.14.0",
60
- "@ultimat3/mail": "31.14.0",
61
- "@ultimat3/notify": "31.14.0",
62
- "@ultimat3/policy": "31.14.0",
63
- "@ultimat3/pwa": "31.14.0",
64
- "@ultimat3/query": "31.14.0",
65
- "@ultimat3/realtime": "31.14.0",
66
- "@ultimat3/render": "31.14.0",
67
- "@ultimat3/schema": "31.14.0",
68
- "@ultimat3/scraping": "31.14.0",
69
- "@ultimat3/seo": "31.14.0",
70
- "@ultimat3/time": "31.14.0"
50
+ "@ultimat3/action": "31.16.0",
51
+ "@ultimat3/ai": "31.16.0",
52
+ "@ultimat3/auth": "31.16.0",
53
+ "@ultimat3/cache": "31.16.0",
54
+ "@ultimat3/core": "31.16.0",
55
+ "@ultimat3/db": "31.16.0",
56
+ "@ultimat3/entity": "31.16.0",
57
+ "@ultimat3/http": "31.16.0",
58
+ "@ultimat3/i18n": "31.16.0",
59
+ "@ultimat3/jobs": "31.16.0",
60
+ "@ultimat3/mail": "31.16.0",
61
+ "@ultimat3/notify": "31.16.0",
62
+ "@ultimat3/policy": "31.16.0",
63
+ "@ultimat3/pwa": "31.16.0",
64
+ "@ultimat3/query": "31.16.0",
65
+ "@ultimat3/realtime": "31.16.0",
66
+ "@ultimat3/render": "31.16.0",
67
+ "@ultimat3/schema": "31.16.0",
68
+ "@ultimat3/scraping": "31.16.0",
69
+ "@ultimat3/seo": "31.16.0",
70
+ "@ultimat3/time": "31.16.0"
71
71
  }
72
72
  }
@@ -3,13 +3,19 @@
3
3
  // A blank `off` is refused at declaration, an unknown name when the pass runs. A key is a bare name
4
4
  // or a kind-qualified one (`'job:eraseAccount'`), which wins over the bare name for its kind.
5
5
 
6
- import type { ExerciseOptions } from '@ultimat3/action';
7
- import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
6
+ import type { ExerciseActorOptions, ExerciseOffOptions } from '@ultimat3/action';
7
+ import { finiteCount, renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
8
8
  import type { ExerciseSetup } from './exercise-setup';
9
+ import type { ExerciseStatementCeiling } from './exercise-statement-ceiling';
9
10
  import type { SeedFactory } from './seed-graph-plan';
10
11
 
11
- /** 39's option type, exactly: `{ actor, input?, runs? }` or `{ off: '<reason>' }`. */
12
- export type ExerciseOverride = ExerciseOptions;
12
+ /**
13
+ * 39's option type — `{ actor, input?, runs? }` or `{ off: '<reason>' }` — and the pass's own
14
+ * `statements: { max, why }`: the ceiling one call is held to, `STATEMENTS_MAX` when omitted.
15
+ */
16
+ export type ExerciseOverride =
17
+ | (ExerciseActorOptions & { readonly statements?: ExerciseStatementCeiling })
18
+ | ExerciseOffOptions;
13
19
 
14
20
  /**
15
21
  * What `defineExercise` returns: the overrides, by primitive name. Read by `runExercisePass` and,
@@ -81,6 +87,23 @@ const blankReason = (name: string): UltimateError =>
81
87
  fix: `defineExercise({ ${renderFixLiteral(name, '<name>')}: { off: '<why this primitive cannot run in the exercise pass>' } }) # in apps/web/exercise.ts`,
82
88
  });
83
89
 
90
+ /** The same silence for a ceiling: `statements: { max }` with no stated reason to move it. */
91
+ const blankCeiling = (name: string): UltimateError =>
92
+ new UltimateError({
93
+ code: 'X_CONTRACT_EXERCISE_UNDECLARED',
94
+ cause: `defineExercise() moves the statement ceiling of ${renderCauseValue(name)} with a blank why, so the exception is silent`,
95
+ fix: `defineExercise({ ${renderFixLiteral(name, '<name>')}: { statements: { max: <n>, why: '<why one call sends that many>' } } }) # in apps/web/exercise.ts`,
96
+ });
97
+
98
+ /** The entry's ceiling, held to a whole count ≥ 1 and a stated reason. */
99
+ const checkCeiling = (name: string, override: ExerciseOverride): void => {
100
+ if ('off' in override || override.statements === undefined) return;
101
+ finiteCount('defineExercise()', `${name}.statements.max`, override.statements.max, 1);
102
+ const { why } = override.statements;
103
+ // Typed, but an untyped `exercise.ts` can omit it: absent is as silent as blank.
104
+ if (typeof why !== 'string' || why.trim().length === 0) throw blankCeiling(name);
105
+ };
106
+
84
107
  export function defineExercise(
85
108
  overrides: Readonly<Record<string, ExerciseOverride>>,
86
109
  app: ExerciseAppOptions = {},
@@ -89,6 +112,7 @@ export function defineExercise(
89
112
  // `Object.entries`, never `for in`: an inherited key is not a declaration.
90
113
  for (const [name, override] of Object.entries(overrides)) {
91
114
  if ('off' in override && override.off.trim().length === 0) throw blankReason(name);
115
+ checkCeiling(name, override);
92
116
  entries.set(name, override);
93
117
  }
94
118
  return Object.freeze({
package/src/errors.ts CHANGED
@@ -76,6 +76,8 @@ export const TESTING_ERROR_CODES = [
76
76
  'X_TEST_MAIL_EXPECTED',
77
77
  'X_TEST_ADAPTER_PORT_UNSWAPPABLE',
78
78
  'X_TEST_FACTORY_INVALID',
79
+ 'X_EXERCISE_SEED_FAILED',
80
+ 'X_STATEMENTS_OVER_BUDGET',
79
81
  ] as const;
80
82
 
81
83
  export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
@@ -154,6 +156,8 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
154
156
  X_TEST_MAIL_EXPECTED: 'toHaveSentMail was handed something other than the mail fixture',
155
157
  X_TEST_ADAPTER_PORT_UNSWAPPABLE: 'swapAdapter() was named a port it cannot swap for one test',
156
158
  X_TEST_FACTORY_INVALID: 'a factory builds a row its own entity refuses',
159
+ X_EXERCISE_SEED_FAILED: 'The scale sweep could not write the sized rows of one entity',
160
+ X_STATEMENTS_OVER_BUDGET: 'One primitive call sent more statements than its ceiling',
157
161
  };
158
162
 
159
163
  // Titles must be registered for `format()` to render the contract's first line. Every code above is
@@ -9,6 +9,7 @@ import { expectedSeqScanReason, statementFingerprint } from '@ultimat3/db';
9
9
  import { captureDeterminism, installDeterminism, restoreCapturedDeterminism } from './determinism';
10
10
  import type { ExerciseDefect } from './exercise-defect';
11
11
  import { roomMail } from './exercise-room-mail';
12
+ import type { StatementCeilingProof } from './exercise-statement-ceiling';
12
13
  import { routeMatches } from './mock-route';
13
14
  import type { PlanProof, SentStatement } from './plan-sweep';
14
15
  import type { LoggedRequest } from './request-log';
@@ -128,6 +129,8 @@ export interface ExerciseRecord {
128
129
  readonly plans?: PlanProof;
129
130
  /** On a reached primitive: its statement shapes at 2 and at 8 rows a table (`scale-sweep.ts`). */
130
131
  readonly scale?: ScaleProof;
132
+ /** On a primitive whose control ran: its busiest call against its statement ceiling. */
133
+ readonly statementCeiling?: StatementCeilingProof;
131
134
  /** Wall time of each proof that ran on it; `ms` above is the control's own call. */
132
135
  readonly proofMs?: ProofMs;
133
136
  }
@@ -0,0 +1,147 @@
1
+ // The absolute statement ceiling: one call sends at most `STATEMENTS_MAX` statements unless its
2
+ // `defineExercise` entry sets `statements: { max, why }`. The scale sweep judges growth; this judges
3
+ // the count — a fixed 300-statement call is flat and slow. Statements inside an `expectedQueryLoop`
4
+ // are not judged, as in the scale sweep: a backfill's pass is a declared loop, its size the table's.
5
+
6
+ import { finiteCount, renderCauseValue, renderFixLiteral, renderFixShellArg } from '@ultimat3/core';
7
+ import type { StatementTally } from './scale-sweep';
8
+
9
+ /** Statements one call may send when its entry declares no `statements`. */
10
+ export const STATEMENTS_MAX = 100;
11
+
12
+ /** `statements: { max: 140, why: 'imports one row per line, bounded by the 140-line form' }`. */
13
+ export interface ExerciseStatementCeiling {
14
+ readonly max: number;
15
+ readonly why: string;
16
+ }
17
+
18
+ /** One call's statements: the count and its shapes, as the room observed them. */
19
+ interface CallTally {
20
+ readonly statements: number;
21
+ readonly shapes: readonly StatementTally[];
22
+ }
23
+
24
+ /** A shape among the over-budget call's largest, by count. */
25
+ export interface CeilingShape {
26
+ readonly fingerprint: string;
27
+ readonly count: number;
28
+ }
29
+
30
+ /** The busiest call against the ceiling in force; `why` / `declared` when the entry declared it. */
31
+ export type StatementCeilingProof =
32
+ | {
33
+ readonly verdict: 'within';
34
+ readonly statements: number;
35
+ readonly max: number;
36
+ /** Statements sent under an `expectedQueryLoop`, left out of `statements`; absent at zero. */
37
+ readonly expected?: number;
38
+ /** The entry's own `statements` — at the default figure too, so no floor re-judges it. */
39
+ readonly declared?: true;
40
+ }
41
+ | {
42
+ readonly verdict: 'over';
43
+ readonly statements: number;
44
+ readonly max: number;
45
+ readonly expected?: number;
46
+ /** The three shapes it sent most, largest first: what a `preload` would fold. */
47
+ readonly top: readonly CeilingShape[];
48
+ readonly why?: string;
49
+ };
50
+
51
+ const TOP_SHAPES = 3;
52
+
53
+ /** A call as judged: the statements no loop declared, and how many one did. */
54
+ interface Judged {
55
+ readonly statements: number;
56
+ readonly expected: number;
57
+ readonly shapes: readonly StatementTally[];
58
+ }
59
+
60
+ // Subtracted rather than summed from `unexpected`: a tally recorded without shapes judges in full.
61
+ const judged = (call: CallTally): Judged => {
62
+ const expected = call.shapes.reduce((sum, shape) => sum + shape.count - shape.unexpected, 0);
63
+ return { statements: call.statements - expected, expected, shapes: call.shapes };
64
+ };
65
+
66
+ /** The busiest of `calls` against `declared`, else `STATEMENTS_MAX`. No call: nothing to judge. */
67
+ export function judgeStatementCeiling(
68
+ calls: readonly CallTally[],
69
+ declared?: ExerciseStatementCeiling,
70
+ ): StatementCeilingProof | undefined {
71
+ const busiest = calls
72
+ .map(judged)
73
+ .reduce<Judged | undefined>(
74
+ (top, call) => (top === undefined || call.statements > top.statements ? call : top),
75
+ undefined,
76
+ );
77
+ if (busiest === undefined) return undefined;
78
+ // `defineExercise` screens a declared max; an override built by hand reaches here unscreened.
79
+ const max = finiteCount('statements', 'max', declared?.max ?? STATEMENTS_MAX, 1);
80
+ const expected = busiest.expected === 0 ? {} : { expected: busiest.expected };
81
+ if (busiest.statements <= max) {
82
+ return {
83
+ verdict: 'within',
84
+ statements: busiest.statements,
85
+ max,
86
+ ...expected,
87
+ ...(declared === undefined ? {} : { declared: true as const }),
88
+ };
89
+ }
90
+ const top = busiest.shapes
91
+ .filter((shape) => shape.unexpected > 0)
92
+ .map(({ fingerprint, unexpected }) => ({ fingerprint, count: unexpected }))
93
+ .sort((a, b) => b.count - a.count || a.fingerprint.localeCompare(b.fingerprint))
94
+ .slice(0, TOP_SHAPES);
95
+ return {
96
+ verdict: 'over',
97
+ statements: busiest.statements,
98
+ max,
99
+ ...expected,
100
+ top,
101
+ ...(declared === undefined ? {} : { why: declared.why }),
102
+ };
103
+ }
104
+
105
+ /** What a finding needs of a record: who it is and its ceiling proof. */
106
+ interface CeilingRecord {
107
+ readonly kind: string;
108
+ readonly name: string;
109
+ readonly statementCeiling?: StatementCeilingProof;
110
+ }
111
+
112
+ export interface StatementCeilingFinding {
113
+ readonly code: 'X_STATEMENTS_OVER_BUDGET';
114
+ readonly cause: string;
115
+ readonly fix: string;
116
+ readonly at: string;
117
+ }
118
+
119
+ /** One finding per primitive whose busiest call went over its ceiling, its top shapes named. */
120
+ export function statementCeilingFindings(
121
+ records: readonly CeilingRecord[],
122
+ ): readonly StatementCeilingFinding[] {
123
+ return records.flatMap((record): StatementCeilingFinding[] => {
124
+ const proof = record.statementCeiling;
125
+ if (proof?.verdict !== 'over') return [];
126
+ const shapes = proof.top.map((one) => `${one.fingerprint} ×${one.count}`).join(', ');
127
+ const ceiling =
128
+ proof.why === undefined
129
+ ? `the default ceiling of ${proof.max}`
130
+ : `its declared ceiling of ${proof.max} (${renderCauseValue(proof.why)})`;
131
+ const looped =
132
+ proof.expected === undefined
133
+ ? ''
134
+ : ` (${proof.expected} more under expectedQueryLoop, not counted)`;
135
+ const name = renderFixShellArg(record.name, '<primitive>');
136
+ const entry = renderFixLiteral(record.name, '<primitive>');
137
+ return [
138
+ {
139
+ code: 'X_STATEMENTS_OVER_BUDGET',
140
+ cause: `${record.kind} ${renderCauseValue(record.name)} sent ${proof.statements} statements in one call${looped}, over ${ceiling}; most sent: ${renderCauseValue(shapes)}`,
141
+ // The edit first: the rerun before it re-sends the same count (`fix-sequence.ts`).
142
+ fix: `defineExercise({ ${entry}: { statements: { max: ${proof.statements}, why: '<why one call needs them>' } } }) # in apps/web/exercise.ts, unless a preload() folds what the call reads row by row; then: x exercise ${name} --json`,
143
+ at: `${record.kind} ${record.name}`,
144
+ },
145
+ ];
146
+ });
147
+ }
package/src/exercise.ts CHANGED
@@ -37,6 +37,8 @@ import type {
37
37
  } from './exercise-report';
38
38
  import { openExerciseRoom } from './exercise-report';
39
39
  import { withExerciseSetup } from './exercise-setup';
40
+ import type { ExerciseStatementCeiling } from './exercise-statement-ceiling';
41
+ import { judgeStatementCeiling } from './exercise-statement-ceiling';
40
42
  import type { Subject } from './exercise-subjects';
41
43
  import { fixedTenant, seatIn, subjectsOf } from './exercise-subjects';
42
44
  import { actorRowsOf, attachSweeps, seated, sizedCall } from './exercise-sweeps';
@@ -120,6 +122,8 @@ interface Prepared {
120
122
  readonly bindInput: OverrideInput | undefined;
121
123
  /** The actor the pass picked, as the paste line spells it (`exercise-override-line.ts`). */
122
124
  readonly actorHint: OverrideHint['actor'];
125
+ /** The entry's `statements: { max, why }`: the ceiling each call is held to. */
126
+ readonly ceiling: ExerciseStatementCeiling | undefined;
123
127
  }
124
128
 
125
129
  /** Thrown out of 39's loop by a bind that failed: the record is the entry's, never the loop's. */
@@ -213,6 +217,8 @@ async function control(
213
217
  verdict.kind === 'defect' && verdictOf.outcome === 'unreached'
214
218
  ? await defectDetail(verdict.error, verdict.input, subject.input)
215
219
  : undefined;
220
+ // Each segment is one call: the ceiling is per call, never the runs' sum.
221
+ const statementCeiling = judgeStatementCeiling(segments, run.ceiling);
216
222
  const record = {
217
223
  kind,
218
224
  name,
@@ -221,6 +227,7 @@ async function control(
221
227
  ms,
222
228
  ...verdictOf,
223
229
  ...(defect === undefined ? {} : { defect }),
230
+ ...(statementCeiling === undefined ? {} : { statementCeiling }),
224
231
  };
225
232
  return { record, output, input: lastInput };
226
233
  }
@@ -312,6 +319,7 @@ async function exerciseOne(
312
319
  lookups,
313
320
  bindInput,
314
321
  actorHint: actorHintOf(chosen, override),
322
+ ceiling: override === undefined || 'off' in override ? undefined : override.statements,
315
323
  };
316
324
  // A's own first input, A's ids in it: B sends exactly what A legitimately would.
317
325
  const drawn = bindIds(drawInput(sampler, subject.input, 0, 0), lookups[0]);
package/src/index.ts CHANGED
@@ -153,6 +153,17 @@ export type {
153
153
  TenantProof,
154
154
  } from './exercise-report';
155
155
  export type { ExerciseSetup, ExerciseSetupHandle } from './exercise-setup';
156
+ export type {
157
+ CeilingShape,
158
+ ExerciseStatementCeiling,
159
+ StatementCeilingFinding,
160
+ StatementCeilingProof,
161
+ } from './exercise-statement-ceiling';
162
+ export {
163
+ judgeStatementCeiling,
164
+ STATEMENTS_MAX,
165
+ statementCeilingFindings,
166
+ } from './exercise-statement-ceiling';
156
167
  export { defineFactory } from './factories';
157
168
  export type { AnyFactory, Factory, FactoryExtension, FactoryOptions } from './factory-api';
158
169
  export type { BelongsToOptions, HasManyOptions } from './factory-associations';
@@ -365,6 +376,9 @@ export type { LoggedRequest } from './request-log';
365
376
  export { reusableDatabase } from './reusable-database';
366
377
  export type { ScaleProof, ScaleShape, StatementTally } from './scale-sweep';
367
378
  export { judgeScale, SCALE_SIZES } from './scale-sweep';
379
+ export type { ScaleSeedFinding } from './scale-sweep-findings';
380
+ export { scaleSeedFindings } from './scale-sweep-findings';
381
+ export type { ScaleSeedFailure } from './scale-sweep-seed';
368
382
  export type { NetworkSnapshot, NetworkState } from './sealed-network';
369
383
  // `setNetworkState` is deliberately not here: it is the offline gate's one writer, and a test that
370
384
  // called it directly would bypass the `network` fixture's disposal and leave the whole process
@@ -404,6 +418,8 @@ export type { EntitySeedWriterOptions, SeedWriterTarget } from './seed-writer';
404
418
  export { entitySeedWriter } from './seed-writer';
405
419
  export type { SharedExamples } from './shared-examples';
406
420
  export { behavesLike, sharedExamples } from './shared-examples';
421
+ // One SQL table scan for the sweep's lost-table reader and `x doctor`'s raw tenant SQL probe.
422
+ export { statementTables } from './sql-tables';
407
423
  // Test doubles: `stub(primitive)` replaces an action's, an llm()'s or a job's body, `swapAdapter`
408
424
  // an adapter port; both are put back after the test that made them (`test-scope.ts`).
409
425
  export { stub } from './stub';
@@ -73,7 +73,7 @@ export class IslandMountMissingError extends UltimateError {
73
73
  fix:
74
74
  component === undefined
75
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); }`,
76
+ : `in ${file} add: import { mountOver } from '@ultimat3/render/client'; import { render } from 'solid-js/web'; export function mount(el: HTMLElement, props: Parameters<typeof ${component}>[0]): () => void { return mountOver(el, (root) => render(() => <${component} {...props} />, root)); }`,
77
77
  });
78
78
  }
79
79
  }
@@ -0,0 +1,46 @@
1
+ // The scale sweep's own failure, as `x exercise` reports it: one `X_EXERCISE_SEED_FAILED` per table
2
+ // the sized seed could not write, naming the entity, the driver's words and every primitive whose
3
+ // scale proof it left `unproven` — never one unexplained `unproven` per primitive.
4
+
5
+ import { renderCauseValue, renderFixLiteral } from '@ultimat3/core';
6
+ import type { ScaleProof } from './scale-sweep';
7
+ import type { ScaleSeedFailure } from './scale-sweep-seed';
8
+
9
+ /** What a finding needs of a record: who it is and its scale proof. */
10
+ interface ScaleRecord {
11
+ readonly kind: string;
12
+ readonly name: string;
13
+ readonly scale?: ScaleProof;
14
+ }
15
+
16
+ export interface ScaleSeedFinding {
17
+ readonly code: 'X_EXERCISE_SEED_FAILED';
18
+ readonly cause: string;
19
+ readonly fix: string;
20
+ readonly at: string;
21
+ }
22
+
23
+ const MAX_NAMED = 10;
24
+
25
+ /** One finding per failed table, in the order the readers' records list them. */
26
+ export function scaleSeedFindings(records: readonly ScaleRecord[]): readonly ScaleSeedFinding[] {
27
+ const groups = new Map<string, { failure: ScaleSeedFailure; readers: string[] }>();
28
+ for (const record of records) {
29
+ const failure = record.scale?.verdict === 'unproven' ? record.scale.seed : undefined;
30
+ if (failure === undefined) continue;
31
+ const group = groups.get(failure.entity) ?? { failure, readers: [] };
32
+ group.readers.push(`${record.kind} ${record.name}`);
33
+ groups.set(failure.entity, group);
34
+ }
35
+ return [...groups.values()].map(({ failure, readers }) => {
36
+ const named = readers.slice(0, MAX_NAMED).join(', ');
37
+ const more = readers.length > MAX_NAMED ? ` and ${readers.length - MAX_NAMED} more` : '';
38
+ const entity = renderFixLiteral(failure.entity, '<entity>');
39
+ return {
40
+ code: 'X_EXERCISE_SEED_FAILED',
41
+ cause: `the scale sweep could not write the sized rows of ${renderCauseValue(failure.entity)} (${renderCauseValue(failure.cause)}), so ${readers.length} primitive(s) reading it are unproven: ${named}${more}`,
42
+ fix: `defineExercise({}, { factories: { ${entity}: defineFactory(<the ${failure.entity} entity>, { defaults: (index) => ({ /* each constrained column, distinct per index */ }) }) } }) # in apps/web/exercise.ts, then: x exercise --json`,
43
+ at: 'apps/web/exercise.ts',
44
+ };
45
+ });
46
+ }
@@ -11,8 +11,8 @@ import type { ScaleProof, StatementTally } from './scale-sweep';
11
11
  import { judgeScale, SCALE_SIZES } from './scale-sweep';
12
12
  import type { ScaleGraph } from './scale-sweep-graph';
13
13
  import { scaleGraph } from './scale-sweep-graph';
14
+ import { readsLost, writeSizedSeeds } from './scale-sweep-seed';
14
15
  import type { SeedFactory, SeedGraph, SeedWriter } from './seed-graph-plan';
15
- import { insertSeedGraph } from './seed-graph-plan';
16
16
  import type { SeedEntity } from './seed-graph-shape';
17
17
 
18
18
  /** What the sweep needs of a primitive: the pass's own call. */
@@ -79,7 +79,10 @@ async function callAt(
79
79
  return 'failure' in seen.value ? { failed: renderThrowable(seen.value.failure) } : seen.observed;
80
80
  }
81
81
 
82
- /** Seed both sizes, call each subject at each, judge. Unseedable: every subject `unproven`. */
82
+ /**
83
+ * Seed both sizes, call each subject at each, judge. A table the sized seed could not write leaves
84
+ * `unproven` only the subjects that read it, the failure on their proof; the rest are judged.
85
+ */
83
86
  export async function scaleSweep(
84
87
  options: ScaleSweepOptions,
85
88
  ): Promise<ReadonlyMap<string, ScaleProof>> {
@@ -99,20 +102,25 @@ export async function scaleSweep(
99
102
  }),
100
103
  );
101
104
  }
102
- try {
103
- for (const size of sizes) await insertSeedGraph(size.write, options.writer);
104
- } catch (error) {
105
- const reason = `the sized seed did not write: ${renderThrowable(error)}`;
106
- for (const subject of options.subjects)
107
- proofs.set(subject.name, { verdict: 'unproven', reason });
108
- return proofs;
109
- }
105
+ const loss = await writeSizedSeeds(
106
+ sizes.map((size) => size.write),
107
+ options.entities,
108
+ options.writer,
109
+ );
110
+ const sent = options.room.sent();
111
+ const subjects = options.subjects.filter((subject) => {
112
+ const seed = readsLost(subject.name, sent, loss, options.entities);
113
+ if (seed === undefined) return true;
114
+ const reason = `the sized seed did not write ${seed.entity}, which it reads: ${seed.cause}`;
115
+ proofs.set(subject.name, { verdict: 'unproven', reason, seed });
116
+ return false;
117
+ });
110
118
  const runs: Call[][] = [];
111
119
  // The reading that answered at the small size is the one the large size repeats.
112
- const selves = options.subjects.map(() => true);
120
+ const selves = subjects.map(() => true);
113
121
  for (const [at, size] of sizes.entries()) {
114
122
  const calls: Call[] = [];
115
- for (const [i, subject] of options.subjects.entries()) {
123
+ for (const [i, subject] of subjects.entries()) {
116
124
  let call = await callAt(subject, size.lookup, size.tenant, options, selves[i] ?? true);
117
125
  if (at === 0 && 'failed' in call) {
118
126
  const other = await callAt(subject, size.lookup, size.tenant, options, false);
@@ -125,7 +133,7 @@ export async function scaleSweep(
125
133
  }
126
134
  runs.push(calls);
127
135
  }
128
- options.subjects.forEach((subject, i) => {
136
+ subjects.forEach((subject, i) => {
129
137
  const small = runs[0]?.[i];
130
138
  const large = runs[1]?.[i];
131
139
  if (small === undefined || large === undefined) return;
@@ -0,0 +1,140 @@
1
+ // The scale sweep's sized seed, written entity by entity: one table's refusal (a unique key, a check)
2
+ // is that table's, never the sweep's. Its rows, and every table that points at it, are skipped; the
3
+ // rest are written, so only a primitive that reads a lost table goes `unproven` (`readsLost`).
4
+
5
+ import { renderThrowable } from '@ultimat3/core';
6
+ import type { SentStatement } from './plan-sweep';
7
+ import type { SeedGraph, SeedRow, SeedWriter } from './seed-graph-plan';
8
+ import { entityRuns } from './seed-graph-plan';
9
+ import type { SeedEntity } from './seed-graph-shape';
10
+ import { statementTables } from './sql-tables';
11
+
12
+ /** One table the sized seed could not write: the entity, and the driver's words (the constraint). */
13
+ export interface ScaleSeedFailure {
14
+ readonly entity: string;
15
+ readonly table: string;
16
+ readonly cause: string;
17
+ }
18
+
19
+ /** What the sized seed did not write: the tables that refused, and every table left without rows. */
20
+ export interface ScaleSeedLoss {
21
+ readonly failures: readonly ScaleSeedFailure[];
22
+ /** Entity name → the failure it lost its rows to: its own, or a referenced table's. */
23
+ readonly lost: ReadonlyMap<string, ScaleSeedFailure>;
24
+ }
25
+
26
+ /** The failure a table pointing at a lost one inherits: the first of its references that is lost. */
27
+ const inherited = (
28
+ entity: SeedEntity | undefined,
29
+ lost: ReadonlyMap<string, ScaleSeedFailure>,
30
+ ): ScaleSeedFailure | undefined => {
31
+ for (const ref of entity?.$references() ?? []) {
32
+ if (ref.targetEntity === entity?.$name) continue;
33
+ const failure = lost.get(ref.targetEntity);
34
+ if (failure !== undefined) return failure;
35
+ }
36
+ return undefined;
37
+ };
38
+
39
+ /**
40
+ * Every graph, in order, one entity's run at a time. A run that throws marks its entity lost; a run
41
+ * of a lost entity, or of one referencing a lost entity, is not sent (its keys point at nothing).
42
+ */
43
+ export async function writeSizedSeeds(
44
+ graphs: readonly SeedGraph[],
45
+ entities: readonly SeedEntity[],
46
+ writer: SeedWriter,
47
+ ): Promise<ScaleSeedLoss> {
48
+ const byName = new Map(entities.map((entity) => [entity.$name, entity]));
49
+ const failures: ScaleSeedFailure[] = [];
50
+ const lost = new Map<string, ScaleSeedFailure>();
51
+ const attempt = async (entity: string, table: string, write: () => Promise<void>) => {
52
+ if (lost.has(entity)) return;
53
+ const from = inherited(byName.get(entity), lost);
54
+ if (from !== undefined) {
55
+ lost.set(entity, from);
56
+ return;
57
+ }
58
+ try {
59
+ await write();
60
+ } catch (error) {
61
+ const failure = { entity, table, cause: renderThrowable(error) };
62
+ failures.push(failure);
63
+ lost.set(entity, failure);
64
+ }
65
+ };
66
+ for (const graph of graphs) {
67
+ for (const run of entityRuns(graph.inserts)) {
68
+ const [first] = run as readonly [SeedRow, ...SeedRow[]];
69
+ await attempt(first.entity, first.table, async () => {
70
+ if (writer.insertMany !== undefined) await writer.insertMany(run);
71
+ else for (const row of run) await writer.insert(row);
72
+ });
73
+ }
74
+ for (const update of graph.updates) {
75
+ const table = byName.get(update.entity)?.$table ?? update.entity;
76
+ await attempt(update.entity, table, () => writer.update(update));
77
+ }
78
+ }
79
+ return { failures, lost };
80
+ }
81
+
82
+ /**
83
+ * Each entity with no rows of its own whose source lost its rows: a view over a lost table (read
84
+ * off its SQL, views over views too) and a history table whose parent is lost — the trigger writes
85
+ * its rows from the parent's. Their reads are judged against rows the sized seed never wrote.
86
+ */
87
+ const derivedLoss = (
88
+ entities: readonly SeedEntity[],
89
+ lost: ReadonlyMap<string, ScaleSeedFailure>,
90
+ ): ReadonlyMap<string, ScaleSeedFailure> => {
91
+ const byTable = new Map(entities.map((entity) => [entity.$table.toLowerCase(), entity.$name]));
92
+ const all = new Map(lost);
93
+ for (let grew = true; grew; ) {
94
+ grew = false;
95
+ for (const entity of entities) {
96
+ if (all.has(entity.$name)) continue;
97
+ const described = entity.$describe();
98
+ const sources = [
99
+ ...(described.historyOf === undefined ? [] : [described.historyOf]),
100
+ ...(described.view === undefined ? [] : statementTables(described.view.sql)).flatMap(
101
+ (table) => byTable.get(table) ?? [],
102
+ ),
103
+ ];
104
+ const failure = sources.map((source) => all.get(source)).find((one) => one !== undefined);
105
+ if (failure === undefined) continue;
106
+ all.set(entity.$name, failure);
107
+ grew = true;
108
+ }
109
+ }
110
+ return all;
111
+ };
112
+
113
+ /**
114
+ * The lost table `subject` read in the pass — any statement it sent naming one in a table position
115
+ * (`statementTables`: a column spelled like one is no read of it) — or none. Read off the room's
116
+ * `sent()`: what a primitive's own call sent is what its sized call sends again.
117
+ */
118
+ export function readsLost(
119
+ subject: string,
120
+ sent: ReadonlyMap<string, SentStatement>,
121
+ loss: ScaleSeedLoss,
122
+ entities: readonly SeedEntity[],
123
+ ): ScaleSeedFailure | undefined {
124
+ if (loss.lost.size === 0) return undefined;
125
+ const lost = derivedLoss(entities, loss.lost);
126
+ const tables = new Map(
127
+ entities.flatMap((entity) => {
128
+ const failure = lost.get(entity.$name);
129
+ return failure === undefined ? [] : [[entity.$table.toLowerCase(), failure] as const];
130
+ }),
131
+ );
132
+ for (const [text, statement] of sent) {
133
+ if (!statement.primitives.has(subject)) continue;
134
+ for (const table of statementTables(text)) {
135
+ const failure = tables.get(table);
136
+ if (failure !== undefined) return failure;
137
+ }
138
+ }
139
+ return undefined;
140
+ }
@@ -2,6 +2,8 @@
2
2
  // sent more often when the tables hold more rows is a loop over rows — an N+1 no test named — and
3
3
  // red, unless `expectedQueryLoop` scoped it, which is reported with its reason. Pure: tallies in.
4
4
 
5
+ import type { ScaleSeedFailure } from './scale-sweep-seed';
6
+
5
7
  /** One statement shape in one call: every statement, and the ones no `expectedQueryLoop` covered. */
6
8
  export interface StatementTally {
7
9
  /** `statementFingerprint`: `posts.findById` when attributed, else the collapsed text. */
@@ -29,8 +31,11 @@ export type ScaleProof =
29
31
  readonly shapes: readonly ScaleShape[];
30
32
  readonly expected: readonly ScaleShape[];
31
33
  }
32
- /** A call at one size did not answer as at the other: the counts are not comparable. Never red. */
33
- | { readonly verdict: 'unproven'; readonly reason: string };
34
+ /**
35
+ * A call at one size did not answer as at the other: the counts are not comparable. Never red
36
+ * itself; `seed` is the sized table it read and could not be written, `X_EXERCISE_SEED_FAILED`.
37
+ */
38
+ | { readonly verdict: 'unproven'; readonly reason: string; readonly seed?: ScaleSeedFailure };
34
39
 
35
40
  /** Rows a table per tenant at each size: a loop over them sends 2 statements, then 8. */
36
41
  export const SCALE_SIZES = { small: 2, large: 8 } as const;
@@ -38,7 +43,10 @@ export const SCALE_SIZES = { small: 2, large: 8 } as const;
38
43
  /**
39
44
  * Per shape, the large run against the small one. Only unexpected statements are judged; a shape
40
45
  * that grew only under an `expectedQueryLoop` is listed beside the verdict with its reason. A shape
41
- * absent at the small size and present at the large one grew from zero.
46
+ * absent at the small size and sent exactly ONCE at the large one is a different PATH, not a loop:
47
+ * the two calls branched on what they were handed. Only that is `unproven`. One sent more than once
48
+ * where it was absent is a loop over rows the small graph held none of (a filter on the third enum
49
+ * value, which two rows never reach) — red, as is a shape that grew from one or more.
42
50
  */
43
51
  export function judgeScale(
44
52
  small: readonly StatementTally[],
@@ -68,7 +76,12 @@ export function judgeScale(
68
76
  a.fingerprint.localeCompare(b.fingerprint);
69
77
  shapes.sort(byName);
70
78
  expected.sort(byName);
71
- return shapes.length === 0
72
- ? { verdict: 'flat', expected }
73
- : { verdict: 'grows', shapes, expected };
79
+ if (shapes.length === 0) return { verdict: 'flat', expected };
80
+ const grown = shapes.filter((shape) => shape.small > 0 || shape.large > 1);
81
+ if (grown.length > 0) return { verdict: 'grows', shapes: grown, expected };
82
+ const appeared = shapes.map((shape) => `${shape.fingerprint} 0 → ${shape.large}`).join(', ');
83
+ return {
84
+ verdict: 'unproven',
85
+ reason: `the call took another path at ${SCALE_SIZES.large} rows than at ${SCALE_SIZES.small} (${appeared}): a branch on the row it was handed, so the counts are not comparable`,
86
+ };
74
87
  }
@@ -15,7 +15,10 @@ export interface SeedColumn {
15
15
 
16
16
  /** What one row lends every column it generates: its place, its canary and its id stream. */
17
17
  export interface ValueContext {
18
- /** 1-based and unique per table, so a value derived from it is unique per table. */
18
+ /**
19
+ * 1-based. For a unique column it continues past the graph written before (`beside`), so a value
20
+ * derived from it is unique per table; for any other column it restarts with each graph.
21
+ */
19
22
  readonly ordinal: number;
20
23
  /** The row's canary: lower-case hex, so it survives a slug or a handle pattern. */
21
24
  readonly canary: string;
package/src/seed-graph.ts CHANGED
@@ -209,6 +209,10 @@ export function seedGraph(
209
209
  // Positions continue past the graph written before this one: a reset factory rebuilt that
210
210
  // graph's first values, and a unique column refused the second copy.
211
211
  const start = besideNext[name] ?? 0;
212
+ // Only a unique column needs the continued position. Every other value is drawn from the row's
213
+ // place in THIS graph, so the scale sweep's 8-row graph opens on the 2-row graph's values and a
214
+ // branch on the handed row takes one path at both sizes (`scale-sweep-branch.test.ts`).
215
+ const uniqueColumns = new Set(allUniques.flat());
212
216
  for (let skipped = 0; factory !== undefined && skipped < start; skipped += 1) factory.build();
213
217
  let ordinal = start;
214
218
  for (const [bucket, tenant] of buckets.entries()) {
@@ -245,7 +249,7 @@ export function seedGraph(
245
249
  valuesInWindow(partitioned.kind, window, ordinal, position),
246
250
  )
247
251
  : candidatesFor(property, column, {
248
- ordinal,
252
+ ordinal: uniqueColumns.has(property) ? ordinal : ordinal - start,
249
253
  canary,
250
254
  position,
251
255
  patterns: patterns.get(property),
@@ -0,0 +1,61 @@
1
+ // The tables one SQL statement reads or writes, read without a parser: each name after `from`,
2
+ // `join`, `update`, `into` or `using`, and each further name of a comma list there (`from orgs o,
3
+ // posts p`). Schema-qualified and double-quoted names answer their last part, lowercased.
4
+
5
+ // Whitespace, `as` and the comma are scanned by index, so no regex here can backtrack
6
+ // (CodeQL js/polynomial-redos).
7
+
8
+ const CLAUSE = /\b(?:from|join|update|into|using)\s+/gi;
9
+ const NAME = /(?:"([^"]+)"|(\w+))(?:\.(?:"([^"]+)"|(\w+)))?/y;
10
+ const WORD = /\w+/y;
11
+ const SPACE = /\s/;
12
+ /** The words that end a list: never read as an alias. */
13
+ const NOT_ALIAS = new Set(
14
+ 'where on set join inner left right full cross natural group order limit offset returning values using union except intersect having window for select default lateral do when then'.split(
15
+ ' ',
16
+ ),
17
+ );
18
+
19
+ function skipSpace(s: string, i: number): number {
20
+ let at = i;
21
+ while (at < s.length && SPACE.test(s.charAt(at))) at++;
22
+ return at;
23
+ }
24
+
25
+ /** The `\w+` at `at`, or null. */
26
+ function wordAt(s: string, at: number): string | null {
27
+ WORD.lastIndex = at;
28
+ return WORD.exec(s)?.[0] ?? null;
29
+ }
30
+
31
+ /** Past an alias — `as p` or bare `p` — after whitespace at `at`; `at` itself when there is none. */
32
+ function skipAlias(s: string, at: number): number {
33
+ const start = skipSpace(s, at);
34
+ if (start === at) return at;
35
+ const word = wordAt(s, start);
36
+ if (word === null) return at;
37
+ if (word.toLowerCase() === 'as') {
38
+ const next = skipSpace(s, start + 2);
39
+ const alias = next > start + 2 ? wordAt(s, next) : null;
40
+ if (alias !== null && !NOT_ALIAS.has(alias.toLowerCase())) return next + alias.length;
41
+ }
42
+ return NOT_ALIAS.has(word.toLowerCase()) ? at : start + word.length;
43
+ }
44
+
45
+ /** Every table `statement` names in a table position, in order, repeats kept. */
46
+ export function statementTables(statement: string): readonly string[] {
47
+ const tables: string[] = [];
48
+ for (const clause of statement.matchAll(CLAUSE)) {
49
+ let at = clause.index + clause[0].length;
50
+ for (;;) {
51
+ NAME.lastIndex = at;
52
+ const name = NAME.exec(statement);
53
+ if (name === null) break;
54
+ tables.push((name[3] ?? name[4] ?? name[1] ?? name[2] ?? '').toLowerCase());
55
+ at = skipSpace(statement, skipAlias(statement, NAME.lastIndex));
56
+ if (statement.charAt(at) !== ',') break;
57
+ at = skipSpace(statement, at + 1);
58
+ }
59
+ }
60
+ return tables;
61
+ }