@ultimat3/testing 31.47.1 → 31.49.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
@@ -60,7 +60,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
60
60
  | `fault-proxy.ts` | `faultProxy({ target })` — a Bun TCP proxy whose mode switches mid-run: `pass`, `delay(ms)`, `blackhole` (bytes held, never dropped), `reset`, `refuse` |
61
61
  | `drills.ts` · `drill-verdict.ts` | the nine fault drills (`x drill`) and the verdict over evidence alone; a property with no evidence is red, and an answer may reach the load `DRILL_ANSWER_SLACK_MS` (500) past the deadline it was given by |
62
62
  | `drill-fleet.ts` · `drill-run.ts` | `startDrillFleet` — `web`, `worker` (and `sync` for `nats-down`) as processes on a scratch database, every service behind a proxy; `runDrill` — baseline, fault, recovery, judged |
63
- | `drill-rollout.ts` · `drill-rollout-verdict.ts` · `drill-output.ts` | `roll-before-migrate`: `startDrillFleet({ beforeMigrate: { rewind, watch } })` migrates, runs the caller's `rewind`, starts `web`, `worker` and `scheduler` unready and counts each output line naming `watch`; `runRollout` waits for every role to meet the schema, runs `fleet.rollout.migrate()`, asks each `/readyz` — `roles-wait`, `serves-after-migrate`, `one-wait-line` |
63
+ | `drill-rollout.ts` · `drill-rollout-verdict.ts` · `drill-output.ts` | `roll-before-migrate`: `startDrillFleet({ beforeMigrate: { rewind, watch } })` migrates, runs the caller's `rewind`, starts the roles `drillRoles(drill, found)` names (`web`, `worker`, `scheduler`, then `sync` on a bus and `replicator` on a logical server; `drillRolesNotPlayed` states the rest) unready and counts each output line naming `watch`; `runRollout` waits for every role to meet the schema, runs `fleet.rollout.migrate()`, asks each `/readyz` — `roles-wait`, `serves-after-migrate`, `one-wait-line` |
64
64
  | `drill-load.ts` · `drill-writes.ts` | the load's lanes; `drillWriteTargets` — every action an anonymous POST reaches, each request a fresh seeded draw with the app's `exercise.ts` override, so a job enqueued over HTTP is on the table for `worker-sigkill`/`worker-sigterm` |
65
65
  | `drill-sync.ts` | `startDrillSync` — the sync-client lane: `hello`, resubscribe, redial on a drop, every `replay-gap` counted; `sync-resumes` reads it |
66
66
  | `tenant-proof-report.ts` | `tenantProofFindings` — one coded finding per crossing (`X_TENANT_LEAK`, `X_TENANT_WRITE_CROSSED`), `tenantFindingLines` the human lines. Paths, tables and seeded ids, never a bound value |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.47.1",
3
+ "version": "31.49.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,27 +47,27 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.47.1",
51
- "@ultimat3/ai": "31.47.1",
52
- "@ultimat3/auth": "31.47.1",
53
- "@ultimat3/cache": "31.47.1",
54
- "@ultimat3/core": "31.47.1",
55
- "@ultimat3/db": "31.47.1",
56
- "@ultimat3/entity": "31.47.1",
57
- "@ultimat3/http": "31.47.1",
58
- "@ultimat3/i18n": "31.47.1",
59
- "@ultimat3/jobs": "31.47.1",
60
- "@ultimat3/mail": "31.47.1",
61
- "@ultimat3/notify": "31.47.1",
62
- "@ultimat3/policy": "31.47.1",
63
- "@ultimat3/pwa": "31.47.1",
64
- "@ultimat3/query": "31.47.1",
65
- "@ultimat3/realtime": "31.47.1",
66
- "@ultimat3/render": "31.47.1",
67
- "@ultimat3/schema": "31.47.1",
68
- "@ultimat3/scraping": "31.47.1",
69
- "@ultimat3/seo": "31.47.1",
70
- "@ultimat3/time": "31.47.1"
50
+ "@ultimat3/action": "31.49.0",
51
+ "@ultimat3/ai": "31.49.0",
52
+ "@ultimat3/auth": "31.49.0",
53
+ "@ultimat3/cache": "31.49.0",
54
+ "@ultimat3/core": "31.49.0",
55
+ "@ultimat3/db": "31.49.0",
56
+ "@ultimat3/entity": "31.49.0",
57
+ "@ultimat3/http": "31.49.0",
58
+ "@ultimat3/i18n": "31.49.0",
59
+ "@ultimat3/jobs": "31.49.0",
60
+ "@ultimat3/mail": "31.49.0",
61
+ "@ultimat3/notify": "31.49.0",
62
+ "@ultimat3/policy": "31.49.0",
63
+ "@ultimat3/pwa": "31.49.0",
64
+ "@ultimat3/query": "31.49.0",
65
+ "@ultimat3/realtime": "31.49.0",
66
+ "@ultimat3/render": "31.49.0",
67
+ "@ultimat3/schema": "31.49.0",
68
+ "@ultimat3/scraping": "31.49.0",
69
+ "@ultimat3/seo": "31.49.0",
70
+ "@ultimat3/time": "31.49.0"
71
71
  },
72
72
  "peerDependencies": {
73
73
  "solid-js": "^1.9.18"
@@ -4,6 +4,7 @@
4
4
  import type {
5
5
  AuthCodeRecord,
6
6
  AuthGrantRecord,
7
+ AuthServerClient,
7
8
  AuthTokenRecord,
8
9
  DeviceCodeRecord,
9
10
  } from '@ultimat3/auth/adapter';
@@ -67,3 +68,15 @@ export const deviceRecord = (deviceCodeHash: string, userCodeHash: string): Devi
67
68
  createdAt: at(0),
68
69
  expiresAt: at(600),
69
70
  });
71
+
72
+ export const clientRecord = (clientId: string, createdAt: Date): AuthServerClient => ({
73
+ clientId,
74
+ name: clientId,
75
+ secretHash: null,
76
+ authMethod: 'none',
77
+ redirectUris: ['https://app.test/cb'],
78
+ grantTypes: ['authorization_code', 'refresh_token'],
79
+ scopes: [],
80
+ resources: [],
81
+ createdAt,
82
+ });
@@ -7,6 +7,7 @@ import { expect, test } from 'bun:test';
7
7
  import type { AuthServerStore } from '@ultimat3/auth/adapter';
8
8
  import {
9
9
  at,
10
+ clientRecord,
10
11
  codeRecord,
11
12
  deviceRecord,
12
13
  grantRecord,
@@ -195,6 +196,52 @@ export const AUTH_SERVER_STORE_CHECKS: readonly AuthServerStoreCheck[] = [
195
196
  expect((await store.getGrant(live))?.id).toBe(live);
196
197
  },
197
198
  },
199
+ {
200
+ // Restates `@ultimat3/auth`'s own purge-of-clients case (authorization-server-purge-fixture.ts,
201
+ // test-only there), under ids of its own: a shared table holds every check's rows.
202
+ name: 'purge deletes a self-registered client past the idle window that nothing names, only it',
203
+ async run(store) {
204
+ const id = (label: string): string => `d_${idOf(label)}`;
205
+ const [old, granted, young, pending, device] = [
206
+ id('old'),
207
+ id('granted'),
208
+ id('young'),
209
+ id('code'),
210
+ id('device'),
211
+ ];
212
+ const staticOld = idOf('static-old');
213
+ for (const [clientId, created] of [
214
+ [staticOld, at(0)],
215
+ [old, at(0)],
216
+ [granted, at(0)],
217
+ [young, at(600)],
218
+ [pending, at(0)],
219
+ [device, at(0)],
220
+ ] as const) {
221
+ await store.putClient(clientRecord(clientId, created));
222
+ }
223
+ await store.putGrant({
224
+ ...grantRecord(idOf('grant'), idOf('subject'), granted),
225
+ refreshedAt: at(900),
226
+ });
227
+ await store.putCode({
228
+ ...codeRecord(idOf('code'), idOf('grant')),
229
+ clientId: pending,
230
+ expiresAt: at(2000),
231
+ });
232
+ await store.putDevice({
233
+ ...deviceRecord(idOf('device'), idOf('user-code')),
234
+ clientId: device,
235
+ createdAt: at(900),
236
+ expiresAt: at(2000),
237
+ });
238
+ expect(await store.purge(at(1000), at(500))).toBeGreaterThanOrEqual(1);
239
+ expect(await store.getClient(old)).toBeNull();
240
+ for (const kept of [staticOld, granted, young, pending, device]) {
241
+ expect((await store.getClient(kept))?.clientId).toBe(kept);
242
+ }
243
+ },
244
+ },
198
245
  ];
199
246
 
200
247
  export const authServerStoreConformance: SharedExamples<
@@ -1,6 +1,7 @@
1
- // The two ways a fault drill ends red. Declared in `errors.ts` with this package's codes, thrown
1
+ // The three ways a fault drill ends red. Declared in `errors.ts` with this package's codes, thrown
2
2
  // from here: a drill whose service is missing is REFUSED, never skipped — a green drill that ran
3
- // nothing is the vacuous pass — and a drill whose property failed names the property and evidence.
3
+ // nothing is the vacuous pass — a drill whose property failed names the property and evidence, and
4
+ // a scratch database the teardown could not drop is named with the paste that drops it.
4
5
 
5
6
  import { renderCauseValue, renderFixShellArg, UltimateError } from '@ultimat3/core';
6
7
  import type { DrillFailure } from './drill-verdict';
@@ -43,3 +44,37 @@ export class DrillFailedError extends UltimateError {
43
44
  });
44
45
  }
45
46
  }
47
+
48
+ /** A paste that does by hand what the drop could not: terminate the slot holder, then drop. */
49
+ function dropFix(adminUrl: string, database: string): string {
50
+ const url = new URL(adminUrl);
51
+ const db = renderFixShellArg(database, '<database>');
52
+ const host = renderFixShellArg(url.hostname, '<host>');
53
+ const port = renderFixShellArg(url.port || '5432', '<port>');
54
+ const user = renderFixShellArg(decodeURIComponent(url.username), '<user>');
55
+ const admin = renderFixShellArg(url.pathname.slice(1) || 'postgres', '<admin database>');
56
+ return (
57
+ `psql -h ${host} -p ${port} -U ${user} -d ${admin}` +
58
+ ` -c "select pg_terminate_backend(active_pid) from pg_replication_slots where database = '${db}'"` +
59
+ ` -c 'select pg_sleep(1)' -c 'DROP DATABASE IF EXISTS ${db} WITH (FORCE)'`
60
+ );
61
+ }
62
+
63
+ /**
64
+ * The fleet's scratch database outlived its drop: a slot still held after its holder was
65
+ * terminated, or the server refused. The password is never in the fix — psql asks for it.
66
+ */
67
+ export class DrillTeardownFailedError extends UltimateError {
68
+ constructor(input: {
69
+ readonly database: string;
70
+ readonly adminUrl: string;
71
+ readonly why: string;
72
+ }) {
73
+ super({
74
+ code: 'X_DRILL_TEARDOWN_FAILED',
75
+ cause: `x drill could not drop its scratch database ${renderCauseValue(input.database)}: ${input.why}; it is left on the server`,
76
+ fix: dropFix(input.adminUrl, input.database),
77
+ meta: { database: input.database },
78
+ });
79
+ }
80
+ }
@@ -11,17 +11,19 @@ import { tmpdir } from 'node:os';
11
11
  import { join } from 'node:path';
12
12
  import { tailOf } from './drill-output';
13
13
  import { probeStatus } from './drill-probe';
14
+ import { scratchDatabase } from './drill-scratch-db';
14
15
  import type { DrillRole, DrillService } from './drills';
15
16
  import { E2eAppFailedError } from './e2e-errors';
16
17
  import type { FaultProxy } from './fault-proxy';
17
18
  import { faultProxy, faultTarget, throughFaultProxy } from './fault-proxy';
18
19
  import { bindFreePorts, isPortClash } from './free-port-bind';
19
- import { dropSql, urlFor } from './template-db';
20
20
  import { testSealKeyEnv } from './test-seal-key';
21
21
 
22
22
  export interface DrillServiceUrls {
23
23
  /** A Postgres URL with rights to CREATE DATABASE: the drill's scratch database is made there. */
24
24
  readonly postgres: string;
25
+ /** That server runs `wal_level=logical`, so a replicator can stream from the scratch database. */
26
+ readonly logicalPostgres?: boolean | undefined;
25
27
  readonly redis?: string | undefined;
26
28
  /** NATS, and the variable the app's `realtime.urlEnv` reads it from. */
27
29
  readonly nats?: { readonly url: string; readonly env: string } | undefined;
@@ -99,28 +101,6 @@ const refuse = (step: string, output: string): E2eAppFailedError =>
99
101
  fix: 'ROLE=web bun apps/web/server.ts # in the app root, with the same DATABASE_URL: read why the role will not start',
100
102
  });
101
103
 
102
- /** Create the scratch database on the admin URL; answers its own URL and its drop. */
103
- async function scratchDatabase(adminUrl: string) {
104
- const name = `x_drill_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
105
- const admin = new Bun.SQL(adminUrl);
106
- try {
107
- await admin.unsafe(`create database ${name}`);
108
- } finally {
109
- await admin.close();
110
- }
111
- return {
112
- url: urlFor(adminUrl, name),
113
- async drop(): Promise<void> {
114
- const again = new Bun.SQL(adminUrl);
115
- try {
116
- await again.unsafe(dropSql(name));
117
- } finally {
118
- await again.close();
119
- }
120
- },
121
- };
122
- }
123
-
124
104
  async function waitReady(url: string, deadlineMs: number, alive: () => boolean): Promise<boolean> {
125
105
  const until = performance.now() + deadlineMs;
126
106
  while (performance.now() < until && alive()) {
@@ -280,11 +260,23 @@ export async function startDrillFleet(options: DrillFleetOptions): Promise<Drill
280
260
  };
281
261
  return { base: webBase, databaseUrl: database.url, proxies, roles, rollout, stop };
282
262
  } catch (error) {
283
- await stop();
284
- throw error;
263
+ return stopAfterFailedStart(error, stop);
285
264
  }
286
265
  }
287
266
 
267
+ /**
268
+ * A start that failed stops what it began, then rethrows ITS error: the stop's own failure (a
269
+ * scratch database left behind) is a later, smaller fact, and replacing the start's refusal with it
270
+ * hid why the drill never ran.
271
+ */
272
+ export async function stopAfterFailedStart(
273
+ error: unknown,
274
+ stop: () => Promise<void>,
275
+ ): Promise<never> {
276
+ await Promise.allSettled([stop()]);
277
+ throw error;
278
+ }
279
+
288
280
  /** A role's exit, or `null` past `withinMs`: SIGKILLed then, so a wedged drain ends the drill. */
289
281
  export async function exitWithin(role: DrillRoleProcess, withinMs: number): Promise<number | null> {
290
282
  const exited = await Promise.race([role.exited(), Bun.sleep(withinMs).then(() => null)]);
@@ -0,0 +1,125 @@
1
+ // A drill's scratch database: created on the admin URL, dropped when the fleet stops. The drop
2
+ // waits out a logical slot a role's walsender still holds — postgres refuses `DROP DATABASE` on a
3
+ // database with an ACTIVE slot before `WITH (FORCE)` terminates anyone — then terminates the holder.
4
+
5
+ import { renderCauseValue, renderThrowable } from '@ultimat3/core';
6
+ import { DrillTeardownFailedError } from './drill-errors';
7
+ import { dropSql, urlFor } from './template-db';
8
+
9
+ /** The admin connection the drop runs on; injected so the unit tests need no server. */
10
+ export interface ScratchAdminSql {
11
+ query(
12
+ statement: string,
13
+ params?: readonly unknown[],
14
+ ): Promise<readonly Record<string, unknown>[]>;
15
+ close(): Promise<void>;
16
+ }
17
+
18
+ /**
19
+ * How many times the slots are asked again per wait, each ask holding the SERVER 50 ms — ~5 s, as
20
+ * realtime's `SLOT_RELEASE_POLLS`: a walsender whose socket closed exits in milliseconds. A count,
21
+ * not a clock: nothing waits on this process's timers, and a slot nobody holds costs one ask.
22
+ */
23
+ export const SCRATCH_SLOT_POLLS = 100;
24
+
25
+ const NAME = /^x_drill_[0-9a-f]{16}$/;
26
+
27
+ /** The slots on the database still held, with who holds them; the sleep runs only per held row. */
28
+ const HELD_SQL =
29
+ 'select slot_name, active_pid, pg_sleep(0.05) from pg_replication_slots ' +
30
+ 'where database = $1 and active_pid is not null';
31
+
32
+ const TERMINATE_SQL =
33
+ 'select pg_terminate_backend(active_pid) from pg_replication_slots ' +
34
+ 'where database = $1 and active_pid is not null';
35
+
36
+ interface Holder {
37
+ readonly slot: string;
38
+ readonly pid: number;
39
+ }
40
+
41
+ const holdersOf = (rows: readonly Record<string, unknown>[]): readonly Holder[] =>
42
+ rows.map((row) => ({
43
+ slot: typeof row['slot_name'] === 'string' ? row['slot_name'] : '<unnamed>',
44
+ pid: Number(row['active_pid']),
45
+ }));
46
+
47
+ /** Polls until no slot on the database is active, or the bound: then the last holders seen. */
48
+ async function awaitInactive(sql: ScratchAdminSql, name: string): Promise<readonly Holder[]> {
49
+ let holders: readonly Holder[] = [];
50
+ for (let poll = 0; poll < SCRATCH_SLOT_POLLS; poll += 1) {
51
+ holders = holdersOf(await sql.query(HELD_SQL, [name]));
52
+ if (holders.length === 0) return holders;
53
+ }
54
+ return holders;
55
+ }
56
+
57
+ const refused = (adminUrl: string, database: string, why: string): DrillTeardownFailedError =>
58
+ new DrillTeardownFailedError({ database, adminUrl, why });
59
+
60
+ /**
61
+ * Drop `name`: wait (bounded) for its slots to go inactive, terminate a holder that outlived the
62
+ * wait and wait again, then `DROP DATABASE … WITH (FORCE)`, which removes the inactive slot too.
63
+ */
64
+ export async function dropScratchDatabase(
65
+ sql: ScratchAdminSql,
66
+ name: string,
67
+ adminUrl: string,
68
+ ): Promise<void> {
69
+ if (!NAME.test(name)) {
70
+ throw refused(adminUrl, name, `${renderCauseValue(name)} is not a drill scratch database`);
71
+ }
72
+ // Every statement in one `try`: the admin session can drop during the wait, and Bun.SQL then
73
+ // rejects a poll or the terminate with a raw error the drill would otherwise print uncoded.
74
+ let holders: readonly Holder[];
75
+ try {
76
+ holders = await awaitInactive(sql, name);
77
+ if (holders.length > 0) {
78
+ await sql.query(TERMINATE_SQL, [name]);
79
+ holders = await awaitInactive(sql, name);
80
+ }
81
+ if (holders.length === 0) await sql.query(dropSql(name));
82
+ } catch (error) {
83
+ throw refused(adminUrl, name, renderThrowable(error));
84
+ }
85
+ if (holders.length > 0) {
86
+ const named = holders.map((holder) => `slot ${holder.slot} (pid ${String(holder.pid)})`);
87
+ throw refused(
88
+ adminUrl,
89
+ name,
90
+ `still used by an active logical replication slot after its holder was terminated: ${named.join(', ')}`,
91
+ );
92
+ }
93
+ }
94
+
95
+ const bunAdmin = (url: string): ScratchAdminSql => {
96
+ // Bun.SQL is the blessed Postgres client: no driver package.
97
+ const sql = new Bun.SQL(url);
98
+ return {
99
+ query: async (statement, params = []) => [...(await sql.unsafe(statement, [...params]))],
100
+ close: () => sql.close(),
101
+ };
102
+ };
103
+
104
+ /** Create the scratch database on the admin URL; answers its name, its URL and its drop. */
105
+ export async function scratchDatabase(adminUrl: string, connect = bunAdmin) {
106
+ const name = `x_drill_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
107
+ const admin = connect(adminUrl);
108
+ try {
109
+ await admin.query(`create database ${name}`);
110
+ } finally {
111
+ await admin.close();
112
+ }
113
+ return {
114
+ name,
115
+ url: urlFor(adminUrl, name),
116
+ async drop(): Promise<void> {
117
+ const again = connect(adminUrl);
118
+ try {
119
+ await dropScratchDatabase(again, name, adminUrl);
120
+ } finally {
121
+ await again.close();
122
+ }
123
+ },
124
+ };
125
+ }
@@ -22,8 +22,18 @@ export interface DrillDeclarations {
22
22
  readonly nats: { readonly env: string } | undefined;
23
23
  }
