Skip to content
Open
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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ DATABASE_URL=postgresql://postgres:postgres@localhost:5432/durable_copilot
# PILOTSWARM_TURN_TIMEOUT_MS=1200000
# Stop a pooled Copilot runtime after this many idle ms; 0 keeps idle runtimes.
# PILOTSWARM_COPILOT_CLIENT_IDLE_STOP_MS=30000
# Linux: oom_score_adj (-999..1000) for each Copilot runtime; 1000 prefers it over the worker as OOM victim.
# PILOTSWARM_COPILOT_RUNTIME_OOM_SCORE_ADJ=1000
# Duroxide lock settings; an unset renewal buffer is 75% of its lock timeout.
# PILOTSWARM_WORKER_LOCK_TIMEOUT_MS=10000
# PILOTSWARM_WORKER_LOCK_RENEWAL_BUFFER_MS=
Expand Down
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Changelog

## Unreleased

### The OOM killer can prefer the Copilot runtime

New opt-in worker option `copilotRuntimeOomScoreAdj` (env
`PILOTSWARM_COPILOT_RUNTIME_OOM_SCORE_ADJ`), a whole number from -999 to 1000
(#441). On Linux, the worker writes it to each Copilot runtime's
`oom_score_adj` as the runtime starts; tools the runtime starts inherit it.
With `1000`, an out-of-memory kill usually takes a runtime, which the worker
replaces (#329), rather than the worker, which drops every session. It does
not help where the kernel kills the container's processes together, and then
a node-wide shortage can take the whole worker container. A value below the
worker's own score is not written. Unset changes nothing. A killed runtime's
tool processes can outlive it (#385), and a runtime killed again and again can
repeat a turn (#384). See [configuration](docs/developer/reference/configuration.md)
for the limits.
## 0.8.22 — 2026-12-01

**Upgrade: rolling deploy from 0.8.21 works.** No migration and no
Expand Down
3 changes: 2 additions & 1 deletion docs/architecture/orchestration/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,8 @@ or SDK change broke the binding), the worker warns once and counts it as
`pilotswarm.copilot_runtime.exits{outcome="unclaimed"}`: that client runs
unwatched, as before #329. `runtime-loss.test.js` kills a runtime found by its
process tree, not through the monitor, so it catches such a break. An exit
after startup is logged with its pid, exit code, signal and the warm sessions
after startup is logged with its pid, exit code, signal, the `oom_score_adj`
the worker gave it (if `copilotRuntimeOomScoreAdj` is set) and the warm sessions
on that runtime, and counted on `pilotswarm.copilot_runtime.exits`. An exit
heard while the SDK is starting the same client is decided when the start
settles: the SDK's own restart stops the previous runtime first.
Expand Down
39 changes: 39 additions & 0 deletions docs/developer/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ AZURE_STORAGE_CONTAINER=copilot-sessions
# PILOTSWARM_WORKER_CONCURRENCY=2
# PILOTSWARM_TURN_TIMEOUT_MS=1200000
# PILOTSWARM_COPILOT_CLIENT_IDLE_STOP_MS=30000
# PILOTSWARM_COPILOT_RUNTIME_OOM_SCORE_ADJ=1000
```

> **Provider types and models** are declared in `.model_providers.json`, usually
Expand Down Expand Up @@ -333,6 +334,40 @@ Duroxide runtime concurrency, and process-wide worker limits.
`PilotSwarmWorker({ copilotClientIdleStopMs })` option takes precedence. It
is parsed the same way, except that a number is rounded down, and an
invalid option falls back to the default, not to the env var.
- `PILOTSWARM_COPILOT_RUNTIME_OOM_SCORE_ADJ`
Linux only. Gives each Copilot runtime the worker starts this
`oom_score_adj`, a whole number from -999 to 1000. Unset by default: nothing
is written. When memory runs out, the kernel's OOM killer kills the process
with the highest memory use plus `oom_score_adj`/1000 of the memory limit.
`1000` is the useful value: a killed runtime is replaced and its turns
retry, while a killed worker drops every session. The score is written as
the runtime starts, so the tools it starts afterwards inherit it. The
worker's own score never changes. Limits:
- It is a preference, not a guarantee.
- Where the kernel kills a container's processes together
(`memory.oom.group=1`, which Kubernetes 1.28+ sets on cgroup v2 unless the
kubelet's `singleProcessOOMKill` is true), it does not help when the
container reaches its own limit. When the whole node runs out, a runtime
at `1000` can make the kernel pick the worker's container and kill all of
it.
- `-1000` (never kill) is refused. A value below the worker's own score is
not written, so a runtime is never harder to kill than its worker; the
worker warns at startup when the value is not above its own score.
- A killed runtime's turn is retried. A runtime killed again and again can
repeat a turn and its side effects. Tool processes of a killed runtime can
outlive it and run alongside the retry.
- It does not cover the short runtimes that list models or write title
summaries, tool handlers and workflow scripts that run in the worker, or
the optional regen distiller: they keep the worker's score. A tool that
uses a lot of memory is itself the likelier victim, which is a tool
failure, not a runtime loss.
- The worker writes only when `/proc` shows its own PID namespace. A failed
write logs a warning (repeats are counted, not logged each time) and the
runtime keeps its score.

The `PilotSwarmWorker({ copilotRuntimeOomScoreAdj })` option takes
precedence; `null` or `""` there means unset, without reading the env var.
An invalid value logs a warning and sets nothing.
- Duroxide lock settings. Each has a matching `PilotSwarmWorker` option
(`workerLockTimeoutMs`, `workerLockRenewalBufferMs`, `orchestratorLockTimeoutMs`,
`orchestratorLockRenewalBufferMs`, `sessionLockTimeoutMs`,
Expand All @@ -359,6 +394,7 @@ PILOTSWARM_ORCHESTRATION_CONCURRENCY=2
PILOTSWARM_WORKER_CONCURRENCY=2
PILOTSWARM_TURN_TIMEOUT_MS=1200000
PILOTSWARM_COPILOT_CLIENT_IDLE_STOP_MS=30000
PILOTSWARM_COPILOT_RUNTIME_OOM_SCORE_ADJ=1000
PILOTSWARM_WORKER_LOCK_TIMEOUT_MS=10000
PILOTSWARM_ORCHESTRATOR_LOCK_TIMEOUT_MS=60000
PILOTSWARM_ORCHESTRATOR_LOCK_RENEWAL_BUFFER_MS=45000
Expand Down Expand Up @@ -498,6 +534,7 @@ new PilotSwarmWorker({
workerNodeId: "pod-1", // identifier for this worker (default: hostname)
turnTimeoutMs: 1_200_000, // explicit override; 0 disables the cap
copilotClientIdleStopMs: 30_000, // stop an unused pooled Copilot runtime after this long; 0 keeps it
copilotRuntimeOomScoreAdj: 1000, // Linux: prefer Copilot runtimes over the worker as OOM victims; unset by default
workflowScripts: { enabled: true }, // run workflow script states; on by default (env PILOTSWARM_WORKFLOW_SCRIPTS=0 turns them off)

// Blob storage for session dehydration
Expand All @@ -516,6 +553,8 @@ new PilotSwarmWorker({
`PILOTSWARM_TURN_TIMEOUT_MS`, then the 20-minute SDK default. The idle
runtime stop works the same way: `copilotClientIdleStopMs`, then
`PILOTSWARM_COPILOT_CLIENT_IDLE_STOP_MS`, then 30 seconds.
`copilotRuntimeOomScoreAdj` wins over
`PILOTSWARM_COPILOT_RUNTIME_OOM_SCORE_ADJ`; with neither, nothing is written.

## Enhanced Facts & Knowledge Graph (optional)

Expand Down
34 changes: 34 additions & 0 deletions packages/sdk/src/copilot-runtime-monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import { AsyncLocalStorage } from "node:async_hooks";
import diagnosticsChannel from "node:diagnostics_channel";
import type { ChildProcess } from "node:child_process";
import { RuntimeOomScoreSetter } from "./oom-score.js";

/** Every message of a turn that ended because its runtime exited starts its explanation with this. */
export const COPILOT_RUNTIME_EXIT_MARKER = "Copilot runtime exited";
Expand Down Expand Up @@ -56,6 +57,15 @@ export interface CopilotRuntimeExit {
requested: boolean;
/** The runtime exited before its client's start settled. */
duringStartup: boolean;
/** The oom_score_adj the monitor gave this runtime (issue 441); absent when it set none. */
oomScoreAdj?: number;
}

export interface CopilotRuntimeMonitorOptions {
/** The oom_score_adj to give each runtime when it is bound (issue 441), read at each bind; undefined sets none. */
runtimeOomScoreAdj?: () => number | undefined;
/** Writes the score and returns whether it took (a RuntimeOomScoreSetter per monitor); tests replace it. */
setOomScoreAdj?: (pid: number | undefined, value: number) => boolean;
}

export interface CopilotRuntimeWatch {
Expand Down Expand Up @@ -87,6 +97,7 @@ interface RuntimeState {
interface ChildState {
exit: CopilotRuntimeExit | null;
listeners: Set<(exit: CopilotRuntimeExit) => void>;
oomScoreAdj?: number;
}

interface SpawnClaim {
Expand Down Expand Up @@ -124,10 +135,12 @@ function subscribeOnce(): void {
export class CopilotRuntimeMonitor {
private readonly states = new WeakMap<object, RuntimeState>();
private readonly children = new WeakMap<ChildProcess, ChildState>();
private oomScoreSetter: RuntimeOomScoreSetter | undefined;

constructor(
private readonly onUnexpectedExit: (client: object, exit: CopilotRuntimeExit) => void,
private readonly onUnclaimed?: (client: object) => void,
private readonly options: CopilotRuntimeMonitorOptions = {},
) {}

/**
Expand Down Expand Up @@ -227,6 +240,11 @@ export class CopilotRuntimeMonitor {
}
}

/**
* Bind a runtime spawn to its client. It runs a microtask after the spawn, before the client's start resolves. A
* process the runtime starts inherits the score only if it starts after the write; the runtime starts tools only
* for a turn, after that start resolves.
*/
private bind(client: object, state: RuntimeState, child: ChildProcess): void {
const childState: ChildState = { exit: null, listeners: new Set() };
this.children.set(child, childState);
Expand All @@ -238,6 +256,7 @@ export class CopilotRuntimeMonitor {
signal: signal ?? null,
requested: state.stopping,
duringStartup: state.startedChild !== child,
...(childState.oomScoreAdj !== undefined ? { oomScoreAdj: childState.oomScoreAdj } : {}),
};
childState.exit = exit;
for (const listener of [...childState.listeners]) {
Expand All @@ -251,6 +270,21 @@ export class CopilotRuntimeMonitor {
}
try { this.onUnexpectedExit(client, exit); } catch {}
});
this.scoreRuntime(child, childState);
}

/** Give the runtime the configured oom_score_adj (issue 441). Its exit listener is already attached. */
private scoreRuntime(child: ChildProcess, childState: ChildState): void {
try {
const value = this.options.runtimeOomScoreAdj?.();
if (value === undefined) return;
const set = this.options.setOomScoreAdj
?? ((pid: number | undefined, score: number) => (this.oomScoreSetter ??= new RuntimeOomScoreSetter()).set(pid, score));
if (set(child.pid, value)) childState.oomScoreAdj = value;
} catch (error: unknown) {
console.warn(`[SessionManager] did not set oom_score_adj on Copilot runtime pid ${child.pid ?? "unknown"} `
+ `(${error instanceof Error ? error.message : String(error)}); it keeps its current score.`);
}
}
}

Expand Down
150 changes: 150 additions & 0 deletions packages/sdk/src/oom-score.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/**
* The Linux OOM killer's preference for the Copilot runtime (issue 441).
*
* The kernel kills the process with the highest score: its memory use plus `oom_score_adj` / 1000 of the memory
* limit. A worker's node process is usually the largest, so it is usually the one killed, and every session on the
* worker drops. Since #329 a killed runtime is replaced and its turns retry, so a deployment may ask for the runtime
* to be the victim instead. Processes the runtime starts after the write, including its tools, inherit the score.
*
* The setting is a victim preference, never an exemption: -1000 (OOM-immune) is refused, and a value below the
* worker's own score is not written, so a runtime is never harder to kill than its worker.
*
* @internal
*/
import { closeSync, constants, openSync, readFileSync, writeSync } from "node:fs";

/** -1000 makes a process OOM-immune, so the lowest accepted value is -999. */
export const OOM_SCORE_ADJ_MIN = -999;
export const OOM_SCORE_ADJ_MAX = 1000;

/** A whole number from -999 to 1000, or undefined. A string may carry surrounding spaces. */
export function parseOomScoreAdj(raw: unknown): number | undefined {
const value = typeof raw === "number" ? raw
: typeof raw === "string" && /^\s*-?\d+\s*$/.test(raw) ? Number(raw.trim())
: Number.NaN;
if (!Number.isInteger(value) || value < OOM_SCORE_ADJ_MIN || value > OOM_SCORE_ADJ_MAX) return undefined;
return value === 0 ? 0 : value;
}

export interface OomScoreHost {
platform: NodeJS.Platform;
selfPid: number;
read(path: string): string;
/** Write to an existing file, never creating or truncating one. */
write(path: string, data: string): void;
warn(message: string): void;
}

/** @internal Write `data` to a file that must already exist (a `/proc` file); never creates or truncates one. */
export function writeExistingFile(path: string, data: string): void {
const fd = openSync(path, constants.O_WRONLY);
try {
writeSync(fd, data);
} finally {
closeSync(fd);
}
}

function defaultOomScoreHost(): OomScoreHost {
return {
platform: process.platform,
selfPid: process.pid,
read: (path) => readFileSync(path, "utf8"),
write: writeExistingFile,
warn: (message) => console.warn(message),
};
}

/**
* Whether `/proc` shows this process's own PID namespace, so that `/proc/<pid>` names the process this worker
* spawned. `NStgid` lists the process's pid from the namespace of the `/proc` mount inward: exactly one entry, equal
* to our pid, means the mount is ours. A `/proc` from another namespace either lists more entries or has no
* `/proc/self` for us at all.
*/
export function procIsOwnPidNamespace(host: OomScoreHost): boolean {
const match = /^NStgid:[ \t]*(.*)$/m.exec(host.read("/proc/self/status"));
if (!match) return false;
const ids = match[1].trim().split(/\s+/);
return ids.length === 1 && ids[0] === String(host.selfPid);
}

/** This process's own oom_score_adj, or undefined when it cannot be read (not Linux, or no readable `/proc`). */
export function readOwnOomScoreAdj(host: OomScoreHost = defaultOomScoreHost()): number | undefined {
if (host.platform !== "linux") return undefined;
try {
const text = host.read("/proc/self/oom_score_adj").trim();
const value = /^-?\d+$/.test(text) ? Number(text) : Number.NaN;
return Number.isInteger(value) && value >= -1000 && value <= 1000 ? value : undefined;
} catch {
return undefined;
}
}

/**
* The startup warning when `configured` gives the runtime no preference over the worker, or undefined. `own` is the
* worker's score from readOwnOomScoreAdj.
*/
export function oomScorePreferenceWarning(configured: number, own: number | undefined): string | undefined {
if (own === undefined || configured > own) return undefined;
return `[PilotSwarmWorker] copilotRuntimeOomScoreAdj ${configured} is ${configured === own ? "equal to" : "below"} `
+ `this worker's own oom_score_adj ${own}: ${configured === own
? "Copilot runtimes get no preference as OOM victims."
: "it is not written, so Copilot runtimes keep the worker's score."}`;
}

function errorReason(error: unknown): string {
const code = (error as { code?: unknown } | null)?.code;
return typeof code === "string" ? code : error instanceof Error ? error.message : String(error);
}

/**
* Writes the configured score to each runtime this worker starts. Repeated failures with the same reason are counted
* and logged at the 1st, 10th, 100th, ... occurrence, so a persistent failure does not log once per spawn.
*/
export class RuntimeOomScoreSetter {
private readonly failures = new Map<string, number>();

constructor(private readonly host: OomScoreHost = defaultOomScoreHost()) {}

/**
* Write `value` to `/proc/<pid>/oom_score_adj` of a runtime this worker started. Linux only, and never this
* process. Returns whether the kernel took the value; otherwise the runtime keeps the score it inherited.
*/
set(pid: unknown, value: unknown): boolean {
if (this.host.platform !== "linux") return false;
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 1 || pid === this.host.selfPid) return false;
const score = parseOomScoreAdj(value);
if (score === undefined) return this.fail("INVALID", `invalid value ${String(value)}`, pid);
let ownNamespace: boolean;
try {
ownNamespace = procIsOwnPidNamespace(this.host);
} catch {
ownNamespace = false;
}
if (!ownNamespace) return this.fail("PID_NAMESPACE", "/proc is not this worker's PID namespace", pid, score);
const own = readOwnOomScoreAdj(this.host);
if (own === undefined ? score < 0 : score < own) {
return this.fail("BELOW_WORKER", own === undefined
? "the worker's own score is unreadable, so only values of 0 or more are written"
: `it is below the worker's own score ${own}`, pid, score);
}
try {
this.host.write(`/proc/${pid}/oom_score_adj`, String(score));
return true;
} catch (error: unknown) {
return this.fail(errorReason(error), errorReason(error), pid, score);
}
}

