mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
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:
1 parent
07af22c57f
commit
0abb7834f7
5 files changed
+303
-17
No files matched your search
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user