From dd7fc1f90a13c7a297749c12f97ca9169135a274 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:08:25 -0500 Subject: [PATCH] fix: raise the native journal read limit to 256 MiB (#14711) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native sessions persist control-plane state so they can resume safely. > - The state includes committed provider history needed for recovery. > - The server, runnerd recovery, and durable control plane validate this state before trusting its identity. > - Their differing 64 MiB and 192 MiB limits can reject a valid journal before recovery. > - This pull request aligns all three local state limits at 256 MiB. > - Larger files remain bounded, while recovery can read larger valid histories. ## Linked Issues or Issue Description Refs #13882 Refs #14312 ## What Changed - Raise the server and runnerd recovery limits from 64 MiB to 256 MiB, and align the durable control-plane limit from 192 MiB to 256 MiB. - Add coverage for a valid history above 64 MiB and rejection above 256 MiB. ## Verification - Matching server recovery passed with more than 64 MiB of actual committed event payloads (128 events with 512 KiB deltas). - The real runnerd exact-authority resume regression with the test Codex provider passed with 193 MiB of valid JSON whitespace appended. It crosses the former 192 MiB core limit and confirms the same provider identity. This exercises the runner process and durable control plane with a simulated provider, not a live OpenAI API call. This test used approximately 1.15 GiB peak RSS. - The actual runnerd reader accepted valid 256 MiB JSON and rejected valid 256 MiB + 1 byte. The reader call took 231 ms; the fresh process peaked at 1,244 MiB RSS. - Server tests reject mismatched identity above 64 MiB and files above 256 MiB. - `pnpm -r typecheck`, `pnpm build`, and `git diff --check` passed. - Full local `pnpm test:run`: 13,730 passed, 575 skipped, 7 failed across 6 files. All failures were embedded PostgreSQL startup errors after five attempts. They affected agent hiring, instruction revisions, environment images, reviewed chat bindings, issue monitoring, and legacy continuation authority. The focused journal tests passed; the latest pushed head passed all ordinary CI checks. Superagent is the only blocking check. ## Risks - **Open review concern:** Greptile is 5/5, but Superagent is `ACTION_REQUIRED` with two P2 findings on the server and runnerd readers. Both flag the increased synchronous parsing and memory cost. This PR keeps the requested fixed-limit change small. It does not add a worker parser or a process-wide memory budget. This resource tradeoff needs review before merge. - Large state parsing is synchronous and can consume several times the file size in memory. - Remote checkpoint archive and expanded-size limits remain 64 MiB, so this change alone does not make larger remote checkpoint transfers portable. ## Model Used - OpenAI Codex, GPT-6, with delegated assistance from `gpt-6-luna` at high reasoning effort; tool use and code execution. The GPT-6 context window is not exposed in this task runtime. ## 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 - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] 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 --------- Co-authored-by: Paperclip --- doc/execution-semantics.md | 5 + .../durable-prp-control-plane.ts | 2 +- .../src/live/runnerd-codex-transport.test.ts | 54 +++++++- .../src/live/runnerd-codex-transport.ts | 5 +- .../native-session-executor.test.ts | 126 ++++++++++++++++-- .../native-runtime/native-session-executor.ts | 4 +- 6 files changed, 176 insertions(+), 20 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 4f76aa6abb0..fb1c1cae671 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1256,6 +1256,11 @@ turn finishes during shutdown, its release checkpoints the session before returning instead of leaving a new idle owner behind. If checkpointing fails, the retained state continues to block unverified reuse. +Local durable control-plane state is bounded at 256 MiB in the server, +runnerd recovery, and durable control-plane readers. These paths synchronously +read and parse the full JSON file, so memory use and parse time grow with file +size. Remote checkpoint archive and expanded-size limits remain 64 MiB. + ### Warm sandbox continuity For the native runner, warm mode requests a reusable sandbox lease **before** diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index ad3a029c7ab..b3385626ecb 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -58,7 +58,7 @@ const maxCommands = 500; // polling turn regains the event loop. Match the transport's explicit deferred // event bound so a valid burst is not compacted before it can be observed. const maxCommittedEventWindow = 4_096; -const maxStateBytes = 192 * 1024 * 1024; +const maxStateBytes = 256 * 1024 * 1024; const authChallengeTtlMs = 5_000; const stableIdPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,239}$/; const runnerDigestPattern = /^sha256:[0-9a-f]{64}$/; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index f959b4213ad..7ee61f16def 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -4,12 +4,14 @@ import { mkdir, lstat, mkdtemp, + open, readFile, readdir, readlink, rename, rm, stat, + truncate, writeFile, } from "node:fs/promises"; import { createHash, randomUUID } from "node:crypto"; @@ -421,6 +423,38 @@ it("requires an explicit retained state directory before adopting a runner", () expect(signal).not.toHaveBeenCalled(); }); +it("reads valid control-plane history above 64 MiB and rejects it above 256 MiB", async () => { + const root = await mkdtemp(join(tmpdir(), "runnerd-large-control-state-")); + const stateDirectory = join(root, "control-plane"); + const statePath = join(stateDirectory, "control-plane-state.json"); + try { + await mkdir(stateDirectory, { recursive: true }); + await writeFile( + statePath, + JSON.stringify({ + committedEvents: [ + { + eventType: "history", + payload: { text: "x".repeat(64 * 1024 * 1024 + 1) }, + }, + ], + }), + ); + expect( + runnerdRecoveryInternals.readControlPlaneState(stateDirectory), + ).toMatchObject({ + committedEvents: [{ eventType: "history" }], + }); + + await truncate(statePath, 256 * 1024 * 1024 + 1); + expect(() => + runnerdRecoveryInternals.readControlPlaneState(stateDirectory), + ).toThrow("native_runner_control_plane_state_unsafe"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + it("carries the provider attachment seed across consecutive authority rotations", () => { const baseIdentity = { runnerInstanceId: "runner-warm-seed", @@ -6358,7 +6392,7 @@ it.each([ }, ); -it.each([0, 3 * 1024 * 1024])( +it.each([0, 193 * 1024 * 1024])( "probes an exact-authority resume with %i extra journal bytes and confirms its live provider identity", async (extraJournalBytes) => { const stateDirectory = await mkdtemp( @@ -6411,10 +6445,20 @@ it.each([0, 3 * 1024 * 1024])( "control-plane-state.json", ); if (extraJournalBytes > 0) { - const journal = await readFile(statePath, "utf8"); - const paddedJournal = `${journal}${" ".repeat(extraJournalBytes)}`; - await writeFile(statePath, paddedJournal); - expect(Buffer.byteLength(paddedJournal)).toBeGreaterThan(2 * 1024 * 1024); + const padding = Buffer.alloc(1024 * 1024, 0x20); + const stateHandle = await open(statePath, "a"); + try { + for (let remaining = extraJournalBytes; remaining > 0;) { + const bytesToWrite = Math.min(remaining, padding.length); + await stateHandle.write(padding, 0, bytesToWrite); + remaining -= bytesToWrite; + } + } finally { + await stateHandle.close(); + } + expect((await stat(statePath)).size).toBeGreaterThan( + 64 * 1024 * 1024, + ); } const beforeResume = JSON.parse(await readFile(statePath, "utf8")) as { commands: Array<{ type: string }>; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 2176cbd4d1a..3947426a073 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -150,13 +150,15 @@ export function withCodexCollaborationRuntimeInstructions( return `${base}\n\n${CODEX_COLLABORATION_RUNTIME_INSTRUCTIONS}`; } +const CONTROL_PLANE_STATE_MAX_BYTES = 256 * 1024 * 1024; + function readControlPlaneState(directory: string): Record { const path = resolve(directory, "control-plane-state.json"); const metadata = lstatSync(path); if ( metadata.isSymbolicLink() || !metadata.isFile() || - metadata.size > 64 * 1024 * 1024 + metadata.size > CONTROL_PLANE_STATE_MAX_BYTES ) { throw new Error("native_runner_control_plane_state_unsafe"); } @@ -6741,6 +6743,7 @@ export const runnerdLaunchProfileInternals = Object.freeze({ export const runnerdRecoveryInternals = Object.freeze({ completedMaintenanceTerminalReceipt, completedMaintenanceTerminalReplayMatches, + readControlPlaneState, awaitProviderDrainBarrier, awaitAdoptedRunnerAuthentication, awaitRunnerSuspensionBarrier, diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index ca537cb0fb6..8a0d9c3f74b 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -6,6 +6,7 @@ import { lstat, mkdir, mkdtemp, + open, readdir, realpath, readFile, @@ -9746,7 +9747,7 @@ describe("runnerd provider runtime wiring", () => { } }); - it("resumes an existing scoped authority only for the exact current run", async () => { + it("resumes a matching scoped authority with valid history above 64 MiB", async () => { const stateBase = await mkdtemp( join(tmpdir(), "paperclip-current-scoped-state-"), ); @@ -9785,9 +9786,65 @@ describe("runnerd provider runtime wiring", () => { state.createTransport.mock.calls[0]![0].stateDirectory!; await mkdir(join(scopedRoot, "control-plane"), { recursive: true }); await mkdir(join(scopedRoot, "runner"), { recursive: true }); - await writeFile( - join(scopedRoot, "control-plane", "control-plane-state.json"), - JSON.stringify(durableControlPlaneState(identity)), + const controlPlaneStatePath = join( + scopedRoot, + "control-plane", + "control-plane-state.json", + ); + const stateWithHistory = JSON.stringify({ + ...durableControlPlaneState(identity), + committedEvents: [], + }); + const committedEventsMarker = '"committedEvents":[]'; + const eventsStart = stateWithHistory.indexOf(committedEventsMarker); + expect(eventsStart).toBeGreaterThanOrEqual(0); + const eventArrayStart = eventsStart + '"committedEvents":'.length; + const historyPrefix = stateWithHistory.slice(0, eventArrayStart + 1); + const historySuffix = stateWithHistory.slice(eventArrayStart + 2); + const payloadBytesPerEvent = 512 * 1024; + const eventCount = 128; + const delta = "x".repeat(payloadBytesPerEvent); + const event = (sourceSeq: number) => { + const sourceEventId = `event-current-scoped-state-${sourceSeq}`; + return JSON.stringify({ + sourceSeq, + sourceEventId, + eventType: "item.delta", + priority: 1, + envelope: { + schema: "paperclip.prp.event.v1", + schemaVersion: 1, + sourceKind: "runner", + sourceInstanceId: identity.runnerInstanceId, + sourceEventId, + sourceSeq, + normalizedSessionId: identity.normalizedSessionId, + runId: identity.runId, + turnId: "turn-current-scoped-state", + itemId: "item-current-scoped-state", + eventType: "item.delta", + priority: 1, + emittedAt: "2026-09-30T00:00:00.000Z", + payload: { delta }, + }, + deliveryCount: 1, + logicalEffectCount: 1, + }); + }; + await writeFile(controlPlaneStatePath, historyPrefix); + const stateHandle = await open(controlPlaneStatePath, "a"); + try { + for (let index = 0; index < eventCount; index += 1) { + if (index > 0) await stateHandle.write(","); + await stateHandle.write(event(index + 1)); + } + await stateHandle.write("]"); + await stateHandle.write(historySuffix); + } finally { + await stateHandle.close(); + } + expect((await lstat(controlPlaneStatePath)).size).toBeGreaterThan( + 64 * 1024 * 1024, ); await writeFile( join(scopedRoot, "runner", "runner-state.json"), @@ -10040,7 +10097,14 @@ describe("runnerd provider runtime wiring", () => { }, ); - it.each(["missing", "malformed", "unknown_schema", "mismatched", "oversized"] as const)( + it.each([ + "missing", + "malformed", + "unknown_schema", + "mismatched", + "large_mismatched", + "oversized", + ] as const)( "fails closed on %s durable identity in an existing scoped root", async (caseName) => { const stateBase = await mkdtemp( @@ -10101,6 +10165,25 @@ describe("runnerd provider runtime wiring", () => { ), ); } + if (caseName === "large_mismatched") { + await writeFile( + join(scopedRoot, "control-plane", "control-plane-state.json"), + JSON.stringify({ + ...durableControlPlaneState({ + runId: scopedExecution.binding.runId, + normalizedSessionId: "session-owned-by-another-scope", + runnerInstanceId: "runner-owned-by-another-scope", + environmentLeaseId: "lease-owned-by-another-scope", + }), + committedEvents: [ + { + eventType: "history", + payload: { text: "x".repeat(64 * 1024 * 1024 + 1) }, + }, + ], + }), + ); + } if (caseName === "oversized") { const identity = { runId: scopedExecution.binding.runId, @@ -10108,12 +10191,33 @@ describe("runnerd provider runtime wiring", () => { runnerInstanceId: `runner-${caseName}-scoped-state`, environmentLeaseId: scopedExecution.binding.executionWorkspaceId, }; - // Valid JSON and valid ready authority: only the byte bound rejects - // this file. Malformed sparse padding would not test that boundary. - await writeFile( - join(scopedRoot, "control-plane", "control-plane-state.json"), - JSON.stringify(durableControlPlaneState(identity)).padEnd(64 * 1024 * 1024 + 1, " "), + // Keep the file valid JSON so only the byte limit rejects it. Append + // bounded whitespace chunks to avoid a 256 MiB test allocation. + const statePath = join( + scopedRoot, + "control-plane", + "control-plane-state.json", ); + const serializedState = JSON.stringify( + durableControlPlaneState(identity), + ); + await writeFile( + statePath, + serializedState, + ); + const padding = Buffer.alloc(1024 * 1024, 0x20); + const remainingBytes = + 256 * 1024 * 1024 + 1 - Buffer.byteLength(serializedState); + const stateHandle = await open(statePath, "a"); + try { + for (let remaining = remainingBytes; remaining > 0;) { + const bytesToWrite = Math.min(remaining, padding.length); + await stateHandle.write(padding, 0, bytesToWrite); + remaining -= bytesToWrite; + } + } finally { + await stateHandle.close(); + } await mkdir(join(scopedRoot, "runner"), { recursive: true }); await writeFile( join(scopedRoot, "runner", "runner-state.json"), @@ -10138,7 +10242,7 @@ describe("runnerd provider runtime wiring", () => { expect(quarantineEntries).toHaveLength(1); expect(quarantineEntries[0]!.isDirectory()).toBe(true); expect(quarantineEntries[0]!.name).toContain( - caseName === "mismatched" + caseName === "mismatched" || caseName === "large_mismatched" ? ".identity_mismatch." : ".identity_indeterminate.", ); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 36884c09809..a72722aba4b 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -283,8 +283,8 @@ const MAX_REMOTE_CHECKPOINT_EXPANDED_BYTES = 64 * 1024 * 1024; const MAX_REMOTE_CHECKPOINT_ENTRIES = 20_000; // Identity is read from the complete control-plane state, including its PRP // event window. Match the transport's bounded reader so verbose valid turns do -// not lose continuation authority merely because their history exceeds 2 MiB. -const NATIVE_CONTROL_PLANE_STATE_MAX_BYTES = 64 * 1024 * 1024; +// not lose continuation authority merely because their history exceeds 64 MiB. +const NATIVE_CONTROL_PLANE_STATE_MAX_BYTES = 256 * 1024 * 1024; const NATIVE_RUNNER_STATE_MAX_BYTES = 16 * 1024 * 1024; const NATIVE_WARM_CHECKPOINT_MAX_BYTES = 8 * 1024 * 1024; const CODEX_HOME_NON_PERSISTENT_ENTRIES = [