Files
reverse-engineering-anything/tests/boundary/process/adbDescriptorPressure.test.ts
T
morluto 7107abf8b8 fix(adb): run adb commands under owned supervision and start the adb server explicitly (#11772)
* fix(adb): run adb commands under owned supervision and start the adb server explicitly

The adb version probe and device commands now run through runOwnedCommand
in their own process group, keeping adb's SIGTERM-first stop through the
termination policy. A device command's escaped descendants are swept with
its cleanup, and cleanup that fails stays owned by the provider, which
retries it before its next operation.

Device operations start the adb server with an explicit `adb start-server`
first. The server is an external shared service: REA may start it but never
stops it, so a device command never forks it into its own cleanup.

runOwnedCommand gains a byte-limited stdout collector: output beyond
maxStdoutBytes is an output-limit failure, like an exceeded diagnostic
budget, and the collected bytes are kept exactly for binary protocols such
as screencap. Ownership preparation that cannot start its own helper for
lack of host capacity is reported as the command's host-capacity launch
failure.

* fix(adb): preserve completed refusals, server startup facts, and lazy server start

* fix(adb): scope runtime-root command cleanup and preserve incomplete command cleanup

* fix(adb): preserve completed bugreports and staging directories across command cleanup failures

* fix(adb): preserve bugreport command cleanup across readback failures and project live cleanup resources
2026-11-16 21:13:43 -05:00

117 lines
4.2 KiB
TypeScript

import { execFile } from "node:child_process";
import { chmod, 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";
// Exhausts the open-file limit, then starts the selected adb through the
// version probe and a device command; both take the owned stop-signal route.
const PRESSURE = `
import { open } from "node:fs/promises";
import { pathToFileURL } from "node:url";
const [repo, binary] = process.argv.slice(1);
const load = (path) => import(pathToFileURL(repo + "/dist/" + path));
const { inspectAdbClient } = await load("adb/AdbConfiguration.js");
const { runAdbCapture } = await load("adb/AdbCommand.js");
const { ArtifactResourceScope } = await load("resources/index.js");
const { primaryAnalysisError } = await load("domain/analysisErrorBase.js");
const resources = new ArtifactResourceScope();
const selection = { binary, pathSource: "environment", environment: {}, resources };
// Under pressure, owned launch preparation may also leave cleanup to retry;
// the report's primary failure is still the host's capacity.
const facts = (error) => {
const primary = primaryAnalysisError(error);
return {
tag: primary._tag,
...(primary.cleanupResources.length === 0 ? {} : { cleanupPending: true }),
resource: primary.resource,
retryable: primary.retryable,
reportedLimits: primary.reportedLimits,
};
};
const probe = () =>
inspectAdbClient(selection).then(
(identity) => ({ version: identity.version }),
(cause) => facts(cause),
);
const command = () =>
runAdbCapture("adb devices", { device: "serial" }, selection, ["devices"],
{ timeoutMs: 10_000, maxOutputBytes: 1024 }, undefined,
).then((result) => result.ok ? { ok: true } : facts(result.error));
const handles = [];
for (let index = 0; index < 128; index += 1) {
try {
handles.push(await open("/dev/null", "r"));
} catch (cause) {
if (cause.code !== "EMFILE") throw cause;
break;
}
}
if (handles.length === 128) throw new Error("Run under a low descriptor limit");
const pressure = { probe: await probe(), command: await command() };
for (const handle of handles) await handle.close();
await resources.retryCleanup();
const after = { probe: await probe(), command: await command() };
process.stdout.write(JSON.stringify({ pressure, after }));
`;
it.skipIf(process.platform === "win32")(
"reports open-file exhaustion as retryable host capacity without an unhandled spawn error",
async () => {
const directory = await createTestTempDirectory("rea-adb-descriptors-");
const adb = join(directory, "adb");
await writeFile(
adb,
`#!/bin/sh
if [ "$1" = version ]; then printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\n'; fi
exit 0
`,
);
await chmod(adb, 0o755);
const { stdout, stderr } = await promisify(execFile)(
"/bin/sh",
[
"-c",
'ulimit -n 64; exec "$@"',
"adb-descriptor-pressure",
process.execPath,
"--input-type=module",
"--eval",
PRESSURE,
process.cwd(),
adb,
],
{ timeout: 30_000, maxBuffer: 1024 * 1024 },
);
// The host refused a launch owned supervision needed: adb itself, ps for
// the Linux ownership baseline, or the macOS ownership helper's compiler.
const capacity = {
tag: "AnalysisResourceConstraintError",
resource: "capacity",
retryable: true,
reportedLimits: {
spawn_error: "EMFILE",
exhausted_resource: "file-descriptors",
command: expect.stringMatching(/(?:^|\/)(?:adb|ps|xcrun)$/u) as unknown,
},
};
// An unhandled child error would exit the process before this report.
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({
pressure: {
probe: capacity,
// On macOS the failed helper preparation leaves its root to remove,
// and the next launch reports that pending cleanup until it succeeds.
command:
process.platform === "darwin"
? expect.objectContaining({ cleanupPending: true })
: capacity,
},
after: { probe: { version: "34.0.5-cli" }, command: { ok: true } },
});
},
);