@ultimat3/testing 31.0.0 → 31.2.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/README.md CHANGED
@@ -383,6 +383,7 @@ postFactory.attributesFor(); // an action input: no i
383
383
  | | |
384
384
  |---|---|
385
385
  | **strategies** | `build` (memory, never a database), `create` (writes, answers the row AS STORED: declared defaults, generated columns, timestamps), `attributesFor` (an input: no primary key, no `belongsTo` key, no transient), `buildList` / `createList` |
386
+ | **literals** | `defaults` is checked against the entity's columns as written: `status: 'open'` for an `enumerated(['open', 'closed'])` column compiles with no `as const`, `status: 'nope'` does not. Once checked, a default's literal widens (``title: `t${n}` `` → `string`), so `build({ title: 'x' })` compiles (`factories-literals.test.ts`) |
386
387
  | **sequence** | `index` (`n` above), per factory, shared by every `with()` view and `extend()` child — ids never repeat |
387
388
  | **trait** | a named partial (or `(n, ids, transient) => partial`). `with('a', 'b')` composes left to right; a call's override wins. An undeclared one fails at `with()` (`X_TEST_FACTORY_TRAIT_UNKNOWN`) |
388
389
  | **transient** | declared defaults a call may override; read by `defaults`, traits and callbacks; never written |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.0.0",
3
+ "version": "31.2.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.2.0",
51
+ "@ultimat3/ai": "31.2.0",
52
+ "@ultimat3/auth": "31.2.0",
53
+ "@ultimat3/cache": "31.2.0",
54
+ "@ultimat3/core": "31.2.0",
55
+ "@ultimat3/db": "31.2.0",
56
+ "@ultimat3/entity": "31.2.0",
57
+ "@ultimat3/http": "31.2.0",
58
+ "@ultimat3/i18n": "31.2.0",
59
+ "@ultimat3/jobs": "31.2.0",
60
+ "@ultimat3/mail": "31.2.0",
61
+ "@ultimat3/notify": "31.2.0",
62
+ "@ultimat3/policy": "31.2.0",
63
+ "@ultimat3/pwa": "31.2.0",
64
+ "@ultimat3/query": "31.2.0",
65
+ "@ultimat3/realtime": "31.2.0",
66
+ "@ultimat3/render": "31.2.0",
67
+ "@ultimat3/schema": "31.2.0",
68
+ "@ultimat3/scraping": "31.2.0",
69
+ "@ultimat3/seo": "31.2.0",
70
+ "@ultimat3/time": "31.2.0"
71
71
  }
72
72
  }
@@ -3,6 +3,8 @@
3
3
  // and a column stores only what Postgres stores. Lifted from `entity/src/write-parity.test.ts`.
4
4
 
5
5
  import { expect } from 'bun:test';
6
+ import { isUltimateError } from '@ultimat3/core';
7
+ import { SQLSTATE, sqlState } from '@ultimat3/db';
6
8
  import {
7
9
  arrayOf,
8
10
  bigint,
@@ -106,7 +108,19 @@ const docs = remember(
106
108
  );
107
109
 
108
110
  const ID = idAt(1);
109
- const UNIQUE = 'X_DB_UNIQUE_VIOLATION';
111
+ /** A duplicate key: the framework's code AND Postgres' SQLSTATE, on every driver — a caller that
112
+ * branches on `sqlState(error)` (an upsert retry, a "taken" message) must not see Postgres only. */
113
+ const DUPLICATE = { code: 'X_DB_UNIQUE_VIOLATION', sqlState: SQLSTATE.uniqueViolation };
114
+
115
+ /** The refusal's code and SQLSTATE, or the value when nothing was refused. */
116
+ const duplicate = async (work: () => Promise<unknown>): Promise<unknown> => {
117
+ try {
118
+ return { ok: await work() };
119
+ } catch (error) {
120
+ return { code: isUltimateError(error) ? error.code : 'uncoded', sqlState: sqlState(error) };
121
+ }
122
+ };
123
+
110
124
  const REFUSED = { code: 'X_INVARIANT_VIOLATED' };
111
125
 
112
126
  const undefinedIsAbsent: readonly EntityDriverCheck[] = [
@@ -142,23 +156,19 @@ const undefinedIsAbsent: readonly EntityDriverCheck[] = [
142
156
  const keysAreKept: readonly EntityDriverCheck[] = [
143
157
  checkOver({ tags }, 'a duplicate primary key is refused, not a silent replace', async (db) => {
144
158
  await db.tags.insert({ code: 'a', slug: 'one' });
145
- expect(await outcome(() => db.tags.insert({ code: 'a', slug: 'two' }))).toEqual({
146
- code: UNIQUE,
147
- });
159
+ expect(await duplicate(() => db.tags.insert({ code: 'a', slug: 'two' }))).toEqual(DUPLICATE);
148
160
  expect((await db.tags.all()).map((row) => row.slug)).toEqual(['one']);
149
161
  }),
150
162
  checkOver({ tags }, 'a duplicate unique column is refused', async (db) => {
151
163
  await db.tags.insert({ code: 'a', slug: 'one' });
152
- expect(await outcome(() => db.tags.insert({ code: 'b', slug: 'one' }))).toEqual({
153
- code: UNIQUE,
154
- });
164
+ expect(await duplicate(() => db.tags.insert({ code: 'b', slug: 'one' }))).toEqual(DUPLICATE);
155
165
  }),
156
166
  checkOver({ tags }, 'insertAll with a duplicate inside the batch stores nothing', async (db) => {
157
167
  const batch = [
158
168
  { code: 'a', slug: 'one' },
159
169
  { code: 'a', slug: 'two' },
160
170
  ];
161
- expect(await outcome(() => db.tags.insertAll(batch))).toEqual({ code: UNIQUE });
171
+ expect(await duplicate(() => db.tags.insertAll(batch))).toEqual(DUPLICATE);
162
172
  expect(await db.tags.all()).toHaveLength(0);
163
173
  }),
164
174
  checkOver({ tags }, 'a patch moving the primary key leaves one row, not two', async (db) => {
@@ -194,9 +204,9 @@ const keysAreKept: readonly EntityDriverCheck[] = [
194
204
  async (db) => {
195
205
  await db.notes.insert({ id: idAt(1), title: 'one', body: 'same' });
196
206
  await db.notes.insert({ id: idAt(2), title: 'two', body: 'same' });
197
- expect(await outcome(() => db.notes.updateWhere({ body: 'same' }, { id: idAt(3) }))).toEqual({
198
- code: UNIQUE,
199
- });
207
+ expect(
208
+ await duplicate(() => db.notes.updateWhere({ body: 'same' }, { id: idAt(3) })),
209
+ ).toEqual(DUPLICATE);
200
210
  const kept = (await db.notes.all()).map((row) => [row.id, row.title, row.body]).sort();
201
211
  expect(kept).toEqual([
202
212
  [idAt(1), 'one', 'same'],
@@ -211,10 +221,8 @@ const keysAreKept: readonly EntityDriverCheck[] = [
211
221
  await db.countries.insert({ id: idAt(1), iso: 'AA', name: 'Same' });
212
222
  await db.countries.insert({ id: idAt(2), iso: 'BB', name: 'Same' });
213
223
  expect(
214
- await outcome(() => db.countries.updateWhere({ name: 'Same' }, { iso: 'ZZ' })),
215
- ).toEqual({
216
- code: UNIQUE,
217
- });
224
+ await duplicate(() => db.countries.updateWhere({ name: 'Same' }, { iso: 'ZZ' })),
225
+ ).toEqual(DUPLICATE);
218
226
  const kept = (await db.countries.all()).map((row) => [row.id, row.iso]).sort();
219
227
  expect(kept).toEqual([
220
228
  [idAt(1), 'AA'],
@@ -224,9 +232,7 @@ const keysAreKept: readonly EntityDriverCheck[] = [
224
232
  ),
225
233
  checkOver({ docs }, 'a unique declared as an invariant refuses a second row', async (db) => {
226
234
  await db.docs.insert({ id: idAt(1), slug: 'one' });
227
- expect(await outcome(() => db.docs.insert({ id: idAt(2), slug: 'one' }))).toEqual({
228
- code: UNIQUE,
229
- });
235
+ expect(await duplicate(() => db.docs.insert({ id: idAt(2), slug: 'one' }))).toEqual(DUPLICATE);
230
236
  }),
231
237
  checkOver(
232
238
  { docs },
@@ -234,14 +240,12 @@ const keysAreKept: readonly EntityDriverCheck[] = [
234
240
  async (db) => {
235
241
  await db.docs.insert({ id: idAt(1), slug: 'one' });
236
242
  await db.docs.insert({ id: idAt(2), slug: 'two' });
237
- expect(await outcome(() => db.docs.update(idAt(2), { slug: 'one' }))).toEqual({
238
- code: UNIQUE,
239
- });
243
+ expect(await duplicate(() => db.docs.update(idAt(2), { slug: 'one' }))).toEqual(DUPLICATE);
240
244
  const pair = [
241
245
  { id: idAt(3), slug: 'three' },
242
246
  { id: idAt(4), slug: 'three' },
243
247
  ];
244
- expect(await outcome(() => db.docs.insertAll(pair))).toEqual({ code: UNIQUE });
248
+ expect(await duplicate(() => db.docs.insertAll(pair))).toEqual(DUPLICATE);
245
249
  expect((await db.docs.all()).map((row) => row.slug).sort()).toEqual(['one', 'two']);
246
250
  },
247
251
  ),
@@ -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
  }
package/src/factories.ts CHANGED
@@ -10,10 +10,12 @@ import { persistRow } from './factory-persist';
10
10
  import { attributesOf, type FactorySpec, rowSteps, type Step } from './factory-pipeline';
11
11
  import type {
12
12
  BelongsToMap,
13
+ DefaultsBound,
13
14
  EntityLike,
14
15
  FactoryIds,
15
16
  HasManyMap,
16
17
  None,
18
+ SettledAttrs,
17
19
  StoredOf,
18
20
  TraitMap,
19
21
  } from './factory-types';
@@ -162,22 +164,30 @@ function extended(
162
164
  }
163
165
 
164
166
  export function defineFactory<
165
- TAttrs extends object,
167
+ TAttrs extends DefaultsBound<TAttrs, E>,
166
168
  E extends EntityLike = EntityLike,
167
169
  TTransient extends object = None,
168
- TTraits extends TraitMap<TAttrs & StoredOf<E, TAttrs>, TTransient> = TraitMap<
169
- TAttrs & StoredOf<E, TAttrs>,
170
+ TTraits extends TraitMap<
171
+ SettledAttrs<TAttrs> & StoredOf<E, SettledAttrs<TAttrs>>,
170
172
  TTransient
171
- >,
173
+ > = TraitMap<SettledAttrs<TAttrs> & StoredOf<E, SettledAttrs<TAttrs>>, TTransient>,
172
174
  TBelongs extends BelongsToMap = None,
173
175
  TMany extends HasManyMap = None,
174
176
  >(
175
177
  entity: E,
176
- options: FactoryOptions<TAttrs, TTraits, TTransient, TBelongs, TMany, StoredOf<E, TAttrs>, E>,
178
+ options: FactoryOptions<
179
+ TAttrs,
180
+ TTraits,
181
+ TTransient,
182
+ TBelongs,
183
+ TMany,
184
+ StoredOf<E, SettledAttrs<TAttrs>>,
185
+ E
186
+ >,
177
187
  ): Factory<
178
- TAttrs,
188
+ SettledAttrs<TAttrs>,
179
189
  Extract<keyof TTraits, string>,
180
- StoredOf<E, TAttrs>,
190
+ StoredOf<E, SettledAttrs<TAttrs>>,
181
191
  TTransient,
182
192
  TBelongs,
183
193
  TMany
@@ -211,9 +221,9 @@ export function defineFactory<
211
221
  afterCreate: erased.afterCreate === undefined ? [] : [erased.afterCreate.bind(options)],
212
222
  };
213
223
  return view(spec, sequence, seed, []) as unknown as Factory<
214
- TAttrs,
224
+ SettledAttrs<TAttrs>,
215
225
  Extract<keyof TTraits, string>,
216
- StoredOf<E, TAttrs>,
226
+ StoredOf<E, SettledAttrs<TAttrs>>,
217
227
  TTransient,
218
228
  TBelongs,
219
229
  TMany
@@ -12,6 +12,7 @@ import type {
12
12
  ForeignKeysOf,
13
13
  HasManyMap,
14
14
  None,
15
+ SettledAttrs,
15
16
  TraitMap,
16
17
  WriteBound,
17
18
  } from './factory-types';
@@ -31,19 +32,26 @@ export interface FactoryOptions<
31
32
  * Every column the factory owns; called once per row. `index` is the sequence. It must name each
32
33
  * `belongsTo` key, so a key that is not a column is a compile error HERE: a check written as a
33
34
  * constraint on `belongsTo` fixed the row type before this was read, and every row became `object`.
35
+ * `Readonly<TAttrs>` is the slot that keeps an enum literal literal (`DefaultsBound`).
34
36
  */
35
37
  defaults(
36
38
  index: number,
37
39
  ids: FactoryIds,
38
40
  transient: TTransient,
39
- ): TAttrs & WriteBound<E> & Readonly<Record<ForeignKeysOf<TBelongs>, unknown>>;
41
+ ): TAttrs & Readonly<TAttrs> & WriteBound<E> & Readonly<Record<ForeignKeysOf<TBelongs>, unknown>>;
40
42
  readonly traits?: TTraits;
41
43
  /** Attributes a call may pass that are never written: read by `defaults`, traits and callbacks. */
42
44
  readonly transient?: TTransient;
43
45
  readonly belongsTo?: TBelongs;
44
46
  readonly hasMany?: TMany;
45
- /** After the row is assembled, before any write — both strategies. */
46
- afterBuild?(row: NoInfer<TAttrs>, context: FactoryContext<TTransient>): void;
47
+ /**
48
+ * After the row is assembled, before any write — both strategies. The row is `build()`'s own
49
+ * type: a column holds its declared union, never the widened `SettledAttrs` one.
50
+ */
51
+ afterBuild?(
52
+ row: NoInfer<SettledAttrs<TAttrs> & Partial<TRow>>,
53
+ context: FactoryContext<TTransient>,
54
+ ): void;
47
55
  /** After the row and its `hasMany` children are stored — `create()` only. */
48
56
  afterCreate?(
49
57
  row: NoInfer<Created<TRow, TMany>>,
@@ -68,7 +76,7 @@ export interface FactoryExtension<
68
76
  readonly traits?: TTraits;
69
77
  readonly transient?: Partial<TTransient>;
70
78
  readonly hasMany?: TMoreMany;
71
- afterBuild?(row: TAttrs, context: FactoryContext<TTransient>): void;
79
+ afterBuild?(row: TAttrs & Partial<TRow>, context: FactoryContext<TTransient>): void;
72
80
  afterCreate?(
73
81
  row: Created<TRow, TMany & TMoreMany>,
74
82
  context: FactoryContext<TTransient>,
@@ -129,3 +129,34 @@ export type StoredOf<E, TAttrs> = E extends { readonly $row: infer R extends obj
129
129
  export type WriteBound<E> = E extends { readonly $columns: infer C extends ColumnMap }
130
130
  ? Partial<Insertable<C>>
131
131
  : object;
132
+
133
+ /**
134
+ * Any value at all (`{} | null | undefined` is `unknown`, so `Record<string, unknown>` fits), but
135
+ * spelled as a union so the checker sees it include `string` — `unknown` alone would not keep a literal.
136
+ */
137
+ // biome-ignore lint/complexity/noBannedTypes: `{}` is what makes the union admit `unknown`.
138
+ export type AttrValue = string | number | boolean | bigint | symbol | {} | null | undefined;
139
+
140
+ /**
141
+ * The bound on what `defaults` returns. Its per-key `AttrValue` is what keeps `status: 'open'` a
142
+ * literal: TypeScript widens a literal unless the slot it lands in is a type variable whose
143
+ * constraint holds `string`, and `WriteBound<E>` is a conditional over an unfixed `E` that never
144
+ * is. Self-referential (`keyof A`) rather than a `Record`, so an `interface` still satisfies it.
145
+ */
146
+ export type DefaultsBound<A, E> = { readonly [K in keyof A]: AttrValue } & WriteBound<E>;
147
+
148
+ type Widened<V> = V extends string
149
+ ? string
150
+ : V extends number
151
+ ? number
152
+ : V extends boolean
153
+ ? boolean
154
+ : V extends bigint
155
+ ? bigint
156
+ : V;
157
+
158
+ /**
159
+ * The literals `DefaultsBound` kept, widened back once checked: `title: \`t${n}\`` must not make
160
+ * `build({ title: 'x' })` a type error. A column's own union returns through `Partial<TRow>`.
161
+ */
162
+ export type SettledAttrs<A> = { [K in keyof A]: Widened<A[K]> };
package/src/index.ts CHANGED
@@ -171,10 +171,12 @@ export type { EntityRegistry, FactoryRegistry } from './factory-registry';
171
171
  export { factoriesFor } from './factory-registry';
172
172
  export type {
173
173
  AttributesFor,
174
+ AttrValue,
174
175
  BelongsTo,
175
176
  BelongsToMap,
176
177
  Built,
177
178
  Created,
179
+ DefaultsBound,
178
180
  EntityLike,
179
181
  FactoryContext,
180
182
  FactoryIds,
@@ -184,6 +186,7 @@ export type {
184
186
  HasMany,
185
187
  HasManyMap,
186
188
  None,
189
+ SettledAttrs,
187
190
  StoredOf,
188
191
  Trait,
189
192
  TraitMap,
@@ -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> => {