Files
rea/scripts/verify/bounded-file-reads.mjs
T
RRFZ d5b4c4bb61 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`.
2026-11-26 23:25:32 +08:00

51 lines
1.5 KiB
JavaScript

/**
* 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;
};