24
24
 
25
+ /** The `wal_level=logical` server `docker/test-services.env` publishes: the replicator's. */
26
+ const LOGICAL_POSTGRES_ENV = 'TEST_REPLICATION_URL';
27
+ /** Where the rollout order hands a bus the app itself does not declare. */
28
+ const DEFAULT_BUS_ENV = 'NATS_URL';
29
+
25
30
  type Env = Readonly<Record<string, string | undefined>>;
26
31
 
32
+ const present = (env: Env, name: string): string | undefined => {
33
+ const value = env[name]?.trim();
34
+ return value === undefined || value === '' ? undefined : value;
35
+ };
36
+
27
37
  const read = (env: Env, name: string, drill: Drill): string => {
28
38
  const value = env[name]?.trim();
29
39
  if (value === undefined || value === '') {
@@ -60,8 +70,24 @@ export function drillServices(
60
70
  },
61
71
  });
62
72
  }
63
- const postgres = read(env, DRILL_SERVICE_ENV.postgres, drill);
64
73
  const redis = declared.redis ? read(env, DRILL_SERVICE_ENV.redis, drill) : undefined;
74
+ if (drill.fault.kind === 'order') {
75
+ // Every role that can start is played, so the bus and the logical server are taken when the
76
+ // run has them; without them the drill still plays what Postgres alone serves, and says so.
77
+ const logical = present(env, LOGICAL_POSTGRES_ENV);
78
+ const bus =
79
+ declared.nats === undefined
80
+ ? present(env, DRILL_SERVICE_ENV.nats)
81
+ : read(env, DRILL_SERVICE_ENV.nats, drill);
82
+ return {
83
+ postgres: logical ?? read(env, DRILL_SERVICE_ENV.postgres, drill),
84
+ logicalPostgres: logical !== undefined,
85
+ redis,
86
+ nats:
87
+ bus === undefined ? undefined : { url: bus, env: declared.nats?.env ?? DEFAULT_BUS_ENV },
88
+ };
89
+ }
90
+ const postgres = read(env, DRILL_SERVICE_ENV.postgres, drill);
65
91
  const nats =
66
92
  declared.nats === undefined
67
93
  ? undefined
package/src/drills.ts CHANGED
@@ -9,10 +9,11 @@ import type { FaultMode } from './fault-proxy';
9
9
  export type DrillService = 'postgres' | 'redis' | 'nats';
10
10
 
11
11
  /**
12
- * A role the fleet runs as its own process (`ROLE`, `apps/web/server.ts`); `sync` only for a drill
13
- * whose sync client needs a node to dial, `scheduler` only for the rollout-order drill.
12
+ * A role the fleet runs as its own process (`ROLE`, `apps/web/server.ts`); `sync` for a drill whose
13
+ * sync client needs a node to dial and for the rollout order, `scheduler` and `replicator` for the
14
+ * rollout order alone.
14
15
  */
15
- export type DrillRole = 'web' | 'worker' | 'sync' | 'scheduler';
16
+ export type DrillRole = 'web' | 'worker' | 'sync' | 'scheduler' | 'replicator';
16
17
 
17
18
  export type DrillName =
18
19
  | 'pg-blackhole'
