Skip to content

Commit f12062a

Browse files
committed
test(structure): per-package eager-closure budgets (#1960)
ADR-0019 requires platform-package façades to stay implementation-lazy and is explicit that a startup threshold alone is not a substitute for preserving the loading shape. #1950 built the AST-level walker (eager-import-closure.fixtures.ts) and proved the planted-red procedure on one file (session-teardown.ts's android-helper denylist); this generalizes it into a data-driven budget table so any workspace-package façade -- or a designated hub module -- can get an eager-closure ceiling without a bespoke test. Seeds a budget for every packages/*/src/facades/*.ts file (discovered the same way package-boundaries.test.ts discovers façades, not hand-listed) from its measured current closure size, plus a platform-implementation denylist for façades whose contract is implementation-neutral vocabulary. Also demonstrates the mechanism on two designated hub modules (cli.ts, session-teardown.ts) alongside their existing, more specific ad hoc pins. Closes #1960
1 parent 04e4c23 commit f12062a

2 files changed

Lines changed: 234 additions & 0 deletions

File tree

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
import { expect, test } from 'vitest';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { eagerClosureOf } from './eager-import-closure.fixtures.ts';
5+
import {
6+
EAGER_CLOSURE_BUDGETS,
7+
PLATFORM_IMPLEMENTATION_PATTERNS,
8+
type EagerClosureBudget,
9+
} from './eager-closure-budgets.ts';
10+
11+
/**
12+
* The ADR-0019 loading-shape probe, generalized (#1739, #1960).
13+
*
14+
* ADR-0019 requires platform-package façades to stay implementation-lazy and is explicit that a
15+
* startup threshold alone is not a substitute for preserving the loading shape: "the tracking
16+
* issue owns the exact probe and planted-red procedure." #1950 built the walker this file reuses
17+
* (`eager-import-closure.fixtures.ts`, AST-level: static value edges plus top-level dynamic
18+
* imports, type-only erased) and proved the planted-red procedure on one file. This is that
19+
* probe, generalized to every workspace-package façade plus designated hub modules, driven by the
20+
* data table in `eager-closure-budgets.ts` instead of one-off pins.
21+
*
22+
* - Catches: a façade or vocabulary entry silently going eager -- the regression class #1950
23+
* fixed once (the android teardown-helper pin below) and #1956/#1959 fix at two more sites.
24+
* Before this file, nothing prevented a fourth instance: layering R3/R13 govern import
25+
* *direction* (may this file import that one at all), not *evaluation weight* (how much of the
26+
* repo importing it drags along).
27+
* - Evidence: the planted-red procedure that proved the #1950 pin re-verified here (see the git
28+
* history on this file's introduction for the observed failing run); simulation on the whole
29+
* unit-core suite showed single-file regressions of this class cost 5-12% of the suite's total
30+
* import work each.
31+
* - Cost: one unit-lane test file plus one data module; the walker parses each reachable file once
32+
* per entry (whole-table run is a fraction of a second), no subprocess, no device.
33+
* - Kill criterion: if two consecutive quarters show no budget ever tightening or firing, or
34+
* ADR-0019 composition lands a stronger structural proof of the loading shape, delete this gate
35+
* in favor of that proof.
36+
*/
37+
38+
const repoRoot = path.resolve(import.meta.dirname, '../..');
39+
40+
/**
41+
* Every `.ts` file under a `src/facades/` directory, discovered the same way
42+
* `package-boundaries.test.ts` discovers façades (directory membership, not a hand-maintained
43+
* list) -- so a new façade directory shows up here, and must gain a table entry, the moment it
44+
* exists.
45+
*/
46+
function discoverFacadeFiles(): string[] {
47+
const packagesDir = path.join(repoRoot, 'packages');
48+
const files: string[] = [];
49+
for (const pkgEntry of fs.readdirSync(packagesDir).sort()) {
50+
const facadesDir = path.join(packagesDir, pkgEntry, 'src/facades');
51+
if (!fs.existsSync(facadesDir)) continue;
52+
for (const file of fs.readdirSync(facadesDir).sort()) {
53+
if (file.endsWith('.ts')) files.push(path.join(facadesDir, file));
54+
}
55+
}
56+
return files;
57+
}
58+
59+
function relList(files: readonly string[]): string[] {
60+
return [...files].map((file) => path.relative(repoRoot, file)).sort();
61+
}
62+
63+
test('every discovered façade has exactly one budget entry, and no budget entry is stale', () => {
64+
// Bidirectional, mirroring the repo's other exhaustiveness gates (R7/R10 field checklists,
65+
// the facade-exports exhaustive re-export check): a façade with no budget would let this whole
66+
// mechanism go silently vacuous for it, and a budget entry for a file that is no longer a
67+
// façade would let the table drift from what it claims to police.
68+
const discovered = new Set(discoverFacadeFiles());
69+
const facadeEntries = EAGER_CLOSURE_BUDGETS.filter((entry) => entry.kind === 'facade');
70+
const budgeted = new Set(facadeEntries.map((entry) => path.resolve(repoRoot, entry.entryFile)));
71+
72+
const missingBudget = relList([...discovered].filter((file) => !budgeted.has(file)));
73+
const staleBudget = relList([...budgeted].filter((file) => !discovered.has(file)));
74+
75+
expect(
76+
missingBudget,
77+
'These façades exist under a `src/facades/` directory but have no entry in ' +
78+
'eager-closure-budgets.ts. Add one (measure the current closure size with eagerClosureOf ' +
79+
'and round up a few files for headroom), or the loading-shape probe silently does not ' +
80+
'cover them.',
81+
).toEqual([]);
82+
expect(
83+
staleBudget,
84+
"These eager-closure-budgets.ts entries are marked kind: 'facade' but no longer name a file " +
85+
'under a `src/facades/` directory. Remove the stale entry or fix its path.',
86+
).toEqual([]);
87+
});
88+
89+
test('every budgeted entry file exists on disk', () => {
90+
const missing = EAGER_CLOSURE_BUDGETS.filter(
91+
(entry) => !fs.existsSync(path.resolve(repoRoot, entry.entryFile)),
92+
).map((entry) => entry.entryFile);
93+
expect(
94+
missing,
95+
'These eager-closure-budgets.ts entries name a file that does not exist.',
96+
).toEqual([]);
97+
});
98+
99+
test.for(EAGER_CLOSURE_BUDGETS)(
100+
'$id stays within its eager-closure budget of $budget modules',
101+
(entry: EagerClosureBudget) => {
102+
const closure = eagerClosureOf(path.resolve(repoRoot, entry.entryFile));
103+
const evaluated = relList(closure);
104+
expect(
105+
closure.length,
106+
`${entry.id} evaluates ${closure.length} modules on import, over its budget of ` +
107+
`${entry.budget}. Either the budget needs a reviewed increase (name what legitimately ` +
108+
'grew and why), or something that used to load on demand now loads eagerly -- check the ' +
109+
'newest entries below against what this entry point should need.\nEvaluated ' +
110+
`(${evaluated.length}):\n${evaluated.join('\n')}`,
111+
).toBeLessThanOrEqual(entry.budget);
112+
},
113+
);
114+
115+
test.for(EAGER_CLOSURE_BUDGETS.filter((entry) => entry.denyPlatformImplementations))(
116+
'$id never evaluates a concrete platform implementation before discovery/binding',
117+
(entry: EagerClosureBudget) => {
118+
const closure = eagerClosureOf(path.resolve(repoRoot, entry.entryFile));
119+
const offenders = relList(
120+
closure.filter((file) =>
121+
PLATFORM_IMPLEMENTATION_PATTERNS.some((pattern) => pattern.test(file)),
122+
),
123+
);
124+
expect(
125+
offenders,
126+
`${entry.id} is implementation-neutral vocabulary (ADR-0019) and must not evaluate a ` +
127+
'concrete platform implementation until discovery/binding selects one. Load the ' +
128+
`offending module(s) on demand instead of with a static value import:\n${offenders.join('\n')}`,
129+
).toEqual([]);
130+
},
131+
);
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Per-entry eager-closure budgets -- the ADR-0019 loading-shape probe (#1739, #1960).
2+
//
3+
// ADR-0019's "Implementation-laziness" section requires platform-package façades to stay
4+
// implementation-lazy and is explicit that a startup-time threshold alone is not a substitute for
5+
// preserving the loading shape (`docs/adr/0019-request-bound-platform-runtime.md`): "the tracking
6+
// issue owns the exact probe and planted-red procedure." #1950 built the AST-level walker
7+
// (`eager-import-closure.fixtures.ts`) and proved the planted-red procedure on one file
8+
// (`session-teardown.ts`'s android-helper denylist, kept below as its own ad hoc test). This
9+
// table generalizes that proof: every workspace-package façade gets a numeric ceiling on how many
10+
// repo modules importing it may evaluate, plus -- for façades whose contract is
11+
// implementation-neutral vocabulary -- a standing assertion that the closure never reaches a
12+
// concrete platform implementation before discovery/binding selects one.
13+
//
14+
// Entry files are repo-root-relative.
15+
16+
export type EagerClosureBudget = {
17+
/** Stable label for test names and failure messages -- the entry's repo-relative path. */
18+
id: string;
19+
/** Repo-root-relative path to the module a consumer imports. */
20+
entryFile: string;
21+
/**
22+
* Upper bound on `eagerClosureOf(entryFile).length`. Seeded from the file's CURRENT measured
23+
* closure size (recorded in the trailing comment on each entry below) plus a few files of
24+
* headroom for ordinary drift. A regression of the class this gate exists to catch -- a static
25+
* value import of a heavy module that used to be lazy -- costs tens to low-hundreds of extra
26+
* evaluated modules (#1960 simulation: single-file regressions of this class cost 5-12% of
27+
* suite import work each), far past any of this table's headroom.
28+
*/
29+
budget: number;
30+
/**
31+
* 'facade' entries are discovered mechanically -- every `.ts` file under a `src/facades/`
32+
* directory -- and the exhaustiveness test in `eager-closure-budgets.test.ts` requires each one
33+
* to appear here exactly once. 'hub' entries are hand-designated, high-fan-in files that
34+
* value-import a façade for only a slice of it (ADR-0019's other named case). There is no
35+
* mechanical way to enumerate "every hub" the way a façade directory enumerates every façade,
36+
* so membership is a reviewed judgment call -- the same judgment call the two existing ad hoc
37+
* pins this table's mechanism is built to generalize already made by hand.
38+
*/
39+
kind: 'facade' | 'hub';
40+
/**
41+
* When true, the closure must never evaluate a concrete platform implementation (matched by
42+
* `PLATFORM_IMPLEMENTATION_PATTERNS`) -- the ADR-0019 rule that a façade whose contract is
43+
* implementation-neutral vocabulary may not evaluate implementation before discovery/binding
44+
* selects one. Hub entries default this false: a hub is a *consumer* of façades, not vocabulary
45+
* itself, and may legitimately reach one platform family already (e.g. session teardown's Apple
46+
* perf cleanup steps) through its own lazy seam. Verified, not merely assumed -- see the
47+
* measurement note on the `src/daemon/session-teardown.ts` entry below.
48+
*/
49+
denyPlatformImplementations: boolean;
50+
};
51+
52+
/**
53+
* A concrete platform implementation: the legacy daemon-owned `src/platforms/<family>/` tree, or
54+
* a `@agent-device/platform-<family>` workspace package. ADR-0019 names both as "concrete device
55+
* mechanics" that platform-neutral code may depend on only through contracts, never directly.
56+
*/
57+
export const PLATFORM_IMPLEMENTATION_PATTERNS: RegExp[] = [
58+
/[/\\]platforms[/\\](apple|android|harmonyos|vega|linux|web)[/\\]/,
59+
/[/\\]packages[/\\]platform-(apple|android|harmonyos|vega|linux|web)[/\\]/,
60+
];
61+
62+
function facade(entryFile: string, budget: number): EagerClosureBudget {
63+
return { id: entryFile, entryFile, budget, kind: 'facade', denyPlatformImplementations: true };
64+
}
65+
66+
function hub(entryFile: string, budget: number): EagerClosureBudget {
67+
return { id: entryFile, entryFile, budget, kind: 'hub', denyPlatformImplementations: false };
68+
}
69+
70+
export const EAGER_CLOSURE_BUDGETS: EagerClosureBudget[] = [
71+
// packages/contracts/src/facades/*.ts -- measured 2026-08-22 on origin/main (base e5bfde3d1);
72+
// budget = actual + a few files of headroom. All 14 are implementation-neutral vocabulary per
73+
// ADR-0019 ("Contracts may depend on kernel vocabulary but never on concrete platform
74+
// packages or daemon implementation types"), so all deny platform implementations.
75+
facade('packages/contracts/src/facades/client.ts', 4), // actual 2
76+
facade('packages/contracts/src/facades/command.ts', 12), // actual 9
77+
facade('packages/contracts/src/facades/device.ts', 11), // actual 8
78+
facade('packages/contracts/src/facades/interaction.ts', 30), // actual 25
79+
facade('packages/contracts/src/facades/capture.ts', 12), // actual 9
80+
facade('packages/contracts/src/facades/platform.ts', 48), // actual 42
81+
facade('packages/contracts/src/facades/session.ts', 8), // actual 5
82+
facade('packages/contracts/src/facades/recording.ts', 6), // actual 3
83+
facade('packages/contracts/src/facades/observability.ts', 10), // actual 7
84+
facade('packages/contracts/src/facades/remote.ts', 4), // actual 2
85+
facade('packages/contracts/src/facades/replay.ts', 6), // actual 3
86+
facade('packages/contracts/src/facades/snapshot.ts', 11), // actual 8
87+
facade('packages/contracts/src/facades/divergence.ts', 6), // actual 3
88+
facade('packages/contracts/src/facades/progress.ts', 3), // actual 1
89+
90+
// Designated hub modules (ADR-0019's other named case): high-fan-in entry points that already
91+
// hold their own ad hoc eager-closure pin (`cli-startup-import-closure.test.ts`,
92+
// `session-teardown-import-closure.test.ts`). Those files keep their existing, MORE specific
93+
// assertions -- each names an individual known-expensive module, a stronger property for that
94+
// one module than a numeric ceiling gives. This table adds a second, general-purpose layer: a
95+
// size ceiling that catches ANY unexpected growth at the entry, not only the one pattern each ad
96+
// hoc test already watches for.
97+
hub('src/cli.ts', 420), // actual 386
98+
// session-teardown.ts already eagerly evaluates 24 Apple perf/runner modules under
99+
// src/platforms/apple/ (that migration hasn't happened yet -- only the Android perf/
100+
// snapshot-helper pair is lazy today, per the ad hoc test above), so denyPlatformImplementations
101+
// stays false here: turning it on would fail on today's real, reviewed state, not a regression.
102+
hub('src/daemon/session-teardown.ts', 140), // actual 121
103+
];

0 commit comments

Comments
 (0)