private fail(key: string, reason: string, pid: number, score?: number): false {
const count = (this.failures.get(key) ?? 0) + 1;
this.failures.set(key, count);
let power = count;
while (power % 10 === 0) power /= 10;
if (power === 1) {
this.host.warn(`[SessionManager] did not set oom_score_adj${score === undefined ? "" : ` ${score}`} on Copilot `
+ `runtime pid ${pid} (${reason}); it keeps its current score.${count > 1 ? ` Seen ${count} times.` : ""}`);
}
return false;
}
}
9 changes: 8 additions & 1 deletion packages/sdk/src/session-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,11 @@ export interface WorkerDefaults {
* worker resolves its own default, DEFAULT_COPILOT_CLIENT_IDLE_STOP_MS).
*/
copilotClientIdleStopMs?: number;
/**
* The Linux oom_score_adj (-999 to 1000) each Copilot runtime this
* manager starts gets (issue 441). Undefined sets none.
*/
copilotRuntimeOomScoreAdj?: number;
}

/** Resolve every part of a bound agent using the same authorized package copy. */
Expand Down Expand Up @@ -1141,6 +1146,7 @@ export class SessionManager {
private readonly runtimeMonitor = new CopilotRuntimeMonitor(
(client, exit) => this._onRuntimeLost(client as CopilotClient, exit),
() => this._onRuntimeUnclaimed(),
{ runtimeOomScoreAdj: () => this.workerDefaults?.copilotRuntimeOomScoreAdj },
);
/** The client each warm session was created or resumed on, for the runtime-loss log (review S8). */
private readonly runtimeClients = new WeakMap<ManagedSession, CopilotClient>();
Expand Down Expand Up @@ -2027,8 +2033,9 @@ export class SessionManager {
const warm = [...this.sessions].filter(([, managed]) => this.runtimeClients.get(managed) === client);
const inFlight = warm.filter(([, managed]) => managed.getActiveTurn() !== null).map(([id]) => id);
const idle = warm.filter(([, managed]) => managed.getActiveTurn() === null).map(([id]) => id);
const score = exit.oomScoreAdj !== undefined ? `, oom_score_adj ${exit.oomScoreAdj}` : "";
console.warn(`[SessionManager] Copilot runtime exited ${exit.duringStartup ? "during startup" : "after startup"} `
+ `(${describeCopilotRuntimeExit(exit)}); its client leaves the pool (${keys} key(s)) and is not reused. `
+ `(${describeCopilotRuntimeExit(exit)}${score}); its client leaves the pool (${keys} key(s)) and is not reused. `
+ `In-flight turns: [${inFlight.join(", ")}]; idle warm sessions: [${idle.join(", ")}].`);
runtimeMetrics().copilotRuntime(exit.duringStartup ? "during_startup" : "after_startup");
this._evictClient(client);
Expand Down
Loading
Loading