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

A check never trips its own CPU guard: test workers follow the cell's CPU limit, not the host's #2247

Closed opened this in answer to
Closed without merging

torque/forge:torque/2243-a-check-never-trips-its-own-cpu-guard-te → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +416 −13
README.md +10 −4
@@ -939,10 +939,16 @@ bun run check:record # the same, and rewrites scripts/test-times.json
939939 it says here is what the deploy will say. It type-checks once, then runs the
940940 test files `scripts/gate.ts` admits — every `test/*.test.ts` not in its
941941 `EXCLUDED` — as parallel `bun test` shards
942 (`scripts/test-shards.ts`): one per CPU the process may use, no more than
943 one per 512 MiB of the memory its cgroup allows (16 on the 16-CPU, 8 GiB
944 check cell; the old ceiling of eight left half of it idle, #2038), and
945 `FORGE_CHECK_SHARDS=2` turns that down on a small or busy host. Each
942 (`scripts/test-shards.ts`): one per CPU the process may use, less one for
943 the runner, no more than one per 512 MiB of the memory its cgroup allows
944 (15 on the 16-CPU, 8 GiB check cell), and `FORGE_CHECK_SHARDS=2` turns
945 that down on a small or busy host. The CPUs are the cell's, not the
946 host's: the forge hands a check its `check.limits.cpus` as
947 `FORGE_CELL_CPUS`, the shard count and tsc's `GOMAXPROCS` both follow it,
948 and an override never goes past it — inside a cell the host's 80 CPUs are
949 visible, and a gate sized by them was stopped for keeping 16.1 cores busy
950 (#2243). The full gate's summary ends with the peak cores of any 30 s
951 window, counted as the cell's guard counts them (`scripts/cores.ts`). Each
946952 shard's output is written whole as it finishes; the log ends with every
947953 failing test from every shard, or on green with one line — how many tests,
948954 across how many files, in how long, then the slowest and fastest shard.
docs/APPS.md +2 −1
@@ -1137,7 +1137,8 @@ honours the change, never a restart. The variable stays the boot default
11371137 until a value is set, and every change is listed on that page with who
11381138 made it, when, and from what to what (`core/capacity.ts`). The shard count
11391139 reaches a check's commands and an agent's shell as `FORGE_CHECK_SHARDS`,
1140 from the setting, never from the forge's own environment.
1140 from the setting, never from the forge's own environment; inside a check
1141 it never goes past `FORGE_CELL_CPUS`, the check cell's CPU limit (#2243).
11411142
11421143 ### Boards: counting the forge's own tables
11431144
forge.json +2 −2
@@ -14,8 +14,8 @@
1414 }
1515 },
1616 "check": {
17 "fast": "bun scripts/gate.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --tier fast --diff $FORGE_CHECK_BASE..HEAD --learned \"$FORGE_CHECK_LEARNED\"",
18 "run": "bun scripts/gate.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --gate --impact",
17 "fast": "bun scripts/gate.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB GOMAXPROCS=$FORGE_CELL_CPUS ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --tier fast --diff $FORGE_CHECK_BASE..HEAD --learned \"$FORGE_CHECK_LEARNED\"",
18 "run": "bun scripts/gate.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB GOMAXPROCS=$FORGE_CELL_CPUS ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --gate --impact",
1919 "timeout": 7200,
2020 "limits": {
2121 "memory": 8192,
scripts/cores.ts added +140
@@ -0,0 +1,140 @@
1 /**
2 * How many cores the gate kept busy, counted as the forge's guard counts
3 * them (`apps/contain.ts`): user + system ticks, the process's own and its
4 * reaped children's (`/proc/<pid>/stat` fields 14–17), summed over a tree,
5 * sampled every second, cores = Δticks ÷ CLK_TCK ÷ Δseconds across a 30 s
6 * window. The guard stops a check whose window goes past its limit; the
7 * gate's summary prints the peak beside that limit, so a check's log says
8 * how close it came (#2243).
9 */
10
11 import { readdirSync, readFileSync } from "node:fs";
12
13 /** Ticks per second in `/proc/<pid>/stat` (`USER_HZ`, 100 on Linux). */
14 export const CLK_TCK = 100;
15 /** The guard's window, `WATCH.cpuWindowMs` in `apps/contain.ts`. */
16 export const WINDOW_MS = 30_000;
17
18 export interface Sample {
19 /** Milliseconds, any monotonic clock. */
20 readonly at: number;
21 /** CPU ticks of the whole tree at `at`. */
22 readonly ticks: number;
23 }
24
25 /**
26 * One `/proc/<pid>/stat` line: its parent and utime + stime + cutime +
27 * cstime. The command name sits in parentheses and may hold spaces, so
28 * fields are counted from the last `)`. Anything malformed is `undefined`.
29 */
30 export function parseStat(
31 text: string,
32 ): { ppid: number; ticks: number } | undefined {
33 const close = text.lastIndexOf(")");
34 if (close < 0) return undefined;
35 const fields = text.slice(close + 2).split(" ");
36 const numbers = [1, 11, 12, 13, 14].map((i) => Number(fields[i]));
37 if (!numbers.every((n) => Number.isInteger(n) && n >= 0)) return undefined;
38 const [ppid, ...times] = numbers as [number, ...number[]];
39 return { ppid, ticks: times.reduce((sum, n) => sum + n, 0) };
40 }
41
42 /** Ticks of `root` and every process under it, from pid → stat rows. */
43 export function treeTicks(
44 rows: ReadonlyMap<number, { ppid: number; ticks: number }>,
45 root: number,
46 ): number {
47 const children = new Map<number, number[]>();
48 for (const [pid, row] of rows) {
49 const list = children.get(row.ppid);
50 if (list) list.push(pid);
51 else children.set(row.ppid, [pid]);
52 }
53 let total = 0;
54 const stack = rows.has(root) ? [root] : [];
55 const seen = new Set<number>();
56 while (stack.length > 0) {
57 const pid = stack.pop()!;
58 if (seen.has(pid)) continue;
59 seen.add(pid);
60 total += rows.get(pid)!.ticks;
61 stack.push(...(children.get(pid) ?? []));
62 }
63 return total;
64 }
65
66 /**
67 * The most cores any window of at least `windowMs` saw, as the guard
68 * reads it: each sample against the latest earlier one at least a window
69 * before it. `undefined` when the samples span less than one window — the
70 * guard never judged such a run either.
71 */
72 export function peakCores(
73 samples: readonly Sample[],
74 windowMs: number = WINDOW_MS,
75 ): number | undefined {
76 let peak: number | undefined;
77 let start = 0;
78 for (let i = 0; i < samples.length; i++) {
79 const now = samples[i]!;
80 while (
81 start + 1 < i &&
82 now.at - samples[start + 1]!.at >= windowMs
83 )
84 start++;
85 const oldest = samples[start]!;
86 if (start >= i || now.at - oldest.at < windowMs) continue;
87 const cores =
88 (now.ticks - oldest.ticks) / CLK_TCK / ((now.at - oldest.at) / 1000);
89 if (peak === undefined || cores > peak) peak = cores;
90 }
91 return peak;
92 }
93
94 /** Every process's stat row; an unreadable `/proc` is an empty table. */
95 function processRows(): Map<number, { ppid: number; ticks: number }> {
96 const rows = new Map<number, { ppid: number; ticks: number }>();
97 let names: string[] = [];
98 try {
99 names = readdirSync("/proc");
100 } catch {
101 return rows;
102 }
103 for (const name of names) {
104 if (!/^\d+$/.test(name)) continue;
105 try {
106 const row = parseStat(readFileSync(`/proc/${name}/stat`, "utf8"));
107 if (row) rows.set(Number(name), row);
108 } catch {
109 // Gone between the listing and the read.
110 }
111 }
112 return rows;
113 }
114
115 /**
116 * Samples `root`'s tree every `everyMs` until `stop()`, which takes a last
117 * sample and answers the peak. Off Linux there is no `/proc`: the peak is
118 * `undefined`.
119 */
120 export function watchCores(
121 root: number = process.pid,
122 everyMs = 1_000,
123 ): { stop(): number | undefined } {
124 const samples: Sample[] = [];
125 const take = (): void => {
126 const rows = processRows();
127 if (rows.size > 0)
128 samples.push({ at: performance.now(), ticks: treeTicks(rows, root) });
129 };
130 take();
131 const timer = setInterval(take, everyMs);
132 timer.unref();
133 return {
134 stop() {
135 clearInterval(timer);
136 take();
137 return peakCores(samples);
138 },
139 };
140 }
scripts/gate-summary.ts +25 −2
@@ -58,8 +58,14 @@ export function cgroupMemory(read: Reader): CgroupMemory {
5858 export type GateSummary = {
5959 /** Shards the gate ran at once. */
6060 shards: number;
61 /** `os.availableParallelism()`. */
61 /** CPUs the workers may keep busy (`cpuBudget` in scripts/shards.ts). */
6262 cpus: number;
63 /** `os.availableParallelism()`: the host's, inside a check cell. */
64 host?: number;
65 /** The cell's CPU limit (`FORGE_CELL_CPUS`), when the forge handed one. */
66 cell?: number;
67 /** The most cores a 30 s window saw, as the cell's guard counts them (scripts/cores.ts). */
68 peakCores?: number | undefined;
6369 /** Most shards whatever the host (`SHARDS_MAX` in scripts/shards.ts). */
6470 shardsMax: number;
6571 /** Files the gate named. */
@@ -79,6 +85,22 @@ export type GateSummary = {
7985
8086 const gib = (bytes: number): string => `${(bytes / GIB).toFixed(2)} GiB`;
8187
88 /** Where the CPU count came from, when the summary was told. */
89 function budget(s: GateSummary): string {
90 if (s.host === undefined) return "";
91 return s.cell === undefined
92 ? ` (host ${s.host}, less 1 for the runner)`
93 : ` (cell ${s.cell} of host ${s.host}, less 1 for the runner)`;
94 }
95
96 /** The peak beside the limit the guard holds the cell to. */
97 function cores(s: GateSummary): string {
98 const of = s.cell === undefined ? "" : ` of the cell's ${s.cell}`;
99 return s.peakCores === undefined
100 ? "not measured (no /proc, or under one 30 s window)"
101 : `${s.peakCores.toFixed(1)}${of} over a 30 s window`;
102 }
103
82104 /**
83105 * Why the gate ran `shards` at once: the bounds `shardCount` took the least
84106 * of, and, when memory held it under one per CPU, that it did.
@@ -91,7 +113,7 @@ function why(s: GateSummary): string {
91113 `at ${(s.workerBytes / 1024 ** 2).toFixed(0)} MiB each`;
92114 const bounds = set
93115 ? [`FORGE_CHECK_SHARDS ${s.override!.trim()}`, `${s.files} files`]
94 : [`${s.cpus} CPUs`, `${byMemory} by memory, ${room}`, `SHARDS_MAX ${s.shardsMax}`, `${s.files} files`];
116 : [`${s.cpus} CPUs${budget(s)}`, `${byMemory} by memory, ${room}`, `SHARDS_MAX ${s.shardsMax}`, `${s.files} files`];
95117 const held = !set && s.shards < s.cpus && s.shards === byMemory && byMemory < Math.min(s.shardsMax, s.files);
96118 return `${s.shards} = least of ${bounds.join("; ")}${held ? " — fewer than the CPUs because of memory" : ""}`;
97119 }
@@ -111,6 +133,7 @@ export function summaryLines(s: GateSummary): string[] {
111133 `test-shards: shards: ${why(s)}`,
112134 `test-shards: wall: ${s.wallSeconds.toFixed(1)}s`,
113135 `test-shards: peak memory: ${peak}`,
136 ...(s.host === undefined ? [] : [`test-shards: peak cores: ${cores(s)}`]),
114137 `test-shards: slowest ${top.length} of ${s.times.length} files${skipped > 0 ? ` (${skipped} of ${s.files} skipped after a red file)` : ""}:`,
115138 ...top.map((t) => ` ${t.seconds.toFixed(1).padStart(6)}s ${t.file}`),
116139 ...slowest
scripts/shards.ts +34 −1
@@ -24,6 +24,36 @@ export const SHARDS_MAX = 32;
2424 */
2525 export const WORKER_MEMORY_BYTES = 512 * 1024 * 1024;
2626
27 /**
28 * The CPUs the gate's workers may keep busy: the least of what the
29 * process sees (`availableParallelism()`) and the cell's limit
30 * (`FORGE_CELL_CPUS`, the check's `check.limits.cpus` as the forge
31 * resolved it), less one for the runner itself; at least one. A check
32 * cell has no CPU cgroup: the forge counts the cell's cores over 30 s and
33 * stops it past the limit (`apps/contain.ts`), so inside it
34 * `availableParallelism()` is the host's — 80 on the vxrail, which with
35 * `SHARDS_MAX` 32 ran a 16-CPU cell at 16.1 cores (#2243). `cell` absent
36 * or empty is no limit; anything but a whole number from 1 is refused.
37 */
38 export function cpuBudget(
39 host: number,
40 cell: string | undefined,
41 ):
42 | { ok: true; value: number; cell: number | undefined }
43 | { ok: false; error: string } {
44 let limit: number | undefined;
45 if (cell !== undefined && cell.trim() !== "") {
46 if (!/^[1-9][0-9]{0,3}$/.test(cell.trim()))
47 return {
48 ok: false,
49 error: `FORGE_CELL_CPUS must be a whole number from 1, not ${JSON.stringify(cell)}`,
50 };
51 limit = Number(cell.trim());
52 }
53 const cpus = Math.min(Math.floor(host), limit ?? Infinity);
54 return { ok: true, value: Math.max(1, cpus - 1), cell: limit };
55 }
56
2757 /**
2858 * How many shards: one per CPU the process may use, no more than its
2959 * memory holds at {@link WORKER_MEMORY_BYTES} each, capped at
@@ -31,13 +61,15 @@ export const WORKER_MEMORY_BYTES = 512 * 1024 * 1024;
3161 * not fewer: most of a forge test's time is spent waiting on git children
3262 * and timers, not computing. `memory` absent is not a bound.
3363 * `FORGE_CHECK_SHARDS` overrides it (still capped at the file count) so a
34 * small or busy host can turn it down.
64 * small or busy host can turn it down. `ceiling`, when given, bounds even
65 * the override: inside a cell, the {@link cpuBudget} its limit allows.
3566 */
3667 export function shardCount(
3768 cpus: number,
3869 files: number,
3970 override?: string,
4071 memory?: number,
72 ceiling?: number,
4173 ): { ok: true; value: number } | { ok: false; error: string } {
4274 let n = Math.min(SHARDS_MAX, Math.floor(cpus));
4375 if (memory !== undefined && Number.isFinite(memory) && memory > 0)
@@ -50,6 +82,7 @@ export function shardCount(
5082 };
5183 n = Number(override.trim());
5284 }
85 if (ceiling !== undefined) n = Math.min(n, ceiling);
5386 return { ok: true, value: Math.max(1, Math.min(n, files)) };
5487 }
5588
scripts/test-shards.ts +26 −2
@@ -52,6 +52,7 @@ import {
5252 parseTimes,
5353 SHARDS_MAX,
5454 WORKER_MEMORY_BYTES,
55 cpuBudget,
5556 shardCount,
5657 sliceFiles,
5758 splitArgs,
@@ -62,6 +63,7 @@ import {
6263 } from "./shards.ts";
6364 import { gateFiles, gateRefusal, presentTests } from "./gate.ts";
6465 import { cgroupMemory, summaryLines } from "./gate-summary.ts";
66 import { watchCores } from "./cores.ts";
6567 import { GATE_FILE, executedFiles, formatImpact, gateListAdds, handedImpact, mergeImpact, parseImpact } from "../src/checks/impact.ts";
6668 import { fastSet, importsOf, duration } from "../src/checks/tiers.ts";
6769 import { CHECK_CACHE } from "../src/checks/cache.ts";
@@ -339,13 +341,28 @@ const readLimit = (path: string): string | undefined => {
339341 return undefined;
340342 }
341343 };
342 const cpus = availableParallelism();
344 // The cell's limit, not the host's CPUs: inside a check cell
345 // `availableParallelism()` is the whole machine's, and the forge stops a
346 // cell that keeps more cores busy than it declared (#2243).
347 const host = availableParallelism();
348 const budget = cpuBudget(host, process.env["FORGE_CELL_CPUS"]);
349 if (!budget.ok) {
350 console.error(`test-shards: ${budget.error}`);
351 process.exit(2);
352 }
353 const cpus = budget.value;
343354 const shardsOverride = process.env["FORGE_CHECK_SHARDS"];
344355 const memory = memoryLimit(totalmem(), [
345356 readLimit("/sys/fs/cgroup/memory.max"),
346357 readLimit("/sys/fs/cgroup/memory/memory.limit_in_bytes"),
347358 ]);
348 const count = shardCount(cpus, files.length, shardsOverride, memory);
359 const count = shardCount(
360 cpus,
361 files.length,
362 shardsOverride,
363 memory,
364 budget.cell === undefined ? undefined : cpus,
365 );
349366 if (!count.ok) {
350367 console.error(`test-shards: ${count.error}`);
351368 process.exit(2);
@@ -526,6 +543,9 @@ async function pool(width: number): Promise<Timed[]> {
526543 return results.filter((result): result is Timed => result !== undefined);
527544 }
528545
546 // The timed full gate's summary says how many cores it kept busy, as the
547 // cell's guard counts them.
548 const coreWatch = timed ? watchCores() : undefined;
529549 const started = performance.now();
530550 // Serial one-file processes when SHARDS=1; record keeps its worker width;
531551 // multi-shard still runs every slice side by side.
@@ -539,6 +559,7 @@ if (results.length < slices.length) {
539559 );
540560 }
541561 const wall = (performance.now() - started) / 1000;
562 const peakCores = coreWatch?.stop();
542563 const ending = tally(results, wall);
543564 const spread = results.map((result) => result.seconds);
544565 console.log(`\n${ending.lines.join("\n")}`);
@@ -595,6 +616,9 @@ if (timed)
595616 `\n${summaryLines({
596617 shards: count.value,
597618 cpus,
619 host,
620 ...(budget.cell === undefined ? {} : { cell: budget.cell }),
621 peakCores,
598622 shardsMax: SHARDS_MAX,
599623 files: files.length,
600624 override: shardsOverride,
src/checks/service.ts +4
@@ -792,6 +792,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
792792 FORGE_CHECK: run.id,
793793 FORGE_COMMIT: x.commitOid,
794794 FORGE_CHECK_IMPACT: IMPACT_FILE,
795 // The cores the cell is held to: inside it the host's CPU count is
796 // visible, and a gate that sized itself by that one was stopped
797 // for going past this (#2243).
798 FORGE_CELL_CPUS: String(resolveLimits("step", manifest.limits).cpus),
795799 ...(base === undefined
796800 ? {}
797801 : {
test/check-tiers.test.ts +18
@@ -577,6 +577,24 @@ describe("the tiers in the forge's own checks service", () => {
577577 expect(verdict.learn).toContain("test/y.test.ts");
578578 });
579579
580 test("the check is told its cell's CPU limit, so it sizes itself by that and not the host (#2243)", async () => {
581 const pull = listPulls(app.db, repo.id, { state: "open", limit: 5 })[0]!;
582 const pushed = await commitToBranch(app, alice, repo, {
583 message: "Declares one CPU",
584 files: [
585 {
586 path: "forge.json",
587 content: JSON.stringify({
588 check: { run: 'echo "CELL=$FORGE_CELL_CPUS"', full: 'echo "CELL=$FORGE_CELL_CPUS"', limits: { cpus: 1 } },
589 }),
590 },
591 ],
592 });
593 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
594 const done = await checks.gate(repo, pull, pushed.value.commitOid);
595 expect(done.lines.join("\n")).toContain("CELL=1");
596 });
597
580598 const finished = async (pullId: string, oid: string): Promise<Run> => {
581599 const deadline = Date.now() + 30_000;
582600 let run: Run | undefined;
test/cores.test.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * The gate's core count (`scripts/cores.ts`), worked by hand against the
3 * arithmetic of the cell's guard (`apps/contain.ts`): ticks ÷ 100 ÷ seconds
4 * over a 30 s window.
5 */
6 import { describe, expect, test } from "bun:test";
7 import { CLK_TCK, WINDOW_MS, parseStat, peakCores, treeTicks, watchCores } from "../scripts/cores.ts";
8
9 describe("parseStat", () => {
10 test("parent and utime + stime + cutime + cstime, a name with spaces and parentheses", () => {
11 // pid (comm) state ppid pgrp session tty tpgid flags minflt cminflt majflt cmajflt utime stime cutime cstime …
12 const line = "4242 (bun (test) x) S 7 4242 4242 0 -1 4194560 100 0 0 0 250 50 1200 300 20 0 9 0\n";
13 expect(parseStat(line)).toEqual({ ppid: 7, ticks: 250 + 50 + 1200 + 300 });
14 });
15
16 test("anything malformed is undefined", () => {
17 expect(parseStat("")).toBeUndefined();
18 expect(parseStat("1 (x) S 0 1 1 0 -1 0 0 0 0 0 a b c d")).toBeUndefined();
19 expect(parseStat("1 (x) S 0")).toBeUndefined();
20 });
21 });
22
23 describe("treeTicks", () => {
24 test("the root and everything under it, nothing beside it", () => {
25 const rows = new Map([
26 [10, { ppid: 1, ticks: 5 }],
27 [11, { ppid: 10, ticks: 7 }],
28 [12, { ppid: 11, ticks: 11 }],
29 [20, { ppid: 1, ticks: 1000 }],
30 ]);
31 expect(treeTicks(rows, 10)).toBe(23);
32 expect(treeTicks(rows, 11)).toBe(18);
33 expect(treeTicks(rows, 99)).toBe(0);
34 });
35 });
36
37 describe("peakCores", () => {
38 test("by hand: 16.1 cores over 30 s is 48 300 ticks", () => {
39 expect(CLK_TCK).toBe(100);
40 expect(WINDOW_MS).toBe(30_000);
41 // 0 s → 30 s: 30 000 ticks = 300 CPU-s / 30 s = 10 cores.
42 // 30 s → 60 s: 48 300 ticks = 483 CPU-s / 30 s = 16.1 cores, the #2099 kill.
43 const samples = [
44 { at: 0, ticks: 0 },
45 { at: 30_000, ticks: 30_000 },
46 { at: 60_000, ticks: 78_300 },
47 ];
48 expect(peakCores(samples)).toBeCloseTo(16.1, 10);
49 });
50
51 test("each sample against the latest one a whole window before it, as the guard reads it", () => {
52 // Every second for 40 s: 2 cores for 20 s, then 8 cores.
53 const samples = [];
54 let ticks = 0;
55 for (let s = 0; s <= 40; s++) {
56 samples.push({ at: s * 1000, ticks });
57 ticks += (s < 20 ? 2 : 8) * CLK_TCK;
58 }
59 // Best window, 10 s → 40 s: 10 s at 2 + 20 s at 8 = 180 CPU-s / 30 s = 6.
60 expect(peakCores(samples)).toBeCloseTo(6, 10);
61 });
62
63 test("under one window: not measured", () => {
64 expect(peakCores([])).toBeUndefined();
65 expect(peakCores([{ at: 0, ticks: 0 }, { at: 29_999, ticks: 9_999_999 }])).toBeUndefined();
66 });
67
68 test("watchCores samples its own process; a short run is under a window", () => {
69 const watch = watchCores(process.pid, 10);
70 expect(watch.stop()).toBeUndefined();
71 });
72 });
test/gate-summary.test.ts +11
@@ -156,6 +156,17 @@ describe("summaryLines", () => {
156156 expect(lines[4]).toBe("test-shards: slowest 1 of 1 files (39 of 40 skipped after a red file):");
157157 });
158158
159 test("inside a cell: the CPUs are the cell's less the runner, and the peak cores sit beside its limit (#2243)", () => {
160 const lines = summaryLines({ ...base, shards: 12, cpus: 15, host: 80, cell: 16, peakCores: 9.26 });
161 expect(lines[1]).toBe(
162 "test-shards: shards: 12 = least of 15 CPUs (cell 16 of host 80, less 1 for the runner); 192 by memory, 96.00 GiB (no cgroup limit) at 512 MiB each; SHARDS_MAX 32; 12 files",
163 );
164 expect(lines[4]).toBe("test-shards: peak cores: 9.3 of the cell's 16 over a 30 s window");
165 expect(summaryLines({ ...base, host: 8, cpus: 7 })[4]).toBe(
166 "test-shards: peak cores: not measured (no /proc, or under one 30 s window)",
167 );
168 });
169
159170 test("FORGE_CHECK_SHARDS is named as the reason when it is set", () => {
160171 expect(summaryLines({ ...base, shards: 1, override: "1" })[1]).toBe(
161172 "test-shards: shards: 1 = least of FORGE_CHECK_SHARDS 1; 12 files",
test/shards.test.ts +72 −1
@@ -11,6 +11,7 @@ import {
1111 SECONDS_PER_BYTE_DEFAULT,
1212 SHARDS_MAX,
1313 WORKER_MEMORY_BYTES,
14 cpuBudget,
1415 formatTimes,
1516 heaviestFirst,
1617 memoryLimit,
@@ -254,6 +255,75 @@ describe("shardCount", () => {
254255 });
255256 });
256257
258 describe("the cell's CPUs, not the host's (#2243)", () => {
259 test("cpuBudget: the least of host and cell, less one for the runner, at least one", () => {
260 // The vxrail: 80 CPUs seen inside a 16-CPU check cell.
261 expect(cpuBudget(80, "16")).toEqual({ ok: true, value: 15, cell: 16 });
262 expect(cpuBudget(80, " 4\n")).toEqual({ ok: true, value: 3, cell: 4 });
263 // A cell bigger than the host is held to the host.
264 expect(cpuBudget(8, "16")).toEqual({ ok: true, value: 7, cell: 16 });
265 expect(cpuBudget(80, "1")).toEqual({ ok: true, value: 1, cell: 1 });
266 expect(cpuBudget(1, undefined)).toEqual({ ok: true, value: 1, cell: undefined });
267 expect(cpuBudget(80, "")).toEqual({ ok: true, value: 79, cell: undefined });
268 for (const bad of ["0", "-4", "four", "1.5", "1e3", "99999"])
269 expect(cpuBudget(80, bad).ok).toBe(false);
270 });
271
272 test("inside a cell, the budget bounds the shard count and even the override", () => {
273 const GiB = 1024 * 1024 * 1024;
274 // 15 = least of 15 CPUs, 16 by 8 GiB, SHARDS_MAX 32, 400 files.
275 expect(shardCount(15, 400, undefined, 8 * GiB, 15)).toEqual({ ok: true, value: 15 });
276 expect(shardCount(15, 400, "20", 8 * GiB, 15)).toEqual({ ok: true, value: 15 });
277 expect(shardCount(15, 400, "2", 8 * GiB, 15)).toEqual({ ok: true, value: 2 });
278 });
279
280 test("FORGE_CELL_CPUS=4 on a many-core host: never more than 4 workers at once", async () => {
281 const dir = mkdtempSync(join(tmpdir(), "shards-cell-"));
282 const names = Array.from({ length: 12 }, (_, i) => `w${i}.test.ts`);
283 for (const name of names)
284 writeFileSync(
285 join(dir, name),
286 `import { test } from "bun:test";
287 import { appendFileSync } from "node:fs";
288 test("holds a worker", async () => {
289 appendFileSync(${JSON.stringify(join(dir, "spans"))}, "+" + Date.now() + "\\n");
290 await Bun.sleep(400);
291 appendFileSync(${JSON.stringify(join(dir, "spans"))}, "-" + Date.now() + "\\n");
292 });
293 `,
294 );
295 const env: Record<string, string | undefined> = { ...process.env, FORGE_CELL_CPUS: "4" };
296 delete env["FORGE_CHECK_SHARDS"];
297 const script = new URL("../scripts/test-shards.ts", import.meta.url).pathname;
298 const child = Bun.spawn(["bun", script, ...names], {
299 cwd: dir,
300 env,
301 stdin: "ignore",
302 stdout: "pipe",
303 stderr: "pipe",
304 });
305 const out = await new Response(child.stdout).text();
306 const code = await child.exited;
307 const spans = readFileSync(join(dir, "spans"), "utf8");
308 rmSync(dir, { recursive: true, force: true });
309 expect(code).toBe(0);
310 // The most files running at one moment is the most workers at once.
311 const events = spans
312 .trim()
313 .split("\n")
314 .map((line) => ({ at: Number(line.slice(1)), delta: line[0] === "+" ? 1 : -1 }))
315 .sort((a, b) => a.at - b.at || a.delta - b.delta);
316 let now = 0;
317 let most = 0;
318 for (const event of events) most = Math.max(most, (now += event.delta));
319 expect(events.length).toBe(24);
320 expect(most).toBeGreaterThanOrEqual(1);
321 expect(most).toBeLessThanOrEqual(4);
322 // 4 CPUs, one kept for the runner: 3 shards, whatever the host has.
323 expect(out).toContain("test-shards: 12 files in 3 shards");
324 }, 60_000);
325 });
326
257327 const green = (files: string[], tests: number): ShardResult => ({
258328 files,
259329 code: 0,
@@ -563,7 +633,8 @@ describe("the gate audit alone, first in the check", () => {
563633 for (const command of [check.value.run, check.value.fast ?? ""]) {
564634 expect(command.startsWith("bun scripts/gate.ts && ")).toBe(true);
565635 // TypeScript 7 (#1864): a Go binary, so its heap bound is GOMEMLIMIT, not node's.
566 expect(command).toContain(" && GOMEMLIMIT=2GiB ./node_modules/typescript/bin/tsc --noEmit ");
636 // …and its threads by the cell's CPUs, so tsc alone stays under the cell's guard (#2243).
637 expect(command).toContain(" && GOMEMLIMIT=2GiB GOMAXPROCS=$FORGE_CELL_CPUS ./node_modules/typescript/bin/tsc --noEmit ");
567638 expect(command.indexOf("scripts/gate.ts")).toBeLessThan(command.indexOf("bin/tsc"));
568639 // tsc will not create its build-info directory (#1881): a checkout with no restored cache failed TS5033.
569640 expect(command).toContain(`mkdir -p ${CHECK_CACHE} && `);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs