From b48a374910001b8ae9c087db94a755bf54fcbf4d Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:31:50 -0800 Subject: [PATCH 1/5] fix(server): git commands no longer fork the whole server on Linux On Linux every command ProcessRunner and GitVcsDriver run was a fork of the whole server, which blocks the event loop while the kernel copies its page tables. Commands now start from one small long-lived launcher process that passes each child's pipes back over IPC, so Effect's native spawner keeps its semantics. Launches go through the env -C trampoline, so a hung cwd cannot stall the launcher. If the launcher cannot start, commands fall back to the native spawner. macOS and Windows are unchanged. Fixes #31422 Co-Authored-By: Claude Opus 5.5 --- apps/server/src/bin.ts | 4 + apps/server/src/cli/runningServer.ts | 2 +- apps/server/src/cli/server.ts | 5 +- apps/server/src/cli/service.ts | 6 +- apps/server/src/cli/thread.ts | 2 +- apps/server/src/cli/update.ts | 2 +- .../ServerEnvironmentLabel.test.ts | 2 +- apps/server/src/git/GitManager.test.ts | 2 +- apps/server/src/process-launcher.ts | 3 + apps/server/src/process/ProcessLauncher.ts | 341 ++++++++++++++++++ .../src/process/processLauncherWorker.ts | 112 ++++++ apps/server/src/processRunner.test.ts | 287 ++++++++++++++- apps/server/src/processRunner.ts | 6 +- apps/server/src/vcs/GitVcsDriver.test.ts | 16 + apps/server/src/vcs/GitVcsDriver.ts | 8 +- apps/server/src/vcs/GitVcsDriverCore.test.ts | 2 +- apps/server/vite.config.ts | 4 +- knip.jsonc | 1 + 18 files changed, 789 insertions(+), 16 deletions(-) create mode 100644 apps/server/src/process-launcher.ts create mode 100644 apps/server/src/process/ProcessLauncher.ts create mode 100644 apps/server/src/process/processLauncherWorker.ts diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 7b980e01b5fa7..4bbc5801d2c83 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -53,6 +53,10 @@ if ( const launcherOptions = launcher?.parseServiceLauncherArgs(process.argv.slice(3)); if (launcher !== undefined && launcherOptions !== undefined) { await launcher.runServiceLauncherCli(launcherOptions); + } else if (process.argv[2] === "__process-launcher") { + // Single executables host the launcher here; other builds start process-launcher.mjs directly. + const { runProcessLauncher } = await import("./process/processLauncherWorker.ts"); + runProcessLauncher(); } else { const { runCliCommand } = await loadCliMain(); await runCliCommand(); diff --git a/apps/server/src/cli/runningServer.ts b/apps/server/src/cli/runningServer.ts index cf315ff223ae5..d077ef22889d3 100644 --- a/apps/server/src/cli/runningServer.ts +++ b/apps/server/src/cli/runningServer.ts @@ -102,7 +102,7 @@ export const changeState = Effect.fn("RunningServer.changeState")(function* Effect.Effect, ) => ServerOwnership.acquireServerOwnership(serverRuntimeStatePath).pipe( - Effect.provide(ProcessRunner.layer), + Effect.provide(ProcessRunner.layerWithSpawner), Effect.catchTags({ ServerAlreadyRunningError: ifServerRuns }), Effect.andThen(locally), // The lock proves the recorded server is gone; drop its record once the change lands. diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.ts index 303402d46c2b4..ed18616a32b90 100644 --- a/apps/server/src/cli/server.ts +++ b/apps/server/src/cli/server.ts @@ -27,7 +27,10 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* ( // Before config resolution, which claims a port and creates directories. const { runServer } = yield* Effect.promise(() => import("../server.ts")); const logLevel = yield* GlobalFlag.LogLevel; - const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer)); + // Before the server grows, so the native spawner's fork is cheap and no launcher outlives this scope. + const selectAutomaticPort = yield* AutomaticPort.make.pipe( + Effect.provide(ProcessRunner.layerWithSpawner), + ); const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort }); const run = Effect.raceFirst( runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config)), diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index fc2aa8d0889aa..a36762386ef6f 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -23,7 +23,7 @@ export const layer = (config: ServerConfig.ServerConfig["Service"]) => baseDir: config.baseDir, logsDir: config.logsDir, cliVersion: packageJson.version, - }).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(FetchHttpClient.layer)); + }).pipe(Layer.provide(ProcessRunner.layerWithSpawner), Layer.provide(FetchHttpClient.layer)); export type ServiceReconcileResult = | { @@ -362,7 +362,7 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe( const protection = status.installed && (yield* HostProcess.Platform) === "linux" ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe( - Effect.provide(ProcessRunner.layer), + Effect.provide(ProcessRunner.layerWithSpawner), ) : undefined; const commands = { @@ -487,7 +487,7 @@ const serviceProtectCommand = Command.make("protect", { ? "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`." : "Protected T3 Code's OOM score; the server takes it after `t3 service restart`. Memory protection applies once the kernel's memory controller is enabled. Undo with `t3 service protect --undo`.", ); - }).pipe(Effect.provide(ProcessRunner.layer)), + }).pipe(Effect.provide(ProcessRunner.layerWithSpawner)), ); }), ), diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index f57f1eed163f4..75b9324e8c8df 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -390,7 +390,7 @@ export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( Option.isSome(targetInfo) && targetInfo.value.type === "File" ? path.dirname(target) : target; const listed = yield* listGitCheckouts(gitDirectory).pipe( Effect.flatMap((paths) => Effect.forEach(paths, realPath)), - Effect.provide(ProcessRunner.layer), + Effect.provide(ProcessRunner.layerWithSpawner), ); const ownCheckout = listed .filter((checkout) => contains(checkout, target)) diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 07f3458fb3b66..231bf89675727 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -297,7 +297,7 @@ export const updateCommand = Command.make("update", { Effect.provide( Layer.mergeAll( CliService.layer(config), - ProcessRunner.layer, + ProcessRunner.layerWithSpawner, FetchHttpClient.layer, ManagedPolicy.layer, ), diff --git a/apps/server/src/environment/ServerEnvironmentLabel.test.ts b/apps/server/src/environment/ServerEnvironmentLabel.test.ts index 6cf235d67814b..139b7a901bcea 100644 --- a/apps/server/src/environment/ServerEnvironmentLabel.test.ts +++ b/apps/server/src/environment/ServerEnvironmentLabel.test.ts @@ -39,7 +39,7 @@ it.effect("falls back to the hostname when hostnamectl never answers", () => Effect.provide( Layer.mergeAll( FileSystem.layerNoop({ exists: () => Effect.succeed(false) }), - ProcessRunner.layer.pipe( + ProcessRunner.layerWithSpawner.pipe( Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, neverExits)), ), ), diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 1bce13cb0f020..a1e4199b2d9b2 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -720,7 +720,7 @@ function makeManager(input?: { ), ), ) - : GitVcsDriver.layer; + : GitVcsDriver.layerWithSpawner; const layerVcsDriver = (watchesGitSpawns ? Layer.fresh(gitVcsDriver) : gitVcsDriver).pipe( Layer.provide(layerGitDriverSpawner), Layer.provideMerge(VcsProcess.layer), diff --git a/apps/server/src/process-launcher.ts b/apps/server/src/process-launcher.ts new file mode 100644 index 0000000000000..7399bdc7d72ce --- /dev/null +++ b/apps/server/src/process-launcher.ts @@ -0,0 +1,3 @@ +import { runProcessLauncher } from "./process/processLauncherWorker.ts"; + +runProcessLauncher(); diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts new file mode 100644 index 0000000000000..a62ed14f708eb --- /dev/null +++ b/apps/server/src/process/ProcessLauncher.ts @@ -0,0 +1,341 @@ +// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - IPC and timer callbacks implement the spawner boundary, as in the native spawner. +import * as NodeChildProcess from "node:child_process"; +import * as NodeEvents from "node:events"; +import type * as NodeNet from "node:net"; +import type * as NodeStream from "node:stream"; +import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import * as NonBlockingSpawner from "./NonBlockingSpawner.ts"; +import type { LauncherEvent, LauncherSpawnRequest } from "./processLauncherWorker.ts"; + +// A launcher that misses either is treated as hung; neither happens to a healthy one. +const READY_TIMEOUT = "10 seconds"; +const SPAWN_REPLY_TIMEOUT = "10 seconds"; + +/** A child of the launcher, presented to the native spawner as a Node ChildProcess. */ +class HostedChild + extends NodeEvents.EventEmitter + implements NodeChildProcessSpawner.SpawnedChildProcess +{ + pid: number | undefined; + exitCode: number | null = null; + signalCode: NodeJS.Signals | null = null; + stdin: NodeStream.Writable | null = null; + stdout: NodeStream.Readable | null = null; + stderr: NodeStream.Readable | null = null; + readonly stdio: Array = []; + referenced = true; + /** Its pipes are handed over and the native spawner owns it. */ + started = false; + /** No longer awaited: its spawn failed, timed out or it exited. */ + settled = false; + readonly launcher: Launcher; + + constructor(launcher: Launcher) { + super(); + this.launcher = launcher; + } + + kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean { + if (this.pid === undefined || this.exitCode !== null || this.signalCode !== null) return false; + try { + process.kill(this.pid, signal); + return true; + } catch { + return false; + } + } + + ref(): void { + this.referenced = true; + syncRef(this.launcher); + } + + unref(): void { + this.referenced = false; + syncRef(this.launcher); + } + + fail(error: Error): void { + this.settled = true; + this.emit("error", error); + } + + exit(code: number | null, signal: NodeJS.Signals | null): void { + this.settled = true; + this.exitCode = code; + this.signalCode = signal; + // Node destroys stdin at exit and drains output nobody reads, so pipes never hold a child. + this.stdin?.destroy(); + this.emit("exit", code, signal); + process.nextTick(() => { + for (const stream of [this.stdout, this.stderr]) { + if ( + stream && + stream.listenerCount("data") === 0 && + stream.listenerCount("readable") === 0 + ) { + stream.resume(); + } + } + }); + } +} + +interface Launcher { + readonly worker: NodeChildProcess.ChildProcess; + readonly children: Map; + readonly ready: Deferred.Deferred; + closed: boolean; + /** Counts messages from the launcher, so a slow server is not mistaken for a hung launcher. */ + heard: number; +} + +const syncRef = (launcher: Launcher) => { + if ([...launcher.children.values()].some((child) => child.referenced)) { + launcher.worker.channel?.ref(); + } else { + launcher.worker.channel?.unref(); + } +}; + +const killGroup = (pid: number) => { + try { + process.kill(-pid, "SIGKILL"); + } catch { + // The group is already gone. + } +}; + +const launcherArguments = Effect.fn("ProcessLauncher.launcherArguments")(function* () { + // A single executable has no sibling script, so it hosts the launcher as a hidden subcommand. + if (yield* HostProcess.IsExecutable) return ["__process-launcher"]; + const path = yield* Path.Path; + const fromSource = import.meta.url.endsWith(".ts"); + return [ + ...(fromSource ? ["--experimental-strip-types"] : []), + yield* path + .fromFileUrl( + new URL(fromSource ? "../process-launcher.ts" : "./process-launcher.mjs", import.meta.url), + ) + .pipe(Effect.orDie), + ]; +}); + +// On Linux, libuv forks the whole server for every spawn and blocks the event loop while the +// kernel copies its page tables, so commands are launched by a small long-lived helper instead. +// The helper passes each child's pipes back, so the native spawner keeps all of its semantics. +export const make = Effect.fn("ProcessLauncher.make")(function* ( + replyTimeout: Duration.Input = SPAWN_REPLY_TIMEOUT, +) { + const fallback = yield* ChildProcessSpawner.ChildProcessSpawner; + if ((yield* HostProcess.Platform) !== "linux") return fallback; + + const executablePath = yield* HostProcess.ExecutablePath; + const args = yield* launcherArguments(); + let current: Launcher | undefined; + // A launcher that never starts will not start next time either; stop forking for it. + let unavailable = false; + let warned = false; + let shutDown = false; + let nextId = 0; + + const close = (launcher: Launcher, hung = false) => { + if (launcher.closed) return; + launcher.closed = true; + if (current === launcher) current = undefined; + const ready = Deferred.isDoneUnsafe(launcher.ready); + if (!ready) unavailable = true; + Deferred.doneUnsafe(launcher.ready, Exit.succeed(false)); + const error = new Error( + hung ? "The process launcher did not respond." : "The process launcher exited.", + ); + for (const child of launcher.children.values()) { + if (child.settled) continue; + if (child.pid !== undefined) killGroup(child.pid); + if (child.started) { + child.exit(null, "SIGKILL"); + } else { + for (const stream of child.stdio) stream?.destroy(); + child.fail(error); + } + } + launcher.children.clear(); + if (launcher.worker.connected) launcher.worker.disconnect(); + // A started launcher kills its children and exits once disconnected; a hung one never reads that. + if (hung || !ready) launcher.worker.kill("SIGKILL"); + }; + + const onEvent = ( + launcher: Launcher, + event: LauncherEvent, + socket: NodeNet.Socket | undefined, + ) => { + launcher.heard++; + if (event.type === "ready") { + Deferred.doneUnsafe(launcher.ready, Exit.succeed(true)); + return; + } + const child = launcher.children.get(event.id); + if (child === undefined) { + socket?.destroy(); + return; + } + switch (event.type) { + case "stdio": + if (child.settled) socket?.destroy(); + else if (socket) { + child.stdio[event.fd] = socket; + if (event.fd === 0) { + // Unlike Node's own stdin pipe this socket also reads, and an unread write resets it. + socket.on("error", () => {}); + child.stdin = socket; + } else if (event.fd === 1) child.stdout = socket; + else if (event.fd === 2) child.stderr = socket; + } + break; + case "pid": + child.pid = event.pid; + break; + case "spawn": + child.started = true; + child.emit("spawn"); + break; + case "exit": + launcher.children.delete(event.id); + syncRef(launcher); + if (!child.settled) child.exit(event.code, event.signal); + break; + case "error": + if (child.pid !== undefined || child.settled) break; + launcher.children.delete(event.id); + syncRef(launcher); + child.fail(Object.assign(new Error(event.error.message), event.error)); + break; + } + }; + + const launch = (): Launcher | undefined => { + if (unavailable || shutDown) return undefined; + if (current !== undefined) return current; + const env: NodeJS.ProcessEnv = { ...process.env, ELECTRON_RUN_AS_NODE: "1" }; + delete env.NODE_OPTIONS; + // `node --watch` children would report their imports over the launcher's IPC channel. + delete env.WATCH_REPORT_DEPENDENCIES; + const worker = NodeChildProcess.spawn(executablePath, args, { + cwd: "/", + env, + stdio: ["ignore", "ignore", "inherit", "ipc"], + }); + const launcher: Launcher = { + worker, + children: new Map(), + ready: Deferred.makeUnsafe(), + closed: false, + heard: 0, + }; + worker.unref(); + worker.channel?.unref(); + worker.on("message", (event: LauncherEvent, socket: NodeNet.Socket | undefined) => + onEvent(launcher, event, socket), + ); + worker.on("error", () => close(launcher)); + worker.once("disconnect", () => close(launcher)); + worker.once("exit", () => close(launcher)); + current = launcher; + return launcher; + }; + + const spawnProcess = ( + command: string, + commandArgs: ReadonlyArray, + options: NodeChildProcess.SpawnOptions, + ): NodeChildProcessSpawner.SpawnedChildProcess => { + const launcher = current; + // Lost or replaced between the readiness check and the spawn; rare enough to fork for. + if (launcher === undefined || launcher.closed || !Deferred.isDoneUnsafe(launcher.ready)) { + return NodeChildProcess.spawn(command, [...commandArgs], options); + } + const id = ++nextId; + const child = new HostedChild(launcher); + launcher.children.set(id, child); + syncRef(launcher); + const request: LauncherSpawnRequest = { + type: "spawn", + id, + command, + args: commandArgs, + // The launcher runs in `/` with its own environment; children inherit the server's. + options: { ...options, cwd: options.cwd ?? process.cwd(), env: options.env ?? process.env }, + }; + launcher.worker.send(request, (error) => { + if (error) close(launcher); + }); + // The native spawner waits for the reply uninterruptibly, so a hung launcher must not hold it. + // Hung means silent for a whole window; replies queued behind a busy server count once read. + const watch = (heard: number) => + setTimeout( + () => + setImmediate(() => { + if (child.started || child.settled) return; + if (launcher.heard === heard) close(launcher, true); + else watch(launcher.heard); + }), + Duration.toMillis(replyTimeout), + ).unref(); + watch(launcher.heard); + return child; + }; + + // The trampoline keeps a hung cwd or PATH entry from stalling the launcher, and with it every command. + // Fresh: the server has already built this layer around the forking spawner. + const hosted = Context.get( + yield* Layer.build( + Layer.fresh(NonBlockingSpawner.layer).pipe( + Layer.provide(NodeChildProcessSpawner.layerWithSpawn(spawnProcess)), + ), + ), + ChildProcessSpawner.ChildProcessSpawner, + ); + + const isReady = Effect.suspend(() => { + const launcher = launch(); + if (launcher === undefined) return Effect.succeed(false); + return Deferred.await(launcher.ready).pipe( + Effect.timeoutOption(READY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.tap((ready) => { + if (ready) return Effect.void; + close(launcher); + if (!unavailable || warned || shutDown) return Effect.void; + warned = true; + return Effect.logWarning("The process launcher did not start; commands fork the server."); + }), + ); + }); + + yield* Effect.addFinalizer(() => + Effect.sync(() => { + shutDown = true; + if (current) close(current); + }), + ); + // Start while the server is still small; the launcher's own fork is the last full-size one. + launch(); + return ChildProcessSpawner.make((command) => + Effect.flatMap(isReady, (ready) => (ready ? hosted : fallback).spawn(command)), + ); +}); + +/** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */ +export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make()); diff --git a/apps/server/src/process/processLauncherWorker.ts b/apps/server/src/process/processLauncherWorker.ts new file mode 100644 index 0000000000000..58918127d90ad --- /dev/null +++ b/apps/server/src/process/processLauncherWorker.ts @@ -0,0 +1,112 @@ +// @effect-diagnostics nodeBuiltinImport:off - the launcher loads only Node builtins so it starts in milliseconds. +import * as NodeChildProcess from "node:child_process"; +import type * as NodeNet from "node:net"; + +export interface LauncherSpawnRequest { + readonly type: "spawn"; + readonly id: number; + readonly command: string; + readonly args: ReadonlyArray; + readonly options: NodeChildProcess.SpawnOptions; +} + +export interface LauncherError { + readonly message: string; + readonly code?: string | undefined; + readonly errno?: number | undefined; + readonly syscall?: string | undefined; + readonly path?: string | undefined; +} + +/** Per child, in order: `pid`, `stdio` per piped fd (carrying its socket), `spawn`, then `exit`; or `error`. */ +export type LauncherEvent = + | { readonly type: "ready" } + | { readonly type: "pid"; readonly id: number; readonly pid: number } + | { readonly type: "stdio"; readonly id: number; readonly fd: number } + | { readonly type: "spawn"; readonly id: number } + | { + readonly type: "exit"; + readonly id: number; + readonly code: number | null; + readonly signal: NodeJS.Signals | null; + } + | { readonly type: "error"; readonly id: number; readonly error: LauncherError }; + +// Leaves out spawnargs; the server's spawner redacts its own copy. +const toLauncherError = (cause: unknown): LauncherError => { + const error = cause as Partial | undefined; + return { + message: typeof error?.message === "string" ? error.message : String(cause), + code: error?.code, + errno: error?.errno, + syscall: error?.syscall, + path: error?.path, + }; +}; + +// Child stdio has no public paused option; this is what net's pauseOnCreate does. +const stopReading = (socket: NodeNet.Socket) => + (socket as unknown as { _handle?: { readStop?: () => void } | null })._handle?.readStop?.(); + +// Bundled import.meta.main is always true; importing this module must have no side effects. +export function runProcessLauncher(): void { + const channel = process.send?.bind(process); + if (!channel) { + process.stderr.write("The process launcher is started by the T3 server.\n"); + process.exitCode = 1; + return; + } + const send = (event: LauncherEvent, socket?: NodeNet.Socket) => + channel(event, socket, undefined, () => {}); + const children = new Map(); + + // Group signals target the server; this process exits when the server's channel closes. + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => {}); + process.on("disconnect", () => { + for (const child of children.values()) { + try { + process.kill(-child.pid!, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + } + process.exit(0); + }); + + process.on("message", (request: LauncherSpawnRequest) => { + const { id } = request; + let child: NodeChildProcess.ChildProcess; + try { + child = NodeChildProcess.spawn(request.command, [...request.args], request.options); + } catch (cause) { + send({ type: "error", id, error: toLauncherError(cause) }); + return; + } + const stdio = child.stdio.map((socket) => socket as NodeNet.Socket | null); + // The server reads and writes these pipes itself, so no byte may be consumed here. + for (const socket of stdio) if (socket) stopReading(socket); + // Node flushes and destroys a child's stdio at exit, even while a socket waits to be sent. + child.stdin = null; + child.stdout = null; + child.stderr = null; + child.stdio.fill(null); + child.on("error", (cause) => { + if (child.pid === undefined) for (const socket of stdio) socket?.destroy(); + send({ type: "error", id, error: toLauncherError(cause) }); + }); + child.once("spawn", () => { + children.set(id, child); + // First, so the server can kill the child if this process dies while handing over its pipes. + send({ type: "pid", id, pid: child.pid! }); + stdio.forEach((socket, fd) => { + if (socket) send({ type: "stdio", id, fd }, socket); + }); + send({ type: "spawn", id }); + }); + child.once("exit", (code, signal) => { + children.delete(id); + send({ type: "exit", id, code, signal }); + }); + }); + send({ type: "ready" }); +} diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 6768fa23c763b..a1cd00d95b055 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -1,17 +1,28 @@ +// @effect-diagnostics nodeBuiltinImport:off - A test kills the helper mid-handoff and watches its child through a FIFO. import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodeNet from "node:net"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Cause from "effect/Cause"; +import * as FileSystem from "effect/FileSystem"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import { ChildProcessSpawner } from "effect/process"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; +import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import * as ProcessRunner from "./processRunner.ts"; type ChildProcessCommand = { @@ -72,7 +83,7 @@ const runWith = }), ), Effect.provide( - ProcessRunner.layer.pipe( + ProcessRunner.layerWithSpawner.pipe( Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), ), ), @@ -288,6 +299,278 @@ describe("runProcess", () => { ); }); +describe("ProcessRunner.layer", () => { + // Forking the server for every git call stalls its event loop in proportion to its RSS. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "launches commands from a helper process instead of forking the server", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] }); + + expect( + Number(result.stdout.trim()), + "the command's parent process is the server process itself", + ).not.toBe(process.pid); + }).pipe( + Effect.provide( + // The server's own spawner is already wrapped, as in server.ts. + ProcessRunner.layer.pipe( + Layer.provide(NonBlockingSpawner.layer), + Layer.provide(NodeServices.layer), + ), + ), + ), + ); + + // Callers report a missing CLI from the NotFound reason. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "reports a missing command as a NotFound spawn failure", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const error = yield* runner + .run({ command: "t3code-missing-command", args: [] }) + .pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound"); + }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "kills descendants that ignore SIGTERM when a run is interrupted", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const leader = yield* Deferred.make(); + const run = yield* runner + .run({ + command: "sh", + args: ["-c", `(trap "" TERM; exec sleep 1000) & echo $$; wait`], + onStdoutChunk: (chunk) => + Deferred.doneUnsafe(leader, Exit.succeed(Number(new TextDecoder().decode(chunk)))), + }) + .pipe(Effect.forkChild); + const pgid = yield* Deferred.await(leader); + yield* Fiber.interrupt(run); + + expect(() => process.kill(-pgid, 0)).toThrow(expect.objectContaining({ code: "ESRCH" })); + }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs in the server's working directory and fails stdin a command never reads", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const result = yield* runner.run({ command: "pwd", args: [] }); + const error = yield* runner + .run({ command: "true", args: [], stdin: "x".repeat(16 * 1024 * 1024) }) + .pipe(Effect.flip); + + expect(result.stdout.trim()).toBe(process.cwd()); + expect(error._tag).toBe("ProcessStdinError"); + }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "rejects a NUL byte in an environment value without echoing the value", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const error = yield* runner + .run({ command: "true", args: [], env: { T3_TOKEN: "secret\0value" } }) + .pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("BadArgument"); + expect(String(error.cause)).toContain("T3_TOKEN"); + expect(String(error.cause)).not.toContain("secret"); + }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + ); + + // Descendants keep writing after the leader exits; losing the helper must not truncate that. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "delivers output written after the helper process dies", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make("sh", [ + "-c", + `d=$(mktemp -d); mkfifo "$d/f"; (cat "$d/f"; rm -r "$d") & echo "$PPID $d/f"`, + ]), + ); + expect(yield* handle.exitCode).toBe(0); + const output = yield* handle.stdout.pipe( + Stream.tap((chunk) => { + const [helper, fifo] = new TextDecoder().decode(chunk).trim().split(" "); + if (fifo === undefined) return Effect.void; + process.kill(Number(helper), "SIGKILL"); + return fs.writeFileString(fifo, "complete\n"); + }), + Stream.decodeText(), + Stream.mkString, + ); + + expect(output).toMatch(/ \S+\ncomplete\n$/); + }).pipe( + Effect.scoped, + Effect.provide(ProcessLauncher.layer.pipe(Layer.provideMerge(NodeServices.layer))), + ), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "kills a command whose helper dies while handing over its pipes", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const fifo = `${yield* fs.makeTempDirectoryScoped()}/alive`; + NodeChildProcess.execFileSync("mkfifo", [fifo]); + // Reaches EOF once the command, its only writer, is gone. + const alive = new NodeNet.Socket({ + fd: NodeFS.openSync(fifo, NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK), + readable: true, + writable: false, + }); + const commandReady = Deferred.makeUnsafe(); + const commandGone = Deferred.makeUnsafe(); + alive.once("data", () => Deferred.doneUnsafe(commandReady, Exit.void)); + alive.once("end", () => Deferred.doneUnsafe(commandGone, Exit.void)); + + const helperPaused = Deferred.makeUnsafe(); + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + helper.on("message", (event: { readonly type: string }) => { + if (event.type !== "stdio" || Deferred.isDoneUnsafe(helperPaused)) return; + process.kill(helper.pid!, "SIGSTOP"); + Deferred.doneUnsafe(helperPaused, Exit.succeed(helper.pid!)); + }); + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get( + yield* Layer.build(ProcessRunner.layer), + ProcessRunner.ProcessRunner, + ); + const run = yield* runner + .run({ + command: "sh", + args: ["-c", `exec 3>"$0"; echo ready >&3; exec sleep 1000`, fifo], + }) + .pipe(Effect.forkChild); + const helper = yield* Deferred.await(helperPaused); + yield* Deferred.await(commandReady); + process.kill(helper, "SIGKILL"); + + expect((yield* Effect.flip(Fiber.join(run)))._tag).toBe("ProcessSpawnError"); + yield* Deferred.await(commandGone); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "replaces a helper that stops answering", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const parentPid = runner + .run({ command: "sh", args: ["-c", "echo $PPID"] }) + .pipe(Effect.map((result) => Number(result.stdout.trim()))); + const helper = yield* parentPid; + process.kill(helper, "SIGSTOP"); + const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip); + const replacement = yield* parentPid; + + expect(error._tag).toBe("ProcessSpawnError"); + expect(replacement).not.toBe(helper); + expect(replacement).not.toBe(process.pid); + }).pipe( + Effect.provide( + ProcessRunner.layerWithSpawner.pipe( + Layer.provide( + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + ProcessLauncher.make("1 second"), + ), + ), + Layer.provide(NodeServices.layer), + ), + ), + ), + ); + + // Under load the server reads the helper's replies late; that is not a hung helper. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "keeps a helper whose replies wait behind a busy server", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + let blocked = false; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + helper.on("message", (event: { readonly type: string }) => { + if (event.type !== "pid" || blocked) return; + blocked = true; + // Holds the server's event loop past the reply deadline, as a loaded server does. + NodeChildProcess.execFileSync("sleep", ["1.5"]); + }); + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get( + yield* Layer.build( + ProcessRunner.layerWithSpawner.pipe( + Layer.provide( + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + ProcessLauncher.make("1 second"), + ), + ), + ), + ), + ProcessRunner.ProcessRunner, + ); + const parentPid = runner + .run({ command: "sh", args: ["-c", "echo $PPID"] }) + .pipe(Effect.map((result) => Number(result.stdout.trim()))); + const first = yield* parentPid; + const second = yield* parentPid; + + expect(blocked).toBe(true); + expect(second).toBe(first); + expect(first).not.toBe(process.pid); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); + describe("isWindowsCommandNotFound", () => { it.effect("matches the localized German cmd.exe error text", () => Effect.gen(function* () { diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index 4c7efd3cc9942..e2e4982120cc3 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -10,6 +10,7 @@ import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import { collectUint8StreamText, decodeUtf8, @@ -406,4 +407,7 @@ export const make = Effect.fn("ProcessRunner.make")(function* () { }); }); -export const layer = Layer.effect(ProcessRunner, make()); +/** Runs commands with the ChildProcessSpawner in context, which tests replace with fakes. */ +export const layerWithSpawner = Layer.effect(ProcessRunner, make()); + +export const layer = layerWithSpawner.pipe(Layer.provide(ProcessLauncher.layer)); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 882469b57a5c0..c3b41366896a2 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -154,6 +154,22 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +// Forking the server for every git call stalls its event loop in proportion to its RSS. +it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs git from the process launcher instead of forking the server", + () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const result = yield* driver.execute({ + operation: "GitVcsDriver.test.parentPid", + cwd: process.cwd(), + args: ["-c", "alias.parent-pid=!awk '{print $4}' /proc/$PPID/stat", "parent-pid"], + }); + + assert.notStrictEqual(Number(result.stdout.trim()), process.pid); + }).pipe(Effect.provide(layerGitContract)), +); + interface UntrackedBlobChange { readonly git: Effect.Success>["git"]; readonly write: ( diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 3ba545caf97a8..ce1cd0b77a4f8 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -48,6 +48,7 @@ import { PATCH_RENDER_PREFIX_ARGS, splitNullSeparatedGitStdoutPaths, } from "./GitVcsDriverCore.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as CheckoutCloner from "./CheckoutCloner.ts"; import * as CheckpointUntrackedBlobs from "./checkpointUntrackedBlobs.ts"; import * as VcsDriver from "./VcsDriver.ts"; @@ -2605,4 +2606,9 @@ export const make = Effect.gen(function* () { }); export const layerVcs = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver); -export const layer = Layer.effect(GitVcsDriver, make).pipe(Layer.provide(CheckoutCloner.layer)); +/** Runs git with the ChildProcessSpawner in context, which tests replace with fakes. */ +export const layerWithSpawner = Layer.effect(GitVcsDriver, make).pipe( + Layer.provide(CheckoutCloner.layer), +); + +export const layer = layerWithSpawner.pipe(Layer.provide(ProcessLauncher.layer)); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b7125614c0ef7..394202fe9c4ad 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2763,7 +2763,7 @@ describe("rejected git refs", () => { const failWith = (stderr: string) => { const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeFailedHandle(stderr))); - const layer = GitVcsDriver.layer.pipe( + const layer = GitVcsDriver.layerWithSpawner.pipe( Layer.provide(layerServerConfig), Layer.provideMerge( Layer.merge( diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 2715d2987b604..2bec8830d86c5 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -110,12 +110,12 @@ export default mergeConfig( }, }, ], - // SEA embeds one entry; expose the history worker as a hidden subcommand. + // SEA embeds one entry; expose the workers as hidden subcommands. entry: packBootstrap ? ["src/bin.ts"] : packExecutable ? ["src/binMain.ts"] - : ["src/bin.ts", "src/claude-history-worker.ts"], + : ["src/bin.ts", "src/claude-history-worker.ts", "src/process-launcher.ts"], outDir: packBootstrap ? "dist-exe" : packExecutable ? cliAssetDir : "dist", sourcemap: !packExecutable, clean: true, diff --git a/knip.jsonc b/knip.jsonc index bd3228b7ac504..02ebb4bc8fecf 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -57,6 +57,7 @@ "entry": [ "src/bin.ts!", "src/claude-history-worker.ts!", + "src/process-launcher.ts!", "scripts/cli.ts", "scripts/fetch-expo-schema.ts", "scripts/probe-claude-fork-local-rollback-replay.ts", From 67924c8e6eb9825fd14ebaa2022dc8eda42d04a6 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:59:16 -0800 Subject: [PATCH 2/5] fix(server): a lost pipe handle fails the command instead of reading as no output Co-Authored-By: Claude Opus 5.5 --- apps/server/src/process/ProcessLauncher.ts | 17 ++++++- apps/server/src/processRunner.test.ts | 44 ++++++++++++++++++- .../src/project/ManagedProjectFolders.test.ts | 2 +- 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts index a62ed14f708eb..70a1b689ac968 100644 --- a/apps/server/src/process/ProcessLauncher.ts +++ b/apps/server/src/process/ProcessLauncher.ts @@ -40,10 +40,16 @@ class HostedChild /** No longer awaited: its spawn failed, timed out or it exited. */ settled = false; readonly launcher: Launcher; + /** The fds requested as pipes, each of which must arrive before the child counts as started. */ + readonly pipes: ReadonlyArray; - constructor(launcher: Launcher) { + constructor(launcher: Launcher, stdio: NodeChildProcess.SpawnOptions["stdio"]) { super(); this.launcher = launcher; + const modes = typeof stdio === "string" || stdio === undefined ? Array(3).fill(stdio) : stdio; + this.pipes = modes.flatMap((mode, fd) => + mode === undefined || mode === null || mode === "pipe" || mode === "overlapped" ? [fd] : [], + ); } kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean { @@ -208,6 +214,13 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( child.pid = event.pid; break; case "spawn": + // A lost handle would otherwise read as a command that printed nothing. + if (child.pipes.some((fd) => child.stdio[fd] == null)) { + if (child.pid !== undefined) killGroup(child.pid); + for (const stream of child.stdio) stream?.destroy(); + child.fail(new Error("The process launcher did not hand over the command's pipes.")); + break; + } child.started = true; child.emit("spawn"); break; @@ -267,7 +280,7 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( return NodeChildProcess.spawn(command, [...commandArgs], options); } const id = ++nextId; - const child = new HostedChild(launcher); + const child = new HostedChild(launcher, options.stdio); launcher.children.set(id, child); syncRef(launcher); const request: LauncherSpawnRequest = { diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index a1cd00d95b055..bec715a7a0c3b 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -348,7 +348,7 @@ describe("ProcessRunner.layer", () => { const run = yield* runner .run({ command: "sh", - args: ["-c", `(trap "" TERM; exec sleep 1000) & echo $$; wait`], + args: ["-c", `(trap "" TERM; echo $$; exec sleep 1000) & wait`], onStdoutChunk: (chunk) => Deferred.doneUnsafe(leader, Exit.succeed(Number(new TextDecoder().decode(chunk)))), }) @@ -484,6 +484,48 @@ describe("ProcessRunner.layer", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "fails a command whose output pipe never arrives instead of returning no output", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + const emit = helper.emit.bind(helper); + helper.emit = ((event: string, ...rest: Array) => { + const [message, socket] = rest as [{ type?: string; fd?: number }, NodeNet.Socket?]; + if (event !== "message" || message.type !== "stdio" || message.fd !== 1) { + return emit(event, ...rest); + } + socket?.destroy(); + return emit(event, message, undefined); + }) as typeof helper.emit; + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get( + yield* Layer.build(ProcessRunner.layer), + ProcessRunner.ProcessRunner, + ); + + const error = yield* runner.run({ command: "echo", args: ["output"] }).pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( "replaces a helper that stops answering", () => diff --git a/apps/server/src/project/ManagedProjectFolders.test.ts b/apps/server/src/project/ManagedProjectFolders.test.ts index 07da49c732539..fdb94791adff3 100644 --- a/apps/server/src/project/ManagedProjectFolders.test.ts +++ b/apps/server/src/project/ManagedProjectFolders.test.ts @@ -543,7 +543,7 @@ it.effect("says Git is not installed when a named project cannot start Git", () ); }), { - git: GitVcsDriver.layer.pipe( + git: GitVcsDriver.layerWithSpawner.pipe( Layer.provide( Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, From b8a2836b41a7228862cfb9b4756fe6e7c54ae7de Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:53:31 -0800 Subject: [PATCH 3/5] refactor(server): the process launcher is the server's one spawner ProcessRunner.layer and GitVcsDriver.layer each provided the launcher themselves, so the split layerWithSpawner existed for tests and one-shot CLI commands, and a layer provided inside a service could build its own. server.ts now provides ProcessLauncher.layerServer wherever it provides its spawner; both layers go back to using the spawner in context, which CLI commands leave native. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/cli/runningServer.ts | 2 +- apps/server/src/cli/server.ts | 5 +-- apps/server/src/cli/service.ts | 6 +-- apps/server/src/cli/thread.ts | 2 +- apps/server/src/cli/update.ts | 2 +- .../ServerEnvironmentLabel.test.ts | 2 +- apps/server/src/git/GitManager.test.ts | 2 +- apps/server/src/process/ProcessLauncher.ts | 3 ++ apps/server/src/processRunner.test.ts | 38 +++++++------------ apps/server/src/processRunner.ts | 6 +-- .../src/project/ManagedProjectFolders.test.ts | 2 +- apps/server/src/server.ts | 10 +++-- apps/server/src/vcs/GitVcsDriver.test.ts | 13 ++++++- apps/server/src/vcs/GitVcsDriver.ts | 8 +--- apps/server/src/vcs/GitVcsDriverCore.test.ts | 2 +- 15 files changed, 47 insertions(+), 56 deletions(-) diff --git a/apps/server/src/cli/runningServer.ts b/apps/server/src/cli/runningServer.ts index d077ef22889d3..cf315ff223ae5 100644 --- a/apps/server/src/cli/runningServer.ts +++ b/apps/server/src/cli/runningServer.ts @@ -102,7 +102,7 @@ export const changeState = Effect.fn("RunningServer.changeState")(function* Effect.Effect, ) => ServerOwnership.acquireServerOwnership(serverRuntimeStatePath).pipe( - Effect.provide(ProcessRunner.layerWithSpawner), + Effect.provide(ProcessRunner.layer), Effect.catchTags({ ServerAlreadyRunningError: ifServerRuns }), Effect.andThen(locally), // The lock proves the recorded server is gone; drop its record once the change lands. diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.ts index ed18616a32b90..303402d46c2b4 100644 --- a/apps/server/src/cli/server.ts +++ b/apps/server/src/cli/server.ts @@ -27,10 +27,7 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* ( // Before config resolution, which claims a port and creates directories. const { runServer } = yield* Effect.promise(() => import("../server.ts")); const logLevel = yield* GlobalFlag.LogLevel; - // Before the server grows, so the native spawner's fork is cheap and no launcher outlives this scope. - const selectAutomaticPort = yield* AutomaticPort.make.pipe( - Effect.provide(ProcessRunner.layerWithSpawner), - ); + const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer)); const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort }); const run = Effect.raceFirst( runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config)), diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index a36762386ef6f..fc2aa8d0889aa 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -23,7 +23,7 @@ export const layer = (config: ServerConfig.ServerConfig["Service"]) => baseDir: config.baseDir, logsDir: config.logsDir, cliVersion: packageJson.version, - }).pipe(Layer.provide(ProcessRunner.layerWithSpawner), Layer.provide(FetchHttpClient.layer)); + }).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(FetchHttpClient.layer)); export type ServiceReconcileResult = | { @@ -362,7 +362,7 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe( const protection = status.installed && (yield* HostProcess.Platform) === "linux" ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe( - Effect.provide(ProcessRunner.layerWithSpawner), + Effect.provide(ProcessRunner.layer), ) : undefined; const commands = { @@ -487,7 +487,7 @@ const serviceProtectCommand = Command.make("protect", { ? "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`." : "Protected T3 Code's OOM score; the server takes it after `t3 service restart`. Memory protection applies once the kernel's memory controller is enabled. Undo with `t3 service protect --undo`.", ); - }).pipe(Effect.provide(ProcessRunner.layerWithSpawner)), + }).pipe(Effect.provide(ProcessRunner.layer)), ); }), ), diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 75b9324e8c8df..f57f1eed163f4 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -390,7 +390,7 @@ export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( Option.isSome(targetInfo) && targetInfo.value.type === "File" ? path.dirname(target) : target; const listed = yield* listGitCheckouts(gitDirectory).pipe( Effect.flatMap((paths) => Effect.forEach(paths, realPath)), - Effect.provide(ProcessRunner.layerWithSpawner), + Effect.provide(ProcessRunner.layer), ); const ownCheckout = listed .filter((checkout) => contains(checkout, target)) diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 231bf89675727..07f3458fb3b66 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -297,7 +297,7 @@ export const updateCommand = Command.make("update", { Effect.provide( Layer.mergeAll( CliService.layer(config), - ProcessRunner.layerWithSpawner, + ProcessRunner.layer, FetchHttpClient.layer, ManagedPolicy.layer, ), diff --git a/apps/server/src/environment/ServerEnvironmentLabel.test.ts b/apps/server/src/environment/ServerEnvironmentLabel.test.ts index 139b7a901bcea..6cf235d67814b 100644 --- a/apps/server/src/environment/ServerEnvironmentLabel.test.ts +++ b/apps/server/src/environment/ServerEnvironmentLabel.test.ts @@ -39,7 +39,7 @@ it.effect("falls back to the hostname when hostnamectl never answers", () => Effect.provide( Layer.mergeAll( FileSystem.layerNoop({ exists: () => Effect.succeed(false) }), - ProcessRunner.layerWithSpawner.pipe( + ProcessRunner.layer.pipe( Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, neverExits)), ), ), diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index a1e4199b2d9b2..1bce13cb0f020 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -720,7 +720,7 @@ function makeManager(input?: { ), ), ) - : GitVcsDriver.layerWithSpawner; + : GitVcsDriver.layer; const layerVcsDriver = (watchesGitSpawns ? Layer.fresh(gitVcsDriver) : gitVcsDriver).pipe( Layer.provide(layerGitDriverSpawner), Layer.provideMerge(VcsProcess.layer), diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts index 70a1b689ac968..29479a78d7364 100644 --- a/apps/server/src/process/ProcessLauncher.ts +++ b/apps/server/src/process/ProcessLauncher.ts @@ -352,3 +352,6 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( /** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */ export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make()); + +/** The server's one spawner: memoized, so every build site shares a single launcher. */ +export const layerServer = layer.pipe(Layer.provide(NonBlockingSpawner.layer)); diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index bec715a7a0c3b..61c3305622783 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -21,7 +21,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; -import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import * as ProcessRunner from "./processRunner.ts"; @@ -83,7 +82,7 @@ const runWith = }), ), Effect.provide( - ProcessRunner.layerWithSpawner.pipe( + ProcessRunner.layer.pipe( Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), ), ), @@ -299,6 +298,9 @@ describe("runProcess", () => { ); }); +// The server's spawner stack, as server.ts builds it. +const layerLaunched = ProcessRunner.layer.pipe(Layer.provide(ProcessLauncher.layerServer)); + describe("ProcessRunner.layer", () => { // Forking the server for every git call stalls its event loop in proportion to its RSS. it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( @@ -312,15 +314,7 @@ describe("ProcessRunner.layer", () => { Number(result.stdout.trim()), "the command's parent process is the server process itself", ).not.toBe(process.pid); - }).pipe( - Effect.provide( - // The server's own spawner is already wrapped, as in server.ts. - ProcessRunner.layer.pipe( - Layer.provide(NonBlockingSpawner.layer), - Layer.provide(NodeServices.layer), - ), - ), - ), + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), ); // Callers report a missing CLI from the NotFound reason. @@ -336,7 +330,7 @@ describe("ProcessRunner.layer", () => { expect(error._tag).toBe("ProcessSpawnError"); expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound"); - }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), ); it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( @@ -357,7 +351,7 @@ describe("ProcessRunner.layer", () => { yield* Fiber.interrupt(run); expect(() => process.kill(-pgid, 0)).toThrow(expect.objectContaining({ code: "ESRCH" })); - }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), ); it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( @@ -372,7 +366,7 @@ describe("ProcessRunner.layer", () => { expect(result.stdout.trim()).toBe(process.cwd()); expect(error._tag).toBe("ProcessStdinError"); - }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), ); it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( @@ -388,7 +382,7 @@ describe("ProcessRunner.layer", () => { expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("BadArgument"); expect(String(error.cause)).toContain("T3_TOKEN"); expect(String(error.cause)).not.toContain("secret"); - }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)))), + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), ); // Descendants keep writing after the leader exits; losing the helper must not truncate that. @@ -465,10 +459,7 @@ describe("ProcessRunner.layer", () => { NodeModule.syncBuiltinESMExports(); }), ); - const runner = Context.get( - yield* Layer.build(ProcessRunner.layer), - ProcessRunner.ProcessRunner, - ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); const run = yield* runner .run({ command: "sh", @@ -515,10 +506,7 @@ describe("ProcessRunner.layer", () => { NodeModule.syncBuiltinESMExports(); }), ); - const runner = Context.get( - yield* Layer.build(ProcessRunner.layer), - ProcessRunner.ProcessRunner, - ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); const error = yield* runner.run({ command: "echo", args: ["output"] }).pipe(Effect.flip); @@ -544,7 +532,7 @@ describe("ProcessRunner.layer", () => { expect(replacement).not.toBe(process.pid); }).pipe( Effect.provide( - ProcessRunner.layerWithSpawner.pipe( + ProcessRunner.layer.pipe( Layer.provide( Layer.effect( ChildProcessSpawner.ChildProcessSpawner, @@ -589,7 +577,7 @@ describe("ProcessRunner.layer", () => { ); const runner = Context.get( yield* Layer.build( - ProcessRunner.layerWithSpawner.pipe( + ProcessRunner.layer.pipe( Layer.provide( Layer.effect( ChildProcessSpawner.ChildProcessSpawner, diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index e2e4982120cc3..4c7efd3cc9942 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -10,7 +10,6 @@ import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; -import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import { collectUint8StreamText, decodeUtf8, @@ -407,7 +406,4 @@ export const make = Effect.fn("ProcessRunner.make")(function* () { }); }); -/** Runs commands with the ChildProcessSpawner in context, which tests replace with fakes. */ -export const layerWithSpawner = Layer.effect(ProcessRunner, make()); - -export const layer = layerWithSpawner.pipe(Layer.provide(ProcessLauncher.layer)); +export const layer = Layer.effect(ProcessRunner, make()); diff --git a/apps/server/src/project/ManagedProjectFolders.test.ts b/apps/server/src/project/ManagedProjectFolders.test.ts index fdb94791adff3..07da49c732539 100644 --- a/apps/server/src/project/ManagedProjectFolders.test.ts +++ b/apps/server/src/project/ManagedProjectFolders.test.ts @@ -543,7 +543,7 @@ it.effect("says Git is not installed when a named project cannot start Git", () ); }), { - git: GitVcsDriver.layerWithSpawner.pipe( + git: GitVcsDriver.layer.pipe( Layer.provide( Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 499c1e2acc0ca..26cea18609b93 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -33,7 +33,6 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; -import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; import * as KeepAwake from "./background/KeepAwake.ts"; import * as ServerConfig from "./config.ts"; import { withRootRequestSpans, withUntracedRequests } from "./http.ts"; @@ -48,6 +47,7 @@ import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; +import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import * as SpawnWorker from "./process/SpawnWorker.ts"; import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts"; import * as PullRequestHttp from "./pullRequest/http.ts"; @@ -410,11 +410,11 @@ const layerHttpServer = Layer.unwrap( ).pipe( Layer.provide(ManagedPolicy.layer), // NodeHttpServer.layer also outputs NodeServices, whose spawner would shadow the wrapped one. - (layer) => NonBlockingSpawner.layer.pipe(Layer.provideMerge(layer)), + (layer) => ProcessLauncher.layerServer.pipe(Layer.provideMerge(layer)), ); const layerPlatformServices = DocumentText.layer.pipe( - Layer.provideMerge(NonBlockingSpawner.layer), + Layer.provideMerge(ProcessLauncher.layerServer), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner)), ); @@ -1436,5 +1436,7 @@ const layerMakeServer = Layer.unwrap( export const runServer = Layer.launch( // For the layers above whose spawner requirement is not met by one of them. - layerMakeServer.pipe(Layer.provide(NonBlockingSpawner.layer.pipe(Layer.provide(layerSpawner)))), + layerMakeServer.pipe( + Layer.provide(ProcessLauncher.layerServer.pipe(Layer.provide(layerSpawner))), + ), ); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index c3b41366896a2..13bbe6ecc9cc4 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -25,6 +25,7 @@ import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as ServerConfig from "../config.ts"; import { gitCommandDuration, gitCommandsTotal } from "../observability/Metrics.ts"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; import type * as VcsDriver from "./VcsDriver.ts"; @@ -167,7 +168,17 @@ it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( }); assert.notStrictEqual(Number(result.stdout.trim()), process.pid); - }).pipe(Effect.provide(layerGitContract)), + }).pipe( + Effect.provide( + GitVcsDriver.layer.pipe( + Layer.provide(layerServerConfig), + Layer.provideMerge(VcsProcess.layer), + // The server's spawner stack, as server.ts builds it. + Layer.provide(ProcessLauncher.layerServer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), ); interface UntrackedBlobChange { diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index ce1cd0b77a4f8..3ba545caf97a8 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -48,7 +48,6 @@ import { PATCH_RENDER_PREFIX_ARGS, splitNullSeparatedGitStdoutPaths, } from "./GitVcsDriverCore.ts"; -import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as CheckoutCloner from "./CheckoutCloner.ts"; import * as CheckpointUntrackedBlobs from "./checkpointUntrackedBlobs.ts"; import * as VcsDriver from "./VcsDriver.ts"; @@ -2606,9 +2605,4 @@ export const make = Effect.gen(function* () { }); export const layerVcs = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver); -/** Runs git with the ChildProcessSpawner in context, which tests replace with fakes. */ -export const layerWithSpawner = Layer.effect(GitVcsDriver, make).pipe( - Layer.provide(CheckoutCloner.layer), -); - -export const layer = layerWithSpawner.pipe(Layer.provide(ProcessLauncher.layer)); +export const layer = Layer.effect(GitVcsDriver, make).pipe(Layer.provide(CheckoutCloner.layer)); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 394202fe9c4ad..b7125614c0ef7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2763,7 +2763,7 @@ describe("rejected git refs", () => { const failWith = (stderr: string) => { const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeFailedHandle(stderr))); - const layer = GitVcsDriver.layerWithSpawner.pipe( + const layer = GitVcsDriver.layer.pipe( Layer.provide(layerServerConfig), Layer.provideMerge( Layer.merge( From 8fb0c4e7a0cde719c04a81c9fd5ce55a92711fdd Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:19:56 -0800 Subject: [PATCH 4/5] fix(server): a launcher that cannot spawn, or a command that inherits stdio, uses the native spawner Node throws some spawn errnos instead of emitting "error", which failed the server layer while the launcher started. Inherited stdio resolved against the launcher's /dev/null instead of the server's streams (sudo in runPrivileged). Tests now check that a killed descendant stopped rather than was reaped, and that a parent PID is a real helper before signalling it. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/process/ProcessLauncher.ts | 51 ++++++++---- apps/server/src/processRunner.test.ts | 91 ++++++++++++++++++---- apps/server/src/vcs/GitVcsDriver.test.ts | 1 + 3 files changed, 116 insertions(+), 27 deletions(-) diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts index 29479a78d7364..f62a3c8445da2 100644 --- a/apps/server/src/process/ProcessLauncher.ts +++ b/apps/server/src/process/ProcessLauncher.ts @@ -46,10 +46,7 @@ class HostedChild constructor(launcher: Launcher, stdio: NodeChildProcess.SpawnOptions["stdio"]) { super(); this.launcher = launcher; - const modes = typeof stdio === "string" || stdio === undefined ? Array(3).fill(stdio) : stdio; - this.pipes = modes.flatMap((mode, fd) => - mode === undefined || mode === null || mode === "pipe" || mode === "overlapped" ? [fd] : [], - ); + this.pipes = stdioModes(stdio).flatMap((mode, fd) => (isPipe(mode) ? [fd] : [])); } kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean { @@ -98,6 +95,16 @@ class HostedChild } } +const stdioModes = (stdio: NodeChildProcess.SpawnOptions["stdio"]) => + typeof stdio === "string" || stdio === undefined ? Array(3).fill(stdio) : stdio; + +const isPipe = (mode: unknown) => + mode === undefined || mode === null || mode === "pipe" || mode === "overlapped"; + +// The launcher's own stdin and stdout are /dev/null, so only pipes and "ignore" mean the same there. +const isHostable = (stdio: NodeChildProcess.SpawnOptions["stdio"]) => + stdioModes(stdio).every((mode) => isPipe(mode) || mode === "ignore"); + interface Launcher { readonly worker: NodeChildProcess.ChildProcess; readonly children: Map; @@ -245,11 +252,18 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( delete env.NODE_OPTIONS; // `node --watch` children would report their imports over the launcher's IPC channel. delete env.WATCH_REPORT_DEPENDENCIES; - const worker = NodeChildProcess.spawn(executablePath, args, { - cwd: "/", - env, - stdio: ["ignore", "ignore", "inherit", "ipc"], - }); + let worker: NodeChildProcess.ChildProcess; + try { + worker = NodeChildProcess.spawn(executablePath, args, { + cwd: "/", + env, + stdio: ["ignore", "ignore", "inherit", "ipc"], + }); + } catch { + // Node throws some errnos, such as ENOMEM, instead of emitting "error". + unavailable = true; + return undefined; + } const launcher: Launcher = { worker, children: new Map(), @@ -276,7 +290,12 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( ): NodeChildProcessSpawner.SpawnedChildProcess => { const launcher = current; // Lost or replaced between the readiness check and the spawn; rare enough to fork for. - if (launcher === undefined || launcher.closed || !Deferred.isDoneUnsafe(launcher.ready)) { + if ( + launcher === undefined || + launcher.closed || + !Deferred.isDoneUnsafe(launcher.ready) || + !isHostable(options.stdio) + ) { return NodeChildProcess.spawn(command, [...commandArgs], options); } const id = ++nextId; @@ -321,18 +340,22 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( ChildProcessSpawner.ChildProcessSpawner, ); + const warnUnavailable = Effect.suspend(() => { + if (!unavailable || warned || shutDown) return Effect.void; + warned = true; + return Effect.logWarning("The process launcher did not start; commands fork the server."); + }); + const isReady = Effect.suspend(() => { const launcher = launch(); - if (launcher === undefined) return Effect.succeed(false); + if (launcher === undefined) return Effect.as(warnUnavailable, false); return Deferred.await(launcher.ready).pipe( Effect.timeoutOption(READY_TIMEOUT), Effect.map(Option.getOrElse(() => false)), Effect.tap((ready) => { if (ready) return Effect.void; close(launcher); - if (!unavailable || warned || shutDown) return Effect.void; - warned = true; - return Effect.logWarning("The process launcher did not start; commands fork the server."); + return warnUnavailable; }), ); }); diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 61c3305622783..e2acb8e5faefd 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -301,6 +301,14 @@ describe("runProcess", () => { // The server's spawner stack, as server.ts builds it. const layerLaunched = ProcessRunner.layer.pipe(Layer.provide(ProcessLauncher.layerServer)); +// A command's $PPID, required to be the helper: signalling a fallback's parent would hit the test runner. +const expectHelperPid = (stdout: string) => { + expect(stdout.trim()).toMatch(/^[1-9]\d*$/); + const pid = Number(stdout.trim()); + expect(pid, "the command's parent process is the server process itself").not.toBe(process.pid); + return pid; +}; + describe("ProcessRunner.layer", () => { // Forking the server for every git call stalls its event loop in proportion to its RSS. it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( @@ -310,13 +318,64 @@ describe("ProcessRunner.layer", () => { const runner = yield* ProcessRunner.ProcessRunner; const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] }); - expect( - Number(result.stdout.trim()), - "the command's parent process is the server process itself", - ).not.toBe(process.pid); + expectHelperPid(result.stdout); }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), ); + // The helper's stdin and stdout are /dev/null, so inherited stdio must come from the server. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "forks the server for a command that inherits its stdio", + () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make("sh", ["-c", "echo $PPID >&2"], { stdin: "inherit" }), + ); + const parent = yield* handle.stderr.pipe(Stream.decodeText(), Stream.mkString); + + expect(Number(parent.trim())).toBe(process.pid); + }).pipe( + Effect.scoped, + Effect.provide(ProcessLauncher.layerServer.pipe(Layer.provideMerge(NodeServices.layer))), + ), + ); + + // Node throws some spawn errnos, such as ENOMEM, instead of emitting "error". + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs commands natively when starting the helper throws", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const launcherArgs = args[1]; + if ( + Array.isArray(launcherArgs) && + launcherArgs.some((arg) => String(arg).includes("process-launcher")) + ) { + throw Object.assign(new Error("spawn ENOMEM"), { code: "ENOMEM" }); + } + return spawn(...args); + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); + const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] }); + + expect(Number(result.stdout.trim())).toBe(process.pid); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + // Callers report a missing CLI from the NotFound reason. it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( "reports a missing command as a NotFound spawn failure", @@ -337,21 +396,27 @@ describe("ProcessRunner.layer", () => { "kills descendants that ignore SIGTERM when a run is interrupted", () => Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; const runner = yield* ProcessRunner.ProcessRunner; - const leader = yield* Deferred.make(); + const started = yield* Deferred.make(); const run = yield* runner .run({ command: "sh", - args: ["-c", `(trap "" TERM; echo $$; exec sleep 1000) & wait`], + args: ["-c", `(trap "" TERM; exec sleep 1000) & echo $!; wait`], onStdoutChunk: (chunk) => - Deferred.doneUnsafe(leader, Exit.succeed(Number(new TextDecoder().decode(chunk)))), + Deferred.doneUnsafe(started, Exit.succeed(Number(new TextDecoder().decode(chunk)))), }) .pipe(Effect.forkChild); - const pgid = yield* Deferred.await(leader); + const descendant = yield* Deferred.await(started); yield* Fiber.interrupt(run); + // A killed process stays a zombie until reaped, and a PID namespace's init may never reap it. + const state = yield* fs.readFileString(`/proc/${descendant}/stat`).pipe( + Effect.map((stat) => stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0]), + Effect.orElseSucceed(() => "gone"), + ); - expect(() => process.kill(-pgid, 0)).toThrow(expect.objectContaining({ code: "ESRCH" })); - }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + expect(["gone", "Z"]).toContain(state); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provideMerge(NodeServices.layer)))), ); it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( @@ -401,9 +466,9 @@ describe("ProcessRunner.layer", () => { expect(yield* handle.exitCode).toBe(0); const output = yield* handle.stdout.pipe( Stream.tap((chunk) => { - const [helper, fifo] = new TextDecoder().decode(chunk).trim().split(" "); + const [helper = "", fifo] = new TextDecoder().decode(chunk).trim().split(" "); if (fifo === undefined) return Effect.void; - process.kill(Number(helper), "SIGKILL"); + process.kill(expectHelperPid(helper), "SIGKILL"); return fs.writeFileString(fifo, "complete\n"); }), Stream.decodeText(), @@ -521,7 +586,7 @@ describe("ProcessRunner.layer", () => { const runner = yield* ProcessRunner.ProcessRunner; const parentPid = runner .run({ command: "sh", args: ["-c", "echo $PPID"] }) - .pipe(Effect.map((result) => Number(result.stdout.trim()))); + .pipe(Effect.map((result) => expectHelperPid(result.stdout))); const helper = yield* parentPid; process.kill(helper, "SIGSTOP"); const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 13bbe6ecc9cc4..c3b5d4143086b 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -167,6 +167,7 @@ it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( args: ["-c", "alias.parent-pid=!awk '{print $4}' /proc/$PPID/stat", "parent-pid"], }); + assert.match(result.stdout.trim(), /^[1-9]\d*$/); assert.notStrictEqual(Number(result.stdout.trim()), process.pid); }).pipe( Effect.provide( From 17a7d03833faf9068946303fe7b2bd70477cb690 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:29:49 -0800 Subject: [PATCH 5/5] test(server): the descendant-kill test waits for the trap, and every helper probe checks its pid Co-Authored-By: Claude Opus 5.5 --- apps/server/src/processRunner.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index e2acb8e5faefd..bd4ad037defa6 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -402,12 +402,20 @@ describe("ProcessRunner.layer", () => { const run = yield* runner .run({ command: "sh", - args: ["-c", `(trap "" TERM; exec sleep 1000) & echo $!; wait`], + // The descendant prints its pid only once it ignores SIGTERM. + args: ["-c", `sh -c 'trap "" TERM; echo $$; exec sleep 1000' & wait`], onStdoutChunk: (chunk) => Deferred.doneUnsafe(started, Exit.succeed(Number(new TextDecoder().decode(chunk)))), }) .pipe(Effect.forkChild); const descendant = yield* Deferred.await(started); + const ignored = (yield* fs.readFileString(`/proc/${descendant}/status`)).match( + /^SigIgn:\s*([0-9a-f]+)$/m, + )?.[1]; + expect( + BigInt(`0x${ignored ?? "0"}`) & (1n << 14n), + "the descendant ignores SIGTERM", + ).not.toBe(0n); yield* Fiber.interrupt(run); // A killed process stays a zombie until reaped, and a PID namespace's init may never reap it. const state = yield* fs.readFileString(`/proc/${descendant}/stat`).pipe( @@ -655,13 +663,12 @@ describe("ProcessRunner.layer", () => { ); const parentPid = runner .run({ command: "sh", args: ["-c", "echo $PPID"] }) - .pipe(Effect.map((result) => Number(result.stdout.trim()))); + .pipe(Effect.map((result) => expectHelperPid(result.stdout))); const first = yield* parentPid; const second = yield* parentPid; expect(blocked).toBe(true); expect(second).toBe(first); - expect(first).not.toBe(process.pid); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); });