@ultimat3/testing 31.24.0 → 31.25.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 +2 -0
- package/package.json +22 -22
- package/src/admin-mount-boundary.ts +29 -0
- package/src/driver-store-boundary.ts +39 -0
- package/src/import-graph.ts +102 -0
- package/src/job-driver-checks-settle.ts +61 -2
- package/src/registry-environment.ts +82 -0
- package/src/registry-leak-guard.ts +98 -14
- package/src/registry-snapshot.ts +27 -5
package/CLAUDE.md
CHANGED
|
@@ -85,6 +85,8 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
|
|
|
85
85
|
| Leaks are the file's, not the next file's | `installRegistryLeakGuard()` runs from the preload and fails the run naming the FILE that left cache tags declared or a cache tier registered after its last test (`X_TEST_REGISTRY_LEAK`). |
|
|
86
86
|
| Reported and restored are different sets | the guard also RESTORES, at the same file boundary, the registries whose module-scope declarations a neighbour's cleanup destroys |
|
|
87
87
|
| A catalog restore is a MERGE, never a replace | the other three registries are replaced with the snapshot. `registerCatalog` has no inverse, so all a file can cost its neighbour is a `resetCatalogs()` |
|
|
88
|
+
| A file's policy environment is ITS import graph | at the body's start the permission set and role map narrow to names a module the file's import graph reaches declared (`import-graph.ts`, `registry-environment.ts`), plus the preload's and any first declared during this load; the body's own declarations end with the file. Framework repo only: an app keeps the union (`loadApp()` is no static edge) |
|
|
89
|
+
| Noted driver stores and mounted admins end with the file | `driver-store-boundary.ts`: back to the preload's notes (a store noted at a fixture's import is no later file's); `admin-mount-boundary.ts`: back to what the body inherited. Read through the require cache / the global symbol — never an import |
|
|
88
90
|
| Permissions are still REPLACED at a file boundary, and it is measured | a dynamic `loadApp()`'s `definePermissions()` is dropped there. Open. Full rule: `docs/history/testing.md` |
|
|
89
91
|
| Guarded state is boot state | the guard covers only registries that must be clean at file end — `declareTags` and `registerTier` are boot installs; "filled" and "cleared" are two questions. Full rule: `docs/history/testing.md` |
|
|
90
92
|
| An empty registry is a premise you state | a test whose subject is "nothing is declared" — `x db gen` with nothing to generate — calls `isolateEntityRegistry()` and restores in a `finally`. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.25.0",
|
|
4
4
|
"description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -47,26 +47,26 @@
|
|
|
47
47
|
"test": "bun test"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@ultimat3/action": "31.
|
|
51
|
-
"@ultimat3/ai": "31.
|
|
52
|
-
"@ultimat3/auth": "31.
|
|
53
|
-
"@ultimat3/cache": "31.
|
|
54
|
-
"@ultimat3/core": "31.
|
|
55
|
-
"@ultimat3/db": "31.
|
|
56
|
-
"@ultimat3/entity": "31.
|
|
57
|
-
"@ultimat3/http": "31.
|
|
58
|
-
"@ultimat3/i18n": "31.
|
|
59
|
-
"@ultimat3/jobs": "31.
|
|
60
|
-
"@ultimat3/mail": "31.
|
|
61
|
-
"@ultimat3/notify": "31.
|
|
62
|
-
"@ultimat3/policy": "31.
|
|
63
|
-
"@ultimat3/pwa": "31.
|
|
64
|
-
"@ultimat3/query": "31.
|
|
65
|
-
"@ultimat3/realtime": "31.
|
|
66
|
-
"@ultimat3/render": "31.
|
|
67
|
-
"@ultimat3/schema": "31.
|
|
68
|
-
"@ultimat3/scraping": "31.
|
|
69
|
-
"@ultimat3/seo": "31.
|
|
70
|
-
"@ultimat3/time": "31.
|
|
50
|
+
"@ultimat3/action": "31.25.0",
|
|
51
|
+
"@ultimat3/ai": "31.25.0",
|
|
52
|
+
"@ultimat3/auth": "31.25.0",
|
|
53
|
+
"@ultimat3/cache": "31.25.0",
|
|
54
|
+
"@ultimat3/core": "31.25.0",
|
|
55
|
+
"@ultimat3/db": "31.25.0",
|
|
56
|
+
"@ultimat3/entity": "31.25.0",
|
|
57
|
+
"@ultimat3/http": "31.25.0",
|
|
58
|
+
"@ultimat3/i18n": "31.25.0",
|
|
59
|
+
"@ultimat3/jobs": "31.25.0",
|
|
60
|
+
"@ultimat3/mail": "31.25.0",
|
|
61
|
+
"@ultimat3/notify": "31.25.0",
|
|
62
|
+
"@ultimat3/policy": "31.25.0",
|
|
63
|
+
"@ultimat3/pwa": "31.25.0",
|
|
64
|
+
"@ultimat3/query": "31.25.0",
|
|
65
|
+
"@ultimat3/realtime": "31.25.0",
|
|
66
|
+
"@ultimat3/render": "31.25.0",
|
|
67
|
+
"@ultimat3/schema": "31.25.0",
|
|
68
|
+
"@ultimat3/scraping": "31.25.0",
|
|
69
|
+
"@ultimat3/seo": "31.25.0",
|
|
70
|
+
"@ultimat3/time": "31.25.0"
|
|
71
71
|
}
|
|
72
72
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The admins `defineAdmin()` mounted, put back at the file boundary to what the file inherited:
|
|
2
|
+
// ~50 admin suites mount one and never clear it, and the `i18n` step audits EVERY mounted admin,
|
|
3
|
+
// so on a shared worker one file's admin was a later file's X_CATALOG_MISSING_KEYS.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `@ultimat3/admin`'s `ADMIN_MOUNTS`, restated as `@ultimat3/cli`'s `runtime-admin.ts` does —
|
|
7
|
+
* never imported: `testing` is tier 5 beside `admin`, and an app with no admin must not load one.
|
|
8
|
+
*/
|
|
9
|
+
const ADMIN_MOUNTS = Symbol.for('ultimate.admin.mounts');
|
|
10
|
+
|
|
11
|
+
type Mounted = readonly (readonly [string, unknown])[];
|
|
12
|
+
|
|
13
|
+
const held = (): Map<string, unknown> | undefined => {
|
|
14
|
+
const value = (globalThis as { [key: symbol]: unknown })[ADMIN_MOUNTS];
|
|
15
|
+
return value instanceof Map ? (value as Map<string, unknown>) : undefined;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Every mount by base path, in declaration order; nothing while no admin was ever declared. */
|
|
19
|
+
export function captureAdminMounts(): Mounted {
|
|
20
|
+
return [...(held() ?? new Map<string, unknown>())];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Exactly `mounted` again, in its order — the same Map, so a reader holding it sees the change. */
|
|
24
|
+
export function restoreAdminMounts(mounted: Mounted): void {
|
|
25
|
+
const live = held();
|
|
26
|
+
if (live === undefined) return;
|
|
27
|
+
live.clear();
|
|
28
|
+
for (const [basePath, app] of mounted) live.set(basePath, app);
|
|
29
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The driver kinds `@ultimat3/entity` has noted (`driverStores()`), put back at the file boundary
|
|
2
|
+
// to what the preload had noted: the drift step reads that record to tell a Postgres app from a
|
|
3
|
+
// `defineDriver` one, and one file's custom driver made every later file's fixture app non-SQL.
|
|
4
|
+
|
|
5
|
+
import type { clearDriverStores, driverStores, noteDriverStore } from '@ultimat3/entity/adapter';
|
|
6
|
+
import { loaded } from './per-test-reset';
|
|
7
|
+
|
|
8
|
+
interface DriverRegistry {
|
|
9
|
+
readonly driverStores: typeof driverStores;
|
|
10
|
+
readonly clearDriverStores: typeof clearDriverStores;
|
|
11
|
+
readonly noteDriverStore: typeof noteDriverStore;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type Noted = ReturnType<typeof driverStores>;
|
|
15
|
+
|
|
16
|
+
const EMPTY: Noted = { sql: [], custom: [] };
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The registry module when something in this process loaded it, else `undefined`. Read through the
|
|
20
|
+
* `require` cache, never imported: `@ultimat3/entity` stays out of every `packages/core` graph.
|
|
21
|
+
*/
|
|
22
|
+
const registry = (): DriverRegistry | undefined => {
|
|
23
|
+
const path = loaded('@ultimat3/entity', 'driver-registry.ts');
|
|
24
|
+
return path === undefined ? undefined : (require(path) as DriverRegistry);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** What is noted now; nothing when the package was never loaded. */
|
|
28
|
+
export function captureDriverStores(): Noted {
|
|
29
|
+
return registry()?.driverStores() ?? EMPTY;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Exactly `noted` again — a REPLACE, as the permission set is. A no-op while entity is unloaded. */
|
|
33
|
+
export function restoreDriverStores(noted: Noted): void {
|
|
34
|
+
const live = registry();
|
|
35
|
+
if (live === undefined) return;
|
|
36
|
+
live.clearDriverStores();
|
|
37
|
+
for (const name of noted.sql) live.noteDriverStore('sql', name);
|
|
38
|
+
for (const name of noted.custom) live.noteDriverStore('custom', name);
|
|
39
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Every module a test file can reach by import, read from source: what a shared worker uses to
|
|
2
|
+
// tell a file's OWN environment from the declarations an earlier file's imports left behind. Bun
|
|
3
|
+
// publishes no module graph (`require.cache` entries carry no `children` for ESM), so it is scanned.
|
|
4
|
+
|
|
5
|
+
/** The closure, and whether every module in it could be read: an incomplete one filters nothing. */
|
|
6
|
+
export interface ImportGraph {
|
|
7
|
+
readonly modules: ReadonlySet<string>;
|
|
8
|
+
readonly complete: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Only these are scanned; a `.json` or `.css` import is a leaf that declares nothing. */
|
|
12
|
+
const CODE = /\.[cm]?[jt]sx?$/;
|
|
13
|
+
|
|
14
|
+
/** `bin.ts` opens with a shebang, which the transpiler refuses as a syntax error. */
|
|
15
|
+
const withoutShebang = (source: string): string =>
|
|
16
|
+
source.startsWith('#!') ? `//${source.slice(2)}` : source;
|
|
17
|
+
|
|
18
|
+
const transpilers = {
|
|
19
|
+
ts: new Bun.Transpiler({ loader: 'ts' }),
|
|
20
|
+
tsx: new Bun.Transpiler({ loader: 'tsx' }),
|
|
21
|
+
js: new Bun.Transpiler({ loader: 'js' }),
|
|
22
|
+
jsx: new Bun.Transpiler({ loader: 'jsx' }),
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
const transpilerFor = (path: string): Bun.Transpiler => {
|
|
26
|
+
if (path.endsWith('.tsx')) return transpilers.tsx;
|
|
27
|
+
if (path.endsWith('.jsx')) return transpilers.jsx;
|
|
28
|
+
if (/\.[cm]?ts$/.test(path)) return transpilers.ts;
|
|
29
|
+
return transpilers.js;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const dirOf = (path: string): string => path.slice(0, Math.max(path.lastIndexOf('/'), 0)) || '/';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A module's direct imports, resolved, or `undefined` when its source could not be read. Third-
|
|
36
|
+
* party code under `node_modules` is a leaf: it never declares an Ultimate permission, and walking
|
|
37
|
+
* it would multiply the scan for nothing. A specifier that does not resolve statically (a template
|
|
38
|
+
* `import()`, a plugin's virtual module) is skipped — the caller keeps anything first declared
|
|
39
|
+
* during the file, so a module reached that way is not lost on its first evaluation.
|
|
40
|
+
*/
|
|
41
|
+
async function directImports(path: string): Promise<readonly string[] | undefined> {
|
|
42
|
+
if (!CODE.test(path) || path.endsWith('.d.ts') || path.includes('/node_modules/')) return [];
|
|
43
|
+
let source: string;
|
|
44
|
+
try {
|
|
45
|
+
source = await Bun.file(path).text();
|
|
46
|
+
} catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
let specifiers: readonly string[];
|
|
50
|
+
try {
|
|
51
|
+
specifiers = transpilerFor(path)
|
|
52
|
+
.scanImports(withoutShebang(source))
|
|
53
|
+
.map((entry) => entry.path);
|
|
54
|
+
} catch {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
const dir = dirOf(path);
|
|
58
|
+
const resolved: string[] = [];
|
|
59
|
+
for (const specifier of specifiers) {
|
|
60
|
+
if (specifier.startsWith('bun:') || specifier.startsWith('node:')) continue;
|
|
61
|
+
try {
|
|
62
|
+
resolved.push(Bun.resolveSync(specifier, dir));
|
|
63
|
+
} catch {
|
|
64
|
+
// Unresolvable statically: see the doc comment.
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return resolved;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One reader per process: a module's imports are read once however many files reach it. */
|
|
71
|
+
export function importGraphReader(): (entry: string) => Promise<ImportGraph> {
|
|
72
|
+
const direct = new Map<string, Promise<readonly string[] | undefined>>();
|
|
73
|
+
const importsOf = (path: string): Promise<readonly string[] | undefined> => {
|
|
74
|
+
let pending = direct.get(path);
|
|
75
|
+
if (pending === undefined) {
|
|
76
|
+
pending = directImports(path);
|
|
77
|
+
direct.set(path, pending);
|
|
78
|
+
}
|
|
79
|
+
return pending;
|
|
80
|
+
};
|
|
81
|
+
return async (entry) => {
|
|
82
|
+
const modules = new Set<string>([entry]);
|
|
83
|
+
let complete = true;
|
|
84
|
+
let frontier = [entry];
|
|
85
|
+
while (frontier.length > 0) {
|
|
86
|
+
const next: string[] = [];
|
|
87
|
+
for (const imports of await Promise.all(frontier.map(importsOf))) {
|
|
88
|
+
if (imports === undefined) {
|
|
89
|
+
complete = false;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
for (const module of imports) {
|
|
93
|
+
if (modules.has(module)) continue;
|
|
94
|
+
modules.add(module);
|
|
95
|
+
next.push(module);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
frontier = next;
|
|
99
|
+
}
|
|
100
|
+
return { modules, complete };
|
|
101
|
+
};
|
|
102
|
+
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// What every `JobDriver` records for `onSettled` (J11): a settle that ENDS a run of a job with a
|
|
2
2
|
// hook owes it, the hook's return clears the debt under that claim, and a debt a crash left is
|
|
3
|
-
// taken once per grace
|
|
3
|
+
// taken once per grace — and a row the CLAIM settles (a final-attempt burial, an expiry) owes it
|
|
4
|
+
// too, named by `ClaimOptions.settleOwed`. A driver with no `settleDebt` fails here.
|
|
5
|
+
//
|
|
4
6
|
// Type-only imports: the barrel never loads `@ultimat3/jobs`.
|
|
5
7
|
|
|
6
8
|
import { expect } from 'bun:test';
|
|
7
|
-
import type { JobDriver, SettleDebt } from '@ultimat3/jobs';
|
|
9
|
+
import type { JobDriver, JobRecord, SettleDebt } from '@ultimat3/jobs';
|
|
8
10
|
import type { JobDriverCheck } from './job-driver-checks';
|
|
9
11
|
|
|
10
12
|
let minted = 0;
|
|
@@ -93,4 +95,61 @@ export const SETTLE_DEBT_CHECKS: readonly JobDriverCheck[] = [
|
|
|
93
95
|
expect(await lost(debt, at.name)).toEqual([]);
|
|
94
96
|
},
|
|
95
97
|
},
|
|
98
|
+
{
|
|
99
|
+
name: 'a row the claim buries or expires owes onSettled when settleOwed names its job',
|
|
100
|
+
async run(driver) {
|
|
101
|
+
const debt = debtOf(driver);
|
|
102
|
+
const hooked = scope();
|
|
103
|
+
const plain = scope();
|
|
104
|
+
// A final attempt whose lease lapsed (0 ms), for each job; and an expired row of the hooked.
|
|
105
|
+
const lapsing = async (at: typeof hooked): Promise<string> => {
|
|
106
|
+
const { id } = await driver.enqueue({
|
|
107
|
+
name: at.name,
|
|
108
|
+
queue: at.queue,
|
|
109
|
+
input: {},
|
|
110
|
+
idempotencyKey: 'lapsing',
|
|
111
|
+
maxAttempts: 1,
|
|
112
|
+
});
|
|
113
|
+
const taken = await driver.claim({
|
|
114
|
+
queues: [at.queue],
|
|
115
|
+
limit: 1,
|
|
116
|
+
visibilityTimeoutMs: 0,
|
|
117
|
+
workerId: 'w-gone',
|
|
118
|
+
});
|
|
119
|
+
expect(taken.map((row) => row.id)).toEqual([id]);
|
|
120
|
+
return id;
|
|
121
|
+
};
|
|
122
|
+
const dead = await lapsing(hooked);
|
|
123
|
+
const unowed = await lapsing(plain);
|
|
124
|
+
const expired = await driver.enqueue({
|
|
125
|
+
name: hooked.name,
|
|
126
|
+
queue: hooked.queue,
|
|
127
|
+
input: {},
|
|
128
|
+
idempotencyKey: 'expired',
|
|
129
|
+
maxAttempts: 3,
|
|
130
|
+
expiresAt: 1,
|
|
131
|
+
});
|
|
132
|
+
const buried: JobRecord[] = [];
|
|
133
|
+
for (const at of [hooked, plain]) {
|
|
134
|
+
const handed = await driver.claim({
|
|
135
|
+
queues: [at.queue],
|
|
136
|
+
limit: 10,
|
|
137
|
+
visibilityTimeoutMs: 30_000,
|
|
138
|
+
workerId: 'w-burier',
|
|
139
|
+
settleOwed: [hooked.name],
|
|
140
|
+
onExhausted: (rows) => buried.push(...rows),
|
|
141
|
+
});
|
|
142
|
+
expect(handed).toEqual([]);
|
|
143
|
+
}
|
|
144
|
+
expect(buried.map((row) => row.id).sort()).toEqual([dead, expired.id, unowed].sort());
|
|
145
|
+
// Recorded by the claim's own write: a burier that dies now leaves it for the leader.
|
|
146
|
+
expect([...(await lost(debt, hooked.name))].sort()).toEqual([dead, expired.id].sort());
|
|
147
|
+
expect(await lost(debt, plain.name)).toEqual([]);
|
|
148
|
+
// Paid under the claim the buried row carries — the one the burier was handed.
|
|
149
|
+
for (const row of buried.filter((each) => each.name === hooked.name)) {
|
|
150
|
+
expect(await debt.clear(row.id, row.claim ?? 0)).toBe(true);
|
|
151
|
+
}
|
|
152
|
+
expect(await lost(debt, hooked.name)).toEqual([]);
|
|
153
|
+
},
|
|
154
|
+
},
|
|
96
155
|
];
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The permissions and roles a test file inherits on a shared worker: what a module in ITS import
|
|
2
|
+
// graph declared, never what a module only an earlier file imported left behind. Read from each
|
|
3
|
+
// name's declaration site; `registry-leak-guard.ts` owns WHEN, `import-graph.ts` the graph.
|
|
4
|
+
|
|
5
|
+
import type { RoleMap } from '@ultimat3/policy';
|
|
6
|
+
import type { ImportGraph } from './import-graph';
|
|
7
|
+
import type { ProcessRegistrySnapshot } from './registry-snapshot';
|
|
8
|
+
|
|
9
|
+
/** The policy half of a snapshot — the only half this narrows. */
|
|
10
|
+
export type PolicyEnvironment = Pick<
|
|
11
|
+
ProcessRegistrySnapshot,
|
|
12
|
+
'permissions' | 'permissionSites' | 'roles' | 'roleSites'
|
|
13
|
+
>;
|
|
14
|
+
|
|
15
|
+
/** Names kept whatever the graph says: the preload's, and those first declared during THIS load. */
|
|
16
|
+
export interface KeptNames {
|
|
17
|
+
readonly permissions: ReadonlySet<string>;
|
|
18
|
+
readonly roles: ReadonlySet<string>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** `?x-reload=…` is a loader's cache key, not part of the file. */
|
|
22
|
+
const withoutQuery = (path: string): string => path.replace(/\?.*$/, '');
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The file a stack frame names — `at /a/b.ts:5:1`, `at fn (/a/b.ts:5:1)`, `at async C:\a\b.ts:5:1`
|
|
26
|
+
* — `/`-normalised, or `undefined` for a frame that names none (`unknown site`, `<anonymous>`).
|
|
27
|
+
*/
|
|
28
|
+
export function siteFile(frame: string): string | undefined {
|
|
29
|
+
const line = frame.trim();
|
|
30
|
+
const file = (/\(([^()]+):\d+:\d+\)$/.exec(line) ??
|
|
31
|
+
/^at (?:async )?(.+):\d+:\d+$/.exec(line))?.[1];
|
|
32
|
+
if (file === undefined || file.startsWith('<') || file.startsWith('native')) return undefined;
|
|
33
|
+
return withoutQuery(file.replaceAll('\\', '/'));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* In the graph when ANY site is, and when a site cannot be read at all: an unreadable site is
|
|
38
|
+
* provenance this cannot judge, and dropping a name a cached module really declared is the one
|
|
39
|
+
* failure a file cannot repair from inside.
|
|
40
|
+
*/
|
|
41
|
+
const reachable = (sites: readonly string[], modules: ReadonlySet<string>): boolean =>
|
|
42
|
+
sites.length === 0 ||
|
|
43
|
+
sites.some((site) => {
|
|
44
|
+
const file = siteFile(site);
|
|
45
|
+
return file === undefined || modules.has(file);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `inherited` narrowed to the names `graph` reaches, plus `kept`. An incomplete graph narrows
|
|
50
|
+
* nothing: a module it could not read may be the one that declared.
|
|
51
|
+
*/
|
|
52
|
+
export function ownEnvironment(
|
|
53
|
+
inherited: PolicyEnvironment,
|
|
54
|
+
graph: ImportGraph,
|
|
55
|
+
kept: KeptNames,
|
|
56
|
+
): PolicyEnvironment {
|
|
57
|
+
if (!graph.complete) return inherited;
|
|
58
|
+
const modules = new Set([...graph.modules].map((path) => path.replaceAll('\\', '/')));
|
|
59
|
+
const permissions = inherited.permissions.filter(
|
|
60
|
+
(name) =>
|
|
61
|
+
kept.permissions.has(name) ||
|
|
62
|
+
reachable(
|
|
63
|
+
Object.hasOwn(inherited.permissionSites, name)
|
|
64
|
+
? (inherited.permissionSites[name] ?? [])
|
|
65
|
+
: [],
|
|
66
|
+
modules,
|
|
67
|
+
),
|
|
68
|
+
);
|
|
69
|
+
const roles: Record<string, RoleMap[string]> = {};
|
|
70
|
+
const roleSites: Record<string, string> = {};
|
|
71
|
+
for (const [name, definition] of Object.entries(inherited.roles)) {
|
|
72
|
+
const site = Object.hasOwn(inherited.roleSites, name) ? inherited.roleSites[name] : undefined;
|
|
73
|
+
if (!kept.roles.has(name) && !reachable(site === undefined ? [] : [site], modules)) continue;
|
|
74
|
+
roles[name] = definition;
|
|
75
|
+
if (site !== undefined) roleSites[name] = site;
|
|
76
|
+
}
|
|
77
|
+
const permitted = new Set(permissions);
|
|
78
|
+
const permissionSites = Object.fromEntries(
|
|
79
|
+
Object.entries(inherited.permissionSites).filter(([name]) => permitted.has(name)),
|
|
80
|
+
);
|
|
81
|
+
return { permissions, permissionSites, roles, roleSites };
|
|
82
|
+
}
|
|
@@ -5,13 +5,19 @@
|
|
|
5
5
|
|
|
6
6
|
import { afterAll } from 'bun:test';
|
|
7
7
|
import { knownTags, registeredTiers } from '@ultimat3/cache';
|
|
8
|
+
import { configureLocales } from '@ultimat3/i18n';
|
|
9
|
+
import { captureAdminMounts, restoreAdminMounts } from './admin-mount-boundary';
|
|
8
10
|
import { isAppRoot } from './app-root';
|
|
11
|
+
import { captureDriverStores, restoreDriverStores } from './driver-store-boundary';
|
|
9
12
|
import { RegistryLeakError } from './errors';
|
|
10
13
|
import { runBoundaryHooks, runFileBoundary } from './file-boundary';
|
|
14
|
+
import { type ImportGraph, importGraphReader } from './import-graph';
|
|
15
|
+
import { ownEnvironment } from './registry-environment';
|
|
11
16
|
import type { ProcessRegistrySnapshot } from './registry-snapshot';
|
|
12
17
|
import {
|
|
13
18
|
captureProcessRegistries,
|
|
14
19
|
mergeSnapshots,
|
|
20
|
+
restorePolicyRegistries,
|
|
15
21
|
restoreProcessRegistries,
|
|
16
22
|
} from './registry-snapshot';
|
|
17
23
|
import { rerunDeclarations } from './rerun-declarations';
|
|
@@ -34,14 +40,14 @@ import { frameworkDeclarationRegistries } from './rerun-registries';
|
|
|
34
40
|
* "Idiomatic to leave filled" says nothing about a file that calls `clear*()`/`reset*()` and takes
|
|
35
41
|
* a module-scope declaration from every file after it — a module evaluates once per process, so the
|
|
36
42
|
* next file's own `import` is a cache hit that declares nothing. That is what `registry-snapshot.ts`
|
|
37
|
-
* repairs, and it repairs
|
|
43
|
+
* repairs, and it repairs SEVEN registries out of the set that has one:
|
|
38
44
|
*
|
|
39
45
|
* | registry | reset export | owner | in the snapshot? |
|
|
40
46
|
* |---|---|---|---|
|
|
41
47
|
* | locales / catalogs | `resetCatalogs` | `@ultimat3/i18n` | yes |
|
|
42
48
|
* | permissions / roles | `restorePermissions` / `restoreRoles` | `@ultimat3/policy` | yes |
|
|
43
49
|
* | routes | `clearRoutes` | `@ultimat3/render` | **no** |
|
|
44
|
-
* | jobs | `resetJobs` / `restoreJobs` | `@ultimat3/jobs` |
|
|
50
|
+
* | jobs | `resetJobs` / `restoreJobs` | `@ultimat3/jobs` | yes (2026-11) |
|
|
45
51
|
* | tasks | `restoreTasks` | `@ultimat3/jobs` | yes (22.7) |
|
|
46
52
|
* | measurement actor | `resetMeasurementActor` | `@ultimat3/core` | yes |
|
|
47
53
|
* | actions | `resetActions` | `@ultimat3/action` | **no** |
|
|
@@ -109,7 +115,10 @@ const repoRelative = (path: string): string => {
|
|
|
109
115
|
*/
|
|
110
116
|
const BASELINE_HOOK = '__ultimateRegistryLeakBaseline';
|
|
111
117
|
|
|
112
|
-
/**
|
|
118
|
+
/**
|
|
119
|
+
* Appended: the TAG baseline is the file's whole module scope, its body's declarations included.
|
|
120
|
+
* The RESTORE baseline is not — it is taken at `BODY_START_HOOK`, below.
|
|
121
|
+
*/
|
|
113
122
|
const SAMPLE_BASELINE = `\n;globalThis[${JSON.stringify(BASELINE_HOOK)}]?.();\n`;
|
|
114
123
|
|
|
115
124
|
/**
|
|
@@ -117,6 +126,14 @@ const SAMPLE_BASELINE = `\n;globalThis[${JSON.stringify(BASELINE_HOOK)}]?.();\n`
|
|
|
117
126
|
* and before its body (measured on Bun 1.4.4) — the start of the window in which the BODY declares
|
|
118
127
|
* (`rerun-declarations.ts`). On line 1 with no newline, so every line number a stack trace or a
|
|
119
128
|
* coverage report names is the file's own.
|
|
129
|
+
*
|
|
130
|
+
* It is also where the RESTORE snapshot is taken, and why there rather than after the body: the
|
|
131
|
+
* imports are the file's environment — a cached module never declares again, so what it declared
|
|
132
|
+
* has to outlive the file — but a `.test.ts` body is imported by no other file, so nothing it
|
|
133
|
+
* declared is anyone's cache hit. Sampled after the body (until 2026-11), every test file's
|
|
134
|
+
* module-scope `definePermissions()` / `defineRoles()` was folded into what each later file on the
|
|
135
|
+
* worker inherited: strict permission checking switched on for files that declared nothing, and
|
|
136
|
+
* `X_ROLE_REDEFINED` in the next file that defined the same role its own way.
|
|
120
137
|
*/
|
|
121
138
|
const BODY_START_HOOK = '__ultimateBodyStart';
|
|
122
139
|
const SAMPLE_BODY_START = `;globalThis[${JSON.stringify(BODY_START_HOOK)}]?.();`;
|
|
@@ -146,8 +163,10 @@ export function installRegistryLeakGuard(): void {
|
|
|
146
163
|
let current:
|
|
147
164
|
| {
|
|
148
165
|
readonly file: string;
|
|
149
|
-
|
|
166
|
+
/** Unset until the body ends: a body that threw is restored, never judged for tags. */
|
|
167
|
+
before: RegistrySample | undefined;
|
|
150
168
|
readonly snapshot: ProcessRegistrySnapshot;
|
|
169
|
+
readonly admins: ReturnType<typeof captureAdminMounts>;
|
|
151
170
|
}
|
|
152
171
|
| undefined;
|
|
153
172
|
const leaks: RegistryLeak[] = [];
|
|
@@ -157,14 +176,30 @@ export function installRegistryLeakGuard(): void {
|
|
|
157
176
|
const pristineLocales = JSON.stringify(captureProcessRegistries().locales);
|
|
158
177
|
const inApp = isAppRoot();
|
|
159
178
|
const reruns = rerunDeclarations(frameworkDeclarationRegistries);
|
|
179
|
+
// The preload's own declarations are every file's: no test file's graph reaches the preload.
|
|
180
|
+
const atPreload = captureProcessRegistries();
|
|
181
|
+
const preloadNames = {
|
|
182
|
+
permissions: new Set(atPreload.permissions),
|
|
183
|
+
roles: new Set(Object.keys(atPreload.roles)),
|
|
184
|
+
};
|
|
185
|
+
// What the last boundary put back: a name live at a body's start and absent here was declared
|
|
186
|
+
// by a module THIS file's load evaluated for the first time — its own, whatever the graph says.
|
|
187
|
+
let lastBoundary = atPreload;
|
|
188
|
+
const preloadStores = captureDriverStores();
|
|
189
|
+
const graphOf = importGraphReader();
|
|
190
|
+
let graph: ImportGraph | undefined;
|
|
160
191
|
|
|
161
192
|
const close = (): void => {
|
|
162
193
|
if (current === undefined) return;
|
|
163
|
-
const leak =
|
|
194
|
+
const leak =
|
|
195
|
+
current.before === undefined
|
|
196
|
+
? undefined
|
|
197
|
+
: leakBetween(current.file, current.before, sampleRegistries());
|
|
164
198
|
if (leak !== undefined) leaks.push(leak);
|
|
165
199
|
// The repair, at the only point it is safe: the file is over and the next one has not
|
|
166
200
|
// evaluated yet, so what goes back is exactly what that file inherited — module-scope
|
|
167
|
-
// declarations included, which is the half a plain `resetX()` in a `beforeEach` destroys
|
|
201
|
+
// declarations included, which is the half a plain `resetX()` in a `beforeEach` destroys —
|
|
202
|
+
// and the file's own BODY excluded (`BODY_START_HOOK`).
|
|
168
203
|
//
|
|
169
204
|
// In an APP, declarations are put back as a UNION with what the process holds now (22.7,
|
|
170
205
|
// shared worker): an app module a test imported lazily declared its permissions and roles once,
|
|
@@ -189,23 +224,70 @@ export function installRegistryLeakGuard(): void {
|
|
|
189
224
|
...merged,
|
|
190
225
|
locales: declaredLazily ? live.locales : current.snapshot.locales,
|
|
191
226
|
tasks: current.snapshot.tasks,
|
|
227
|
+
jobs: current.snapshot.jobs,
|
|
192
228
|
};
|
|
193
229
|
restoreProcessRegistries(restored);
|
|
230
|
+
// To the PRELOAD's notes, never the body's start: a store is noted as its driver is built,
|
|
231
|
+
// and a fixture module that builds one at import noted it for every later file on the worker —
|
|
232
|
+
// whose drift step then read its fixture app as "a store that owns its own schema".
|
|
233
|
+
restoreDriverStores(preloadStores);
|
|
234
|
+
restoreAdminMounts(current.admins);
|
|
194
235
|
accumulated = mergeSnapshots(accumulated, restored);
|
|
236
|
+
lastBoundary = restored;
|
|
195
237
|
current = undefined;
|
|
196
238
|
};
|
|
197
239
|
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
240
|
+
// The framework repository's files, on a shared worker, start from THEIR graph's policy
|
|
241
|
+
// declarations (`registry-environment.ts`), put in place before the body runs. An app keeps the
|
|
242
|
+
// union: its tests reach app modules through `loadApp()`, which no static graph shows.
|
|
243
|
+
const narrowed = (
|
|
244
|
+
live: ProcessRegistrySnapshot,
|
|
245
|
+
inherited: ProcessRegistrySnapshot,
|
|
246
|
+
): ProcessRegistrySnapshot => {
|
|
247
|
+
if (inApp || graph === undefined) return inherited;
|
|
248
|
+
const fresh = (names: readonly string[], before: readonly string[]): Set<string> =>
|
|
249
|
+
new Set(names.filter((name) => !before.includes(name)));
|
|
250
|
+
const kept = {
|
|
251
|
+
permissions: new Set([
|
|
252
|
+
...preloadNames.permissions,
|
|
253
|
+
...fresh(live.permissions, lastBoundary.permissions),
|
|
254
|
+
]),
|
|
255
|
+
roles: new Set([
|
|
256
|
+
...preloadNames.roles,
|
|
257
|
+
...fresh(Object.keys(live.roles), Object.keys(lastBoundary.roles)),
|
|
258
|
+
]),
|
|
259
|
+
};
|
|
260
|
+
// The locale config likewise: an earlier file's import that narrowed it (an app's
|
|
261
|
+
// `defineCatalogs()`) is no environment of this one — unless THIS load moved it.
|
|
262
|
+
const movedNow = JSON.stringify(live.locales) !== JSON.stringify(lastBoundary.locales);
|
|
263
|
+
const locales = movedNow ? live.locales : atPreload.locales;
|
|
264
|
+
const own = { ...inherited, ...ownEnvironment(inherited, graph, kept), locales };
|
|
265
|
+
restorePolicyRegistries(own);
|
|
266
|
+
configureLocales(locales);
|
|
267
|
+
return own;
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
// Both called from the file's own source, once per test file. At the body's START everything
|
|
271
|
+
// the file's IMPORT graph registered is its environment, and is what the boundary restores to.
|
|
272
|
+
// At the body's END everything the module scope registered is the TAG baseline — importing an
|
|
273
|
+
// app module is how an app declares its tags — and everything after it is the file's to undo.
|
|
274
|
+
hookHost[BODY_START_HOOK] = () => {
|
|
275
|
+
reruns.bodyStart();
|
|
204
276
|
if (pending === undefined) return;
|
|
205
|
-
|
|
206
|
-
|
|
277
|
+
const live = captureProcessRegistries();
|
|
278
|
+
accumulated = mergeSnapshots(accumulated, live);
|
|
279
|
+
current = {
|
|
280
|
+
file: pending,
|
|
281
|
+
before: undefined,
|
|
282
|
+
snapshot: narrowed(live, accumulated),
|
|
283
|
+
admins: captureAdminMounts(),
|
|
284
|
+
};
|
|
207
285
|
pending = undefined;
|
|
208
286
|
};
|
|
287
|
+
hookHost[BASELINE_HOOK] = () => {
|
|
288
|
+
reruns.bodyEnd();
|
|
289
|
+
if (current !== undefined && current.before === undefined) current.before = sampleRegistries();
|
|
290
|
+
};
|
|
209
291
|
|
|
210
292
|
// The only signal Bun gives a preload for "a new test file starts": its hooks carry no file. A
|
|
211
293
|
// load handler MUST answer with contents — one that answers `undefined` makes Bun load nothing
|
|
@@ -225,6 +307,8 @@ export function installRegistryLeakGuard(): void {
|
|
|
225
307
|
runFileBoundary();
|
|
226
308
|
close();
|
|
227
309
|
pending = repoRelative(args.path);
|
|
310
|
+
// Read before the file evaluates — a body-start hook is synchronous and this is not.
|
|
311
|
+
graph = inApp ? undefined : await graphOf(args.path);
|
|
228
312
|
// `loading` closes the previous file's window first (`fileEnd`).
|
|
229
313
|
reruns.loading(args.path);
|
|
230
314
|
return {
|
package/src/registry-snapshot.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// module declares at MODULE scope evaluates once per `bun test` process — a neighbour's clear is
|
|
4
4
|
// permanent and there is no second evaluation left to redo it.
|
|
5
5
|
//
|
|
6
|
-
//
|
|
6
|
+
// SEVEN registries, out of roughly nine that publish a `clear*`/`reset*`. The missing ones and what
|
|
7
7
|
// each still needs are tabulated in `registry-leak-guard.ts` beside `RegistrySample` — every one of
|
|
8
8
|
// them needs a RESTORE in its owning package first, the way `restorePermissions` / `restoreRoles`
|
|
9
9
|
// were added to `@ultimat3/policy` for the two rows below.
|
|
@@ -25,8 +25,8 @@ import {
|
|
|
25
25
|
registeredLocales,
|
|
26
26
|
resetCatalogs,
|
|
27
27
|
} from '@ultimat3/i18n';
|
|
28
|
-
import type { TaskHandle } from '@ultimat3/jobs';
|
|
29
|
-
import { registeredTasks, restoreTasks } from '@ultimat3/jobs';
|
|
28
|
+
import type { AnyJobHandle, TaskHandle } from '@ultimat3/jobs';
|
|
29
|
+
import { registeredJobs, registeredTasks, restoreJobs, restoreTasks } from '@ultimat3/jobs';
|
|
30
30
|
import type { RoleMap } from '@ultimat3/policy';
|
|
31
31
|
import {
|
|
32
32
|
knownPermissions,
|
|
@@ -57,6 +57,13 @@ export interface ProcessRegistrySnapshot {
|
|
|
57
57
|
* fired in every later file's `appManifest` round — 14 framework failures, measured.
|
|
58
58
|
*/
|
|
59
59
|
readonly tasks: readonly TaskHandle[];
|
|
60
|
+
/**
|
|
61
|
+
* Jobs, for the tasks' reason read the other way: `job()` runs at module scope (`sendMailJob`),
|
|
62
|
+
* and `job.test.ts` `resetJobs()` in every `beforeEach` — so on a shared worker every later file
|
|
63
|
+
* lost the jobs its cached imports had declared, and a fixture app with no module of its own
|
|
64
|
+
* read as X_APP_EMPTY (`@ultimat3/cli`'s `loadApp` counts the process's registries).
|
|
65
|
+
*/
|
|
66
|
+
readonly jobs: readonly AnyJobHandle[];
|
|
60
67
|
/** `defineCatalogs()` calls so far — see `@ultimat3/i18n`'s `catalogDeclarationCount`. */
|
|
61
68
|
readonly catalogDeclarations: number;
|
|
62
69
|
/**
|
|
@@ -77,6 +84,7 @@ export function captureProcessRegistries(): ProcessRegistrySnapshot {
|
|
|
77
84
|
roles: roleDefinitions(),
|
|
78
85
|
roleSites: roleDeclarationSites(),
|
|
79
86
|
tasks: registeredTasks(),
|
|
87
|
+
jobs: registeredJobs(),
|
|
80
88
|
catalogDeclarations: catalogDeclarationCount(),
|
|
81
89
|
measurementActor: declaredMeasurementActor(),
|
|
82
90
|
};
|
|
@@ -92,13 +100,24 @@ export function restoreProcessRegistries(snapshot: ProcessRegistrySnapshot): voi
|
|
|
92
100
|
// a partial call can never widen `supported` back.
|
|
93
101
|
configureLocales(snapshot.locales);
|
|
94
102
|
restoreCatalogs(snapshot.catalogs);
|
|
95
|
-
|
|
96
|
-
restoreRoles(snapshot.roles, snapshot.roleSites);
|
|
103
|
+
restorePolicyRegistries(snapshot);
|
|
97
104
|
restoreTasks(snapshot.tasks);
|
|
105
|
+
restoreJobs(snapshot.jobs);
|
|
98
106
|
if (snapshot.measurementActor === undefined) resetMeasurementActor();
|
|
99
107
|
else defineMeasurementActor(snapshot.measurementActor);
|
|
100
108
|
}
|
|
101
109
|
|
|
110
|
+
/** The permission set and the role map alone, each with its declaration sites. */
|
|
111
|
+
export function restorePolicyRegistries(
|
|
112
|
+
snapshot: Pick<
|
|
113
|
+
ProcessRegistrySnapshot,
|
|
114
|
+
'permissions' | 'permissionSites' | 'roles' | 'roleSites'
|
|
115
|
+
>,
|
|
116
|
+
): void {
|
|
117
|
+
restorePermissions(snapshot.permissions, snapshot.permissionSites);
|
|
118
|
+
restoreRoles(snapshot.roles, snapshot.roleSites);
|
|
119
|
+
}
|
|
120
|
+
|
|
102
121
|
/**
|
|
103
122
|
* Repair a clear; never undo a registration. The catalogs are the one registry here restored by
|
|
104
123
|
* MERGE rather than by replacement, and the module cache is why.
|
|
@@ -154,6 +173,8 @@ export function mergeSnapshots(
|
|
|
154
173
|
}
|
|
155
174
|
const tasks = new Map(older.tasks.map((handle) => [handle.name, handle] as const));
|
|
156
175
|
for (const handle of newer.tasks) tasks.set(handle.name, handle);
|
|
176
|
+
const jobs = new Map(older.jobs.map((handle) => [handle.name, handle] as const));
|
|
177
|
+
for (const handle of newer.jobs) jobs.set(handle.name, handle);
|
|
157
178
|
return {
|
|
158
179
|
locales: newer.locales,
|
|
159
180
|
catalogs: [...catalogs],
|
|
@@ -162,6 +183,7 @@ export function mergeSnapshots(
|
|
|
162
183
|
roles: { ...older.roles, ...newer.roles },
|
|
163
184
|
roleSites: { ...older.roleSites, ...newer.roleSites },
|
|
164
185
|
tasks: [...tasks.values()],
|
|
186
|
+
jobs: [...jobs.values()],
|
|
165
187
|
catalogDeclarations: Math.max(older.catalogDeclarations, newer.catalogDeclarations),
|
|
166
188
|
// Last declaration wins, as `defineMeasurementActor` itself has it; "none" never erases one.
|
|
167
189
|
measurementActor: newer.measurementActor ?? older.measurementActor,
|