diff --git a/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.test.ts b/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.test.ts index b2bb7d83e81..a9c1db2f8ee 100644 --- a/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.test.ts @@ -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(); diff --git a/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.ts b/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.ts index 2dc3476fe64..e7bcbff81c5 100644 --- a/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.ts +++ b/packages/paperclip-runner/src/drivers/opencode/memory-kill-evidence.ts @@ -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//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 { + 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()), }; }, }; diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts index 1a576d00434..d66e463ce0f 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -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, diff --git a/server/src/services/native-runtime/native-provider-failure.test.ts b/server/src/services/native-runtime/native-provider-failure.test.ts index b266a9e6bef..83b0263e013 100644 --- a/server/src/services/native-runtime/native-provider-failure.test.ts +++ b/server/src/services/native-runtime/native-provider-failure.test.ts @@ -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: { diff --git a/server/src/services/native-runtime/native-provider-failure.ts b/server/src/services/native-runtime/native-provider-failure.ts index 5a5beb75c57..218deb57f9e 100644 --- a/server/src/services/native-runtime/native-provider-failure.ts +++ b/server/src/services/native-runtime/native-provider-failure.ts @@ -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 = NAT return { runnerFailureCode: codes.has(value) ? value : "unrecognized" }; } -function byteCountField(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(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, +): Pick { + 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 { 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), }; }