The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(runner): prevent trace scans from delaying live events (#13228)
Dotta1616046c24d6
diff --git a/packages/paperclip-runner/README.md b/packages/paperclip-runner/README.mdindex ff2590152d..bf0f50eb5f 100644--- a/packages/paperclip-runner/README.md+++ b/packages/paperclip-runner/README.md@@ -41,6 +41,16 @@ route/service authorities; it does not copy those rules into this package.## Quick start+Native provider debug-trace correlation uses an incremental index owned by its transport. Pending+event lookups read only newly appended bytes, with a 1 MiB read budget per lookup;+they retry until the observed suffix is indexed. Partial records remain pending,+and trace replacement or truncation invalidates the index. Closing a transport+clears its index. Other active transports cannot evict its progress. Records over+64 KiB are skipped by the correlation index without buffering or parsing their+full contents; the original trace file retains them. Do not restore a full+synchronous trace scan for each pending event: it blocks event delivery and can+leave the board showing an active run after the provider turn has already ended.+The package also builds `paperclip-runner-acpx-sidecar`. This bounded v2stdin/stdout bridge admits the pinned Claude and Codex ACPX profiles. Itvalidates the exact model, session identity, tool catalog, structured input,diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.tsindex 3f169beaa3..ba6ac7897e 100644--- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts+++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts@@ -1,3 +1,4 @@+import { RunnerdTraceFrameIndex } from "./runnerd-trace-frame-index.js";import { codexExecutableReadOnlyRoots } from "../drivers/codex/codex-security-config.js";import { isCanonicalProviderEventType } from "../provider-events.js";import { execFileSync } from "node:child_process";@@ -1509,34 +1510,8 @@ type PendingTraceRehydration = {type PendingDriverTraceInterpretation = CodexTraceInterpretation;-function locateRunnerdTraceFrame(- tracePath: string,- sourceEventId: string,-): { frameId: number | null; nativeChannelSettled: boolean } {- const lines = readFileSync(tracePath, "utf8").split("\n");- let frameId: number | null = null;- let nativeChannelSettled = false;- for (let index = lines.length - 1; index >= 0; index -= 1) {- if (!lines[index]?.trim()) continue;- const entry = record(JSON.parse(lines[index]!));- if (entry.kind === "trace_status" && entry.debugChannel === "rust_native") {- nativeChannelSettled = true;- }- if (- entry.kind !== "interpretation" ||- !Array.isArray(entry.emittedEventIds)- ) {- continue;- }- if ((entry.emittedEventIds as unknown[]).includes(sourceEventId)) {- frameId = typeof entry.frameId === "number" ? entry.frameId : null;- break;- }- }- return { frameId, nativeChannelSettled };-}-function appendRunnerdRehydrationTrace(+ index: RunnerdTraceFrameIndex,tracePath: string | undefined,sourceEventId: string,eventType: string,@@ -1546,7 +1521,7 @@ function appendRunnerdRehydrationTrace(if (!tracePath) return "not_applicable";if (!existsSync(tracePath)) return "retry";try {- const { frameId, nativeChannelSettled } = locateRunnerdTraceFrame(+ const { frameId, nativeChannelSettled } = index.locate(tracePath,sourceEventId,);@@ -1598,6 +1573,7 @@ function appendRunnerdRehydrationTrace(}function appendCodexDriverInterpretationTrace(+ index: RunnerdTraceFrameIndex,tracePath: string | undefined,input: PendingDriverTraceInterpretation,debugSequence: number,@@ -1605,7 +1581,7 @@ function appendCodexDriverInterpretationTrace(if (!tracePath) return "not_applicable";if (!existsSync(tracePath)) return "retry";try {- const { frameId, nativeChannelSettled } = locateRunnerdTraceFrame(+ const { frameId, nativeChannelSettled } = index.locate(tracePath,input.sourceEventId,);@@ -3355,6 +3331,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {#controlPlaneRelease: (() => Promise<void> | void) | null = null;#nextTraceDebugSequence = 1;#traceRehydrationSpoolOverflow = false;+ readonly #traceFrameIndex = new RunnerdTraceFrameIndex();#pendingTraceRehydrations: PendingTraceRehydration[] = [];#pendingDriverTraceInterpretations: PendingDriverTraceInterpretation[] = [];readonly #bridgedRuntimeInputs = new Map<string, { durableTurnId: string }>();@@ -3909,6 +3886,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {const tracePath = this.options.environment?.PAPERCLIP_PROVIDER_TRACE_PATH;if (!tracePath) return;const traceResult = appendCodexDriverInterpretationTrace(+ this.#traceFrameIndex,tracePath,input,this.#nextTraceDebugSequence,@@ -4219,6 +4197,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {}this.#pendingTraceRehydrations = [];this.#pendingDriverTraceInterpretations = [];+ this.#traceFrameIndex.clear();}if (this.#pump !== null) clearInterval(this.#pump);this.#pump = null;@@ -6038,6 +6017,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {visibleNotificationCount: notifications.length,};const traceResult = appendRunnerdRehydrationTrace(+ this.#traceFrameIndex,this.options.environment.PAPERCLIP_PROVIDER_TRACE_PATH,pending.sourceEventId,pending.eventType,@@ -6188,6 +6168,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {const retry: PendingTraceRehydration[] = [];for (const pending of this.#pendingTraceRehydrations) {const traceResult = appendRunnerdRehydrationTrace(+ this.#traceFrameIndex,tracePath,pending.sourceEventId,pending.eventType,@@ -6202,6 +6183,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {const driverRetry: PendingDriverTraceInterpretation[] = [];for (const pending of this.#pendingDriverTraceInterpretations) {const traceResult = appendCodexDriverInterpretationTrace(+ this.#traceFrameIndex,tracePath,pending,this.#nextTraceDebugSequence,diff --git a/packages/paperclip-runner/src/live/runnerd-trace-frame-index.test.ts b/packages/paperclip-runner/src/live/runnerd-trace-frame-index.test.tsnew file mode 100644index 0000000000..2c1731e7ee--- /dev/null+++ b/packages/paperclip-runner/src/live/runnerd-trace-frame-index.test.ts@@ -0,0 +1,158 @@+import { appendFileSync, mkdtempSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { RunnerdTraceFrameIndex } from "./runnerd-trace-frame-index.js";++vi.mock("node:fs", async (importOriginal) => {+ const fs = await importOriginal<typeof import("node:fs")>();+ return { ...fs, readSync: vi.fn(fs.readSync) };+});++const interpretation = (frameId: number, ...emittedEventIds: string[]) =>+ `${JSON.stringify({ kind: "interpretation", frameId, emittedEventIds })}\n`;+const settled = `${JSON.stringify({ kind: "trace_status", debugChannel: "rust_native", status: "complete" })}\n`;++describe("runnerd trace frame index", () => {+ let directory: string;+ let path: string;+ let index: RunnerdTraceFrameIndex;+ beforeEach(() => {+ directory = mkdtempSync(join(tmpdir(), "runnerd-trace-index-"));+ path = join(directory, "trace.ndjson");+ index = new RunnerdTraceFrameIndex();+ vi.mocked(readSync).mockClear();+ });+ afterEach(() => {+ index.clear();+ rmSync(directory, { recursive: true, force: true });+ });++ it("indexes appended records once across repeated pending lookups and both stages", () => {+ const first = interpretation(1, "event-1", "event-2");+ writeFileSync(path, first);+ expect(index.locate(path, "event-2")).toEqual({ frameId: 1, nativeChannelSettled: false });+ for (let i = 0; i < 4096; i++) {+ expect(index.locate(path, `pending-${i}`)).toEqual({ frameId: null, nativeChannelSettled: false });+ expect(index.locate(path, "event-1").frameId).toBe(1);+ }+ expect(readSync).toHaveBeenCalledTimes(1);+ appendFileSync(path, interpretation(2, "pending-1") + settled);+ expect(index.locate(path, "pending-1")).toEqual({ frameId: 2, nativeChannelSettled: true });+ expect(index.locate(path, "missing")).toEqual({ frameId: null, nativeChannelSettled: true });+ expect(readSync).toHaveBeenCalledTimes(2);+ expect(vi.mocked(readSync).mock.calls[1]![4]).toBe(Buffer.byteLength(first));+ });++ it("retains partial lines and split UTF-8 until the append is complete", () => {+ const line = Buffer.from(interpretation(9, "event-π"));+ const split = line.indexOf(Buffer.from("π")) + 2;+ writeFileSync(path, line.subarray(0, split));+ expect(index.locate(path, "event-π").frameId).toBeNull();+ appendFileSync(path, line.subarray(split, line.length - 1));+ expect(index.locate(path, "event-π").frameId).toBeNull();+ appendFileSync(path, "\n");+ expect(index.locate(path, "event-π").frameId).toBe(9);+ });++ it("matches the latest interpretation and only settlement records after it", () => {+ writeFileSync(path, interpretation(1, "same") + settled + interpretation(2, "same"));+ expect(index.locate(path, "same")).toEqual({ frameId: 2, nativeChannelSettled: false });+ expect(index.locate(path, "missing").nativeChannelSettled).toBe(true);+ appendFileSync(path, settled);+ expect(index.locate(path, "same")).toEqual({ frameId: 2, nativeChannelSettled: true });+ });++ it("recovers from a damaged line without discarding valid correlations", () => {+ writeFileSync(path, 'null\n{broken}\n' + interpretation(3, "event"));+ expect(index.locate(path, "event").frameId).toBe(3);+ });++ it("invalidates old correlations when the trace is truncated or replaced", () => {+ writeFileSync(path, interpretation(12345, "old-long-event") + settled);+ expect(index.locate(path, "old-long-event").frameId).toBe(12345);+ writeFileSync(path, interpretation(2, "new"));+ expect(index.locate(path, "old-long-event")).toEqual({ frameId: null, nativeChannelSettled: false });+ expect(index.locate(path, "new").frameId).toBe(2);+ writeFileSync(join(directory, "replacement"), interpretation(4, "replacement-event"));+ renameSync(join(directory, "replacement"), path);+ expect(index.locate(path, "new").frameId).toBeNull();+ expect(index.locate(path, "replacement-event").frameId).toBe(4);+ });++ it("bounds each read while making forward progress through a large trace", () => {+ const content = JSON.stringify({ kind: "frame", rawBase64: "x".repeat(3 * 1024 * 1024) }) + "\n" + interpretation(4, "last");+ writeFileSync(path, content);+ expect(index.locate(path, "last").frameId).toBeNull();+ expect(index.locate(path, "last").frameId).toBeNull();+ expect(index.locate(path, "last").frameId).toBeNull();+ expect(index.locate(path, "last").frameId).toBe(4);+ for (const call of vi.mocked(readSync).mock.calls) expect(call[3]).toBeLessThanOrEqual(1024 * 1024);+ const calls = vi.mocked(readSync).mock.calls.length;+ for (let i = 0; i < 1000; i++) index.locate(path, "missing");+ expect(readSync).toHaveBeenCalledTimes(calls);+ });++ it("retries missing files and clears retained indexes on close", () => {+ expect(() => index.locate(path, "event")).toThrow();+ writeFileSync(path, interpretation(1, "event"));+ expect(index.locate(path, "event").frameId).toBe(1);+ index.clear();+ expect(index.locate(path, "event").frameId).toBe(1);+ expect(readSync).toHaveBeenCalledTimes(2);+ });++ it("does not resolve from an incomplete prefix of a large trace", () => {+ writeFileSync(path, interpretation(1, "same") + settled ++ JSON.stringify({ kind: "frame", rawBase64: "x".repeat(1024 * 1024) }) + "\n" ++ interpretation(2, "same"));+ expect(index.locate(path, "same")).toEqual({ frameId: null, nativeChannelSettled: false });+ expect(index.locate(path, "same")).toEqual({ frameId: 2, nativeChannelSettled: false });+ });++ it("keeps progress for more than 16 interleaved active transports", () => {+ const raw = JSON.stringify({ kind: "frame", rawBase64: "x".repeat(2 * 1024 * 1024) }) + "\n";+ const traces = Array.from({ length: 24 }, (_, i) => {+ const tracePath = join(directory, `trace-${i}.ndjson`);+ writeFileSync(tracePath, raw + interpretation(i, "last"));+ return { tracePath, index: new RunnerdTraceFrameIndex() };+ });+ for (let round = 0; round < 3; round++) {+ for (const [i, trace] of traces.entries()) {+ expect(trace.index.locate(trace.tracePath, "last").frameId).toBe(round === 2 ? i : null);+ }+ }+ expect(readSync).toHaveBeenCalledTimes(72);+ for (let i = 0; i < 24; i++) {+ expect(vi.mocked(readSync).mock.calls[24 + i]![4]).toBe(1024 * 1024);+ expect(vi.mocked(readSync).mock.calls[48 + i]![4]).toBe(2 * 1024 * 1024);+ }+ });++ it("skips oversized records across appends without decoding or parsing them", () => {+ const parse = vi.spyOn(JSON, "parse");+ try {+ writeFileSync(path, '{"kind":"frame","rawBase64":"');+ const chunk = "x".repeat(32 * 1024);+ for (let i = 0; i < 256; i++) {+ appendFileSync(path, chunk);+ expect(index.locate(path, "after").frameId).toBeNull();+ }+ expect(parse).not.toHaveBeenCalled();+ appendFileSync(path, '"}\n' + interpretation(7, "after"));+ expect(index.locate(path, "after").frameId).toBe(7);+ expect(parse).toHaveBeenCalledTimes(1);+ expect(Buffer.byteLength(parse.mock.calls[0]![0])).toBeLessThan(64 * 1024);+ } finally {+ parse.mockRestore();+ }+ });++ it("waits for a partial later interpretation before returning an older match", () => {+ const next = interpretation(2, "same");+ writeFileSync(path, interpretation(1, "same") + next.slice(0, -1));+ expect(index.locate(path, "same").frameId).toBeNull();+ appendFileSync(path, "\n");+ expect(index.locate(path, "same").frameId).toBe(2);+ });+});diff --git a/packages/paperclip-runner/src/live/runnerd-trace-frame-index.ts b/packages/paperclip-runner/src/live/runnerd-trace-frame-index.tsnew file mode 100644index 0000000000..4916c23529--- /dev/null+++ b/packages/paperclip-runner/src/live/runnerd-trace-frame-index.ts@@ -0,0 +1,118 @@+import { closeSync, fstatSync, openSync, readSync, statSync } from "node:fs";++const READ_BUDGET_BYTES = 1024 * 1024;+const MAX_RECORD_BYTES = 64 * 1024;++type Frame = { frameId: number | null; record: number };++/** Incremental, best-effort index of the append-only native debug trace. */+export class RunnerdTraceFrameIndex {+ #identity = "";+ #offset = 0;+ #mtimeMs = 0;+ #record = 0;+ #settledAt = 0;+ #partial: Buffer[] = [];+ #partialBytes = 0;+ #discardUntilNewline = false;+ #frames = new Map<string, Frame>();++ locate(tracePath: string, sourceEventId: string) {+ const stat = statSync(tracePath);+ const identity = `${stat.dev}:${stat.ino}`;+ if (+ identity !== this.#identity || stat.size < this.#offset ||+ (stat.size === this.#offset && stat.mtimeMs !== this.#mtimeMs)+ ) {+ this.clear();+ this.#identity = identity;+ }+ this.#mtimeMs = stat.mtimeMs;+ if (stat.size > this.#offset) {+ const fd = openSync(tracePath, "r");+ try {+ const opened = fstatSync(fd);+ // Do not mix a replacement file with the prefix we already indexed.+ if (`${opened.dev}:${opened.ino}` !== identity) {+ return { frameId: null, nativeChannelSettled: false };+ }+ const buffer = Buffer.allocUnsafe(Math.min(READ_BUDGET_BYTES, stat.size - this.#offset));+ const bytes = readSync(fd, buffer, 0, buffer.length, this.#offset);+ this.#offset += bytes;+ let start = 0;+ for (let end = buffer.indexOf(10); end !== -1 && end < bytes; end = buffer.indexOf(10, start)) {+ this.#consume(buffer.subarray(start, end), true);+ start = end + 1;+ }+ if (start < bytes) this.#consume(buffer.subarray(start, bytes), false);+ } finally {+ closeSync(fd);+ }+ }+ // Until the observed suffix is indexed, a later interpretation or terminal+ // status may supersede the prefix. Let the existing pending queue retry.+ if (this.#offset < stat.size || this.#partialBytes > 0 || this.#discardUntilNewline) {+ return { frameId: null, nativeChannelSettled: false };+ }+ const frame = this.#frames.get(sourceEventId);+ return {+ frameId: frame?.frameId ?? null,+ nativeChannelSettled: this.#settledAt > (frame?.record ?? 0),+ };+ }++ clear() {+ this.#identity = "";+ this.#offset = 0;+ this.#mtimeMs = 0;+ this.#record = 0;+ this.#settledAt = 0;+ this.#partial = [];+ this.#partialBytes = 0;+ this.#discardUntilNewline = false;+ this.#frames.clear();+ }++ #consume(part: Buffer, terminated: boolean) {+ if (this.#discardUntilNewline || this.#partialBytes + part.length > MAX_RECORD_BYTES) {+ // Raw provider frames can be tens of MiB. Correlation needs only small+ // interpretation/status records; leave oversized records in the raw file.+ this.#partial = [];+ this.#partialBytes = 0;+ this.#discardUntilNewline = !terminated;+ return;+ }+ if (!terminated) {+ this.#partial.push(Buffer.from(part));+ this.#partialBytes += part.length;+ return;+ }+ const line = this.#partialBytes > 0+ ? Buffer.concat([...this.#partial, part]).toString("utf8")+ : part.toString("utf8");+ this.#partial = [];+ this.#partialBytes = 0;+ this.#indexLine(line);+ }++ #indexLine(line: string) {+ if (!line.trim()) return;+ let entry: Record<string, unknown>;+ try {+ entry = JSON.parse(line);+ } catch {+ // A damaged debug record must not block later valid correlations.+ return;+ }+ if (!entry || typeof entry !== "object") return;+ this.#record += 1;+ if (entry.kind === "trace_status" && entry.debugChannel === "rust_native") {+ this.#settledAt = this.#record;+ }+ if (entry.kind !== "interpretation" || !Array.isArray(entry.emittedEventIds)) return;+ const frameId = typeof entry.frameId === "number" ? entry.frameId : null;+ for (const eventId of entry.emittedEventIds) {+ if (typeof eventId === "string") this.#frames.set(eventId, { frameId, record: this.#record });+ }+ }+}