mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
fix(opencode): record kernel OOM evidence when opencode serve is SIGKILLed (#23372)
## 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 and reads its event stream. > - Sometimes `opencode serve` dies by SIGKILL in the middle of a turn. The run then fails with `opencode_server_exited`. > - The failure record shows `signal: SIGKILL` and `ECONNREFUSED`, but it does not show who sent the signal. > - A SIGKILL alone does not prove a kernel OOM kill. Recent failures were short turns with few or no tool calls, so the cause is not clear. > - This pull request records the kernel cgroup v2 OOM evidence when `opencode serve` dies by a signal. > - The benefit is that the next failure tells us if the kernel memory limit killed OpenCode or if something else did. ## Linked Issues or Issue Description Refs #17398 (the Legacy OpenCode adapter makes sandbox tool commands the first OOM victims). Refs #16844 (the same protection for Claude). **What happened?** On a cloud sandbox, a native OpenCode turn failed with `opencode_server_exited`. The run failure record had `streamFailure: server_exited`, `signal: SIGKILL` and `connectionError: ECONNREFUSED`, and `timeoutFired` was false. The Runner process stayed alive. The Runner sends SIGKILL to OpenCode only at shutdown or at a failed start, so the signal came from outside the Runner. The record has no kernel memory evidence, so we cannot tell if the kernel OOM killer sent it. **Expected behavior** When `opencode serve` dies by a signal, the failure record says if the kernel recorded an OOM kill in its cgroup after launch. It also gives the memory limit and the peak use. **Steps to reproduce** 1. Start a native OpenCode turn in a Linux sandbox that uses cgroup v2. 2. Send SIGKILL to the `opencode serve` process while the turn runs. 3. Read `resultJson.nativeTurnFailure` for the failed run. Before this change, it has no memory evidence. **Paperclip version or commit** `master` at6678554a5a. ## What Changed - Add `memory-kill-evidence.ts` to the OpenCode driver. It reads the process cgroup from `/proc/<pid>/cgroup` (unified v2 entry only). It records the `oom_kill` count from `memory.events` right after spawn. Later it compares the count and finds the nearest numeric `memory.max` and that cgroup `memory.peak`. It never reads outside the cgroup root. It returns nothing when cgroup v2 evidence is not readable. - Start the probe after `opencode serve` spawns, on Linux only. A new `memoryKillProbe` driver option sets other paths for tests, or `false` turns the probe off. - When the event stream fails and the process died by a signal, add `memoryKill` (`observed` or `not_observed`), `memoryLimitBytes` and `memoryPeakBytes` to the `opencodeFailure` record. - Keep the three fields in the server closed-vocabulary projection (`native-provider-failure.ts`). Only the two known `memoryKill` values and positive safe integers pass. They reach `resultJson.nativeTurnFailure` and the run failure context. - 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`: 4/4 pass. The tests cover an observed kill, no kill, no limit, no readable cgroup v2 data, cgroup v1, and a path that tries to leave the cgroup root. - `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 uses a fake cgroup tree. It kills OpenCode right after the turn opens, with no tool calls. It now expects `memoryKill: "observed"` and the limit. It fails when the probe is off. - `cd server && npx vitest run src/services/native-runtime/native-provider-failure.test.ts`: 63/63 pass. - These local runs used the parent commit201abacd. The patch applies to current `master` with only line offsets. CI runs the full suites on this branch. ## Risks - Low risk. The probe reads a few small files: once at spawn and once after a signal death. All read errors give no evidence. They do not throw. - On hosts without cgroup v2 (macOS, Windows, cgroup v1), the probe reports nothing. - `memoryKill: "not_observed"` means that the kernel did not count an OOM kill in the cgroup of OpenCode or its child cgroups. An OOM kill in a different cgroup (for example a parent limit with another member) can still kill OpenCode. Read the field with `memoryLimitBytes` and `memoryPeakBytes`. ## 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:
1 parent
6678554a5a
commit
43fedd51c5
6 files changed
+266
-6
No files matched your search
@@ -0,0 +1,68 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { startOpenCodeMemoryKillProbe } from "./memory-kill-evidence.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
function memoryEvents(oomKills: number): string {
|
||||
return `low 0\nhigh 0\nmax 3\noom 1\noom_kill ${oomKills}\noom_group_kill 0\n`;
|
||||
}
|
||||
|
||||
/** A fake /proc and cgroup v2 tree: a limited sandbox root with OpenCode in init.scope. */
|
||||
async function fixture(membership = "0::/init.scope\n") {
|
||||
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-memory-"));
|
||||
roots.push(root);
|
||||
const procRoot = join(root, "proc");
|
||||
const cgroupRoot = join(root, "cgroup");
|
||||
const scope = join(cgroupRoot, "init.scope");
|
||||
await mkdir(join(procRoot, "42"), { recursive: true });
|
||||
await mkdir(scope, { recursive: true });
|
||||
await writeFile(join(procRoot, "42", "cgroup"), membership);
|
||||
await writeFile(join(cgroupRoot, "memory.max"), "8589934592\n");
|
||||
await writeFile(join(cgroupRoot, "memory.peak"), "8400000000\n");
|
||||
await writeFile(join(scope, "memory.max"), "max\n");
|
||||
await writeFile(join(scope, "memory.events"), memoryEvents(2));
|
||||
return { paths: { procRoot, cgroupRoot }, scope };
|
||||
}
|
||||
|
||||
describe("startOpenCodeMemoryKillProbe", () => {
|
||||
it("reports a kernel OOM kill recorded after OpenCode started, with the applying limit", async () => {
|
||||
const { paths, scope } = await fixture();
|
||||
const probe = startOpenCodeMemoryKillProbe(42, paths);
|
||||
expect(probe?.evidence()).toEqual({
|
||||
memoryKill: "not_observed", memoryLimitBytes: 8_589_934_592, memoryPeakBytes: 8_400_000_000,
|
||||
});
|
||||
await writeFile(join(scope, "memory.events"), memoryEvents(3));
|
||||
expect(probe?.evidence()).toEqual({
|
||||
memoryKill: "observed", memoryLimitBytes: 8_589_934_592, memoryPeakBytes: 8_400_000_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("omits the limit when no cgroup up to the root sets one", async () => {
|
||||
const { paths } = await fixture();
|
||||
await writeFile(join(paths.cgroupRoot, "memory.max"), "max\n");
|
||||
expect(startOpenCodeMemoryKillProbe(42, paths)?.evidence()).toEqual({ memoryKill: "not_observed" });
|
||||
});
|
||||
|
||||
it("reports nothing without readable cgroup v2 evidence", async () => {
|
||||
const { paths, scope } = await fixture();
|
||||
expect(startOpenCodeMemoryKillProbe(7, paths)).toBeNull();
|
||||
expect(startOpenCodeMemoryKillProbe(0, paths)).toBeNull();
|
||||
const probe = startOpenCodeMemoryKillProbe(42, paths);
|
||||
await rm(join(scope, "memory.events"));
|
||||
expect(probe?.evidence()).toBeNull();
|
||||
const v1 = await fixture("4:memory:/init.scope\n");
|
||||
expect(startOpenCodeMemoryKillProbe(42, v1.paths)).toBeNull();
|
||||
});
|
||||
|
||||
it("never reads outside the cgroup root", async () => {
|
||||
const { paths } = await fixture("0::/../../proc\n");
|
||||
expect(startOpenCodeMemoryKillProbe(42, paths)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
|
||||
/**
|
||||
* Kernel memory evidence for an `opencode serve` process that died by signal.
|
||||
*
|
||||
* A SIGKILL alone does not say who sent it. The cgroup v2 `oom_kill` counter
|
||||
* 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.
|
||||
*/
|
||||
export interface OpenCodeMemoryKillEvidence {
|
||||
/** Whether the kernel recorded an OOM kill in OpenCode's cgroup after launch. */
|
||||
memoryKill: "observed" | "not_observed";
|
||||
/** The nearest memory limit that applies to OpenCode's cgroup, if any. */
|
||||
memoryLimitBytes?: number;
|
||||
/** Peak memory use of the cgroup that holds that limit, if reported. */
|
||||
memoryPeakBytes?: number;
|
||||
}
|
||||
|
||||
export interface OpenCodeMemoryKillProbe {
|
||||
evidence(): OpenCodeMemoryKillEvidence | null;
|
||||
}
|
||||
|
||||
export interface OpenCodeMemoryKillProbePaths {
|
||||
cgroupRoot: string;
|
||||
procRoot: string;
|
||||
}
|
||||
|
||||
const DEFAULT_PATHS: OpenCodeMemoryKillProbePaths = {
|
||||
cgroupRoot: "/sys/fs/cgroup",
|
||||
procRoot: "/proc",
|
||||
};
|
||||
|
||||
function readText(path: string): string | null {
|
||||
try {
|
||||
return readFileSync(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readCount(path: string): number | null {
|
||||
const value = readText(path)?.trim();
|
||||
if (!value || !/^\d+$/.test(value)) return null;
|
||||
const parsed = Number(value);
|
||||
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]);
|
||||
return Number.isSafeInteger(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 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"));
|
||||
if (membership === null) return null;
|
||||
const unified = membership.split("\n").find((line) => line.startsWith("0::"));
|
||||
if (!unified) return null;
|
||||
const root = resolve(paths.cgroupRoot);
|
||||
const directory = resolve(root, `.${unified.slice(3).trim()}`);
|
||||
return isInside(root, directory) ? directory : null;
|
||||
}
|
||||
|
||||
function isInside(root: string, path: string): boolean {
|
||||
const inside = relative(root, path);
|
||||
return inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside);
|
||||
}
|
||||
|
||||
/** Walks up to the cgroup root and returns the first numeric memory limit. */
|
||||
function nearestLimit(
|
||||
directory: string,
|
||||
cgroupRoot: 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")) };
|
||||
if (current === root) return null;
|
||||
const parent = resolve(current, "..");
|
||||
if (parent === current || !isInside(root, parent)) return null;
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function startOpenCodeMemoryKillProbe(
|
||||
pid: number,
|
||||
paths: OpenCodeMemoryKillProbePaths = DEFAULT_PATHS,
|
||||
): 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;
|
||||
return {
|
||||
evidence() {
|
||||
const current = readOomKills(directory);
|
||||
if (current === null) return null;
|
||||
const limit = nearestLimit(directory, paths.cgroupRoot);
|
||||
return {
|
||||
memoryKill: current > baseline ? "observed" : "not_observed",
|
||||
...(limit ? { memoryLimitBytes: limit.limitBytes } : {}),
|
||||
...(limit && limit.peakBytes !== null ? { memoryPeakBytes: limit.peakBytes } : {}),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -3665,13 +3665,25 @@ describe("OpenCodeServerDriver", () => {
|
||||
const opened = new Promise<void>(resolve => { streamOpened = resolve; });
|
||||
let serverPid: number | undefined;
|
||||
let eventRequests = 0;
|
||||
// A fake cgroup v2 tree: the kernel records the kill as a new oom_kill.
|
||||
const procRoot = join(root, "proc");
|
||||
const cgroupRoot = join(root, "cgroup");
|
||||
const memoryEvents = (oomKills: number) => `oom 0\noom_kill ${oomKills}\n`;
|
||||
const refused = () => new TypeError("fetch failed", {
|
||||
cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1"), { code: "ECONNREFUSED" }),
|
||||
});
|
||||
const driver = new OpenCodeServerDriver({
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731", runtimeDirectory: root, command: fixture,
|
||||
environment: { PATH: process.env.PATH, OPENROUTER_API_KEY: "fixture-key" },
|
||||
onSpawn: async ({ pid }) => { serverPid = pid; },
|
||||
memoryKillProbe: { procRoot, cgroupRoot },
|
||||
onSpawn: async ({ pid }) => {
|
||||
serverPid = pid;
|
||||
await mkdir(join(procRoot, String(pid)), { recursive: true });
|
||||
await mkdir(join(cgroupRoot, "init.scope"), { recursive: true });
|
||||
await writeFile(join(procRoot, String(pid), "cgroup"), "0::/init.scope\n");
|
||||
await writeFile(join(cgroupRoot, "memory.max"), "8589934592\n");
|
||||
await writeFile(join(cgroupRoot, "init.scope", "memory.events"), memoryEvents(0));
|
||||
},
|
||||
// Own the event stream so the fixture cannot finish the turn on its own,
|
||||
// then report the refused reconnects a dead server produces.
|
||||
fetch: async (input, init) => {
|
||||
@@ -3687,6 +3699,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
const events = collectTurnEvents(session.events());
|
||||
const turn = await session.startTurn({ message: { role: "user", text: "install dependencies" } });
|
||||
await opened;
|
||||
await writeFile(join(cgroupRoot, "init.scope", "memory.events"), memoryEvents(1));
|
||||
process.kill(serverPid!, "SIGKILL");
|
||||
stream.error(refused());
|
||||
const observed = await events;
|
||||
@@ -3699,12 +3712,15 @@ describe("OpenCodeServerDriver", () => {
|
||||
providerTerminalObserved: false,
|
||||
error: {
|
||||
code: "opencode_server_exited",
|
||||
opencodeFailure: { kind: "server_exited", signal: "SIGKILL", connectionError: "ECONNREFUSED" },
|
||||
opencodeFailure: { kind: "server_exited", signal: "SIGKILL", connectionError: "ECONNREFUSED", memoryKill: "observed" },
|
||||
},
|
||||
},
|
||||
});
|
||||
const diagnostic = observed.find(event => event.eventType === "harness.diagnostic" && event.payload.code === "opencode_sse_failed");
|
||||
expect(diagnostic?.payload.failure).toEqual({ kind: "server_exited", signal: "SIGKILL", connectionError: "ECONNREFUSED" });
|
||||
expect(diagnostic?.payload.failure).toEqual({
|
||||
kind: "server_exited", signal: "SIGKILL", connectionError: "ECONNREFUSED",
|
||||
memoryKill: "observed", memoryLimitBytes: 8_589_934_592,
|
||||
});
|
||||
expect(eventRequests).toBe(4);
|
||||
} finally {
|
||||
await session.close({ reason: "test complete" });
|
||||
|
||||
@@ -27,6 +27,12 @@ import { parseOpenCodeReasoningMode, type OpenCodeReasoningMode } from "./reason
|
||||
import { attributeUnsupportedToolMedia } from "./tool-media-attribution.js";
|
||||
import { createUpstreamServedTap, type UpstreamServed } from "./upstream-served.js";
|
||||
import { openCodeProviderFailure } from "./provider-failure.js";
|
||||
import {
|
||||
startOpenCodeMemoryKillProbe,
|
||||
type OpenCodeMemoryKillEvidence,
|
||||
type OpenCodeMemoryKillProbe,
|
||||
type OpenCodeMemoryKillProbePaths,
|
||||
} from "./memory-kill-evidence.js";
|
||||
import { createOpenCodeCompanyObservability } from "./company-observability.js";
|
||||
import { startOpenCodePerformanceDiagnostics } from "./performance-diagnostics.js";
|
||||
import { PROVIDER_PERFORMANCE_ENV } from "../../contracts/provider-performance.js";
|
||||
@@ -224,6 +230,11 @@ export interface OpenCodeServerDriverOptions {
|
||||
}) => Promise<void>;
|
||||
/** Keep false when an outer supervisor already owns the process group. */
|
||||
isolateProcessGroup?: boolean;
|
||||
/**
|
||||
* Where to read kernel OOM evidence for a killed OpenCode server. Defaults
|
||||
* to the host's cgroup v2 and proc mounts on Linux; false disables it.
|
||||
*/
|
||||
memoryKillProbe?: OpenCodeMemoryKillProbePaths | false;
|
||||
onDiagnostic?: (message: string) => void;
|
||||
fetch?: typeof globalThis.fetch;
|
||||
now?: () => Date;
|
||||
@@ -235,6 +246,7 @@ interface OpenCodeRuntime {
|
||||
version: string;
|
||||
permissionMode: "allow" | "ask" | "deny";
|
||||
process: ChildProcess;
|
||||
memoryKillProbe: OpenCodeMemoryKillProbe | null;
|
||||
bridge: OpenCodeMcpBridge;
|
||||
trace: ProviderTraceFileSink | null;
|
||||
sensitiveValues: readonly string[];
|
||||
@@ -1714,7 +1726,7 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
if (attempts > 3) {
|
||||
await this.#completionSettlement;
|
||||
if (this.#closed) return;
|
||||
const failure = await openCodeEventStreamFailure(error, this.#runtime.process);
|
||||
const failure = await openCodeEventStreamFailure(error, this.#runtime.process, this.#runtime.memoryKillProbe);
|
||||
if (this.#closed) return;
|
||||
this.#emit("harness.diagnostic", {
|
||||
code: "opencode_sse_failed",
|
||||
@@ -2939,6 +2951,13 @@ async function startRuntime(input: {
|
||||
: child.pid,
|
||||
startedAt: new Date().toISOString(),
|
||||
});
|
||||
// Record the cgroup's OOM kill count before OpenCode can do any work, so a
|
||||
// later SIGKILL can be attributed to the kernel's memory limit or not.
|
||||
const memoryKillPaths = input.options.memoryKillProbe;
|
||||
const memoryKillProbe = child.pid && memoryKillPaths !== false
|
||||
&& (memoryKillPaths !== undefined || globalThis.process.platform === "linux")
|
||||
? startOpenCodeMemoryKillProbe(child.pid, memoryKillPaths)
|
||||
: null;
|
||||
const baseUrl = `http://127.0.0.1:${port}`;
|
||||
const health = await waitForHealth(
|
||||
baseUrl,
|
||||
@@ -2966,6 +2985,7 @@ async function startRuntime(input: {
|
||||
version,
|
||||
permissionMode: input.options.permissionMode ?? "allow",
|
||||
process: child,
|
||||
memoryKillProbe,
|
||||
bridge,
|
||||
trace: input.trace,
|
||||
sensitiveValues,
|
||||
@@ -3559,7 +3579,7 @@ async function waitForExit(
|
||||
}
|
||||
|
||||
/** Closed vocabulary for a lost OpenCode event stream. Never provider text. */
|
||||
export interface OpenCodeEventStreamFailure {
|
||||
export interface OpenCodeEventStreamFailure extends Partial<OpenCodeMemoryKillEvidence> {
|
||||
kind: "server_exited" | "connection_failed" | "http_error" | "stream_closed" | "stream_error";
|
||||
exitCode?: number;
|
||||
signal?: string;
|
||||
@@ -3585,6 +3605,7 @@ function connectionErrorCode(error: unknown): string | undefined {
|
||||
async function openCodeEventStreamFailure(
|
||||
error: unknown,
|
||||
process: ChildProcess,
|
||||
memoryKillProbe: OpenCodeMemoryKillProbe | null = null,
|
||||
): Promise<OpenCodeEventStreamFailure> {
|
||||
const connectionError = connectionErrorCode(error);
|
||||
// A refused or reset connection usually means `opencode serve` has died.
|
||||
@@ -3596,6 +3617,8 @@ async function openCodeEventStreamFailure(
|
||||
...(process.exitCode !== null ? { exitCode: process.exitCode } : {}),
|
||||
...(process.signalCode !== null && process.signalCode in osConstants.signals ? { signal: process.signalCode } : {}),
|
||||
...(connectionError ? { connectionError } : {}),
|
||||
// Only a signal death can be a kernel OOM kill; say whether it was one.
|
||||
...(process.signalCode !== null ? memoryKillProbe?.evidence() ?? {} : {}),
|
||||
};
|
||||
}
|
||||
const httpStatus = record(error).httpStatus;
|
||||
|
||||
@@ -233,6 +233,25 @@ describe("native provider failure observation", () => {
|
||||
expect(readNativeTurnFailureDiagnostic({ provider: "opencode", category: "server_overloaded" })).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the kernel memory evidence for a killed OpenCode server", () => {
|
||||
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",
|
||||
memoryLimitBytes: 8_589_934_592, memoryPeakBytes: 8_400_000_000 },
|
||||
} } });
|
||||
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",
|
||||
memoryLimitBytes: 8_589_934_592, memoryPeakBytes: 8_400_000_000,
|
||||
});
|
||||
expect(readNativeTurnFailureDiagnostic(diagnostic)).toEqual(diagnostic);
|
||||
const base = { provider: "opencode", category: "turn_failed", streamFailure: "server_exited" };
|
||||
expect(readNativeTurnFailureDiagnostic({ ...base, memoryKill: "private text", memoryLimitBytes: -1,
|
||||
memoryPeakBytes: "8000" })).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: {
|
||||
|
||||
@@ -142,6 +142,11 @@ export interface NativeOpenCodeTurnFailureDiagnostic {
|
||||
exitCode?: number;
|
||||
signal?: string;
|
||||
connectionError?: string;
|
||||
/** Whether the kernel recorded an OOM kill in `opencode serve`'s cgroup, for a signal death. */
|
||||
memoryKill?: "observed" | "not_observed";
|
||||
/** The nearest cgroup memory limit over `opencode serve`, and that cgroup's peak use. */
|
||||
memoryLimitBytes?: number;
|
||||
memoryPeakBytes?: 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. */
|
||||
@@ -161,16 +166,24 @@ 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
|
||||
? { [key]: value } as { [P in K]?: number } : {};
|
||||
}
|
||||
|
||||
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 } = entry;
|
||||
const { exitCode, signal, connectionError, memoryKill } = 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),
|
||||
...httpStatusField(entry.httpStatus),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user