@ultimat3/testing 30.8.0 → 30.9.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/CLAUDE.md CHANGED
@@ -16,7 +16,7 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
16
16
  | No mocks of the DB | clone a template database; `template-db.ts` is the only DB path |
17
17
  | No wall clock | `withFrozenClock` / `advanceClock`; `Date.now()` is frozen by the preload |
18
18
  | Frozen ≠ different | `globalThis.Date` becomes a subclass; `FrozenDate[Symbol.hasInstance]` brands on the `[[DateValue]]` slot (`Date.prototype.getTime.call(value)` throws or not) |
19
- | No unmocked egress | `sealed-network.ts` seals `fetch`; `sealed-sockets.ts` `WebSocket`, `Bun.connect` (not loopback); `sealed-dns.ts` the three `lookup`s (a mocked host answers `MOCKED_HOST_ADDRESS`); a miss is `X_TEST_NETWORK_SEALED` |
19
+ | No unmocked egress | `sealed-network.ts` seals `fetch`; `sealed-sockets.ts` `WebSocket`, `Bun.connect`, `node:*`, UDP (not loopback); `sealed-dns*.ts` every resolver, named imports too (wiki `Testing.md`); a miss is `X_TEST_NETWORK_SEALED` |
20
20
  | One `mockFetch`, and it grows | a verb in the match, ordered answers, a pinned dial's name (`mock-route.ts`) and `requestLog` (`request-log.ts`). A stream bound for a real server logs `null` (teeing drains it). `original(input, init)` goes as handed: `tls`, `unix`, `proxy` are in no `Request`. `cassette()`: below |
21
21
  | Self is not egress | a port core's `markListening()` announced passes through — a socket test never unseals |
22
22
  | Offline is a state, not a mock | `network.offline()` / `.drop()` fail every dial, loopback too, as `X_TEST_NETWORK_OFFLINE` before any mock: the app's offline path runs |
@@ -35,7 +35,7 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
35
35
  | Every message thunk needs a test that PROVOKES it | a thunk is a function, so an unread message is an UNCOVERED function and `bun run scripts/coverage-gate.ts --package testing` is what says so |
36
36
  | Test names | the filename picks the step; a typed helper prefixes its own name. `testName(type, name)` is for an outer `describe` only — never on the inner `test` too, the prefix would print twice |
37
37
  | One body shape, five registrars | `test` (= `fixtureTest`), `unitTest`, `contractTest`, `liveTest`, `jobTest` all take `FixtureBody` + `{ timeoutMs }`: `unitTest('…', async ({ runJobs }) => …)`. Never `describe(testName('unit', …))` + `test` to get a fixture |
38
- | `runJobs` says who and what | `{ actor }` is the WORKER's identity (the org stays the job's declared tenant), `{ tenantId }` the enqueuer's row; `executions[n].result` is the body's return. A fresh event bus per fixture |
38
+ | `runJobs` says who and what | `{ actor }` is the WORKER's identity (the org stays the job's declared tenant), `{ tenantId }` the enqueuer's row; `executions[n].result` is the body's return. A fresh event bus per fixture. Bodies run on the preload's frozen clock (`ctx.clock`), so a `backfill()` throttle moves `Date.now()` instead of sleeping |
39
39
  | A `runJobs` pass is a real worker's `tick()` | `fixture-jobs.ts` builds an unstarted `jobWorker` per pass, so admission runs: `concurrency` waits and `whenBusy: 'fail'` refuses (`X_JOB_KEY_BUSY`) exactly as in a fleet. Full rule: `docs/history/testing.md` |
40
40
  | Per-test state is `per-test-reset.ts` | the app preload's `beforeEach` resets the jobs event bus — only when `@ultimat3/jobs` is already loaded, so the reset never loads it |
41
41
  | A `mock.module` ends with its file | `module-mock-boundary.ts` wraps it (and `vi.mock`/`jest.mock`): the real namespace is snapshotted on a file's first mock, so its top-level code RUNS, and mocked back at the boundary. A preload's mock is left. A real one that throws on load: the next file fails `X_TEST_MODULE_MOCK_UNRESTORABLE` |
@@ -51,7 +51,7 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
51
51
  | A passkey test signs for real | `softAuthenticator` is `@ultimat3/auth/soft-authenticator`'s, never re-exported here (one value, one path: `flight-copies`) and never a second one (auth's own suites need it, and auth cannot import testing) |
52
52
  | A reached job is crash-proven | `exercise-crash.ts`: `crashProof` with the control's input and actor, after the tenant proof; only `diverged` is red (`X_JOB_CRASH_DIVERGED`), its place `crashEffectPlace` (`inside` a step via jobs' `currentStep()`, or `after` one). Its world is `alone`: only the job's own row is claimed, a child is an `enqueue:` effect, never run. Committed: job bodies escape transactions |
53
53
  | The tenant proof is taint only | `tenant-proof.ts`: B, A, B; B is A's role minus `tenancy:cross`. Leak = seeded canary or unhanded id (`tenant-canary.ts`); write = moved digest. Only `crossed` is red |
