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
94 changes: 68 additions & 26 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
// The process group is killed on exit, so its stderr closes promptly.
const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
// How often the CLI's process tree is recorded when no agent scope will stop what it leaves.
// How often a working CLI's process tree is recorded when no agent scope will stop what it leaves.
const CLAUDE_DESCENDANT_POLL = "1 second";
// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
const CLAUDE_ROOT_REFUSAL =
Expand Down Expand Up @@ -556,8 +556,9 @@ function makeClaudeDescendantTracker(cliPid: number) {
}

/**
* 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.
* Process table reads for every working CLI. A poll reads the table once for all of them, so the
* `ps` cost does not grow with open sessions. Jobs start only while a CLI works, so an idle CLI is
* left out of polls; its turn ends with one last read.
*/
export function makeClaudeDescendantPoll(
readProcessTable: Effect.Effect<ReadonlyArray<ClaudeProcessRow>>,
Expand All @@ -570,27 +571,44 @@ export function makeClaudeDescendantPoll(
reading.withPermits(1)(readProcessTable.pipe(Effect.map(apply)));
return {
// 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")),
// only into the CLIs working when its read began.
poll: Effect.suspend(() =>
live.size === 0
? Effect.void
: reading
.withPermits(1)(
Effect.suspend(() => {
const working = [...live];
return readProcessTable.pipe(
Effect.map((rows) => {
for (const tracker of working)
if (live.has(tracker)) tracker.record(rows, true);
}),
);
}),
)
.pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")),
),
track: (cliPid: number) => {
const tracker = makeClaudeDescendantTracker(cliPid);
live.add(tracker);
let exited = false;
const refresh = read((rows) => void tracker.record(rows, true));
return {
tracked: tracker.tracked,
refresh: read((rows) => void tracker.record(rows, true)),
refresh,
/** Polls this CLI from now until its turn settles. */
work: () => {
if (!exited) live.add(tracker);
},
settle: Effect.suspend(() => {
live.delete(tracker);
return exited ? Effect.void : refresh;
}),
/** Reads the table after the CLI exited: what it left that is still the same process. */
leftovers: Effect.sync(() => live.delete(tracker)).pipe(
leftovers: Effect.sync(() => {
exited = true;
live.delete(tracker);
}).pipe(
Effect.andThen(
read((rows) => {
const running = tracker.record(rows, false);
Expand Down Expand Up @@ -1587,8 +1605,7 @@ export const layerQueryRunner: Layer.Layer<
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 = descendantPoll.track(cliPid);
const startPolling = () => {
polling ??= runFork(
descendantPoll.poll.pipe(
Effect.repeat({
Expand All @@ -1602,12 +1619,20 @@ export const layerQueryRunner: Layer.Layer<
}),
),
);
};
const trackDescendants = (cliPid: number) => {
const tracker = descendantPoll.track(cliPid);
const work = () => {
tracker.work();
startPolling();
};
work();
const stop = tracker.leftovers.pipe(
Effect.map((rows) => {
for (const row of rows) killClaudeDescendant(row);
}),
);
return { refresh: tracker.refresh, stop };
return { refresh: tracker.refresh, work, settle: tracker.settle, stop };
};

// The open span below is the tracing boundary for both attempts.
Expand Down Expand Up @@ -1700,7 +1725,7 @@ export const layerQueryRunner: Layer.Layer<
if (answered) return;
stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
};
let refreshDescendants: Effect.Effect<void> = Effect.void;
let descendants: ReturnType<typeof trackDescendants> | undefined;
const spawnProcess =
options.spawnClaudeCodeProcess ??
((spawnOptions: ClaudeSpawnOptions) => {
Expand All @@ -1718,7 +1743,7 @@ export const layerQueryRunner: Layer.Layer<
if (unit === undefined && child.pid !== undefined) {
const tracker = trackDescendants(child.pid);
child.once("exit", () => runFork(tracker.stop));
refreshDescendants = tracker.refresh;
descendants = tracker;
}
return child;
}
Expand Down Expand Up @@ -1899,6 +1924,16 @@ export const layerQueryRunner: Layer.Layer<
}
}),
),
// The result waits for the turn's last tree read, so a session closed on it keeps that job.
Stream.tap((message) =>
descendants === undefined
? Effect.void
: message.type === "result"
? descendants.settle
: message.type === "assistant"
? Effect.sync(descendants.work)
: Effect.void,
),
Stream.tap((message) =>
logProtocolEvent({
direction: "incoming",
Expand All @@ -1910,7 +1945,12 @@ export const layerQueryRunner: Layer.Layer<
offer: (message, onQueued) =>
Effect.uninterruptibleMask((restore) =>
restore(Queue.offer(promptQueue, message)).pipe(
Effect.tap(() => Effect.sync(() => onQueued?.())),
Effect.tap(() =>
Effect.sync(() => {
descendants?.work();
onQueued?.();
}),
),
),
).pipe(
Effect.asVoid,
Expand Down Expand Up @@ -2101,7 +2141,9 @@ export const layerQueryRunner: Layer.Layer<
),
),
// A job started since the last poll is recorded before the CLI is told to exit.
close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
close: Effect.suspend(() =>
processExited || descendants === undefined ? Effect.void : descendants.refresh,
).pipe(
Effect.andThen(Queue.shutdown(promptQueue)),
Effect.andThen(closeClaudeQuery(queryRuntime)),
Effect.tap(() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as TestClock from "effect/testing/TestClock";
import { vi } from "vite-plus/test";

Expand Down Expand Up @@ -831,7 +832,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
},
);

it.effect("reads the process table once per poll for every running CLI", () => {
it.effect("reads the process table once per poll for every working CLI", () => {
let reads = 0;
const descendantPoll = makeClaudeDescendantPoll(
Effect.sync(() => {
Expand All @@ -847,6 +848,8 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
const first = descendantPoll.track(1000);
const second = descendantPoll.track(2000);
return Effect.gen(function* () {
first.work();
second.work();
yield* descendantPoll.poll;
assert.strictEqual(reads, 1);
assert.deepStrictEqual(
Expand All @@ -859,37 +862,121 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
);
yield* first.leftovers;
assert.isTrue(descendantPoll.hasLive());
yield* second.leftovers;
// A settled turn reads the table once more, then idles out of polls.
yield* second.settle;
assert.strictEqual(reads, 3);
assert.isFalse(descendantPoll.hasLive());
yield* descendantPoll.poll;
assert.strictEqual(reads, 3);
});
});

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],
it.effect(
"does not record a poll's table into a CLI that started working 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))),
);
assert.strictEqual(late.tracked.size, 0);
});
});
return Effect.gen(function* () {
const first = descendantPoll.track(1000);
first.work();
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);
late.work();
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);
});
},
);

it.effect("reads the CLI's process tree once when its turn ends and not while it is idle", () =>
Effect.gen(function* () {
const cli = fakeClaudeCli(
[
'dir=$(dirname "$0")',
`while read -r line; do case "$line" in *'"type":"user"'*) break;; esac; done`,
`perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`,
'echo $! > "$dir/leftover.pid"',
`echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"native-session-fake-cli"}'`,
'read -r _ < "$dir/exit"',
].join("\n"),
);
const dir = NodePath.dirname(cli);
NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "exit")]);
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
try {
process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
} catch {}
NodeFS.rmSync(dir, { recursive: true, force: true });
}),
);
const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
alive.resume();
let listings = 0;
const countingSpawner = Layer.effect(
ChildProcessSpawner.ChildProcessSpawner,
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return ChildProcessSpawner.make((command) => {
if (command._tag === "StandardCommand" && command.command === "ps") listings += 1;
return spawner.spawn(command);
});
}),
).pipe(Layer.provide(NodeServices.layer));

const session = yield* openFakeCli(cli).pipe(
Effect.provide(
layerQueryRunner.pipe(
Layer.provide(countingSpawner),
Layer.provide(PortScanner.layerTest),
Layer.provide(
Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }),
),
Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
),
),
);
const turnEnded = yield* Deferred.make<void>();
yield* session.messages.pipe(
Stream.tap((message) =>
message.type === "result" ? Deferred.succeed(turnEnded, undefined) : Effect.void,
),
Stream.runDrain,
Effect.ignore,
Effect.forkScoped,
);
yield* session.offer({
type: "user",
message: { role: "user", content: "Start a job." },
parent_tool_use_id: null,
session_id: "native-session-fake-cli",
});
yield* Deferred.await(turnEnded);
const listingsAtTurnEnd = listings;
yield* TestClock.adjust("1 minute");
// The CLI exits on its own, so only the turn-end read can have recorded the job.
yield* Effect.promise(() => NodeFS.promises.writeFile(NodePath.join(dir, "exit"), "\n"));
yield* Effect.promise(() => leftoverStopped);
assert.equal(listings, listingsAtTurnEnd + 1);
}),
);

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