@ultimat3/testing 30.7.0 → 30.9.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/src/exercise.ts CHANGED
@@ -5,30 +5,27 @@
5
5
  // Committed, never rolled back. Around that call the tenant proof runs: the pair's other tenant
6
6
  // calls with the first one's ids before and after it (`tenant-proof.ts`, plan 101, 40). A reached
7
7
  // job is then killed at every step boundary (`exercise-crash.ts`).
8
+ //
9
+ // Each record is its primitive's alone: an entry's input that throws is that primitive unreached,
10
+ // what the input sent is never the call's, and a name two kinds share has an entry per kind.
8
11
 
9
12
  import type { Actor, ExerciseAttempt, ExerciseVerdict } from '@ultimat3/core';
10
- import { isUltimateError, renderThrowable, runExercise } from '@ultimat3/core';
11
- import { registeredJobs } from '@ultimat3/jobs';
13
+ import { runExercise } from '@ultimat3/core';
14
+ import { LIVE_STATES, registeredJobs } from '@ultimat3/jobs';
12
15
  import type { ExerciseOverride, ExerciseOverrides } from './define-exercise';
13
- import { assertOverridesKnown, unknownDeclaration } from './define-exercise';
16
+ import { assertOverridesKnown, overrideFor, unknownDeclaration } from './define-exercise';
14
17
  import type { RoleGrants } from './exercise-actor';
15
18
  import { chooseActor } from './exercise-actor';
16
19
  import { seatActorUsers } from './exercise-actor-user';
17
20
  import { proveCrash } from './exercise-crash';
18
21
  import { defectDetail } from './exercise-defect';
19
- import { driftOverrideLine } from './exercise-drift-hint';
20
22
  import type { IdLookup, Sampler } from './exercise-input';
21
- import {
22
- bindIds,
23
- drawInput,
24
- idStem,
25
- loadSampler,
26
- namesActorEntity,
27
- seededIds,
28
- } from './exercise-input';
23
+ import { bindIds, drawInput, loadSampler, namesActorEntity, seededIds } from './exercise-input';
29
24
  import { ambientJobRows } from './exercise-job-run';
25
+ import { judged, labelFor } from './exercise-judge';
26
+ import { mergeObserved } from './exercise-observed';
30
27
  import type { OverrideInput } from './exercise-override-input';
31
- import { overrideInput } from './exercise-override-input';
28
+ import { inputThrew, overrideInput } from './exercise-override-input';
32
29
  import type {
33
30
  EffectPayload,
34
31
  ExerciseEffect,
@@ -37,12 +34,11 @@ import type {
37
34
  ExerciseRoom,
38
35
  Observed,
39
36
  } from './exercise-report';
40
- import { openExerciseRoom, overrideLine } from './exercise-report';
37
+ import { openExerciseRoom } from './exercise-report';
41
38
  import { withExerciseSetup } from './exercise-setup';
42
39
  import type { Subject } from './exercise-subjects';
43
40
  import { fixedTenant, seatIn, subjectsOf } from './exercise-subjects';
44
41
  import { actorRowsOf, attachSweeps, seated, sizedCall } from './exercise-sweeps';
45
- import type { RunJobs } from './fixture-jobs';
46
42
  import { testJobs } from './fixture-jobs';
47
43
  import { deferredMayStayNull, pairGraph, seedPass, tenantPair } from './seed-graph-pass';
48
44
  import type { SeedGraph, SeedWriter } from './seed-graph-plan';
@@ -68,31 +64,32 @@ export interface ExercisePassOptions {
68
64
  readonly onPhases?: (ms: ExercisePhaseMs) => void;
69
65
  }
70
66
 
71
- const isOff = (overrides: ExerciseOverrides | undefined, name: string): boolean => {
72
- const override = overrides?.entries.get(name);
67
+ const isOff = (overrides: ExerciseOverrides | undefined, subject: Subject): boolean => {
68
+ const override = overrideFor(overrides, subject.kind, subject.name);
73
69
  return override !== undefined && 'off' in override;
74
70
  };
75
71
 
76
- const codeOf = (error: unknown): string | undefined => {
77
- if (isUltimateError(error)) return error.code;
78
- return typeof error === 'string' ? /^(X_[A-Z0-9_]+)/.exec(error)?.[1] : undefined;
79
- };
80
-
81
- const reasonOf = (error: unknown): string =>
82
- isUltimateError(error) ? error.cause : typeof error === 'string' ? error : renderThrowable(error);
72
+ /** The ids of every row the call's queue holds now: what an attempt adds is the call's. */
73
+ const queuedIds = async (): Promise<ReadonlySet<string>> =>
74
+ new Set((await ambientJobRows()).map((record) => record.id));
83
75
 
84
76
  /**
85
- * Jobs the primitive queued, its own job excepted. Never run: a job's children are left queued as
86
- * an action's are (`exercise-job-run.ts`), so their statements are theirs, never this record's.
77
+ * Jobs the primitive queued — rows an ATTEMPT added (`mine`), still live — its own job excepted.
78
+ * Never run: a job's children are left queued as an action's are (`exercise-job-run.ts`). A row
79
+ * the override's input added between calls is on the same queue, so the call can find it, and is
80
+ * not in `mine`: the input's enqueue is never the primitive's.
87
81
  */
88
- async function enqueued(subject: Subject, jobs: RunJobs) {
89
- const effects: ExerciseEffect[] = [];
90
- for (const handle of registeredJobs()) {
91
- if (subject.kind === 'job' && handle.name === subject.name) continue;
92
- const count = await jobs.depth(handle);
93
- if (count > 0) effects.push({ kind: 'enqueue', job: handle.name, count });
82
+ async function enqueued(subject: Subject, mine: ReadonlySet<string>) {
83
+ const counts = new Map<string, number>();
84
+ for (const record of await ambientJobRows()) {
85
+ if (!mine.has(record.id) || !LIVE_STATES.has(record.state)) continue;
86
+ if (subject.kind === 'job' && record.name === subject.name) continue;
87
+ counts.set(record.name, (counts.get(record.name) ?? 0) + 1);
94
88
  }
95
- return effects;
89
+ const order = registeredJobs().map((handle) => handle.name);
90
+ return [...counts]
91
+ .sort(([a], [b]) => order.indexOf(a) - order.indexOf(b))
92
+ .map(([job, count]): ExerciseEffect => ({ kind: 'enqueue', job, count }));
96
93
  }
97
94
 
98
95
  /**
@@ -108,47 +105,11 @@ async function queuedPayloads(subject: Subject): Promise<readonly EffectPayload[
108
105
  }));
109
106
  }
110
107
 
111
- interface Run {
112
- readonly verdict: ExerciseVerdict;
113
- readonly answered: boolean;
114
- readonly lastError: unknown;
115
- readonly lastInput: unknown;
116
- }
117
-
118
- function judged(subject: Subject, run: Run, observed: Observed, sampler: Sampler) {
119
- const idFields = (input: unknown): readonly string[] =>
120
- typeof input === 'object' && input !== null
121
- ? Object.keys(input).filter((key) => idStem(key) !== undefined)
122
- : [];
123
- const unreached = (code: string | undefined, reason: string) => ({
124
- outcome: 'unreached' as const,
125
- ...(code === undefined ? {} : { code }),
126
- reason,
127
- override: overrideLine(subject.name, idFields(run.lastInput)),
128
- });
129
- if (observed.refusedHosts.length > 0) {
130
- // A call out is a refusal whatever the handler made of it: sealed, so never sent.
131
- const hosts = [...new Set(observed.refusedHosts)].join(', ');
132
- return unreached('X_TEST_NETWORK_SEALED', `called out to ${hosts}: sealed, never sent`);
133
- }
134
- if (run.verdict.kind === 'pass' && run.answered) return { outcome: 'reached' as const };
135
- if (run.verdict.kind === 'drift') {
136
- // The field no draw can fill, named: `...drawn` alone told the author nothing to write.
137
- const fields = idFields(run.lastInput);
138
- return {
139
- ...unreached('X_CONTRACT_DRIFT', 'its input schema refused every generated value'),
140
- override: driftOverrideLine(subject.name, subject.input, sampler, fields),
141
- };
142
- }
143
- if (run.verdict.kind === 'defect') {
144
- return unreached(codeOf(run.verdict.error) ?? 'X_CONTRACT_DEFECT', run.verdict.defect);
145
- }
146
- return unreached(codeOf(run.lastError), reasonOf(run.lastError));
147
- }
148
-
149
108
  /** Everything one primitive's calls share: who acts in each tenant, and how ids are bound. */
150
109
  interface Prepared {
151
110
  readonly subject: Subject;
111
+ /** The entry key and room label: `labelFor`'s. */
112
+ readonly key: string;
152
113
  readonly options: ExercisePassOptions;
153
114
  readonly tenant: string;
154
115
  readonly actor: Actor | null;
@@ -158,13 +119,21 @@ interface Prepared {
158
119
  readonly bindInput: OverrideInput | undefined;
159
120
  }
160
121
 
161
- /** A's positive control: 39's loop, as the pass has always run it. */
122
+ /** Thrown out of 39's loop by a bind that failed: the record is the entry's, never the loop's. */
123
+ class BindThrew {
124
+ constructor(readonly error: unknown) {}
125
+ }
126
+
127
+ /**
128
+ * A's positive control: 39's loop, as the pass has always run it. The room records each CALL
129
+ * alone: an override's input runs between calls, and what it sends is never this primitive's.
130
+ */
162
131
  async function control(
163
132
  run: Prepared,
164
133
  room: ExerciseRoom,
165
134
  sampler: Sampler,
166
135
  ): Promise<{ readonly record: ExerciseRecord; readonly output: unknown; readonly input: unknown }> {
167
- const { subject, actor, tenant, declaredRuns, lookups, bindInput } = run;
136
+ const { subject, key, actor, tenant, declaredRuns, lookups, bindInput } = run;
168
137
  const { kind, name } = subject;
169
138
  let binds = 0;
170
139
  await using jobs = await testJobs();
@@ -172,43 +141,71 @@ async function control(
172
141
  let lastError: unknown;
173
142
  let lastInput: unknown;
174
143
  let output: unknown;
175
- room.begin(name);
144
+ const segments: Observed[] = [];
145
+ const mine = new Set<string>();
176
146
  const started = performance.now();
177
- const verdict = await runExercise({
178
- name,
179
- runs: run.runs,
180
- stoppedLabel: 'stopped before the call answered',
181
- // The minimal draw on every run the pass adds; 39's seeded draw only on runs an override asks.
182
- draw: (at, n) => drawInput(sampler, subject.input, at, declaredRuns === undefined ? 0 : n),
183
- bind: async (drawn) => {
184
- const bound = bindIds(drawn, lookups[binds++ === 0 ? 0 : 1]);
185
- const given = bindInput === undefined ? bound : await bindInput(bound, actor);
186
- lastInput = seatIn(subject, given, tenant);
187
- return lastInput;
188
- },
189
- accepts: async (input) =>
190
- (await subject.input['~standard'].validate(input)).issues === undefined,
191
- attempt: async (input): Promise<ExerciseAttempt> => {
192
- try {
193
- const answer = await subject.call(input, actor, tenant, jobs);
194
- if ('failure' in answer) {
195
- lastError = answer.failure;
196
- return { ok: false, reached: true, error: answer.failure };
147
+ let verdict: ExerciseVerdict;
148
+ try {
149
+ verdict = await runExercise({
150
+ name,
151
+ runs: run.runs,
152
+ stoppedLabel: 'stopped before the call answered',
153
+ // The minimal draw on every run the pass adds; 39's seeded draw only on runs an override asks.
154
+ draw: (at, n) => drawInput(sampler, subject.input, at, declaredRuns === undefined ? 0 : n),
155
+ bind: async (drawn) => {
156
+ const bound = bindIds(drawn, lookups[binds++ === 0 ? 0 : 1]);
157
+ try {
158
+ // On the call's own queue: a job the input enqueues is there when the call looks it up.
159
+ const given =
160
+ bindInput === undefined ? bound : await bindInput(bound, actor, { onCallQueue: true });
161
+ lastInput = seatIn(subject, given, tenant);
162
+ } catch (error) {
163
+ throw new BindThrew(error);
197
164
  }
198
- answered = true;
199
- output = answer.output;
200
- return { ok: true, reached: true };
201
- } catch (error) {
202
- lastError = error;
203
- return { ok: false, reached: false, error };
204
- }
205
- },
206
- statusOf: (await import('@ultimat3/http')).statusFor,
207
- });
165
+ return lastInput;
166
+ },
167
+ accepts: async (input) =>
168
+ (await subject.input['~standard'].validate(input)).issues === undefined,
169
+ attempt: async (input): Promise<ExerciseAttempt> => {
170
+ const before = await queuedIds();
171
+ room.begin(key);
172
+ try {
173
+ const answer = await subject.call(input, actor, tenant, jobs);
174
+ if ('failure' in answer) {
175
+ lastError = answer.failure;
176
+ return { ok: false, reached: true, error: answer.failure };
177
+ }
178
+ answered = true;
179
+ output = answer.output;
180
+ return { ok: true, reached: true };
181
+ } catch (error) {
182
+ lastError = error;
183
+ return { ok: false, reached: false, error };
184
+ } finally {
185
+ segments.push(room.end());
186
+ for (const id of await queuedIds()) if (!before.has(id)) mine.add(id);
187
+ }
188
+ },
189
+ statusOf: (await import('@ultimat3/http')).statusFor,
190
+ });
191
+ } catch (error) {
192
+ if (!(error instanceof BindThrew)) throw error;
193
+ const observed = mergeObserved(segments);
194
+ const record = {
195
+ kind,
196
+ name,
197
+ statements: observed.statements,
198
+ effects: observed.effects,
199
+ ms: Math.round(performance.now() - started),
200
+ ...inputThrew(name, key, error.error),
201
+ };
202
+ return { record, output, input: lastInput };
203
+ }
208
204
  const ms = Math.round(performance.now() - started);
209
- const observed = room.end();
210
- const effects = [...observed.effects, ...(await enqueued(subject, jobs))];
211
- const verdictOf = judged(subject, { verdict, answered, lastError, lastInput }, observed, sampler);
205
+ const observed = mergeObserved(segments);
206
+ const effects = [...observed.effects, ...(await enqueued(subject, mine))];
207
+ const outcome = { verdict, answered, lastError, lastInput };
208
+ const verdictOf = judged(subject, key, outcome, observed, sampler);
212
209
  // A 5xx's cause, statement and fields: the code alone sent the author to reproduce it by hand.
213
210
  const defect =
214
211
  verdict.kind === 'defect' && verdictOf.outcome === 'unreached'
@@ -229,13 +226,14 @@ async function control(
229
226
  /** One B leg: B's actor, A's ids, a queue of its own. What it answered and every effect it had. */
230
227
  async function attack(
231
228
  subject: Subject,
229
+ key: string,
232
230
  input: unknown,
233
231
  actor: Actor | null,
234
232
  tenant: string,
235
233
  room: ExerciseRoom,
236
234
  ): Promise<LegAnswer> {
237
235
  await using jobs = await testJobs();
238
- room.begin(subject.name);
236
+ room.begin(key);
239
237
  let output: unknown;
240
238
  // A job's org is re-seated in B's: B cannot enqueue a payload naming A (refused at the enqueue,
241
239
  // which proves nothing), so the attack that matters is a job of B's carrying A's ids.
@@ -261,6 +259,7 @@ async function attack(
261
259
 
262
260
  async function exerciseOne(
263
261
  subject: Subject,
262
+ key: string,
264
263
  options: ExercisePassOptions,
265
264
  [tenant, other]: readonly [string, string],
266
265
  graph: SeedGraph,
@@ -268,7 +267,7 @@ async function exerciseOne(
268
267
  sampler: Sampler,
269
268
  ): Promise<ExerciseRecord> {
270
269
  const { kind, name } = subject;
271
- const override: ExerciseOverride | undefined = options.overrides?.entries.get(name);
270
+ const override: ExerciseOverride | undefined = overrideFor(options.overrides, kind, name);
272
271
  const none = { kind, name, statements: 0, effects: [], ms: 0 };
273
272
  if (override !== undefined && 'off' in override) {
274
273
  return { ...none, outcome: 'off', reason: override.off.trim() };
@@ -301,6 +300,7 @@ async function exerciseOne(
301
300
  ] as const;
302
301
  const run: Prepared = {
303
302
  subject,
303
+ key,
304
304
  options,
305
305
  tenant,
306
306
  actor,
@@ -311,7 +311,13 @@ async function exerciseOne(
311
311
  };
312
312
  // A's own first input, A's ids in it: B sends exactly what A legitimately would.
313
313
  const drawn = bindIds(drawInput(sampler, subject.input, 0, 0), lookups[0]);
314
- const given = bindInput === undefined ? drawn : await bindInput(drawn, actor);
314
+ let given: unknown;
315
+ try {
316
+ given = bindInput === undefined ? drawn : await bindInput(drawn, actor);
317
+ } catch (error) {
318
+ const threw = inputThrew(name, key, error);
319
+ return { ...none, ...threw, tenant: { verdict: 'unproven', reason: threw.reason } };
320
+ }
315
321
  const seat = subject.seat?.(given, tenant);
316
322
  if (seat?.kind === 'fixed') {
317
323
  const fixed = fixedTenant(name, seat.declared);
@@ -332,7 +338,7 @@ async function exerciseOne(
332
338
  read: kind === 'query',
333
339
  sweep: kind === 'job',
334
340
  tenantless: seat?.kind === 'none',
335
- attack: () => attack(subject, input, intruder, other, room),
341
+ attack: () => attack(subject, key, input, intruder, other, room),
336
342
  control: async () => {
337
343
  const done = await control(run, room, sampler);
338
344
  reachedWith = done.input;
@@ -355,9 +361,14 @@ async function exerciseOne(
355
361
  export async function runExercisePass(
356
362
  options: ExercisePassOptions,
357
363
  ): Promise<readonly ExerciseRecord[]> {
358
- const subjects = await subjectsOf();
364
+ // Each call's request is its entry's, read by kind: an action's cookies are never its job twin's.
365
+ const subjects = await subjectsOf((kind, name) => {
366
+ const entry = overrideFor(options.overrides, kind, name);
367
+ return entry === undefined || 'off' in entry ? undefined : entry.request;
368
+ });
359
369
  const known = new Set(subjects.map((subject) => subject.name));
360
- assertOverridesKnown(options.overrides, known);
370
+ assertOverridesKnown(options.overrides, subjects);
371
+ const label = labelFor(subjects);
361
372
  if (options.only !== undefined && !known.has(options.only)) {
362
373
  throw unknownDeclaration([options.only], known, 'x exercise');
363
374
  }
@@ -367,7 +378,7 @@ export async function runExercisePass(
367
378
  const passSeed = options.seed ?? (crypto.getRandomValues(new Uint32Array(1))[0] as number);
368
379
  // The app's setup runs inside the seal, before the first row: its routes answer every call.
369
380
  const room = await withExerciseSetup(await openExerciseRoom(), options.overrides?.setup);
370
- const live = chosen.filter((subject) => !isOff(options.overrides, subject.name));
381
+ const live = chosen.filter((subject) => !isOff(options.overrides, subject));
371
382
  const records: ExerciseRecord[] = [];
372
383
  let graph: SeedGraph;
373
384
  const seedStarted = performance.now();
@@ -387,7 +398,8 @@ export async function runExercisePass(
387
398
  const index = live.indexOf(subject);
388
399
  const at = Math.max(0, index);
389
400
  const view = pairGraph(graph, at);
390
- records.push(await exerciseOne(subject, options, tenantPair(graph, at), view, room, sampler));
401
+ const pair = tenantPair(graph, at);
402
+ records.push(await exerciseOne(subject, label(subject), options, pair, view, room, sampler));
391
403
  }
392
404
  } catch (error) {
393
405
  await room[Symbol.asyncDispose]();
@@ -396,9 +408,12 @@ export async function runExercisePass(
396
408
  const seed = Math.round(primitivesStarted - seedStarted);
397
409
  const primitives = Math.round(performance.now() - primitivesStarted);
398
410
  // The sweeps: every reached primitive again at two sizes, then every statement planned.
399
- const reached = new Set(records.filter((r) => r.outcome === 'reached').map((r) => r.name));
400
- const swept = await attachSweeps(records, {
401
- subjects: chosen.filter((subject) => reached.has(subject.name)),
411
+ const reached = new Set(records.filter((r) => r.outcome === 'reached').map(label));
412
+ const swept = await attachSweeps(records, label, {
413
+ // Named by label: the sweeps key their proofs by name, and a shared name is two primitives.
414
+ subjects: chosen
415
+ .filter((subject) => reached.has(label(subject)))
416
+ .map((subject) => ({ ...subject, name: label(subject) })),
402
417
  entities: options.entities,
403
418
  // The sized graphs close their cycles as the pass's did: a refused deferred key stays null.
404
419
  writer: deferredMayStayNull(options.writer),
@@ -407,7 +422,7 @@ export async function runExercisePass(
407
422
  room,
408
423
  factories: options.overrides?.factories,
409
424
  setup: async (subject, sized, tenant, self) => {
410
- const full = chosen.find((one) => one.name === subject.name);
425
+ const full = chosen.find((one) => label(one) === subject.name);
411
426
  if (full === undefined) return undefined;
412
427
  const call = await sizedCall(full, options, sampler, { graph: sized, tenant, self });
413
428
  // Before the sweep's room opens: the sized tenant's actor is a user too.
@@ -4,9 +4,9 @@
4
4
  // edge. A structural seam keeps the direction honest and survives the bundler changing underneath.
5
5
 
6
6
  import { basename, join } from 'node:path';
7
- import { islandMountMissing, islandNotBuilt } from './errors';
8
7
  import { onFileBoundary } from './file-boundary';
9
8
  import { createIslandDocument, FakeElement, handlerFor, parseHtml } from './island-dom';
9
+ import { islandMountMissing, islandNotBuilt } from './island-errors';
10
10
  import { installGlobals } from './island-globals';
11
11
  import type { ResizeInput } from './island-observers';
12
12
  import { deliverResize } from './island-observers';
@@ -5,7 +5,7 @@
5
5
  // holding a connection — so the trace this returns is keyed by step name and counts executions.
6
6
  // Nothing here polls or sleeps: a job becomes due only because `clock.advance()` said so.
7
7
 
8
- import type { Actor, Ctx } from '@ultimat3/core';
8
+ import type { Actor, Ctx, FrozenClock } from '@ultimat3/core';
9
9
  import { assert, ctxOf } from '@ultimat3/core';
10
10
  import type {
11
11
  AnyJobHandle,
@@ -16,7 +16,7 @@ import type {
16
16
  JobRecord,
17
17
  StepStatus,
18
18
  } from '@ultimat3/jobs';
19
- import { frozenNow } from './determinism';
19
+ import { advanceClock, frozenNow, setFrozenClock } from './determinism';
20
20
  import { frozenScheduler } from './frozen-scheduler';
21
21
 
22
22
  export interface StepTally {
@@ -92,6 +92,23 @@ const CLAIM_LIMIT = 64;
92
92
  * reads the same clock, so a renewal can never report a lease lost that `clock.advance()` did not.
93
93
  */
94
94
  const RENEW_MS = 1;
95
+ /**
96
+ * The clock a body runs on: the preload's frozen instant, as a `FrozenClock`. `systemClock` read
97
+ * the frozen `Date` too, but had no `advance` — so a `backfill()` pacer saw every batch as instant
98
+ * and slept its whole `rate` interval in WALL time. Moving the instant is the wait now, and it is
99
+ * a move the frozen scheduler hears, so the renewals see exactly the time the throttle spent.
100
+ */
101
+ const PRELOAD_CLOCK: FrozenClock = Object.freeze({
102
+ now: frozenNow,
103
+ monotonic: () => frozenNow().getTime(),
104
+ advance: (ms: number): void => {
105
+ advanceClock(ms);
106
+ },
107
+ set: (at: Date | number | string): void => {
108
+ setFrozenClock(at instanceof Date ? at.getTime() : at);
109
+ },
110
+ });
111
+
95
112
  /** A drain that has not settled in this many rounds is a runaway, not a slow queue. */
96
113
  const MAX_ROUNDS = 100;
97
114
  const LIVE_STATES: ReadonlySet<string> = new Set(['ready', 'delayed', 'running', 'suspended']);
@@ -125,7 +142,7 @@ export async function testJobs(): Promise<RunJobs> {
125
142
  // the process's own handed back with the driver.
126
143
  const previousBus = jobs.eventBus();
127
144
  jobs.setEventBus(jobs.memoryEventBus());
128
- const anonymousWorker = ctxOf({ role: 'worker' });
145
+ const anonymousWorker = ctxOf({ role: 'worker', clock: PRELOAD_CLOCK });
129
146
  const renewals = frozenScheduler();
130
147
 
131
148
  const introspect = (): NonNullable<JobDriver['introspect']> => {
@@ -200,7 +217,9 @@ export async function testJobs(): Promise<RunJobs> {
200
217
  const history: JobExecution[] = [];
201
218
 
202
219
  const ctxFor = (options: JobDrainAs): Ctx =>
203
- options.actor === undefined ? anonymousWorker : ctxOf({ role: 'worker', actor: options.actor });
220
+ options.actor === undefined
221
+ ? anonymousWorker
222
+ : ctxOf({ role: 'worker', actor: options.actor, clock: PRELOAD_CLOCK });
204
223
  const traced = (): JobRunTrace => ({ executions: [...history], steps: tallyOf(history) });
205
224
 
206
225
  const tick = async (options: JobDrainAs = {}): Promise<JobRunTrace> => {
@@ -0,0 +1,82 @@
1
+ // The two refusals `mountIsland` gives before any island code runs: the file the test named was
2
+ // not built, or its chunk exports no `mount`. Codes registered with the rest in `errors.ts`.
3
+
4
+ import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
5
+
6
+ /** Neither path is controlled by the framework: both arrive from the test's own call. */
7
+ const ISLAND_PLACEHOLDER = '<the island path the cause names>';
8
+
9
+ /**
10
+ * The builder produced no chunk for the file the test named. Listing what it DID build is the
11
+ * whole value: a path relative to the test file instead of to the app root, a typo, and an island
12
+ * outside the discovery glob are one symptom and three different edits, and only the list tells
13
+ * them apart. An empty list is its own answer — the glob found nothing at all under this root.
14
+ */
15
+ export class IslandNotBuiltError extends UltimateError {
16
+ constructor(input: { file: string; root: string; built: readonly string[] }) {
17
+ const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
18
+ super({
19
+ code: 'X_TEST_ISLAND_NOT_BUILT',
20
+ cause:
21
+ input.built.length === 0
22
+ ? `no island was built under ${renderCauseValue(input.root)}, so ${renderCauseValue(input.file)} cannot be mounted`
23
+ : `${renderCauseValue(input.file)} is not in the bundle built from ${renderCauseValue(input.root)}; it built ${input.built.join(', ')}`,
24
+ fix:
25
+ input.built.length === 0
26
+ ? 'x g island <name> --at apps/web/site — then set root to the directory holding apps/'
27
+ : `mountIsland({ build, root, file: ${renderFixLiteral(input.built[0], ISLAND_PLACEHOLDER)} }) — the path is app-root-relative, not relative to the test, and ${file} is not one of them`,
28
+ });
29
+ }
30
+ }
31
+
32
+ export const islandNotBuilt = (
33
+ file: string,
34
+ root: string,
35
+ built: readonly string[],
36
+ ): UltimateError => new IslandNotBuiltError({ file, root, built });
37
+
38
+ /** A name that can be written as a JSX tag. `export default` and `export { x as 'a b' }` are both
39
+ * legal ES and neither can — a paste emitting one is a syntax error in the reader's own file. */
40
+ const JSX_NAME = /^[A-Za-z_$][\w$]*$/;
41
+
42
+ /**
43
+ * The export the paste renders. A component first — an initial capital that is not the whole name,
44
+ * which is what separates `Counter` from a `PROPS` constant — and any other usable identifier
45
+ * after it, because a lowercase component still compiles and beats a name the reader must invent.
46
+ */
47
+ const componentOf = (exported: readonly string[]): string | undefined => {
48
+ const usable = exported.filter((name) => JSX_NAME.test(name) && name !== 'default');
49
+ return usable.find((name) => /^[A-Z]/.test(name) && name !== name.toUpperCase()) ?? usable[0];
50
+ };
51
+
52
+ /**
53
+ * The chunk built and imported, and exports no `mount`. Distinct from a build failure: the island
54
+ * compiles, ships and is served — the hydration runtime calls `m.mount(el, props)` and the browser
55
+ * throws on a page that passed every gate. Naming the exports it DOES have is what separates a
56
+ * renamed export from a file that exports only its component.
57
+ *
58
+ * The paste is built from THOSE exports rather than from a sketch. It read
59
+ * `render(() => <Island {...props} />, el)` with `props: Props` until 2026-08-21, and none of
60
+ * `Island`, `Props` or `render` exists in the file the reader was told to paste it into — three
61
+ * compile errors handed out as the remedy for one. Two of them the error already knew the answer
62
+ * to, from its own cause; the third is an import, so the import is in the line.
63
+ */
64
+ export class IslandMountMissingError extends UltimateError {
65
+ constructor(input: { file: string; exported: readonly string[] }) {
66
+ const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
67
+ const component = componentOf(input.exported);
68
+ super({
69
+ code: 'X_TEST_ISLAND_NO_MOUNT',
70
+ cause: `the chunk built from ${renderCauseValue(input.file)} exports ${
71
+ input.exported.length === 0 ? 'nothing' : input.exported.join(', ')
72
+ } — the hydration runtime calls m.mount(el, props)`,
73
+ fix:
74
+ component === undefined
75
+ ? `${file} exports nothing a mount could render — x g island <name> --at apps/web/site writes an island whose mount() is already there, and its shape is the one to copy`
76
+ : `in ${file} add: import { render } from 'solid-js/web'; export function mount(el: HTMLElement, props: Parameters<typeof ${component}>[0]): () => void { el.textContent = ''; return render(() => <${component} {...props} />, el); }`,
77
+ });
78
+ }
79
+ }
80
+
81
+ export const islandMountMissing = (file: string, exported: readonly string[]): UltimateError =>
82
+ new IslandMountMissingError({ file, exported });
@@ -21,7 +21,7 @@ const EQUALITY = /(?<![<>!])=(?!>)/;
21
21
  const IS_NULL = /\bIS\s+NULL\b/i;
22
22
 
23
23
  /** The parts of `text` between `word`s that stand outside every parenthesis and literal. */
24
- function splitTop(text: string, word: 'AND' | 'OR'): string[] {
24
+ export function splitTop(text: string, word: 'AND' | 'OR'): string[] {
25
25
  const parts: string[] = [];
26
26
  let depth = 0;
27
27
  let quoted = false;
@@ -43,7 +43,7 @@ function splitTop(text: string, word: 'AND' | 'OR'): string[] {
43
43
  }
44
44
 
45
45
  /** `((a = $1))` → `a = $1`: parentheses that wrap the whole text, and only those. */
46
- function unwrap(text: string): string {
46
+ export function unwrap(text: string): string {
47
47
  let rest = text.trim();
48
48
  for (;;) {
49
49
  if (!rest.startsWith('(') || !rest.endsWith(')')) return rest;