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 = [