@ultimat3/testing 31.48.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.48.0",
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.48.0",
51
- "@ultimat3/ai": "31.48.0",
52
- "@ultimat3/auth": "31.48.0",
53
- "@ultimat3/cache": "31.48.0",
54
- "@ultimat3/core": "31.48.0",
55
- "@ultimat3/db": "31.48.0",
56
- "@ultimat3/entity": "31.48.0",
57
- "@ultimat3/http": "31.48.0",
58
- "@ultimat3/i18n": "31.48.0",
59
- "@ultimat3/jobs": "31.48.0",
60
- "@ultimat3/mail": "31.48.0",
61
- "@ultimat3/notify": "31.48.0",
62
- "@ultimat3/policy": "31.48.0",
63
- "@ultimat3/pwa": "31.48.0",
64
- "@ultimat3/query": "31.48.0",
65
- "@ultimat3/realtime": "31.48.0",
66
- "@ultimat3/render": "31.48.0",
67
- "@ultimat3/schema": "31.48.0",
68
- "@ultimat3/scraping": "31.48.0",
69
- "@ultimat3/seo": "31.48.0",
70
- "@ultimat3/time": "31.48.0"
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,12 +11,12 @@ 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 {
@@ -101,28 +101,6 @@ const refuse = (step: string, output: string): E2eAppFailedError =>
101
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',
102
102
  });
103
103
 
104
- /** Create the scratch database on the admin URL; answers its own URL and its drop. */
105
- async function scratchDatabase(adminUrl: string) {
106
- const name = `x_drill_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
107
- const admin = new Bun.SQL(adminUrl);
108
- try {
109
- await admin.unsafe(`create database ${name}`);
110
- } finally {
111
- await admin.close();
112
- }
113
- return {
114
- url: urlFor(adminUrl, name),
115
- async drop(): Promise<void> {
116
- const again = new Bun.SQL(adminUrl);
117
- try {
118
- await again.unsafe(dropSql(name));
119
- } finally {
120
- await again.close();
121
- }
122
- },
123
- };
124
- }
125
-
126
104
  async function waitReady(url: string, deadlineMs: number, alive: () => boolean): Promise<boolean> {
127
105
  const until = performance.now() + deadlineMs;
128
106
  while (performance.now() < until && alive()) {
@@ -282,11 +260,23 @@ export async function startDrillFleet(options: DrillFleetOptions): Promise<Drill
282
260
  };
283
261
  return { base: webBase, databaseUrl: database.url, proxies, roles, rollout, stop };
284
262
  } catch (error) {
285
- await stop();
286
- throw error;
263
+ return stopAfterFailedStart(error, stop);
287
264
  }
288
265
  }
289
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
+
290
280
  /** A role's exit, or `null` past `withinMs`: SIGKILLed then, so a wedged drain ends the drill. */
291
281
  export async function exitWithin(role: DrillRoleProcess, withinMs: number): Promise<number | null> {
292
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
+ }
@@ -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';
@@ -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
  /**