mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(runner): prevent trace scans from delaying live events (#13228)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native runner sends events that keep task state and steering
controls current.
> - Debug trace correlation reread and parsed the full trace for each
pending event.
> - Repeated scans blocked event delivery and left task state minutes
behind the provider.
> - This pull request indexes appended trace records once and reuses
those correlations.
> - Operators get current run state while native trace evidence remains
available.
## Linked Issues or Issue Description
**What happened?**
Native runs appeared live after their provider turn ended. Steering was
unavailable while the board still showed an active run. A CPU profile
attributed 93% of sampled time to trace lookup and file reads.
**Expected behavior**
Debug trace correlation must not delay run events or task state by
minutes.
**Steps to reproduce**
1. Enable native provider trace capture for a Codex run.
2. Produce a long event stream with pending correlations.
3. Compare provider event times with persisted run event times.
**Paperclip version**
Reproduced on source build 6dd48cad43.
**Deployment mode**
Self-hosted server with the native Codex runner.
Related event-delivery work: Refs #12208. This fix addresses synchronous
trace lookup rather than disconnect draining. Searches found no
duplicate trace-index fix.
## What Changed
- Add a transport-owned incremental index for native trace frame
correlations.
- Read at most 1 MiB per lookup and retry incomplete prefixes and
partial records.
- Preserve latest-frame and terminal-status ordering. Invalidate
replaced or truncated traces.
- Clear each index on transport close. Keep active indexes independent.
- Skip correlation records over 64 KiB without buffering or parsing
their full contents. Preserve the original trace file.
- Add regression tests for repeated misses, appended records, partial
UTF-8, large traces, replacement, and cleanup.
- Document the trace lookup performance constraint.
## Verification
- Latest revision: 11 index regressions and the existing real-runner
trace correlation test pass (12 tests).
- Includes 24 interleaved active traces, oversized records across
appends, and incomplete later interpretations.
- `pnpm build` and `pnpm -r typecheck` pass on final head `ddc74e42c`.
- The real-process hard-restart regression passes after rebuilding its
fake-provider binary from the rebased sources.
- The full local test command reports a pre-existing assertion mismatch
in `native-session-resume.test.ts`: the damaged-epoch recovery case
expects the old attach error instead of the new startup-history error.
The same exact failure was reproduced in an isolated checkout of
unchanged base `a20ecce40`. The PR does not change that test or startup
behavior.
- A recorded-trace benchmark reduced 120 lookups from 2.20 seconds to 22
milliseconds.
- The deployed hotfix removed the scan hotspot. The final main-thread
profile was 94% idle. A guarded restart reported no lost runs.
- All GitHub checks pass on `ddc74e42c`, including build, typecheck,
general tests, serialized server tests, end-to-end tests, canary dry
run, and security checks. Greptile is 5/5 on that exact head with no
open threads.
- Two timeout cases from the long local run pass in isolation: exhausted
quota-monitor evidence and native-question expiry. The duplicate full
local run was stopped after the complete CI suite passed.
## Risks
Each active transport retains event-to-frame mappings in memory and
clears them on close. Records over 64 KiB do not enter the correlation
index; the original trace file retains them. Large traces can need
multiple pending retries before a correlation is available. These
records are diagnostic; this change does not alter execution authority,
event acknowledgements, or provider commands.
## Model Used
OpenAI Codex, GPT-6. The runtime does not expose a more specific model
ID or context-window size. Used reasoning, code editing, shell
execution, CPU profiling, and tests.
## 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 (focused tests; the
full-suite baseline failure is documented above)
- [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
- [x] All Paperclip CI gates are green
- [x] 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 <noreply@paperclip.ing>
This commit is contained in:
1 parent
87b3e5fc61
commit
1616046c24
4 files changed
+297
-29
No files matched your search
@@ -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 v2
|
||||
stdin/stdout bridge admits the pinned Claude and Codex ACPX profiles. It
|
||||
validates the exact model, session identity, tool catalog, structured input,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user