Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(process): release handles and close worker on incomplete cleanup (#2321)
Vinícius Andrade1e38a038c610
diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.tsindex 6a587915b..de7ac6c42 100644--- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts+++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts@@ -83,6 +83,7 @@ export class JavaScriptAnalysisWorker {readonly #resultBudgetBytes: number;/** Null when the runtime enforces the V8 heap flags instead. */readonly #processMemoryLimitBytes: number | null;+ readonly #onStdinError = (): void => {};readonly #onStdout = (chunk: Buffer | string): void => {try {this.#pending +=@@ -784,20 +785,40 @@ export class JavaScriptAnalysisWorker {if (this.#supervisor !== undefined) {const supervisor = this.#supervisor;const stopped = await supervisor.stop();+ supervisor.launch.process.stdout?.off("data", this.#onStdout);if (stopped.status === "incomplete") {+ try {+ const stdin = supervisor.launch.process.stdin;+ if (+ stdin !== undefined &&+ stdin !== null &&+ !stdin.destroyed &&+ !stdin.writableEnded+ ) {+ stdin.off("error", this.#onStdinError);+ stdin.once("error", this.#onStdinError);+ stdin.end();+ }+ } catch {+ // Cooperative protocol stdin may already be closed or broken.+ }+ this.#resetState();pendingCleanup.add(this);return this.#cleanupError(stopped.reason, original);}- supervisor.launch.process.stdout?.off("data", this.#onStdout);supervisor.dispose();this.#supervisor = undefined;}+ this.#resetState();+ return undefined;+ }++ #resetState(): void {this.#ready = false;this.#frames = [];this.#pending = "";this.#decoder = new StringDecoder("utf8");this.#protocolFailure = undefined;- return undefined;}}diff --git a/src/process/ProviderProcess.ts b/src/process/ProviderProcess.tsindex d7b95613f..8e650898b 100644--- a/src/process/ProviderProcess.ts+++ b/src/process/ProviderProcess.ts@@ -61,6 +61,8 @@ export interface ProviderProcessHandle extends Pick</** True once an enforced process memory limit reported an allocation failure. */readonly memoryLimitReached?: boolean;kill(signal?: NodeJS.Signals | number): boolean;+ unref?(): void;+ ref?(): void;}/** Process handle returned by a provider-specific launcher. */@@ -371,13 +373,33 @@ export class ProviderProcessSupervisor {this.launch.process.off("error", this.#onError);}+ /** Release event-loop references so incomplete cleanup does not prevent host exit. */+ unref(): void {+ const process = this.launch.process;+ process.unref?.();+ (process.stdin as { unref?: () => void } | null | undefined)?.unref?.();+ (process.stdout as { unref?: () => void } | null | undefined)?.unref?.();+ (process.stderr as { unref?: () => void } | null | undefined)?.unref?.();+ }++ /** Restore event-loop references when retrying supervised process cleanup. */+ ref(): void {+ const process = this.launch.process;+ process.ref?.();+ (process.stdin as { ref?: () => void } | null | undefined)?.ref?.();+ (process.stdout as { ref?: () => void } | null | undefined)?.ref?.();+ (process.stderr as { ref?: () => void } | null | undefined)?.ref?.();+ }+async #stop(options: ProviderProcessStopOptions,): Promise<ProviderProcessStopResult> {+ this.ref();let completed = false;try {const result = await this.#stopWithin(options);completed = result.status !== "incomplete";+ if (!completed) this.unref();return result;} finally {if (completed) this.dispose();diff --git a/src/process/ProviderProcessOutput.test.ts b/src/process/ProviderProcessOutput.test.tsindex 28dc87dff..3ca2621f0 100644--- a/src/process/ProviderProcessOutput.test.ts+++ b/src/process/ProviderProcessOutput.test.ts@@ -121,3 +121,40 @@ it("reports a reached process memory limit only when the handle observed one", (supervisor.dispose();}});++it("unreferences process and stream handles when stop reports incomplete cleanup", async () => {+ const unrefProcess = vi.fn();+ const unrefStdin = vi.fn();+ const unrefStdout = vi.fn();+ const unrefStderr = vi.fn();+ const producer = Object.assign(new EventEmitter(), {+ stdout: Object.assign(new PassThrough(), { unref: unrefStdout }),+ stdin: Object.assign(new PassThrough(), { unref: unrefStdin }),+ stderr: Object.assign(new PassThrough(), { unref: unrefStderr }),+ exitCode: null,+ signalCode: null,+ kill: () => false,+ unref: unrefProcess,+ });+ const supervisor = new ProviderProcessSupervisor({+ process: producer,+ ownsProcessLifetime: true,+ cleanup: async () => ({+ cleaned: false,+ reason: "process table could not be inspected: spawn EPERM",+ }),+ });+ try {+ const result = await supervisor.stop();+ expect(result).toMatchObject({+ status: "incomplete",+ reason: "process table could not be inspected: spawn EPERM",+ });+ expect(unrefProcess).toHaveBeenCalledTimes(1);+ expect(unrefStdin).toHaveBeenCalledTimes(1);+ expect(unrefStdout).toHaveBeenCalledTimes(1);+ expect(unrefStderr).toHaveBeenCalledTimes(1);+ } finally {+ supervisor.dispose();+ }+});diff --git a/src/windows/WindowsOwnedProcess.ts b/src/windows/WindowsOwnedProcess.tsindex 1b96db867..b6a530461 100644--- a/src/windows/WindowsOwnedProcess.ts+++ b/src/windows/WindowsOwnedProcess.ts@@ -67,6 +67,7 @@ export class WindowsOwnedProcess extends EventEmitter {#closed = false;#failure: string | undefined;#timer: NodeJS.Timeout | undefined;+ #unreferenced = false;#cleanup: Promise<ProcessCleanupResult> | undefined;readonly #memoryLimitBytes: number | undefined;#memoryLimitReached = false;@@ -222,6 +223,18 @@ export class WindowsOwnedProcess extends EventEmitter {return this.#cleanup;}+ /** Release event-loop references so unsettled jobs do not prevent host exit. */+ unref(): void {+ this.#unreferenced = true;+ this.#timer?.unref();+ }++ /** Restore event-loop references when retrying process lifecycle observation. */+ ref(): void {+ this.#unreferenced = false;+ this.#timer?.ref();+ }+async #stop(): Promise<ProcessCleanupResult> {if (this.#closed) return { cleaned: true, signaled: false };let timer: NodeJS.Timeout | undefined;@@ -255,6 +268,7 @@ export class WindowsOwnedProcess extends EventEmitter {#schedule(): void {if (this.#closed || this.#timer !== undefined) return;this.#timer = setTimeout(() => this.#poll(), 25);+ if (this.#unreferenced) this.#timer.unref();}#poll(): void {diff --git a/tests/boundary/javascript/javascriptSourceAnalysisWorker.test.ts b/tests/boundary/javascript/javascriptSourceAnalysisWorker.test.tsindex 0e41a11bb..04ba5201f 100644--- a/tests/boundary/javascript/javascriptSourceAnalysisWorker.test.ts+++ b/tests/boundary/javascript/javascriptSourceAnalysisWorker.test.ts@@ -1,7 +1,13 @@import { createHash } from "node:crypto";+import { execFile } from "node:child_process";+import { readFile } from "node:fs/promises";+import { join } from "node:path";+import { promisify } from "node:util";import { expect, it } from "vitest";import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";+import type { OwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";@@ -151,6 +157,121 @@ it("preserves a failed owned cleanup retry when the next caller cancels before a}});+it("ends worker stdin and unreferences process handles when cleanup reports inspection uncertainty", async () => {+ let stdinEnded = false;+ let unreferenced = false;+ let permitCleanup = false;+ let childStdin: typeof process.stdin | undefined;+ const worker = new JavaScriptAnalysisWorker(+ { heapMb: 128, timeoutMs: 30_000 },+ async (request) => {+ const launched = await spawnOwnedProviderProcess(request);+ const originalUnref = launched.process.unref;+ launched.process.unref = () => {+ unreferenced = true;+ originalUnref?.call(launched.process);+ };+ childStdin = launched.process.stdin as unknown as typeof process.stdin;+ launched.process.stdin?.once("finish", () => {+ stdinEnded = true;+ });+ return {+ ...launched,+ cleanup: async () =>+ permitCleanup+ ? launched.cleanup === undefined+ ? cleanupOwnedProcessGroup(launched.ownership)+ : launched.cleanup()+ : {+ cleaned: false,+ reason: "process table could not be inspected: spawn EPERM",+ },+ };+ },+ );+ try {+ const file = source("app.mjs", "export const observed = 7;");+ const result = await worker.analyze(file, 100);+ if (!result.ok) throw result.error.error;+ const closing = worker.close();+ await expect(closing).rejects.toBeInstanceOf(ProviderCleanupError);+ await expect(closing).rejects.toMatchObject({+ cause: {+ message: "process table could not be inspected: spawn EPERM",+ },+ });+ expect(childStdin?.writableEnded || stdinEnded).toBe(true);+ expect(unreferenced).toBe(true);+ const errorListeners = childStdin?.listenerCount("error");+ for (let retry = 0; retry < 3; retry++)+ await expect(worker.close()).rejects.toBeInstanceOf(ProviderCleanupError);+ expect(childStdin?.listenerCount("error")).toBeLessThanOrEqual(+ errorListeners ?? 0,+ );+ permitCleanup = true;+ await worker.close();+ } finally {+ permitCleanup = true;+ await worker.close().catch(() => {});+ }+});++it("lets a separate host exit while its live worker cleanup remains incomplete", async () => {+ const root = await createTestTempDirectory("rea-worker-incomplete-host-");+ const ownershipPath = join(root, "ownership.json");+ const workerUrl = new URL(+ "../../../dist/javascript/analysis/JavaScriptAnalysisWorker.js",+ import.meta.url,+ ).href;+ const launcherUrl = new URL(+ "../../../dist/process/ProviderProcess.js",+ import.meta.url,+ ).href;+ const script = `+import { writeFile } from "node:fs/promises";+import { pathToFileURL } from "node:url";+import { JavaScriptAnalysisWorker } from ${JSON.stringify(workerUrl)};+import { spawnOwnedProviderProcess } from ${JSON.stringify(launcherUrl)};+const worker = new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 10000 }, async request => {+ const entry = pathToFileURL(request.arguments.at(-1)).href;+ const launched = await spawnOwnedProviderProcess({ ...request, arguments: [+ ...request.arguments.slice(0, -1), "--input-type=module", "-e",+ "const interval = setInterval(() => {}, 1000); setTimeout(() => clearInterval(interval), 60000); await import(" + JSON.stringify(entry) + ");"+ ] });+ // The launcher is deliberately orphaned when this host exits; cleanup still+ // requires its run token and executable identity, rather than its old parent.+ const { expectedParentPid, ...ownership } = launched.ownership;+ await writeFile(${JSON.stringify(ownershipPath)}, JSON.stringify(ownership));+ return { ...launched, cleanup: async () => ({ cleaned: false, reason: "fixture inspection unavailable" }) };+});+const analyzed = await worker.analyze(${JSON.stringify(source("app.mjs", "export const value = 1;"))}, 100);+if (!analyzed.ok) throw analyzed.error.error;+try { await worker.close(); throw new Error("cleanup unexpectedly completed"); }+catch (error) {+ if (error.cleanupIncomplete !== true) throw error;+ process.stdout.write(JSON.stringify({ code: "cleanup_incomplete", reason: error.cause.message }) + "\\n");+}+`;+ try {+ const result = await promisify(execFile)(+ process.execPath,+ ["--input-type=module", "-e", script],+ { timeout: 10_000 },+ );+ expect(JSON.parse(result.stdout)).toMatchObject({+ code: "cleanup_incomplete",+ reason: "fixture inspection unavailable",+ });+ } finally {+ const ownership = JSON.parse(+ await readFile(ownershipPath, "utf8"),+ ) as OwnedProcessGroup;+ expect(await cleanupOwnedProcessGroup(ownership)).toMatchObject({+ cleaned: true,+ });+ }+});+// The handshake mirrors the real server: only Node.js reports an enforced V8 heap limit.const resourceFailureWorker = (heapLimit: string) =>new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 30_000 }, (request) =>