@ultimat3/testing 31.0.0 → 31.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.0.0",
3
+ "version": "31.1.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.0.0",
51
- "@ultimat3/ai": "31.0.0",
52
- "@ultimat3/auth": "31.0.0",
53
- "@ultimat3/cache": "31.0.0",
54
- "@ultimat3/core": "31.0.0",
55
- "@ultimat3/db": "31.0.0",
56
- "@ultimat3/entity": "31.0.0",
57
- "@ultimat3/http": "31.0.0",
58
- "@ultimat3/i18n": "31.0.0",
59
- "@ultimat3/jobs": "31.0.0",
60
- "@ultimat3/mail": "31.0.0",
61
- "@ultimat3/notify": "31.0.0",
62
- "@ultimat3/policy": "31.0.0",
63
- "@ultimat3/pwa": "31.0.0",
64
- "@ultimat3/query": "31.0.0",
65
- "@ultimat3/realtime": "31.0.0",
66
- "@ultimat3/render": "31.0.0",
67
- "@ultimat3/schema": "31.0.0",
68
- "@ultimat3/scraping": "31.0.0",
69
- "@ultimat3/seo": "31.0.0",
70
- "@ultimat3/time": "31.0.0"
50
+ "@ultimat3/action": "31.1.0",
51
+ "@ultimat3/ai": "31.1.0",
52
+ "@ultimat3/auth": "31.1.0",
53
+ "@ultimat3/cache": "31.1.0",
54
+ "@ultimat3/core": "31.1.0",
55
+ "@ultimat3/db": "31.1.0",
56
+ "@ultimat3/entity": "31.1.0",
57
+ "@ultimat3/http": "31.1.0",
58
+ "@ultimat3/i18n": "31.1.0",
59
+ "@ultimat3/jobs": "31.1.0",
60
+ "@ultimat3/mail": "31.1.0",
61
+ "@ultimat3/notify": "31.1.0",
62
+ "@ultimat3/policy": "31.1.0",
63
+ "@ultimat3/pwa": "31.1.0",
64
+ "@ultimat3/query": "31.1.0",
65
+ "@ultimat3/realtime": "31.1.0",
66
+ "@ultimat3/render": "31.1.0",
67
+ "@ultimat3/schema": "31.1.0",
68
+ "@ultimat3/scraping": "31.1.0",
69
+ "@ultimat3/seo": "31.1.0",
70
+ "@ultimat3/time": "31.1.0"
71
71
  }
72
72
  }
@@ -1,20 +1,22 @@
1
1
  // What one primitive did in the exercise pass, and the room it did it in: the network sealed with
2
2
  // every allow and mock cleared, the mail fixture, the clock frozen, statements and committed rows
3
- // observed. Every seam is process-global, so the room hands back exactly what it found.
3
+ // observed. Every seam is process-global, so the room keeps only what the observed call's own
4
+ // async context did — a timer's or another request's work in the same window is not the call's.
4
5
 
5
6
  import type { DbStatementEvent } from '@ultimat3/core';
6
- import { isSelfOrigin, peerAddressClass, subscribe } from '@ultimat3/core';
7
+ import { asyncContext, isSelfOrigin, peerAddressClass, subscribe } from '@ultimat3/core';
7
8
  import { expectedSeqScanReason, statementFingerprint } from '@ultimat3/db';
8
9
  import { captureDeterminism, installDeterminism, restoreCapturedDeterminism } from './determinism';
9
10
  import type { ExerciseDefect } from './exercise-defect';
10
- import { testMail } from './fixture-mail';
11
+ import { roomMail } from './exercise-room-mail';
11
12
  import { routeMatches } from './mock-route';
12
13
  import type { PlanProof, SentStatement } from './plan-sweep';
14
+ import type { LoggedRequest } from './request-log';
13
15
  import type { ScaleProof, StatementTally } from './scale-sweep';
14
16
  import {
15
17
  captureNetwork,
16
18
  isNetworkSealed,
17
- requestLog,
19
+ onDial,
18
20
  resetNetwork,
19
21
  restoreCapturedNetwork,
20
22
  sealNetwork,
@@ -180,7 +182,7 @@ const tally = (keys: readonly string[]): ReadonlyMap<string, number> => {
180
182
  return counts;
181
183
  };
182
184
 
183
- /** What happened between `begin()` and `end()`. */
185
+ /** What the observed call did — it and the work it started, never a neighbour in its window. */
184
186
  export interface Observed {
185
187
  readonly statements: number;
186
188
  readonly effects: readonly ExerciseEffect[];
@@ -192,14 +194,32 @@ export interface Observed {
192
194
  readonly shapes: readonly StatementTally[];
193
195
  }
194
196
 
197
+ /** What `observe` hands back: what the call did, and its value or what it threw. */
198
+ export type Observation<T> =
199
+ | { readonly observed: Observed; readonly value: T }
200
+ | { readonly observed: Observed; readonly error: unknown };
201
+
195
202
  export interface ExerciseRoom extends AsyncDisposable {
196
- /** `subject`: the primitive the statements until `end()` are sent for — what the plan sweep reads. */
197
- begin(subject?: string): void;
198
- end(): Observed;
199
- /** Every distinct statement text sent between a `begin(subject)` and its `end()`, so far. */
203
+ /**
204
+ * Run `fn` — one primitive's call — and hand back what it did. Attributed by async context, never
205
+ * by time: `fn` runs under a marker of this call's own, and a statement, row, mail or dial counts
206
+ * only when it is made under it. Work `fn` starts and does not await carries the marker too, until
207
+ * `observe` returns. `subject`: the primitive the statements are sent for — what the plan sweep
208
+ * reads; none, and they are tallied but not planned.
209
+ */
210
+ observe<T>(subject: string | undefined, fn: () => Promise<T>): Promise<Observation<T>>;
211
+ /** Whether the caller is inside the call being observed — for a seam the room does not own. */
212
+ owns(): boolean;
213
+ /** Every distinct statement text an `observe(subject, …)` call sent, so far. */
200
214
  sent(): ReadonlyMap<string, SentStatement>;
201
215
  }
202
216
 
217
+ /**
218
+ * The room's marker in flight — an identity object, never a credential. Never `ctx.requestId`: a job subject runs under the worker's own
219
+ * context, and a request the call did not make has one too.
220
+ */
221
+ const scope = asyncContext<object>('the exercise room');
222
+
203
223
  export async function openExerciseRoom(): Promise<ExerciseRoom> {
204
224
  const clock = captureDeterminism();
205
225
  if (!clock.installed) installDeterminism();
@@ -209,14 +229,20 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
209
229
  // a refusal by definition.
210
230
  resetNetwork();
211
231
  sealNetwork();
212
- const mail = await testMail();
232
+ // The call in flight: a fresh object per `observe`, so a straggler of the call before is not it.
233
+ let marker: object | undefined;
234
+ const owns = (): boolean => marker !== undefined && scope.get() === marker;
235
+ const mail = await roomMail(owns);
213
236
  let statements = 0;
214
- let logFrom = 0;
237
+ const calls: LoggedRequest[] = [];
215
238
  let subject: string | undefined;
216
239
  const rows: string[] = [];
217
240
  const shapes = new Map<string, { count: number; unexpected: number; expected?: string }>();
218
241
  const sent = new Map<string, { primitives: Set<string>; scan?: string }>();
242
+ // Every observer below returns at once unless the sender is the observed call: the bus delivers
243
+ // synchronously in the sender's context (`instrument`), so `owns()` reads the sender's marker.
219
244
  const counting = (event: DbStatementEvent): void => {
245
+ if (!owns()) return;
220
246
  statements += 1;
221
247
  const fingerprint = statementFingerprint(event);
222
248
  const shape = shapes.get(fingerprint) ?? { count: 0, unexpected: 0 };
@@ -237,75 +263,93 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
237
263
  // Subscribers on the bus, beside any outer one — released at dispose, never displacing it.
238
264
  const offStatements = subscribe('db.statement', (event) => counting(event.payload));
239
265
  const offRows = subscribe('entity', (event) => {
266
+ if (!owns()) return;
240
267
  if (event.name === 'entity.row') rows.push(`${event.payload.entity}\u0000${event.payload.op}`);
241
268
  if (event.name !== 'entity.bulk') return;
242
269
  const { entity, op } = event.payload;
243
270
  for (let i = 0; i < event.payload.rows; i += 1) rows.push(`${entity}\u0000${op}`);
244
271
  });
272
+ const offDials = onDial((call) => {
273
+ if (owns()) calls.push(call);
274
+ });
245
275
 
246
- return {
247
- begin: (name) => {
248
- subject = name;
249
- statements = 0;
250
- shapes.clear();
251
- rows.length = 0;
252
- mail.clear();
253
- logFrom = requestLog().length;
254
- },
255
- end: (): Observed => {
256
- const calls = requestLog().slice(logFrom);
257
- // A call a route answered never left the process: the app's `setup` installed it.
258
- const { mocks } = captureNetwork();
259
- const refused = (call: (typeof calls)[number]): boolean =>
260
- !local(call.url) && !mocks.some((route) => routeMatches(route, call));
261
- const effects: ExerciseEffect[] = [
262
- ...[...tally(rows)].map(([key, count]): ExerciseEffect => {
263
- const [entity = '', op = ''] = key.split('\u0000');
264
- return { kind: 'row', entity, op, rows: count };
276
+ const begin = (name: string | undefined): object => {
277
+ subject = name;
278
+ statements = 0;
279
+ shapes.clear();
280
+ rows.length = 0;
281
+ calls.length = 0;
282
+ mail.clear();
283
+ marker = {};
284
+ return marker;
285
+ };
286
+ const end = (): Observed => {
287
+ marker = undefined;
288
+ // A call a route answered never left the process: the app's `setup` installed it.
289
+ const { mocks } = captureNetwork();
290
+ const refused = (call: (typeof calls)[number]): boolean =>
291
+ !local(call.url) && !mocks.some((route) => routeMatches(route, call));
292
+ const effects: ExerciseEffect[] = [
293
+ ...[...tally(rows)].map(([key, count]): ExerciseEffect => {
294
+ const [entity = '', op = ''] = key.split('\u0000');
295
+ return { kind: 'row', entity, op, rows: count };
296
+ }),
297
+ ...[...tally(mail.sent().map((message) => message.mailId))].map(
298
+ ([id, count]): ExerciseEffect => ({ kind: 'mail', mail: id, count }),
299
+ ),
300
+ ...calls.map(
301
+ (call): ExerciseEffect => ({
302
+ kind: 'network',
303
+ method: call.method,
304
+ host: hostOf(call.url),
305
+ refused: refused(call),
265
306
  }),
266
- ...[...tally(mail.outbox().map((sent) => sent.message.mailId))].map(
267
- ([id, count]): ExerciseEffect => ({ kind: 'mail', mail: id, count }),
268
- ),
269
- ...calls.map(
270
- (call): ExerciseEffect => ({
271
- kind: 'network',
272
- method: call.method,
273
- host: hostOf(call.url),
274
- refused: refused(call),
275
- }),
276
- ),
277
- ];
278
- const refusedHosts = calls.filter(refused).map((c) => hostOf(c.url));
279
- const payloads: EffectPayload[] = [
280
- ...mail.outbox().map(({ message }, i) => ({
281
- path: `effect.mail[${i}]`,
282
- value: {
283
- to: message.to,
284
- cc: message.cc,
285
- bcc: message.bcc,
286
- replyTo: message.replyTo,
287
- subject: message.subject,
288
- text: message.text,
289
- html: message.html,
290
- unsubscribeUrl: message.unsubscribeUrl,
291
- },
292
- })),
293
- // Headers left out: a bearer token is not A's row, and a header is no row's text.
294
- ...calls.map((call, i) => ({
295
- path: `effect.network[${i}]`,
296
- value: { url: call.url, body: call.body },
297
- })),
298
- ];
299
- subject = undefined;
300
- const tallies = [...shapes].map(([fingerprint, shape]) => ({ fingerprint, ...shape }));
301
- return { statements, effects, refusedHosts, payloads, shapes: tallies };
307
+ ),
308
+ ];
309
+ const refusedHosts = calls.filter(refused).map((c) => hostOf(c.url));
310
+ const payloads: EffectPayload[] = [
311
+ ...mail.sent().map((message, i) => ({
312
+ path: `effect.mail[${i}]`,
313
+ value: {
314
+ to: message.to,
315
+ cc: message.cc,
316
+ bcc: message.bcc,
317
+ replyTo: message.replyTo,
318
+ subject: message.subject,
319
+ text: message.text,
320
+ html: message.html,
321
+ unsubscribeUrl: message.unsubscribeUrl,
322
+ },
323
+ })),
324
+ // Headers left out: a bearer token is not A's row, and a header is no row's text.
325
+ ...calls.map((call, i) => ({
326
+ path: `effect.network[${i}]`,
327
+ value: { url: call.url, body: call.body },
328
+ })),
329
+ ];
330
+ subject = undefined;
331
+ const tallies = [...shapes].map(([fingerprint, shape]) => ({ fingerprint, ...shape }));
332
+ return { statements, effects, refusedHosts, payloads, shapes: tallies };
333
+ };
334
+
335
+ return {
336
+ observe: async <T>(name: string | undefined, fn: () => Promise<T>): Promise<Observation<T>> => {
337
+ const mine = begin(name);
338
+ try {
339
+ const value = await scope.run(mine, fn);
340
+ return { observed: end(), value };
341
+ } catch (error) {
342
+ return { observed: end(), error };
343
+ }
302
344
  },
345
+ owns,
303
346
  sent: () => sent,
304
347
  [Symbol.asyncDispose]: async (): Promise<void> => {
305
348
  // Each restore runs whatever the one before it did: a throw must not strand a seam.
306
349
  try {
307
350
  mail[Symbol.dispose]();
308
351
  } finally {
352
+ offDials();
309
353
  offRows();
310
354
  offStatements();
311
355
  restoreCapturedNetwork(network);
@@ -0,0 +1,40 @@
1
+ // The exercise room's mail seam: every send delivered to memory, and only the observed call's
2
+ // kept. Asked at the send, in the sender's own async context — a timer's or another request's
3
+ // mail sent while the call awaits is somebody else's effect, never the primitive's.
4
+
5
+ import type { MailMessage } from '@ultimat3/mail';
6
+
7
+ export interface RoomMail extends Disposable {
8
+ /** The observed call's messages since `clear()`, newest first — the `outbox()` order. */
9
+ sent(): readonly MailMessage[];
10
+ clear(): void;
11
+ }
12
+
13
+ /** Install a driver frame whose kept messages are those sent while `owns()` answers true. */
14
+ export async function roomMail(owns: () => boolean): Promise<RoomMail> {
15
+ const { memoryMailDriver } = await import('@ultimat3/mail');
16
+ // The installer is the `./adapter` subpath's, never the barrel's (slice 21).
17
+ const { installMailDriver } = await import('@ultimat3/mail/adapter');
18
+ const memory = memoryMailDriver();
19
+ const kept: MailMessage[] = [];
20
+ const release = installMailDriver({
21
+ name: 'test',
22
+ send: async (message) => {
23
+ // Read before the first await: the send's own context, not whatever resumes it.
24
+ const mine = owns();
25
+ const result = await memory.send(message);
26
+ if (mine) kept.unshift(message);
27
+ return result;
28
+ },
29
+ });
30
+ return {
31
+ sent: () => [...kept],
32
+ clear: () => {
33
+ kept.length = 0;
34
+ memory.clear();
35
+ },
36
+ [Symbol.dispose]: (): void => {
37
+ release();
38
+ },
39
+ };
40
+ }
package/src/exercise.ts CHANGED
@@ -171,23 +171,21 @@ async function control(
171
171
  (await subject.input['~standard'].validate(input)).issues === undefined,
172
172
  attempt: async (input): Promise<ExerciseAttempt> => {
173
173
  const before = await queuedIds();
174
- room.begin(key);
175
- try {
176
- const answer = await subject.call(input, actor, tenant, jobs);
177
- if ('failure' in answer) {
178
- lastError = answer.failure;
179
- return { ok: false, reached: true, error: answer.failure };
180
- }
181
- answered = true;
182
- output = answer.output;
183
- return { ok: true, reached: true };
184
- } catch (error) {
185
- lastError = error;
186
- return { ok: false, reached: false, error };
187
- } finally {
188
- segments.push(room.end());
189
- for (const id of await queuedIds()) if (!before.has(id)) mine.add(id);
174
+ const seen = await room.observe(key, () => subject.call(input, actor, tenant, jobs));
175
+ segments.push(seen.observed);
176
+ for (const id of await queuedIds()) if (!before.has(id)) mine.add(id);
177
+ if ('error' in seen) {
178
+ lastError = seen.error;
179
+ return { ok: false, reached: false, error: seen.error };
180
+ }
181
+ const answer = seen.value;
182
+ if ('failure' in answer) {
183
+ lastError = answer.failure;
184
+ return { ok: false, reached: true, error: answer.failure };
190
185
  }
186
+ answered = true;
187
+ output = answer.output;
188
+ return { ok: true, reached: true };
191
189
  },
192
190
  statusOf: (await import('@ultimat3/http')).statusFor,
193
191
  });
@@ -237,7 +235,6 @@ async function attack(
237
235
  room: ExerciseRoom,
238
236
  ): Promise<LegAnswer> {
239
237
  await using jobs = await testJobs();
240
- room.begin(key);
241
238
  let output: unknown;
242
239
  // A job's org is re-seated in B's: B cannot enqueue a payload naming A (refused at the enqueue,
243
240
  // which proves nothing), so the attack that matters is a job of B's carrying A's ids.
@@ -245,19 +242,20 @@ async function attack(
245
242
  // Every `crossTenant()` B's call opened: a job's declared sweep is told from a leak by it alone.
246
243
  // On the bus, so the barrel stays entity-free (`seed-writer.ts`'s rule) with no import at all.
247
244
  const crossings: string[] = [];
245
+ // B's own: a scope another context opened in the window excuses nothing of B's.
248
246
  const offCrossings = subscribe('entity.cross_tenant', (event) => {
249
- crossings.push(event.payload.reason);
247
+ if (room.owns()) crossings.push(event.payload.reason);
250
248
  });
249
+ let observed: Observed;
251
250
  try {
252
- const answer = await subject.call(sent, actor, tenant, jobs);
253
- output = answer.output;
254
- } catch {
255
- // B's refusal is the answer a scoped primitive gives: only what B got back, and what B's call
256
- // did to A's rows, is judged — never whether B was refused.
251
+ // A throw is B's refusal, the answer a scoped primitive gives: only what B got back, and what
252
+ // B's call did to A's rows, is judged — never whether B was refused.
253
+ const seen = await room.observe(key, () => subject.call(sent, actor, tenant, jobs));
254
+ observed = seen.observed;
255
+ if ('value' in seen) output = seen.value.output;
257
256
  } finally {
258
257
  offCrossings();
259
258
  }
260
- const observed = room.end();
261
259
  const payloads = [...observed.payloads, ...(await queuedPayloads(subject))];
262
260
  return { output, payloads, crossings };
263
261
  }
@@ -71,15 +71,12 @@ async function callAt(
71
71
  return { failed: `its exercise.ts input threw: ${renderThrowable(error)}` };
72
72
  }
73
73
  if (prepared === undefined) return { failed: 'no actor its policy permits' };
74
- options.room.begin();
75
- try {
76
- const answer = await subject.call(prepared.input, prepared.actor, tenant, jobs);
77
- const observed = options.room.end();
78
- return 'failure' in answer ? { failed: renderThrowable(answer.failure) } : observed;
79
- } catch (error) {
80
- options.room.end();
81
- return { failed: renderThrowable(error) };
82
- }
74
+ // Observed by the call's own async context: a timer's statement in its window is not its shape.
75
+ const seen = await options.room.observe(undefined, () =>
76
+ subject.call(prepared.input, prepared.actor, tenant, jobs),
77
+ );
78
+ if ('error' in seen) return { failed: renderThrowable(seen.error) };
79
+ return 'failure' in seen.value ? { failed: renderThrowable(seen.value.failure) } : seen.observed;
83
80
  }
84
81
 
85
82
  /** Seed both sizes, call each subject at each, judge. Unseedable: every subject `unproven`. */
@@ -42,6 +42,24 @@ const state: SealState = {
42
42
  network: 'online',
43
43
  };
44
44
 
45
+ const dialListeners = new Set<(call: LoggedRequest) => void>();
46
+
47
+ /**
48
+ * Each dial as it is logged, synchronously and in the dialler's own async context — so a listener
49
+ * can tell whose call it was (`exercise-report.ts`'s room). Internal: never on the barrel.
50
+ */
51
+ export function onDial(listener: (call: LoggedRequest) => void): () => void {
52
+ dialListeners.add(listener);
53
+ return () => {
54
+ dialListeners.delete(listener);
55
+ };
56
+ }
57
+
58
+ const logDial = (call: LoggedRequest): void => {
59
+ state.log.push(call);
60
+ for (const listener of dialListeners) listener(call);
61
+ };
62
+
45
63
  /**
46
64
  * What a mocked host resolves to: one `public` address (`classifyAddress`), so an SSRF screen
47
65
  * passes it, and never a host network — a screen refuses those. Never dialled: a dial pinned to it
@@ -76,7 +94,7 @@ const isThisMachine = (hostname: string): boolean => {
76
94
  /** The socket dials' gate: the same allow-list, offline state and record as `fetch`. No mocks — a
77
95
  * socket test injects its transport (`connect`, `client`), it does not intercept the dial. */
78
96
  const socketRefusal = (url: string, method: string): Error | undefined => {
79
- state.log.push({ method, url, headers: {}, body: null });
97
+ logDial({ method, url, headers: {}, body: null });
80
98
  let target: URL;
81
99
  try {
82
100
  target = new URL(url);
@@ -135,7 +153,7 @@ export function sealNetwork(): void {
135
153
  // In the log before the first await, so concurrent calls keep their order; every verdict below
136
154
  // is reached before the body is awaited too, so a call is judged by the state it was made in.
137
155
  const call = { method, url, headers: headersOf(probe), body: null as string | null };
138
- state.log.push(call);
156
+ logDial(call);
139
157
  const openEnded = isOpenEnded(input, init);
140
158
  /** A finite body is in the entry when `fetch` settles; an open-ended one, once it ends. */
141
159
  const logBody = async (source: Request | undefined): Promise<void> => {