Skip to content

fix(sdk): stop idle pooled Copilot runtimes; end tool shells on every teardown (#331) - #377

Open
ChrisKrawczyk wants to merge 7 commits into
fix/329-dead-runtimefrom
fix/331-idle-runtime-stop
Open

ChrisKrawczyk wants to merge 7 commits into
fix/329-dead-runtimefrom
fix/331-idle-runtime-stop

Conversation

@ChrisKrawczyk

@ChrisKrawczyk ChrisKrawczyk commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #331

Stacked on #376 (the dead-runtime fix for #329). Review only the commits after #376's head, and retarget this PR to main after #376 merges.

A worker kept one Copilot runtime process per credential, transport and workspace root for its whole life, even after every session on it had dehydrated. Each idle runtime kept its memory and its tool shells. Now an unused pooled runtime stops after an idle period, and every session teardown ends that session's background shells. No orchestration version and no migration.

Idle stop

Setting Default Meaning
PilotSwarmWorker({ copilotClientIdleStopMs }) 30000 Stop a pooled Copilot runtime after this many ms with no warm session and no lease. 0 disables the idle stop.
PILOTSWARM_COPILOT_CLIENT_IDLE_STOP_MS 30000 The same, when the option is not set. The option takes precedence.

On by default. The value must be a whole number of milliseconds: anything else (30s, 1e3, -1) logs a warning and uses the default. A numeric option is rounded down; a negative or non-finite one gets the same warning. An invalid option does not fall back to the env value. Values above 2^31-1 are clamped. sessionIdleTimeoutSeconds is not passed to the SDK: the idle stop works at the pool, not in the runtime.

  • SessionManager tracks warm sessions by client object, not by key, so a client shared by several keys stays in use while any of its sessions is warm.
  • A short-lived user of a pooled client holds a lease while it runs: the vision lookup's runtime start and model-catalog read (listModels), a state or epoch reset's deleteSession, a dehydrate's retry re-resume, and a session being created or resumed.
  • When a client has no warm session and no lease, an idle timer starts; any new session or lease cancels it. When it fires, a client still starting is left for another idle period. Otherwise the client leaves the pool map first and is marked retiring, so a caller that already picked it takes a fresh client instead. Then stop() runs with the same 10 s deadline as shutdown, falling back to forceStop(). The next user of the key starts a fresh runtime and resumes from saved state.
  • A warm session that moves to another client key releases its old one. After a reset, the session's key binding is restored.
  • A reset does not call deleteSession on a runtime that never started. It may still create a pooled client it does not use, which the idle stop then removes (Teardowns outside the sweep still wait on an unbounded disconnect, plus two idle-stop residuals #396).
  • A client supplied through the client setter is pinned and never stopped for idleness.
  • _stopClient marks the stop as requested, so the Warm session reused after copilot-runtime dies: turns stall ~300 s and same-worker retries fail with 'Connection is closed.' #329 runtime monitor does not report it as a lost runtime.

#320

#320 (renewable GitHub credentials) adds its own client-retirement bookkeeping and conflicts with main. This PR generalizes the same idea (retiringClients, per-client tracking, one _stopClient with the forced-stop fallback). The plan is for #320 to rebase onto this and retire a client through _stopClient instead of adding a second mechanism.

Shells end with their session

A tool shell runs under setsid and outlives client.stop(). Before this change only workspace sessions, the user's Stop and a Workflow's own script tasks ended background shells. Now every teardown of a warm session runs the same cleanup: dehydrate, eviction, destroy, invalidation, a state or epoch reset, an epoch start, a rebind, a hydrate over a warm session, a client change and a runtime loss.

  1. rpc.tasks.cancel for each of the session's background shells and agent tasks. The cancels run concurrently and share one wait. A shell whose cancel is not confirmed is killed with the processes below it, by its exact identity.
  2. Then what is left of each shell's own process session (Linux) or process group (other POSIX) is killed, so a daemon a shell left behind dies too.

A worker shutdown sends no cancel: it lists the shells, stops the runtime, then kills them (below).

The kill is strict:

  • A process is identified by its pid and start time: kernel clock ticks on Linux, the ps start (to the second) elsewhere. A shell's pid is bound only if its process started no more than 2 s after the task's reported start. Its pid and start are recorded then, and matched exactly right before each signal, from a fresh /proc read on Linux and the pass's listing elsewhere. An unknown identity, or Windows, means no signal.
  • A group is killed only while it has a live member and its recorded leader is unchanged or gone.
  • No signal is sent after the teardown's deadline. The shutdown's kills have no deadline; they run right after each runtime's stop.
  • The worker's own session and group, and a scope led by the worker or its direct child (the CLI), are never killed. A worker running as PID 1 can still kill its shells' scopes.
  • One process-table read per pass serves every shell.

Teardowns from the eviction sweep run concurrently, at most 8 at a time. Each one's cancel and disconnect share one 20 s deadline. At shutdown, each runtime runs list, stop and kill on its own, so a running turn still ends through client.stop() first, and one slow runtime does not delay the kills for the others. Listing each session's shells is bounded at 5 s.

Limits:

The default agent prompt (1.25.0) and base-v2.md now tell agents that background shells end when the session is torn down.

summarizeSession

One 60 s budget covers starting the one-shot client, creating its session and the wait for session.idle. When it runs out, the fallback title is used; a prompt that was already sent is aborted first, waiting at most 5 s for the abort. The client is stopped in finally on success, failure and the early return: forced at once when the budget is spent, otherwise stop() with the same 10 s deadline and forced-stop fallback.

Tests

  • test/local/copilot-runtime-idle-stop.test.js (a real runtime with a scripted model endpoint, and PostgreSQL):
    • An idle pooled runtime stops, its Copilot process exits, and the next turn resumes on a fresh runtime.
    • An eviction, a dehydrate, a worker shutdown and a session cancel each end the shell and the daemon it left behind (skipped on Windows).
  • test/unit/copilot-runtime-idle-stop.test.mjs:
    • idle stop, the grace boundary, and a fresh client on the stopped key that resumes;
    • lease protection during a vision lookup's listModels, a state reset, overlapping leases and a session open;
    • the key-move release and the key restore after a reset;
    • a runtime shared by two sessions; 0 and a caller-supplied client; the strict parse and the clamp;
    • a hung or failing stop() is forced; a cold reset deletes nothing;
    • every teardown of a session without a workspace cancels its shells (destroy, dehydrate, invalidation, eviction, a state or epoch reset, a rebind); sweep teardowns run concurrently under one deadline; shutdown kills each runtime's shells after its stop;
    • a one-shot prompt that never goes idle times out and aborts; the summarize budget, and that summarizeSession always stops its client.
  • test/unit/process-tree.test.mjs:
    • finding a shell's own session below the CLI, and killing a daemon outside its tree;
    • never taking a scope this process or its direct child leads; still finding the shell's scope when the worker is PID 1; not killing a scope whose id went to a new leader;
    • exact start identity, an unknown start, the deadline check, and no signal on Windows;
    • concurrent cancels, one table read for many shells, and a zombie counted as not running.

Multi-model review

Three models (Claude Opus 5.5, GPT-6.2 Sol and Gemini 4 Argon) reviewed this PR as five specialists in a threaded debate, then a synthesis re-checked each finding against the code. The result was 0 must-fix, 14 should-fix, 8 to consider, 2 trade-offs and 8 observations. The fixes are in the commits "harden background shell kills" and "bound session teardowns and fix idle-stop bookkeeping", with two docs commits. All should-fix findings are fixed except SF-4 (below).

  • Kill path: the exact start identity, fail-closed on an unknown identity or Windows, the deadline check, the PID-1 guard, concurrent cancels and one table read.
  • Teardown: concurrent sweep teardowns, each under one deadline, and a per-runtime shutdown order.
  • summarizeSession: one budget over start, create and prompt, with a forced stop.
  • Tests: the real runtime's exit, the grace boundary, lease coverage, fixture shells that end with their directory, zombies counted as not running, and the summarize budget through the activity.
  • Consider: C-1 (the vision lookup), C-3 (the clamp and strict parse), C-4 (one deadline over the cancel and the disconnect on invalidation), C-7 (agent guidance) and C-8 (the reset, epoch and rebind cases) are fixed as well. C-2 is partly fixed: a reset no longer deletes on a runtime that never started, but it still creates a client (Teardowns outside the sweep still wait on an unbounded disconnect, plus two idle-stop residuals #396).
  • Trade-offs:

Each fix has a regression test. For SF-1, SF-2, SF-3, SF-7, SF-8, C-1 and C-3, the test was also shown to fail without the fix.

Left as follow-ups:

C-5 (summarize still starts its own unpooled client for each call) is recorded in the review and not changed here; this PR only bounds it.

Left for @github/copilot-sdk

Validation

All runs were on Linux (Node 24.22.1, PostgreSQL 16), one suite at a time, at 769c67cb (stacked on #376 at d74443b0, rebased on 0.8.18, 1f6af957).

  • CI steps: lint, privacy (0 findings), deploy-scripts (402 passed, 43 skipped of 445), ci-scripts 152/152, sdk-api 63/63, SDK unit 3121/3121, campaign 57/57 and 3/3, app 99/99, 312 of 315 (3 skipped), 2134/2134 and 3/3.
  • Full run-tests.sh: 444 of 444 files; 4584 passed, 0 failed and 26 skipped of 4610.

chkraw and others added 7 commits November 24, 2026 18:28
A worker kept one Copilot runtime process per credential, transport and
workspace root for its whole life, even after every session on it had
dehydrated. Each idle runtime held its memory, and its tool shells.

- SessionManager counts warm sessions per client object (a client
  shared by several keys is counted once) and leases a client to each
  short-lived user: a model-catalog read, a reset's deleteSession, a
  dehydrate's re-resume, and a session being opened.
- After copilotClientIdleStopMs (worker default 30000; env
  PILOTSWARM_COPILOT_CLIENT_IDLE_STOP_MS; 0 disables it) with no warm
  session and no lease, the client leaves the pool first, then stops,
  falling back to forceStop() after the 10 s shutdown deadline. The next
  user of the key starts a fresh runtime and resumes from saved state.
  A client installed through the `client` setter is never stopped.
- A warm session that moves to another client key releases the old one.
- Every teardown cancels the session's background shells and agent
  tasks (rpc.tasks.cancel): dehydrate, eviction, destroy, invalidation,
  reset, rebind, hydrate, client change and worker shutdown, not only
  workspace sessions. A tool shell runs under setsid and outlives
  client.stop(). After each cancel round, what is left of the shell's
  own session (Linux) or process group (other POSIX) is killed, so a
  daemon it started does not survive it. A descendant that calls setsid
  itself still escapes; Windows is a no-op.
- summarizeSession waits at most 60 s for its title (then uses the
  fallback title and aborts the turn) and always stops its one-shot
  client, with the same forced-stop fallback.

No orchestration replay change, no migration.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc944a13-3e0b-43de-8040-5863182bbdb0
…op test (#331)

A worker shutdown cancelled each warm session's shells before it stopped the
runtimes. For a turn still running, that cancel ended the turn's tool call
before CopilotClient.stop did, and the model run took another step
(workspace-moves M3b). Shutdown now only lists each session's shells and their
process sessions or groups, stops the runtimes, then kills what it listed, so
the stop stays the first thing to end a running turn.

The idle-stop integration test waited for a dehydrate the live orchestration
never runs (its hold window only rotates affinity). It now reclaims the warm
session through the eviction sweep, covers eviction, dehydrate and shutdown
for the shell cleanup, and the docs name the sweep as the usual trigger.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc944a13-3e0b-43de-8040-5863182bbdb0
Review fixes for the shell cleanup in this PR:
- SF-1: shellProcessScope no longer refuses a scope whose chain reaches
  PID 1, so the sid/pgid kill runs when the worker is PID 1 in a container.
- SF-2: the raw-PID fallback records (pid, kernel start ticks) at binding
  and signals only on exact equality, verifies each descendant from the
  same snapshot, fails closed on unknown identity and on win32, and checks
  an absolute deadline synchronously right before every signal, so an
  abandoned loop never signals. The scope kills use the same deadline.
- SF-3: background task cancels run concurrently and share one wait.
- SF-5: one process snapshot per pass.
- cancelBackgroundTasks takes an absolute deadline, bounds the task list
  by it and skips the pause when no scope is left; listBackgroundShells
  returns the bound shells for shutdown.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc944a13-3e0b-43de-8040-5863182bbdb0
Review fixes for the idle stop and the teardown paths in this PR:
- SF-6: the eviction sweep tears sessions down concurrently (8 at a time);
  each workspace release runs its cancel and disconnect under one shared
  20 s deadline, and the cancel is never skipped.
- SF-7: shutdown lists, stops and then kills shells per runtime, so one
  slow runtime no longer delays the kills of the others.
- SF-8/SF-14: summarizeSession bounds start, create and prompt with one
  60 s budget and force-stops the one-shot client when it is spent.
- C-1: the vision lookup prefers the runtime the session is warm on, then
  its recorded key, and starts any other client under a lease; the key
  binding is restored after each state reset in getOrCreate.
- C-2: a state reset deletes no session on a runtime that never started.
- C-3: the idle grace is clamped to the largest timer delay, and
  PILOTSWARM_COPILOT_CLIENT_IDLE_STOP_MS is parsed strictly; junk such as
  "30s" or "1e3" is ignored with a warning.
- SF-9..SF-13: the unit and local idle-stop tests assert process exit and
  the effects the review asked for.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc944a13-3e0b-43de-8040-5863182bbdb0
- design.md, configuration.md, the workspaces proposal and CHANGELOG:
  strict parsing and clamping of the idle grace, exact start identity,
  no signal after the deadline, per-runtime shutdown kills, the summarize
  budget, and that killed descendants are reaped only when a reaping init
  (for example tini) runs as PID 1; without one they stay zombies that
  hold only a PID slot.
- C-7: the default agent prompt (1.25.0) and base-v2 say background
  shells end when the session is torn down.
- agent-tuning-log: record the prompt change.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc944a13-3e0b-43de-8040-5863182bbdb0
After the rebase onto #376, the warm-first vision lookup skips a runtime
that has exited as well as one being stopped. Say so in design.md.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc944a13-3e0b-43de-8040-5863182bbdb0
#331)

The teardown deadline is 20 s (5 s when the runtime may be gone); a
shutdown's shell kills have none and run right after each runtime's stop.
The idle-stop option is parsed as strictly as the env var: a number is
rounded down, and an invalid option uses the default rather than the env
var. A Workflow's script tasks already ended their shells before this
change. CLI 1.0.83 kept listing a self-ended detached shell as running;
CLI 1.0.112 reports it completed (process-tree.ts comment only).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cc944a13-3e0b-43de-8040-5863182bbdb0

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants