Prevent zombie processes after plugin startup and reload (#10470)

* fix(server): prevent zombie children after plugin builds

Retiring a compiler thread closed its libuv loop while esbuild still owned a native child. Run the compiler in a subprocess so the daemon can reap it when the idle compiler disconnects.

* test(ci): check plugin compiler reaping on macOS
This commit is contained in:
Mohamed Boudra
2026-11-22 11:11:59 +07:00
committed by GitHub
parent 20f217b8cb
commit 4b429c0030
4 changed files with 116 additions and 42 deletions
+8 -2
View File
@@ -278,8 +278,8 @@ jobs:
# native-recursive.ts serves darwin and win32, but windows-latest above is the only
# runner that exercises it. macOS — the platform the reported watcher bug was on —
# otherwise has no server-test coverage. Scoped to the observer/watcher suites to
# bound runtime.
# otherwise has no server-test coverage. Keep this job scoped to regressions
# reported on macOS.
server-tests-macos:
name: server-tests (macos-latest, file observation)
needs: changes
@@ -307,6 +307,12 @@ jobs:
src/server/workspace-git-service.observation.integration.test.ts \
--bail=1
- name: Verify plugin compiler children are reaped
run: |
npm run test:unit --workspace=@getpaseo/server -- \
src/server/plugins/index.posix.test.ts \
-t "reaps compiler children" --bail=1
desktop-tests-ubuntu:
name: desktop-tests (ubuntu-latest)
needs: changes
@@ -1,4 +1,3 @@
import { parentPort } from "node:worker_threads";
import type { ZodIssue } from "zod";
import { compilePlugin, compileDirectoryPlugin } from "./compiler-build.js";
import { runPluginBuild } from "./preparation-build.js";
@@ -16,13 +15,16 @@ export type CompilerReply =
warnings?: unknown[];
};
const port = parentPort!;
// The compiler owner serializes requests; the port queues the first request
// until this entrypoint has loaded, including in source/tsx development.
port.on("message", (task: CompilerTask) => {
// The compiler owner serializes requests. IPC holds the process open between
// tasks and lets it exit when the daemon retires it or exits.
process.on("message", (task: CompilerTask) => {
void run(task);
});
function reply(message: CompilerReply): void {
if (process.connected) process.send!(message);
}
async function run(task: CompilerTask): Promise<void> {
try {
let value: unknown;
@@ -38,17 +40,16 @@ async function run(task: CompilerTask): Promise<void> {
task.directory,
task.commands,
{
info: (data, message) =>
port.postMessage({ kind: "log", data, message } satisfies CompilerReply),
info: (data, message) => reply({ kind: "log", data, message }),
},
task.environment,
);
break;
}
port.postMessage({ kind: "result", value } satisfies CompilerReply);
reply({ kind: "result", value });
} catch (cause) {
const error = cause instanceof Error ? cause : new Error(String(cause));
port.postMessage({
reply({
kind: "error",
error,
// Error cloning drops own metadata such as filesystem code/path. Zod's
@@ -57,6 +58,6 @@ async function run(task: CompilerTask): Promise<void> {
...("issues" in error ? { issues: error.issues as ZodIssue[] } : {}),
...("errors" in error ? { errors: error.errors as unknown[] } : {}),
...("warnings" in error ? { warnings: error.warnings as unknown[] } : {}),
} satisfies CompilerReply);
});
}
}
+55 -30
View File
@@ -1,6 +1,6 @@
import { type ChildProcess, fork } from "node:child_process";
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
import { Worker } from "node:worker_threads";
import pLimit from "p-limit";
import { ZodError } from "zod";
import type * as build from "./compiler-build.js";
@@ -35,17 +35,21 @@ const workerUrl = new URL(
source ? "./compiler-worker.ts" : "./compiler-worker.js",
import.meta.url,
);
// Resolve the development loader once at module initialization, never during a
// compile request. Packaged workers execute ordinary JavaScript without tsx.
const workerEntrypoint = source
? `import(${JSON.stringify(pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm/api")).href)}).then(({ register }) => { register(); return import(${JSON.stringify(workerUrl.href)}); });`
: workerUrl;
const workerExecArgv = source
? ["--import", pathToFileURL(createRequire(import.meta.url).resolve("tsx")).href]
: [];
// Reuse the isolate during a build batch (notably daemon bootstrap), then release
// TypeScript's heap when idle. Only this owner admits work or stops the worker.
interface CompilerProcess {
child: ChildProcess;
exited: Promise<void>;
}
// Reuse the process during a build batch, then release TypeScript's heap.
// esbuild starts a native child. Terminating a worker thread closes its libuv
// loop before it can reap that child, leaving a zombie under the daemon PID.
class PluginCompiler {
private readonly queue = pLimit(1);
private worker: Worker | null = null;
private worker: CompilerProcess | null = null;
private idleTimer: ReturnType<typeof setTimeout> | null = null;
private stopping: Promise<unknown> = Promise.resolve();
@@ -58,12 +62,14 @@ class PluginCompiler {
this.idleTimer = null;
await this.stopping;
const worker = this.worker ?? this.startWorker();
worker.ref();
worker.child.ref();
worker.child.channel?.ref();
try {
return await this.request<T>(worker, task, onLog);
} finally {
if (this.worker === worker) {
worker.unref();
worker.child.unref();
worker.child.channel?.unref();
this.idleTimer = setTimeout(() => this.stopWorker(worker), IDLE_TIMEOUT_MS);
this.idleTimer.unref();
} else {
@@ -73,38 +79,51 @@ class PluginCompiler {
});
}
private startWorker(): Worker {
const worker = new Worker(workerEntrypoint, { eval: source, execArgv: [] });
this.worker = worker;
// Keep error/exit ownership while idle too. The next caller gets a fresh
// isolate after a crash; author build commands are never retried.
worker.on("error", () => this.stopWorker(worker));
worker.on("exit", () => {
if (this.worker === worker) this.stopWorker(worker);
private startWorker(): CompilerProcess {
const child = fork(workerUrl, [], {
execArgv: workerExecArgv,
serialization: "advanced",
stdio: ["ignore", "inherit", "inherit", "ipc"],
});
const exited = new Promise<void>((resolve) => {
child.once("exit", () => resolve());
child.on("error", () => {
if (child.pid === undefined) resolve();
});
});
const worker = { child, exited };
this.worker = worker;
child.once("disconnect", () => this.stopWorker(worker));
void exited.then(() => this.stopWorker(worker));
return worker;
}
private stopWorker(worker: Worker): void {
private stopWorker(worker: CompilerProcess): void {
if (this.worker !== worker) return;
this.worker = null;
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
this.stopping = worker.terminate();
this.stopping = worker.exited;
// Close IPC so the compiler can finish any in-flight work and exit. Its
// pipes close with it, ending esbuild's service.
if (worker.child.connected) worker.child.disconnect();
}
private async request<T extends CompilerTask>(
worker: Worker,
worker: CompilerProcess,
task: T,
onLog?: (data: Record<string, unknown>, message: string) => void,
): Promise<TaskResult[T["kind"]]> {
let onMessage: (reply: CompilerReply) => void;
let onError: (error: Error) => void;
let onExit: (code: number) => void;
let onDisconnect: () => void;
const { child } = worker;
try {
return await new Promise<TaskResult[T["kind"]]>((resolve, reject) => {
onError = reject;
onExit = (code) => reject(new Error(`Plugin compiler worker exited (code ${code})`));
onDisconnect = () => reject(new Error("Plugin compiler worker disconnected"));
onMessage = (reply) => {
if (reply.kind === "log") {
onLog?.(reply.data, reply.message);
@@ -116,20 +135,26 @@ class PluginCompiler {
if (reply.errors) Object.assign(error, { errors: reply.errors });
if (reply.warnings) Object.assign(error, { warnings: reply.warnings });
// Promise.all can reject while the other target is still compiling.
// Retire the isolate before another request can enter it.
// Retire the compiler before another request can enter it.
this.stopWorker(worker);
reject(error);
}
};
worker.on("error", onError);
worker.on("exit", onExit);
worker.on("message", onMessage);
worker.postMessage(task, []);
child.on("error", onError);
child.on("exit", onExit);
child.on("disconnect", onDisconnect);
child.on("message", onMessage);
child.send(task, (error) => {
if (!error) return;
this.stopWorker(worker);
reject(error);
});
});
} finally {
worker.off("message", onMessage!);
worker.off("error", onError!);
worker.off("exit", onExit!);
child.off("message", onMessage!);
child.off("error", onError!);
child.off("exit", onExit!);
child.off("disconnect", onDisconnect!);
}
}
}
@@ -1,3 +1,4 @@
import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import {
cp,
@@ -236,6 +237,47 @@ function nextNotification(service: PluginService, pluginId: string): Promise<voi
}
describe("PluginService", () => {
it.skipIf(process.platform === "win32")(
"reaps compiler children after starting and reloading a client-only directory plugin",
async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-reaping-"));
roots.push(directory);
const id = "client-only-reaping";
await writeFile(path.join(directory, "paseo-plugin.json"), JSON.stringify({ id }));
await writeFile(
path.join(directory, "index.client.ts"),
"export default function contribute() {}",
);
const service = createService(
directory,
{ [id]: { source: "directory", path: directory } },
{ builtinPlugins: new BuiltinPluginLoader(directory, []) },
);
const compilerChildren = () =>
execFileSync("ps", ["-axo", "ppid=,stat=,command="], { encoding: "utf8" })
.split("\n")
.map((line) => line.trim())
.filter((line) => {
const [parent, state, ...command] = line.split(/\s+/);
return (
parent === String(process.pid) &&
(state?.startsWith("Z") || /esbuild|compiler-worker/.test(command.join(" ")))
);
});
try {
await service.start();
expect(service.catalog()[0]?.id).toBe(id);
await expect.poll(compilerChildren, { timeout: 5_000 }).toEqual([]);
await service.reloadPlugin(id);
expect(service.catalog()[0]?.id).toBe(id);
await expect.poll(compilerChildren, { timeout: 5_000 }).toEqual([]);
} finally {
await service.stopAllPlugins();
}
},
20_000,
);
it.each([
{ shadow: false, runtime: "subprocess" },
{ shadow: true, runtime: "subprocess" },