fix(verify): bound concurrent file reads in architecture and limit guards (#14720)

* fix(verify): bound concurrent file reads in architecture and limit guards

`scripts/verify/architecture-guards.mjs` reads every `.ts`, `.mts`, `.mjs`,
and `.py` file under `src/`, `tests/`, `scripts/`, and `bridge/` (8,203 files
on current `main`) via unbounded `Promise.all(paths.map(readFile))`. On
Windows, queuing all `open()` calls at once exceeds the UCRT 8,192 file
descriptor ceiling and deterministically fails `npm run verify:architecture-guards`,
`npm run check:fast`, and the pre-push hook with `EMFILE: too many open files`.

Add a zero-dependency JSDoc-typed `mapWithConcurrency` helper in
`scripts/verify/bounded-file-reads.mjs` (default cap 64, registered in
`tsconfig.scripts.json` so it runs before `npm ci`), apply it across all four
bulk `readFile` loops in `scripts/verify/architecture-guards.mjs` and the
sibling `src/` scan in `scripts/verify/rea-numeric-limits.mjs`, and add unit
coverage in `tests/evaluation/boundedFileReads.test.ts`.

* test(verify): copy bounded-file-reads helper in numericLimitGuardPermission fixture

`scripts/verify/rea-numeric-limits.mjs` now imports
`./bounded-file-reads.mjs`. Copy both scripts into the temporary checkout
in `tests/boundary/process/numericLimitGuardPermission.test.ts` so the
copied verifier starts cleanly on non-root Linux/macOS runs instead of
failing with `ERR_MODULE_NOT_FOUND`.
This commit is contained in:
RRFZ authored and GitHub committed 2026-11-26 23:25:32 +08:00
1 parent 5a283a5f87
commit d5b4c4bb61
6 files changed
+211 -30

No files matched your search

+23 -24
View File
@@ -2,6 +2,7 @@ import { readFile, readdir, rm, writeFile } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { recordPredicateCounts } from "./record-predicate-guard.mjs";
import { mapWithConcurrency } from "./bounded-file-reads.mjs";
import {
compareCountedBaseline,
recordLoweredBaseline,
@@ -59,16 +60,14 @@ const listFiles = async (dir) => {
};
const sources = await listFiles(join(root, "src"));
const files = await Promise.all(
sources.map(async (path) => {
const source = await readFile(path, "utf8");
return {
path: relative(root, path).split(sep).join("/"),
content: blankComments(source),
source,
};
}),
);
const files = await mapWithConcurrency(sources, async (path) => {
const source = await readFile(path, "utf8");
return {
path: relative(root, path).split(sep).join("/"),
content: blankComments(source),
source,
};
});
const failures = [];
const check = (label, selected, pattern, allow = []) => {
const offenders = selected.filter(
@@ -937,15 +936,16 @@ const listTestFiles = async (dir) => {
}
return output;
};
const testFiles = await Promise.all(
const testFiles = await mapWithConcurrency(
[
...(await listTestFiles(join(root, "src"))),
...(await listFiles(join(root, "tests"))),
...(await listTestFiles(join(root, "tests"))),
].map(async (path) => ({
],
async (path) => ({
path: relative(root, path).split(sep).join("/"),
content: await readFile(path, "utf8"),
})),
}),
);
checkCounted(
"test redefines process.platform or process.arch (inject the platform: pass it as a parameter or host option, or mock src/platform/HostPlatform)",
@@ -997,20 +997,18 @@ checkCounted(
// processes that may still use it confirm cleanup; otherwise it is retained
// and named. scripts/lib/verifier-fixture.mjs owns that ordering on a
// src/process PrivateRuntimeRoot, so verifiers allocate roots through it.
const verifierScripts = await Promise.all(
const verifierScripts = await mapWithConcurrency(
(await readdir(join(root, "scripts"), { recursive: true }))
.map((path) => path.split(sep).join("/"))
.filter(
(path) =>
/^(?:verify-[^/]+|verify\/.+)\.mjs$/u.test(path) &&
path !== "verify/architecture-guards.mjs",
)
.map(async (path) => ({
path: `scripts/${path}`,
content: blankComments(
await readFile(join(root, "scripts", path), "utf8"),
),
})),
),
async (path) => ({
path: `scripts/${path}`,
content: blankComments(await readFile(join(root, "scripts", path), "utf8")),
}),
);
// The Windows native lane tests PrivateRuntimeRoot itself: it calls
// PrivateRuntimeRoot.create under a parent whose DELETE lease forces a sharing
@@ -1116,7 +1114,7 @@ const vocabularyGuardPath =
"scripts/verify/retired-target-failure-vocabulary.mjs";
const vocabularyGuardTestPath =
"tests/evaluation/retiredTargetFailureVocabulary.test.ts";
const vocabularyFiles = await Promise.all(
const vocabularyFiles = await mapWithConcurrency(
[
...(await listVocabularyFiles(join(root, "src"), [".ts", ".mts", ".py"])),
...(await listVocabularyFiles(join(root, "tests"), [".ts", ".mjs", ".py"])),
@@ -1126,10 +1124,11 @@ const vocabularyFiles = await Promise.all(
".py",
])),
...(await listVocabularyFiles(join(root, "bridge"), [".py"])),
].map(async (path) => ({
],
async (path) => ({
path: relative(root, path).split(sep).join("/"),
content: await readFile(path, "utf8"),
})),
}),
);
const retiredVocabulary = vocabularyFiles.filter(
({ path, content }) =>
+50
View File
@@ -0,0 +1,50 @@
/**
* Default upper bound on concurrent file reads for repository-wide verification
* scans so large checkouts stay well below Windows UCRT (8192) and macOS/Linux
* per-process file descriptor limits without serializing disk I/O.
*/
export const DEFAULT_FILE_READ_CONCURRENCY = 64;
/**
* Map `items` asynchronously while keeping at most `concurrency` callbacks in
* flight, preserving input order and failing fast on the first rejection.
*
* @template T, U
* @param {readonly T[]} items
* @param {(item: T, index: number) => Promise<U>} mapper
* @param {number} [concurrency]
* @returns {Promise<U[]>}
*/
export const mapWithConcurrency = async (
items,
mapper,
concurrency = DEFAULT_FILE_READ_CONCURRENCY,
) => {
if (!Number.isInteger(concurrency) || concurrency < 1) {
throw new RangeError(
`Expected a positive integer concurrency limit, received ${String(concurrency)}.`,
);
}
if (items.length === 0) return [];
/** @type {U[]} */
const results = Array.from({ length: items.length });
let nextIndex = 0;
let failed = false;
const workerCount = Math.min(concurrency, items.length);
await Promise.all(
Array.from({ length: workerCount }, async () => {
while (!failed) {
const index = nextIndex;
if (index >= items.length) return;
nextIndex += 1;
try {
results[index] = await mapper(/** @type {T} */ (items[index]), index);
} catch (cause) {
failed = true;
throw cause;
}
}
}),
);
return results;
};
+5 -3
View File
@@ -2,6 +2,7 @@ import { readFile, readdir, stat } from "node:fs/promises";
import { join, relative, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import ts from "typescript6";
import { mapWithConcurrency } from "./bounded-file-reads.mjs";
// Recognized numeric REA_ limit reads must be an analysis setting or a
// documented exception with a reason. External behavioral witnesses are
@@ -1361,11 +1362,12 @@ if (direct) {
}
const discovered = discoverNumericLimitUses(
await Promise.all(
(await listFiles(join(root, "src"))).map(async (path) => ({
await mapWithConcurrency(
await listFiles(join(root, "src")),
async (path) => ({
path: relative(root, path),
source: await readFile(path, "utf8"),
})),
}),
),
);
@@ -50,10 +50,12 @@ processTest.skipIf(
'export const limit = { update_mode: "parameter" };',
);
}
await copyFile(
for (const script of [
"scripts/verify/rea-numeric-limits.mjs",
join(root, "scripts/verify/rea-numeric-limits.mjs"),
);
"scripts/verify/bounded-file-reads.mjs",
]) {
await copyFile(script, join(root, script));
}
const run = () =>
processes.run(
process.execPath,
+127
View File
@@ -0,0 +1,127 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
DEFAULT_FILE_READ_CONCURRENCY,
mapWithConcurrency,
} from "../../scripts/verify/bounded-file-reads.mjs";
describe("mapWithConcurrency", () => {
it("caps peak in-flight callbacks and preserves input order", async () => {
const items = Array.from({ length: 16 }, (_, index) => index);
let inFlight = 0;
let peakInFlight = 0;
const results = await mapWithConcurrency(
items,
async (item, index) => {
inFlight += 1;
peakInFlight = Math.max(peakInFlight, inFlight);
// Reverse relative completion timing so out-of-order completion still
// writes back to the original slot.
await new Promise((resolve) =>
setTimeout(resolve, (items.length - item) % 4),
);
inFlight -= 1;
return `${index}:${item * 2}`;
},
3,
);
expect(peakInFlight).toBe(3);
expect(results).toEqual(items.map((item, index) => `${index}:${item * 2}`));
});
it("reads temporary files with bounded concurrency", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-bounded-file-reads-"));
try {
const paths = await Promise.all(
Array.from({ length: 20 }, async (_, index) => {
const path = join(root, `file-${index}.txt`);
await writeFile(path, `content-${index}`, "utf8");
return path;
}),
);
let inFlight = 0;
let peakInFlight = 0;
const contents = await mapWithConcurrency(
paths,
async (path) => {
inFlight += 1;
peakInFlight = Math.max(peakInFlight, inFlight);
try {
return await readFile(path, "utf8");
} finally {
inFlight -= 1;
}
},
4,
);
expect(peakInFlight).toBeLessThanOrEqual(4);
expect(contents).toEqual(
Array.from({ length: 20 }, (_, index) => `content-${index}`),
);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("returns an empty array without calling mapper when items is empty", async () => {
let called = 0;
const results = await mapWithConcurrency([], async () => {
called += 1;
return called;
});
expect(results).toEqual([]);
expect(called).toBe(0);
expect(DEFAULT_FILE_READ_CONCURRENCY).toBeGreaterThan(0);
expect(DEFAULT_FILE_READ_CONCURRENCY).toBeLessThanOrEqual(128);
});
it("stops dispatching new items after a rejection", async () => {
const started: number[] = [];
const items = Array.from({ length: 12 }, (_, index) => index);
let releaseFirstItem!: () => void;
const firstItemGate = new Promise<void>((resolve) => {
releaseFirstItem = resolve;
});
let firstItemFinished!: () => void;
const firstItemDone = new Promise<void>((resolve) => {
firstItemFinished = resolve;
});
await expect(
mapWithConcurrency(
items,
async (item) => {
started.push(item);
if (item === 0) {
await firstItemGate;
firstItemFinished();
return item;
}
if (item === 1) throw new Error("boom");
return item;
},
2,
),
).rejects.toThrow("boom");
releaseFirstItem();
await firstItemDone;
await new Promise((resolve) => setTimeout(resolve, 10));
expect(started).toEqual([0, 1]);
});
it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])(
"rejects invalid concurrency %s",
async (invalid) => {
await expect(
mapWithConcurrency([1, 2], async (item) => item, invalid),
).rejects.toThrow(RangeError);
},
);
});
+1
View File
@@ -21,6 +21,7 @@
"scripts/lib/verifier-run.mjs",
"scripts/lib/verifier-source-loader.mjs",
"scripts/verify-package-evidence.mjs",
"scripts/verify/bounded-file-reads.mjs",
"scripts/verify/completeness-ternary-guard.mjs",
"scripts/verify/javascript/digests.mjs",
"scripts/verify/javascript/output.mjs",