@ultimat3/testing 31.15.0 → 31.17.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.
@@ -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
+ }
@@ -75,9 +75,12 @@ export async function sizedCall(
75
75
  return { actor, input: seatIn(subject, given, tenant) };
76
76
  }
77
77
 
78
+ /** What the sweeps write on a record: a primitive's, or a route load's (`exercise-route-loads.ts`). */
79
+ type SweptFields = Pick<ExerciseRecord, 'plans' | 'scale' | 'proofMs'>;
80
+
78
81
  /** The records with both sweeps' verdicts and scale time on them, and each sweep's whole time. */
79
- export interface Swept {
80
- readonly records: readonly ExerciseRecord[];
82
+ export interface Swept<R extends SweptFields = ExerciseRecord> {
83
+ readonly records: readonly R[];
81
84
  readonly ms: Pick<ExercisePhaseMs, 'scale' | 'plans'>;
82
85
  }
83
86
 
@@ -99,11 +102,11 @@ const timed = (subject: ScaleSubject, spent: Map<string, number>): ScaleSubject
99
102
  * only: with none, the pass ran on a driver that sends no SQL and there is no plan to read. Each
100
103
  * proof is found under `label(record)`, the name its primitive ran under in the room.
101
104
  */
102
- export async function attachSweeps(
103
- records: readonly ExerciseRecord[],
104
- label: (record: ExerciseRecord) => string,
105
+ export async function attachSweeps<R extends SweptFields>(
106
+ records: readonly R[],
107
+ label: (record: R) => string,
105
108
  options: ScaleSweepOptions,
106
- ): Promise<Swept> {
109
+ ): Promise<Swept<R>> {
107
110
  const spent = new Map<string, number>();
108
111
  let scale: Awaited<ReturnType<typeof scaleSweep>>;
109
112
  const scaleStarted = performance.now();
package/src/exercise.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // `runExercisePass`: every registered action, query and job, run once with no test written. Each
2
2
  // gets its own pair of committed tenants from the pass's one seed graph, an actor its policy allows,
3
- // and the input 39's minimal draw gives with seeded ids bound in; the verdict is 39's loop.
3
+ // and the input 39's minimal draw gives with seeded ids bound in; the verdict is 39's loop. Each
4
+ // route `load` it is handed runs after them, in a pair of its own (`exercise-route-loads.ts`).
4
5
  //
5
6
  // Committed, never rolled back. Around that call the tenant proof runs: the pair's other tenant
6
7
  // calls with the first one's ids before and after it (`tenant-proof.ts`, plan 101, 40). A reached
@@ -36,7 +37,18 @@ import type {
36
37
  Observed,
37
38
  } from './exercise-report';
38
39
  import { openExerciseRoom } from './exercise-report';
40
+ import type { RouteLoadRecord } from './exercise-route-loads';
41
+ import {
42
+ reachedRouteSubjects,
43
+ routeSizedCall,
44
+ runRouteLoads,
45
+ splitRouteRecords,
46
+ sweepLabel,
47
+ } from './exercise-route-loads';
48
+ import type { RouteLoadSubject } from './exercise-route-subjects';
39
49
  import { withExerciseSetup } from './exercise-setup';
50
+ import type { ExerciseStatementCeiling } from './exercise-statement-ceiling';
51
+ import { judgeStatementCeiling } from './exercise-statement-ceiling';
40
52
  import type { Subject } from './exercise-subjects';
41
53
  import { fixedTenant, seatIn, subjectsOf } from './exercise-subjects';
42
54
  import { actorRowsOf, attachSweeps, seated, sizedCall } from './exercise-sweeps';
@@ -63,6 +75,13 @@ export interface ExercisePassOptions {
63
75
  readonly roles: RoleGrants;
64
76
  /** Told once, as the pass returns: how long each phase took, so a slow pass names its slow part. */
65
77
  readonly onPhases?: (ms: ExercisePhaseMs) => void;
78
+ /**
79
+ * Route `load`s run after the primitives (`routeLoadSubjects()`), each in a tenant pair of its
80
+ * own, swept and planned with them. Omitted, and on an `only` run: none.
81
+ */
82
+ readonly routes?: readonly RouteLoadSubject[];
83
+ /** Told once, as the pass returns: each route load's record, the sweeps' proofs on it. */
84
+ readonly onRoutes?: (records: readonly RouteLoadRecord[]) => void;
66
85
  }
67
86
 
68
87
  const isOff = (overrides: ExerciseOverrides | undefined, subject: Subject): boolean => {
@@ -120,6 +139,8 @@ interface Prepared {
120
139
  readonly bindInput: OverrideInput | undefined;
121
140
  /** The actor the pass picked, as the paste line spells it (`exercise-override-line.ts`). */
122
141
  readonly actorHint: OverrideHint['actor'];
142
+ /** The entry's `statements: { max, why }`: the ceiling each call is held to. */
143
+ readonly ceiling: ExerciseStatementCeiling | undefined;
123
144
  }
124
145
 
125
146
  /** Thrown out of 39's loop by a bind that failed: the record is the entry's, never the loop's. */
@@ -213,6 +234,8 @@ async function control(
213
234
  verdict.kind === 'defect' && verdictOf.outcome === 'unreached'
214
235
  ? await defectDetail(verdict.error, verdict.input, subject.input)
215
236
  : undefined;
237
+ // Each segment is one call: the ceiling is per call, never the runs' sum.
238
+ const statementCeiling = judgeStatementCeiling(segments, run.ceiling);
216
239
  const record = {
217
240
  kind,
218
241
  name,
@@ -221,6 +244,7 @@ async function control(
221
244
  ms,
222
245
  ...verdictOf,
223
246
  ...(defect === undefined ? {} : { defect }),
247
+ ...(statementCeiling === undefined ? {} : { statementCeiling }),
224
248
  };
225
249
  return { record, output, input: lastInput };
226
250
  }
@@ -312,6 +336,7 @@ async function exerciseOne(
312
336
  lookups,
313
337
  bindInput,
314
338
  actorHint: actorHintOf(chosen, override),
339
+ ceiling: override === undefined || 'off' in override ? undefined : override.statements,
315
340
  };
316
341
  // A's own first input, A's ids in it: B sends exactly what A legitimately would.
317
342
  const drawn = bindIds(drawInput(sampler, subject.input, 0, 0), lookups[0]);
@@ -383,14 +408,17 @@ export async function runExercisePass(
383
408
  // The app's setup runs inside the seal, before the first row: its routes answer every call.
384
409
  const room = await withExerciseSetup(await openExerciseRoom(), options.overrides?.setup);
385
410
  const live = chosen.filter((subject) => !isOff(options.overrides, subject));
411
+ const routes = options.only === undefined ? (options.routes ?? []) : [];
386
412
  const records: ExerciseRecord[] = [];
413
+ let routeRecords: readonly RouteLoadRecord[] = [];
387
414
  let graph: SeedGraph;
388
415
  const seedStarted = performance.now();
389
416
  let primitivesStarted = seedStarted;
390
417
  try {
391
418
  // Seeded before the first primitive runs: a failure here is the pass's, never one primitive's.
392
419
  graph = await seedPass(options.entities, options.writer, {
393
- primitives: live.length,
420
+ // A route's pair after every primitive's: a run with no routes seeds what it always did.
421
+ primitives: live.length + routes.length,
394
422
  seed: passSeed,
395
423
  ...(options.overrides?.factories === undefined
396
424
  ? {}
@@ -405,6 +433,11 @@ export async function runExercisePass(
405
433
  const pair = tenantPair(graph, at);
406
434
  records.push(await exerciseOne(subject, label(subject), options, pair, view, room, sampler));
407
435
  }
436
+ routeRecords = await runRouteLoads(routes, options, {
437
+ view: (i) => pairGraph(graph, live.length + i),
438
+ tenant: (i) => tenantPair(graph, live.length + i)[0],
439
+ room,
440
+ });
408
441
  } catch (error) {
409
442
  await room[Symbol.asyncDispose]();
410
443
  throw error;
@@ -413,11 +446,14 @@ export async function runExercisePass(
413
446
  const primitives = Math.round(performance.now() - primitivesStarted);
414
447
  // The sweeps: every reached primitive again at two sizes, then every statement planned.
415
448
  const reached = new Set(records.filter((r) => r.outcome === 'reached').map(label));
416
- const swept = await attachSweeps(records, label, {
449
+ const swept = await attachSweeps([...records, ...routeRecords], sweepLabel(label), {
417
450
  // Named by label: the sweeps key their proofs by name, and a shared name is two primitives.
418
- subjects: chosen
419
- .filter((subject) => reached.has(label(subject)))
420
- .map((subject) => ({ ...subject, name: label(subject) })),
451
+ subjects: [
452
+ ...chosen
453
+ .filter((subject) => reached.has(label(subject)))
454
+ .map((subject) => ({ ...subject, name: label(subject) })),
455
+ ...reachedRouteSubjects(routes, routeRecords),
456
+ ],
421
457
  entities: options.entities,
422
458
  // The sized graphs close their cycles as the pass's did: a refused deferred key stays null.
423
459
  writer: deferredMayStayNull(options.writer),
@@ -427,7 +463,9 @@ export async function runExercisePass(
427
463
  factories: options.overrides?.factories,
428
464
  setup: async (subject, sized, tenant, self) => {
429
465
  const full = chosen.find((one) => label(one) === subject.name);
430
- if (full === undefined) return undefined;
466
+ if (full === undefined) {
467
+ return routeSizedCall(routes, options, { label: subject.name, graph: sized, tenant });
468
+ }
431
469
  const call = await sizedCall(full, options, sampler, { graph: sized, tenant, self });
432
470
  // Before the sweep's room opens: the sized tenant's actor is a user too.
433
471
  if (call !== undefined) await seatActorUsers([call.actor]);
@@ -435,5 +473,7 @@ export async function runExercisePass(
435
473
  },
436
474
  });
437
475
  options.onPhases?.({ seed, primitives, ...swept.ms });
438
- return swept.records;
476
+ const split = splitRouteRecords(swept.records);
477
+ options.onRoutes?.(split.routes);
478
+ return split.primitives;
439
479
  }
@@ -103,7 +103,7 @@ const RENEW_MS = 1;
103
103
  * and slept its whole `rate` interval in WALL time. Moving the instant is the wait now, and it is
104
104
  * a move the frozen scheduler hears, so the renewals see exactly the time the throttle spent.
105
105
  */
106
- const PRELOAD_CLOCK: FrozenClock = Object.freeze({
106
+ export const PRELOAD_CLOCK: FrozenClock = Object.freeze({
107
107
  now: frozenNow,
108
108
  monotonic: () => frozenNow().getTime(),
109
109
  advance: (ms: number): void => {
package/src/index.ts CHANGED
@@ -152,7 +152,21 @@ export type {
152
152
  TenantLeg,
153
153
  TenantProof,
154
154
  } from './exercise-report';
155
+ export type { RouteLoadRecord } from './exercise-route-loads';
156
+ export type { RouteLoadSubject } from './exercise-route-subjects';
157
+ export { routeLoadSubjects } from './exercise-route-subjects';
155
158
  export type { ExerciseSetup, ExerciseSetupHandle } from './exercise-setup';
159
+ export type {
160
+ CeilingShape,
161
+ ExerciseStatementCeiling,
162
+ StatementCeilingFinding,
163
+ StatementCeilingProof,
164
+ } from './exercise-statement-ceiling';
165
+ export {
166
+ judgeStatementCeiling,
167
+ STATEMENTS_MAX,
168
+ statementCeilingFindings,
169
+ } from './exercise-statement-ceiling';
156
170
  export { defineFactory } from './factories';
157
171
  export type { AnyFactory, Factory, FactoryExtension, FactoryOptions } from './factory-api';
158
172
  export type { BelongsToOptions, HasManyOptions } from './factory-associations';
@@ -365,6 +379,9 @@ export type { LoggedRequest } from './request-log';
365
379
  export { reusableDatabase } from './reusable-database';
366
380
  export type { ScaleProof, ScaleShape, StatementTally } from './scale-sweep';
367
381
  export { judgeScale, SCALE_SIZES } from './scale-sweep';
382
+ export type { ScaleSeedFinding } from './scale-sweep-findings';
383
+ export { scaleSeedFindings } from './scale-sweep-findings';
384
+ export type { ScaleSeedFailure } from './scale-sweep-seed';
368
385
  export type { NetworkSnapshot, NetworkState } from './sealed-network';
369
386
  // `setNetworkState` is deliberately not here: it is the offline gate's one writer, and a test that
370
387
  // called it directly would bypass the `network` fixture's disposal and leave the whole process
@@ -404,6 +421,8 @@ export type { EntitySeedWriterOptions, SeedWriterTarget } from './seed-writer';
404
421
  export { entitySeedWriter } from './seed-writer';
405
422
  export type { SharedExamples } from './shared-examples';
406
423
  export { behavesLike, sharedExamples } from './shared-examples';
424
+ // One SQL table scan for the sweep's lost-table reader and `x doctor`'s raw tenant SQL probe.
425
+ export { statementTables } from './sql-tables';
407
426
  // Test doubles: `stub(primitive)` replaces an action's, an llm()'s or a job's body, `swapAdapter`
408
427
  // an adapter port; both are put back after the test that made them (`test-scope.ts`).
409
428
  export { stub } from './stub';
@@ -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
+ }