@@ -111,15 +112,60 @@ export const DRILL_NAMES: readonly DrillName[] = DRILLS.map((drill) => drill.nam
111
112
  export const drillNamed = (name: string): Drill | undefined =>
112
113
  DRILLS.find((drill) => drill.name === name);
113
114
 
115
+ /** What this run can start beyond the roles Postgres alone serves. */
116
+ export interface DrillRoleFacts {
117
+ /** A NATS server: `sync` needs a bus. */
118
+ readonly bus: boolean;
119
+ /** The scratch database sits on a `wal_level=logical` server: the replicator streams from it. */
120
+ readonly logicalPostgres: boolean;
121
+ /** The app declares an entity on a table: with none, the replicator refuses to boot. */
122
+ readonly publishable: boolean;
123
+ }
124
+
125
+ /** A role the rollout order did not start, and what would have let it. */
126
+ export interface DrillRoleNotPlayed {
127
+ readonly role: DrillRole;
128
+ readonly needs: string;
129
+ }
130
+
131
+ const POSTGRES_ONLY: DrillRoleFacts = { bus: false, logicalPostgres: false, publishable: false };
132
+
133
+ /** The rollout order's roles beyond `web`, `worker` and `scheduler`, each with its gap if any. */
134
+ const rolloutExtras = (
135
+ found: DrillRoleFacts,
136
+ ): readonly (DrillRoleNotPlayed & { gap: boolean })[] => [
137
+ { role: 'sync', needs: 'TEST_NATS_URL', gap: !found.bus },
138
+ found.publishable
139
+ ? { role: 'replicator', needs: 'TEST_REPLICATION_URL', gap: !found.logicalPostgres }
140
+ : { role: 'replicator', needs: 'an entity on a table', gap: true },
141
+ ];
142
+
114
143
  /**
115
144
  * The roles a drill's fleet runs: a sync client needs the sync node it dials; the rollout order is
116
- * played on every role Postgres alone serves (`replicator` needs a logical server, `sync` a bus).
145
+ * played on every role this run can start, since each one meets the same behind schema.
117
146
  */
118
- export const drillRoles = (drill: Drill): readonly DrillRole[] => {
119
- if (drill.fault.kind === 'order') return ['web', 'worker', 'scheduler'];
147
+ export const drillRoles = (
148
+ drill: Drill,
149
+ found: DrillRoleFacts = POSTGRES_ONLY,
150
+ ): readonly DrillRole[] => {
151
+ if (drill.fault.kind === 'order') {
152
+ const extras = rolloutExtras(found).filter((extra) => !extra.gap);
153
+ return ['web', 'worker', 'scheduler', ...extras.map((extra) => extra.role)];
154
+ }
120
155
  return drill.holds.includes('sync-resumes') ? ['web', 'worker', 'sync'] : ['web', 'worker'];
121
156
  };
122
157
 
158
+ /** The rollout-order roles this run leaves out: stated in the report, never dropped silently. */
159
+ export const drillRolesNotPlayed = (
160
+ drill: Drill,
161
+ found: DrillRoleFacts,
162
+ ): readonly DrillRoleNotPlayed[] =>
163
+ drill.fault.kind === 'order'
164
+ ? rolloutExtras(found)
165
+ .filter((extra) => extra.gap)
166
+ .map(({ role, needs }) => ({ role, needs }))
167
+ : [];
168
+
123
169
  /** The service a drill needs running, when it needs one beyond Postgres. */
124
170
  export const drillService = (drill: Drill): DrillService | undefined =>
125
171
  drill.fault.kind === 'service' ? drill.fault.service : undefined;
@@ -4,7 +4,18 @@
4
4
 
5
5
  import { expect } from 'bun:test';
6
6
  import { isUltimateError } from '@ultimat3/core';
7
- import { decimal, entity, integer, json, money, t, text, timestamp, uuid } from '@ultimat3/entity';
7
+ import {
8
+ bigint,
9
+ decimal,
10
+ entity,
11
+ integer,
12
+ json,
13
+ money,
14
+ t,
15
+ text,
16
+ timestamp,
17
+ uuid,
18
+ } from '@ultimat3/entity';
8
19
  import { remember } from './entity-conformance-entities';
9
20
  import { checkOver, idAt } from './entity-conformance-support';
10
21
  import type { EntityDriverCheck } from './entity-driver-conformance';
@@ -49,6 +60,10 @@ const rates = remember(
49
60
  }),
50
61
  );
51
62
 
63
+ const totals = remember(
64
+ entity('ec_a_totals', { columns: { id: uuid().primaryKey(), n: bigint() } }),
65
+ );
66
+
52
67
  const ORG = idAt('a1');
53
68
  const OTHER_ORG = idAt('a2');
54
69
  const [POST_A, POST_B, POST_C] = [idAt('aaa'), idAt('bbb'), idAt('ccc')];
@@ -207,4 +222,31 @@ const extremes: readonly EntityDriverCheck[] = [
207
222
  ),
208
223
  ];
209
224
 
210
- export const AGGREGATE_CHECKS: readonly EntityDriverCheck[] = [...countBy, ...extremes];
225
+ /** Nineteen digits: past it Postgres' own `avg(bigint)` has no fraction digits left to answer in. */
226
+ const NINETEEN = 9_000_000_000_000_000_000n;
227
+
228
+ const means: readonly EntityDriverCheck[] = [
229
+ checkOver(
230
+ { totals },
231
+ 'avg over 19-digit bigints keeps six decimals',
232
+ async (db) => {
233
+ // Ten rows of N and one of N + 5: the mean is N + 5/11 = N.454545(45…), which rounds DOWN
234
+ // at six places — and up, wrongly, in a division that rounded once at seven first.
235
+ for (let index = 0; index < 11; index += 1) {
236
+ const n = (index === 10 ? NINETEEN + 5n : NINETEEN).toString();
237
+ await db.totals.insert({ id: idAt(index + 1), n });
238
+ }
239
+ expect(await db.totals.avg('n')).toBe('9000000000000000000.454545');
240
+ expect(await db.totals.aggregate({ mean: { fn: 'avg', column: 'n' } })).toEqual({
241
+ mean: '9000000000000000000.454545',
242
+ });
243
+ // Two rows one apart: the half the server's own scale dropped.
244
+ const pair = db.totals.andWhere('id', 'in', [idAt(10), idAt(11)]);
245
+ expect(await pair.avg('n')).toBe('9000000000000000002.500000');
246
+ expect(await db.totals.andWhere('n', 'lt', 0).avg('n')).toBeNull();
247
+ },
248
+ ['aggregate:avg'],
249
+ ),
250
+ ];
251
+
252
+ export const AGGREGATE_CHECKS: readonly EntityDriverCheck[] = [...countBy, ...extremes, ...means];
@@ -188,6 +188,31 @@ const writes: readonly EntityDriverCheck[] = [
188
188
  ]);
189
189
  },
190
190
  ),
191
+ checkOver(
192
+ { uniques },
193
+ 'a batch whose end state is unique but whose order meets a stored value moves no row',
194
+ async (db) => {
195
+ await db.uniques.insertAll([
196
+ { id: 'a', slug: 'x' },
197
+ { id: 'b', slug: 'y' },
198
+ { id: 'c', slug: 'q' },
199
+ ]);
200
+ // `c` takes `b`'s value before `b` lets it go: Postgres checks a plain unique per row, so the
201
+ // one statement is refused and rolled back whole — `a`'s new value included.
202
+ const shift = () =>
203
+ db.uniques.updateMany([
204
+ { id: 'a', patch: { slug: 'w' } },
205
+ { id: 'c', patch: { slug: 'y' } },
206
+ { id: 'b', patch: { slug: 'z' } },
207
+ ]);
208
+ expect(await codeOf(shift)).toBe('X_DB_UNIQUE_VIOLATION');
209
+ expect((await db.uniques.orderBy('id').all()).map((row) => row.slug)).toEqual([
210
+ 'x',
211
+ 'y',
212
+ 'q',
213
+ ]);
214
+ },
215
+ ),
191
216
  checkOver(
192
217
  { broad },
193
218
  'a 200-row, 600-column updateMany past the bind ceiling lands every patch, or none of them',
package/src/errors.ts CHANGED
@@ -83,6 +83,7 @@ export const TESTING_ERROR_CODES = [
83
83
  'X_TEST_SOAK_HEAP_GROWTH',
84
84
  'X_TEST_TEMP_TREE_LEFT',
85
85
  'X_TEST_ISLAND_BUILD_REUSED',
86
+ 'X_DRILL_TEARDOWN_FAILED',
86
87
  ] as const;
87
88
 
88
89
  export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
@@ -169,6 +170,7 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
169
170
  X_TEST_SOAK_HEAP_GROWTH: 'a soak() run grew the live heap past its stated bound',
170
171
  X_TEST_TEMP_TREE_LEFT: 'a temp tree survived its own remove',
171
172
  X_TEST_ISLAND_BUILD_REUSED: 'an island builder answered the shipped build with the coverage one',
173
+ X_DRILL_TEARDOWN_FAILED: 'a fault drill could not drop its scratch database',
172
174
  };
173
175
 
174
176
  // Titles must be registered for `format()` to render the contract's first line. Every code above is
package/src/index.ts CHANGED
@@ -71,7 +71,11 @@ export {
71
71
  // `x drill` (plan 101 / 40): the nine fault drills, the fleet they run on, the verdict over evidence.
72
72
  export type { DrillConfig, DrillTiming } from './drill-budgets';
73
73
  export { drillBudgets } from './drill-budgets';
74
- export { DrillFailedError, DrillServiceMissingError } from './drill-errors';
74
+ export {
75
+ DrillFailedError,
76
+ DrillServiceMissingError,
77
+ DrillTeardownFailedError,
78
+ } from './drill-errors';
75
79
  export type { DrillFleet, DrillRoleProcess, DrillRollout, DrillServiceUrls } from './drill-fleet';
76
80
  export { startDrillFleet } from './drill-fleet';
77
81
  export { bunDrillSql } from './drill-jobs';
@@ -89,8 +93,15 @@ export type { DrillBudgets, DrillEvidence, DrillFailure, DrillProperty } from '.
89
93
  export { judgeDrill } from './drill-verdict';
90
94
  export type { DrillWrites } from './drill-writes';
91
95
  export { drillWriteTargets } from './drill-writes';
92
- export type { Drill, DrillName, DrillRole, DrillService } from './drills';
93
- export { DRILL_NAMES, DRILLS, drillNamed, drillRoles } from './drills';
96
+ export type {
97
+ Drill,
98
+ DrillName,
99
+ DrillRole,
100
+ DrillRoleFacts,
101
+ DrillRoleNotPlayed,
102
+ DrillService,
103
+ } from './drills';
104
+ export { DRILL_NAMES, DRILLS, drillNamed, drillRoles, drillRolesNotPlayed } from './drills';
94
105
  export type { A11yFinding, A11yRule } from './e2e-a11y';
95
106
  export { auditTree, NAMED_ROLES } from './e2e-a11y';
96
107
  export type { A11yAllow, A11yOptions } from './e2e-a11y-run';
@@ -11,7 +11,7 @@ export class TestPolicyExpectedError extends UltimateError {
11
11
  super({
12
12
  code: 'X_TEST_POLICY_EXPECTED',
13
13
  cause: `toDenyPolicy expects a policy — an object with run() (@ultimat3/policy) or evaluate() — and received ${describeValue(received)}`,
14
- fix: "expect(post.policy).toDenyPolicy(ctx) — pass the policy object (@ultimat3/policy's, with run() or evaluate()), never the action or its result",
14
+ fix: "expect(post.policy).toDenyPolicy(ctx) // pass the policy object (@ultimat3/policy's, with run() or evaluate()), never the action or its result",
15
15
  });
16
16
  }
17
17
  }
@@ -22,18 +22,29 @@ export class TestOpenApiExpectedError extends UltimateError {
22
22
  super({
23
23
  code: 'X_TEST_OPENAPI_EXPECTED',
24
24
  cause: `toMatchOpenApi expects an OpenAPI document — an object with operations: [{ operationId, required? }] — and received ${describeValue(received)}`,
25
- fix: 'expect(await app.openapi()).toMatchOpenApi(committed) — the receiver is the generated document: an object with operations: [{ operationId, required? }]',
25
+ fix: 'expect(await app.openapi()).toMatchOpenApi(committed) // the receiver is the generated document: an object with operations: [{ operationId, required? }]',
26
26
  });
27
27
  }
