From 6a3e355dc8382b21a159b16dc53a3660a796056c Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:40:00 -0800 Subject: [PATCH] perf(server): idle agent sessions free their memory after 2 minutes An agent session stayed alive for 30 minutes after its turn ended, holding its CLI process. Providers with native resume now release an idle session after 2 minutes and resume the same conversation on the next message. Providers without native resume keep 30 minutes, since a released session would come back as a summary of the thread. On macOS the shared Claude process poll now covers only CLIs that are working: from launch or a queued prompt until the turn's result, which ends with one last read. An idle CLI costs no `ps` runs. Rebuilt from #35711 on top of the shared poll. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 94 ++++++++---- .../ClaudeAgentSdkQueryRunner.test.ts | 141 ++++++++++++++---- .../ProviderSessionManager.test.ts | 39 ++++- .../ProviderSessionManager.ts | 29 ++-- 4 files changed, 239 insertions(+), 64 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f6d84df4dcda9..9ff0c8fc16511 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -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 = @@ -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>, @@ -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); @@ -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 | undefined; - const trackDescendants = (cliPid: number) => { - const tracker = descendantPoll.track(cliPid); + const startPolling = () => { polling ??= runFork( descendantPoll.poll.pipe( Effect.repeat({ @@ -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. @@ -1700,7 +1725,7 @@ export const layerQueryRunner: Layer.Layer< if (answered) return; stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); }; - let refreshDescendants: Effect.Effect = Effect.void; + let descendants: ReturnType | undefined; const spawnProcess = options.spawnClaudeCodeProcess ?? ((spawnOptions: ClaudeSpawnOptions) => { @@ -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; } @@ -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", @@ -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, @@ -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(() => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 431ee35e27187..76439d76924b5 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -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"; @@ -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(() => { @@ -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( @@ -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(); - const table = Deferred.makeUnsafe>>(); - 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(); + const table = Deferred.makeUnsafe>>(); + 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((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(); + 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"; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 4f67c42bb6d76..14d17371983b5 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -649,7 +649,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( function layerTest(input: { readonly state: Ref.Ref; - readonly idleTimeoutMs: number; + readonly idleTimeoutMs?: number; readonly maxIdlePinMs?: number; readonly failEventStream?: boolean; readonly normalizeThreadLoadModelSelection?: (selection: ModelSelection) => ModelSelection; @@ -769,7 +769,7 @@ function layerTest(input: { layerConfiguredMcpRegistry, McpProviderSessions.layer, ProviderSessionManager.layerWithOptions({ - idleTimeoutMs: input.idleTimeoutMs, + ...(input.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: input.idleTimeoutMs }), ...(input.maxIdlePinMs === undefined ? {} : { maxIdlePinMs: input.maxIdlePinMs }), }).pipe( Layer.provide( @@ -2102,6 +2102,41 @@ it.effect( }), ); +it.effect.each([ + { resume: "native resume", supportsNativeResume: true, minutes: 2 }, + { resume: "no native resume", supportsNativeResume: false, minutes: 30 }, +])( + "ProviderSessionManagerV2 releases an idle session with $resume after $minutes minutes", + ({ supportsNativeResume, minutes }) => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const capabilities = { + ...CodexCapabilities, + turns: { ...CodexCapabilities.turns, supportsNativeResume }, + }; + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make("thread-default-idle-timeout"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }), + ], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + yield* TestClock.adjust(minutes * 60_000 - 1_000); + assert.isTrue(yield* manager.isLive(providerSessionId)); + yield* TestClock.adjust("1 second"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + }).pipe(Effect.provide(layerTest({ state, capabilities }))); + }), +); + it.effect.each(["session metadata", "session status changes", "provider work"] as const)( "ProviderSessionManagerV2 expires idle sessions according to %s", (activity) => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b840379ae5b54..6d445f5b0bdf7 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -78,7 +78,9 @@ import { import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; -const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const DEFAULT_IDLE_TIMEOUT_MS = 2 * 60 * 1000; +// Without native resume, a released session comes back as a summary of the thread, so it stays longer. +const NO_NATIVE_RESUME_IDLE_TIMEOUT_MS = 30 * 60 * 1000; const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000; const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000; /** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */ @@ -576,7 +578,14 @@ export const layerWithOptions = ( readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; }) => `${input.providerSessionId}\u0000${input.threadId}`; - const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS); + const idleTimeoutFor = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) => + Math.max( + 1, + options.idleTimeoutMs ?? + (runtime.providerSession.capabilities.turns.supportsNativeResume === true + ? DEFAULT_IDLE_TIMEOUT_MS + : NO_NATIVE_RESUME_IDLE_TIMEOUT_MS), + ); const maxIdlePinMs = Math.max(0, options.maxIdlePinMs ?? DEFAULT_MAX_IDLE_PIN_MS); interface PreparedMcpCredential { readonly mcpCredentialId: string | undefined; @@ -1688,7 +1697,7 @@ export const layerWithOptions = ( pinnedForMs: now - pinnedSinceMs, }); // Recheck on this fiber; scheduleIdleReleaseInternal would interrupt it and self-deadlock. - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); + yield* Effect.sleep(Duration.millis(idleTimeoutFor(probedRuntime))); return yield* releaseIfStillIdle(input); } yield* Effect.logWarning("orchestration-v2.driver-session.idle-release-pin-expired", { @@ -1758,7 +1767,7 @@ export const layerWithOptions = ( yield* cancelIdleFiber(entry.idleFiber); const generation = entry.idleGeneration + 1; - const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutFor(entry.runtime))).pipe( Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })), Effect.forkIn(layerScope), ); @@ -2128,7 +2137,7 @@ export const layerWithOptions = ( const pending = entry.idleThreadUnloads.get(providerThreadId); if (pending === undefined) return; const generation = pending.generation + 1; - const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutFor(entry.runtime))).pipe( Effect.andThen( unloadIdleThread({ providerSessionId, @@ -2217,10 +2226,12 @@ export const layerWithOptions = ( : yield* entry.runtime .hasPendingBackgroundWorkForThread(pending.providerThread) .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (hasPendingWork) return "deferred" as const; + if (hasPendingWork) return { retryAfterMs: idleTimeoutFor(entry.runtime) }; const child = yield* delegatedChildArchive(input.threadId); // Unloading now would miss the archive once the parent takes the result. - if (child === "awaiting_delivery") return "deferred" as const; + if (child === "awaiting_delivery") { + return { retryAfterMs: idleTimeoutFor(entry.runtime) }; + } const archive = child === "ready"; if (input.archiveOnly === true && !archive) return "skipped" as const; // null when skipped, otherwise whether this native thread is the app thread's loaded one. @@ -2295,8 +2306,8 @@ export const layerWithOptions = ( }), ); // Wait outside the lock so the next attach is not blocked. - if (outcome === "deferred" && input.archiveOnly !== true) { - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); + if (typeof outcome === "object" && input.archiveOnly !== true) { + yield* Effect.sleep(Duration.millis(outcome.retryAfterMs)); return yield* unloadIdleThread(input); } },