fix(opencode): attribute the memory that fills the sandbox before an OOM kill (#23391)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native Runner starts `opencode serve` for each OpenCode agent
turn in a cloud sandbox with an 8 GiB cgroup memory limit.
> - #23372 added kernel evidence to a signal death of `opencode serve`.
The first event with that evidence shows `memoryKill: "observed"` and
`memoryPeakBytes` at the 8 GiB limit, so the kernel OOM killer stopped
OpenCode.
> - These deaths happen on light turns: one or two small tool calls,
then model generation, about 30 to 60 seconds after OpenCode starts. No
large Bash command runs.
> - The record does not say which memory filled the limit: OpenCode
itself, another process, or shared memory (tmpfs). A correct fix needs
that fact.
> - This pull request samples that memory while OpenCode runs and
reports the last sample with the death.
> - The benefit is that the next OOM kill names the memory consumer, so
the fix can target it.

## Linked Issues or Issue Description

Refs #23372 (adds `memoryKill`, `memoryLimitBytes` and
`memoryPeakBytes`). Refs #17398 (the Legacy OpenCode adapter makes tool
commands the first OOM victims; that does not help when no large tool
command runs).

**What happened?**
On a cloud sandbox, native OpenCode turns fail with
`opencode_server_exited`. With #23372 deployed, the failure record shows
`signal: SIGKILL`, `memoryKill: observed`, `memoryLimitBytes:
8589934592` and `memoryPeakBytes: 8589942784`. The turn made only two
light tool calls before the kill. The record does not show which process
or memory type used the 8 GiB.

**Expected behavior**
When the kernel stops `opencode serve`, the failure record shows how
much memory OpenCode used, how the limited cgroup memory divides into
anonymous, shared and file memory, and the largest other process.

**Steps to reproduce**
1. Run a native OpenCode turn in a Linux sandbox with a cgroup v2 memory
limit.
2. Make the sandbox use all of its memory limit so that the kernel OOM
killer stops `opencode serve`.
3. Read `resultJson.nativeTurnFailure`. Before this change, it has no
memory attribution.

**Paperclip version or commit**
`master` at d1680baf8f.

## What Changed

- `memory-kill-evidence.ts`: when OpenCode runs under a numeric cgroup
memory limit, the probe samples every second (an unref timer, Linux
only). Each sample reads:
  - OpenCode `VmRSS` and `VmHWM` from `/proc/<pid>/status`.
- `anon`, `shmem` and `file` from `memory.stat` of the cgroup that holds
the limit.
- The largest other process by `VmRSS`, among only the processes charged
to the limited cgroup: the `cgroup.procs` of that cgroup and its
descendants. Processes in other cgroups are not compared. Only the
kernel task name is kept. A name outside `[A-Za-z0-9._+:-]{1,15}`
becomes `other`.
- One sample reads at most 64 `cgroup.procs` files and 256 process
`status` files.
- A signal death reports the last sample: `opencodeRssBytes`,
`opencodePeakRssBytes`, `cgroupAnonBytes`, `cgroupShmemBytes`,
`cgroupFileBytes`, `largestProcessName`, `largestProcessRssBytes` and
`memorySampleAgeMs`.
- The probe stops its timer when OpenCode exits. A sample after OpenCode
is gone, or while it is a zombie whose status has no `VmRSS`, keeps the
previous sample. Without a memory limit, the probe does not sample.
- `native-provider-failure.ts`: the closed-vocabulary projection keeps
the new fields. Counts must be safe integers that are zero or more. The
name must match the kernel task-name pattern. Other values are dropped.
- This is a diagnostic. It does not change how a turn fails or recovers.

## Verification

- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/memory-kill-evidence.test.ts`: 7/7 pass. New tests
build a fake `/proc` and cgroup tree. They check:
  - the reported sample, the `other` name and the sample age;
  - that a larger process in another cgroup is not reported;
- that a zombie status without `VmRSS`, and a removed status, both keep
the previous sample;
- that one sample with 400 processes in the cgroup stops at the
256-process limit and takes less than 100 ms;
  - that no sampling happens without a memory limit.
- Scan cost on a real Daytona sandbox (8 GiB cgroup v2 limit, 21
processes): one sample takes 0.75 ms (mean of 200 samples against the
real `/proc` and `/sys/fs/cgroup`). At the 1 s interval, this is less
than 0.1% of the main thread. The fake-tree test at the 256-process
limit sets an upper bound of 100 ms for one sample.
- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/opencode-server-driver.test.ts -t "OpenCode stops
mid-turn|classifies a lost event stream"`: 2/2 pass (the SIGKILL
integration test from #23372 is unchanged).
- `cd server && npx vitest run
src/services/native-runtime/native-provider-failure.test.ts`: 64/64
pass. A new test checks that the fields pass through and that bad values
are dropped.
- A scoped `tsc --noEmit` of
`server/src/services/native-runtime/native-provider-failure.ts` shows no
errors. Without the typed helper, it shows the error that CI reported on
the first commit.
- `tsc -p packages/paperclip-runner/tsconfig.json --noEmit` shows no
errors in the changed files.
- These local runs used an older parent commit with the same versions of
these files. The change applies to current `master` without conflicts.
CI runs the full suites.

## Risks

- Low risk. Sampling runs only on Linux under a numeric cgroup memory
limit. Each sample reads the OpenCode `status` file, the limited cgroup
`memory.stat`, at most 64 `cgroup.procs` files and at most 256 process
`status` files. All read errors give no data. They do not throw. The
reads are synchronous. The measured cost is 0.75 ms for one sample in a
real sandbox.
- The timer is unref, so it does not keep the Runner alive. It stops
when OpenCode exits.
- The largest-process name can only be a short kernel task name. No
command line or path is read.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in an agent sandbox.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
paperclipbugbotandClaude Opus 5.5 authored and GitHub committed 2026-12-01 18:28:43 +00:00
1 parent 07af22c57f
commit 0abb7834f7
5 files changed
+303 -17

No files matched your search

@@ -61,6 +61,73 @@ describe("startOpenCodeMemoryKillProbe", () => {
expect(startOpenCodeMemoryKillProbe(42, v1.paths)).toBeNull();
});
it("reports which memory filled the limit at the last sample before the death", async () => {
const { paths } = await fixture();
const status = (name: string, rssKb: number, hwmKb = rssKb) =>
`Name:\t${name}\nVmHWM:\t${hwmKb} kB\nVmRSS:\t${rssKb} kB\n`;
await writeFile(join(paths.procRoot, "42", "status"), status("opencode", 7_000_000, 7_500_000));
// Process 10 is visible but runs in another cgroup, so its memory does not use this limit.
for (const [pid, name, rssKb] of [["7", "node", 300_000], ["8", "bun runner/../x", 900_000], ["9", "git", 100], ["10", "postgres", 50_000_000]] as const) {
await mkdir(join(paths.procRoot, pid), { recursive: true });
await writeFile(join(paths.procRoot, pid, "status"), status(name, rssKb));
}
await writeFile(join(paths.cgroupRoot, "cgroup.procs"), "7\n");
await writeFile(join(paths.cgroupRoot, "init.scope", "cgroup.procs"), "42\n8\n9\n");
await writeFile(join(paths.cgroupRoot, "memory.stat"), "anon 7600000000\nfile 500000000\nshmem 20000000\nshmem_thp 0\n");
let clock = 1_000;
const probe = startOpenCodeMemoryKillProbe(42, paths, { sampleIntervalMs: 0, now: () => clock });
expect(probe?.evidence()).toEqual({
memoryKill: "not_observed", memoryLimitBytes: 8_589_934_592, memoryPeakBytes: 8_400_000_000,
});
probe?.sample();
// A killed OpenCode can stay a zombie whose status has no resident set,
// and then disappear. Neither replaces the sample taken while it ran.
await writeFile(join(paths.cgroupRoot, "memory.stat"), "anon 100\nfile 100\nshmem 0\n");
await writeFile(join(paths.procRoot, "42", "status"), "Name:\topencode\nState:\tZ (zombie)\n");
probe?.sample();
await rm(join(paths.procRoot, "42", "status"));
probe?.sample();
clock = 1_750;
expect(probe?.evidence()).toEqual({
memoryKill: "not_observed", memoryLimitBytes: 8_589_934_592, memoryPeakBytes: 8_400_000_000,
opencodeRssBytes: 7_168_000_000, opencodePeakRssBytes: 7_680_000_000,
cgroupAnonBytes: 7_600_000_000, cgroupShmemBytes: 20_000_000, cgroupFileBytes: 500_000_000,
// A name outside the kernel task-name vocabulary is reported as `other`.
largestProcessName: "other", largestProcessRssBytes: 921_600_000,
memorySampleAgeMs: 750,
});
probe?.stop();
});
it("bounds one sample to the scan limits, even with many processes in the limited cgroup", async () => {
const { paths } = await fixture();
await writeFile(join(paths.procRoot, "42", "status"), "Name:\topencode\nVmHWM:\t10 kB\nVmRSS:\t10 kB\n");
// 400 processes, more than the 256-process limit; the largest is beyond it.
const pids = Array.from({ length: 400 }, (_, index) => String(1_000 + index));
for (const [index, pid] of pids.entries()) {
await mkdir(join(paths.procRoot, pid), { recursive: true });
await writeFile(join(paths.procRoot, pid, "status"), `Name:\tworker\nVmHWM:\t${index + 1} kB\nVmRSS:\t${index + 1} kB\n`);
}
await writeFile(join(paths.cgroupRoot, "init.scope", "cgroup.procs"), `42\n${pids.join("\n")}\n`);
const probe = startOpenCodeMemoryKillProbe(42, paths, { sampleIntervalMs: 0 });
const started = performance.now();
for (let round = 0; round < 10; round++) probe?.sample();
const perSampleMs = (performance.now() - started) / 10;
// The scan reads 42 and the next 255 pids: the largest it can see is pid 1254.
expect(probe?.evidence()).toMatchObject({ largestProcessName: "worker", largestProcessRssBytes: 255 * 1024 });
// One sample at the scan limit stays far below the 1s sampling interval.
expect(perSampleMs).toBeLessThan(100);
});
it("does not sample memory without a cgroup memory limit", async () => {
const { paths } = await fixture();
await writeFile(join(paths.cgroupRoot, "memory.max"), "max\n");
await writeFile(join(paths.procRoot, "42", "status"), "Name:\topencode\nVmHWM:\t10 kB\nVmRSS:\t10 kB\n");
const probe = startOpenCodeMemoryKillProbe(42, paths, { sampleIntervalMs: 0 });
probe?.sample();
expect(probe?.evidence()).toEqual({ memoryKill: "not_observed" });
});
it("never reads outside the cgroup root", async () => {
const { paths } = await fixture("0::/../../proc\n");
expect(startOpenCodeMemoryKillProbe(42, paths)).toBeNull();
@@ -1,4 +1,4 @@
import { readFileSync } from "node:fs";
import { readFileSync, readdirSync } from "node:fs";
import { isAbsolute, join, relative, resolve, sep } from "node:path";
/**
@@ -8,6 +8,11 @@ import { isAbsolute, join, relative, resolve, sep } from "node:path";
* does: it counts processes in the cgroup (and its descendants) that any OOM
* killer stopped. Runner records the counter when OpenCode starts and compares
* it after the process is gone. Only kernel numbers are reported, never text.
*
* Under a memory limit, Runner also samples which memory filled the cgroup:
* OpenCode's own resident set, the limited cgroup's anonymous, shared and file
* memory, and the largest other process. The last sample before a death says
* whether OpenCode itself, another process, or shared memory used the limit.
*/
export interface OpenCodeMemoryKillEvidence {
/** Whether the kernel recorded an OOM kill in OpenCode's cgroup after launch. */
@@ -16,10 +21,26 @@ export interface OpenCodeMemoryKillEvidence {
memoryLimitBytes?: number;
/** Peak memory use of the cgroup that holds that limit, if reported. */
memoryPeakBytes?: number;
/** OpenCode's resident set at the last sample, and its kernel high-water mark. */
opencodeRssBytes?: number;
opencodePeakRssBytes?: number;
/** The limited cgroup's anonymous, shared (tmpfs, shm) and file memory at the last sample. */
cgroupAnonBytes?: number;
cgroupShmemBytes?: number;
cgroupFileBytes?: number;
/** The largest other process at the last sample: its kernel name and resident set. */
largestProcessName?: string;
largestProcessRssBytes?: number;
/** How old the last sample was when the evidence was read. */
memorySampleAgeMs?: number;
}
export interface OpenCodeMemoryKillProbe {
evidence(): OpenCodeMemoryKillEvidence | null;
/** Takes one memory sample now. The probe also samples on its own timer. */
sample(): void;
/** Stops the sampling timer. Evidence keeps the last sample. */
stop(): void;
}
export interface OpenCodeMemoryKillProbePaths {
@@ -27,10 +48,35 @@ export interface OpenCodeMemoryKillProbePaths {
procRoot: string;
}
export interface OpenCodeMemoryKillProbeOptions {
/** Milliseconds between memory samples; 0 disables the timer. */
sampleIntervalMs?: number;
now?: () => number;
}
const DEFAULT_PATHS: OpenCodeMemoryKillProbePaths = {
cgroupRoot: "/sys/fs/cgroup",
procRoot: "/proc",
};
const DEFAULT_SAMPLE_INTERVAL_MS = 1_000;
/**
* Bounds one sample. A sandbox runs a few dozen processes; at these limits one
* sample reads at most 64 `cgroup.procs` files and 256 `status` files.
*/
const MAX_SCANNED_CGROUPS = 64;
const MAX_SCANNED_PROCESSES = 256;
/** Kernel task names are at most 15 bytes. Anything else is reported as `other`. */
const PROCESS_NAME = /^[A-Za-z0-9._+:-]{1,15}$/;
interface MemorySample {
at: number;
opencodeRssBytes: number | null;
opencodePeakRssBytes: number | null;
cgroupAnonBytes: number | null;
cgroupShmemBytes: number | null;
cgroupFileBytes: number | null;
largestProcess: { name: string; rssBytes: number } | null;
}
function readText(path: string): string | null {
try {
@@ -47,18 +93,22 @@ function readCount(path: string): number | null {
return Number.isSafeInteger(parsed) ? parsed : null;
}
function readOomKills(cgroupDirectory: string): number | null {
const events = readText(join(cgroupDirectory, "memory.events"));
if (events === null) return null;
for (const line of events.split("\n")) {
const match = /^oom_kill (\d+)$/.exec(line.trim());
if (!match) continue;
const parsed = Number(match[1]);
/** The numeric value of `key value` lines, as in `memory.events` and `memory.stat`. */
function keyedCount(text: string, key: string): number | null {
for (const line of text.split("\n")) {
const [name, value, extra] = line.trim().split(/\s+/);
if (name !== key || extra !== undefined || !value || !/^\d+$/.test(value)) continue;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : null;
}
return null;
}
function readOomKills(cgroupDirectory: string): number | null {
const events = readText(join(cgroupDirectory, "memory.events"));
return events === null ? null : keyedCount(events, "oom_kill");
}
/** The unified (v2) cgroup directory of a process, kept inside the cgroup root. */
function cgroupDirectoryOf(pid: number, paths: OpenCodeMemoryKillProbePaths): string | null {
const membership = readText(join(paths.procRoot, String(pid), "cgroup"));
@@ -79,12 +129,12 @@ function isInside(root: string, path: string): boolean {
function nearestLimit(
directory: string,
cgroupRoot: string,
): { limitBytes: number; peakBytes: number | null } | null {
): { directory: string; limitBytes: number; peakBytes: number | null } | null {
const root = resolve(cgroupRoot);
for (let current = directory; ; ) {
const limitBytes = readCount(join(current, "memory.max"));
if (limitBytes !== null && limitBytes > 0)
return { limitBytes, peakBytes: readCount(join(current, "memory.peak")) };
return { directory: current, limitBytes, peakBytes: readCount(join(current, "memory.peak")) };
if (current === root) return null;
const parent = resolve(current, "..");
if (parent === current || !isInside(root, parent)) return null;
@@ -92,21 +142,126 @@ function nearestLimit(
}
}
/** `VmRSS` and `VmHWM` from `/proc/<pid>/status`, converted from kB to bytes. */
function processMemory(procRoot: string, pid: string): { name: string | null; rssBytes: number | null; peakRssBytes: number | null } | null {
const status = readText(join(procRoot, pid, "status"));
if (status === null) return null;
const kilobytes = (key: string) => {
const match = new RegExp(`^${key}:\\s+(\\d+) kB$`, "m").exec(status);
const value = match ? Number(match[1]) * 1024 : null;
return value !== null && Number.isSafeInteger(value) ? value : null;
};
const name = /^Name:\s+(.*)$/m.exec(status)?.[1]?.trim() ?? null;
return { name, rssBytes: kilobytes("VmRSS"), peakRssBytes: kilobytes("VmHWM") };
}
/**
* Processes charged to the limited cgroup: the `cgroup.procs` of that cgroup
* and its descendants. Processes in other cgroups do not use this limit.
*/
function limitedProcesses(limitDirectory: string): string[] {
const pids: string[] = [];
const pending = [limitDirectory];
for (let scannedCgroups = 0; pending.length > 0 && scannedCgroups < MAX_SCANNED_CGROUPS; scannedCgroups++) {
const directory = pending.shift()!;
for (const pid of readText(join(directory, "cgroup.procs"))?.split("\n") ?? []) {
if (!/^\d+$/.test(pid)) continue;
pids.push(pid);
if (pids.length >= MAX_SCANNED_PROCESSES) return pids;
}
try {
for (const entry of readdirSync(directory, { withFileTypes: true }))
if (entry.isDirectory()) pending.push(join(directory, entry.name));
} catch {
// An unreadable cgroup has no visible children.
}
}
return pids;
}
/** The process charged to the limit with the largest resident set, other than OpenCode. */
function largestOtherProcess(
procRoot: string,
limitDirectory: string,
opencodePid: string,
): { name: string; rssBytes: number } | null {
let largest: { name: string; rssBytes: number } | null = null;
for (const entry of limitedProcesses(limitDirectory)) {
if (entry === opencodePid) continue;
const memory = processMemory(procRoot, entry);
if (!memory || memory.rssBytes === null) continue;
if (largest && memory.rssBytes <= largest.rssBytes) continue;
const name = memory.name !== null && PROCESS_NAME.test(memory.name) ? memory.name : "other";
largest = { name, rssBytes: memory.rssBytes };
}
return largest;
}
function sampleFields(sample: MemorySample | null, now: number): Omit<OpenCodeMemoryKillEvidence, "memoryKill" | "memoryLimitBytes" | "memoryPeakBytes"> {
if (!sample) return {};
return {
...(sample.opencodeRssBytes !== null ? { opencodeRssBytes: sample.opencodeRssBytes } : {}),
...(sample.opencodePeakRssBytes !== null ? { opencodePeakRssBytes: sample.opencodePeakRssBytes } : {}),
...(sample.cgroupAnonBytes !== null ? { cgroupAnonBytes: sample.cgroupAnonBytes } : {}),
...(sample.cgroupShmemBytes !== null ? { cgroupShmemBytes: sample.cgroupShmemBytes } : {}),
...(sample.cgroupFileBytes !== null ? { cgroupFileBytes: sample.cgroupFileBytes } : {}),
...(sample.largestProcess
? { largestProcessName: sample.largestProcess.name, largestProcessRssBytes: sample.largestProcess.rssBytes }
: {}),
memorySampleAgeMs: Math.max(0, Math.round(now - sample.at)),
};
}
/**
* Records the OOM kill count of a just-started process's cgroup. Returns null
* when the platform has no readable cgroup v2 memory controller, so callers
* report nothing rather than a guess.
* report nothing rather than a guess. Samples memory only under a numeric
* memory limit, where an OOM kill can happen.
*/
export function startOpenCodeMemoryKillProbe(
pid: number,
paths: OpenCodeMemoryKillProbePaths = DEFAULT_PATHS,
options: OpenCodeMemoryKillProbeOptions = {},
): OpenCodeMemoryKillProbe | null {
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
const directory = cgroupDirectoryOf(pid, paths);
if (directory === null) return null;
const baseline = readOomKills(directory);
if (baseline === null) return null;
const now = options.now ?? Date.now;
const limitDirectory = nearestLimit(directory, paths.cgroupRoot)?.directory ?? null;
const opencodePid = String(pid);
let lastSample: MemorySample | null = null;
let stopped = false;
const sample = () => {
if (stopped || limitDirectory === null) return;
const opencode = processMemory(paths.procRoot, opencodePid);
// OpenCode is gone, or is a zombie whose status has no resident set: keep
// the sample taken while it was alive, not post-kill totals.
if (!opencode || opencode.rssBytes === null) return;
const stat = readText(join(limitDirectory, "memory.stat"));
lastSample = {
at: now(),
opencodeRssBytes: opencode.rssBytes,
opencodePeakRssBytes: opencode.peakRssBytes,
cgroupAnonBytes: stat === null ? null : keyedCount(stat, "anon"),
cgroupShmemBytes: stat === null ? null : keyedCount(stat, "shmem"),
cgroupFileBytes: stat === null ? null : keyedCount(stat, "file"),
largestProcess: largestOtherProcess(paths.procRoot, limitDirectory, opencodePid),
};
};
const interval = options.sampleIntervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS;
const timer = limitDirectory !== null && interval > 0 ? setInterval(sample, interval) : null;
timer?.unref();
const stop = () => {
stopped = true;
if (timer) clearInterval(timer);
};
return {
sample,
stop,
evidence() {
const current = readOomKills(directory);
if (current === null) return null;
@@ -115,6 +270,7 @@ export function startOpenCodeMemoryKillProbe(
memoryKill: current > baseline ? "observed" : "not_observed",
...(limit ? { memoryLimitBytes: limit.limitBytes } : {}),
...(limit && limit.peakBytes !== null ? { memoryPeakBytes: limit.peakBytes } : {}),
...sampleFields(lastSample, now()),
};
},
};
@@ -2985,6 +2985,8 @@ async function startRuntime(input: {
&& (memoryKillPaths !== undefined || globalThis.process.platform === "linux")
? startOpenCodeMemoryKillProbe(child.pid, memoryKillPaths)
: null;
// The probe samples memory while OpenCode runs and keeps the last sample.
if (memoryKillProbe) child.once("exit", () => memoryKillProbe.stop());
const baseUrl = `http://127.0.0.1:${port}`;
const health = await waitForHealth(
baseUrl,
@@ -252,6 +252,29 @@ describe("native provider failure observation", () => {
memoryPeakBytes: "8000" })).toEqual(base);
});
it("keeps the memory attribution sample for a killed OpenCode server", () => {
const attribution = {
opencodeRssBytes: 7_168_000_000, opencodePeakRssBytes: 7_680_000_000,
cgroupAnonBytes: 7_600_000_000, cgroupShmemBytes: 0, cgroupFileBytes: 500_000_000,
largestProcessName: "node", largestProcessRssBytes: 307_200_000, memorySampleAgeMs: 750,
};
const observed = createNativeProviderFailureObservation({ kind: "opencode", model });
observed.observe({ ...event, payload: { status: "failed", error: {
code: "opencode_server_exited",
opencodeFailure: { kind: "server_exited", signal: "SIGKILL", memoryKill: "observed", ...attribution },
} } });
const diagnostic = observed.unclassifiedTurnFailure("turn", terminal);
expect(diagnostic).toEqual({
provider: "opencode", category: "turn_failed", runnerFailureCode: "opencode_server_exited",
streamFailure: "server_exited", signal: "SIGKILL", memoryKill: "observed", ...attribution,
});
expect(readNativeTurnFailureDiagnostic(diagnostic)).toEqual(diagnostic);
const base = { provider: "opencode", category: "turn_failed", streamFailure: "server_exited" };
expect(readNativeTurnFailureDiagnostic({ ...base, opencodeRssBytes: -1, cgroupAnonBytes: 1.5,
largestProcessName: "/home/user/secret project", largestProcessRssBytes: "9", memorySampleAgeMs: null }))
.toEqual(base);
});
it("records only known signal names for a lost OpenCode server", () => {
const observed = createNativeProviderFailureObservation({ kind: "opencode", model });
observed.observe({ ...event, payload: { status: "failed", error: {
@@ -147,6 +147,17 @@ export interface NativeOpenCodeTurnFailureDiagnostic {
/** The nearest cgroup memory limit over `opencode serve`, and that cgroup's peak use. */
memoryLimitBytes?: number;
memoryPeakBytes?: number;
/** `opencode serve`'s resident set at the last memory sample, and its high-water mark. */
opencodeRssBytes?: number;
opencodePeakRssBytes?: number;
/** The limited cgroup's anonymous, shared and file memory at the last sample. */
cgroupAnonBytes?: number;
cgroupShmemBytes?: number;
cgroupFileBytes?: number;
/** The largest other process at the last sample: a kernel task name and its resident set. */
largestProcessName?: string;
largestProcessRssBytes?: number;
memorySampleAgeMs?: number;
/** The stream failure's HTTP status, or else the provider error's status. */
httpStatus?: number;
/** The provider error's category and retryability, when the turn carried one. */
@@ -166,24 +177,51 @@ function runnerFailureCodeField(value: unknown, codes: ReadonlySet<string> = NAT
return { runnerFailureCode: codes.has(value) ? value : "unrecognized" };
}
function byteCountField<K extends "memoryLimitBytes" | "memoryPeakBytes">(key: K, value: unknown): { [P in K]?: number } {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0
type OpenCodeMemoryCountKey =
| "memoryLimitBytes" | "memoryPeakBytes" | "opencodeRssBytes" | "opencodePeakRssBytes"
| "cgroupAnonBytes" | "cgroupShmemBytes" | "cgroupFileBytes" | "largestProcessRssBytes" | "memorySampleAgeMs";
/** A kernel count: a safe integer, positive for a limit, otherwise zero or more. */
function memoryCountField<K extends OpenCodeMemoryCountKey>(key: K, value: unknown, minimum = 0): { [P in K]?: number } {
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum
? { [key]: value } as { [P in K]?: number } : {};
}
/** Kernel task names are at most 15 bytes; the driver reports any other name as `other`. */
const OPENCODE_PROCESS_NAME = /^[A-Za-z0-9._+:-]{1,15}$/;
function openCodeMemoryFields(
entry: Record<string, unknown>,
): Pick<NativeOpenCodeTurnFailureDiagnostic, OpenCodeMemoryCountKey | "memoryKill" | "largestProcessName"> {
const { memoryKill, largestProcessName } = entry;
return {
...(memoryKill === "observed" || memoryKill === "not_observed"
? { memoryKill: memoryKill as "observed" | "not_observed" } : {}),
...memoryCountField("memoryLimitBytes", entry.memoryLimitBytes, 1),
...memoryCountField("memoryPeakBytes", entry.memoryPeakBytes, 1),
...memoryCountField("opencodeRssBytes", entry.opencodeRssBytes),
...memoryCountField("opencodePeakRssBytes", entry.opencodePeakRssBytes),
...memoryCountField("cgroupAnonBytes", entry.cgroupAnonBytes),
...memoryCountField("cgroupShmemBytes", entry.cgroupShmemBytes),
...memoryCountField("cgroupFileBytes", entry.cgroupFileBytes),
...(typeof largestProcessName === "string" && OPENCODE_PROCESS_NAME.test(largestProcessName)
? { largestProcessName: largestProcessName as string } : {}),
...memoryCountField("largestProcessRssBytes", entry.largestProcessRssBytes),
...memoryCountField("memorySampleAgeMs", entry.memorySampleAgeMs),
};
}
function openCodeStreamFailureFields(value: unknown): Omit<NativeOpenCodeTurnFailureDiagnostic, "provider" | "category" | "runnerFailureCode"> {
const entry = record(value);
const kind = entry.kind ?? entry.streamFailure;
if (typeof kind !== "string" || !OPENCODE_STREAM_FAILURE_KINDS.has(kind)) return {};
const { exitCode, signal, connectionError, memoryKill } = entry;
const { exitCode, signal, connectionError } = entry;
return {
streamFailure: kind,
...(typeof exitCode === "number" && Number.isInteger(exitCode) && exitCode >= 0 && exitCode <= 255 ? { exitCode } : {}),
...(typeof signal === "string" && OPENCODE_EXIT_SIGNALS.has(signal) ? { signal } : {}),
...(typeof connectionError === "string" && OPENCODE_CONNECTION_ERRORS.has(connectionError) ? { connectionError } : {}),
...(memoryKill === "observed" || memoryKill === "not_observed" ? { memoryKill } : {}),
...byteCountField("memoryLimitBytes", entry.memoryLimitBytes),
...byteCountField("memoryPeakBytes", entry.memoryPeakBytes),
...openCodeMemoryFields(entry),
...httpStatusField(entry.httpStatus),
};
}