Public: anyone can read this; the crew can change it.

Test what the change reaches, by measured coverage, not by guessing: a per-test impact map from the full run drives the fast tier #1281

Closed opened this in answer to
Closed without merging

torque/forge:torque/1279-test-what-the-change-reaches-by-measured → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +1402 −40
README.md +3 −1

Diff not shown — a line 2,030 characters wide (limit 2,000). +3 −1

View file
scripts/impact-baseline.test.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * The impact map's baseline (#1279): what loading the forge runs before
3 * any test asks it anything. `scripts/test-shards.ts --record` runs this
4 * file under coverage first; a test is then said to execute a file only
5 * where it ran a line this did not. Without it, every test that boots the
6 * server "executes" every page the server imports, and a change to one
7 * page reaches the whole suite.
8 *
9 * Load the hubs and build the route tables — the handler factories run
10 * there — and nothing else: no app, no database, no request, so the
11 * migrations, the middleware and every handler stay what the tests that
12 * run them executed. Not part of the gate (`scripts/gate.ts` names
13 * `test/` files only).
14 */
15
16 import { expect, test } from "bun:test";
17
18 test("loading the forge builds its routes and runs nothing else", async () => {
19 await import("../src/app.ts");
20 const { buildApiRouter, buildRouter } = await import("../src/http/server.ts");
21 expect(buildRouter()).toBeDefined();
22 expect(buildApiRouter()).toBeDefined();
23 });
scripts/impact.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * The test impact map (#1279): for each test file, the repository files it
3 * executed when it ran alone under `bun test --coverage` — lines beyond
4 * those loading the forge runs. Measured, not guessed — so a pull's diff
5 * intersected with it is the set of tests the change can reach.
6 *
7 * `scripts/test-shards.ts --record` runs every file on its own with an LCOV
8 * report and writes `scripts/test-impact.json` from those reports, next to
9 * `scripts/test-times.json`; `--tier fast` reads it. This module only reads
10 * and writes the formats.
11 */
12
13 import { TEST_FILE } from "./shards.ts";
14
15 /** A repository-relative path a test may execute: no climbing, no flags. */
16 const REPO_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[A-Za-z0-9_][A-Za-z0-9_./@+-]{0,511}$/;
17
18 /** Repository file → the lines a run executed in it, from an LCOV report. */
19 export type Hits = Map<string, ReadonlySet<number>>;
20
21 /**
22 * The lines an LCOV report says ran (`DA:<line>,<count>` with a count
23 * above zero), by repository file (`SF:`). Bun names a file when the run
24 * loaded it, so a file loaded and never called is here with only its
25 * load-time lines. Other test files and anything outside the repository
26 * (`node_modules`, absolute paths), which no diff of ours changes, are
27 * left out.
28 */
29 export function lcovHits(lcov: string): Hits {
30 const hits = new Map<string, Set<number>>();
31 let current: Set<number> | undefined;
32 for (const line of lcov.split("\n")) {
33 if (line.startsWith("SF:")) {
34 let path = line.slice(3).trim();
35 if (path.startsWith("./")) path = path.slice(2);
36 current =
37 REPO_PATH.test(path) &&
38 !path.startsWith("node_modules/") &&
39 !TEST_FILE.test(path)
40 ? (hits.get(path) ?? new Set())
41 : undefined;
42 if (current !== undefined) hits.set(path, current);
43 } else if (line.startsWith("end_of_record")) current = undefined;
44 else if (current !== undefined && line.startsWith("DA:")) {
45 const [at, count] = line.slice(3).split(",");
46 const number = Number(at);
47 if (Number.isInteger(number) && number > 0 && Number(count) > 0)
48 current.add(number);
49 }
50 }
51 return hits;
52 }
53
54 /**
55 * The files a test executed, sorted: those where it ran a line the
56 * baseline did not. The baseline is what merely loading the forge runs —
57 * every module's top level and the route tables the server builds
58 * (`scripts/impact-baseline.test.ts`) — so a test that boots the server
59 * executes the pages it renders, not every page the server imports
60 * (#1279: 146 of 160 tests were picked for importing src/http/server.ts).
61 * A file the baseline never loaded counts on any line run.
62 */
63 export function executedFiles(hits: Hits, baseline: Hits = new Map()): string[] {
64 const out: string[] = [];
65 for (const [file, lines] of hits) {
66 const boot = baseline.get(file);
67 for (const line of lines)
68 if (boot === undefined || !boot.has(line)) {
69 out.push(file);
70 break;
71 }
72 }
73 return out.sort();
74 }
75
76 /**
77 * The pages a baseline failed to load, sorted. Every page is loaded by
78 * the hub, so a page the baseline missed would count as executed by every
79 * test that boots the server; `--record` refuses such a baseline.
80 */
81 export function baselineGaps(baseline: Hits, pages: readonly string[]): string[] {
82 return pages.filter((page) => !baseline.has(page)).sort();
83 }
84
85 export type Impact = Map<string, readonly string[]>;
86
87 /**
88 * Reads `scripts/test-impact.json`: one object, test file to the sorted
89 * list of repository files it executed, e.g.
90 * `{ "test/crew.test.ts": ["src/crew/run.ts", …] }`. Anything else — not
91 * JSON, a key that is not a test file, a value that is not a list of
92 * repository paths — refuses the whole map, so a half-trusted map never
93 * decides what a pull skips.
94 */
95 export function parseImpact(
96 text: string,
97 ): { ok: true; value: Impact } | { ok: false; error: string } {
98 let data: unknown;
99 try {
100 data = JSON.parse(text);
101 } catch {
102 return { ok: false, error: "not JSON" };
103 }
104 if (typeof data !== "object" || data === null || Array.isArray(data))
105 return { ok: false, error: "not an object of test file to files" };
106 const impact: Impact = new Map();
107 for (const [test, files] of Object.entries(data)) {
108 if (!TEST_FILE.test(test) || !REPO_PATH.test(test))
109 return { ok: false, error: `${JSON.stringify(test)} is not a test file` };
110 if (
111 !Array.isArray(files) ||
112 !files.every((file) => typeof file === "string" && REPO_PATH.test(file))
113 )
114 return {
115 ok: false,
116 error: `${test}: not a list of repository paths`,
117 };
118 impact.set(test, files as string[]);
119 }
120 return { ok: true, value: impact };
121 }
122
123 /**
124 * The map as it is checked in: tests sorted, each test's files sorted, one
125 * file per line, so a refresh reads as a small diff.
126 */
127 export function formatImpact(impact: ReadonlyMap<string, readonly string[]>): string {
128 const tests = [...impact.keys()].sort();
129 if (tests.length === 0) return "{}\n";
130 const blocks = tests.map((test) => {
131 const files = [...impact.get(test)!].sort();
132 return files.length === 0
133 ? ` ${JSON.stringify(test)}: []`
134 : ` ${JSON.stringify(test)}: [\n${files.map((file) => ` ${JSON.stringify(file)}`).join(",\n")}\n ]`;
135 });
136 return `{\n${blocks.join(",\n")}\n}\n`;
137 }
scripts/test-impact.json added +666
@@ -0,0 +1,666 @@
1 {
2 "test/branch_tell.test.ts": [
3 "src/web/studio/branch_tell.ts"
4 ],
5 "test/check-list.test.ts": [
6 "scripts/gate.ts"
7 ],
8 "test/check-tiers.test.ts": [
9 "scripts/impact.ts",
10 "scripts/shards.ts",
11 "src/actions/access.ts",
12 "src/actions/pulls.ts",
13 "src/actions/repos.ts",
14 "src/actions/runs.ts",
15 "src/actions/verify.ts",
16 "src/app.ts",
17 "src/apps/checkout.ts",
18 "src/apps/contain.ts",
19 "src/apps/manifest.ts",
20 "src/apps/process.ts",
21 "src/checks/bun-test.ts",
22 "src/checks/failures.ts",
23 "src/checks/history.ts",
24 "src/checks/landing.ts",
25 "src/checks/learned.ts",
26 "src/checks/service.ts",
27 "src/checks/summary.ts",
28 "src/checks/tiers.ts",
29 "src/core/accounts.ts",
30 "src/core/capacity.ts",
31 "src/core/commit_identity.ts",
32 "src/core/events.ts",
33 "src/core/following.ts",
34 "src/core/issues.ts",
35 "src/core/origins.ts",
36 "src/core/pull_trust.ts",
37 "src/core/pulls.ts",
38 "src/core/repos.ts",
39 "src/core/reserved.ts",
40 "src/core/runs.ts",
41 "src/core/schema.ts",
42 "src/core/sealed.ts",
43 "src/core/users.ts",
44 "src/core/verify.ts",
45 "src/core/webhooks.ts",
46 "src/git/env.ts",
47 "src/git/guard.ts",
48 "src/git/hooks.ts",
49 "src/git/merge.ts",
50 "src/git/read.ts",
51 "src/git/repos.ts",
52 "src/git/write.ts",
53 "src/kernel/db.ts",
54 "src/kernel/id.ts",
55 "src/kernel/log.ts",
56 "src/kernel/migrate.ts",
57 "src/kernel/result.ts",
58 "src/origins/write-through.ts",
59 "src/runs/lease.ts",
60 "src/runs/log.ts",
61 "src/runs/paths.ts"
62 ],
63 "test/code.test.ts": [
64 "src/web/code.ts",
65 "src/web/highlight-html.ts",
66 "src/web/highlight.ts",
67 "src/web/html.ts"
68 ],
69 "test/contract.test.ts": [
70 "src/apps/scaffold.ts",
71 "src/contract/can.ts",
72 "src/crew/brief.ts"
73 ],
74 "test/crew-brief-gate.test.ts": [
75 "src/crew/brief.ts"
76 ],
77 "test/crew-limits.test.ts": [
78 "src/crew/limits.ts"
79 ],
80 "test/crew-sandbox.test.ts": [
81 "src/actions/access.ts",
82 "src/actions/repos.ts",
83 "src/actions/verify.ts",
84 "src/app.ts",
85 "src/core/capacity.ts",
86 "src/core/events.ts",
87 "src/core/following.ts",
88 "src/core/repos.ts",
89 "src/core/reserved.ts",
90 "src/core/runs.ts",
91 "src/core/schema.ts",
92 "src/core/sealed.ts",
93 "src/core/users.ts",
94 "src/core/verify.ts",
95 "src/core/webhooks.ts",
96 "src/crew/claude.ts",
97 "src/crew/sandbox.ts",
98 "src/git/env.ts",
99 "src/git/guard.ts",
100 "src/git/hooks.ts",
101 "src/git/read.ts",
102 "src/git/repos.ts",
103 "src/kernel/db.ts",
104 "src/kernel/id.ts",
105 "src/kernel/migrate.ts",
106 "src/kernel/result.ts",
107 "src/web/html.ts",
108 "src/web/studio/sandbox.ts"
109 ],
110 "test/data-home.test.ts": [
111 "src/kernel/data_home.ts"
112 ],
113 "test/decide.test.ts": [
114 "src/actions/access.ts",
115 "src/actions/crew.ts",
116 "src/actions/issues.ts",
117 "src/actions/repos.ts",
118 "src/actions/verify.ts",
119 "src/app.ts",
120 "src/core/agents.ts",
121 "src/core/capacity.ts",
122 "src/core/events.ts",
123 "src/core/following.ts",
124 "src/core/issues.ts",
125 "src/core/origins.ts",
126 "src/core/repos.ts",
127 "src/core/reserved.ts",
128 "src/core/schema.ts",
129 "src/core/sealed.ts",
130 "src/core/users.ts",
131 "src/core/verify.ts",
132 "src/core/webhooks.ts",
133 "src/crew/decide.ts",
134 "src/crew/direct.ts",
135 "src/crew/route.ts",
136 "src/git/env.ts",
137 "src/git/guard.ts",
138 "src/git/hooks.ts",
139 "src/git/read.ts",
140 "src/git/repos.ts",
141 "src/kernel/db.ts",
142 "src/kernel/id.ts",
143 "src/kernel/log.ts",
144 "src/kernel/migrate.ts",
145 "src/kernel/result.ts",
146 "src/origins/write-through.ts"
147 ],
148 "test/diff.test.ts": [
149 "src/core/reviews.ts",
150 "src/git/diff.ts",
151 "src/git/env.ts",
152 "src/git/guard.ts",
153 "src/git/repos.ts",
154 "src/kernel/result.ts",
155 "src/web/code.ts",
156 "src/web/diff-view.ts",
157 "src/web/html.ts",
158 "src/web/icons.ts",
159 "src/web/worddiff.ts",
160 "test/helpers/git-client.ts"
161 ],
162 "test/enterable-apps.test.ts": [
163 "src/actions/access.ts",
164 "src/actions/crew.ts",
165 "src/actions/verify.ts",
166 "src/app.ts",
167 "src/core/agents.ts",
168 "src/core/app_members.ts",
169 "src/core/events.ts",
170 "src/core/following.ts",
171 "src/core/orgs.ts",
172 "src/core/repos.ts",
173 "src/core/reserved.ts",
174 "src/core/schema.ts",
175 "src/core/sealed.ts",
176 "src/core/users.ts",
177 "src/core/verify.ts",
178 "src/core/webhooks.ts",
179 "src/git/guard.ts",
180 "src/kernel/db.ts",
181 "src/kernel/id.ts",
182 "src/kernel/log.ts",
183 "src/kernel/migrate.ts",
184 "src/kernel/result.ts",
185 "test/helpers/globals.ts"
186 ],
187 "test/forge-cloudflare-celld.test.ts": [
188 "scripts/celld.ts"
189 ],
190 "test/forge-cloudflare.test.ts": [
191 "infra/forge-cloudflare/worker.js"
192 ],
193 "test/git-local.test.ts": [
194 "src/git/diff.ts",
195 "src/git/guard.ts",
196 "src/git/local.ts",
197 "src/kernel/result.ts",
198 "test/helpers/git-client.ts"
199 ],
200 "test/git-ssh.test.ts": [
201 "src/apps/tty.ts",
202 "src/git/smart-ssh.ts",
203 "src/kernel/log.ts",
204 "src/ssh/auth.ts",
205 "src/ssh/channels.ts",
206 "src/ssh/server.ts",
207 "src/ssh/transport.ts",
208 "src/tui/app/app.ts",
209 "src/tui/app/keys.ts",
210 "src/tui/app/palette.ts",
211 "src/tui/forge.ts",
212 "src/tui/screens/about.ts",
213 "src/tui/screens/apptty.ts",
214 "src/tui/screens/assign.ts",
215 "src/tui/screens/commit.ts",
216 "src/tui/screens/commits.ts",
217 "src/tui/screens/common.ts",
218 "src/tui/screens/contribute.ts",
219 "src/tui/screens/dashboard.ts",
220 "src/tui/screens/external.ts",
221 "src/tui/screens/finder.ts",
222 "src/tui/screens/issue.ts",
223 "src/tui/screens/issues.ts",
224 "src/tui/screens/mirror.ts",
225 "src/tui/screens/newpull.ts",
226 "src/tui/screens/newrepo.ts",
227 "src/tui/screens/pull.ts",
228 "src/tui/screens/refs.ts",
229 "src/tui/screens/repo.ts",
230 "src/tui/screens/review.ts",
231 "src/tui/screens/runlist.ts",
232 "src/tui/screens/signin.ts",
233 "src/tui/screens/thread.ts",
234 "src/tui/screens/verdicts.ts",
235 "src/tui/screens/where.ts",
236 "src/tui/screens/workspace.ts",
237 "src/tui/session.ts",
238 "src/tui/ssh.ts",
239 "src/tui/term/graphics.ts",
240 "src/tui/term/input.ts",
241 "src/tui/term/render.ts",
242 "src/tui/term/screen.ts",
243 "src/tui/term/terminal.ts",
244 "src/tui/term/width.ts",
245 "src/tui/ui/diff.ts",
246 "src/tui/ui/editor.ts",
247 "src/tui/ui/fuzzy.ts",
248 "src/tui/ui/icons.ts",
249 "src/tui/ui/image.ts",
250 "src/tui/ui/layout.ts",
251 "src/tui/ui/markdown.ts",
252 "src/tui/ui/textarea.ts",
253 "src/tui/ui/theme.ts",
254 "src/tui/ui/widgets.ts",
255 "test/helpers/git-client.ts",
256 "test/helpers/globals.ts",
257 "test/helpers/tools.ts"
258 ],
259 "test/git-trust.test.ts": [
260 "src/git/env.ts"
261 ],
262 "test/git.test.ts": [
263 "src/git/env.ts",
264 "src/git/guard.ts",
265 "src/git/read.ts",
266 "src/git/repos.ts",
267 "src/git/smart-http.ts",
268 "src/http/caller.ts",
269 "src/http/limits.ts",
270 "src/kernel/error.ts",
271 "src/kernel/result.ts",
272 "test/helpers/git-client.ts"
273 ],
274 "test/helpers.test.ts": [
275 "src/kernel/log.ts",
276 "test/helpers/git-client.ts",
277 "test/helpers/globals.ts",
278 "test/helpers/tools.ts"
279 ],
280 "test/highlight.test.ts": [
281 "src/web/highlight-html.ts",
282 "src/web/highlight.ts",
283 "src/web/html.ts"
284 ],
285 "test/hollow.test.ts": [
286 "scripts/gate.ts",
287 "scripts/hollow-allow.ts",
288 "scripts/hollow.ts"
289 ],
290 "test/image-gif.test.ts": [
291 "src/design/image/gif.ts",
292 "src/kernel/result.ts"
293 ],
294 "test/image-graphics.test.ts": [
295 "src/design/image/gif.ts",
296 "src/design/image/image.ts",
297 "src/design/image/jpeg.ts",
298 "src/design/image/png.ts",
299 "src/kernel/result.ts",
300 "src/tui/term/graphics.ts",
301 "src/tui/term/screen.ts",
302 "src/tui/term/terminal.ts",
303 "src/tui/term/width.ts",
304 "src/tui/ui/image.ts",
305 "src/tui/ui/theme.ts"
306 ],
307 "test/image-jpeg.test.ts": [
308 "src/design/image/jpeg.ts",
309 "src/kernel/result.ts"
310 ],
311 "test/image-png.test.ts": [
312 "src/design/image/png.ts",
313 "src/kernel/result.ts"
314 ],
315 "test/kernel.test.ts": [
316 "src/kernel/db.ts",
317 "src/kernel/error.ts",
318 "src/kernel/id.ts",
319 "src/kernel/migrate.ts",
320 "src/kernel/result.ts"
321 ],
322 "test/keys.test.ts": [
323 "test/helpers/tools.ts"
324 ],
325 "test/origins-operator.test.ts": [
326 "src/app.ts",
327 "src/core/events.ts",
328 "src/core/following.ts",
329 "src/core/schema.ts",
330 "src/git/read.ts",
331 "src/kernel/db.ts",
332 "src/kernel/id.ts",
333 "src/kernel/migrate.ts",
334 "src/kernel/result.ts",
335 "src/origins/oauth.ts"
336 ],
337 "test/pacing.test.ts": [
338 "src/crew/limits.ts",
339 "src/crew/pacing.ts"
340 ],
341 "test/palette.test.ts": [
342 "src/web/palette.ts"
343 ],
344 "test/qr.test.ts": [
345 "src/design/qr.ts",
346 "src/kernel/result.ts"
347 ],
348 "test/refresh-meta.test.ts": [
349 "src/web/html.ts",
350 "src/web/layout.ts"
351 ],
352 "test/restore-card.test.ts": [
353 "src/actions/access.ts",
354 "src/actions/repos.ts",
355 "src/actions/verify.ts",
356 "src/app.ts",
357 "src/core/apps.ts",
358 "src/core/capacity.ts",
359 "src/core/commit_identity.ts",
360 "src/core/events.ts",
361 "src/core/following.ts",
362 "src/core/issues.ts",
363 "src/core/pulls.ts",
364 "src/core/repos.ts",
365 "src/core/reserved.ts",
366 "src/core/schema.ts",
367 "src/core/sealed.ts",
368 "src/core/users.ts",
369 "src/core/verify.ts",
370 "src/core/webhooks.ts",
371 "src/git/env.ts",
372 "src/git/guard.ts",
373 "src/git/hooks.ts",
374 "src/git/merge.ts",
375 "src/git/read.ts",
376 "src/git/repos.ts",
377 "src/git/write.ts",
378 "src/kernel/db.ts",
379 "src/kernel/id.ts",
380 "src/kernel/log.ts",
381 "src/kernel/migrate.ts",
382 "src/kernel/result.ts",
383 "src/snapshot/snapshot.ts",
384 "src/snapshot/store.ts"
385 ],
386 "test/review-gate.test.ts": [
387 "src/actions/access.ts",
388 "src/actions/crew.ts",
389 "src/actions/issues.ts",
390 "src/actions/pillars.ts",
391 "src/actions/pulls.ts",
392 "src/actions/repos.ts",
393 "src/actions/runs.ts",
394 "src/actions/verify.ts",
395 "src/app.ts",
396 "src/apps/checkout.ts",
397 "src/checks/landing.ts",
398 "src/checks/service.ts",
399 "src/contract/policy.ts",
400 "src/core/accounts.ts",
401 "src/core/agents.ts",
402 "src/core/capacity.ts",
403 "src/core/commit_identity.ts",
404 "src/core/decisions.ts",
405 "src/core/events.ts",
406 "src/core/following.ts",
407 "src/core/holds.ts",
408 "src/core/issues.ts",
409 "src/core/origins.ts",
410 "src/core/pillars.ts",
411 "src/core/pulls.ts",
412 "src/core/repos.ts",
413 "src/core/reserved.ts",
414 "src/core/reviews.ts",
415 "src/core/runs.ts",
416 "src/core/schema.ts",
417 "src/core/sealed.ts",
418 "src/core/users.ts",
419 "src/core/verify.ts",
420 "src/core/webhooks.ts",
421 "src/crew/autonomy.ts",
422 "src/crew/breaker.ts",
423 "src/crew/direct.ts",
424 "src/crew/dispatch.ts",
425 "src/crew/guard.ts",
426 "src/crew/interrupted.ts",
427 "src/crew/review.ts",
428 "src/git/diff.ts",
429 "src/git/env.ts",
430 "src/git/guard.ts",
431 "src/git/hooks.ts",
432 "src/git/merge.ts",
433 "src/git/read.ts",
434 "src/git/repos.ts",
435 "src/git/write.ts",
436 "src/kernel/db.ts",
437 "src/kernel/id.ts",
438 "src/kernel/log.ts",
439 "src/kernel/migrate.ts",
440 "src/kernel/result.ts",
441 "src/origins/write-through.ts"
442 ],
443 "test/review-route.test.ts": [
444 "src/actions/access.ts",
445 "src/actions/crew.ts",
446 "src/actions/pulls.ts",
447 "src/actions/repos.ts",
448 "src/actions/runs.ts",
449 "src/actions/verify.ts",
450 "src/app.ts",
451 "src/core/accounts.ts",
452 "src/core/agents.ts",
453 "src/core/capacity.ts",
454 "src/core/commit_identity.ts",
455 "src/core/events.ts",
456 "src/core/following.ts",
457 "src/core/holds.ts",
458 "src/core/issues.ts",
459 "src/core/origins.ts",
460 "src/core/pulls.ts",
461 "src/core/repos.ts",
462 "src/core/reserved.ts",
463 "src/core/reviews.ts",
464 "src/core/runs.ts",
465 "src/core/schema.ts",
466 "src/core/sealed.ts",
467 "src/core/users.ts",
468 "src/core/verify.ts",
469 "src/core/webhooks.ts",
470 "src/crew/breaker.ts",
471 "src/crew/direct.ts",
472 "src/crew/dispatch.ts",
473 "src/crew/guard.ts",
474 "src/crew/review.ts",
475 "src/crew/runner.ts",
476 "src/git/diff.ts",
477 "src/git/env.ts",
478 "src/git/guard.ts",
479 "src/git/hooks.ts",
480 "src/git/merge.ts",
481 "src/git/read.ts",
482 "src/git/repos.ts",
483 "src/git/write.ts",
484 "src/kernel/db.ts",
485 "src/kernel/id.ts",
486 "src/kernel/log.ts",
487 "src/kernel/migrate.ts",
488 "src/kernel/result.ts",
489 "src/origins/write-through.ts"
490 ],
491 "test/run-secrets.test.ts": [
492 "src/actions/access.ts",
493 "src/actions/repos.ts",
494 "src/actions/verify.ts",
495 "src/app.ts",
496 "src/core/capacity.ts",
497 "src/core/events.ts",
498 "src/core/following.ts",
499 "src/core/repos.ts",
500 "src/core/reserved.ts",
501 "src/core/run_secret.ts",
502 "src/core/schema.ts",
503 "src/core/sealed.ts",
504 "src/core/secret_store.ts",
505 "src/core/users.ts",
506 "src/core/verify.ts",
507 "src/core/webhooks.ts",
508 "src/crew/grant.ts",
509 "src/crew/leak.ts",
510 "src/crew/sandbox.ts",
511 "src/git/env.ts",
512 "src/git/guard.ts",
513 "src/git/hooks.ts",
514 "src/git/read.ts",
515 "src/git/repos.ts",
516 "src/kernel/db.ts",
517 "src/kernel/error.ts",
518 "src/kernel/id.ts",
519 "src/kernel/log.ts",
520 "src/kernel/migrate.ts",
521 "src/kernel/result.ts",
522 "src/kernel/secret.ts",
523 "src/runs/log.ts",
524 "test/helpers/globals.ts"
525 ],
526 "test/scale.test.ts": [
527 "src/actions/access.ts",
528 "src/actions/issues.ts",
529 "src/actions/repos.ts",
530 "src/actions/users.ts",
531 "src/actions/verify.ts",
532 "src/app.ts",
533 "src/core/capacity.ts",
534 "src/core/events.ts",
535 "src/core/following.ts",
536 "src/core/issues.ts",
537 "src/core/origins.ts",
538 "src/core/pins.ts",
539 "src/core/pulls.ts",
540 "src/core/repos.ts",
541 "src/core/reserved.ts",
542 "src/core/schema.ts",
543 "src/core/sealed.ts",
544 "src/core/secret_store.ts",
545 "src/core/tokens.ts",
546 "src/core/users.ts",
547 "src/core/verify.ts",
548 "src/core/visibility.ts",
549 "src/core/webhooks.ts",
550 "src/git/env.ts",
551 "src/git/guard.ts",
552 "src/git/hooks.ts",
553 "src/git/read.ts",
554 "src/git/repos.ts",
555 "src/kernel/db.ts",
556 "src/kernel/id.ts",
557 "src/kernel/log.ts",
558 "src/kernel/migrate.ts",
559 "src/kernel/result.ts",
560 "src/origins/write-through.ts",
561 "test/helpers/globals.ts",
562 "test/helpers/verified.ts"
563 ],
564 "test/schema-additive.test.ts": [
565 "src/kernel/migrate.ts"
566 ],
567 "test/schema-migrations.test.ts": [
568 "src/apps/process.ts",
569 "src/kernel/db.ts",
570 "src/kernel/error.ts",
571 "src/kernel/migrate.ts"
572 ],
573 "test/session-settle.test.ts": [
574 "src/apps/process.ts",
575 "src/crew/claude.ts",
576 "src/crew/sandbox.ts",
577 "src/runs/paths.ts"
578 ],
579 "test/shards.test.ts": [
580 "scripts/gate.ts",
581 "scripts/shards.ts",
582 "src/apps/manifest.ts",
583 "src/kernel/result.ts"
584 ],
585 "test/snapshot-store.test.ts": [
586 "src/snapshot/store.ts"
587 ],
588 "test/spawn-plan.test.ts": [
589 "src/kernel/result.ts",
590 "src/spawn/plan.ts"
591 ],
592 "test/spawn.test.ts": [
593 "src/actions/access.ts",
594 "src/actions/repos.ts",
595 "src/actions/spawn.ts",
596 "src/actions/verify.ts",
597 "src/app.ts",
598 "src/core/agents.ts",
599 "src/core/capacity.ts",
600 "src/core/events.ts",
601 "src/core/following.ts",
602 "src/core/orgs.ts",
603 "src/core/repos.ts",
604 "src/core/reserved.ts",
605 "src/core/schema.ts",
606 "src/core/sealed.ts",
607 "src/core/users.ts",
608 "src/core/verify.ts",
609 "src/core/webhooks.ts",
610 "src/git/env.ts",
611 "src/git/guard.ts",
612 "src/git/hooks.ts",
613 "src/git/merge.ts",
614 "src/git/read.ts",
615 "src/git/repos.ts",
616 "src/git/write.ts",
617 "src/http/context.ts",
618 "src/kernel/db.ts",
619 "src/kernel/error.ts",
620 "src/kernel/id.ts",
621 "src/kernel/log.ts",
622 "src/kernel/migrate.ts",
623 "src/kernel/result.ts",
624 "src/kernel/secret.ts",
625 "src/spawn/claim.ts",
626 "src/spawn/placement.ts",
627 "src/spawn/plan.ts",
628 "src/ssh/keys.ts",
629 "src/ssh/wire.ts"
630 ],
631 "test/standing.test.ts": [
632 "src/actions/access.ts",
633 "src/actions/repos.ts",
634 "src/actions/verify.ts",
635 "src/app.ts",
636 "src/core/capacity.ts",
637 "src/core/events.ts",
638 "src/core/following.ts",
639 "src/core/repos.ts",
640 "src/core/reserved.ts",
641 "src/core/runs.ts",
642 "src/core/schema.ts",
643 "src/core/sealed.ts",
644 "src/core/standing.ts",
645 "src/core/subscriptions.ts",
646 "src/core/usage.ts",
647 "src/core/users.ts",
648 "src/core/verify.ts",
649 "src/core/webhooks.ts",
650 "src/crew/limits.ts",
651 "src/git/env.ts",
652 "src/git/guard.ts",
653 "src/git/hooks.ts",
654 "src/git/read.ts",
655 "src/git/repos.ts",
656 "src/kernel/db.ts",
657 "src/kernel/error.ts",
658 "src/kernel/id.ts",
659 "src/kernel/migrate.ts",
660 "src/kernel/result.ts",
661 "src/kernel/secret.ts"
662 ],
663 "test/tree.test.ts": [
664 "scripts/tree.ts"
665 ]
666 }
scripts/test-shards.ts +138 −8
@@ -29,10 +29,25 @@
2929 * `--record` refreshes that table: the same number of workers, but each
3030 * file is its own `bun test`, timed alone from spawn to exit, and the
3131 * table is rewritten from those times when every file is green.
32 *
33 * `--record` also runs each file under `--coverage` and rewrites
34 * `scripts/test-impact.json` (`scripts/impact.ts`): the repository files
35 * each test executed beyond what loading the forge runs, measured first
36 * by `scripts/impact-baseline.test.ts`. `--tier fast` intersects the diff with that map
37 * (`src/checks/tiers.ts`, #1279); a missing or refused map is said, and
38 * the fast tier falls back to guessing from imports and names.
3239 */
3340
3441 import { availableParallelism } from "node:os";
35 import { readFileSync, statSync, writeFileSync } from "node:fs";
42 import {
43 mkdtempSync,
44 readFileSync,
45 rmSync,
46 statSync,
47 writeFileSync,
48 } from "node:fs";
49 import { tmpdir } from "node:os";
50 import { join } from "node:path";
3651 import {
3752 formatTimes,
3853 parseShardSpec,
@@ -46,9 +61,39 @@ import {
4661 type ShardResult,
4762 } from "./shards.ts";
4863 import { GATE } from "./gate.ts";
49 import { fastSet, importsOf, duration } from "../src/checks/tiers.ts";
64 import {
65 baselineGaps,
66 executedFiles,
67 formatImpact,
68 lcovHits,
69 parseImpact,
70 type Hits,
71 type Impact,
72 } from "./impact.ts";
73 import {
74 fastSet,
75 importsOf,
76 planLine,
77 reachLine,
78 } from "../src/checks/tiers.ts";
5079
5180 const TIMES = new URL("./test-times.json", import.meta.url).pathname;
81 const IMPACT = new URL("./test-impact.json", import.meta.url).pathname;
82 const BASELINE = "./scripts/impact-baseline.test.ts";
83
84 /** The impact map, or why there is none (said in the log, never fatal). */
85 function readImpact(): { value: Impact } | { error: string } {
86 let text: string;
87 try {
88 text = readFileSync(IMPACT, "utf8");
89 } catch {
90 return { error: "no scripts/test-impact.json" };
91 }
92 const parsed = parseImpact(text);
93 return parsed.ok
94 ? { value: parsed.value }
95 : { error: `scripts/test-impact.json refused (${parsed.error})` };
96 }
5297
5398 const argv = process.argv.slice(2);
5499 const record = argv.includes("--record");
@@ -205,20 +250,27 @@ if (tier === "fast") {
205250 }
206251 return found;
207252 };
253 const impact = readImpact();
254 if ("error" in impact)
255 console.log(`test-shards: ${impact.error}; guessing from imports and names`);
208256 const plan = fastSet({
209257 changed,
210258 tests: files,
211259 imports,
212260 times: timesTable.ok ? timesTable.value : new Map(),
213261 learned: (learnedArg.value ?? "").split(",").filter((f) => f !== ""),
262 ...("value" in impact ? { impact: impact.value } : {}),
214263 });
215 console.log(
216 `test-shards: fast tier, ${plan.files.length} of ${files.length} files for ${changed.length} changed ` +
217 `(expected ${duration(plan.expected)}${plan.overBudget ? ", over the 5m budget" : ""})`,
218 );
264 console.log(`test-shards: ${reachLine(plan)}`);
265 console.log(`test-shards: ${planLine(plan, files.length)}`);
219266 for (const file of plan.files)
220267 console.log(` ${file}: ${plan.why.get(file)}`);
221268 files = plan.files;
269 // Measured, an empty set is an answer: the change reaches no test.
270 if (files.length === 0) {
271 console.log("test-shards: fast tier, the change reaches no test; nothing to run");
272 process.exit(0);
273 }
222274 }
223275
224276 if (files.length === 0) {
@@ -336,7 +388,11 @@ async function drain(
336388 take(decoder.decode());
337389 }
338390
339 type Timed = ShardResult & { seconds: number };
391 type Timed = ShardResult & {
392 seconds: number;
393 /** Recording: the lines the file ran, by repository file, from its LCOV. */
394 hits: Hits | undefined;
395 };
340396
341397 /**
342398 * One shard. `live` (shards running one at a time) writes the shard's
@@ -368,7 +424,12 @@ async function runShard(
368424 // to bun test shards — a leftover max-old-space-size races the check
369425 // cell's memory cgroup and the kernel SIGKILLs the gate (exit 137).
370426 delete childEnv["NODE_OPTIONS"];
371 const child = Bun.spawn(["bun", "test", ...flags, ...paths], {
427 // Recording, each file writes its own LCOV report: what it executed.
428 const coverage = record ? mkdtempSync(join(tmpdir(), "test-impact-")) : "";
429 const coverageFlags = record
430 ? ["--coverage", "--coverage-reporter=lcov", `--coverage-dir=${coverage}`]
431 : [];
432 const child = Bun.spawn(["bun", "test", ...flags, ...coverageFlags, ...paths], {
372433 stdin: "ignore",
373434 stdout: "pipe",
374435 stderr: "pipe",
@@ -393,6 +454,15 @@ async function runShard(
393454 children.delete(child);
394455 const text = output.join("");
395456 const seconds = ((performance.now() - started) / 1000).toFixed(1);
457 let hits: Hits | undefined;
458 if (record) {
459 try {
460 hits = lcovHits(readFileSync(join(coverage, "lcov.info"), "utf8"));
461 } catch {
462 hits = undefined;
463 }
464 rmSync(coverage, { recursive: true, force: true });
465 }
396466 process.stdout.write(
397467 live
398468 ? `${text.endsWith("\n") || text === "" ? "" : "\n"}── shard ${where} done (exit ${code}, ${seconds}s)\n`
@@ -403,6 +473,7 @@ async function runShard(
403473 code,
404474 output: text,
405475 seconds: (performance.now() - started) / 1000,
476 hits,
406477 };
407478 }
408479
@@ -430,6 +501,49 @@ async function pool(width: number): Promise<Timed[]> {
430501 return results.filter((result): result is Timed => result !== undefined);
431502 }
432503
504 /**
505 * Recording: what loading the forge runs, which no test is said to
506 * execute. `undefined` when the probe is red or wrote no report — then
507 * the map is not rewritten, since without it every test that boots the
508 * server would execute every page.
509 */
510 function measureBaseline(): Hits | undefined {
511 const dir = mkdtempSync(join(tmpdir(), "test-impact-"));
512 try {
513 const probe = Bun.spawnSync(
514 [
515 "bun",
516 "test",
517 "--coverage",
518 "--coverage-reporter=lcov",
519 `--coverage-dir=${dir}`,
520 BASELINE,
521 ],
522 { stdin: "ignore", stdout: "pipe", stderr: "pipe" },
523 );
524 if (probe.exitCode !== 0) return undefined;
525 const hits = lcovHits(readFileSync(join(dir, "lcov.info"), "utf8"));
526 const pages = [...new Bun.Glob("src/web/pages/*.ts").scanSync(".")];
527 const gaps = baselineGaps(hits, pages);
528 if (pages.length === 0 || gaps.length > 0) {
529 console.log(
530 `test-shards: ${BASELINE} did not load ${pages.length === 0 ? "any page" : gaps.join(", ")}`,
531 );
532 return undefined;
533 }
534 return hits;
535 } catch {
536 return undefined;
537 } finally {
538 rmSync(dir, { recursive: true, force: true });
539 }
540 }
541 const baseline = record ? measureBaseline() : undefined;
542 if (record && baseline === undefined)
543 console.log(
544 `test-shards: ${BASELINE} was red or wrote no report; times only, the impact map is kept as it was`,
545 );
546
433547 const started = performance.now();
434548 // Serial one-file processes when SHARDS=1; record keeps its worker width;
435549 // multi-shard still runs every slice side by side.
@@ -463,6 +577,22 @@ if (record) {
463577 console.log(
464578 `test-shards: wrote ${results.length} times to scripts/test-times.json`,
465579 );
580 // The same rule for the impact map: what ran is refreshed, the rest
581 // kept. A file with no report is left as it was, and said.
582 if (baseline !== undefined) {
583 const known = readImpact();
584 const map: Impact = new Map("value" in known ? known.value : []);
585 const missing: string[] = [];
586 for (const result of results) {
587 if (result.hits === undefined) missing.push(result.files[0]!);
588 else map.set(result.files[0]!, executedFiles(result.hits, baseline));
589 }
590 writeFileSync(IMPACT, formatImpact(map));
591 console.log(
592 `test-shards: wrote ${results.length - missing.length} coverage maps to scripts/test-impact.json` +
593 (missing.length > 0 ? `; no report for ${missing.join(", ")}` : ""),
594 );
595 }
466596 }
467597 }
468598 process.exit(ending.code);
src/checks/tiers.ts +170 −31
@@ -1,7 +1,9 @@
11 /**
22 * The check's two tiers (#1198). `fast` judges every push to a pull: the
3 * test files that touch what the pull changed, plus every test that is
4 * quick anyway. `full` is the whole gate, run once when the pull lands.
3 * test files that reach what the pull changed — measured by each test's
4 * recorded coverage where there is a map (#1279), guessed from imports
5 * and names where there is not. `full` is the whole gate, run once when
6 * the pull lands.
57 *
68 * Plain data in, plain data out: which files the fast tier runs, what the
79 * checks line says, and what a red full gate on land does to the pull.
@@ -64,6 +66,37 @@ function namesOf(path: string): string[] {
6466 const stemOf = (test: string): string =>
6567 test.replace(/^test\//, "").replace(/\.test\.[cm]?[jt]sx?$/, "");
6668
69 /** The reasons only the guess gives (see {@link fastSet}). */
70 const GUESS = /^(?:imports |named for |quick$)/;
71
72 /** A test file, by its name. */
73 const TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
74
75 /** Code: what a test can execute, so what can have no test reaching it. */
76 const CODE_FILE = /\.[cm]?[jt]sx?$/;
77
78 /**
79 * Files whose effect no coverage map can bound: how the check runs
80 * (`forge.json`, `package.json`, the lockfile, `bunfig.toml`,
81 * `tsconfig.json`), the runner and its tables (`scripts/**`), and the
82 * kernel every module stands on (`src/kernel/**`). A change to one runs
83 * the full tier on push.
84 */
85 const WHOLE = [
86 /^forge\.json$/,
87 /^package\.json$/,
88 /^bun\.lockb?$/,
89 /^bunfig\.toml$/,
90 /^tsconfig\.json$/,
91 /^scripts\//,
92 /^src\/kernel\//,
93 ];
94
95 /** The first changed file only the full tier can judge, if any. */
96 export function wholeChange(changed: readonly string[]): string | undefined {
97 return changed.find((file) => WHOLE.some((rule) => rule.test(file)));
98 }
99
67100 export interface FastInput {
68101 /** Files the pull changed, repository-relative. */
69102 readonly changed: readonly string[];
@@ -75,6 +108,12 @@ export interface FastInput {
75108 readonly times: ReadonlyMap<string, number>;
76109 /** Tests a red full gate on land taught this pull. */
77110 readonly learned?: readonly string[];
111 /**
112 * The files each test executed when it ran alone under coverage
113 * (`scripts/test-impact.json`, #1279). Absent: no map, so every test is
114 * picked by the guess, as before it.
115 */
116 readonly impact?: ReadonlyMap<string, readonly string[]>;
78117 }
79118
80119 export interface FastPlan {
@@ -84,47 +123,110 @@ export interface FastPlan {
84123 /** Expected seconds, from the times table (a test it lacks counts 5). */
85124 readonly expected: number;
86125 readonly overBudget: boolean;
126 /** The changed file that made this the full tier; `null` when it is not. */
127 readonly full: string | null;
128 /** How many files the pull changed. */
129 readonly changed: number;
130 /** Changed code files no test reaches: coverage gaps, sorted. */
131 readonly unreached: readonly string[];
132 /** Whether a coverage map decided (#1279); `false` is all guess. */
133 readonly measured: boolean;
134 /** How many of the files only the guess picked. */
135 readonly guessed: number;
87136 }
88137
89138 /**
90 * The fast tier for a diff: a changed test; a test importing a changed file
91 * directly or through up to two hops of source; a test whose name matches a
92 * changed source path; whatever the pull learned; and every test known to
93 * take under a second. A test with no recorded time is not known to be quick, so it runs only when
94 * something above picks it.
139 * The fast tier for a diff.
140 *
141 * A change to a file no map can bound ({@link wholeChange}) runs every test.
142 * Otherwise: a changed test; a test whose measured coverage executed a
143 * changed file; whatever the pull learned. The guess — a test importing a
144 * changed file directly or through up to two hops of source, or named for
145 * a changed source path — is kept only where the map has nothing to say:
146 * for a test the map has never seen (a new test), and for a changed file
147 * no mapped test executed (a new module). Without a map every test is
148 * guessed, and every test known to take under a second runs as well; with
149 * one, nothing the change cannot reach runs. A changed code file that
150 * nothing reaches is a coverage gap, and is said.
95151 */
96152 export function fastSet(input: FastInput): FastPlan {
97153 const tests = new Set(input.tests);
98 const why = new Map<string, string>();
99 const take = (test: string, reason: string): void => {
100 if (tests.has(test) && !why.has(test)) why.set(test, reason);
101 };
102154 const changed = new Set(input.changed);
155 const finish = (
156 files: string[],
157 why: Map<string, string>,
158 full: string | null,
159 unreached: string[],
160 ): FastPlan => {
161 const guessed = files.filter((file) => GUESS.test(why.get(file) ?? "")).length;
162 const expected = files.reduce(
163 (sum, file) => sum + (input.times.get(file) ?? UNKNOWN_SECONDS),
164 0,
165 );
166 return {
167 files,
168 why,
169 expected,
170 overBudget: expected > FAST_BUDGET_SECONDS,
171 full,
172 changed: changed.size,
173 unreached,
174 measured: input.impact !== undefined,
175 guessed,
176 };
177 };
178
179 const whole = wholeChange(input.changed);
180 if (whole !== undefined) {
181 const why = new Map(input.tests.map((test) => [test, `full: ${whole} changed`]));
182 return finish([...input.tests], why, whole, []);
183 }
184
185 const why = new Map<string, string>();
186 const reached = new Set<string>();
187 const take = (test: string, reason: string, by?: string): void => {
188 if (!tests.has(test)) return;
189 if (by !== undefined) reached.add(by);
190 if (!why.has(test)) why.set(test, reason);
191 };
103192 for (const file of changed) take(file, "changed");
104193
105 const sources = input.changed.filter((file) => !tests.has(file));
194 const impact = input.impact;
195 const seen = new Set<string>();
196 if (impact !== undefined)
197 for (const test of input.tests)
198 for (const file of impact.get(test) ?? []) {
199 seen.add(file);
200 if (changed.has(file)) take(test, `executes ${file}`, file);
201 }
202
203 // The guess: every changed source for a test the map has not measured;
204 // only the sources the map has never seen executed for one it has.
205 const sources = input.changed.filter((file) => !TEST_FILE.test(file));
206 const unseen = new Set(sources.filter((file) => !seen.has(file)));
207 const guessed = (test: string): ReadonlySet<string> =>
208 impact?.has(test) ? unseen : new Set(sources);
106209 const names = new Map<string, string>();
107210 for (const source of sources)
108211 for (const name of namesOf(source)) names.set(name, source);
109212 for (const test of input.tests) {
110213 const hit = names.get(stemOf(test));
111 if (hit !== undefined) take(test, `named for ${hit}`);
214 if (hit !== undefined && guessed(test).has(hit))
215 take(test, `named for ${hit}`, hit);
112216 }
113217
114218 for (const test of input.tests) {
115 if (why.has(test)) continue;
219 const targets = guessed(test);
220 if (targets.size === 0) continue;
116221 let frontier: readonly string[] = input.imports(test);
117 const seen = new Set<string>();
222 const walked = new Set<string>();
118223 for (let depth = 0; depth <= IMPORT_DEPTH && frontier.length > 0; depth++) {
119 const hit = frontier.find((file) => changed.has(file));
120 if (hit !== undefined) {
121 take(test, `imports ${hit}`);
122 break;
123 }
224 const hits = frontier.filter((file) => targets.has(file));
225 for (const hit of hits) take(test, `imports ${hit}`, hit);
124226 const next: string[] = [];
125227 for (const file of frontier) {
126 if (seen.has(file)) continue;
127 seen.add(file);
228 if (walked.has(file)) continue;
229 walked.add(file);
128230 next.push(...input.imports(file));
129231 }
130232 frontier = next;
@@ -132,18 +234,55 @@ export function fastSet(input: FastInput): FastPlan {
132234 }
133235
134236 for (const test of input.learned ?? []) take(test, "failed on land before");
135 for (const test of input.tests) {
136 const seconds = input.times.get(test);
137 if (seconds !== undefined && seconds < QUICK_SECONDS)
138 take(test, "quick");
139 }
237 if (impact === undefined)
238 for (const test of input.tests) {
239 const seconds = input.times.get(test);
240 if (seconds !== undefined && seconds < QUICK_SECONDS)
241 take(test, "quick");
242 }
140243
244 const unreached = sources
245 .filter((file) => CODE_FILE.test(file) && !reached.has(file))
246 .sort();
141247 const files = input.tests.filter((test) => why.has(test));
142 const expected = files.reduce(
143 (sum, file) => sum + (input.times.get(file) ?? UNKNOWN_SECONDS),
144 0,
248 return finish(files, why, null, unreached);
249 }
250
251 const plural = (count: number, one: string, many = `${one}s`): string =>
252 `${count} ${count === 1 ? one : many}`;
253
254 /**
255 * What the change reaches, in one line for the check's log:
256 * `3 changed files reach 14 tests; src/web/x.ts reaches none`, or why it
257 * is the full tier.
258 */
259 export function reachLine(plan: FastPlan): string {
260 if (plan.full !== null)
261 return `${plan.full} changed, which no map can bound: full tier, ${plural(plan.files.length, "test")}`;
262 const head = `${plural(plan.changed, "changed file")} ${plan.changed === 1 ? "reaches" : "reach"} ${plural(plan.files.length, "test")}`;
263 if (plan.unreached.length === 0) return head;
264 const gaps = plan.unreached;
265 return `${head}; ${gaps.join(", ")} ${gaps.length === 1 ? "reaches" : "reach"} none`;
266 }
267
268 /**
269 * The fast tier's plan, in one line for the check's log:
270 * `fast tier, 12 of 195 files for 1 changed, by coverage (expected 48s)`.
271 * Said `by guess` without a map, and how many the guess added beside one.
272 */
273 export function planLine(plan: FastPlan, total: number): string {
274 const how =
275 plan.full !== null
276 ? `full: ${plan.full} changed`
277 : !plan.measured
278 ? "by guess"
279 : plan.guessed === 0
280 ? "by coverage"
281 : `by coverage, ${plan.guessed} by guess`;
282 return (
283 `fast tier, ${plan.files.length} of ${total} files for ${plan.changed} changed, ${how} ` +
284 `(expected ${duration(plan.expected)}${plan.overBudget ? ", over the 5m budget" : ""})`
145285 );
146 return { files, why, expected, overBudget: expected > FAST_BUDGET_SECONDS };
147286 }
148287
149288 /** `220` → `3m40s`, `45` → `45s`. */
test/check-tiers.test.ts +265
@@ -21,8 +21,18 @@ import {
2121 fastSet,
2222 importsOf,
2323 landVerdict,
24 planLine,
25 reachLine,
2426 tierLine,
27 wholeChange,
2528 } from "../src/checks/tiers.ts";
29 import {
30 baselineGaps,
31 executedFiles,
32 formatImpact,
33 lcovHits,
34 parseImpact,
35 } from "../scripts/impact.ts";
2636 import { parseCheck } from "../src/apps/manifest.ts";
2737
2838 const tests = [
@@ -101,6 +111,261 @@ describe("the fast set", () => {
101111 });
102112 });
103113
114 describe("the fast set, by measured coverage (#1279)", () => {
115 // What each test executed when it ran alone under coverage.
116 const impact = new Map<string, readonly string[]>([
117 ["test/snapshot-store.test.ts", ["src/snapshot/store.ts"]],
118 [
119 "test/snapshot.test.ts",
120 ["src/snapshot/service.ts", "src/snapshot/store.ts"],
121 ],
122 ["test/web-phone.test.ts", ["src/web/phone.ts", "src/web/x.ts"]],
123 ["test/deep.test.ts", ["src/a.ts", "src/b.ts", "src/c.ts", "src/d.ts"]],
124 ["test/tiny.test.ts", ["src/tiny.ts"]],
125 ]);
126
127 test("a diff to one source file picks exactly the tests that executed it", () => {
128 const plan = fastSet({
129 changed: ["src/snapshot/service.ts"],
130 tests,
131 imports,
132 times,
133 impact,
134 });
135 // store's test is named like service's dir and was guessed before;
136 // the quick test always ran. Neither executes service.ts.
137 expect(plan.files).toEqual(["test/snapshot.test.ts"]);
138 expect(plan.why.get("test/snapshot.test.ts")).toBe(
139 "executes src/snapshot/service.ts",
140 );
141 expect(plan.unreached).toEqual([]);
142 expect(reachLine(plan)).toBe("1 changed file reaches 1 test");
143 });
144
145 test("a change to one page runs the tests that executed it, not every server test", () => {
146 // #1280: 146 of 160 were picked for importing src/http/server.ts.
147 const served = [
148 "test/board.test.ts",
149 "test/accounts.test.ts",
150 "test/api-errors.test.ts",
151 ];
152 const plan = fastSet({
153 changed: ["src/web/pages/board.ts"],
154 tests: served,
155 imports: (file) =>
156 served.includes(file)
157 ? ["src/http/server.ts"]
158 : file === "src/http/server.ts"
159 ? ["src/web/pages/board.ts", "src/web/pages/accounts.ts"]
160 : [],
161 times: new Map([
162 ["test/board.test.ts", 12],
163 ["test/accounts.test.ts", 30],
164 ["test/api-errors.test.ts", 8],
165 ]),
166 impact: new Map([
167 ["test/board.test.ts", ["src/http/server.ts", "src/web/pages/board.ts"]],
168 ["test/accounts.test.ts", ["src/http/server.ts", "src/web/pages/accounts.ts"]],
169 ["test/api-errors.test.ts", ["src/http/server.ts"]],
170 ]),
171 });
172 expect(plan.files).toEqual(["test/board.test.ts"]);
173 expect(planLine(plan, served.length)).toBe(
174 "fast tier, 1 of 3 files for 1 changed, by coverage (expected 12s)",
175 );
176 });
177
178 test("the plan line says how the set was chosen", () => {
179 const measured = fastSet({
180 changed: ["src/snapshot/fresh.ts"],
181 tests,
182 imports: (file) =>
183 file === "src/snapshot/service.ts" ? ["src/snapshot/fresh.ts"] : imports(file),
184 times,
185 impact,
186 });
187 expect(planLine(measured, 5)).toBe(
188 "fast tier, 1 of 5 files for 1 changed, by coverage, 1 by guess (expected 30s)",
189 );
190 const guessed = fastSet({ changed: ["src/snapshot/store.ts"], tests, imports, times });
191 expect(planLine(guessed, 5)).toBe(
192 "fast tier, 3 of 5 files for 1 changed, by guess (expected 1m00s)",
193 );
194 const full = fastSet({ changed: ["forge.json"], tests, imports, times, impact });
195 expect(planLine(full, 5)).toBe(
196 "fast tier, 5 of 5 files for 1 changed, full: forge.json changed (expected 2m50s)",
197 );
198 });
199
200 test("coverage reaches past the two-hop guess", () => {
201 const plan = fastSet({ changed: ["src/d.ts"], tests, imports, times, impact });
202 expect(plan.files).toEqual(["test/deep.test.ts"]);
203 });
204
205 test("an unmapped new test is picked by the hop rule; mapped ones are not guessed", () => {
206 const plan = fastSet({
207 changed: ["src/snapshot/store.ts"],
208 tests: [...tests, "test/new.test.ts"],
209 imports: (file) =>
210 file === "test/new.test.ts" ? ["src/snapshot/service.ts"] : imports(file),
211 times,
212 impact,
213 });
214 expect(plan.files).toEqual([
215 "test/snapshot-store.test.ts",
216 "test/snapshot.test.ts",
217 "test/new.test.ts",
218 ]);
219 expect(plan.why.get("test/new.test.ts")).toBe("imports src/snapshot/store.ts");
220 });
221
222 test("a changed file the map never saw is guessed from imports", () => {
223 const plan = fastSet({
224 changed: ["src/snapshot/fresh.ts"],
225 tests,
226 imports: (file) =>
227 file === "src/snapshot/service.ts" ? ["src/snapshot/fresh.ts"] : imports(file),
228 times,
229 impact,
230 });
231 expect(plan.files).toEqual(["test/snapshot.test.ts"]);
232 });
233
234 test("a changed file no test reaches is a gap, said in the line", () => {
235 const plan = fastSet({
236 changed: ["src/snapshot/store.ts", "src/web/y.ts", "README.md"],
237 tests,
238 imports,
239 times,
240 impact,
241 learned: ["test/tiny.test.ts"],
242 });
243 expect(plan.files).toEqual([
244 "test/snapshot-store.test.ts",
245 "test/snapshot.test.ts",
246 "test/tiny.test.ts",
247 ]);
248 expect(plan.unreached).toEqual(["src/web/y.ts"]);
249 expect(reachLine(plan)).toBe(
250 "3 changed files reach 3 tests; src/web/y.ts reaches none",
251 );
252 });
253
254 test("a kernel, manifest or script change runs the full tier", () => {
255 for (const file of [
256 "src/kernel/result.ts",
257 "forge.json",
258 "package.json",
259 "scripts/test-shards.ts",
260 ]) {
261 const plan = fastSet({
262 changed: ["src/snapshot/store.ts", file],
263 tests,
264 imports,
265 times,
266 impact,
267 });
268 expect(plan.files).toEqual(tests);
269 expect(plan.full).toBe(file);
270 expect(reachLine(plan)).toBe(
271 `${file} changed, which no map can bound: full tier, 5 tests`,
272 );
273 }
274 expect(wholeChange(["src/kernelish.ts", "docs/scripts/x.md"])).toBeUndefined();
275 });
276 });
277
278 describe("the impact map's formats", () => {
279 test("lcov gives the lines each repository file ran, not tests or packages", () => {
280 const lcov = [
281 "TN:",
282 "SF:src/a.ts",
283 "DA:1,1",
284 "DA:2,0",
285 "DA:3,4",
286 "end_of_record",
287 "SF:test/helpers/git.ts",
288 "DA:5,1",
289 "end_of_record",
290 "SF:test/other.test.ts",
291 "DA:1,1",
292 "end_of_record",
293 "SF:node_modules/x/index.js",
294 "DA:1,1",
295 "end_of_record",
296 "SF:/usr/lib/bun.ts",
297 "SF:../outside.ts",
298 "DA:1,1",
299 "end_of_record",
300 "",
301 ].join("\n");
302 const hits = lcovHits(lcov);
303 expect([...hits.keys()].sort()).toEqual(["src/a.ts", "test/helpers/git.ts"]);
304 expect([...hits.get("src/a.ts")!].sort()).toEqual([1, 3]);
305 });
306
307 test("a file only loaded, as loading the forge loads it, is not executed", () => {
308 // What loading the forge ran: each page's imports and route factory.
309 const baseline = lcovHits(
310 [
311 "SF:src/http/server.ts", "DA:1,1", "DA:2,1", "end_of_record",
312 "SF:src/web/pages/board.ts", "DA:1,1", "DA:9,1", "end_of_record",
313 "SF:src/web/pages/accounts.ts", "DA:1,1", "end_of_record",
314 ].join("\n"),
315 );
316 // A test that booted the server and rendered the board.
317 const run = lcovHits(
318 [
319 "SF:src/http/server.ts", "DA:1,1", "DA:2,1", "DA:40,3", "end_of_record",
320 "SF:src/web/pages/board.ts", "DA:1,1", "DA:9,1", "DA:12,1", "end_of_record",
321 "SF:src/web/pages/accounts.ts", "DA:1,1", "DA:7,0", "end_of_record",
322 "SF:src/web/board.ts", "DA:1,1", "end_of_record",
323 ].join("\n"),
324 );
325 expect(executedFiles(run, baseline)).toEqual([
326 "src/http/server.ts",
327 "src/web/board.ts",
328 "src/web/pages/board.ts",
329 ]);
330 // Without the baseline, every file loaded counts.
331 expect(executedFiles(run)).toHaveLength(4);
332 });
333
334 test("a baseline that missed a page is refused, one that loaded them all is not", () => {
335 // The probe itself runs under --record only (scripts/test-shards.ts);
336 // here, the rule it is judged by.
337 const pages = ["src/web/pages/board.ts", "src/web/pages/accounts.ts"];
338 const baseline = lcovHits(
339 ["SF:src/web/pages/board.ts", "DA:1,1", "end_of_record"].join("\n"),
340 );
341 expect(baselineGaps(baseline, pages)).toEqual(["src/web/pages/accounts.ts"]);
342 const full = lcovHits(
343 [
344 "SF:src/web/pages/board.ts", "DA:1,1", "end_of_record",
345 "SF:src/web/pages/accounts.ts", "DA:1,1", "end_of_record",
346 ].join("\n"),
347 );
348 expect(baselineGaps(full, pages)).toEqual([]);
349 });
350
351 test("the map round-trips, and anything untrusted refuses the whole of it", () => {
352 const map = new Map([
353 ["test/b.test.ts", ["src/z.ts", "src/a.ts"]],
354 ["test/a.test.ts", []],
355 ]);
356 const text = formatImpact(map);
357 expect(text.indexOf("test/a.test.ts")).toBeLessThan(text.indexOf("test/b.test.ts"));
358 const back = parseImpact(text);
359 if (!back.ok) throw new Error(back.error);
360 expect(back.value.get("test/b.test.ts")).toEqual(["src/a.ts", "src/z.ts"]);
361 expect(parseImpact("[]").ok).toBe(false);
362 expect(parseImpact('{"src/a.ts": []}').ok).toBe(false);
363 expect(parseImpact('{"test/a.test.ts": ["../etc/passwd"]}').ok).toBe(false);
364 expect(parseImpact('{"test/a.test.ts": ["--flag"]}').ok).toBe(false);
365 expect(parseImpact('{"test/a.test.ts": "src/a.ts"}').ok).toBe(false);
366 });
367 });
368
104369 describe("importsOf", () => {
105370 test("resolves relative specifiers and leaves packages out", () => {
106371 const source = `import { a } from "../src/snapshot/store.ts";\nimport x from "node:fs";\nconst m = await import("./helper.ts");`;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs