Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 83 additions & 37 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,40 +534,75 @@ function claudeDescendants(
return found;
}

/** What a CLI started, by pid and start time, recorded from each process table read while it runs. */
export function makeClaudeDescendantTracker(
cliPid: number,
const processIdentity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;

/** What one CLI started, by pid and start time, recorded from each process table read while it runs. */
function makeClaudeDescendantTracker(cliPid: number) {
const tracked = new Map<string, ClaudeProcessRow>();
// After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
const record = (rows: ReadonlyArray<ClaudeProcessRow>, cliRunning: boolean) => {
const running = new Set(rows.map(processIdentity));
// `ps -A` lists itself, so no rows is a failed read.
if (rows.length === 0) return running;
const roots = cliRunning ? [cliPid] : [];
for (const [key, row] of tracked) {
if (running.has(key)) roots.push(row.pid);
else tracked.delete(key);
}
for (const row of claudeDescendants(rows, roots)) tracked.set(processIdentity(row), row);
return running;
};
return { tracked: tracked as ReadonlyMap<string, ClaudeProcessRow>, record };
}

/**
* Process table reads for every running CLI. A poll reads the table once for all of them, so the
* `ps` cost does not grow with open sessions.
*/
export function makeClaudeDescendantPoll(
readProcessTable: Effect.Effect<ReadonlyArray<ClaudeProcessRow>>,
) {
const tracked = new Map<string, ClaudeProcessRow>();
const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;
// The poll, a session close and the exit read one at a time, so each table is newer than all
// recorded here, and a pid and start time it no longer lists never run again.
const live = new Set<ReturnType<typeof makeClaudeDescendantTracker>>();
// Polls, session closes and exits read one at a time, so each table is newer than all recorded,
// and a pid and start time it no longer lists never run again.
const reading = Semaphore.makeUnsafe(1);
// After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")(
function* (cliRunning: boolean) {
const rows = yield* readProcessTable;
const running = new Set(rows.map(identity));
// `ps -A` lists itself, so no rows is a failed read.
if (rows.length === 0) return running;
const roots = cliRunning ? [cliPid] : [];
for (const [key, row] of tracked) {
if (running.has(key)) roots.push(row.pid);
else tracked.delete(key);
}
for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row);
return running;
},
(effect) => reading.withPermits(1)(effect),
);
const read = <A>(apply: (rows: ReadonlyArray<ClaudeProcessRow>) => A) =>
reading.withPermits(1)(readProcessTable.pipe(Effect.map(apply)));
return {
tracked: tracked as ReadonlyMap<string, ClaudeProcessRow>,
refresh: refresh(true).pipe(Effect.asVoid),
/** Reads the table after the CLI exited: what it left that is still the same process. */
leftovers: refresh(false).pipe(
Effect.map((running) => [...tracked.values()].filter((row) => running.has(identity(row)))),
),
// A table read before a CLI started may list an older process under its pid, so a poll records
// only into the CLIs tracked when its read began.
poll: reading
.withPermits(1)(
Effect.suspend(() => {
const tracked = [...live];
return readProcessTable.pipe(
Effect.map((rows) => {
for (const tracker of tracked) if (live.has(tracker)) tracker.record(rows, true);
}),
);
}),
)
.pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")),
track: (cliPid: number) => {
const tracker = makeClaudeDescendantTracker(cliPid);
live.add(tracker);
return {
tracked: tracker.tracked,
refresh: read((rows) => void tracker.record(rows, true)),
/** Reads the table after the CLI exited: what it left that is still the same process. */
leftovers: Effect.sync(() => live.delete(tracker)).pipe(
Effect.andThen(
read((rows) => {
const running = tracker.record(rows, false);
return [...tracker.tracked.values()].filter((row) =>
running.has(processIdentity(row)),
);
}),
),
),
};
},
hasLive: () => live.size > 0,
};
}

Expand Down Expand Up @@ -1549,8 +1584,24 @@ export const layerQueryRunner: Layer.Layer<
// Without an agent scope, a job that left the CLI's group escapes the group kill and is
// re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is
// still the same process (pid and start time) is stopped after it exits.
const descendantPoll = makeClaudeDescendantPoll(readProcessTable);
// One poll serves every CLI. The first tracked CLI starts it; it stops once none is left.
let polling: Fiber.Fiber<unknown> | undefined;
const trackDescendants = (cliPid: number) => {
const tracker = makeClaudeDescendantTracker(cliPid, readProcessTable);
const tracker = descendantPoll.track(cliPid);
polling ??= runFork(
descendantPoll.poll.pipe(
Effect.repeat({
schedule: Schedule.spaced(CLAUDE_DESCENDANT_POLL),
// Cleared in the same step that ends the poll, so the next tracked CLI starts a new one.
while: () => {
if (descendantPoll.hasLive()) return true;
polling = undefined;
return false;
},
}),
),
);
const stop = tracker.leftovers.pipe(
Effect.map((rows) => {
for (const row of rows) killClaudeDescendant(row);
Expand Down Expand Up @@ -1666,12 +1717,7 @@ export const layerQueryRunner: Layer.Layer<
);
if (unit === undefined && child.pid !== undefined) {
const tracker = trackDescendants(child.pid);
const polling = runFork(
tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
);
child.once("exit", () =>
runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
);
child.once("exit", () => runFork(tracker.stop));
refreshDescendants = tracker.refresh;
}
return child;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
ClaudeAgentSdkQueryRunner,
type ClaudeAgentSdkQueryOpenInput,
layerQueryRunner,
makeClaudeDescendantTracker,
makeClaudeDescendantPoll,
spawnClaudeProcessGroup,
} from "./ClaudeAdapterV2.ts";

Expand Down Expand Up @@ -734,10 +734,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
"keeps only the descendants the CLI still has running, however many jobs it ran",
() => {
let table: ReadonlyArray<ReturnType<typeof processRow>> = [];
const tracker = makeClaudeDescendantTracker(
1000,
Effect.sync(() => table),
);
const tracker = makeClaudeDescendantPoll(Effect.sync(() => table)).track(1000);
const jobs = (poll: number) => [0, 1, 2, 3].map((job) => 1100 + poll * 4 + job);
return Effect.gen(function* () {
for (let poll = 0; poll < 50; poll++) {
Expand Down Expand Up @@ -781,10 +778,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
[processRow(1000, 10, 0), ...unrelated, orphan],
[...unrelated, orphan],
];
const tracker = makeClaudeDescendantTracker(
1000,
Effect.sync(() => tables.shift() ?? []),
);
const tracker = makeClaudeDescendantPoll(Effect.sync(() => tables.shift() ?? [])).track(1000);
return Effect.gen(function* () {
yield* tracker.refresh;
yield* tracker.refresh;
Expand All @@ -811,10 +805,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
processRow(1001, 1000, 0),
processRow(1100, 1001, 1),
]);
const tracker = makeClaudeDescendantTracker(
1000,
Effect.suspend(() => read),
);
const tracker = makeClaudeDescendantPoll(Effect.suspend(() => read)).track(1000);
return Effect.gen(function* () {
yield* tracker.refresh;
read = Deferred.succeed(olderReadStarted, undefined).pipe(
Expand All @@ -840,6 +831,66 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
},
);

it.effect("reads the process table once per poll for every running CLI", () => {
let reads = 0;
const descendantPoll = makeClaudeDescendantPoll(
Effect.sync(() => {
reads++;
return [
processRow(1000, 10, 0),
processRow(1100, 1000, 1),
processRow(2000, 10, 0),
processRow(2100, 2000, 1),
];
}),
);
const first = descendantPoll.track(1000);
const second = descendantPoll.track(2000);
return Effect.gen(function* () {
yield* descendantPoll.poll;
assert.strictEqual(reads, 1);
assert.deepStrictEqual(
[...first.tracked.values()].map((row) => row.pid),
[1100],
);
assert.deepStrictEqual(
[...second.tracked.values()].map((row) => row.pid),
[2100],
);
yield* first.leftovers;
assert.isTrue(descendantPoll.hasLive());
yield* second.leftovers;
assert.isFalse(descendantPoll.hasLive());
});
});

it.effect("does not record a poll's table into a CLI tracked after the read began", () => {
const readStarted = Deferred.makeUnsafe<void>();
const table = Deferred.makeUnsafe<ReadonlyArray<ReturnType<typeof processRow>>>();
const descendantPoll = makeClaudeDescendantPoll(
Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(table))),
);
return Effect.gen(function* () {
const first = descendantPoll.track(1000);
const polling = yield* descendantPoll.poll.pipe(Effect.forkChild);
yield* Deferred.await(readStarted);
// The earlier process at pid 2000 exited and the pid went to a newly tracked CLI.
const late = descendantPoll.track(2000);
yield* Deferred.succeed(table, [
processRow(1000, 10, 0),
processRow(1100, 1000, 1),
processRow(2000, 10, 0),
processRow(2100, 2000, 1),
]);
yield* Fiber.join(polling);
assert.deepStrictEqual(
[...first.tracked.values()].map((row) => row.pid),
[1100],
);
assert.strictEqual(late.tracked.size, 0);
});
});

const rootRefusal =
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";

Expand Down
Loading