28
28
  }
29
29
 
30
- /** `toBeWithinBudget` handed something that is not a finite number. */
30
+ /**
31
+ * `toBeWithinBudget` handed something that is not a finite number — as the measurement, or as the
32
+ * LIMIT: `budgets['renamedKey']` is `undefined`, and `x <= undefined` is false, so `.not` held.
33
+ */
31
34
  export class TestNumberExpectedError extends UltimateError {
32
- constructor(received: unknown) {
33
- super({
34
- code: 'X_TEST_NUMBER_EXPECTED',
35
- cause: `toBeWithinBudget expects a finite number to compare against the budget, and received ${describeValue(received)}`,
36
- fix: 'expect(bytes).toBeWithinBudget(limit) — pass the measured number itself, e.g. (await Bun.file(path).arrayBuffer()).byteLength, never a Promise or a string',
37
- });
35
+ constructor(received: unknown, side: 'measurement' | 'limit' = 'measurement') {
36
+ super(
37
+ side === 'limit'
38
+ ? {
39
+ code: 'X_TEST_NUMBER_EXPECTED',
40
+ cause: `toBeWithinBudget expects a finite number as the budget's limit, and was given ${describeValue(received)}`,
41
+ fix: "expect(bytes).toBeWithinBudget(budgets['<a key the table has>']) // the limit read undefined or NaN: name a key your budgets table declares",
42
+ }
43
+ : {
44
+ code: 'X_TEST_NUMBER_EXPECTED',
45
+ cause: `toBeWithinBudget expects a finite number to compare against the budget, and received ${describeValue(received)}`,
46
+ fix: 'expect(bytes).toBeWithinBudget(limit) // pass the measured number itself, e.g. (await Bun.file(path).arrayBuffer()).byteLength, never a Promise or a string',
47
+ },
48
+ );
38
49
  }
39
50
  }
package/src/matchers.ts CHANGED
@@ -269,6 +269,10 @@ const implementations: ExpectExtendMatchers<UltimateMatchers<unknown>> = {
269
269
  if (typeof received !== 'number' || !Number.isFinite(received)) {
270
270
  throw new TestNumberExpectedError(received);
271
271
  }
272
+ // The limit too: a renamed budget key reads `undefined`, and `received <= undefined` is false.
273
+ if (typeof limit !== 'number' || !Number.isFinite(limit)) {
274
+ throw new TestNumberExpectedError(limit, 'limit');
275
+ }
272
276
  return result(
273
277
  received <= limit,
274
278
  () => `expected ${received} to be within the budget of ${limit}`,
@@ -1,7 +1,7 @@
1
1
  // What every test starts from, put back by the preload before each one — the per-TEST half of
2
- // isolation, beside `file-boundary.ts`'s per-file half: the jobs event bus, which STORES what it is
3
- // handed (an answer one test published resumed the next test's waiting run), and the installed
4
- // rate-limit store, read per request (a bucket one test drained was the next test's 429).
2
+ // isolation, beside `file-boundary.ts`'s per-file half: the jobs event bus (it STORES what it is
3
+ // handed), the installed rate-limit store (a drained bucket was the next test's 429) and the
4
+ // once-per-operation wire-dates warn (a rerun in one process never saw its warn).
5
5
 
6
6
  import { beforeEach } from 'bun:test';
7
7
  import type { clearDefaultRateLimitBuckets } from '@ultimat3/http/adapter';
@@ -42,9 +42,9 @@ function resolvedFrom(pkg: string): string | null {
42
42
  const paths = new Map<string, string | null>();
43
43
 
44
44
  /**
45
- * Before each test: a fresh DEFAULT event bus and the DEFAULT rate-limit buckets emptied — each
46
- * only when its package is loaded. Already evaluated, so each import answers from the registry, the
47
- * same instance. Only the defaults: a bus or store installed for the file (`beforeAll`, a booted
45
+ * Before each test: a fresh DEFAULT event bus, the DEFAULT rate-limit buckets emptied and the
46
+ * wire-dates warn forgotten — each only when its package is loaded. Already evaluated, so each
47
+ * import answers from the registry, the same instance. Only the defaults: a bus or store installed for the file (`beforeAll`, a booted
48
48
  * app's) stays installed, and carries across that file's tests as it would in production.
49
49
  */
50
50
  export async function resetPerTestState(): Promise<void> {
@@ -62,6 +62,13 @@ export async function resetPerTestState(): Promise<void> {
62
62
  };
63
63
  http.clearDefaultRateLimitBuckets();
64
64
  }
65
+ const wireDates = loaded('@ultimat3/http', 'wire-dates-cap.ts');
66
+ if (wireDates !== undefined) {
67
+ // An internal seam, off the package's API on purpose: an app forgets nothing it warned about.
68
+ // Its name is held by `per-test-reset.test.ts`, which reds if this stops resetting the set.
69
+ const http = (await import(wireDates)) as { readonly resetWireDatesCap: () => void };
70
+ http.resetWireDatesCap();
71
+ }
65
72
  }
66
73
 
67
74
  /**