@ultimat3/testing 30.8.0 → 31.0.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.
Files changed (159) hide show
  1. package/CLAUDE.md +49 -62
  2. package/README.md +179 -39
  3. package/package.json +23 -17
  4. package/src/ai-conformance-answer.ts +67 -0
  5. package/src/ai-gateway-conformance.ts +105 -0
  6. package/src/ai-provider-conformance.ts +69 -0
  7. package/src/ai-provider-transport-conformance.ts +170 -0
  8. package/src/audit-sink-conformance.ts +204 -0
  9. package/src/auth-adapter-conformance-credentials.ts +124 -0
  10. package/src/auth-adapter-conformance-mfa.ts +70 -0
  11. package/src/auth-adapter-conformance-passkeys.ts +133 -0
  12. package/src/auth-adapter-conformance-sessions.ts +115 -0
  13. package/src/auth-adapter-conformance-support.ts +71 -0
  14. package/src/auth-adapter-conformance-users.ts +128 -0
  15. package/src/auth-adapter-conformance.ts +34 -0
  16. package/src/auth-limiter-factory-conformance.ts +224 -0
  17. package/src/auth-server-store-conformance-records.ts +69 -0
  18. package/src/auth-server-store-conformance.ts +208 -0
  19. package/src/cache-tier-conformance-checks.ts +142 -0
  20. package/src/cache-tier-conformance.ts +24 -0
  21. package/src/cassette-format.ts +8 -13
  22. package/src/cassette-record.ts +1 -1
  23. package/src/cdp-browser.ts +10 -11
  24. package/src/cdp-e2e-page.ts +2 -2
  25. package/src/cdp-e2e-session.ts +2 -2
  26. package/src/cdp-network-probe.ts +1 -1
  27. package/src/cdp-offline-script.ts +2 -2
  28. package/src/clock-conformance.ts +126 -0
  29. package/src/conformance.ts +239 -0
  30. package/src/e2e-browser-handle.ts +1 -2
  31. package/src/e2e-error-codes.ts +17 -16
  32. package/src/e2e-run.ts +4 -3
  33. package/src/embedder-conformance.ts +101 -0
  34. package/src/entity-conformance-aggregates.ts +210 -0
  35. package/src/entity-conformance-batches.ts +216 -0
  36. package/src/entity-conformance-bulk.ts +379 -0
  37. package/src/entity-conformance-checks.ts +27 -0
  38. package/src/entity-conformance-entities.ts +52 -0
  39. package/src/entity-conformance-locks.ts +286 -0
  40. package/src/entity-conformance-matrix.ts +397 -0
  41. package/src/entity-conformance-reads.ts +241 -0
  42. package/src/entity-conformance-support.ts +56 -0
  43. package/src/entity-conformance-tenancy.ts +296 -0
  44. package/src/entity-conformance-values.ts +305 -0
  45. package/src/entity-conformance-versions.ts +60 -0
  46. package/src/entity-conformance-writes.ts +348 -0
  47. package/src/entity-driver-conformance.ts +103 -0
  48. package/src/error-groups-store-conformance.ts +198 -0
  49. package/src/error-reporter-conformance.ts +119 -0
  50. package/src/errors.ts +41 -11
  51. package/src/event-bus-conformance.ts +161 -0
  52. package/src/exercise-drift-hint.ts +4 -1
  53. package/src/exercise-judge.ts +5 -3
  54. package/src/exercise-override-input.ts +22 -9
  55. package/src/exercise-override-line.ts +98 -0
  56. package/src/exercise-report.ts +30 -51
  57. package/src/exercise-sweeps.ts +3 -1
  58. package/src/exercise.ts +38 -19
  59. package/src/factories.ts +192 -179
  60. package/src/factory-api.ts +131 -0
  61. package/src/factory-associations.ts +67 -0
  62. package/src/factory-errors.ts +38 -0
  63. package/src/factory-lint.ts +92 -0
  64. package/src/factory-persist.ts +74 -16
  65. package/src/factory-pipeline.ts +191 -0
  66. package/src/factory-registry.ts +2 -1
  67. package/src/factory-types.ts +131 -0
  68. package/src/failure-store-conformance.ts +137 -0
  69. package/src/fixture-jobs.ts +50 -15
  70. package/src/fixture-mail.ts +7 -7
  71. package/src/fixture-seed.ts +111 -0
  72. package/src/fixture-statements.ts +68 -52
  73. package/src/framework-fixtures.ts +1 -1
  74. package/src/idempotency-store-conformance.ts +186 -0
  75. package/src/idempotency-store-replay-conformance.ts +140 -0
  76. package/src/idempotency-store-tx-conformance.ts +132 -0
  77. package/src/idempotency-store-world-conformance.ts +82 -0
  78. package/src/identity-provider-conformance.ts +144 -0
  79. package/src/image-transform-conformance.ts +89 -0
  80. package/src/index.ts +68 -157
  81. package/src/isr-store-conformance.ts +113 -0
  82. package/src/job-sim-effects.ts +19 -31
  83. package/src/job-sim-world.ts +6 -15
  84. package/src/lease-store-conformance.ts +195 -0
  85. package/src/mail-driver-conformance.ts +108 -0
  86. package/src/matcher-doubles.ts +104 -0
  87. package/src/matcher-stub.ts +78 -0
  88. package/src/matcher-surface.ts +21 -0
  89. package/src/matchers.ts +19 -1
  90. package/src/mcp-confirmation-store-conformance.ts +262 -0
  91. package/src/meter-store-conformance.ts +135 -0
  92. package/src/notify-digest-conformance.ts +133 -0
  93. package/src/notify-inbox-conformance.ts +130 -0
  94. package/src/notify-ledger-conformance.ts +134 -0
  95. package/src/notify-preference-conformance.ts +49 -0
  96. package/src/notify-stores-conformance.ts +73 -0
  97. package/src/outbox-store-conformance-claims.ts +112 -0
  98. package/src/outbox-store-conformance-subject.ts +65 -0
  99. package/src/outbox-store-conformance.ts +71 -0
  100. package/src/per-test-reset.ts +55 -20
  101. package/src/plan-oracle.ts +10 -3
  102. package/src/plan-sweep.ts +37 -12
  103. package/src/preload.ts +4 -2
  104. package/src/purge-conformance.ts +79 -0
  105. package/src/push-device-conformance.ts +124 -0
  106. package/src/push-subscription-conformance.ts +123 -0
  107. package/src/quiet-logs.ts +4 -4
  108. package/src/rate-limit-store-conformance.ts +178 -0
  109. package/src/registry-leak-error.ts +8 -1
  110. package/src/scale-sweep-run.ts +3 -1
  111. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  112. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  113. package/src/scrape-driver-conformance-site.ts +84 -0
  114. package/src/scrape-driver-conformance.ts +34 -0
  115. package/src/sealed-dns-resolver.ts +56 -0
  116. package/src/sealed-dns.ts +63 -64
  117. package/src/sealed-network.ts +13 -12
  118. package/src/sealed-node-sockets.ts +63 -0
  119. package/src/sealed-sockets.ts +13 -8
  120. package/src/sealed-udp.ts +118 -0
  121. package/src/search-index-conformance-list.ts +76 -0
  122. package/src/search-index-conformance-support.ts +69 -0
  123. package/src/search-index-conformance-versions.ts +66 -0
  124. package/src/search-index-conformance.ts +126 -0
  125. package/src/secret-source-conformance.ts +91 -0
  126. package/src/seed-factories.ts +57 -0
  127. package/src/seed-writer.ts +8 -19
  128. package/src/semantic-cache-factory-conformance.ts +86 -0
  129. package/src/sms-transport-conformance.ts +102 -0
  130. package/src/step-store-conformance.ts +171 -0
  131. package/src/storage-conformance-read-checks.ts +132 -0
  132. package/src/storage-conformance-shape.ts +121 -0
  133. package/src/storage-conformance-stream-checks.ts +226 -0
  134. package/src/storage-conformance.ts +34 -0
  135. package/src/stub-action.ts +24 -0
  136. package/src/stub-errors.ts +86 -0
  137. package/src/stub-job.ts +30 -0
  138. package/src/stub-query.ts +25 -0
  139. package/src/stub-script.ts +76 -0
  140. package/src/stub-stack.ts +29 -0
  141. package/src/stub.ts +73 -0
  142. package/src/swap-adapter.ts +135 -0
  143. package/src/test-scope.ts +96 -0
  144. package/src/test-types.ts +1 -1
  145. package/src/totp-replay-guard-conformance.ts +76 -0
  146. package/src/transport-conformance.ts +179 -0
  147. package/src/upload-scanner-conformance.ts +112 -0
  148. package/src/vector-store-conformance-checks.ts +174 -0
  149. package/src/vector-store-conformance.ts +21 -0
  150. package/src/cdp-connection.ts +0 -291
  151. package/src/cdp-errors.ts +0 -179
  152. package/src/cdp-launch-attempt.ts +0 -224
  153. package/src/cdp-launch-candidates.ts +0 -62
  154. package/src/cdp-launch-profile.ts +0 -106
  155. package/src/cdp-launch-reap.ts +0 -68
  156. package/src/cdp-launch-wire.ts +0 -171
  157. package/src/cdp-launch.ts +0 -175
  158. package/src/cdp-pipe.ts +0 -77
  159. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,137 @@
1
+ // The `FailureStore` contract of `@ultimat3/core` as shared examples, for a store of your own:
2
+ // `behavesLike(failureStoreConformance, () => subject)`. A bundle is saved by the request that
3
+ // FAILED — its transaction is rolling back — so the save must land outside it, whole, and once.
4
+
5
+ import { expect, test } from 'bun:test';
6
+ import { uuidV7 } from '@ultimat3/core';
7
+ import type { FailureBundle, FailureStore } from '@ultimat3/core/adapter';
8
+ import type { DbClient } from '@ultimat3/db';
9
+ import { raw, withTransaction } from '@ultimat3/db';
10
+ import type { SharedExamples } from './shared-examples';
11
+ import { sharedExamples } from './shared-examples';
12
+
13
+ type Maybe<T> = T | Promise<T>;
14
+
15
+ export interface FailureStoreSubject {
16
+ readonly store: FailureStore;
17
+ /** The bundle saved under `id`, read back from wherever the store put it. */
18
+ find(id: string): Promise<FailureBundle | undefined>;
19
+ /** The database a failing request's transaction runs on. */
20
+ readonly client: DbClient;
21
+ }
22
+
23
+ export interface FailureStoreCheck {
24
+ readonly name: string;
25
+ run(subject: FailureStoreSubject): Promise<void>;
26
+ }
27
+
28
+ /** A bundle with every field populated and nested — a store that flattens one is caught. */
29
+ export const failureBundle = (over: Partial<FailureBundle> = {}): FailureBundle => {
30
+ const requestId = uuidV7();
31
+ return {
32
+ id: uuidV7(),
33
+ fingerprint: `fp-${requestId}`,
34
+ code: 'X_INTERNAL',
35
+ operation: 'POST /api/orders',
36
+ primitive: 'action',
37
+ name: 'placeOrder',
38
+ at: Date.parse('2026-11-06T10:00:00.000Z'),
39
+ requestId,
40
+ traceId: `trace-${requestId}`,
41
+ build: 'build-7',
42
+ input: { sku: 'a-1', quantity: 2, note: null, lines: [{ minor: 1250, currency: 'EUR' }] },
43
+ masked: ['input.card'],
44
+ actor: {
45
+ kind: 'user',
46
+ id: 'u1',
47
+ orgId: 'org-1',
48
+ roles: ['buyer'],
49
+ scopes: [],
50
+ permissions: ['orders:write'],
51
+ },
52
+ flags: { checkoutV2: true, tier: 'gold' },
53
+ reads: [{ entity: 'order', row: { id: 'o1', total: 2500 }, masked: ['token'] }],
54
+ truncated: false,
55
+ ...over,
56
+ };
57
+ };
58
+
59
+ const PARALLEL = 12;
60
+
61
+ // A foreign failure the request body raises: test input handed to the subject, never a verdict.
62
+ const REQUEST_FAILED = new RangeError('the request failed');
63
+
64
+ export const FAILURE_STORE_CHECKS: readonly FailureStoreCheck[] = [
65
+ {
66
+ name: 'a saved bundle reads back whole',
67
+ async run({ store, find }) {
68
+ const bundle = failureBundle();
69
+ await store.save(bundle);
70
+ expect(await find(bundle.id)).toEqual(bundle);
71
+ },
72
+ },
73
+ {
74
+ name: 'a bundle with nothing optional reads back whole',
75
+ async run({ store, find }) {
76
+ const bundle = failureBundle({
77
+ operation: null,
78
+ requestId: null,
79
+ traceId: null,
80
+ build: null,
81
+ input: undefined,
82
+ actor: null,
83
+ flags: {},
84
+ reads: [],
85
+ masked: [],
86
+ truncated: true,
87
+ });
88
+ await store.save(bundle);
89
+ const { input: _input, ...rest } = bundle;
90
+ expect(await find(bundle.id)).toMatchObject(rest);
91
+ },
92
+ },
93
+ {
94
+ name: 'saving one id twice keeps the first bundle, and does not throw',
95
+ async run({ store, find }) {
96
+ const bundle = failureBundle();
97
+ await store.save(bundle);
98
+ await store.save({ ...bundle, code: 'X_FORBIDDEN' });
99
+ expect((await find(bundle.id))?.code).toBe('X_INTERNAL');
100
+ },
101
+ },
102
+ {
103
+ name: `${PARALLEL} bundles saved at once are ${PARALLEL} bundles`,
104
+ async run({ store, find }) {
105
+ const bundles = Array.from({ length: PARALLEL }, () => failureBundle());
106
+ await Promise.all(bundles.map((bundle) => store.save(bundle)));
107
+ for (const bundle of bundles) expect((await find(bundle.id))?.id).toBe(bundle.id);
108
+ },
109
+ },
110
+ {
111
+ name: 'a bundle saved inside a transaction that rolls back survives it',
112
+ async run({ store, find, client }) {
113
+ const bundle = failureBundle();
114
+ const failed = withTransaction(
115
+ async (tx) => {
116
+ await tx.execute(raw('select 1'));
117
+ await store.save(bundle);
118
+ throw REQUEST_FAILED;
119
+ },
120
+ { client },
121
+ );
122
+ await expect(failed).rejects.toThrow('the request failed');
123
+ expect(await find(bundle.id)).toEqual(bundle);
124
+ },
125
+ },
126
+ ];
127
+
128
+ export const failureStoreConformance: SharedExamples<Maybe<FailureStoreSubject>> = sharedExamples(
129
+ 'a failure store',
130
+ (subject) => {
131
+ for (const check of FAILURE_STORE_CHECKS) {
132
+ test(check.name, async () => {
133
+ await check.run(await subject());
134
+ });
135
+ }
136
+ },
137
+ );
@@ -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 {
@@ -79,6 +79,11 @@ export interface RunJobs extends AsyncDisposable {
79
79
  /** Live jobs claimable right now. `clock.advance()` is what turns delayed into due. */
80
80
  due(): Promise<number>;
81
81
  inFlight(): Promise<number>;
82
+ /**
83
+ * Every row this fixture's queue holds for `handle`, in any state — run or not. What
84
+ * `await expect(runJobs).toHaveEnqueued(handle, input)` reads.
85
+ */
86
+ enqueued(handle: AnyJobHandle): Promise<readonly JobRecord[]>;
82
87
  }
83
88
 
84
89
  const WORKER_ID = 'test-worker';
@@ -92,6 +97,31 @@ const CLAIM_LIMIT = 64;
92
97
  * reads the same clock, so a renewal can never report a lease lost that `clock.advance()` did not.
93
98
  */
94
99
  const RENEW_MS = 1;
100
+ /**
101
+ * The clock a body runs on: the preload's frozen instant, as a `FrozenClock`. `systemClock` read
102
+ * the frozen `Date` too, but had no `advance` — so a `backfill()` pacer saw every batch as instant
103
+ * and slept its whole `rate` interval in WALL time. Moving the instant is the wait now, and it is
104
+ * a move the frozen scheduler hears, so the renewals see exactly the time the throttle spent.
105
+ */
106
+ const PRELOAD_CLOCK: FrozenClock = Object.freeze({
107
+ now: frozenNow,
108
+ monotonic: () => frozenNow().getTime(),
109
+ advance: (ms: number): void => {
110
+ advanceClock(ms);
111
+ },
112
+ // A wait on this clock IS the move: the instant jumps, one microtask yields, and an abort on
113
+ // either side of the jump is honoured — never a wall-clock sleep under a frozen test.
114
+ sleep: async (ms: number, signal?: AbortSignal): Promise<void> => {
115
+ signal?.throwIfAborted();
116
+ advanceClock(ms);
117
+ await Promise.resolve();
118
+ signal?.throwIfAborted();
119
+ },
120
+ set: (at: Date | number | string): void => {
121
+ setFrozenClock(at instanceof Date ? at.getTime() : at);
122
+ },
123
+ });
124
+
95
125
  /** A drain that has not settled in this many rounds is a runaway, not a slow queue. */
96
126
  const MAX_ROUNDS = 100;
97
127
  const LIVE_STATES: ReadonlySet<string> = new Set(['ready', 'delayed', 'running', 'suspended']);
@@ -115,17 +145,17 @@ const tallyOf = (executions: readonly JobExecution[]): Record<string, StepTally>
115
145
 
116
146
  export async function testJobs(): Promise<RunJobs> {
117
147
  const jobs = await import('@ultimat3/jobs');
148
+ // The installers are the `./adapter` subpath's, never the barrel's (slice 21).
149
+ const adapter = await import('@ultimat3/jobs/adapter');
118
150
  const driver: JobDriver = jobs.memoryJobDriver();
119
- // Captured before the overwrite: the ambient driver is process-global, so without this the
120
- // next file to call `send()` enqueues into this test's dead queue instead of sending inline.
121
- const previous = jobs.jobDriver();
122
- jobs.setJobDriver(driver);
151
+ // Released at disposal: the ambient driver is process-global, so without it the next file to
152
+ // call `send()` enqueues into this test's dead queue instead of sending inline.
153
+ const releaseDriver = adapter.installJobDriver(driver);
123
154
  // The same for the event bus `step.waitForEvent` reads: it is ambient and it STORES, so an
124
155
  // answer one test published resumed the next test's waiting run. A fresh bus per fixture, and
125
156
  // the process's own handed back with the driver.
126
- const previousBus = jobs.eventBus();
127
- jobs.setEventBus(jobs.memoryEventBus());
128
- const anonymousWorker = ctxOf({ role: 'worker' });
157
+ const releaseBus = adapter.installEventBus(jobs.memoryEventBus());
158
+ const anonymousWorker = ctxOf({ role: 'worker', clock: PRELOAD_CLOCK });
129
159
  const renewals = frozenScheduler();
130
160
 
131
161
  const introspect = (): NonNullable<JobDriver['introspect']> => {
@@ -140,7 +170,7 @@ export async function testJobs(): Promise<RunJobs> {
140
170
 
141
171
  // Walked by cursor: one `list()` answers a PAGE (`MAX_JOB_PAGE`), and a test that queued more
142
172
  // than a page of jobs must still see every one of them.
143
- const live = async (name?: string): Promise<readonly JobRecord[]> => {
173
+ const rowsOf = async (name?: string): Promise<readonly JobRecord[]> => {
144
174
  const rows: JobRecord[] = [];
145
175
  let after: string | undefined;
146
176
  for (;;) {
@@ -154,8 +184,10 @@ export async function testJobs(): Promise<RunJobs> {
154
184
  if (last === undefined || page.length < jobs.MAX_JOB_PAGE) break;
155
185
  after = jobs.jobCursor(last);
156
186
  }
157
- return rows.filter((record) => LIVE_STATES.has(record.state));
187
+ return rows;
158
188
  };
189
+ const live = async (name?: string): Promise<readonly JobRecord[]> =>
190
+ (await rowsOf(name)).filter((record) => LIVE_STATES.has(record.state));
159
191
 
160
192
  const queues = (): readonly string[] => [
161
193
  ...new Set([jobs.DEFAULT_QUEUE, ...jobs.registeredJobs().map((handle) => handle.queue)]),
@@ -200,7 +232,9 @@ export async function testJobs(): Promise<RunJobs> {
200
232
  const history: JobExecution[] = [];
201
233
 
202
234
  const ctxFor = (options: JobDrainAs): Ctx =>
203
- options.actor === undefined ? anonymousWorker : ctxOf({ role: 'worker', actor: options.actor });
235
+ options.actor === undefined
236
+ ? anonymousWorker
237
+ : ctxOf({ role: 'worker', actor: options.actor, clock: PRELOAD_CLOCK });
204
238
  const traced = (): JobRunTrace => ({ executions: [...history], steps: tallyOf(history) });
205
239
 
206
240
  const tick = async (options: JobDrainAs = {}): Promise<JobRunTrace> => {
@@ -257,15 +291,16 @@ export async function testJobs(): Promise<RunJobs> {
257
291
  (record) => record.state !== 'running' && record.runAt <= frozenNow().getTime(),
258
292
  ).length,
259
293
  inFlight: async () => (await live()).filter((record) => record.state === 'running').length,
294
+ enqueued: (handle: AnyJobHandle) => rowsOf(handle.name),
260
295
  [Symbol.asyncDispose]: async (): Promise<void> => {
261
296
  // A `finally`: a close that throws must still hand every later file its bus and its driver.
262
297
  try {
263
298
  await driver.close?.();
264
299
  } finally {
265
300
  renewals[Symbol.dispose]();
266
- jobs.setEventBus(previousBus);
267
- if (previous === undefined) jobs.resetJobDriver();
268
- else jobs.setJobDriver(previous);
301
+ // Each release removes THIS install only, so a swap made over the fixture survives it.
302
+ releaseBus();
303
+ releaseDriver();
269
304
  }
270
305
  },
271
306
  });
@@ -22,12 +22,11 @@ export interface TestMail extends Disposable {
22
22
  const idOf = (mail: MailRef): string => (typeof mail === 'string' ? mail : mail.id);
23
23
 
24
24
  export async function testMail(): Promise<TestMail> {
25
- const { memoryMailDriver, driverUnavailable, resetMailDriver, setMailDriver, tryMailDriver } =
26
- await import('@ultimat3/mail');
25
+ const { memoryMailDriver, driverUnavailable } = await import('@ultimat3/mail');
26
+ // The installer is the `./adapter` subpath's, never the barrel's (slice 21).
27
+ const { installMailDriver } = await import('@ultimat3/mail/adapter');
27
28
  const memory = memoryMailDriver();
28
29
  const failuresLeft = new Map<string, number>();
29
- // The ambient driver is process-global; the fixture borrows it for one test and hands it back.
30
- const previous = tryMailDriver();
31
30
 
32
31
  const driver: MailDriver = {
33
32
  name: 'test',
@@ -40,7 +39,9 @@ export async function testMail(): Promise<TestMail> {
40
39
  );
41
40
  },
42
41
  };
43
- setMailDriver(driver);
42
+ // The ambient driver is process-global: the fixture borrows a FRAME of it for one test, and its
43
+ // release removes that frame and no other — whatever was installed over or under it meanwhile.
44
+ const release = installMailDriver(driver);
44
45
 
45
46
  return {
46
47
  outbox: () => memory.outbox(),
@@ -54,8 +55,7 @@ export async function testMail(): Promise<TestMail> {
54
55
  failuresLeft.clear();
55
56
  },
56
57
  [Symbol.dispose]: (): void => {
57
- if (previous === undefined) resetMailDriver();
58
- else setMailDriver(previous);
58
+ release();
59
59
  },
60
60
  };
61
61
  }
@@ -0,0 +1,111 @@
1
+ // The `seed` fixture's machinery: `seed('demo')` runs that named seed (a `factorySeed` or any
2
+ // `defineSeed`) once per test into the driver the APP reads through, and `.pick({ ada: 'member:ada'
3
+ // })` hands back the rows it wrote, by the labels the seed gave them. An app registers it with its
4
+ // own seeds and driver — `defineFixtures({ seed: seedFixture({ seeds: [demo], driver }) })`.
5
+
6
+ import { assert } from '@ultimat3/core';
7
+ import type { Driver, EntityCore, Repo, Seed, SeedRun } from '@ultimat3/entity';
8
+
9
+ /** A row a seed wrote, as it handed it to the driver. */
10
+ export interface SeededRow {
11
+ readonly id: string;
12
+ readonly [column: string]: unknown;
13
+ }
14
+
15
+ /** One named seed, run for this test. */
16
+ export interface SeedHandle {
17
+ /** What the run did — `inserted` 0 on a replay into a driver that already holds its rows. */
18
+ readonly ran: Promise<SeedRun>;
19
+ /** `pick({ draft: 'post:draft' })` — seed labels in, rows out, aliased at the call site. */
20
+ pick<const M extends Readonly<Record<string, string>>>(
21
+ labels: M,
22
+ ): Promise<{ readonly [K in keyof M]: SeededRow }>;
23
+ }
24
+
25
+ export interface SeedFixtureOptions {
26
+ /** Every seed a test may name, each under its own `name`. */
27
+ readonly seeds: readonly Seed[];
28
+ /**
29
+ * The driver the app reads through — never one of the fixture's own: rows written where nothing
30
+ * else looks are an empty table to every action under test.
31
+ */
32
+ readonly driver: () => Driver;
33
+ }
34
+
35
+ const idOf = (row: unknown): string | undefined => {
36
+ const value = (row as { readonly id?: unknown } | null)?.id;
37
+ return typeof value === 'string' ? value : undefined;
38
+ };
39
+
40
+ /**
41
+ * Rows are captured on the way IN, not read back: a tenant-scoped entity refuses an unscoped read,
42
+ * and a seed's `upsertAll(…, { onMatch: 'nothing' })` answers nothing for a row already stored — so
43
+ * a replay still finds every label.
44
+ */
45
+ function capturing(base: Driver, rows: Map<string, SeededRow>): Driver {
46
+ const capture = (row: unknown): void => {
47
+ const id = idOf(row);
48
+ if (id !== undefined) rows.set(id, row as SeededRow);
49
+ };
50
+ return {
51
+ transactor: () => base.transactor(),
52
+ repo: <Row>(entity: EntityCore<Row>): Repo<Row> => {
53
+ const inner = base.repo(entity);
54
+ return {
55
+ ...inner,
56
+ insert: async (values, options) => {
57
+ const row = await inner.insert(values, options);
58
+ capture(row);
59
+ return row;
60
+ },
61
+ upsertAll: async (batch, args) => {
62
+ for (const row of batch) capture(row);
63
+ return inner.upsertAll(batch, args);
64
+ },
65
+ };
66
+ },
67
+ };
68
+ }
69
+
70
+ /**
71
+ * The fixture factory. Per test: each name runs at most once (a second `seed('demo')` is the same
72
+ * handle), and a seed's own inserts are idempotent, so the next test's run writes nothing new.
73
+ */
74
+ export function seedFixture(options: SeedFixtureOptions): () => (name: string) => SeedHandle {
75
+ const byName = new Map(options.seeds.map((seed) => [seed.name, seed]));
76
+ return () => {
77
+ const handles = new Map<string, SeedHandle>();
78
+ return (name) => {
79
+ const seed = byName.get(name);
80
+ assert(
81
+ seed !== undefined,
82
+ `no seed named "${name}" is registered with the seed fixture — known: ${[...byName.keys()].join(', ')}`,
83
+ `add it to seedFixture({ seeds: [${name}, …], driver }) in the test preload, or name one of the known seeds`,
84
+ );
85
+ const open = handles.get(name);
86
+ if (open !== undefined) return open;
87
+ const rows = new Map<string, SeededRow>();
88
+ const ran = seed.run({ driver: capturing(options.driver(), rows) });
89
+ const handle: SeedHandle = {
90
+ ran,
91
+ pick: async (labels) => {
92
+ await ran;
93
+ const { seedId } = await import('@ultimat3/entity');
94
+ const picked: Record<string, SeededRow> = {};
95
+ for (const [alias, label] of Object.entries(labels)) {
96
+ const row = rows.get(seedId(label));
97
+ assert(
98
+ row !== undefined,
99
+ `seed "${name}" wrote no row labelled "${label}"`,
100
+ `give the row id: id('${label}') in the seed "${name}" declares, or pick a label it writes`,
101
+ );
102
+ picked[alias] = row;
103
+ }
104
+ return picked as { readonly [K in keyof typeof labels]: SeededRow };
105
+ },
106
+ };
107
+ handles.set(name, handle);
108
+ return handle;
109
+ };
110
+ };
111
+ }
@@ -1,6 +1,6 @@
1
1
  // The `statements` fixture: every statement the test issues, counted by shape — and a shape that
2
- // repeats past the threshold throws where it happened, so an N+1 fails the test that caused it
3
- // instead of warning in a dev server nobody is watching.
2
+ // repeats past the threshold is a verdict raised when the fixture is disposed, so an N+1 fails the
3
+ // test that caused it instead of warning in a dev server nobody is watching.
4
4
  //
5
5
  // Both drivers report here: Postgres per statement, `memoryRepo` per repository operation, so a
6
6
  // loop in a unit test on the in-memory driver is the same verdict under the same `entity.op`.
@@ -8,7 +8,8 @@
8
8
  // Strict by construction: there is no `strict: true` to remember, because a fixture nobody
9
9
  // destructured is a fixture nobody built. Opting in is naming `statements` in the test body.
10
10
 
11
- import type { StatementAttribution, StatementEvent, StatementObserver } from '@ultimat3/db';
11
+ import type { DbStatementEvent, StatementAttribution } from '@ultimat3/core';
12
+ import { captureStatementStacks, subscribe, type UltimateError } from '@ultimat3/core';
12
13
 
13
14
  /** One statement, as this fixture kept it. Bound values are deliberately not retained. */
14
15
  export interface ObservedStatement {
@@ -32,10 +33,12 @@ export interface StatementShape {
32
33
  }
33
34
 
34
35
  /**
35
- * `Disposable`: the observer seam is process-global, so the fixture hands back whatever it found —
36
- * the state, not a fixed default, exactly as `network` and `runJobs` do.
36
+ * `Disposable`: disposal unsubscribes from the bus and THROWS the first verdict, so the test fails
37
+ * at its own teardown. `verdicts()` reads them before that.
37
38
  */
38
39
  export interface TestStatements extends Disposable {
40
+ /** Every N+1 verdict so far — one `X_N_PLUS_ONE_QUERY`/`_WRITE` per shape, in the order crossed. */
41
+ verdicts(): readonly UltimateError[];
39
42
  /** Every statement issued since the fixture was built, in order. */
40
43
  all(): readonly ObservedStatement[];
41
44
  /** How many of one shape, or of everything when asked with no fingerprint. */
@@ -52,7 +55,7 @@ interface ShapeTally {
52
55
  count: number;
53
56
  /** The ones no `expectedQueryLoop()` scope covered — the only ones a verdict may count. */
54
57
  unexpected: number;
55
- /** Whether this shape has already thrown. The flag, not the count, so it throws exactly once. */
58
+ /** Whether this shape already has its verdict. The flag, not the count: one verdict per shape. */
56
59
  failed: boolean;
57
60
  }
58
61
 
@@ -73,13 +76,12 @@ interface ShapeTally {
73
76
  * sent, still observed, and still reported by `count()` and `shapes()`, because a test asserting
74
77
  * "this page issues two statements" must not see a different number depending on who declared what.
75
78
  *
76
- * **It throws where the loop happened, once per shape.** `@ultimat3/db`'s seam deliberately lets a
77
- * throw from `onStatement` propagate to whoever ran the statement, which is what makes the failing
78
- * line the loop's own line rather than a summary at teardown. Once a shape has thrown it keeps
79
- * counting silently: a test that catches the error gets one failure at the statement that crossed
80
- * the threshold, not one per statement after it, and `shapes()` still reports the whole loop. The
81
- * consequence worth knowing is the same one Bullet's `raise` has — a body that swallows every error
82
- * swallows this one too, and `shapes()` is what names the loop in that test.
79
+ * **The verdict is raised at disposal, once per shape.** A `db.statement` subscriber's throw is
80
+ * CONTAINED by the bus — an observer can never fail the work it observes — so the fixture records
81
+ * the `X_N_PLUS_ONE_*` error when a shape crosses the threshold and throws the first one when it is
82
+ * disposed (`using`, or the registered fixture's teardown). The loop runs to its end and every
83
+ * statement is counted; a body that swallows every error cannot swallow this one, because it is
84
+ * raised after the body. The error names the shape and its count, which is what points at the loop.
83
85
  *
84
86
  * The threshold is `@ultimat3/entity`'s `N_PLUS_ONE_THRESHOLD` and there is no knob: a loop that
85
87
  * fails a test and a loop that warns in `x dev` have to be the same loop.
@@ -89,48 +91,55 @@ export async function testStatements(): Promise<TestStatements> {
89
91
  // names `statements` must not load the database layer or the entity registry to run.
90
92
  const db = await import('@ultimat3/db');
91
93
  const { N_PLUS_ONE_THRESHOLD, nPlusOne } = await import('@ultimat3/entity');
92
- // Captured before the overwrite: the seam holds one observer, not a list, so an outer diagnostic
93
- // is displaced for the length of this test and put back after it.
94
- const previous = db.statementObserver();
95
-
96
94
  const seen: ObservedStatement[] = [];
95
+ const verdicts: UltimateError[] = [];
96
+ let disposed = false;
97
97
  const tallies = new Map<string, ShapeTally>();
98
98
 
99
- const observer: StatementObserver = {
100
- onStatement(event: StatementEvent): void {
101
- const fingerprint = db.statementFingerprint(event);
102
- const kind = db.statementKind(event.text);
103
- seen.push({
104
- fingerprint,
105
- kind,
106
- text: event.text,
107
- attribution: event.attribution,
108
- expected: event.expected,
109
- });
110
- let tally = tallies.get(fingerprint);
111
- if (tally === undefined) {
112
- tally = { fingerprint, kind, count: 0, unexpected: 0, failed: false };
113
- tallies.set(fingerprint, tally);
114
- }
115
- tally.count += 1;
116
- if (event.expected !== undefined) return;
117
- // A statement that threw is still a statement: fifty identical timeouts are still a loop.
118
- tally.unexpected += 1;
119
- if (tally.failed || tally.unexpected < N_PLUS_ONE_THRESHOLD) return;
120
- tally.failed = true;
121
- // `@ultimat3/entity`'s error, never one composed here: the `fix:` names the `preload` the
122
- // schema's own relations spell, and a second answer to "what ends this loop" would be one
123
- // the schema never agreed to.
124
- throw nPlusOne({
125
- kind,
126
- subject: fingerprint,
127
- count: tally.unexpected,
128
- entity: event.attribution?.entity,
129
- op: event.attribution?.op,
130
- });
131
- },
99
+ const onStatement = (event: DbStatementEvent): void => {
100
+ const fingerprint = db.statementFingerprint(event);
101
+ const kind = db.statementKind(event.text);
102
+ seen.push({
103
+ fingerprint,
104
+ kind,
105
+ text: event.text,
106
+ attribution: event.attribution,
107
+ expected: event.expected,
108
+ });
109
+ let tally = tallies.get(fingerprint);
110
+ if (tally === undefined) {
111
+ tally = { fingerprint, kind, count: 0, unexpected: 0, failed: false };
112
+ tallies.set(fingerprint, tally);
113
+ }
114
+ tally.count += 1;
115
+ if (event.expected !== undefined) return;
116
+ // A statement that threw is still a statement: fifty identical timeouts are still a loop.
117
+ tally.unexpected += 1;
118
+ if (tally.failed || tally.unexpected < N_PLUS_ONE_THRESHOLD) return;
119
+ tally.failed = true;
120
+ // `@ultimat3/entity`'s error, never one composed here: the `fix:` names the `preload` the
121
+ // schema's own relations spell, and a second answer to "what ends this loop" would be one
122
+ // the schema never agreed to.
123
+ const verdict = nPlusOne({
124
+ kind,
125
+ subject: fingerprint,
126
+ count: tally.unexpected,
127
+ entity: event.attribution?.entity,
128
+ op: event.attribution?.op,
129
+ });
130
+ // The stack the crossing statement was SENT from, not this subscriber's: an awaited driver
131
+ // resumes with no caller frames, so only the funnel's capture names the looping line.
132
+ if (event.callerStack !== undefined) {
133
+ const frames = event.callerStack.split('\n').slice(1).join('\n');
134
+ verdict.stack = `${verdict.name}: ${verdict.message}\n${frames}`;
135
+ }
136
+ verdicts.push(verdict);
132
137
  };
133
- db.setStatementObserver(observer);
138
+ // A subscriber on the bus, beside any outer one (`x dev`'s ledger, a harness) — never displacing
139
+ // it, and released at dispose. It never throws: the bus would contain it.
140
+ const unsubscribe = subscribe('db.statement', (event) => onStatement(event.payload));
141
+ // For the fixture's lifetime only: a stack per statement is cost production never pays.
142
+ const releaseStacks = captureStatementStacks();
134
143
 
135
144
  return {
136
145
  all: (): readonly ObservedStatement[] => [...seen],
@@ -144,8 +153,15 @@ export async function testStatements(): Promise<TestStatements> {
144
153
  ? left.fingerprint.localeCompare(right.fingerprint)
145
154
  : right.count - left.count,
146
155
  ),
156
+ verdicts: (): readonly UltimateError[] => [...verdicts],
147
157
  [Symbol.dispose]: (): void => {
148
- db.setStatementObserver(previous);
158
+ unsubscribe();
159
+ releaseStacks();
160
+ // Once: an explicit dispose inside a `using` scope must not raise the same verdict twice.
161
+ if (disposed) return;
162
+ disposed = true;
163
+ const [first] = verdicts;
164
+ if (first !== undefined) throw first;
149
165
  },
150
166
  };
151
167
  }
@@ -28,7 +28,7 @@ export const FRAMEWORK_FIXTURE_NAMES = [
28
28
  'statements',
29
29
  // Moved here from `DRIVER_FIXTURE_NAMES` on 2026-08-20: the driver it was waiting for is
30
30
  // `subscribeDriver()`, and the framework can build one — a whole `sync` node in this
31
- // process, over the change source `@ultimat3/entity`'s `setRowObserver` gives it. The four left
31
+ // process, over the change source `@ultimat3/entity`'s `entity.row` event gives it. The four left
32
32
  // in that list all need something the framework genuinely cannot bundle: a browser, or a
33
33
  // second build.
34
34
  'subscribe',