fix(ci/tests): bound untyped oxlint threads and fail fast on terminal POSIX poll errors (#13447)

* fix(ci/tests): bound untyped oxlint threads and fail fast on terminal POSIX poll errors

* style(tests): format POSIX observation polling

* fix(ci): pass REA_OXLINT_THREADS and GITHUB_ACTIONS through Turbo lint and format
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 15:48:48 +00:00
1 parent 22042af848
commit 07df0f1c04
10 files changed
+239 -72

No files matched your search

+21 -1
View File
@@ -1,6 +1,7 @@
import { spawnSync } from "node:child_process";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { availableParallelism } from "node:os";
import { dirname, join, relative, sep } from "node:path";
import { z } from "zod";
@@ -79,11 +80,30 @@ try {
typed ? "typed-oxlint.json" : "oxlint.json",
);
await rm(reportPath, { force: true });
const hasExplicitThreads = extraArguments.some(
(argument) =>
argument === "--threads" || argument.startsWith("--threads="),
);
const configuredThreads = Number(process.env.REA_OXLINT_THREADS);
// Match vitest.config.ts runner concurrency so untyped oxlint does not
// saturate every host core on shared developer or agent machines.
const defaultUntypedThreads = Math.min(
process.env.GITHUB_ACTIONS === "true" ? 4 : 2,
availableParallelism(),
);
const untypedThreads =
Number.isSafeInteger(configuredThreads) && configuredThreads > 0
? configuredThreads
: defaultUntypedThreads;
const result = run(
"oxlint",
"bin/oxlint",
[
...(typed ? ["--type-aware", "--threads", "1"] : []),
...(typed
? ["--type-aware", "--threads", "1"]
: hasExplicitThreads
? []
: ["--threads", String(untypedThreads)]),
...extraArguments,
"--format",
"json",
@@ -8,7 +8,10 @@ import {
awaitApktoolOperation,
createApktoolProcessFixture,
} from "../../tests/fixtures/apktoolProcessTree.js";
import { observePosixProcess } from "../../tests/support/process/observePosixProcess.js";
import {
observePosixProcess,
waitForPosixObservation,
} from "../../tests/support/process/observePosixProcess.js";
import { inspectApktoolClient } from "./ApktoolConfiguration.js";
// The interpreter is the test runtime itself, so its environment (and the
@@ -30,34 +33,33 @@ it.skipIf(process.platform === "win32")(
},
).catch((cause: unknown) => cause);
try {
let launched: readonly number[] = [];
await expect
.poll(
async () => {
const marker = await fixture.readMarker();
if (marker?.ready !== true) return false;
launched = [marker.rootPid, marker.childPid];
return (await Promise.all(launched.map(observePosixProcess))).every(
({ kind }) => kind === "running",
);
},
{ interval: 25 },
)
.toBe(true);
const launched = await waitForPosixObservation(
async () => {
const marker = await fixture.readMarker();
if (marker?.ready !== true) return undefined;
const pids = [marker.rootPid, marker.childPid];
return (await Promise.all(pids.map(observePosixProcess))).every(
({ kind }) => kind === "running",
)
? pids
: undefined;
},
{ interval: 25 },
);
controller.abort();
// A regressed probe never settles; bound the wait so cleanup still runs.
const outcome = await awaitApktoolOperation(probe, 15_000);
expect(outcome).toBeInstanceOf(AnalysisCancelledError);
expect(performance.now() - started).toBeLessThan(15_000);
await expect
.poll(
async () =>
(await Promise.all(launched.map(observePosixProcess))).every(
({ kind }) => kind !== "running",
),
{ interval: 25 },
)
.toBe(true);
await waitForPosixObservation(
async () =>
(await Promise.all(launched.map(observePosixProcess))).every(
({ kind }) => kind !== "running",
)
? true
: undefined,
{ interval: 25 },
);
} finally {
controller.abort();
await fixture.cleanup([probe]);
@@ -747,3 +747,63 @@ it.skipIf(resolveTypeScriptCompiler().name !== "tsrs")(
}
},
);
it("passes REA_OXLINT_THREADS and GITHUB_ACTIONS through Turbo lint without changing its cache hash", async () => {
const config = await readRootConfig();
const lintTask = config.tasks.lint;
expect(lintTask).toBeDefined();
const passThroughEnv = z.array(z.string()).parse(lintTask?.passThroughEnv);
expect(passThroughEnv).toEqual(
expect.arrayContaining(["REA_OXLINT_THREADS", "GITHUB_ACTIONS"]),
);
const root = await createTestTempDirectory("rea-turbo-lint-env-");
const cache = join(root, ".turbo-cache");
const observed = join(root, "observed.json");
await writeTaskFixture(root, ["lint"], {
lint: `node -e 'const fs=require("node:fs"); fs.writeFileSync(${JSON.stringify(observed)}, JSON.stringify({threads: process.env.REA_OXLINT_THREADS ?? null, ci: process.env.GITHUB_ACTIONS ?? null})); fs.mkdirSync(".cache/static-checks", {recursive: true}); fs.writeFileSync(".cache/static-checks/oxlint.json", "{}");'`,
});
await writeFile(
join(root, ".gitignore"),
"node_modules/\n.cache/\n.turbo/\n.turbo-cache/\nobserved.json\n",
);
await workflowGit(root, ["init", "--initial-branch=main"]);
await workflowGit(root, ["add", "."]);
await workflowGit(root, ["commit", "-m", "test: seed lint passthrough"]);
const runWithEnv = (envOverrides: Record<string, string>, dryRun = false) =>
spawnSync(
process.execPath,
[
turbo,
"run",
"lint",
...(dryRun ? ["--dry=json"] : ["--output-logs=errors-only"]),
"--cache=local:rw",
"--cache-dir",
cache,
],
{
cwd: root,
encoding: "utf8",
timeout: 30_000,
maxBuffer: 16 * 1024 * 1024,
env: { ...process.env, ...envOverrides },
},
);
const hashOne = dryRunSchema
.parse(JSON.parse(runWithEnv({ REA_OXLINT_THREADS: "1" }, true).stdout))
.tasks.find((entry) => entry.taskId === "lint")?.hash;
const hashTwo = dryRunSchema
.parse(JSON.parse(runWithEnv({ REA_OXLINT_THREADS: "3" }, true).stdout))
.tasks.find((entry) => entry.taskId === "lint")?.hash;
expect(hashOne).toBeDefined();
expect(hashTwo).toBe(hashOne);
const executed = runWithEnv({
REA_OXLINT_THREADS: "1",
GITHUB_ACTIONS: "true",
});
expect(executed.status, executed.stdout + executed.stderr).toBe(0);
expect(JSON.parse(await readFile(observed, "utf8"))).toEqual({
threads: "1",
ci: "true",
});
});
@@ -23,6 +23,7 @@ import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { _electron as electron } from "playwright-core";
import { expect, it, onTestFinished, vi } from "vitest";
import { waitForPosixObservation } from "../../support/process/observePosixProcess.js";
import { z } from "zod";
import { writeFakeXcrun } from "../../fixtures/darwinHelperToolchain.js";
import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js";
@@ -1574,14 +1575,15 @@ it.skipIf(!onDarwin)(
["-e", 'process.title = "npm run check"; setInterval(() => {}, 1_000)'],
);
children.push(titleMutated);
await expect
.poll(async () => {
const process = (await host.listProcesses()).find(
({ pid }) => pid === titleMutated.pid,
);
return process?.command ?? "";
})
.toMatch(/^npm run check/u);
const observedTitle = await waitForPosixObservation(async () => {
const entry = (await host.listProcesses()).find(
({ pid }) => pid === titleMutated.pid,
);
return entry !== undefined && /^npm run check/u.test(entry.command)
? entry.command
: undefined;
});
expect(observedTitle).toMatch(/^npm run check/u);
const processes = await host.listProcesses();
const entries = [decoy, owned, titleMutated].map(({ pid }) => {
@@ -19,7 +19,7 @@ import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
import { waitForTestPidFile } from "../../support/process/pidFile.js";
import { processHasStopped } from "../../support/process/observePosixProcess.js";
import { waitForPosixProcessStopped } from "../../support/process/observePosixProcess.js";
import { testWaitDeadline } from "../../support/testWait.js";
// These tests launch controlled fake providers; Linux admission is injected so
@@ -498,7 +498,7 @@ process.stdin.resume();
if (started.ok) throw new Error("GDB unexpectedly started");
expect(started.error._tag).toBe("AnalysisCancelledError");
expect(await readFile(signalPath, "utf8")).toBe("SIGTERM");
await expect.poll(() => processHasStopped(pid)).toBe(true);
await waitForPosixProcessStopped(pid);
expect(manager.status("unknown-session")).toBeUndefined();
await expect(manager.start()).resolves.toMatchObject({
ok: false,
@@ -630,7 +630,7 @@ process.stdin.on("data", (chunk) => {
join(directory, "pid"),
testWaitDeadline(),
);
await expect.poll(() => processHasStopped(pid)).toBe(true);
await waitForPosixProcessStopped(pid);
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
@@ -1019,7 +1019,7 @@ setInterval(() => {}, 1000);
}
await ownedProcessExit;
const pid = ownedLaunch.ownership.leaderPid;
await expect.poll(() => processHasStopped(pid)).toBe(true);
await waitForPosixProcessStopped(pid);
}
const retried = await manager.retryCleanupFailures();
expect(retried.ok).toBe(false);
@@ -7,7 +7,10 @@ import {
awaitApktoolOperation,
createApktoolProcessFixture,
} from "../../fixtures/apktoolProcessTree.js";
import { observePosixProcess } from "../../support/process/observePosixProcess.js";
import {
observePosixProcess,
waitForPosixObservation,
} from "../../support/process/observePosixProcess.js";
import { ApktoolProvider } from "../../../src/apktool/ApktoolProvider.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -35,21 +38,20 @@ it.skipIf(process.platform === "win32")(
decode_timeout_ms: DECODE_TIMEOUT_MS,
},
});
let launched: readonly number[] = [];
try {
await expect
.poll(
async () => {
const marker = await fixture.readMarker();
if (marker?.ready !== true) return false;
launched = [marker.rootPid, marker.childPid];
return (await Promise.all(launched.map(observePosixProcess))).every(
({ kind }) => kind === "running",
);
},
{ interval: 25 },
)
.toBe(true);
const launched = await waitForPosixObservation(
async () => {
const marker = await fixture.readMarker();
if (marker?.ready !== true) return undefined;
const pids = [marker.rootPid, marker.childPid];
return (await Promise.all(pids.map(observePosixProcess))).every(
({ kind }) => kind === "running",
)
? pids
: undefined;
},
{ interval: 25 },
);
const outcome = await awaitApktoolOperation(pending, 15_000);
const elapsed = performance.now() - started;
expect(outcome.ok).toBe(false);
@@ -66,15 +68,15 @@ it.skipIf(process.platform === "win32")(
// Settlement includes the owned-command deadline, so the timer elapsed.
expect(elapsed).toBeGreaterThanOrEqual(DECODE_TIMEOUT_MS - 50);
expect(elapsed).toBeLessThan(15_000);
await expect
.poll(
async () =>
(await Promise.all(launched.map(observePosixProcess))).every(
({ kind }) => kind !== "running",
),
{ interval: 25 },
)
.toBe(true);
await waitForPosixObservation(
async () =>
(await Promise.all(launched.map(observePosixProcess))).every(
({ kind }) => kind !== "running",
)
? true
: undefined,
{ interval: 25 },
);
} finally {
await fixture.cleanup([pending, provider.close()]);
}
@@ -6,7 +6,10 @@ import { ApktoolCommandCleanup } from "../../../src/apktool/ApktoolCommandCleanu
import { inspectApktoolClient } from "../../../src/apktool/ApktoolConfiguration.js";
import { createApktoolProcessFixture } from "../../fixtures/apktoolProcessTree.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { observePosixProcess } from "../../support/process/observePosixProcess.js";
import {
observePosixProcess,
waitForPosixObservation,
} from "../../support/process/observePosixProcess.js";
const VERSION_PROBE_DEADLINE_MS = 20_000;
@@ -53,15 +56,15 @@ it
// No cancellation has run: fallback teardown must use the last valid
// token owner even when the current marker cannot be read or parsed.
await expect(fixture.cleanup()).rejects.toThrow();
await expect
.poll(
async () =>
(await Promise.all(pids.map(observePosixProcess))).every(
({ kind }) => kind !== "running",
),
{ interval: 25 },
)
.toBe(true);
await waitForPosixObservation(
async () =>
(await Promise.all(pids.map(observePosixProcess))).every(
({ kind }) => kind !== "running",
)
? true
: undefined,
{ interval: 25 },
);
// The still-running version probe would also stop them at its own
// deadline (ApktoolConfiguration: 20 s); fixture teardown must be first.
expect(performance.now() - probeStarted).toBeLessThan(
@@ -1,4 +1,4 @@
import { chmod, rm, writeFile } from "node:fs/promises";
import { chmod, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
@@ -7,6 +7,7 @@ import {
observePosixProcess,
processGroupHasStopped,
processHasStopped,
waitForPosixProcessStopped,
} from "../../support/process/observePosixProcess.js";
it.skipIf(process.platform === "win32")(
@@ -125,3 +126,32 @@ it.skipIf(process.platform === "win32")(
it("observes the current process as live", async () => {
await expect(processHasStopped(process.pid)).resolves.toBe(false);
});
it.skipIf(process.platform === "win32")(
"fails fast on terminal checker errors instead of retry-storming",
async () => {
const directory = await createTestTempDirectory("rea-posix-poll-failfast-");
const checker = join(directory, "ps");
const callsLog = join(directory, "calls.log");
const previousPath = process.env.PATH;
try {
await writeFile(
checker,
`#!/bin/sh\nprintf 'x\\n' >> ${JSON.stringify(callsLog)}\nprintf 'permission denied\\n' >&2\nexit 1\n`,
);
await chmod(checker, 0o700);
process.env.PATH = directory;
await expect(
waitForPosixProcessStopped(123, { interval: 10 }),
).rejects.toMatchObject({ code: 1 });
const calls = (await readFile(callsLog, "utf8"))
.trim()
.split("\n")
.filter(Boolean);
expect(calls).toHaveLength(1);
} finally {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
}
},
);
@@ -1,5 +1,6 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { expect } from "vitest";
const execFileAsync = promisify(execFile);
@@ -109,3 +110,49 @@ export const processGroupHasStopped = async (
}
return true;
};
/**
* Poll until `check()` returns a defined value, aborting immediately on
* terminal inspection errors (such as sandboxed `/bin/ps` `EPERM`) instead of
* letting Vitest's `expect.poll` spin-retry thrown errors for the full deadline.
*/
export const waitForPosixObservation = async <Value>(
check: () => Promise<Value | undefined>,
options?: { readonly interval?: number },
): Promise<Value> => {
let outcome:
| { readonly status: "settled"; readonly value: Value }
| { readonly status: "error"; readonly cause: unknown }
| undefined;
const attempt = async (): Promise<"waiting" | "done"> => {
try {
const value = await check();
if (value === undefined) return "waiting";
outcome = { status: "settled", value };
return "done";
} catch (cause: unknown) {
outcome = { status: "error", cause };
return "done";
}
};
await (
options?.interval === undefined
? expect.poll(attempt)
: expect.poll(attempt, { interval: options.interval })
).toBe("done");
if (outcome?.status === "error") throw outcome.cause;
if (outcome?.status !== "settled")
throw new Error("POSIX observation poll ended without an outcome");
return outcome.value;
};
/** Poll until `pid` is absent or zombie, failing fast on checker errors. */
export const waitForPosixProcessStopped = async (
pid: number,
options?: { readonly interval?: number },
): Promise<void> => {
await waitForPosixObservation(
async () => ((await processHasStopped(pid)) ? true : undefined),
options,
);
};
+1
View File
@@ -75,6 +75,7 @@
]
},
"lint": {
"passThroughEnv": ["REA_OXLINT_THREADS", "GITHUB_ACTIONS"],
"outputs": [".cache/static-checks/oxlint.json"],
"inputs": [
".gitignore",