test(adb): link stub executables to one launched dispatcher (#15698)

* test(adb): link stub executables to one launched dispatcher

macOS checks every newly written executable on its first launch, one file
at a time for the whole host (about 150 ms each; 50 fresh stubs launched
together took 9 s). The ADB tests wrote a fresh fake adb (and Node.js tool
shims) per test, so under parallel load the first launch waited behind
every other test's stubs inside the provider's 10 s adb version probe
deadline or the test's own deadline.

writeShellStub hard-links each stub to one dispatcher the test process has
already launched; the dispatcher sources the stub's script with the stub's
own $0 and arguments. AdbProvider.test.ts drops from 38 s to 12 s alone.

* test(adb): remove the stub dispatcher at worker teardown

Forked Vitest workers skip process exit hooks, so the dispatcher
directory leaked. The test runner now removes it through the worker
cleanup it already uses for the process ownership host.
This commit is contained in:
morluto
2026-12-02 00:28:46 +00:00
committed by GitHub
parent 5b4ed4660e
commit 6bcec126c7
5 changed files with 106 additions and 38 deletions
+8
View File
@@ -413,6 +413,14 @@ Vitest worker limits do not bound subprocesses launched within a test. Bound
those batches separately so repeated CLI validation cannot oversubscribe the
runner. Preserve simultaneous launches where concurrency is itself under test.
On macOS, the first launch of a newly written executable waits for a host-wide
check that handles one file at a time (about 150 ms each; 50 fresh stubs
launched together took 9 s). A stub written per test therefore waits behind
every other test's stubs, inside whichever production deadline first runs it.
Write per-test shell stubs with `writeShellStub` from
`tests/fixtures/shellStub.ts`: each one is a hard link to a dispatcher the test
process has already launched, so no stub pays that wait.
Coordinate expensive checks across agents sharing a host. If a test unexpectedly
consumes heavy CPU, stop its owned process family, retain its log and revision,
and profile a bounded representative case before retrying. Separate production
+4 -6
View File
@@ -89,6 +89,7 @@ import {
} from "../domain/adb/adbDeviceAnalysis.js";
import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js";
import { waitFor } from "../../tests/support/testWait.js";
import { writeShellStub } from "../../tests/fixtures/shellStub.js";
const it = test.skipIf(process.platform === "win32");
@@ -105,14 +106,11 @@ const writeAdbStub = async (
): Promise<{ readonly binary: string; readonly root: string }> => {
const root = await mkdtemp(join("/tmp", "rea-adb-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
const binary = join(root, "adb");
// A running adb server makes `adb start-server` a successful no-op.
await writeFile(
binary,
`#!/bin/sh\nif [ "$1" = "start-server" ]; then exit 0; fi\n${body(root)}\n`,
{ mode: 0o755 },
const binary = await writeShellStub(
join(root, "adb"),
`if [ "$1" = "start-server" ]; then exit 0; fi\n${body(root)}\n`,
);
await chmod(binary, 0o755);
return { binary, root };
};
@@ -1,9 +1,10 @@
import { execFile } from "node:child_process";
import { chmod, mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { writeShellStub } from "../../fixtures/shellStub.js";
import { AdbProvider } from "../../../src/adb/AdbProvider.js";
import { adbResultSchemas } from "../../../src/domain/adb/adbDeviceAnalysis.js";
import {
@@ -17,8 +18,7 @@ const itPosix = it.skipIf(process.platform === "win32");
// AOSP Toybox stat's documented %A/%U/%G/%s/%y conversions are fixed-format
// metadata fields. This shim models those fields from host lstat data; it does
// not claim to exercise an Android device's Toybox binary.
const statShim = String.raw`#!${process.execPath}
const fs = require('node:fs');
const statShim = String.raw`const fs = require('node:fs');
const args = process.argv.slice(2);
fs.appendFileSync(process.env.STAT_CALLS, args.slice(2).length + '\n');
const fail = process.env.STAT_FAIL_PATH;
@@ -33,33 +33,33 @@ for (const path of args.slice(2)) {
process.stdout.write(permissions + '|1000|1000|' + stat.size + '|2026-10-12 00:00:00\n');
}`;
const readlinkShim = String.raw`#!${process.execPath}
const fs = require('node:fs');
const readlinkShim = String.raw`const fs = require('node:fs');
fs.appendFileSync(process.env.READLINK_CALLS, 'called\n');
process.stdout.write(fs.readlinkSync(process.argv[3]));
`;
const makeTool = async (directory: string, name: string, contents: string) => {
const path = join(directory, name);
await writeFile(path, contents);
await chmod(path, 0o755);
return path;
};
const shellQuote = (value: string): string =>
"'" + value.replaceAll("'", "'\\''") + "'";
/** A Node.js tool on PATH whose script keeps the tool's own `argv` indices. */
const makeTool = async (directory: string, name: string, contents: string) => {
const path = join(directory, name);
await writeFile(`${path}.cjs`, contents);
return writeShellStub(
path,
`exec ${shellQuote(process.execPath)} "$0.cjs" "$@"\n`,
);
};
const makeFakeAdb = async (
directory: string,
toolDirectory: string,
calls: string,
linkCalls: string,
) => {
const path = join(directory, "fakeadb");
await writeFile(
path,
`#!/bin/sh
if [ "$1" = version ]; then
return writeShellStub(
join(directory, "fakeadb"),
`if [ "$1" = version ]; then
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"
exit 0
fi
@@ -72,22 +72,17 @@ export STAT_CALLS=${shellQuote(calls)}
export READLINK_CALLS=${shellQuote(linkCalls)}
exec /bin/sh -c "$*"
`,
{ mode: 0o755 },
);
await chmod(path, 0o755);
return path;
};
const makeRawOutputFakeAdb = async (
directory: string,
rawOutput: Buffer,
): Promise<string> => {
const path = join(directory, "fakeadb-raw-output");
const encoded = rawOutput.toString("base64");
await writeFile(
path,
`#!/bin/sh
if [ "$1" = version ]; then
return writeShellStub(
join(directory, "fakeadb-raw-output"),
`if [ "$1" = version ]; then
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"
exit 0
fi
@@ -96,10 +91,7 @@ if [ "$1" = -s ]; then shift 2; fi
[ "$1" = shell ] || exit 90
exec ${shellQuote(process.execPath)} -e 'process.stdout.write(Buffer.from("${encoded}", "base64"))'
`,
{ mode: 0o755 },
);
await chmod(path, 0o755);
return path;
};
const runScript = async (
+59
View File
@@ -0,0 +1,59 @@
import { execFile } from "node:child_process";
import { link, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
// macOS assesses every newly written executable on its first exec, one file at
// a time for the whole host (about 150 ms each, measured with 50 parallel
// launches taking 9 s). A fresh stub per test therefore waits behind every
// other test's fresh stubs, and that wait lands inside whatever production
// deadline first runs it. A hard link shares the assessed file, so every stub
// links one dispatcher this process has already executed. The dispatcher
// sources `<stub>.sh`; `$0` and the arguments stay the stub's own.
const DISPATCHER = '#!/bin/sh\n. "$0.sh"\n';
let dispatcher: Promise<string> | undefined;
let dispatcherDirectory: string | undefined;
const readyDispatcher = (): Promise<string> =>
(dispatcher ??= (async () => {
const directory = await mkdtemp(
join(await realpath(tmpdir()), "rea-shell-stub-"),
);
dispatcherDirectory = directory;
const path = join(directory, "dispatch");
await writeFile(`${path}.sh`, "exit 0\n");
await writeFile(path, DISPATCHER, { mode: 0o755 });
// Pay the first-exec assessment here, before any stub is linked.
await execFileAsync(path);
return path;
})());
/**
* Write a POSIX shell stub at `path` that runs `script` with the stub's own
* `$0` and arguments, as an executable `#!/bin/sh` script would.
*/
export const writeShellStub = async (
path: string,
script: string,
): Promise<string> => {
await writeFile(`${path}.sh`, script);
await link(await readyDispatcher(), path);
return path;
};
/**
* Remove this module's dispatcher. The test runner calls it when the worker
* stops; stubs already linked keep the shared file.
*/
export const closeShellStubDispatcher = async (): Promise<void> => {
const directory = dispatcherDirectory;
if (directory === undefined) return;
await dispatcher?.catch(() => undefined);
await rm(directory, { recursive: true, force: true });
dispatcherDirectory = undefined;
dispatcher = undefined;
};
+15 -4
View File
@@ -2,17 +2,28 @@ import { TestRunner } from "vitest";
import type { ProcessOwnershipHost } from "../src/process/ProcessOwnership.js";
/** Retire each isolated graph's native cache when its test worker stops. */
/**
* Retire each isolated graph's native cache and shell stub dispatcher when its
* test worker stops. Forked workers do not run `process.on("exit")` hooks.
*/
export default class ProcessOwnershipRunner extends TestRunner {
readonly #registeredHosts = new WeakSet<ProcessOwnershipHost>();
readonly #registeredStubOwners = new WeakSet<() => Promise<void>>();
async onBeforeRunFiles(): Promise<void> {
const { systemProcessOwnershipHost } =
await import("../src/process/ProcessOwnershipObservation.js");
if (this.#registeredHosts.has(systemProcessOwnershipHost)) return;
const { closeShellStubDispatcher } =
await import("./fixtures/shellStub.js");
if (this.onCleanupWorkerContext === undefined)
throw new Error("The test pool does not support worker resource cleanup");
this.#registeredHosts.add(systemProcessOwnershipHost);
this.onCleanupWorkerContext(() => systemProcessOwnershipHost.close?.());
if (!this.#registeredHosts.has(systemProcessOwnershipHost)) {
this.#registeredHosts.add(systemProcessOwnershipHost);
this.onCleanupWorkerContext(() => systemProcessOwnershipHost.close?.());
}
if (!this.#registeredStubOwners.has(closeShellStubDispatcher)) {
this.#registeredStubOwners.add(closeShellStubDispatcher);
this.onCleanupWorkerContext(closeShellStubDispatcher);
}
}
}