diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index 6a6e185d44..9b66772bf4 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -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 }) => diff --git a/scripts/verify/bounded-file-reads.mjs b/scripts/verify/bounded-file-reads.mjs new file mode 100644 index 0000000000..244e4ddf2f --- /dev/null +++ b/scripts/verify/bounded-file-reads.mjs @@ -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} mapper + * @param {number} [concurrency] + * @returns {Promise} + */ +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; +}; diff --git a/scripts/verify/rea-numeric-limits.mjs b/scripts/verify/rea-numeric-limits.mjs index 44f85d415b..446a59b76a 100644 --- a/scripts/verify/rea-numeric-limits.mjs +++ b/scripts/verify/rea-numeric-limits.mjs @@ -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"), - })), + }), ), ); diff --git a/tests/boundary/process/numericLimitGuardPermission.test.ts b/tests/boundary/process/numericLimitGuardPermission.test.ts index de1abdd8b5..193ee19936 100644 --- a/tests/boundary/process/numericLimitGuardPermission.test.ts +++ b/tests/boundary/process/numericLimitGuardPermission.test.ts @@ -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, diff --git a/tests/evaluation/boundedFileReads.test.ts b/tests/evaluation/boundedFileReads.test.ts new file mode 100644 index 0000000000..b56a968fdb --- /dev/null +++ b/tests/evaluation/boundedFileReads.test.ts @@ -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((resolve) => { + releaseFirstItem = resolve; + }); + let firstItemFinished!: () => void; + const firstItemDone = new Promise((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); + }, + ); +}); diff --git a/tsconfig.scripts.json b/tsconfig.scripts.json index cc311ffb3f..dc4916f11e 100644 --- a/tsconfig.scripts.json +++ b/tsconfig.scripts.json @@ -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",