Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

[RSI, bug] fix(kernel): bound REPL protocol frame sizes in kernel and host (#2423)

Seth Kartenc91e6e991fc0
diff --git a/packages/coding-agent/.changes/bound-repl-protocol-frames.md b/packages/coding-agent/.changes/bound-repl-protocol-frames.md
new file mode 100644
index 0000000000..f36de25766
--- /dev/null
+++ b/packages/coding-agent/.changes/bound-repl-protocol-frames.md
@@ -0,0 +1 @@
+- Fixed kernel REPL protocol output that could buffer unbounded memory in the host: Python-level stdout/stderr writes now ship as 64 Ki-char frames, oversized result reprs are capped at 1 Mi chars with a marker, oversized display payloads fail the cell, and the host repairs a kernel that streams an oversized protocol line.
diff --git a/packages/coding-agent/src/core/kernel/repl-manager.ts b/packages/coding-agent/src/core/kernel/repl-manager.ts
index 4e58527563..584e5e76f0 100644
--- a/packages/coding-agent/src/core/kernel/repl-manager.ts
+++ b/packages/coding-agent/src/core/kernel/repl-manager.ts
@@ -70,6 +70,10 @@ const REPAIR_STEP_TIMEOUT_MS = 30_000;
const MAX_HANDLED_HOST_REQUEST_IDS = 1024;
// Cap for unattributed background output buffered between and during cells.
const MAX_BACKGROUND_OUTPUT_CHARS = 64 * 1024;
+// Largest legit frame is an attachment display event, base64 capped at
+// MAX_ATTACHMENT_DATA_CHARS; a line that cannot complete within this ceiling is
+// corruption the protocol repair owns, not output worth buffering until OOM.
+const MAX_PROTOCOL_LINE_CHARS = 32 * 1024 * 1024;
const MAX_KERNEL_STDERR_CHARS = 8 * 1024;
const MAX_KERNEL_STDERR_LOG_BYTES = 5 * 1024 * 1024;
@@ -391,9 +395,18 @@ export class ReplKernelManager {
private wireChild(child: ChildProcess): void {
const decoder = new StringDecoder("utf8");
let buffered = "";
+ // A poisoned child's residue must not grow the buffer again before the
+ // protocol repair kills it.
+ let poisoned = false;
child.stdout?.on("data", (buf: Buffer) => {
- if (this.child !== child) return;
+ if (this.child !== child || poisoned) return;
buffered += decoder.write(buf);
+ if (buffered.length > MAX_PROTOCOL_LINE_CHARS) {
+ poisoned = true;
+ buffered = "";
+ this.failProtocolFrame(child, `oversized protocol line: exceeds ${MAX_PROTOCOL_LINE_CHARS} chars`);
+ return;
+ }
let newline = buffered.indexOf("\n");
while (newline !== -1) {
if (this.child !== child) return;
@@ -864,6 +877,9 @@ export class ReplKernelManager {
execution.stdout = execution.stdout.slice(0, execution.maxChars);
execution.stdoutTruncated = true;
}
+ } else if (text.length > 0) {
+ // The buffer filled exactly on an earlier frame; the dropped remainder still counts as truncation.
+ execution.stdoutTruncated = true;
}
} else {
if (execution.stderr.length < execution.maxChars) {
@@ -872,6 +888,8 @@ export class ReplKernelManager {
execution.stderr = execution.stderr.slice(0, execution.maxChars);
execution.stderrTruncated = true;
}
+ } else if (text.length > 0) {
+ execution.stderrTruncated = true;
}
}
execution.opts.onStream?.(text, type);
diff --git a/packages/coding-agent/test/repl-kernel-protocol-corruption.test.ts b/packages/coding-agent/test/repl-kernel-protocol-corruption.test.ts
index 3e2ee779f3..89093ab2e2 100644
--- a/packages/coding-agent/test/repl-kernel-protocol-corruption.test.ts
+++ b/packages/coding-agent/test/repl-kernel-protocol-corruption.test.ts
@@ -63,6 +63,7 @@ input.on("line", (line) => {
process.stdout.write("BROKEN-" + "x".repeat(400) + "\\n");
return;
}
+ if (request.code === "corrupt-huge-line") return process.stdout.write("x".repeat(33 * 1024 * 1024));
if (request.code === "corrupt-idle") {
process.stdout.write(JSON.stringify({ event: "done", id: request.id, status: "ok" }) + "\\n42\\n");
return;
@@ -356,6 +357,16 @@ describe("ReplKernelManager corrupt protocol repair", () => {
}
});
+ it("repairs after an oversized unterminated protocol line", async () => {
+ const { manager } = newManager();
+ try {
+ await expect(manager.execute("corrupt-huge-line")).rejects.toThrow(/oversized protocol line/);
+ expect((await manager.execute("read")).status).toBe("ok");
+ } finally {
+ await manager.shutdown({ snapshot: true, drainHostRequests: true });
+ }
+ });
+
it("repairs an object frame with an unknown event kind instead of hanging the request", async () => {
const { manager, countPath } = newManager();
try {
diff --git a/prime-agent-runtime/src/rlm/repl.md b/prime-agent-runtime/src/rlm/repl.md
index c0cb012775..122bda80fe 100644
--- a/prime-agent-runtime/src/rlm/repl.md
+++ b/prime-agent-runtime/src/rlm/repl.md
@@ -49,12 +49,18 @@ runtime keeps serving. Closing stdin is equivalent to `shutdown`.
tasks inherit the spawning cell's id (even after that cell finished). `null`
for user threads, raw fd writes (`os.write`, C extensions, subprocesses),
and anything else without provable ownership — bytes read from the fd pipes
- are never attributed to a cell.
+ are never attributed to a cell. A Python-level write ships at most 64 Ki
+ characters per frame; a larger write arrives as multiple events in order.
- `{"event":"result","id":str,"text":str}` — `repr` of the cell's trailing
expression when the body ends in an expression whose value is not `None`.
- The value is also bound to `_` in the namespace.
+ The value is also bound to `_` in the namespace. The `repr` content is capped
+ at 1,048,576 characters; a longer `repr` is truncated to the cap and a trailing
+ truncation marker is appended after it, so the total `text` can exceed the cap
+ by the marker's length.
- `{"event":"display","id":str|null,"data":{mime:payload,...}}` — one dict of
- MIME type to JSON payload, shipped verbatim from `emit()`. `id` rides task
+ MIME type to JSON payload, shipped verbatim from `emit()`. A payload whose
+ JSON encoding exceeds 16 Mi characters is refused: `emit()` raises
+ `ValueError` in the calling cell. `id` rides task
context: an asyncio task spawned by a cell keeps that cell's id even after
the cell finishes; user threads emit `null`.
- `{"event":"host_request","id":str,"data":{...}}` — one typed request from
diff --git a/prime-agent-runtime/src/rlm/repl.py b/prime-agent-runtime/src/rlm/repl.py
index 8f888c1c53..6ead01fa71 100644
--- a/prime-agent-runtime/src/rlm/repl.py
+++ b/prime-agent-runtime/src/rlm/repl.py
@@ -34,6 +34,17 @@ PROTOCOL_VERSION = 3
DEFAULT_SNAPSHOT_MAX_BYTES = 256 * 1024 * 1024
DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES = 16 * 1024 * 1024
+# Stream writes must fit one protocol frame: the host buffers whole lines
+# before its per-execution truncation, and raw fd writes already arrive as
+# 64 KiB pump chunks.
+_STREAM_FRAME_TEXT_CAP = 64 * 1024
+# The host truncates results at a smaller per-execution maxChars, so this only
+# bounds a pathological repr in transit.
+_RESULT_TEXT_CAP = 1_048_576
+_RESULT_TRUNCATION_MARKER = f"\n[... result truncated at {_RESULT_TEXT_CAP} characters ...]"
+# Oversized display payloads fail the cell instead of wedging host memory.
+_DISPLAY_PAYLOAD_CAP = 16 * 1024 * 1024
+
# Names the session bootstrap re-creates on every start; never snapshotted.
_ALWAYS_SKIP = {"rlm", "mcp", "bash", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}
# IPython-injected names that may appear in a snapshot payload; never restored.
@@ -97,9 +108,11 @@ def emit(data: dict[str, Any]) -> None:
# Strict-dumps validation: default allow_nan=True would let NaN/Infinity
# serialize as non-JSON text and tear the host's protocol framing (a
# non-serializable value already raises in _send before any bytes are
- # written, so NaN is the only corruption vector). Payloads are small, so
- # the throwaway serialization here is cheap; _send re-serializes.
- json.dumps(data, allow_nan=False)
+ # written, so NaN is the only corruption vector). The encoded length
+ # enforces the display frame cap; _send re-serializes.
+ encoded = json.dumps(data, allow_nan=False)
+ if len(encoded) > _DISPLAY_PAYLOAD_CAP:
+ raise ValueError(f"display payload exceeds the {_DISPLAY_PAYLOAD_CAP}-character frame cap")
_send({"event": "display", "id": _current_cell.get(), "data": data})
@@ -295,13 +308,24 @@ class _TaggedWriter(io.TextIOBase):
def __init__(self, stream: str, fallback_fd: int) -> None:
self._stream = stream
self._fallback_fd = fallback_fd
+ # Keeps one write()'s frames contiguous under concurrent writers.
+ self._frame_lock = threading.Lock()
self._buffer = _TaggedBuffer(fallback_fd)
def write(self, text: str) -> int:
if not isinstance(text, str):
raise TypeError(f"write() argument must be str, not {type(text).__name__}")
if text:
- _send({"event": self._stream, "id": _current_cell.get(), "text": text})
+ cell_id = _current_cell.get()
+ with self._frame_lock:
+ for start in range(0, len(text), _STREAM_FRAME_TEXT_CAP):
+ _send(
+ {
+ "event": self._stream,
+ "id": cell_id,
+ "text": text[start : start + _STREAM_FRAME_TEXT_CAP],
+ }
+ )
return len(text)
def flush(self) -> None:
@@ -592,6 +616,8 @@ async def _handle_execute(req: dict[str, Any], ns: dict[str, Any]) -> None:
result_text = repr(value)
except BaseException as exc: # noqa: BLE001 - a broken __repr__ is a cell error
status, error = "error", _error_event(cell_id, exc)
+ if result_text is not None and len(result_text) > _RESULT_TEXT_CAP:
+ result_text = result_text[:_RESULT_TEXT_CAP] + _RESULT_TRUNCATION_MARKER
_drain_output()
finally:
# Close the interrupt window before the protocol sends so a
diff --git a/prime-agent-runtime/test/test_repl.py b/prime-agent-runtime/test/test_repl.py
index a5c914e94c..c3ca8ab3a0 100644
--- a/prime-agent-runtime/test/test_repl.py
+++ b/prime-agent-runtime/test/test_repl.py
@@ -729,6 +729,21 @@ class ReplTest(unittest.TestCase):
self.assertEqual(one(follow, "result")["text"], "2")
self.assertEqual(one(follow, "done")["status"], "ok")
+ def test_large_write_ships_bounded_stream_frames(self):
+ events = self.repl.execute("chunk", "import sys\nsys.stdout.write('x' * 300_000)")
+ frames = [e["text"] for e in events if e.get("event") == "stdout"]
+ self.assertEqual("".join(frames), "x" * 300_000)
+ self.assertTrue(all(len(frame) <= 65536 for frame in frames))
+
+ def test_oversized_repr_and_display_payloads_are_capped(self):
+ code = "class C:\n def __repr__(self):\n return 'x' * 3_000_000\nC()"
+ events = self.repl.execute("big-repr", code)
+ expected = "x" * 1_048_576 + "\n[... result truncated at 1048576 characters ...]"
+ self.assertEqual(one(events, "result")["text"], expected)
+ events = self.repl.execute("emit-big", "from rlm.repl import emit\nemit({'text/plain': 'x' * 17_000_000})")
+ self.assertEqual(one(events, "error")["ename"], "ValueError")
+ self.assertEqual(one(events, "done")["status"], "error")
+
def test_bash_integration(self):
events = self.repl.execute(
"sh1", "from rlm import bash\nresult = await bash('echo repl-bash')\nresult.output.strip()"