Skip to content

Commit 4d233b1

Browse files
fix(server): stop escaped Claude jobs when the CLI exits on its own
Descendants were recorded only when a session closed, so a CLI that exited by itself still left a job in its own process group running. Without an agent scope, the CLI's process tree is now recorded every second while it runs and again at close, and whatever is still the same process (pid and start time) is killed on any CLI exit. Fixes #34459 AI-assisted; verified with the tests and tools listed above.
1 parent 3d37b31 commit 4d233b1

2 files changed

Lines changed: 77 additions & 27 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ import * as Effect from "effect/Effect";
145145
import * as Equal from "effect/Equal";
146146
import * as Exit from "effect/Exit";
147147
import * as Fiber from "effect/Fiber";
148+
import * as Schedule from "effect/Schedule";
148149
import * as FileSystem from "effect/FileSystem";
149150
import * as Layer from "effect/Layer";
150151
import * as Option from "effect/Option";
@@ -358,6 +359,8 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
358359
const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
359360
// The process group is killed on exit, so its stderr closes promptly.
360361
const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
362+
// How often the CLI's process tree is recorded when no agent scope will stop what it leaves.
363+
const CLAUDE_DESCENDANT_POLL = "1 second";
361364
// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
362365
const CLAUDE_ROOT_REFUSAL =
363366
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
@@ -437,12 +440,12 @@ function killClaudeDescendant(row: ClaudeProcessRow) {
437440

438441
function claudeDescendants(
439442
rows: ReadonlyArray<ClaudeProcessRow>,
440-
rootPid: number,
443+
rootPids: ReadonlyArray<number>,
441444
): ReadonlyArray<ClaudeProcessRow> {
442445
const children = Map.groupBy(rows, (row) => row.ppid);
443446
const found: Array<ClaudeProcessRow> = [];
444-
const seen = new Set<number>([rootPid]);
445-
const pending = [rootPid];
447+
const seen = new Set<number>(rootPids);
448+
const pending = [...rootPids];
446449
for (let parent = pending.pop(); parent !== undefined; parent = pending.pop()) {
447450
for (const child of children.get(parent) ?? []) {
448451
if (seen.has(child.pid)) continue;
@@ -1231,18 +1234,34 @@ export const layerQueryRunner: Layer.Layer<
12311234
Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),
12321235
Effect.orElseSucceed(() => []),
12331236
);
1234-
// A job that left the CLI's group escapes the group kill and is re-parented once the CLI
1235-
// exits, so it is found while the CLI runs and stopped after it exits, if still the same process.
1236-
const stopAfterExit = Effect.fn("ClaudeAgentSdkQueryRunner.stopAfterExit")(function* (
1237-
descendants: ReadonlyArray<ClaudeProcessRow>,
1238-
exited: Promise<void>,
1239-
) {
1240-
yield* Effect.promise(() => exited);
1241-
const running = new Set((yield* readProcessTable).map((row) => `${row.pid} ${row.started}`));
1242-
for (const row of descendants) {
1243-
if (running.has(`${row.pid} ${row.started}`)) killClaudeDescendant(row);
1244-
}
1245-
});
1237+
// Without an agent scope, a job that left the CLI's group escapes the group kill and is
1238+
// re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is
1239+
// still the same process (pid and start time) is stopped after it exits.
1240+
const trackDescendants = (cliPid: number) => {
1241+
const tracked = new Map<string, ClaudeProcessRow>();
1242+
const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;
1243+
// After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
1244+
const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")(function* (
1245+
cliRunning: boolean,
1246+
) {
1247+
const rows = yield* readProcessTable;
1248+
const running = new Set(rows.map(identity));
1249+
const roots = [
1250+
...(cliRunning ? [cliPid] : []),
1251+
...[...tracked.values()].flatMap((row) => (running.has(identity(row)) ? [row.pid] : [])),
1252+
];
1253+
for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row);
1254+
return running;
1255+
});
1256+
const stop = refresh(false).pipe(
1257+
Effect.map((running) => {
1258+
for (const row of tracked.values()) {
1259+
if (running.has(identity(row))) killClaudeDescendant(row);
1260+
}
1261+
}),
1262+
);
1263+
return { refresh: refresh(true).pipe(Effect.asVoid), stop };
1264+
};
12461265

12471266
return ClaudeAgentSdkQueryRunner.of({
12481267
allocateSessionId: random.uuidV4(),
@@ -1307,7 +1326,7 @@ export const layerQueryRunner: Layer.Layer<
13071326
if (answered) return;
13081327
stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
13091328
};
1310-
let cliPid: number | undefined;
1329+
let refreshDescendants: Effect.Effect<void> = Effect.void;
13111330
const spawnProcess =
13121331
options.spawnClaudeCodeProcess ??
13131332
((spawnOptions: ClaudeSpawnOptions) => {
@@ -1321,7 +1340,16 @@ export const layerQueryRunner: Layer.Layer<
13211340
appendStderr,
13221341
stderrDone,
13231342
);
1324-
cliPid = child.pid;
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))),
1350+
);
1351+
refreshDescendants = tracker.refresh;
1352+
}
13251353
return child;
13261354
}
13271355
const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
@@ -1617,16 +1645,8 @@ export const layerQueryRunner: Layer.Layer<
16171645
}),
16181646
),
16191647
),
1620-
close: Effect.gen(function* () {
1621-
const descendants =
1622-
cliPid === undefined || processExited
1623-
? []
1624-
: claudeDescendants(yield* readProcessTable, cliPid);
1625-
const exited = processExit;
1626-
if (descendants.length > 0 && exited !== undefined) {
1627-
runFork(stopAfterExit(descendants, exited));
1628-
}
1629-
}).pipe(
1648+
// A job started since the last poll is recorded before the CLI is told to exit.
1649+
close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
16301650
Effect.andThen(Queue.shutdown(promptQueue)),
16311651
Effect.andThen(closeClaudeQuery(queryRuntime)),
16321652
Effect.tap(() =>

‎apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,36 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
612612
}),
613613
);
614614

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",
624+
].join("\n"),
625+
);
626+
const dir = NodePath.dirname(cli);
627+
NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
628+
yield* Effect.addFinalizer(() =>
629+
Effect.sync(() => {
630+
try {
631+
process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
632+
} catch {}
633+
NodeFS.rmSync(dir, { recursive: true, force: true });
634+
}),
635+
);
636+
const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
637+
const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
638+
alive.resume();
639+
640+
yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner));
641+
yield* Effect.promise(() => leftoverStopped);
642+
}),
643+
);
644+
615645
const rootRefusal =
616646
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
617647

0 commit comments

Comments
 (0)