54
- | Every statement the pass sent is planned | `plan-sweep.ts` (`sweepPlans`): first relation an app table, `PREPARE` in a READ-ONLY transaction with seq/bitmap scans and sorts off, judged by `plan-oracle.ts` (keys: `plan-sort-key.ts`, conditions: `plan-conditions.ts`); red = `X_QUERY_UNINDEXED` / `X_QUERY_SORT_UNSERVED` with the `indexes:` entry (`plan-sweep-fix.ts`). `scan:` or `expectedSeqScan` is exempt, listed; credited: a partial unique whose predicate the statement states, equality-then-range index under a limit, every `or` arm a declared index leads, a whole read a keyed join side probes by a declared index (`plan-probes.ts`); no generic plan is `X_QUERY_PLAN_UNAVAILABLE`, never a pass |
54
+ | Every statement the pass sent is planned | `plan-sweep.ts` (`sweepPlans`): first relation an app table, `PREPARE` in a READ-ONLY transaction with seq/bitmap scans off (sorts too, re-planned, for a limited read's sort), judged by `plan-oracle.ts` (keys: `plan-sort-key.ts`, conditions: `plan-conditions.ts`); red = `X_QUERY_UNINDEXED` / `X_QUERY_SORT_UNSERVED` with the `indexes:` entry (`plan-sweep-fix.ts`). `scan:` or `expectedSeqScan` is exempt, listed; credited: a partial unique whose predicate the statement states, equality-then-range index under a limit, every `or` arm a declared index leads, a whole read a keyed join side probes by a declared index (`plan-probes.ts`); no generic plan is `X_QUERY_PLAN_UNAVAILABLE`, never a pass |
55
55
  | A shape that grows with the rows is red | `scale-sweep-run.ts`: two more tenants at `SCALE_SIZES` (2, 8 rows a table), every reached primitive once in each; `judgeScale` (pure) reds `X_QUERY_SCALES_WITH_ROWS`. Under `expectedQueryLoop` it is listed with its reason |
56
56
  | An erase is PROVED, not asserted | `subject-proof.ts` (`subjectProof`, run by cli's `exercise-subject.ts`): canaries in every table, one person erased, every stored row searched; a survivor outside `retain` is `X_SUBJECT_ERASE_INCOMPLETE`, naming table and column, never the value |
57
57
  | A captured failure replays as a test | `repro.ts`: `reproduce(bundle, { driver })` seeds the rows it read, freezes the clock at its instant, invokes as its actor; masked fields are stood in (`repro-stand-in.ts`). An unregistered name ANSWERS as the failure. `reproJob(runJobs, failure)` for a dead job. What `x repro --write` emits |
@@ -121,9 +121,7 @@ Commands: `bun test`, `bunx tsc --noEmit -p tsconfig.json`.
121
121
  Entry points: `.` (the API), `./preload` (side effects for bunfig) and `./registry-isolation`
122
122
  (`isolateEntityRegistry()`, kept off `.` because it loads `@ultimat3/entity`).
123
123
 
124
- `fixture-island.ts`, `island-dom.ts`, `island-selector.ts` and `island-observers.ts` are on `.` and
125
- import `@ultimat3/core` and nothing else, so they cost a tier-0 test nothing. The whole-chain proof is
126
- `examples/dummy/apps/web/app/settings/settings.island.test.ts`. Full rule: `docs/history/testing.md`.
124
+ The island fixture's cost and its whole-chain proof: `docs/history/testing.md`.
127
125
 
128
126
  ## The browser-backed e2e driver (moved here from `@ultimat3/cli` in 22.0.0)
129
127
 
@@ -150,9 +148,7 @@ Raw CDP: `@ultimat3/core` and Bun, nothing else; `cli` imports it over `cli -> t
150
148
  | `packages/cli/src/verify-e2e.ts` | `withE2eApp` (cli's): in an app on a machine with Chrome, the `e2e` step runs the suite with that preload; otherwise exactly as before |
151
149
  | `cdp-errors.ts` | one constructor per way the browser half refuses |
152
150
 
153
- **Absent by default.** Nothing here runs until `installE2eDriver` is called, so `hasE2eDriver()`
154
- answers `false` and the gate's `e2e` step refuses rather than passing over a browser it lacks.
155
- GitHub-hosted `ubuntu-latest` ships Chrome at `/usr/bin/google-chrome`.
151
+ **Absent by default** until `installE2eDriver`: [`docs/history/testing.md`](../../docs/history/testing.md#the-browser-backed-e2e-driver-moved-here-from-ultimat3cli-in-2200).
156
152
 
157
153
  How the raw-CDP driver behaves — the pipe, the load event, deadlines, the lossy `evaluate`, the
158
154
  refusing `update()` — is [`docs/history/testing.md`](../../docs/history/testing.md#the-e2e-driver-in-brief-moved-2026-10-01).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "30.8.0",
3
+ "version": "30.9.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -46,21 +46,21 @@
46
46
  "test": "bun test"
47
47
  },
48
48
  "dependencies": {
49
- "@ultimat3/action": "30.8.0",
50
- "@ultimat3/cache": "30.8.0",
51
- "@ultimat3/core": "30.8.0",
52
- "@ultimat3/db": "30.8.0",
53
- "@ultimat3/entity": "30.8.0",
54
- "@ultimat3/http": "30.8.0",
55
- "@ultimat3/i18n": "30.8.0",
56
- "@ultimat3/jobs": "30.8.0",
57
- "@ultimat3/mail": "30.8.0",
58
- "@ultimat3/policy": "30.8.0",
59
- "@ultimat3/pwa": "30.8.0",
60
- "@ultimat3/query": "30.8.0",
61
- "@ultimat3/realtime": "30.8.0",
62
- "@ultimat3/render": "30.8.0",
63
- "@ultimat3/schema": "30.8.0",
64
- "@ultimat3/time": "30.8.0"
49
+ "@ultimat3/action": "30.9.0",
50
+ "@ultimat3/cache": "30.9.0",
51
+ "@ultimat3/core": "30.9.0",
52
+ "@ultimat3/db": "30.9.0",
53
+ "@ultimat3/entity": "30.9.0",
54
+ "@ultimat3/http": "30.9.0",
55
+ "@ultimat3/i18n": "30.9.0",
56
+ "@ultimat3/jobs": "30.9.0",
57
+ "@ultimat3/mail": "30.9.0",
58
+ "@ultimat3/policy": "30.9.0",
59
+ "@ultimat3/pwa": "30.9.0",
60
+ "@ultimat3/query": "30.9.0",
61
+ "@ultimat3/realtime": "30.9.0",
62
+ "@ultimat3/render": "30.9.0",
63
+ "@ultimat3/schema": "30.9.0",
64
+ "@ultimat3/time": "30.9.0"
65
65
  }
66
66
  }
package/src/errors.ts CHANGED
@@ -150,6 +150,25 @@ registerErrorCodes(
150
150
  // No `docs:` below: `UltimateError` fills core's `ERROR_DOCS_URL`, one page per code set (a wiki
151
151
  // TABLE ROW has no anchor; per-code links answered 404 until 9.x). Restating it here would drift.
152
152
 
153
+ /** Which dial refused, and so which repair: `dns-record` is a query no mock answers (an MX, a TXT,
154
+ * a reverse lookup), so its fix opens with the one line that lifts it. */
155
+ export type SealedTransport = 'fetch' | 'socket' | 'dns' | 'dns-record';
156
+
157
+ const sealedFix = (url: string, transport: SealedTransport): string => {
158
+ const host = hostOf(url);
159
+ const allow = `allowHost('${host}') if it must be real`;
160
+ switch (transport) {
161
+ case 'socket':
162
+ return `allowHost('${host}') # only if it must be real — otherwise inject the transport: pass the code under test its \`connect\`/\`client\` option, or dial a Bun.listen server on 127.0.0.1 (loopback is never sealed)`;
163
+ case 'dns':
164
+ return `mockFetch('https://${host}/*', () => new Response('{}')) # a mocked host resolves — or ${allow}`;
165
+ case 'dns-record':
166
+ return `allowHost('${host}') # only if it must be real — a mockFetch route answers an address lookup, never this record or a reverse lookup: inject the resolver into the code under test otherwise`;
167
+ case 'fetch':
168
+ return `mockFetch('${url}', () => new Response('{}')) — or ${allow}`;
169
+ }
170
+ };
171
+
153
172
  /**
154
173
  * A test reached the network without a mock or an allowlist entry. Always a bug, never a flake.
155
174
  * `transport` picks the repair: a `fetch` is mocked, a socket (`WebSocket`, `Bun.connect`) has no
@@ -160,21 +179,14 @@ export class NetworkSealedError extends UltimateError {
160
179
  url: string;
161
180
  method: string;
162
181
  allowed: readonly string[];
163
- transport?: 'fetch' | 'socket' | 'dns' | undefined;
182
+ transport?: SealedTransport | undefined;
164
183
  }) {
165
- const allowCall = `allowHost('${hostOf(input.url)}')`;
166
- const allow = `${allowCall} if it must be real`;
167
184
  super({
168
185
  code: 'X_TEST_NETWORK_SEALED',
169
186
  cause: `${input.method} ${input.url} was not mocked (allowed hosts: ${
170
187
  input.allowed.length > 0 ? input.allowed.join(', ') : 'none'
171
188
  })`,
172
- fix:
173
- input.transport === 'socket'
174
- ? `${allowCall} # only if it must be real — otherwise inject the transport: pass the code under test its \`connect\`/\`client\` option, or dial a Bun.listen server on 127.0.0.1 (loopback is never sealed)`
175
- : input.transport === 'dns'
176
- ? `mockFetch('https://${hostOf(input.url)}/*', () => new Response('{}')) # a mocked host resolves — or ${allow}`
177
- : `mockFetch('${input.url}', () => new Response('{}')) — or ${allow}`,
189
+ fix: sealedFix(input.url, input.transport ?? 'fetch'),
178
190
  });
179
191
  }
180
192
  }
@@ -15,8 +15,18 @@ import type { ExerciseOverride } from './define-exercise';
15
15
  import { withExerciseRequest } from './exercise-request';
16
16
  import { testJobs } from './fixture-jobs';
17
17
 
18
+ /**
19
+ * `onCallQueue`: the caller has installed the queue the call it feeds runs on (the control's), and
20
+ * the input binds on it — so a job it enqueues is there when the call looks it up by id. Without
21
+ * it the input gets a queue of its own for its duration: no call shares one with it (the tenant
22
+ * proof's B legs and the scale sweep each open theirs after the bind).
23
+ */
24
+ export interface BindAt {
25
+ readonly onCallQueue?: boolean;
26
+ }
27
+
18
28
  /** `(drawn, actor) => input`, or `undefined` when the override binds nothing. */
19
- export type OverrideInput = (drawn: unknown, actor: Actor | null) => Promise<unknown>;
29
+ export type OverrideInput = (drawn: unknown, actor: Actor | null, at?: BindAt) => Promise<unknown>;
20
30
 
21
31
  export function overrideInput(
22
32
  name: string,
@@ -28,15 +38,18 @@ export function overrideInput(
28
38
  const entry = override === undefined || 'off' in override ? undefined : override;
29
39
  const declared = entry?.actor;
30
40
  // The entry's own request: the binder sees the cookies and headers the call itself will.
31
- return async (drawn, actor) => {
32
- // A queue of its own, as every call gets one: app code that enqueues has a driver, and what it
33
- // queued is the input's, never counted as the primitive's enqueue.
41
+ return async (drawn, actor, at) => {
42
+ const run = async () =>
43
+ rehomed(
44
+ await withExerciseRequest(name, actor, async () => bind(drawn), entry?.request),
45
+ declared?.orgId,
46
+ actor?.orgId,
47
+ );
48
+ if (at?.onCallQueue === true) return run();
49
+ // No call's queue to share: one of its own, so app code that enqueues has a driver.
34
50
  await using _jobs = await testJobs();
35
- return rehomed(
36
- await withExerciseRequest(name, actor, async () => bind(drawn), entry?.request),
37
- declared?.orgId,
38
- actor?.orgId,
39
- );
51
+ // Awaited HERE: a bare `return run()` leaves the block, and disposes the queue, mid-bind.
52
+ return await run();
40
53
  };
41
54
  }
42
55
 
@@ -69,7 +69,9 @@ export async function sizedCall(
69
69
  const lookup = seededIds(graph, options.entities, { ...scope, self });
70
70
  const drawn = bindIds(drawInput(sampler, subject.input, 0, 0), lookup);
71
71
  const bindInput = overrideInput(subject.name, override);
72
- const given = bindInput === undefined ? drawn : await bindInput(drawn, actor);
72
+ // On the sized call's own queue, installed by the sweep before this setup (`scale-sweep-run.ts`).
73
+ const given =
74
+ bindInput === undefined ? drawn : await bindInput(drawn, actor, { onCallQueue: true });
73
75
  return { actor, input: seatIn(subject, given, tenant) };
74
76
  }
75
77
 
package/src/exercise.ts CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  import type { Actor, ExerciseAttempt, ExerciseVerdict } from '@ultimat3/core';
13
13
  import { runExercise } from '@ultimat3/core';
14
- import { registeredJobs } from '@ultimat3/jobs';
14
+ import { LIVE_STATES, registeredJobs } from '@ultimat3/jobs';
15
15
  import type { ExerciseOverride, ExerciseOverrides } from './define-exercise';
16
16
  import { assertOverridesKnown, overrideFor, unknownDeclaration } from './define-exercise';
17
17
  import type { RoleGrants } from './exercise-actor';
@@ -39,7 +39,6 @@ import { withExerciseSetup } from './exercise-setup';
39
39
  import type { Subject } from './exercise-subjects';
40
40
  import { fixedTenant, seatIn, subjectsOf } from './exercise-subjects';
41
41
  import { actorRowsOf, attachSweeps, seated, sizedCall } from './exercise-sweeps';
42
- import type { RunJobs } from './fixture-jobs';
43
42
  import { testJobs } from './fixture-jobs';
44
43
  import { deferredMayStayNull, pairGraph, seedPass, tenantPair } from './seed-graph-pass';
45
44
  import type { SeedGraph, SeedWriter } from './seed-graph-plan';
@@ -70,18 +69,27 @@ const isOff = (overrides: ExerciseOverrides | undefined, subject: Subject): bool
70
69
  return override !== undefined && 'off' in override;
71
70
  };
72
71
 
72
+ /** The ids of every row the call's queue holds now: what an attempt adds is the call's. */
73
+ const queuedIds = async (): Promise<ReadonlySet<string>> =>
74
+ new Set((await ambientJobRows()).map((record) => record.id));
75
+
73
76
  /**
74
- * Jobs the primitive queued, its own job excepted. Never run: a job's children are left queued as
75
- * an action's are (`exercise-job-run.ts`), so their statements are theirs, never this record's.
77
+ * Jobs the primitive queued — rows an ATTEMPT added (`mine`), still live — its own job excepted.
78
+ * Never run: a job's children are left queued as an action's are (`exercise-job-run.ts`). A row
79
+ * the override's input added between calls is on the same queue, so the call can find it, and is
80
+ * not in `mine`: the input's enqueue is never the primitive's.
76
81
  */
77
- async function enqueued(subject: Subject, jobs: RunJobs) {
78
- const effects: ExerciseEffect[] = [];
79
- for (const handle of registeredJobs()) {
80
- if (subject.kind === 'job' && handle.name === subject.name) continue;
81
- const count = await jobs.depth(handle);
82
- if (count > 0) effects.push({ kind: 'enqueue', job: handle.name, count });
82
+ async function enqueued(subject: Subject, mine: ReadonlySet<string>) {
83
+ const counts = new Map<string, number>();
84
+ for (const record of await ambientJobRows()) {
85
+ if (!mine.has(record.id) || !LIVE_STATES.has(record.state)) continue;
86
+ if (subject.kind === 'job' && record.name === subject.name) continue;
87
+ counts.set(record.name, (counts.get(record.name) ?? 0) + 1);
83
88
  }
84
- return effects;
89
+ const order = registeredJobs().map((handle) => handle.name);
90
+ return [...counts]
91
+ .sort(([a], [b]) => order.indexOf(a) - order.indexOf(b))
92
+ .map(([job, count]): ExerciseEffect => ({ kind: 'enqueue', job, count }));
85
93
  }
86
94
 
87
95
  /**
@@ -134,6 +142,7 @@ async function control(
134
142
  let lastInput: unknown;
135
143
  let output: unknown;
136
144
  const segments: Observed[] = [];
145
+ const mine = new Set<string>();
137
146
  const started = performance.now();
138
147
  let verdict: ExerciseVerdict;
139
148
  try {
@@ -146,7 +155,9 @@ async function control(
146
155
  bind: async (drawn) => {
147
156
  const bound = bindIds(drawn, lookups[binds++ === 0 ? 0 : 1]);
148
157
  try {
149
- const given = bindInput === undefined ? bound : await bindInput(bound, actor);
158
+ // On the call's own queue: a job the input enqueues is there when the call looks it up.
159
+ const given =
160
+ bindInput === undefined ? bound : await bindInput(bound, actor, { onCallQueue: true });
150
161
  lastInput = seatIn(subject, given, tenant);
151
162
  } catch (error) {
152
163
  throw new BindThrew(error);
@@ -156,6 +167,7 @@ async function control(
156
167
  accepts: async (input) =>
157
168
  (await subject.input['~standard'].validate(input)).issues === undefined,
158
169
  attempt: async (input): Promise<ExerciseAttempt> => {
170
+ const before = await queuedIds();
159
171
  room.begin(key);
160
172
  try {
161
173
  const answer = await subject.call(input, actor, tenant, jobs);
@@ -171,6 +183,7 @@ async function control(
171
183
  return { ok: false, reached: false, error };
172
184
  } finally {
173
185
  segments.push(room.end());
186
+ for (const id of await queuedIds()) if (!before.has(id)) mine.add(id);
174
187
  }
175
188
  },
176
189
  statusOf: (await import('@ultimat3/http')).statusFor,
@@ -190,7 +203,7 @@ async function control(
190
203
  }
191
204
  const ms = Math.round(performance.now() - started);
192
205
  const observed = mergeObserved(segments);
193
- const effects = [...observed.effects, ...(await enqueued(subject, jobs))];
206
+ const effects = [...observed.effects, ...(await enqueued(subject, mine))];
194
207
  const outcome = { verdict, answered, lastError, lastInput };
195
208
  const verdictOf = judged(subject, key, outcome, observed, sampler);
196
209
  // A 5xx's cause, statement and fields: the code alone sent the author to reproduce it by hand.
@@ -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 {
@@ -92,6 +92,23 @@ const CLAIM_LIMIT = 64;
92
92
  * reads the same clock, so a renewal can never report a lease lost that `clock.advance()` did not.
93
93
  */
94
94
  const RENEW_MS = 1;
95
+ /**
96
+ * The clock a body runs on: the preload's frozen instant, as a `FrozenClock`. `systemClock` read
97
+ * the frozen `Date` too, but had no `advance` — so a `backfill()` pacer saw every batch as instant
98
+ * and slept its whole `rate` interval in WALL time. Moving the instant is the wait now, and it is
99
+ * a move the frozen scheduler hears, so the renewals see exactly the time the throttle spent.
100
+ */
101
+ const PRELOAD_CLOCK: FrozenClock = Object.freeze({
102
+ now: frozenNow,
103
+ monotonic: () => frozenNow().getTime(),
104
+ advance: (ms: number): void => {
105
+ advanceClock(ms);
106
+ },
107
+ set: (at: Date | number | string): void => {
108
+ setFrozenClock(at instanceof Date ? at.getTime() : at);
109
+ },
110
+ });
111
+
95
112
  /** A drain that has not settled in this many rounds is a runaway, not a slow queue. */
96
113
  const MAX_ROUNDS = 100;
97
114
  const LIVE_STATES: ReadonlySet<string> = new Set(['ready', 'delayed', 'running', 'suspended']);
@@ -125,7 +142,7 @@ export async function testJobs(): Promise<RunJobs> {
125
142
  // the process's own handed back with the driver.
126
143
  const previousBus = jobs.eventBus();
127
144
  jobs.setEventBus(jobs.memoryEventBus());
128
- const anonymousWorker = ctxOf({ role: 'worker' });
145
+ const anonymousWorker = ctxOf({ role: 'worker', clock: PRELOAD_CLOCK });
129
146
  const renewals = frozenScheduler();
130
147
 
131
148
  const introspect = (): NonNullable<JobDriver['introspect']> => {
@@ -200,7 +217,9 @@ export async function testJobs(): Promise<RunJobs> {
200
217
  const history: JobExecution[] = [];
201
218
 
202
219
  const ctxFor = (options: JobDrainAs): Ctx =>
203
- options.actor === undefined ? anonymousWorker : ctxOf({ role: 'worker', actor: options.actor });
220
+ options.actor === undefined
221
+ ? anonymousWorker
222
+ : ctxOf({ role: 'worker', actor: options.actor, clock: PRELOAD_CLOCK });
204
223
  const traced = (): JobRunTrace => ({ executions: [...history], steps: tallyOf(history) });
205
224
 
206
225
  const tick = async (options: JobDrainAs = {}): Promise<JobRunTrace> => {
@@ -1,6 +1,6 @@
1
- // The plan oracle: one `explain (format json)` plan, taken with sequential scans, bitmap scans and
2
- // sorts disabled, in; the nodes no index could replace, out. Under those settings the planner picks
3
- // a scan or a sort only when nothing else answers, so the verdict reads the schema, not the rows.
1
+ // The plan oracle: one `explain (format json)` plan, taken with sequential and bitmap scans (and,
2
+ // for a limited sort, sorts) disabled, in; the nodes no index could replace, out. The planner then
3
+ // picks a scan or a sort only when nothing else answers: the verdict reads the schema, not rows.
4
4
  // Pure: JSON in, verdicts out (plan 101, 40-next-query-plans).
5
5
 
6
6
  import { columnsIn } from './plan-conditions';
@@ -89,6 +89,13 @@ export function planRoot(answer: unknown): unknown {
89
89
  return record(first)?.['Plan'] ?? first;
90
90
  }
91
91
 
92
+ /** A `Limit` anywhere in the plan: only beneath one is a sort judged, so only then is one planned. */
93
+ export function planLimited(answer: unknown): boolean {
94
+ const limited = (node: PlanNode): boolean => node.type === 'Limit' || node.children.some(limited);
95
+ const root = nodeOf(planRoot(answer));
96
+ return root !== undefined && limited(root);
97
+ }
98
+
92
99
  /** Every scan beneath `node` (the node itself included), of any table. */
93
100
  const scansBeneath = (node: PlanNode): readonly PlanNode[] => [
94
101
  ...(node.table !== undefined && SCANS.has(node.type) ? [node] : []),
package/src/plan-sweep.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  // The plan sweep: every distinct statement the exercise pass sent whose first relation is an app
2
- // table, planned on the migrated database with sequential scans, bitmap scans and sorts disabled,
3
- // judged by `plan-oracle.ts`, each red node named as the `indexes:` entry that answers it.
4
- // Read-only: `PREPARE` in a read-only transaction whose settings die with it, then `DEALLOCATE`.
2
+ // table, planned on the migrated database with sequential and bitmap scans disabled — and, for a
3
+ // limited read's sort only, sorts too — judged by `plan-oracle.ts`, each red node named as the
4
+ // `indexes:` entry that answers it. Read-only: `PREPARE` in a read-only transaction, `DEALLOCATE`.
5
5
 
6
6
  import { renderThrowable, UltimateError } from '@ultimat3/core';
7
7
  import type { DbClient } from '@ultimat3/db';
8
8
  import { isReservable, raw, sql, withReadTransaction } from '@ultimat3/db';
9
9
  import './errors';
10
- import type { PlanTableColumns } from './plan-oracle';
11
- import { judgePlan } from './plan-oracle';
10
+ import type { PlanTableColumns, PlanVerdict } from './plan-oracle';
11
+ import { judgePlan, planLimited } from './plan-oracle';
12
12
  import type { PlanFinding } from './plan-sweep-fix';
13
13
  import { planFindings } from './plan-sweep-fix';
14
14
  import type { SeedEntity } from './seed-graph-shape';
@@ -47,13 +47,18 @@ export class QueryPlanUnavailableError extends UltimateError {
47
47
  }
48
48
  }
49
49
 
50
- /** The planner's choices the sweep removes: what remains is what the schema can serve. */
51
- const SETTINGS = {
50
+ /**
51
+ * The planner's choices the sweep removes: what remains is what the schema can serve. The access
52
+ * path is judged with sorts allowed — off, an `order by` makes the planner walk whatever index
53
+ * holds the order, whole, instead of the one that keys the read. Only a sort under a `Limit` is
54
+ * judged, so only a limited read is planned again with sorts off, for its sort alone.
55
+ */
56
+ const ACCESS = {
52
57
  enable_seqscan: 'off',
53
58
  enable_bitmapscan: 'off',
54
- enable_sort: 'off',
55
59
  plan_cache_mode: 'force_generic_plan',
56
60
  } as const;
61
+ const SORTS = { ...ACCESS, enable_sort: 'off' } as const;
57
62
  const PREPARED = 'x_plan_sweep';
58
63
  const FIRST_RELATION = /\b(?:from|into|update|join)\s+(?:"?\w+"?\.)?"?([A-Za-z_][\w$]*)"?/i;
59
64
 
@@ -66,7 +71,11 @@ interface Planned {
66
71
  readonly refused?: string;
67
72
  }
68
73
 
69
- async function explain(client: DbClient, statement: string): Promise<Planned> {
74
+ async function explain(
75
+ client: DbClient,
76
+ statement: string,
77
+ settings: typeof ACCESS | typeof SORTS,
78
+ ): Promise<Planned> {
70
79
  const connection = isReservable(client) ? await client.reserve() : undefined;
71
80
  const on = connection ?? client;
72
81
  let prepared = false;
@@ -81,7 +90,7 @@ async function explain(client: DbClient, statement: string): Promise<Planned> {
81
90
  raw(`explain (format json) execute ${PREPARED}${args}`),
82
91
  );
83
92
  },
84
- { settings: SETTINGS, client: on },
93
+ { settings, client: on },
85
94
  );
86
95
  return { plan: rows[0]?.['QUERY PLAN'] };
87
96
  } catch (error) {
@@ -93,6 +102,22 @@ async function explain(client: DbClient, statement: string): Promise<Planned> {
93
102
  }
94
103
  }
95
104
 
105
+ /** One statement's verdicts: its access path planned as is, its limited sort with sorts off. */
106
+ async function judge(
107
+ client: DbClient,
108
+ statement: string,
109
+ tables: PlanTableColumns,
110
+ ): Promise<{ readonly verdicts?: readonly PlanVerdict[]; readonly refused?: string }> {
111
+ const access = await explain(client, statement, ACCESS);
112
+ if (access.refused !== undefined) return { refused: access.refused };
113
+ const read = judgePlan(access.plan, tables).filter((v) => v.code === 'X_QUERY_UNINDEXED');
114
+ if (!planLimited(access.plan)) return { verdicts: read };
115
+ const sorted = await explain(client, statement, SORTS);
116
+ if (sorted.refused !== undefined) return { refused: sorted.refused };
117
+ const sorts = judgePlan(sorted.plan, tables).filter((v) => v.code === 'X_QUERY_SORT_UNSERVED');
118
+ return { verdicts: [...read, ...sorts] };
119
+ }
120
+
96
121
  interface ProofBuilder {
97
122
  planned: number;
98
123
  readonly findings: PlanFinding[];
@@ -132,7 +157,7 @@ export async function sweepPlans(
132
157
  if (entity === undefined) continue;
133
158
  const declared = entity.$describe().scan;
134
159
  const exemptBy = scan ?? declared;
135
- const planned = exemptBy === undefined ? await explain(client, statement) : {};
160
+ const planned = exemptBy === undefined ? await judge(client, statement, judged) : {};
136
161
  for (const name of primitives) {
137
162
  const proof = proofOf(name);
138
163
  proof.planned += 1;
@@ -140,7 +165,7 @@ export async function sweepPlans(
140
165
  else if (planned.refused !== undefined) {
141
166
  proof.unplannable.push({ statement, reason: planned.refused });
142
167
  } else {
143
- proof.findings.push(...planFindings(statement, judgePlan(planned.plan, judged), byTable));
168
+ proof.findings.push(...planFindings(statement, planned.verdicts ?? [], byTable));
144
169
  }
145
170
  }
146
171
  }
@@ -59,6 +59,9 @@ async function callAt(
59
59
  options: ScaleSweepOptions,
60
60
  self: boolean,
61
61
  ): Promise<Call> {
62
+ // Before the setup: an override's input binds on the queue this call runs on, so a job it
63
+ // enqueues is there when the call looks it up by id.
64
+ await using jobs = await testJobs();
62
65
  let prepared: Awaited<ReturnType<ScaleSetup>>;
63
66
  try {
64
67
  prepared = await options.setup(subject, graph, tenant, self);
@@ -68,7 +71,6 @@ async function callAt(
68
71
  return { failed: `its exercise.ts input threw: ${renderThrowable(error)}` };
69
72
  }
70
73
  if (prepared === undefined) return { failed: 'no actor its policy permits' };
71
- await using jobs = await testJobs();
72
74
  options.room.begin();
73
75
  try {
74
76
  const answer = await subject.call(prepared.input, prepared.actor, tenant, jobs);
@@ -0,0 +1,56 @@
1
+ // The `Resolver` half of the sealed resolver: an instance asks its own c-ares channel, never
2
+ // `Bun.dns`, so each class is sealed on its prototype (a named import shares it). A sealed instance
3
+ // answers exactly what the module function of the same name answers — that one is sealed at the root.
4
+
5
+ // why: `node:dns`'s two `Resolver` classes are what an app's own resolver instance is built from.
6
+ import nodeDns from 'node:dns';
7
+ import type { DnsGate } from './sealed-dns';
8
+
9
+ /** Each `Resolver` method and the query its arguments ask; `resolve` names its record type. */
10
+ const RESOLVER_QUERIES: Readonly<Record<string, (args: readonly unknown[]) => string>> = {
11
+ resolve: (args) => (typeof args[1] === 'string' ? args[1].toUpperCase() : 'A'),
12
+ resolve4: () => 'A',
13
+ resolve6: () => 'AAAA',
14
+ resolveAny: () => 'ANY',
15
+ resolveCaa: () => 'CAA',
16
+ resolveCname: () => 'CNAME',
17
+ resolveMx: () => 'MX',
18
+ resolveNaptr: () => 'NAPTR',
19
+ resolveNs: () => 'NS',
20
+ resolvePtr: () => 'PTR',
21
+ resolveSoa: () => 'SOA',
22
+ resolveSrv: () => 'SRV',
23
+ resolveTxt: () => 'TXT',
24
+ reverse: () => 'REVERSE',
25
+ };
26
+
27
+ type Method = (this: unknown, ...args: unknown[]) => unknown;
28
+
29
+ /** Seal one class's prototype, answering through `moduleApi`; returns the uninstaller. */
30
+ const sealPrototype = (prototype: object, moduleApi: object, gate: DnsGate): (() => void) => {
31
+ const originals = new Map<string, Method>();
32
+ for (const [name, queryOf] of Object.entries(RESOLVER_QUERIES)) {
33
+ const original = Reflect.get(prototype, name) as Method;
34
+ const viaModule = Reflect.get(moduleApi, name) as Method;
35
+ originals.set(name, original);
36
+ // A `function`, not an arrow: the real method needs the instance its own servers live on.
37
+ Reflect.set(prototype, name, function sealed(this: unknown, ...args: unknown[]): unknown {
38
+ const verdict = gate(String(args[0]), queryOf(args));
39
+ if ('real' in verdict) return Reflect.apply(original, this, args);
40
+ return Reflect.apply(viaModule, moduleApi, args);
41
+ });
42
+ }
43
+ return () => {
44
+ for (const [name, original] of originals) Reflect.set(prototype, name, original);
45
+ };
46
+ };
47
+
48
+ /** Seal both `Resolver` classes — callback and promise — and return the one uninstaller. */
49
+ export function installResolverSeal(gate: DnsGate): () => void {
50
+ const restoreCallback = sealPrototype(nodeDns.Resolver.prototype, nodeDns, gate);
51
+ const restorePromise = sealPrototype(nodeDns.promises.Resolver.prototype, nodeDns.promises, gate);
52
+ return () => {
53
+ restoreCallback();
54
+ restorePromise();
55
+ };
56
+ }
package/src/sealed-dns.ts CHANGED
@@ -1,86 +1,85 @@
1
- // The resolver half of the sealed network: `Bun.dns.lookup`, `dns.lookup` and `dns.promises.lookup`.
2
- // Only the patching lives here; WHAT a name resolves to is `sealed-network.ts`'s one gate, handed in,
3
- // so a host `fetch` would answer by mock resolves and a host it would refuse does not. A named ESM
4
- // import (`import { lookup } from 'node:dns'`) binds before the seal and is NOT covered (measured).
1
+ // The resolver half of the sealed network: every `Bun.dns` resolution function, which is the ROOT
2
+ // every `node:dns` module function calls at call time — so a named import bound before the seal is
3
+ // sealed too (`sealed-dns-paths.test.ts`). `Resolver` instances: `sealed-dns-resolver.ts`. WHAT a
4
+ // name resolves to is `sealed-network.ts`'s one gate, handed in.
5
5
 
6
- // why: `dns.lookup` and `dns.promises.lookup` are what an app's own resolver calls; Bun ships both.
7
- import nodeDns from 'node:dns';
6
+ import { installResolverSeal } from './sealed-dns-resolver';
8
7
 
9
- /** One lookup's verdict: the addresses to answer, a refusal to raise, or `real` for the resolver. */
8
+ /** One query's verdict: the addresses to answer, a refusal to raise, or `real` for the resolver. */
10
9
  export type DnsVerdict =
11
10
  | { readonly answer: readonly string[] }
12
11
  | { readonly refused: Error }
13
12
  | { readonly real: true };
14
13
 
15
- export type DnsGate = (hostname: string) => DnsVerdict;
14
+ /** `LOOKUP` (getaddrinfo), `REVERSE` (an address to its names) or a record type: `A`, `MX`, … */
15
+ export type DnsGate = (name: string, query: string) => DnsVerdict;
16
16
 
17
- interface LookupEntry {
18
- readonly address: string;
19
- readonly family: number;
20
- }
17
+ /**
18
+ * The queries an address list can answer. A mock declares an HTTP endpoint, not a zone: an MX or
19
+ * TXT answer would be invented, so the gate answers only these and refuses the rest.
20
+ */
21
+ export const ADDRESS_QUERIES: ReadonlySet<string> = new Set(['LOOKUP', 'A', 'ANY']);
21
22
 
22
23
  const familyOf = (address: string): number => (address.includes(':') ? 6 : 4);
23
24
 
24
- const entriesOf = (addresses: readonly string[]): LookupEntry[] =>
25
- addresses.map((address) => ({ address, family: familyOf(address) }));
25
+ /** The raw shape `Bun.dns` answers per query; `node:dns` maps it as it maps a real one. */
26
+ const shaped = (query: string, addresses: readonly string[]): unknown[] =>
27
+ addresses.map((address) => {
28
+ if (query === 'LOOKUP') return { address, family: familyOf(address), ttl: 0 };
29
+ if (query === 'ANY') return { address, ttl: 0, type: familyOf(address) === 6 ? 'AAAA' : 'A' };
30
+ return { address, ttl: 0 };
31
+ });
26
32
 
27
- type NodeCallback = (error: unknown, address?: unknown, family?: number) => void;
33
+ /** Each async `Bun.dns` resolver and the query its arguments ask. */
34
+ const BUN_QUERIES: Readonly<Record<string, (args: readonly unknown[]) => string>> = {
35
+ lookup: () => 'LOOKUP',
36
+ resolve: (args) => (typeof args[1] === 'string' ? args[1].toUpperCase() : 'A'),
37
+ resolveAny: () => 'ANY',
38
+ resolveCaa: () => 'CAA',
39
+ resolveCname: () => 'CNAME',
40
+ resolveMx: () => 'MX',
41
+ resolveNaptr: () => 'NAPTR',
42
+ resolveNs: () => 'NS',
43
+ resolvePtr: () => 'PTR',
44
+ resolveSoa: () => 'SOA',
45
+ resolveSrv: () => 'SRV',
46
+ resolveTxt: () => 'TXT',
47
+ reverse: () => 'REVERSE',
48
+ lookupService: () => 'REVERSE',
49
+ };
28
50
 
29
- /** Node's `(hostname, options?, callback)`; `options.all` answers the list, a number is a family. */
30
- const wantsAll = (options: unknown): boolean =>
31
- typeof options === 'object' && options !== null && 'all' in options && options.all === true;
51
+ type Resolve = (...args: unknown[]) => Promise<unknown>;
32
52
 
33
53
  /**
34
- * Patch the three resolvers and return the uninstaller, which puts back exactly what was there.
54
+ * Patch every resolver and return the uninstaller, which puts back exactly what was there.
35
55
  * Assigned through `Reflect.set`: each is a writable data property the types declare a function.
36
56
  */
37
57
  export function installDnsSeal(gate: DnsGate): () => void {
38
- const originalBun = Reflect.get(Bun.dns, 'lookup') as typeof Bun.dns.lookup;
39
- const originalNode = Reflect.get(nodeDns, 'lookup') as (...args: unknown[]) => void;
40
- const originalPromises = Reflect.get(nodeDns.promises, 'lookup') as (
41
- ...args: unknown[]
42
- ) => Promise<unknown>;
43
-
44
- const sealedBun = async (hostname: string, options?: unknown): Promise<unknown> => {
45
- const verdict = gate(hostname);
58
+ const originals = new Map<string, unknown>();
59
+ for (const [name, queryOf] of Object.entries(BUN_QUERIES)) {
60
+ const original = Reflect.get(Bun.dns, name) as Resolve;
61
+ originals.set(name, original);
62
+ const sealed: Resolve = async (...args) => {
63
+ const query = queryOf(args);
64
+ const verdict = gate(String(args[0]), query);
65
+ if ('refused' in verdict) throw verdict.refused;
66
+ if ('answer' in verdict) return shaped(query, verdict.answer);
67
+ return Reflect.apply(original, Bun.dns, args);
68
+ };
69
+ Reflect.set(Bun.dns, name, sealed);
70
+ }
71
+ // `prefetch` is synchronous and answers nothing: a mocked name has nothing to warm, and an
72
+ // unmocked one throws here rather than hide the egress until the dial that follows it.
73
+ const originalPrefetch = Reflect.get(Bun.dns, 'prefetch') as (...args: unknown[]) => void;
74
+ originals.set('prefetch', originalPrefetch);
75
+ Reflect.set(Bun.dns, 'prefetch', (...args: unknown[]): void => {
76
+ const verdict = gate(String(args[0]), 'LOOKUP');
46
77
  if ('refused' in verdict) throw verdict.refused;
47
- if ('answer' in verdict) return entriesOf(verdict.answer).map((one) => ({ ...one, ttl: 0 }));
48
- return Reflect.apply(originalBun, Bun.dns, [hostname, options]);
49
- };
50
-
51
- const sealedNode = (hostname: string, ...rest: unknown[]): void => {
52
- const verdict = gate(hostname);
53
- if ('real' in verdict) {
54
- Reflect.apply(originalNode, nodeDns, [hostname, ...rest]);
55
- return;
56
- }
57
- const callback = rest.findLast((one) => typeof one === 'function') as NodeCallback | undefined;
58
- const options = rest.length > 1 ? rest[0] : undefined;
59
- // A real lookup answers on a later tick, and a caller may rely on it: never synchronously.
60
- queueMicrotask(() => {
61
- if ('refused' in verdict) return callback?.(verdict.refused);
62
- const entries = entriesOf(verdict.answer);
63
- if (wantsAll(options)) return callback?.(null, entries);
64
- return callback?.(null, entries[0]?.address, entries[0]?.family);
65
- });
66
- };
67
-
68
- const sealedPromises = async (hostname: string, options?: unknown): Promise<unknown> => {
69
- const verdict = gate(hostname);
70
- if ('refused' in verdict) throw verdict.refused;
71
- if ('real' in verdict) {
72
- return Reflect.apply(originalPromises, nodeDns.promises, [hostname, options]);
73
- }
74
- const entries = entriesOf(verdict.answer);
75
- return wantsAll(options) ? entries : entries[0];
76
- };
77
-
78
- Reflect.set(Bun.dns, 'lookup', sealedBun);
79
- Reflect.set(nodeDns, 'lookup', sealedNode);
80
- Reflect.set(nodeDns.promises, 'lookup', sealedPromises);
78
+ if ('real' in verdict) Reflect.apply(originalPrefetch, Bun.dns, args);
79
+ });
80
+ const restoreResolver = installResolverSeal(gate);
81
81
  return () => {
82
- Reflect.set(Bun.dns, 'lookup', originalBun);
83
- Reflect.set(nodeDns, 'lookup', originalNode);
84
- Reflect.set(nodeDns.promises, 'lookup', originalPromises);
82
+ for (const [name, original] of originals) Reflect.set(Bun.dns, name, original);
83
+ restoreResolver();
85
84
  };
86
85
  }
@@ -9,7 +9,7 @@ import { mockRoute, routeMatches, routeNamesHost } from './mock-route';
9
9
  import type { LoggedRequest } from './request-log';
10
10
  import { hasStreamBody, headersOf, isOpenEnded, readBody, requestProbe } from './request-log';
11
11
  import type { DnsVerdict } from './sealed-dns';
12
- import { installDnsSeal } from './sealed-dns';
12
+ import { ADDRESS_QUERIES, installDnsSeal } from './sealed-dns';
13
13
  import { installSocketSeal } from './sealed-sockets';
14
14
 
15
15
  export type FetchLike = typeof globalThis.fetch;
@@ -99,25 +99,26 @@ const isAllowedName = (hostname: string): boolean =>
99
99
 
100
100
  /**
101
101
  * The resolver's gate, in `fetch`'s order: offline refuses every name, this machine and an allowed
102
- * host resolve for real, a host a mock answers resolves to `MOCKED_HOST_ADDRESS`, the rest is
103
- * `X_TEST_NETWORK_SEALED` — the code `fetch` would have raised a moment later.
102
+ * host resolve for real, as does a `LOOKUP` of an address literal (no query leaves; a `REVERSE` of
103
+ * one does), a host a mock answers resolves to `MOCKED_HOST_ADDRESS` for an address query only,
104
+ * the rest is `X_TEST_NETWORK_SEALED` — the code `fetch` would have raised a moment later.
104
105
  */
105
- const dnsVerdict = (hostname: string): DnsVerdict => {
106
+ const dnsVerdict = (hostname: string, query: string): DnsVerdict => {
106
107
  const name = hostname.toLowerCase().replace(/^\[|\]$/g, '');
107
108
  const url = `dns://${name}`;
109
+ const method = query === 'LOOKUP' || query === 'REVERSE' ? query : `RESOLVE ${query}`;
108
110
  if (state.network !== 'online') {
109
- return { refused: new NetworkOfflineError({ url, method: 'LOOKUP', mode: state.network }) };
111
+ return { refused: new NetworkOfflineError({ url, method, mode: state.network }) };
110
112
  }
111
- if (isThisMachine(name) || peerAddressClass(name) !== undefined || isAllowedName(name)) {
112
- return { real: true };
113
- }
114
- if (state.mocks.some((route) => routeNamesHost(route, name))) {
113
+ const literal = query === 'LOOKUP' && peerAddressClass(name) !== undefined;
114
+ if (isThisMachine(name) || literal || isAllowedName(name)) return { real: true };
115
+ if (ADDRESS_QUERIES.has(query) && state.mocks.some((route) => routeNamesHost(route, name))) {
115
116
  return { answer: [MOCKED_HOST_ADDRESS] };
116
117
  }
117
118
  const allowed = [...state.allowed];
118
- return {
119
- refused: new NetworkSealedError({ url, method: 'LOOKUP', allowed, transport: 'dns' }),
120
- };
119
+ // A record no mock answers (MX, TXT, a reverse) is lifted by `allowHost` alone: say that first.
120
+ const transport = ADDRESS_QUERIES.has(query) ? 'dns' : 'dns-record';
121
+ return { refused: new NetworkSealedError({ url, method, allowed, transport }) };
121
122
  };
122
123
 
123
124
  /** Replace global fetch, `WebSocket`, `Bun.connect` and the resolvers. Idempotent: sealing twice
@@ -0,0 +1,63 @@
1
+ // The `node:*` half of the socket seal: `net`, `tls`, `http(s)` and `http2` all dial through
2
+ // `net.Socket#connect` (measured; none reaches `Bun.connect` or `fetch`), so that one prototype is
3
+ // the root. WHETHER a dial may leave is `sealed-network.ts`'s socket gate, handed in.
4
+
5
+ // why: `net.Socket` is the class every node:* client socket is, and the only place they all meet.
6
+ import net from 'node:net';
7
+ import type { SocketGate } from './sealed-sockets';
8
+
9
+ /** A dial target as a URL, so the gate parses one shape. IPv6 literals need their brackets. */
10
+ export const dialUrl = (hostname: string, port: unknown, scheme: 'tcp' | 'udp' = 'tcp'): string => {
11
+ const host = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;
12
+ return `${scheme}://${host}:${typeof port === 'number' || typeof port === 'string' ? port : 0}`;
13
+ };
14
+
15
+ interface Target {
16
+ readonly host?: unknown;
17
+ readonly hostname?: unknown;
18
+ readonly port?: unknown;
19
+ readonly path?: unknown;
20
+ }
21
+
22
+ const isRecord = (value: unknown): value is Target => typeof value === 'object' && value !== null;
23
+
24
+ /**
25
+ * The TCP dial `connect`'s arguments name, or `undefined` for a unix socket — a path on this
26
+ * machine, never egress. Node's three shapes: `[options, cb]` (what `net.connect`, `tls`, `http`
27
+ * hand it), `(options, cb)` and `(port, host?, cb)`. No host is Node's `localhost`.
28
+ */
29
+ const tcpTarget = (args: readonly unknown[]): string | undefined => {
30
+ const first = Array.isArray(args[0]) ? args[0][0] : args[0];
31
+ if (isRecord(first)) {
32
+ const host = first.host ?? first.hostname;
33
+ if (typeof host !== 'string')
34
+ return typeof first.path === 'string' ? undefined : 'tcp://localhost:0';
35
+ return dialUrl(host, first.port);
36
+ }
37
+ if (typeof first === 'string' && !/^\d+$/.test(first)) return undefined;
38
+ return dialUrl(typeof args[1] === 'string' ? args[1] : 'localhost', first);
39
+ };
40
+
41
+ type Connect = (this: net.Socket, ...args: unknown[]) => net.Socket;
42
+
43
+ /**
44
+ * Patch `net.Socket#connect` and return the uninstaller. A refusal is a dial in flight that fails:
45
+ * `connecting` as the real one sets it, so `http`'s first write queues instead of failing
46
+ * `ERR_SOCKET_CLOSED` (measured), then the `error` event a macrotask later, once every client has
47
+ * its listener on. A throw from inside `http.get` would bypass every `error` handler the app wrote.
48
+ */
49
+ export function installNodeSocketSeal(gate: SocketGate): () => void {
50
+ const original = Reflect.get(net.Socket.prototype, 'connect') as Connect;
51
+ const sealed: Connect = function sealedConnect(this: net.Socket, ...args) {
52
+ const target = tcpTarget(args);
53
+ const refusal = target === undefined ? undefined : gate(target, 'CONNECT');
54
+ if (refusal === undefined) return Reflect.apply(original, this, args);
55
+ Reflect.set(this, 'connecting', true);
56
+ setImmediate(() => this.destroy(refusal));
57
+ return this;
58
+ };
59
+ Reflect.set(net.Socket.prototype, 'connect', sealed);
60
+ return () => {
61
+ Reflect.set(net.Socket.prototype, 'connect', original);
62
+ };
63
+ }
@@ -1,9 +1,16 @@
1
1
  // The socket half of the sealed network: `WebSocket` and `Bun.connect`, the two dials that are not
2
2
  // `fetch`. Only the patching lives here; WHETHER a dial may leave is `sealed-network.ts`'s one
3
3
  // gate, handed in, so fetch and sockets cannot disagree about the allow-list or the offline state.
4
+ // `node:*` TCP is `sealed-node-sockets.ts`, UDP `sealed-udp.ts`: installed and undone from here.
5
+
6
+ import { dialUrl, installNodeSocketSeal } from './sealed-node-sockets';
7
+ import { installUdpSeal } from './sealed-udp';
4
8
 
5
9
  /** A dial's verdict: the error to raise, or `undefined` to let it through to the real one. */
6
- export type SocketGate = (url: string, method: 'WEBSOCKET' | 'CONNECT') => Error | undefined;
10
+ export type SocketGate = (
11
+ url: string,
12
+ method: 'WEBSOCKET' | 'CONNECT' | 'SEND',
13
+ ) => Error | undefined;
7
14
 
8
15
  /** `Bun.connect`'s two option shapes, read structurally: TCP names a host, a unix socket a path. */
9
16
  interface ConnectOptions {
@@ -14,12 +21,6 @@ interface ConnectOptions {
14
21
 
15
22
  type Connect = (options: ConnectOptions) => Promise<unknown>;
16
23
 
17
- /** A dial target as a URL, so the gate parses one shape. IPv6 literals need their brackets. */
18
- const tcpUrl = (hostname: string, port: number | undefined): string => {
19
- const host = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;
20
- return `tcp://${host}:${port ?? 0}`;
21
- };
22
-
23
24
  /**
24
25
  * Patch both dials and return the uninstaller, which puts back exactly what was there — the same
25
26
  * originals, so `globalThis.WebSocket === original` holds again. Assigned through `Reflect.set`:
@@ -44,7 +45,7 @@ export function installSocketSeal(gate: SocketGate): () => void {
44
45
  // a path on this machine and is never egress.
45
46
  const sealedConnect: Connect = (options) => {
46
47
  if (options.unix === undefined && options.hostname !== undefined) {
47
- const refusal = gate(tcpUrl(options.hostname, options.port), 'CONNECT');
48
+ const refusal = gate(dialUrl(options.hostname, options.port), 'CONNECT');
48
49
  if (refusal !== undefined) return Promise.reject(refusal);
49
50
  }
50
51
  return originalConnect(options);
@@ -52,8 +53,12 @@ export function installSocketSeal(gate: SocketGate): () => void {
52
53
 
53
54
  Reflect.set(globalThis, 'WebSocket', SealedWebSocket);
54
55
  Reflect.set(Bun, 'connect', sealedConnect);
56
+ const restoreNode = installNodeSocketSeal(gate);
57
+ const restoreUdp = installUdpSeal(gate);
55
58
  return () => {
56
59
  Reflect.set(globalThis, 'WebSocket', OriginalWebSocket);
57
60
  Reflect.set(Bun, 'connect', originalConnect);
61
+ restoreNode();
62
+ restoreUdp();
58
63
  };
59
64
  }
@@ -0,0 +1,118 @@
1
+ // The UDP half of the socket seal: `Bun.udpSocket`, which `node:dgram` sends through too (measured).
2
+ // A connected socket is gated at `connect` and every send after; an unconnected one per datagram.
3
+ // A refusal surfaces as Bun's own UDP failures do: `send` throws, a `connect` rejects.
4
+
5
+ // why: Bun's `dgram.Socket#send` drops a throw when no callback is given (measured); patched below.
6
+ import dgram from 'node:dgram';
7
+ import { dialUrl } from './sealed-node-sockets';
8
+ import type { SocketGate } from './sealed-sockets';
9
+
10
+ type UdpSocketFactory = (options: unknown) => Promise<unknown>;
11
+ type Method = (...args: unknown[]) => unknown;
12
+
13
+ interface ConnectTarget {
14
+ readonly hostname?: unknown;
15
+ readonly port?: unknown;
16
+ }
17
+
18
+ /** The refusals this seal raised: the only errors the `dgram` patch re-emits. */
19
+ const refusals = new WeakSet<Error>();
20
+
21
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
22
+ typeof value === 'object' && value !== null;
23
+
24
+ /** The peer a `connect` option names, as the gate's URL; `undefined` for an unconnected socket. */
25
+ const peerOf = (options: unknown): string | undefined => {
26
+ const connect: unknown = isRecord(options) ? options['connect'] : undefined;
27
+ if (!isRecord(connect)) return undefined;
28
+ const target: ConnectTarget = connect;
29
+ return typeof target.hostname === 'string'
30
+ ? dialUrl(target.hostname, target.port, 'udp')
31
+ : undefined;
32
+ };
33
+
34
+ /**
35
+ * The peer a connected socket sends to, read off the socket at send time: `node:dgram`'s
36
+ * `connect()` re-points the native socket without `Bun.udpSocket` (measured), so a peer remembered
37
+ * from the options would miss it.
38
+ */
39
+ const remoteOf = (socket: object): string | undefined => {
40
+ const remote: unknown = Reflect.get(socket, 'remoteAddress');
41
+ if (!isRecord(remote) || typeof remote['address'] !== 'string') return undefined;
42
+ return dialUrl(remote['address'], remote['port'], 'udp');
43
+ };
44
+
45
+ /**
46
+ * Wrap one socket's two senders. Every datagram of a `sendMany` is judged before any leaves, so a
47
+ * refused batch sends nothing. A connected socket is judged per send: offline may have begun since.
48
+ */
49
+ const sealSends = (socket: object, gate: SocketGate): void => {
50
+ const send = Reflect.get(socket, 'send') as Method;
51
+ const sendMany = Reflect.get(socket, 'sendMany') as Method;
52
+ const judge = (target: string | undefined): void => {
53
+ // No target: an unconnected send without an address, which Bun refuses itself.
54
+ const refusal = target === undefined ? undefined : gate(target, 'SEND');
55
+ if (refusal === undefined) return;
56
+ refusals.add(refusal);
57
+ throw refusal;
58
+ };
59
+ Reflect.set(socket, 'send', (...args: unknown[]): unknown => {
60
+ judge(typeof args[2] === 'string' ? dialUrl(args[2], args[1], 'udp') : remoteOf(socket));
61
+ return Reflect.apply(send, socket, args);
62
+ });
63
+ Reflect.set(socket, 'sendMany', (packets: Iterable<unknown>): unknown => {
64
+ const list = [...packets];
65
+ const remote = remoteOf(socket);
66
+ if (remote !== undefined) judge(remote);
67
+ else {
68
+ for (let at = 0; at + 2 < list.length; at += 3) {
69
+ const address = list[at + 2];
70
+ if (typeof address === 'string') judge(dialUrl(address, list[at + 1], 'udp'));
71
+ }
72
+ }
73
+ return Reflect.apply(sendMany, socket, [list]);
74
+ });
75
+ };
76
+
77
+ /**
78
+ * Bun's `dgram` hands a failed send to the callback and DROPS it without one; Node emits `error`
79
+ * then. Without a callback, a refusal of ours is emitted as Node would, so it fails the test loudly.
80
+ */
81
+ const sealDgramSend = (): (() => void) => {
82
+ const send = Reflect.get(dgram.Socket.prototype, 'send') as Method;
83
+ Reflect.set(
84
+ dgram.Socket.prototype,
85
+ 'send',
86
+ function sealedSend(this: dgram.Socket, ...args: unknown[]) {
87
+ if (typeof args.at(-1) === 'function') return Reflect.apply(send, this, args);
88
+ const reemit = (error: unknown): void => {
89
+ if (error instanceof Error && refusals.has(error)) this.emit('error', error);
90
+ };
91
+ return Reflect.apply(send, this, [...args, reemit]);
92
+ },
93
+ );
94
+ return () => {
95
+ Reflect.set(dgram.Socket.prototype, 'send', send);
96
+ };
97
+ };
98
+
99
+ /** Patch `Bun.udpSocket` and return the uninstaller, which puts back exactly what was there. */
100
+ export function installUdpSeal(gate: SocketGate): () => void {
101
+ const restoreDgram = sealDgramSend();
102
+ const original = Reflect.get(Bun, 'udpSocket') as UdpSocketFactory;
103
+ const sealed: UdpSocketFactory = async (options) => {
104
+ const peer = peerOf(options);
105
+ if (peer !== undefined) {
106
+ const refusal = gate(peer, 'CONNECT');
107
+ if (refusal !== undefined) throw refusal;
108
+ }
109
+ const socket = await original(options);
110
+ if (isRecord(socket)) sealSends(socket, gate);
111
+ return socket;
112
+ };
113
+ Reflect.set(Bun, 'udpSocket', sealed);
114
+ return () => {
115
+ Reflect.set(Bun, 'udpSocket', original);
116
+ restoreDgram();
117
+ };
118
+ }