fix(server): stop jobs a Claude CLI moved out of its process group when the session closes #34505
Mergedjuliusmarmingemerged 0 commits into
main fromrefs/pull/34505/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -1170,3 +1227,9 @@11701227 const runFork = Effect.runForkWith(yield* Effect.context<never>());11711228 const hostEnvironment = yield* HostProcess.Environment;11721229 const portDiscovery = yield* PortScanner.PortDiscovery;1230+ const processRunner = yield* ProcessRunner.make();1231+ const readProcessTable = processRunner1232+ .run({ command: "ps", args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="], timeout: "5 seconds" })1233+ .pipe(1234+ Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),1235+ Effect.orElseSucceed(() => []),@@ -1237,8 +1330,20 @@12371330 const spawnProcess =12381331 options.spawnClaudeCodeProcess ??12391332 ((spawnOptions: ClaudeSpawnOptions) => {12401333 if (platform !== "win32") {12411334 // Node can report "exit" before it has read the stderr the CLI wrote.12421335 let stderrDone = () => {};12431336 stderrClosed = new Promise((resolve) => (stderrDone = resolve));1244- return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone);1337+ const child = spawnClaudeProcessGroup(1338+ spawnOptions,1339+ stopScope,1340+ appendStderr,1341+ stderrDone,1342+ );1343+ if (unit === undefined && child.pid !== undefined) {1344+ const tracker = trackDescendants(child.pid);1345+ const polling = runFork(1346+ tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),1347+ );1348+ child.once("exit", () =>1349+ runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),@@ -581,0 +603,21 @@603+ const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));604+ const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));605+ const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));606+ alive.resume();607+608+ const session = yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner));609+ yield* Effect.promise(() => leftoverStarted);610+ yield* session.close;611+ yield* Effect.promise(() => leftoverStopped);612+ }),613+ );614+615+ // Live clock: the job is found by polling while the CLI runs, and the CLI exits on its own.616+ it.live("stops a job the CLI started in its own process group when the CLI exits", () =>617+ Effect.gen(function* () {618+ const cli = fakeClaudeCli(619+ [620+ 'dir=$(dirname "$0")',621+ `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`,622+ 'echo $! > "$dir/leftover.pid"',623+ "sleep 3",
- @@ -1191,3 +1248,6 @@11911248 const runFork = Effect.runForkWith(yield* Effect.context<never>());11921249 const hostEnvironment = yield* HostProcess.Environment;11931250 const portDiscovery = yield* PortScanner.PortDiscovery;1251+ const processRunner = yield* ProcessRunner.make();1252+ const readProcessTable = processRunner1253+ .run({ command: "ps", args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="], timeout: "5 seconds" })@@ -1193,0 +1252,21 @@1252+ const readProcessTable = processRunner1253+ .run({ command: "ps", args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="], timeout: "5 seconds" })1254+ .pipe(1255+ Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),1256+ Effect.orElseSucceed(() => []),1257+ );1258+ // Without an agent scope, a job that left the CLI's group escapes the group kill and is1259+ // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is1260+ // still the same process (pid and start time) is stopped after it exits.1261+ const trackDescendants = (cliPid: number) => {1262+ const tracked = new Map<string, ClaudeProcessRow>();1263+ const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;1264+ // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.1265+ const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")(function* (1266+ cliRunning: boolean,1267+ ) {1268+ const rows = yield* readProcessTable;1269+ const running = new Set(rows.map(identity));1270+ const roots = [1271+ ...(cliRunning ? [cliPid] : []),1272+ ...[...tracked.values()].flatMap((row) => (running.has(identity(row)) ? [row.pid] : [])),
tanstack-source added labelsbug
juliusmarminge merged thisfdd54b9
juliusmarminge closed this
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes