mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
fix(opencode): record model traffic when opencode serve is OOM-killed (#23428)
## 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 turn and
sends every model request of OpenCode through a local provider proxy.
> - #23372 and #23391 showed that the kernel OOM killer stops `opencode
serve` at the 8 GiB sandbox limit about 50 seconds into light turns, and
that the memory is OpenCode's own resident set (about 7.6 GiB) and
anonymous memory.
> - The retained run log has no raw provider or SSE trace. So we cannot
tell a huge provider response, a loop of model requests, or growth
inside OpenCode on a normal stream from one another.
> - The provider proxy already sees each model request and its response.
It is the cheapest place to measure this.
> - This pull request counts the model traffic in the proxy and reports
the counts when `opencode serve` dies by a signal.
> - The benefit is that the next OOM kill shows which of the three
causes applies, so the fix can target it.
## Linked Issues or Issue Description
Refs #23372 (kernel OOM evidence). Refs #23391 (memory attribution).
**What happened?**
On a cloud sandbox, native OpenCode turns with a fast DeepSeek model
fail with `opencode_server_exited`. The failure record shows
`memoryKill: observed` and `opencodeRssBytes` of about 8.16 GB at the 8
GiB limit. The run log shows no event for about 46 seconds before the
kill. It does not show how much model traffic OpenCode handled in that
time.
**Expected behavior**
When the kernel stops `opencode serve`, the failure record says how many
model requests OpenCode sent, how many bytes the provider returned, and
how large and how old the response was that was still streaming.
**Steps to reproduce**
1. Run a native OpenCode turn through the Runner provider proxy in a
Linux sandbox with a cgroup v2 memory limit.
2. Make the kernel OOM killer stop `opencode serve` while a model
response streams.
3. Read `resultJson.nativeTurnFailure`. Before this change, it has no
model traffic counts.
**Paperclip version or commit**
`master` at fcb8fc5deb.
## What Changed
- New `provider-traffic.ts`: a meter that counts, for one `opencode
serve` launch, model requests, request bytes, completed responses,
response bytes, and the size and age of responses that still stream. It
keeps only numbers. It records no request or response content.
- `startOpenCodeProviderProxy` starts one meter entry for each forwarded
request. It counts response bytes with a pass-through stream in the
existing response pipeline. A request ends as completed only when its
response pipeline finishes. Any other ending counts as interrupted. The
proxy keeps the largest interrupted response's bytes and duration. When
OpenCode dies while it reads a response, its connection closes and that
response ends first, so this keeps the response it was killed on. A
request that the proxy rejects before it calls the provider is not
counted.
- A signal death of `opencode serve` adds these fields to
`opencodeFailure`: `providerRequests`, `providerResponsesCompleted`,
`providerResponsesInterrupted`, `providerRequestBytes`,
`providerResponseBytes`, `providerInflightResponses`,
`providerInflightResponseBytes`, `providerInflightMs`,
`providerInterruptedResponseBytes` and `providerInterruptedMs`.
- `native-provider-failure.ts` keeps the new fields in its closed
vocabulary. Each must be a safe integer that is zero or more. Other
values are dropped.
- `openCodeServerDriverInternals` also exports
`startOpenCodeProviderProxy` for tests.
- This is a diagnostic. It does not change how a turn fails or recovers,
and it does not change any forwarded bytes.
## Verification
- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/provider-traffic.test.ts
src/drivers/opencode/provider-traffic-proxy.test.ts`: 6/6 pass.
- The meter tests check completed and in-flight counts, the largest
in-flight response, the oldest in-flight age, and that late bytes, a
repeated end and bad sizes change nothing.
- A meter test checks that a response which ends before it completes
keeps its size and duration.
- The proxy test sends one finished request and one request whose
response still streams through the real proxy to a local fake provider.
It checks the exact request and response byte counts. Then the client
stops reading, as a killed OpenCode does, and the test checks that the
response is reported as interrupted with its byte count. A second test
checks that a rejected request is not counted.
- `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 test
now expects zero traffic counts, because its fixture does not call the
model.
- `cd server && npx vitest run
src/services/native-runtime/native-provider-failure.test.ts`: 65/65
pass. A new test checks that the counts pass through and that bad values
are dropped.
- A scoped `tsc --noEmit` of the server file shows no errors. `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
the changed code paths. CI runs the full suites on this branch.
## Risks
- Low risk. The counter is a pass-through `Transform` in the existing
response pipeline. It forwards each chunk unchanged and adds its length
to a number.
- The meter keeps one small entry for each in-flight request and removes
it when the request ends.
- Counts are reported only for a signal death of `opencode serve`.
## 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
550d8fc576
commit
64c872e4da
7 files changed
+361
-6
No files matched your search
@@ -3797,6 +3797,9 @@ describe("OpenCodeServerDriver", () => {
|
||||
expect(diagnostic?.payload.failure).toEqual({
|
||||
kind: "server_exited", signal: "SIGKILL", connectionError: "ECONNREFUSED",
|
||||
memoryKill: "observed", memoryLimitBytes: 8_589_934_592,
|
||||
// The fixture never calls the model, so the proxy saw no traffic.
|
||||
providerRequests: 0, providerResponsesCompleted: 0, providerResponsesInterrupted: 0,
|
||||
providerRequestBytes: 0, providerResponseBytes: 0, providerInflightResponses: 0,
|
||||
});
|
||||
expect(eventRequests).toBe(4);
|
||||
} finally {
|
||||
|
||||
@@ -35,6 +35,11 @@ import {
|
||||
type OpenCodeMemoryKillProbePaths,
|
||||
} from "./memory-kill-evidence.js";
|
||||
import { createOpenCodeCompanyObservability } from "./company-observability.js";
|
||||
import {
|
||||
createOpenCodeProviderTrafficMeter,
|
||||
type OpenCodeProviderTrafficEvidence,
|
||||
type OpenCodeProviderTrafficMeter,
|
||||
} from "./provider-traffic.js";
|
||||
import { startOpenCodePerformanceDiagnostics } from "./performance-diagnostics.js";
|
||||
import { PROVIDER_PERFORMANCE_ENV } from "../../contracts/provider-performance.js";
|
||||
import { annotateOmittedProviderText, parseOpenCodeSseFrames } from "./sse-frames.js";
|
||||
@@ -250,6 +255,7 @@ interface OpenCodeRuntime {
|
||||
permissionMode: "allow" | "ask" | "deny";
|
||||
process: ChildProcess;
|
||||
memoryKillProbe: OpenCodeMemoryKillProbe | null;
|
||||
providerTraffic: OpenCodeProviderTrafficMeter | null;
|
||||
bridge: OpenCodeMcpBridge;
|
||||
trace: ProviderTraceFileSink | null;
|
||||
sensitiveValues: readonly string[];
|
||||
@@ -1753,7 +1759,7 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
if (attempts > 3) {
|
||||
await this.#completionSettlement;
|
||||
if (this.#closed) return;
|
||||
const failure = await openCodeEventStreamFailure(error, this.#runtime.process, this.#runtime.memoryKillProbe);
|
||||
const failure = await openCodeEventStreamFailure(error, this.#runtime.process, this.#runtime.memoryKillProbe, this.#runtime.providerTraffic);
|
||||
if (this.#closed) return;
|
||||
this.#emit("harness.diagnostic", {
|
||||
code: "opencode_sse_failed",
|
||||
@@ -2569,6 +2575,8 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
async function startOpenCodeProviderProxy(baseUrl: string, key: string, model: string, environment: NodeJS.ProcessEnv, onServed?: (served: UpstreamServed | null) => void, secretValues: readonly string[] = []) {
|
||||
const upstreamUrl = new URL(`${baseUrl.replace(/\/+$/, "")}/chat/completions`);
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
// Byte and request counts only, so a killed OpenCode can be compared with its model traffic.
|
||||
const traffic = createOpenCodeProviderTrafficMeter();
|
||||
// Agent-local settings keep one runtime's transport configuration out of other sessions.
|
||||
const proxyEnv = {
|
||||
HTTP_PROXY: environment.http_proxy ?? environment.HTTP_PROXY ?? environment.all_proxy ?? environment.ALL_PROXY,
|
||||
@@ -2628,6 +2636,9 @@ async function startOpenCodeProviderProxy(baseUrl: string, key: string, model: s
|
||||
if (redacted) body = redacted;
|
||||
}
|
||||
let served: UpstreamServed | null = null;
|
||||
const metered = traffic.startRequest(body.length);
|
||||
// A response OpenCode stops reading (for example, because it was killed) stays visible as interrupted.
|
||||
let responseCompleted = false;
|
||||
try {
|
||||
const upstream = await new Promise<IncomingMessage>((resolve, reject) => {
|
||||
const outgoing = (upstreamUrl.protocol === "https:" ? requestHttps : requestHttp)(upstreamUrl, {
|
||||
@@ -2652,10 +2663,12 @@ async function startOpenCodeProviderProxy(baseUrl: string, key: string, model: s
|
||||
}
|
||||
response.writeHead(status, headers);
|
||||
if (onServed && status >= 200 && status < 300) {
|
||||
await pipeline(upstream, createUpstreamServedTap({ contentType: headers["content-type"], contentEncoding: headers["content-encoding"],
|
||||
await pipeline(upstream, metered.counter(), createUpstreamServedTap({ contentType: headers["content-type"], contentEncoding: headers["content-encoding"],
|
||||
onServed: value => { served = value; } }), response);
|
||||
} else await pipeline(upstream, response);
|
||||
} else await pipeline(upstream, metered.counter(), response);
|
||||
responseCompleted = true;
|
||||
} finally {
|
||||
metered.end(responseCompleted);
|
||||
try { onServed?.(served); } catch { /* Recording never affects the response. */ }
|
||||
}
|
||||
})().catch(() => {
|
||||
@@ -2678,6 +2691,7 @@ async function startOpenCodeProviderProxy(baseUrl: string, key: string, model: s
|
||||
return {
|
||||
baseURL: `http://127.0.0.1:${address.port}/v1`,
|
||||
token,
|
||||
traffic,
|
||||
close: async () => {
|
||||
for (const controller of controllers) controller.abort();
|
||||
agent.destroy();
|
||||
@@ -3016,6 +3030,7 @@ async function startRuntime(input: {
|
||||
permissionMode: input.options.permissionMode ?? "allow",
|
||||
process: child,
|
||||
memoryKillProbe,
|
||||
providerTraffic: providerProxy?.traffic ?? null,
|
||||
bridge,
|
||||
trace: input.trace,
|
||||
sensitiveValues,
|
||||
@@ -3628,7 +3643,7 @@ async function waitForExit(
|
||||
}
|
||||
|
||||
/** Closed vocabulary for a lost OpenCode event stream. Never provider text. */
|
||||
export interface OpenCodeEventStreamFailure extends Partial<OpenCodeMemoryKillEvidence> {
|
||||
export interface OpenCodeEventStreamFailure extends Partial<OpenCodeMemoryKillEvidence>, Partial<OpenCodeProviderTrafficEvidence> {
|
||||
kind: "server_exited" | "connection_failed" | "http_error" | "stream_closed" | "stream_error";
|
||||
exitCode?: number;
|
||||
signal?: string;
|
||||
@@ -3655,6 +3670,7 @@ async function openCodeEventStreamFailure(
|
||||
error: unknown,
|
||||
process: ChildProcess,
|
||||
memoryKillProbe: OpenCodeMemoryKillProbe | null = null,
|
||||
providerTraffic: OpenCodeProviderTrafficMeter | null = null,
|
||||
): Promise<OpenCodeEventStreamFailure> {
|
||||
const connectionError = connectionErrorCode(error);
|
||||
// A refused or reset connection usually means `opencode serve` has died.
|
||||
@@ -3668,6 +3684,8 @@ async function openCodeEventStreamFailure(
|
||||
...(connectionError ? { connectionError } : {}),
|
||||
// Only a signal death can be a kernel OOM kill; say whether it was one.
|
||||
...(process.signalCode !== null ? memoryKillProbe?.evidence() ?? {} : {}),
|
||||
// Model traffic through Runner's proxy, to tell a huge response or a request loop from OpenCode-side growth.
|
||||
...(process.signalCode !== null ? providerTraffic?.evidence() ?? {} : {}),
|
||||
};
|
||||
}
|
||||
const httpStatus = record(error).httpStatus;
|
||||
@@ -3678,7 +3696,7 @@ async function openCodeEventStreamFailure(
|
||||
return { kind: "stream_error" };
|
||||
}
|
||||
|
||||
export const openCodeServerDriverInternals = { parseSse, openCodeEventStreamFailure };
|
||||
export const openCodeServerDriverInternals = { parseSse, openCodeEventStreamFailure, startOpenCodeProviderProxy };
|
||||
|
||||
class AsyncQueue<T> implements AsyncIterable<T> {
|
||||
#items: T[] = [];
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createServer as createHttpServer } from "node:http";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { openCodeServerDriverInternals } from "./opencode-server-driver.js";
|
||||
|
||||
const { startOpenCodeProviderProxy } = openCodeServerDriverInternals;
|
||||
|
||||
describe("OpenCode provider proxy traffic", () => {
|
||||
it("counts finished and still-streaming model responses", async () => {
|
||||
const frame = 'data: {"choices":[{"delta":{"content":"x"}}]}\n\n';
|
||||
let heldResponseWritten!: () => void;
|
||||
const heldWritten = new Promise<void>(resolve => { heldResponseWritten = resolve; });
|
||||
// One response finishes; the other keeps streaming, like the response a killed OpenCode was reading.
|
||||
const upstream = createHttpServer((request, response) => {
|
||||
void (async () => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of request) chunks.push(Buffer.from(chunk));
|
||||
const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { messages: Array<{ content: string }> };
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
if (body.messages[0]?.content === "hold") {
|
||||
response.write(frame.repeat(3), () => heldResponseWritten());
|
||||
return;
|
||||
}
|
||||
response.end(`${frame}data: [DONE]\n\n`);
|
||||
})().catch(() => response.destroy());
|
||||
});
|
||||
await new Promise<void>(resolve => upstream.listen(0, "127.0.0.1", resolve));
|
||||
const address = upstream.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing fixture address");
|
||||
const proxy = await startOpenCodeProviderProxy(`http://127.0.0.1:${address.port}/v1`, "", "team/model", {});
|
||||
const request = (content: string) => {
|
||||
const body = JSON.stringify({ model: "team/model", stream: true, messages: [{ role: "user", content }] });
|
||||
return { body, response: fetch(`${proxy.baseURL}/chat/completions`, {
|
||||
method: "POST", headers: { Authorization: `Bearer ${proxy.token}`, "Content-Type": "application/json" }, body,
|
||||
}) };
|
||||
};
|
||||
try {
|
||||
expect(proxy.traffic.evidence()).toMatchObject({ providerRequests: 0, providerInflightResponses: 0 });
|
||||
const finished = request("finish");
|
||||
await (await finished.response).text();
|
||||
const held = request("hold");
|
||||
const heldResponse = await held.response;
|
||||
const reader = heldResponse.body!.getReader();
|
||||
await heldWritten;
|
||||
let received = 0;
|
||||
while (received < frame.length * 3) received += (await reader.read()).value?.length ?? 0;
|
||||
const requestBytes = Buffer.byteLength(finished.body) + Buffer.byteLength(held.body);
|
||||
const responseBytes = frame.length + "data: [DONE]\n\n".length + frame.length * 3;
|
||||
expect(proxy.traffic.evidence()).toEqual({
|
||||
providerRequests: 2,
|
||||
providerResponsesCompleted: 1,
|
||||
providerResponsesInterrupted: 0,
|
||||
providerRequestBytes: requestBytes,
|
||||
providerResponseBytes: responseBytes,
|
||||
providerInflightResponses: 1,
|
||||
providerInflightResponseBytes: frame.length * 3,
|
||||
providerInflightMs: expect.any(Number),
|
||||
});
|
||||
// OpenCode dies while it reads: its connection closes, the proxy ends the
|
||||
// response, and the counts must still show that response.
|
||||
await reader.cancel();
|
||||
for (let attempt = 0; proxy.traffic.evidence().providerResponsesInterrupted === 0; attempt++) {
|
||||
if (attempt > 200) throw new Error("The proxy did not end the interrupted response");
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(proxy.traffic.evidence()).toEqual({
|
||||
providerRequests: 2,
|
||||
providerResponsesCompleted: 1,
|
||||
providerResponsesInterrupted: 1,
|
||||
providerRequestBytes: requestBytes,
|
||||
providerResponseBytes: responseBytes,
|
||||
providerInflightResponses: 0,
|
||||
providerInterruptedResponseBytes: frame.length * 3,
|
||||
providerInterruptedMs: expect.any(Number),
|
||||
});
|
||||
} finally {
|
||||
await proxy.close();
|
||||
await new Promise<void>(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not count a request the proxy rejects before calling the provider", async () => {
|
||||
const proxy = await startOpenCodeProviderProxy("http://127.0.0.1:9/v1", "", "team/model", {});
|
||||
try {
|
||||
const response = await fetch(`${proxy.baseURL}/chat/completions`, {
|
||||
method: "POST", headers: { Authorization: `Bearer ${proxy.token}`, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model: "another/model", messages: [] }),
|
||||
});
|
||||
expect(response.status).toBe(400);
|
||||
expect(proxy.traffic.evidence()).toMatchObject({ providerRequests: 0, providerRequestBytes: 0 });
|
||||
} finally {
|
||||
await proxy.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createOpenCodeProviderTrafficMeter } from "./provider-traffic.js";
|
||||
|
||||
describe("createOpenCodeProviderTrafficMeter", () => {
|
||||
it("reports nothing in flight before any request", () => {
|
||||
expect(createOpenCodeProviderTrafficMeter(() => 0).evidence()).toEqual({
|
||||
providerRequests: 0, providerResponsesCompleted: 0, providerResponsesInterrupted: 0,
|
||||
providerRequestBytes: 0, providerResponseBytes: 0, providerInflightResponses: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("counts completed and in-flight model traffic", () => {
|
||||
let clock = 1_000;
|
||||
const meter = createOpenCodeProviderTrafficMeter(() => clock);
|
||||
const title = meter.startRequest(2_000);
|
||||
title.addResponseBytes(500);
|
||||
title.end(true);
|
||||
clock = 2_000;
|
||||
const turn = meter.startRequest(40_000);
|
||||
turn.addResponseBytes(1_000_000);
|
||||
turn.addResponseBytes(3_000_000);
|
||||
clock = 48_500;
|
||||
expect(meter.evidence()).toEqual({
|
||||
providerRequests: 2, providerResponsesCompleted: 1, providerResponsesInterrupted: 0,
|
||||
providerRequestBytes: 42_000, providerResponseBytes: 4_000_500, providerInflightResponses: 1,
|
||||
providerInflightResponseBytes: 4_000_000, providerInflightMs: 46_500,
|
||||
});
|
||||
turn.end(true);
|
||||
// Bytes after a response ended, a repeated end and bad sizes change nothing.
|
||||
turn.addResponseBytes(9);
|
||||
turn.end(false);
|
||||
meter.startRequest(Number.NaN).end(true);
|
||||
expect(meter.evidence()).toEqual({
|
||||
providerRequests: 3, providerResponsesCompleted: 3, providerResponsesInterrupted: 0,
|
||||
providerRequestBytes: 42_000, providerResponseBytes: 4_000_500, providerInflightResponses: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the size and duration of a response that ended before it completed", () => {
|
||||
let clock = 0;
|
||||
const meter = createOpenCodeProviderTrafficMeter(() => clock);
|
||||
const small = meter.startRequest(10);
|
||||
small.addResponseBytes(100);
|
||||
clock = 1_000;
|
||||
small.end(false);
|
||||
const killed = meter.startRequest(10);
|
||||
killed.addResponseBytes(6_000_000);
|
||||
clock = 47_000;
|
||||
// OpenCode died and closed its connection while it read this response.
|
||||
killed.end(false);
|
||||
clock = 50_000;
|
||||
expect(meter.evidence()).toEqual({
|
||||
providerRequests: 2, providerResponsesCompleted: 0, providerResponsesInterrupted: 2,
|
||||
providerRequestBytes: 20, providerResponseBytes: 6_000_100, providerInflightResponses: 0,
|
||||
providerInterruptedResponseBytes: 6_000_000, providerInterruptedMs: 46_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the largest in-flight response and the oldest in-flight age", () => {
|
||||
let clock = 0;
|
||||
const meter = createOpenCodeProviderTrafficMeter(() => clock);
|
||||
const first = meter.startRequest(10);
|
||||
clock = 5_000;
|
||||
const second = meter.startRequest(10);
|
||||
first.addResponseBytes(100);
|
||||
second.addResponseBytes(7_000);
|
||||
clock = 9_000;
|
||||
expect(meter.evidence()).toMatchObject({
|
||||
providerInflightResponses: 2, providerInflightResponseBytes: 7_000, providerInflightMs: 9_000,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Transform } from "node:stream";
|
||||
|
||||
/**
|
||||
* Counts the model traffic that passes through Runner's provider proxy for one
|
||||
* `opencode serve` launch. When OpenCode dies by signal, the counts say whether
|
||||
* the provider sent an unusually large response, OpenCode sent a loop of
|
||||
* requests, or neither (so the memory grew inside OpenCode). Only byte counts,
|
||||
* request counts and durations are kept, never request or response content.
|
||||
*/
|
||||
export interface OpenCodeProviderTrafficEvidence {
|
||||
/** Model requests OpenCode started through the proxy since launch. */
|
||||
providerRequests: number;
|
||||
/** Responses that the proxy forwarded completely. */
|
||||
providerResponsesCompleted: number;
|
||||
/**
|
||||
* Responses that ended before they were forwarded completely, for example
|
||||
* because OpenCode died and closed its connection while it read them.
|
||||
*/
|
||||
providerResponsesInterrupted: number;
|
||||
/** Request body bytes sent to the provider since launch. */
|
||||
providerRequestBytes: number;
|
||||
/** Response bytes received from the provider since launch, including in-flight responses. */
|
||||
providerResponseBytes: number;
|
||||
/** Responses still streaming when the evidence was read. */
|
||||
providerInflightResponses: number;
|
||||
/** Bytes received so far by the largest in-flight response, and the age of the oldest one. */
|
||||
providerInflightResponseBytes?: number;
|
||||
providerInflightMs?: number;
|
||||
/** The largest interrupted response: the bytes it received and how long it streamed. */
|
||||
providerInterruptedResponseBytes?: number;
|
||||
providerInterruptedMs?: number;
|
||||
}
|
||||
|
||||
export interface OpenCodeProviderRequestMeter {
|
||||
addResponseBytes(bytes: number): void;
|
||||
/** A pass-through stream that counts the upstream response bytes it forwards. */
|
||||
counter(): Transform;
|
||||
/** Ends the request. A response that did not complete keeps its size and duration. */
|
||||
end(completed: boolean): void;
|
||||
}
|
||||
|
||||
export interface OpenCodeProviderTrafficMeter {
|
||||
startRequest(requestBytes: number): OpenCodeProviderRequestMeter;
|
||||
evidence(): OpenCodeProviderTrafficEvidence;
|
||||
}
|
||||
|
||||
function safeAdd(total: number, value: number): number {
|
||||
const sum = total + (Number.isFinite(value) && value > 0 ? Math.floor(value) : 0);
|
||||
return Number.isSafeInteger(sum) ? sum : Number.MAX_SAFE_INTEGER;
|
||||
}
|
||||
|
||||
export function createOpenCodeProviderTrafficMeter(now: () => number = Date.now): OpenCodeProviderTrafficMeter {
|
||||
let requests = 0;
|
||||
let completed = 0;
|
||||
let interrupted = 0;
|
||||
let requestBytes = 0;
|
||||
let responseBytes = 0;
|
||||
let largestInterrupted: { bytes: number; durationMs: number } | null = null;
|
||||
const inflight = new Set<{ startedAt: number; bytes: number }>();
|
||||
return {
|
||||
startRequest(bytes) {
|
||||
requests += 1;
|
||||
requestBytes = safeAdd(requestBytes, bytes);
|
||||
const entry = { startedAt: now(), bytes: 0 };
|
||||
inflight.add(entry);
|
||||
let ended = false;
|
||||
const addResponseBytes = (chunkBytes: number) => {
|
||||
if (ended) return;
|
||||
entry.bytes = safeAdd(entry.bytes, chunkBytes);
|
||||
responseBytes = safeAdd(responseBytes, chunkBytes);
|
||||
};
|
||||
return {
|
||||
addResponseBytes,
|
||||
counter() {
|
||||
return new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
addResponseBytes(chunk.length);
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
},
|
||||
end(responseCompleted) {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
inflight.delete(entry);
|
||||
if (responseCompleted) {
|
||||
completed += 1;
|
||||
return;
|
||||
}
|
||||
interrupted += 1;
|
||||
if (!largestInterrupted || entry.bytes >= largestInterrupted.bytes) {
|
||||
largestInterrupted = { bytes: entry.bytes, durationMs: Math.max(0, Math.round(now() - entry.startedAt)) };
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
evidence() {
|
||||
let largest = 0;
|
||||
let oldest: number | null = null;
|
||||
for (const entry of inflight) {
|
||||
largest = Math.max(largest, entry.bytes);
|
||||
oldest = oldest === null ? entry.startedAt : Math.min(oldest, entry.startedAt);
|
||||
}
|
||||
return {
|
||||
providerRequests: requests,
|
||||
providerResponsesCompleted: completed,
|
||||
providerResponsesInterrupted: interrupted,
|
||||
providerRequestBytes: requestBytes,
|
||||
providerResponseBytes: responseBytes,
|
||||
providerInflightResponses: inflight.size,
|
||||
...(inflight.size > 0
|
||||
? { providerInflightResponseBytes: largest, providerInflightMs: Math.max(0, Math.round(now() - (oldest ?? now()))) }
|
||||
: {}),
|
||||
...(largestInterrupted
|
||||
? { providerInterruptedResponseBytes: largestInterrupted.bytes, providerInterruptedMs: largestInterrupted.durationMs }
|
||||
: {}),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -275,6 +275,30 @@ describe("native provider failure observation", () => {
|
||||
.toEqual(base);
|
||||
});
|
||||
|
||||
it("keeps the model traffic counts for a killed OpenCode server", () => {
|
||||
const traffic = {
|
||||
providerRequests: 4, providerResponsesCompleted: 2, providerResponsesInterrupted: 1,
|
||||
providerRequestBytes: 120_000, providerResponseBytes: 9_000_000, providerInflightResponses: 1,
|
||||
providerInflightResponseBytes: 8_000_000, providerInflightMs: 46_500,
|
||||
providerInterruptedResponseBytes: 700_000, providerInterruptedMs: 3_000,
|
||||
};
|
||||
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", ...traffic },
|
||||
} } });
|
||||
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", ...traffic,
|
||||
});
|
||||
expect(readNativeTurnFailureDiagnostic(diagnostic)).toEqual(diagnostic);
|
||||
const base = { provider: "opencode", category: "turn_failed", streamFailure: "server_exited" };
|
||||
expect(readNativeTurnFailureDiagnostic({ ...base, providerRequests: -1, providerResponseBytes: 2.5,
|
||||
providerInflightMs: "46500", providerRequestBytes: Number.MAX_VALUE, providerResponsesInterrupted: -2,
|
||||
providerInterruptedResponseBytes: 1.5, providerInterruptedMs: [] })).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: {
|
||||
|
||||
@@ -158,6 +158,17 @@ export interface NativeOpenCodeTurnFailureDiagnostic {
|
||||
largestProcessName?: string;
|
||||
largestProcessRssBytes?: number;
|
||||
memorySampleAgeMs?: number;
|
||||
/** Model traffic through Runner's provider proxy since `opencode serve` started, for a signal death. */
|
||||
providerRequests?: number;
|
||||
providerResponsesCompleted?: number;
|
||||
providerResponsesInterrupted?: number;
|
||||
providerRequestBytes?: number;
|
||||
providerResponseBytes?: number;
|
||||
providerInflightResponses?: number;
|
||||
providerInflightResponseBytes?: number;
|
||||
providerInflightMs?: number;
|
||||
providerInterruptedResponseBytes?: number;
|
||||
providerInterruptedMs?: 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. */
|
||||
@@ -179,7 +190,10 @@ function runnerFailureCodeField(value: unknown, codes: ReadonlySet<string> = NAT
|
||||
|
||||
type OpenCodeMemoryCountKey =
|
||||
| "memoryLimitBytes" | "memoryPeakBytes" | "opencodeRssBytes" | "opencodePeakRssBytes"
|
||||
| "cgroupAnonBytes" | "cgroupShmemBytes" | "cgroupFileBytes" | "largestProcessRssBytes" | "memorySampleAgeMs";
|
||||
| "cgroupAnonBytes" | "cgroupShmemBytes" | "cgroupFileBytes" | "largestProcessRssBytes" | "memorySampleAgeMs"
|
||||
| "providerRequests" | "providerResponsesCompleted" | "providerRequestBytes" | "providerResponseBytes"
|
||||
| "providerInflightResponses" | "providerInflightResponseBytes" | "providerInflightMs"
|
||||
| "providerResponsesInterrupted" | "providerInterruptedResponseBytes" | "providerInterruptedMs";
|
||||
|
||||
/** 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 } {
|
||||
@@ -208,6 +222,16 @@ function openCodeMemoryFields(
|
||||
? { largestProcessName: largestProcessName as string } : {}),
|
||||
...memoryCountField("largestProcessRssBytes", entry.largestProcessRssBytes),
|
||||
...memoryCountField("memorySampleAgeMs", entry.memorySampleAgeMs),
|
||||
...memoryCountField("providerRequests", entry.providerRequests),
|
||||
...memoryCountField("providerResponsesCompleted", entry.providerResponsesCompleted),
|
||||
...memoryCountField("providerRequestBytes", entry.providerRequestBytes),
|
||||
...memoryCountField("providerResponseBytes", entry.providerResponseBytes),
|
||||
...memoryCountField("providerInflightResponses", entry.providerInflightResponses),
|
||||
...memoryCountField("providerInflightResponseBytes", entry.providerInflightResponseBytes),
|
||||
...memoryCountField("providerInflightMs", entry.providerInflightMs),
|
||||
...memoryCountField("providerResponsesInterrupted", entry.providerResponsesInterrupted),
|
||||
...memoryCountField("providerInterruptedResponseBytes", entry.providerInterruptedResponseBytes),
|
||||
...memoryCountField("providerInterruptedMs", entry.providerInterruptedMs),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user