Skip to content

Commit bca8dd9

Browse files
fix(trajectory): preserve prompts in oversized events (#116220)
Preserve ordinary schema-v1 trajectory payloads while shedding bulky duplicate conversation fields only after an event exceeds the runtime byte cap. Keep the bounded prompt in compact fallback records.
1 parent 61cf4b9 commit bca8dd9

2 files changed

Lines changed: 186 additions & 3 deletions

File tree

‎src/trajectory/runtime.test.ts‎

Lines changed: 155 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ describe("trajectory runtime", () => {
268268
);
269269
});
270270

271-
it("bounds large runtime event fields before serialization", () => {
271+
it("bounds oversized prompts before compact preservation", () => {
272272
const writes: string[] = [];
273273
const recorder = createTrajectoryRuntimeRecorder({
274274
sessionId: "session-1",
@@ -289,13 +289,44 @@ describe("trajectory runtime", () => {
289289

290290
expect(writes).toHaveLength(1);
291291
const parsed = JSON.parse(expectDefined(writes[0], "writes[0] test invariant"));
292+
expect(parsed.data.truncated).toBeUndefined();
292293
expect(parsed.data.prompt.truncated).toBe(true);
293294
expect(parsed.data.prompt.reason).toBe("trajectory-field-size-limit");
294295
expect(
295296
Buffer.byteLength(expectDefined(writes[0], "writes[0] test invariant"), "utf8"),
296297
).toBeLessThanOrEqual(TRAJECTORY_RUNTIME_EVENT_MAX_BYTES + 1);
297298
});
298299

300+
it("keeps normal schema-v1 event payloads unchanged", () => {
301+
const writes: string[] = [];
302+
const recorder = createTrajectoryRuntimeRecorder({
303+
sessionId: "session-1",
304+
sessionFile: "/tmp/session.jsonl",
305+
writer: {
306+
filePath: "/tmp/session.trajectory.jsonl",
307+
write: (line) => {
308+
writes.push(line);
309+
},
310+
flush: async () => undefined,
311+
},
312+
});
313+
const data = {
314+
prompt: "inspect",
315+
systemPrompt: "system prompt",
316+
messages: [{ role: "user", content: "inspect" }],
317+
messagesSnapshot: [{ role: "assistant", content: "done" }],
318+
imagesCount: 0,
319+
};
320+
321+
expectTrajectoryRuntimeRecorder(recorder).recordEvent("prompt.submitted", data);
322+
323+
const parsed = JSON.parse(expectDefined(writes[0], "writes[0] test invariant"));
324+
expect(parsed.schemaVersion).toBe(1);
325+
expect(parsed.data).toEqual(data);
326+
expect(JSON.stringify(parsed.data)).toBe(JSON.stringify(data));
327+
expect(parsed.data.truncated).toBeUndefined();
328+
});
329+
299330
it("preserves usage when truncating oversized runtime events", () => {
300331
const writes: string[] = [];
301332
const usage = {
@@ -322,6 +353,8 @@ describe("trajectory runtime", () => {
322353
runtimeRecorder.recordEvent("model.completed", {
323354
usage,
324355
promptCache,
356+
assistantTexts: ["done"],
357+
finalPromptText: "inspect",
325358
messagesSnapshot: Array.from({ length: 12 }, (_value, index) => ({
326359
role: index % 2 === 0 ? "user" : "assistant",
327360
content: `message-${index} ${"x".repeat(32_000)}`,
@@ -336,9 +369,11 @@ describe("trajectory runtime", () => {
336369
reason: "trajectory-event-size-limit",
337370
usage,
338371
promptCache,
372+
assistantTexts: ["done"],
373+
finalPromptText: "inspect",
339374
});
340375
expect(parsed.data.messagesSnapshot).toBeUndefined();
341-
expect(parsed.data.droppedFields).toContain("messagesSnapshot");
376+
expect(parsed.data.droppedFields).toEqual(["messagesSnapshot"]);
342377
expect(
343378
Buffer.byteLength(expectDefined(writes[0], "writes[0] test invariant"), "utf8"),
344379
).toBeLessThanOrEqual(TRAJECTORY_RUNTIME_EVENT_MAX_BYTES + 1);
@@ -385,6 +420,124 @@ describe("trajectory runtime", () => {
385420
).toBeLessThanOrEqual(TRAJECTORY_RUNTIME_EVENT_MAX_BYTES + 1);
386421
});
387422

423+
it("preserves the prompt when an oversized event drops inlined conversation state", () => {
424+
const writes: string[] = [];
425+
const prompt = "summarize the incident timeline for the deploy that failed";
426+
const recorder = createTrajectoryRuntimeRecorder({
427+
sessionId: "session-1",
428+
sessionFile: "/tmp/session.jsonl",
429+
writer: {
430+
filePath: "/tmp/session.trajectory.jsonl",
431+
write: (line) => {
432+
writes.push(line);
433+
},
434+
flush: async () => undefined,
435+
},
436+
});
437+
438+
const runtimeRecorder = expectTrajectoryRuntimeRecorder(recorder);
439+
runtimeRecorder.recordEvent("context.compiled", {
440+
prompt,
441+
systemPrompt: "x".repeat(32_000),
442+
messages: Array.from({ length: 12 }, (_value, index) => ({
443+
role: index % 2 === 0 ? "user" : "assistant",
444+
content: `message-${index} ${"x".repeat(32_000)}`,
445+
})),
446+
});
447+
448+
expect(writes).toHaveLength(1);
449+
const parsed = JSON.parse(expectDefined(writes[0], "writes[0] test invariant"));
450+
expect(parsed.data).toMatchObject({
451+
truncated: true,
452+
reason: "trajectory-event-size-limit",
453+
prompt,
454+
systemPrompt: "x".repeat(32_000),
455+
});
456+
expect(parsed.data.messages).toBeUndefined();
457+
expect(parsed.data.droppedFields).toEqual(["messages"]);
458+
expect(
459+
Buffer.byteLength(expectDefined(writes[0], "writes[0] test invariant"), "utf8"),
460+
).toBeLessThanOrEqual(TRAJECTORY_RUNTIME_EVENT_MAX_BYTES + 1);
461+
});
462+
463+
it("drops repeated conversation fields in priority order", () => {
464+
const writes: string[] = [];
465+
const prompt = "summarize the incident timeline";
466+
const messageBlocks = Array.from({ length: 12 }, (_value, index) => ({
467+
role: index % 2 === 0 ? "user" : "assistant",
468+
content: `message-${index} ${"x".repeat(32_000)}`,
469+
}));
470+
const recorder = createTrajectoryRuntimeRecorder({
471+
sessionId: "session-1",
472+
sessionFile: "/tmp/session.jsonl",
473+
writer: {
474+
filePath: "/tmp/session.trajectory.jsonl",
475+
write: (line) => {
476+
writes.push(line);
477+
},
478+
flush: async () => undefined,
479+
},
480+
});
481+
482+
expectTrajectoryRuntimeRecorder(recorder).recordEvent("context.compiled", {
483+
prompt,
484+
messagesSnapshot: messageBlocks,
485+
messages: messageBlocks,
486+
systemPrompt: "x".repeat(32_760),
487+
tools: Array.from({ length: 7 }, (_value, index) => ({
488+
name: `tool-${index}`,
489+
description: "x".repeat(32_760),
490+
})),
491+
});
492+
493+
const parsed = JSON.parse(expectDefined(writes[0], "writes[0] test invariant"));
494+
expect(parsed.data.prompt).toBe(prompt);
495+
expect(parsed.data.tools).toHaveLength(7);
496+
expect(parsed.data.messagesSnapshot).toBeUndefined();
497+
expect(parsed.data.messages).toBeUndefined();
498+
expect(parsed.data.systemPrompt).toBeUndefined();
499+
expect(parsed.data.droppedFields).toEqual(["messagesSnapshot", "messages", "systemPrompt"]);
500+
expect(
501+
Buffer.byteLength(expectDefined(writes[0], "writes[0] test invariant"), "utf8"),
502+
).toBeLessThanOrEqual(TRAJECTORY_RUNTIME_EVENT_MAX_BYTES + 1);
503+
});
504+
505+
it("preserves the prompt in the compact fallback for oversized events", () => {
506+
const writes: string[] = [];
507+
const prompt = "summarize the incident timeline for the deploy that failed";
508+
const recorder = createTrajectoryRuntimeRecorder({
509+
sessionId: "session-1",
510+
sessionFile: "/tmp/session.jsonl",
511+
writer: {
512+
filePath: "/tmp/session.trajectory.jsonl",
513+
write: (line) => {
514+
writes.push(line);
515+
},
516+
flush: async () => undefined,
517+
},
518+
});
519+
520+
expectTrajectoryRuntimeRecorder(recorder).recordEvent("context.compiled", {
521+
prompt,
522+
tools: Array.from({ length: 12 }, (_value, index) => ({
523+
name: `tool-${index}`,
524+
description: "x".repeat(32_000),
525+
})),
526+
});
527+
528+
const parsed = JSON.parse(expectDefined(writes[0], "writes[0] test invariant"));
529+
expect(parsed.data).toMatchObject({
530+
truncated: true,
531+
reason: "trajectory-event-size-limit",
532+
prompt,
533+
});
534+
expect(parsed.data.tools).toBeUndefined();
535+
expect(parsed.data.droppedFields).toEqual(["tools"]);
536+
expect(
537+
Buffer.byteLength(expectDefined(writes[0], "writes[0] test invariant"), "utf8"),
538+
).toBeLessThanOrEqual(TRAJECTORY_RUNTIME_EVENT_MAX_BYTES + 1);
539+
});
540+
388541
it("preserves usage on non-final oversized runtime completions", () => {
389542
const writes: string[] = [];
390543
const firstUsage = {

‎src/trajectory/runtime.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,16 @@ const TRAJECTORY_RUNTIME_DATA_ARRAY_MAX_ITEMS = 64;
5050
const TRAJECTORY_RUNTIME_DATA_OBJECT_MAX_KEYS = 64;
5151
const TRAJECTORY_RUNTIME_DATA_MAX_DEPTH = 6;
5252
const TRAJECTORY_RUNTIME_FINAL_PROMPT_MAX_BYTES = 4 * 1024;
53-
const TRAJECTORY_RUNTIME_OVERSIZE_PRESERVED_DATA_KEYS = ["usage", "promptCache"] as const;
53+
// Oversized events first shed repeated conversation state while keeping the
54+
// rest of their schema-v1 payload. The compact fallback then preserves keys
55+
// that remain useful even when every nonessential field must be dropped.
56+
// sanitizeTrajectoryPayload bounds prompt strings before this limiter runs.
57+
const TRAJECTORY_RUNTIME_OVERSIZE_DROP_FIRST_DATA_KEYS = [
58+
"messagesSnapshot",
59+
"messages",
60+
"systemPrompt",
61+
] as const;
62+
const TRAJECTORY_RUNTIME_OVERSIZE_PRESERVED_DATA_KEYS = ["usage", "promptCache", "prompt"] as const;
5463

5564
type TrajectoryRuntimeWriterDiagnostics = QueuedFileWriterDiagnostics;
5665

@@ -84,6 +93,27 @@ function truncateOversizedTrajectoryEvent(
8493
limitBytes: TRAJECTORY_RUNTIME_EVENT_MAX_BYTES,
8594
reason: "trajectory-event-size-limit",
8695
};
96+
const reducedData = { ...originalData };
97+
const reducedDroppedFields: string[] = [];
98+
for (const key of TRAJECTORY_RUNTIME_OVERSIZE_DROP_FIRST_DATA_KEYS) {
99+
if (!Object.hasOwn(reducedData, key)) {
100+
continue;
101+
}
102+
delete reducedData[key];
103+
reducedDroppedFields.push(key);
104+
const reduced = safeJsonStringify({
105+
...event,
106+
data: {
107+
...reducedData,
108+
...baseData,
109+
droppedFields: reducedDroppedFields,
110+
},
111+
});
112+
if (reduced && Buffer.byteLength(reduced, "utf8") <= TRAJECTORY_RUNTIME_EVENT_MAX_BYTES) {
113+
return reduced;
114+
}
115+
}
116+
87117
const buildTruncatedEventLine = (includeDroppedFields: boolean): string | undefined => {
88118
const data: Record<string, unknown> = { ...baseData };
89119
for (const key of TRAJECTORY_RUNTIME_OVERSIZE_PRESERVED_DATA_KEYS) {

0 commit comments

Comments
 (0)