@gadicc/loom 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/.loom-source-manifest.json +6 -1
  2. package/README.md +6 -4
  3. package/db/testing.d.ts +38 -1
  4. package/db/testing.js +66 -18
  5. package/db/testingTiming.js +45 -0
  6. package/esm/src/cli/mod.d.ts.map +1 -1
  7. package/esm/src/cli/mod.js +46 -0
  8. package/esm/src/cli/mod.js.map +1 -1
  9. package/esm/src/cli/testResourceCommand.d.ts +9 -0
  10. package/esm/src/cli/testResourceCommand.d.ts.map +1 -0
  11. package/esm/src/cli/testResourceCommand.js +33 -0
  12. package/esm/src/cli/testResourceCommand.js.map +1 -0
  13. package/esm/src/cli/testResourceHost.d.ts +36 -0
  14. package/esm/src/cli/testResourceHost.d.ts.map +1 -0
  15. package/esm/src/cli/testResourceHost.js +207 -0
  16. package/esm/src/cli/testResourceHost.js.map +1 -0
  17. package/esm/src/cli/testResourceLaunch.d.ts +22 -0
  18. package/esm/src/cli/testResourceLaunch.d.ts.map +1 -0
  19. package/esm/src/cli/testResourceLaunch.js +189 -0
  20. package/esm/src/cli/testResourceLaunch.js.map +1 -0
  21. package/esm/src/cli/testResourcePolicy.d.ts +24 -0
  22. package/esm/src/cli/testResourcePolicy.d.ts.map +1 -0
  23. package/esm/src/cli/testResourcePolicy.js +103 -0
  24. package/esm/src/cli/testResourcePolicy.js.map +1 -0
  25. package/esm/src/cli/testVitestRunner.d.ts +28 -0
  26. package/esm/src/cli/testVitestRunner.d.ts.map +1 -0
  27. package/esm/src/cli/testVitestRunner.js +159 -0
  28. package/esm/src/cli/testVitestRunner.js.map +1 -0
  29. package/package.json +2 -2
  30. package/skills/loom-db/SKILL.md +5 -2
  31. package/skills/loom-db/references/test-boundaries.md +76 -0
  32. package/source/src/cli/mod.ts +70 -0
  33. package/source/src/cli/testResourceCommand.ts +49 -0
  34. package/source/src/cli/testResourceHost.ts +299 -0
  35. package/source/src/cli/testResourceLaunch.ts +257 -0
  36. package/source/src/cli/testResourcePolicy.ts +135 -0
  37. package/source/src/cli/testVitestRunner.ts +222 -0
@@ -0,0 +1,299 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { freemem, totalmem } from "node:os";
3
+ import {
4
+ dirname,
5
+ isAbsolute,
6
+ join,
7
+ relative,
8
+ resolve,
9
+ sep,
10
+ } from "node:path/posix";
11
+ import process from "node:process";
12
+ import {
13
+ parseCpuList,
14
+ selectTestCpus,
15
+ testCpuQuota,
16
+ testMemoryHeadroom,
17
+ type TestCpuCore,
18
+ } from "./testResourcePolicy.ts";
19
+
20
+ /** Read-only resource diagnostics; unknown controller limits are never called unlimited. */
21
+ export interface TestResourceReport {
22
+ platform: string;
23
+ profile: "local" | "ci";
24
+ cpu: {
25
+ online: number[];
26
+ inherited: number[];
27
+ exclusion: ReturnType<typeof selectTestCpus> | null;
28
+ quota:
29
+ | { status: "known"; cpus: number }
30
+ | { status: "unlimited" | "unknown" };
31
+ diagnosticCeiling: number | null;
32
+ };
33
+ memory: {
34
+ capacityBytes: number | null;
35
+ availableBytes: number | null;
36
+ localFloorBytes: number;
37
+ };
38
+ warnings: string[];
39
+ }
40
+
41
+ /** Reader injection permits controller/topology tests without inspecting the test host. */
42
+ export type TestResourceRead = (path: string) => Promise<string | undefined>;
43
+
44
+ async function read(path: string) {
45
+ try {
46
+ return await readFile(path, "utf8");
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ /** Locate every visible cgroup-v2 ancestor, respecting mount roots and escaped paths. */
53
+ export function testCgroupAncestors(
54
+ mountinfo: string | undefined,
55
+ membership: string | undefined,
56
+ ): string[] {
57
+ const current = membership
58
+ ?.split("\n")
59
+ .find((line) => line.startsWith("0::"))
60
+ ?.slice(3);
61
+ if (!current || !isAbsolute(current)) return [];
62
+ const decode = (text: string) =>
63
+ text.replace(/\\(040|011|012|134)/g, (_, code: string) =>
64
+ String.fromCharCode(parseInt(code, 8)),
65
+ );
66
+ for (const line of mountinfo?.split("\n") ?? []) {
67
+ const [left, right] = line.split(" - ");
68
+ if (right?.split(" ")[0] !== "cgroup2") continue;
69
+ const fields = left.split(" ");
70
+ if (fields.length < 5) continue;
71
+ const root = decode(fields[3]);
72
+ const mount = decode(fields[4]);
73
+ if (!isAbsolute(root) || !isAbsolute(mount)) continue;
74
+ const suffix = relative(root, current);
75
+ if (suffix === ".." || suffix.startsWith(`..${sep}`) || isAbsolute(suffix))
76
+ continue;
77
+ const paths = [];
78
+ let path = resolve(mount, suffix);
79
+ for (;;) {
80
+ paths.push(path);
81
+ if (path === resolve(mount)) return paths;
82
+ const parent = dirname(path);
83
+ if (parent === path) break;
84
+ path = parent;
85
+ }
86
+ }
87
+ return [];
88
+ }
89
+
90
+ function limit(text: string | undefined): number | undefined {
91
+ if (text?.trim() === "max") return Infinity;
92
+ if (!text || !/^\d+$/.test(text.trim())) return undefined;
93
+ const value = Number(text.trim());
94
+ return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
95
+ }
96
+
97
+ /** Inspect the current execution boundary without running app config or persisting policy. */
98
+ export async function inspectTestResources(
99
+ options: {
100
+ profile?: "local" | "ci";
101
+ platform?: string;
102
+ env?: Readonly<Record<string, string | undefined>>;
103
+ read?: TestResourceRead;
104
+ } = {},
105
+ ): Promise<TestResourceReport> {
106
+ const platform = options.platform ?? process.platform;
107
+ const env = options.env ?? process.env;
108
+ const ci = [
109
+ env.CI,
110
+ env.GITHUB_ACTIONS,
111
+ env.GITLAB_CI,
112
+ env.BUILDKITE,
113
+ env.TF_BUILD,
114
+ ].some((value) =>
115
+ Boolean(value?.trim() && !/^(0|false)$/i.test(value.trim())),
116
+ );
117
+ const profile = options.profile ?? (ci ? "ci" : "local");
118
+ const load = options.read ?? read;
119
+ const report: TestResourceReport = {
120
+ platform,
121
+ profile,
122
+ cpu: {
123
+ online: [],
124
+ inherited: [],
125
+ exclusion: null,
126
+ quota: { status: "unknown" },
127
+ diagnosticCeiling: null,
128
+ },
129
+ memory: { capacityBytes: null, availableBytes: null, localFloorBytes: 0 },
130
+ warnings: [
131
+ "Read-only diagnostics: no worker default, active-run coordination, or persistent CPU policy is installed.",
132
+ ],
133
+ };
134
+ if (platform !== "linux") {
135
+ report.memory.capacityBytes = totalmem();
136
+ report.memory.availableBytes = freemem();
137
+ if (profile === "local")
138
+ report.memory.localFloorBytes = testMemoryHeadroom(totalmem());
139
+ report.warnings.push(
140
+ "Common CPU exclusion and container limits are unverified on this platform.",
141
+ );
142
+ return report;
143
+ }
144
+ const [onlineText, status, mountinfo, membership, meminfo, osrelease] =
145
+ await Promise.all([
146
+ load("/sys/devices/system/cpu/online"),
147
+ load("/proc/self/status"),
148
+ load("/proc/self/mountinfo"),
149
+ load("/proc/self/cgroup"),
150
+ load("/proc/meminfo"),
151
+ load("/proc/sys/kernel/osrelease"),
152
+ ]);
153
+ try {
154
+ report.cpu.online = parseCpuList(onlineText ?? "");
155
+ report.cpu.inherited = parseCpuList(
156
+ /^Cpus_allowed_list:\s*(.+)$/m.exec(status ?? "")?.[1] ?? "",
157
+ );
158
+ const groups = new Map<string, TestCpuCore>();
159
+ let complete = true;
160
+ for (const cpu of report.cpu.online) {
161
+ const base = `/sys/devices/system/cpu/cpu${cpu}/topology`;
162
+ const [socketText, coreText, siblingText] = await Promise.all([
163
+ load(`${base}/physical_package_id`),
164
+ load(`${base}/core_id`),
165
+ load(`${base}/thread_siblings_list`),
166
+ ]);
167
+ if (
168
+ !/^\d+\s*$/.test(socketText ?? "") ||
169
+ !/^\d+\s*$/.test(coreText ?? "") ||
170
+ !siblingText
171
+ ) {
172
+ complete = false;
173
+ break;
174
+ }
175
+ const socket = Number(socketText),
176
+ core = Number(coreText);
177
+ const siblings = parseCpuList(siblingText).filter((id) =>
178
+ report.cpu.online.includes(id),
179
+ );
180
+ if (!siblings.includes(cpu)) {
181
+ complete = false;
182
+ break;
183
+ }
184
+ const key = `${socket}:${core}`;
185
+ const previous = groups.get(key);
186
+ if (previous && previous.cpus.join(",") !== siblings.join(",")) {
187
+ complete = false;
188
+ break;
189
+ }
190
+ groups.set(key, { socket, core, cpus: siblings });
191
+ }
192
+ if (profile === "local")
193
+ report.cpu.exclusion = selectTestCpus(
194
+ report.cpu.online,
195
+ report.cpu.inherited,
196
+ complete ? [...groups.values()] : undefined,
197
+ );
198
+ if (!complete)
199
+ report.warnings.push(
200
+ "Physical topology unavailable; exclusion describes logical CPUs only.",
201
+ );
202
+ report.warnings.push(
203
+ "Selection uses stable socket/core order; no supported static performance-core mapping is configured.",
204
+ );
205
+ } catch (error) {
206
+ report.warnings.push(
207
+ error instanceof Error ? error.message : "CPU topology unavailable",
208
+ );
209
+ }
210
+ const ancestors = testCgroupAncestors(mountinfo, membership);
211
+ report.warnings.push(
212
+ "Controller calculations cover visible cgroup ancestors; hidden host limits cannot be diagnosed from a container.",
213
+ );
214
+ const hierarchyRoot = mountinfo?.split("\n").some((line) => {
215
+ const [left, right] = line.split(" - ");
216
+ const fields = left.split(" ");
217
+ return (
218
+ right?.startsWith("cgroup2 ") &&
219
+ fields[3] === "/" &&
220
+ fields[4] === ancestors.at(-1)
221
+ );
222
+ });
223
+ const limits = await Promise.all(
224
+ ancestors.map(async (path, index) => {
225
+ const values = await Promise.all(
226
+ ["cpu.max", "memory.max", "memory.high", "memory.current"].map((name) =>
227
+ load(join(path, name)),
228
+ ),
229
+ );
230
+ // The hierarchy root has no resource control files: it is unlimited.
231
+ const root = hierarchyRoot && index === ancestors.length - 1;
232
+ return {
233
+ cpu: values[0] ?? (root ? "max 100000" : undefined),
234
+ max: limit(values[1]) ?? (root ? Infinity : undefined),
235
+ high: limit(values[2]) ?? (root ? Infinity : undefined),
236
+ current: limit(values[3]) ?? (root ? 0 : undefined),
237
+ };
238
+ }),
239
+ );
240
+ const quota = testCpuQuota(limits.map((item) => item.cpu));
241
+ report.cpu.quota =
242
+ quota === undefined
243
+ ? { status: "unknown" }
244
+ : quota === Infinity
245
+ ? { status: "unlimited" }
246
+ : { status: "known", cpus: quota };
247
+ if (quota === undefined)
248
+ report.warnings.push(
249
+ "CPU quota is unknown; the diagnostic ceiling is unavailable.",
250
+ );
251
+ else if (report.cpu.inherited.length)
252
+ report.cpu.diagnosticCeiling = Math.max(
253
+ 1,
254
+ Math.min(report.cpu.inherited.length, Math.ceil(quota)),
255
+ );
256
+ const memory = (key: string) => {
257
+ const value = new RegExp(`^${key}:\\s+(\\d+) kB$`, "m").exec(
258
+ meminfo ?? "",
259
+ )?.[1];
260
+ return value ? Number(value) * 1024 : undefined;
261
+ };
262
+ let capacity = memory("MemTotal");
263
+ let available = memory("MemAvailable");
264
+ let memoryKnown = ancestors.length > 0;
265
+ for (const item of limits) {
266
+ if (
267
+ item.max === undefined ||
268
+ item.high === undefined ||
269
+ item.current === undefined
270
+ )
271
+ memoryKnown = false;
272
+ if (capacity !== undefined && item.max !== undefined)
273
+ capacity = Math.min(capacity, item.max);
274
+ for (const boundary of [item.max, item.high]) {
275
+ if (
276
+ available !== undefined &&
277
+ boundary !== undefined &&
278
+ item.current !== undefined
279
+ )
280
+ available = Math.max(0, Math.min(available, boundary - item.current));
281
+ }
282
+ }
283
+ report.memory.capacityBytes = memoryKnown ? (capacity ?? null) : null;
284
+ report.memory.availableBytes = memoryKnown ? (available ?? null) : null;
285
+ if (!memoryKnown)
286
+ report.warnings.push(
287
+ "Memory controller data is incomplete; effective available memory is unknown.",
288
+ );
289
+ if (memoryKnown && capacity && profile === "local")
290
+ report.memory.localFloorBytes = testMemoryHeadroom(capacity);
291
+ if (/microsoft|wsl/i.test(osrelease ?? ""))
292
+ report.warnings.push(
293
+ "WSL guest CPUs do not reserve physical host headroom.",
294
+ );
295
+ report.warnings.push(
296
+ "Virtualization is otherwise undetermined; guest affinity cannot guarantee physical host headroom.",
297
+ );
298
+ return report;
299
+ }
@@ -0,0 +1,257 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { access } from "node:fs/promises";
4
+ import { availableParallelism } from "node:os";
5
+ import { delimiter, join } from "node:path";
6
+ import process from "node:process";
7
+ import { fileURLToPath } from "node:url";
8
+ import {
9
+ inspectTestResources,
10
+ type TestResourceReport,
11
+ } from "./testResourceHost.ts";
12
+ import { managedVitestModuleURL } from "./testVitestRunner.ts";
13
+
14
+ /** Explicit opt-in launch plan; no machine default or shared admission is implied. */
15
+ export interface ManagedTestPlan {
16
+ workers: number;
17
+ cpus: number[] | null;
18
+ epoch: string | null;
19
+ warnings: string[];
20
+ }
21
+
22
+ /** Combine explicit demand with visible capacity while preserving app caps in-runner. */
23
+ export function planManagedTest(
24
+ report: TestResourceReport,
25
+ workers: string | undefined,
26
+ cpuMode = "inherit",
27
+ ): ManagedTestPlan {
28
+ if (
29
+ (report.profile === "local" && !workers) ||
30
+ (workers !== undefined &&
31
+ workers !== "auto" &&
32
+ (!/^\d+$/.test(workers) ||
33
+ !Number.isSafeInteger(Number(workers)) ||
34
+ Number(workers) < 1))
35
+ ) {
36
+ throw new Error(
37
+ "Select an explicit positive --workers count, or auto; no tuned default has been chosen",
38
+ );
39
+ }
40
+ if (cpuMode !== "inherit" && cpuMode !== "exclude")
41
+ throw new Error("CPU mode must be inherit or exclude");
42
+ if (
43
+ report.profile === "local" &&
44
+ cpuMode === "exclude" &&
45
+ (!report.cpu.exclusion || report.cpu.exclusion.topology !== "physical")
46
+ ) {
47
+ throw new Error(
48
+ "Physical CPU exclusion is unavailable; select explicit inherit mode for a worker cap only",
49
+ );
50
+ }
51
+ if (report.platform === "linux" && !report.cpu.inherited.length)
52
+ throw new Error("Inherited Linux CPU restrictions are unknown");
53
+ const selection =
54
+ report.profile === "local" && cpuMode === "exclude"
55
+ ? report.cpu.exclusion
56
+ : null;
57
+ const cpus = selection?.testCpus ?? null;
58
+ const capacity =
59
+ cpus?.length ?? (report.cpu.inherited.length || availableParallelism());
60
+ const warnings = [
61
+ ...report.warnings,
62
+ "Per-worker memory demand is uncalibrated. This cap is not memory isolation or aggregate admission.",
63
+ ];
64
+ let ceiling =
65
+ report.profile === "ci" || workers === "auto"
66
+ ? capacity
67
+ : Math.min(Number(workers), capacity);
68
+ if (
69
+ report.profile === "ci" &&
70
+ (workers !== undefined || cpuMode === "exclude")
71
+ )
72
+ warnings.push(
73
+ "CI ignores local --workers and CPU exclusion; deliberate app and Vitest CLI caps still apply.",
74
+ );
75
+ if (report.cpu.quota.status === "known")
76
+ ceiling = Math.min(ceiling, Math.ceil(report.cpu.quota.cpus));
77
+ else if (
78
+ report.cpu.quota.status === "unknown" &&
79
+ report.profile === "local"
80
+ ) {
81
+ ceiling = Math.min(ceiling, 1);
82
+ warnings.push(
83
+ "Unknown local quota: the explicit pilot is limited to one worker.",
84
+ );
85
+ }
86
+ if (
87
+ report.profile === "local" &&
88
+ (report.memory.availableBytes === null ||
89
+ report.memory.availableBytes <= report.memory.localFloorBytes)
90
+ ) {
91
+ throw new Error(
92
+ "Local memory headroom is unavailable or below the desktop floor (exit 121)",
93
+ );
94
+ }
95
+ return { workers: ceiling, cpus, epoch: selection?.epoch ?? null, warnings };
96
+ }
97
+
98
+ async function executable(name: string): Promise<string> {
99
+ for (const directory of (process.env.PATH ?? "").split(delimiter)) {
100
+ if (!directory) continue;
101
+ const path = join(
102
+ directory,
103
+ process.platform === "win32" ? `${name}.exe` : name,
104
+ );
105
+ try {
106
+ await access(path, constants.X_OK);
107
+ return path;
108
+ } catch {
109
+ /* Try the next PATH directory. */
110
+ }
111
+ }
112
+ throw new Error(`Required executable ${name} is unavailable`);
113
+ }
114
+
115
+ function launch(
116
+ command: string,
117
+ args: string[],
118
+ cwd: string,
119
+ ): Promise<{ code: number; signal?: NodeJS.Signals }> {
120
+ return new Promise((done) => {
121
+ const foreground =
122
+ process.platform !== "win32" &&
123
+ Boolean(
124
+ process.stdin.isTTY || process.stdout.isTTY || process.stderr.isTTY,
125
+ );
126
+ const grouped = process.platform !== "win32" && !foreground;
127
+ const child = spawn(command, args, {
128
+ cwd,
129
+ env: process.env,
130
+ stdio: "inherit",
131
+ detached: grouped,
132
+ });
133
+ // A terminal already delivers INT/TSTP/CONT to the whole foreground job.
134
+ const signals: NodeJS.Signals[] = foreground
135
+ ? ["SIGTERM", "SIGHUP"]
136
+ : ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
137
+ let receivedSignal: NodeJS.Signals | undefined;
138
+ const handlers = signals.map((signal) => {
139
+ const handler = () => {
140
+ receivedSignal ??= signal;
141
+ if (grouped && child.pid) {
142
+ try {
143
+ process.kill(-child.pid, signal);
144
+ return;
145
+ } catch {
146
+ /* Child may already have exited. */
147
+ }
148
+ }
149
+ child.kill(signal);
150
+ };
151
+ process.on(signal, handler);
152
+ return { signal, handler };
153
+ });
154
+ let settled = false;
155
+ const finish = (value: { code: number; signal?: NodeJS.Signals }) => {
156
+ if (settled) return;
157
+ settled = true;
158
+ for (const item of handlers) process.off(item.signal, item.handler);
159
+ done(value);
160
+ };
161
+ child.once("error", (error) => {
162
+ console.error(`Loom test launcher: ${error.message}`);
163
+ finish({ code: 120 });
164
+ });
165
+ child.once("close", (code, signal) =>
166
+ finish({
167
+ code: code ?? 1,
168
+ ...((receivedSignal ?? signal)
169
+ ? { signal: receivedSignal ?? signal ?? undefined }
170
+ : {}),
171
+ }),
172
+ );
173
+ });
174
+ }
175
+
176
+ /** Run only the verified finite Vitest adapter; all resource diagnostics use stderr. */
177
+ export async function runManagedTestCommand(
178
+ cwd: string,
179
+ args: string[],
180
+ options: {
181
+ workers?: string;
182
+ cpuMode?: string;
183
+ profile?: string;
184
+ quiet?: boolean;
185
+ dryRun?: boolean;
186
+ },
187
+ io: { out: (line: string) => void; err: (line: string) => void },
188
+ ): Promise<number> {
189
+ if (args[0] !== "vitest" || args[1] !== "run") {
190
+ io.err(
191
+ "Usage: loom test run --workers <count|auto> [--cpu-mode inherit|exclude] [--test-profile local|ci] [--dry-run] -- vitest run [args]",
192
+ );
193
+ return 1;
194
+ }
195
+ if (
196
+ options.profile !== undefined &&
197
+ options.profile !== "local" &&
198
+ options.profile !== "ci"
199
+ ) {
200
+ io.err("Test profile must be local or ci.");
201
+ return 120;
202
+ }
203
+ let plan: ManagedTestPlan;
204
+ let report: TestResourceReport;
205
+ let node: string;
206
+ let taskset: string | undefined;
207
+ try {
208
+ report = await inspectTestResources({ profile: options.profile });
209
+ plan = planManagedTest(report, options.workers, options.cpuMode);
210
+ node = await executable("node");
211
+ if (plan.cpus) taskset = await executable("taskset");
212
+ } catch (error) {
213
+ const message = error instanceof Error ? error.message : String(error);
214
+ io.err(`Loom test launcher: ${message}`);
215
+ return message.includes("exit 121") ? 121 : 120;
216
+ }
217
+ if (!options.quiet) {
218
+ io.err(
219
+ `Loom tests: ${report.profile}, explicit ceiling ${plan.workers}, ${plan.cpus ? `CPU exclusion ${plan.epoch}` : "inherited CPUs"}.`,
220
+ );
221
+ for (const warning of plan.warnings) io.err(`Note: ${warning}`);
222
+ }
223
+ if (options.dryRun) {
224
+ io.out(
225
+ JSON.stringify({
226
+ phase: "launcher",
227
+ profile: report.profile,
228
+ ...plan,
229
+ config:
230
+ "not loaded; actual lower app ceiling is resolved once in the runner",
231
+ }),
232
+ );
233
+ return 0;
234
+ }
235
+ const bootstrap = `import { runManagedVitest } from ${JSON.stringify(managedVitestModuleURL)};
236
+ if (Number(process.versions.node.split('.')[0]) < 22 || (process.versions.node.startsWith('22.') && Number(process.versions.node.split('.')[1]) < 13)) { console.error('Loom test preflight: Node >=22.13 is required'); process.exitCode=120; }
237
+ else process.exitCode = await runManagedVitest(process.cwd(), process.argv.slice(1), ${plan.workers}, ${options.quiet ? "undefined" : "(workers,pool) => console.error('Loom resolved Vitest: '+workers+' workers, '+pool+' pool.')"});`;
238
+ const nodeArgs = [
239
+ ...(fileURLToPath(managedVitestModuleURL).endsWith(".ts")
240
+ ? ["--experimental-strip-types"]
241
+ : []),
242
+ "--input-type=module",
243
+ "-e",
244
+ bootstrap,
245
+ "--",
246
+ ...args.slice(1),
247
+ ];
248
+ const result = await launch(
249
+ taskset ?? node,
250
+ taskset && plan.cpus
251
+ ? ["-c", plan.cpus.join(","), node, ...nodeArgs]
252
+ : nodeArgs,
253
+ cwd,
254
+ );
255
+ if (result.signal) process.kill(process.pid, result.signal);
256
+ return result.code;
257
+ }
@@ -0,0 +1,135 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ /** Static online physical-core identity; inherited affinity is deliberately absent. */
4
+ export interface TestCpuCore {
5
+ socket: number;
6
+ core: number;
7
+ cpus: readonly number[];
8
+ }
9
+
10
+ /** Experimental v1 selection, computed in memory without creating host state. */
11
+ export interface TestCpuSelection {
12
+ spec: "loom-cpu-selection-v1";
13
+ epoch: string;
14
+ reservedCpus: number[];
15
+ testCpus: number[];
16
+ reservedCores: number;
17
+ topology: "physical" | "logical-fallback";
18
+ }
19
+
20
+ /** Parses Linux CPU lists strictly and returns normalized ascending indices. */
21
+ export function parseCpuList(text: string): number[] {
22
+ const result = new Set<number>();
23
+ for (const part of text.trim().split(",")) {
24
+ const match = /^(\d+)(?:-(\d+))?$/.exec(part);
25
+ if (!match) throw new Error("Invalid CPU list");
26
+ const start = Number(match[1]);
27
+ const end = Number(match[2] ?? match[1]);
28
+ if (end < start || end > 1_000_000) throw new Error("Invalid CPU range");
29
+ for (let cpu = start; cpu <= end; cpu++) result.add(cpu);
30
+ }
31
+ return [...result].sort((a, b) => a - b);
32
+ }
33
+
34
+ /** Stable selection shared by projects; private masks never choose substitute cores. */
35
+ export function selectTestCpus(
36
+ online: readonly number[],
37
+ inherited: readonly number[],
38
+ physical: readonly TestCpuCore[] | undefined,
39
+ reserve?: number,
40
+ ): TestCpuSelection {
41
+ const normalized = parseCpuList(online.join(","));
42
+ const onlineSet = new Set(normalized);
43
+ const cores = physical
44
+ ? physical.map((item) => ({
45
+ socket: item.socket,
46
+ core: item.core,
47
+ cpus: [...item.cpus].sort((a, b) => a - b),
48
+ }))
49
+ : normalized.map((cpu) => ({ socket: 0, core: cpu, cpus: [cpu] }));
50
+ cores.sort(
51
+ (a, b) => a.socket - b.socket || a.core - b.core || a.cpus[0] - b.cpus[0],
52
+ );
53
+ const covered = cores.flatMap((item) => item.cpus);
54
+ if (
55
+ cores.some(
56
+ (item) =>
57
+ !Number.isInteger(item.socket) ||
58
+ !Number.isInteger(item.core) ||
59
+ item.cpus.length === 0,
60
+ ) ||
61
+ covered.length !== normalized.length ||
62
+ new Set(covered).size !== covered.length ||
63
+ covered.some((cpu) => !onlineSet.has(cpu))
64
+ ) {
65
+ throw new Error("Physical topology must partition the online CPU set");
66
+ }
67
+ const count = reserve ?? (cores.length <= 2 ? 0 : cores.length < 8 ? 1 : 2);
68
+ if (!Number.isSafeInteger(count) || count < 0 || count >= cores.length) {
69
+ throw new Error("Reservation must leave at least one online core");
70
+ }
71
+ const reservedCpus = cores
72
+ .slice(0, count)
73
+ .flatMap((item) => item.cpus)
74
+ .sort((a, b) => a - b);
75
+ const reserved = new Set(reservedCpus);
76
+ const testCpus = [...new Set(inherited)]
77
+ .filter((cpu) => onlineSet.has(cpu) && !reserved.has(cpu))
78
+ .sort((a, b) => a - b);
79
+ if (testCpus.length === 0) {
80
+ throw new Error(
81
+ "Inherited CPU restrictions leave no test CPUs after exclusion",
82
+ );
83
+ }
84
+ const spec = "loom-cpu-selection-v1";
85
+ // No inherited mask, dynamic frequency, memory, or worker choice in the epoch.
86
+ const epoch = createHash("sha256")
87
+ .update(
88
+ JSON.stringify({
89
+ spec,
90
+ online: normalized,
91
+ cores,
92
+ reserve: reserve ?? null,
93
+ }),
94
+ )
95
+ .digest("hex");
96
+ return {
97
+ spec,
98
+ epoch,
99
+ reservedCpus,
100
+ testCpus,
101
+ reservedCores: count,
102
+ topology: physical ? "physical" : "logical-fallback",
103
+ };
104
+ }
105
+
106
+ /** A cgroup quota ceiling, or undefined when any applicable limit is unknown. */
107
+ export function testCpuQuota(
108
+ texts: readonly (string | undefined)[],
109
+ ): number | undefined {
110
+ let capacity = Infinity;
111
+ for (const text of texts) {
112
+ if (text === undefined) return undefined;
113
+ const fields = text.trim().split(/\s+/);
114
+ if (fields.length !== 2 || !/^\d+$/.test(fields[1])) return undefined;
115
+ const period = Number(fields[1]);
116
+ if (!Number.isSafeInteger(period) || period <= 0) return undefined;
117
+ if (fields[0] === "max") continue;
118
+ if (!/^\d+$/.test(fields[0])) return undefined;
119
+ const quota = Number(fields[0]);
120
+ if (!Number.isSafeInteger(quota) || quota <= 0) return undefined;
121
+ capacity = Math.min(capacity, quota / period);
122
+ }
123
+ return texts.length ? capacity : undefined;
124
+ }
125
+
126
+ /** Local desktop reserve; CI does not use this floor. */
127
+ export function testMemoryHeadroom(capacityBytes: number): number {
128
+ if (!Number.isFinite(capacityBytes) || capacityBytes <= 0) {
129
+ throw new Error("Memory capacity must be positive and finite");
130
+ }
131
+ return Math.min(
132
+ 2 * 1024 ** 3,
133
+ Math.max(256 * 1024 ** 2, capacityBytes * 0.1),
134
+ );
135
+ }