Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(transcript): tolerate reasoning differences in replayed history (#18257)

marliessophie8f51bee97557
diff --git a/packages/shared/src/server/transcript/README.md b/packages/shared/src/server/transcript/README.md
index f11a5c924b..831bdab5a9 100644
--- a/packages/shared/src/server/transcript/README.md
+++ b/packages/shared/src/server/transcript/README.md
@@ -93,6 +93,10 @@ to and including the last assistant or tool message before the trace's first
output, is `conversationHistory` without provenance; everything after it is
`currentTurn`, each message with the observation that emitted it.
+`currentTurn.nestingLevel` is the tree depth of its first contributing generation,
+with fetched roots at zero. It is not a parent/child relationship between threads;
+later, deeper generations do not change it. Missing parents make observations roots.
+
```
input: User: Refund my order.
Assistant: [refund call]
@@ -133,21 +137,38 @@ registration and replayed-result suppression happen inside message appending.
### 1. Select a thread
-Continue a thread when it has at least one non-system message and all its
-non-system generation messages appear in the incoming input, regardless of order.
-Supplemental tool responses are not required for this match.
-Otherwise create a new thread. Matching checks presence, not occurrence counts.
+Compare generation messages by role and non-reasoning parts. Continue a thread
+when all its non-system messages with non-reasoning content appear in the incoming
+input, regardless of message order. At least one such message must match: system
+messages and reasoning alone cannot establish continuity. Supplemental tool
+responses are not required. Otherwise create a new thread. Matching checks
+presence, not occurrence counts.
When several threads match, the most recently created matching thread wins.
+Instrumentation should capture the full input and output of each model call,
+including reasoning. Thread matching tolerates missing or changed reasoning and
+provider annotations; it still requires matching text, tool calls, and arguments.
+
### 2. Append messages
-A message is identified by stable JSON of **role + parts**. Object-property
+A message is identified by stable JSON of **role + non-reasoning parts**. Object-property
order is ignored; array order matters. `senderName`, `source`, `finishReason`
-and observation provenance are excluded. All fields inside parts are included.
+and observation provenance are excluded. Parts exclude `providerMetadata` and
+tool calls' raw `toolType` from identity; both remain in the returned messages.
+All other non-reasoning part fields, including tool arguments with those names,
+are included.
- **Inputs:** append only occurrences beyond the number already shown in the
thread, so replayed history disappears but additional identical copies survive (eg user responds "Thank you" twice).
- **Outputs:** always append, then count them so subsequent inputs do not repeat them.
+- **Reasoning:** compare all reasoning parts in a message as one ordered group,
+ counted by role and content within the thread. Preserve reasoning in new messages;
+ on replay, retain only additional occurrences of the whole group. A changed group
+ is retained in full, without deduplicating its individual parts. Newly seen
+ reasoning in a repeated message is appended on
+ its own with the input observation's provenance; it does not duplicate the
+ accompanying text or calls or rewrite an earlier output. The same history/current
+ turn split applies to these messages.
- **Registered tool responses:** use call identity, not message occurrence counts.
Across traces, reused call IDs are matched by call occurrence in complete,
ordered input history. Ambiguous partial replays remain as input messages.
@@ -173,6 +194,7 @@ and observation provenance are excluded. All fields inside parts are included.
`[B, C, A, New]` adds only `New`. Existing display order stays `[A, B, C]`.
- Additional identical input occurrences and always-visible outputs.
- New system instructions within a continuing conversation.
+- Missing or changed reasoning in otherwise matching history.
- Multiple threads when their histories distinguish them.
## Current limitations
@@ -183,6 +205,7 @@ and observation provenance are excluded. All fields inside parts are included.
- **Identical conversations:** unrelated conversations with matching history can join.
- **Whole-message matching:** equivalent content split into different messages
or parts may not match. Reordering parts within a message also changes identity.
+ Splitting or regrouping reasoning can retain repeated reasoning content.
Registered tool responses are the exception: replay is matched by call ID
within the thread (and occurrence for reused IDs), even when grouped with other parts.
- **Name matching is best-effort:** same-name parallel executions can start in a
@@ -197,7 +220,6 @@ and observation provenance are excluded. All fields inside parts are included.
- Root span I/O does not contribute to the transcript, unless it is of type `GENERATION`.
- Do not include status messages and errors in the transcript for v1. Only revisit should we find strong evidence in production data that this is a valuable feature, or if consumers (e.g. Topics, Session UI) require this information.
- Expose a helper method to get the first user message and final assistant message from a given thread. This is useful for consumers (e.g. Topics, Session UI) to display the user question and final assistant answer. Consumers must assess for which thread they want to display this information, and how to handle multiple threads.
-- Differences in part-level `providerMetadata` prevents deduplication when the visible message content is otherwise identical. Should production data show strong enough evidence to support this change, this decision should be revisited.
## Open questions
diff --git a/packages/shared/src/server/transcript/fixtures/fixtures.test.ts b/packages/shared/src/server/transcript/fixtures/fixtures.test.ts
index 097c4de0da..5b19c87381 100644
--- a/packages/shared/src/server/transcript/fixtures/fixtures.test.ts
+++ b/packages/shared/src/server/transcript/fixtures/fixtures.test.ts
@@ -84,6 +84,67 @@ describe("transcript fixtures", () => {
]);
});
+ it("continues and deduplicates tool calls replayed with provider metadata and a raw tool type", () => {
+ const input = { providerMetadata: "argument", toolType: "argument" };
+ const first = {
+ ...generation("1", ["A"], []),
+ output: {
+ tool_calls: [{ toolCallId: "call", toolName: "lookup", args: input }],
+ },
+ };
+ const replay = {
+ role: "assistant",
+ content: [
+ {
+ type: "tool-call",
+ toolCallId: "call",
+ toolName: "lookup",
+ input,
+ providerOptions: { mastra: { modelOutput: "provider details" } },
+ },
+ ],
+ };
+ const second = {
+ ...generation("2", [], []),
+ input: [{ role: "user", content: "A" }, replay],
+ output: { role: "assistant", content: "Done" },
+ };
+ const transcript = assembleTranscript([first, second]);
+ expect(transcript?.threads).toHaveLength(1);
+ expect(transcript?.threads[0].currentTurn.messages).toHaveLength(3);
+ expect(transcript?.threads[0].currentTurn.observations).toEqual([
+ { id: "1", traceId },
+ { id: "2", traceId },
+ ]);
+
+ // Metadata remains available when this is the first recorded occurrence.
+ const standalone = assembleTranscript([second]);
+ expect(
+ standalone?.threads[0].conversationHistory[1].parts[0],
+ ).toMatchObject({
+ toolType: "tool-call",
+ providerMetadata: { mastra: { modelOutput: "provider details" } },
+ input,
+ });
+
+ // These field names can also be real tool arguments and must still match.
+ for (const field of ["providerMetadata", "toolType"]) {
+ const changed = {
+ ...second,
+ input: [
+ second.input[0],
+ {
+ ...replay,
+ content: [
+ { ...replay.content[0], input: { ...input, [field]: "changed" } },
+ ],
+ },
+ ],
+ };
+ expect(assembleTranscript([first, changed])?.threads).toHaveLength(2);
+ }
+ });
+
it("uses the first current-turn generation depth, excluding history and later generations", () => {
const previous = {
...generation("1", ["A"], []),
@@ -130,6 +191,171 @@ describe("transcript fixtures", () => {
expect(transcript?.threads[0].conversationHistory).toHaveLength(2);
});
+ it("continues when replay omits reasoning, without losing the original output", () => {
+ const first = {
+ ...generation("1", ["A"], []),
+ output: {
+ role: "assistant",
+ content: [
+ { type: "reasoning", text: "Consider the choices." },
+ { type: "text", text: "B" },
+ ],
+ },
+ };
+ const second = {
+ ...generation("2", [], []),
+ input: [
+ { role: "user", content: "A" },
+ { role: "assistant", content: "B" },
+ ],
+ };
+ const transcript = assembleTranscript([first, second]);
+ expect(transcript?.threads).toHaveLength(1);
+ expect(transcript?.threads[0].currentTurn.messages).toHaveLength(2);
+ expect(transcript?.threads[0].currentTurn.messages[1]).toMatchObject({
+ observationId: "1",
+ source: "output",
+ parts: [
+ {
+ type: "reasoning",
+ content: { kind: "text", text: "Consider the choices." },
+ },
+ { type: "text", text: "B" },
+ ],
+ });
+ });
+
+ it("does not establish continuity from system messages and reasoning alone", () => {
+ const system = { role: "system", content: "Think carefully." };
+ const reasoning = {
+ role: "assistant",
+ content: [{ type: "reasoning", text: "Consider the choices." }],
+ };
+ const first = {
+ ...generation("1", [], []),
+ input: [system],
+ output: reasoning,
+ };
+ const second = {
+ ...generation("2", [], ["B"]),
+ input: [system, reasoning],
+ };
+ expect(assembleTranscript([first, second])?.threads).toHaveLength(2);
+ });
+
+ it("retains a changed reasoning group in full and deduplicates its later replay", () => {
+ const reasoning = { type: "reasoning", text: "Consider the choices." };
+ const first = {
+ ...generation("1", ["A"], []),
+ output: {
+ role: "assistant",
+ content: [reasoning, { type: "text", text: "B" }],
+ },
+ };
+ const second = {
+ ...generation("2", [], []),
+ input: [
+ { role: "user", content: "A" },
+ { role: "assistant", content: [reasoning, reasoning] },
+ { role: "assistant", content: "B" },
+ ],
+ };
+ const third = { ...second, id: "3" };
+ const transcript = assembleTranscript([first, second, third]);
+ expect(transcript?.threads).toHaveLength(1);
+ const messages = transcript!.threads[0].currentTurn.messages;
+ expect(messages).toHaveLength(3);
+ expect(
+ messages
+ .flatMap(({ parts }) => parts)
+ .filter(({ type }) => type === "reasoning"),
+ ).toHaveLength(3);
+ expect(messages[2]).toMatchObject({ observationId: "2", source: "input" });
+ expect(transcript?.threads[0].currentTurn.observations).toEqual([
+ { id: "1", traceId },
+ { id: "2", traceId },
+ ]);
+ });
+
+ it("keeps changed assistant text in a separate thread despite matching reasoning", () => {
+ const reasoning = { type: "reasoning", text: "Consider the choices." };
+ const first = {
+ ...generation("1", ["A"], []),
+ output: {
+ role: "assistant",
+ content: [reasoning, { type: "text", text: "B" }],
+ },
+ };
+ const second = {
+ ...generation("2", [], []),
+ input: [
+ { role: "user", content: "A" },
+ {
+ role: "assistant",
+ content: [reasoning, { type: "text", text: "Different answer" }],
+ },
+ ],
+ };
+ expect(assembleTranscript([first, second])?.threads).toHaveLength(2);
+ });
+
+ it("retains changed reasoning in cross-trace history and uses the new turn's depth", () => {
+ const first = {
+ ...generation("1", ["A"], []),
+ nestingLevel: 2,
+ output: {
+ role: "assistant",
+ content: [
+ { type: "reasoning", text: "Original reasoning." },
+ { type: "text", text: "B" },
+ ],
+ },
+ };
+ const second = {
+ ...generation("2", [], []),
+ traceId: "next-trace",
+ nestingLevel: 4,
+ input: [
+ { role: "user", content: "A" },
+ {
+ role: "assistant",
+ content: [
+ { type: "reasoning", text: "Revised reasoning." },
+ { type: "text", text: "B" },
+ ],
+ },
+ { role: "user", content: "C" },
+ ],
+ output: { role: "assistant", content: "D" },
+ };
+ const transcript = assembleTranscript([first, second]);
+ expect(transcript?.threads).toHaveLength(1);
+ const thread = transcript!.threads[0];
+ expect(thread.conversationHistory.flatMap(({ parts }) => parts)).toEqual([
+ { type: "text", text: "A" },
+ {
+ type: "reasoning",
+ content: { kind: "text", text: "Original reasoning." },
+ },
+ { type: "text", text: "B" },
+ {
+ type: "reasoning",
+ content: { kind: "text", text: "Revised reasoning." },
+ },
+ ]);
+ for (const message of thread.conversationHistory) {
+ expect(message).not.toHaveProperty("observationId");
+ }
+ expect(thread.currentTurn.nestingLevel).toBe(4);
+ expect(thread.currentTurn.messages.map(({ parts }) => parts)).toEqual([
+ [{ type: "text", text: "C" }],
+ [{ type: "text", text: "D" }],
+ ]);
+ expect(thread.currentTurn.observations).toEqual([
+ { id: "2", traceId: "next-trace" },
+ ]);
+ });
+
it("have unique names", () => {
const names = transcriptFixtures.map((fixture) => fixture.name);
expect(new Set(names).size).toBe(names.length);
diff --git a/packages/shared/src/server/transcript/fixtures/index.ts b/packages/shared/src/server/transcript/fixtures/index.ts
index 86285578ca..7e862f3c5a 100644
--- a/packages/shared/src/server/transcript/fixtures/index.ts
+++ b/packages/shared/src/server/transcript/fixtures/index.ts
@@ -6,6 +6,7 @@ import { supportCopilotRefundLoopFixture } from "./trace/support-copilot-refund-
import { supportCopilotFollowUpFixture } from "./trace/support-copilot-follow-up";
import { standaloneToolObservationFixture } from "./trace/standalone-tool-observation";
import { inheritedConversationHistoryFixture } from "./trace/inherited-conversation-history";
+import { replayedToolCallsWithLateReasoningFixture } from "./trace/replayed-tool-calls-with-late-reasoning";
export type { TranscriptFixture } from "./fixture-types";
@@ -17,4 +18,5 @@ export const transcriptFixtures: TranscriptFixture[] = [
supportCopilotRefundLoopFixture,
supportCopilotFollowUpFixture,
inheritedConversationHistoryFixture,
+ replayedToolCallsWithLateReasoningFixture,
];
diff --git a/packages/shared/src/server/transcript/fixtures/trace/replayed-tool-calls-with-late-reasoning.ts b/packages/shared/src/server/transcript/fixtures/trace/replayed-tool-calls-with-late-reasoning.ts
new file mode 100644
index 0000000000..4664e84b63
--- /dev/null
+++ b/packages/shared/src/server/transcript/fixtures/trace/replayed-tool-calls-with-late-reasoning.ts
@@ -0,0 +1,200 @@
+import type { TranscriptFixture } from "../fixture-types";
+import type { JsonValue } from "../../../../utils/normalized-io/types";
+
+// Entirely invented data: only the observation and message shapes represent
+// the regression. No text, identifiers, dates, or metadata come from a trace.
+const traceId = "synthetic-block-trace";
+const base = { trace_id: traceId, project_id: "synthetic-block-project" };
+const systems = [
+ "Arrange colored blocks.",
+ "Use the available inspection tools.",
+ "Keep the arrangement within the tray.",
+];
+const request = "Place the blue block next to the yellow block.";
+const context = "The tray has three empty slots.";
+const reasoning = "I will inspect the blocks and tray before placing anything.";
+const initial = [
+ ...systems.map((content) => ({ role: "system", content })),
+ { role: "user", content: request },
+];
+const injectedContext = { role: "user", content: context };
+const calls: { id: string; name: string; input: JsonValue }[] = [
+ {
+ id: "synthetic-block-call",
+ name: "inspect_blocks",
+ input: { color: "blue" },
+ },
+ { id: "synthetic-tray-call", name: "inspect_tray", input: { row: 1 } },
+];
+const results: JsonValue[] = [
+ { colors: ["blue", "yellow"] },
+ { emptySlots: 3 },
+];
+const replay = [
+ ...initial,
+ {
+ role: "assistant",
+ content: [
+ { type: "reasoning", text: reasoning },
+ ...calls.map((call) => ({
+ type: "tool-call",
+ toolCallId: call.id,
+ toolName: call.name,
+ input: call.input,
+ providerOptions: { synthetic: { replayMarker: "replayed" } },
+ })),
+ ],
+ },
+ {
+ role: "tool",
+ content: calls.map((call, index) => ({
+ type: "tool-result",
+ toolCallId: call.id,
+ toolName: call.name,
+ output: { type: "json", value: results[index] },
+ })),
+ },
+ injectedContext,
+];
+const time = (second: number) =>
+ `2030-01-01T00:00:${String(second).padStart(2, "0")}.000Z`;
+const provenance = (id: string, start: number, end: number) => ({
+ observationId: id,
+ traceId,
+ startTime: new Date(time(start)),
+ endTime: new Date(time(end)),
+});
+
+export const replayedToolCallsWithLateReasoningFixture = {
+ name: "Replayed tool calls with late reasoning and relocated context",
+ description:
+ "A second generation replays two calls with added reasoning and provider metadata, then moves the injected user context to the end. One depth-two thread preserves the reasoning at its recorded source without repeating calls or results.",
+ observations: [
+ {
+ ...base,
+ id: "synthetic-block-root",
+ parent_observation_id: null,
+ type: "SPAN",
+ name: "Block arrangement",
+ start_time: time(0),
+ end_time: time(9),
+ input: null,
+ output: null,
+ },
+ {
+ ...base,
+ id: "synthetic-block-agent",
+ parent_observation_id: "synthetic-block-root",
+ type: "AGENT",
+ name: "Block arranger",
+ start_time: time(1),
+ end_time: time(8),
+ input: JSON.stringify([...initial, injectedContext]),
+ output: JSON.stringify(replay),
+ },
+ {
+ ...base,
+ id: "synthetic-block-generation-one",
+ parent_observation_id: "synthetic-block-agent",
+ type: "GENERATION",
+ name: "Inspect arrangement",
+ start_time: time(2),
+ end_time: time(3),
+ input: JSON.stringify({ messages: [...initial, injectedContext] }),
+ output: JSON.stringify({
+ role: "assistant",
+ content: null,
+ tool_calls: calls.map((call) => ({
+ id: call.id,
+ type: "function",
+ function: { name: call.name, arguments: JSON.stringify(call.input) },
+ })),
+ }),
+ },
+ ...calls.map((call, index) => ({
+ ...base,
+ id: `synthetic-block-tool-${index + 1}`,
+ parent_observation_id: "synthetic-block-generation-one",
+ type: "TOOL" as const,
+ name: call.name,
+ start_time: time(4 + index),
+ end_time: time(5 + index),
+ input: JSON.stringify(call.input),
+ output: JSON.stringify(results[index]),
+ })),
+ {
+ ...base,
+ id: "synthetic-block-generation-two",
+ parent_observation_id: "synthetic-block-agent",
+ type: "GENERATION",
+ name: "Continue arrangement",
+ start_time: time(7),
+ end_time: time(8),
+ input: JSON.stringify({ messages: replay }),
+ output: null,
+ },
+ ],
+ expected: {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ nestingLevel: 2,
+ messages: [
+ ...systems.map((text) => ({
+ role: "system" as const,
+ parts: [{ type: "text" as const, text }],
+ source: "input" as const,
+ ...provenance("synthetic-block-generation-one", 2, 3),
+ })),
+ ...[request, context].map((text) => ({
+ role: "user" as const,
+ parts: [{ type: "text" as const, text }],
+ source: "input" as const,
+ ...provenance("synthetic-block-generation-one", 2, 3),
+ })),
+ {
+ role: "assistant",
+ parts: calls.map((call) => ({
+ type: "tool-call" as const,
+ toolCallId: call.id,
+ toolName: call.name,
+ input: call.input,
+ toolType: "function",
+ })),
+ source: "output",
+ ...provenance("synthetic-block-generation-one", 2, 3),
+ },
+ ...results.map((value, index) => ({
+ role: "tool" as const,
+ parts: [{ type: "data" as const, value }],
+ source: "output" as const,
+ ...provenance(
+ `synthetic-block-tool-${index + 1}`,
+ 4 + index,
+ 5 + index,
+ ),
+ })),
+ {
+ role: "assistant",
+ parts: [
+ {
+ type: "reasoning",
+ content: { kind: "text", text: reasoning },
+ },
+ ],
+ source: "input",
+ ...provenance("synthetic-block-generation-two", 7, 8),
+ },
+ ],
+ observations: [
+ "synthetic-block-generation-one",
+ "synthetic-block-tool-1",
+ "synthetic-block-tool-2",
+ "synthetic-block-generation-two",
+ ].map((id) => ({ id, traceId })),
+ },
+ },
+ ],
+ },
+} satisfies TranscriptFixture;
diff --git a/packages/shared/src/server/transcript/threads.ts b/packages/shared/src/server/transcript/threads.ts
index cb2283ca37..16b58cf325 100644
--- a/packages/shared/src/server/transcript/threads.ts
+++ b/packages/shared/src/server/transcript/threads.ts
@@ -1,7 +1,8 @@
+import { partition } from "lodash";
import type { NormalizedMessage } from "../../utils/normalized-io";
-import type { Thread, ThreadMessage, Turn } from "./types";
+import type { Thread, ThreadMessage } from "./types";
import type { OrderedObservation } from "./ordering";
-import type { createToolCallRegistry } from "./tool-calls";
+import type { ToolCallRegistry } from "./tool-calls";
export type TranscriptObservation = OrderedObservation & { traceId: string };
@@ -9,129 +10,214 @@ export type KeyedMessage = {
message: NormalizedMessage;
key: string;
};
-export type AssembledTurn = Pick<Turn, "messages"> & {
- observations: Pick<
- TranscriptObservation,
- "id" | "traceId" | "type" | "nestingLevel"
- >[];
-};
+
+type Contributor = Pick<
+ TranscriptObservation,
+ "id" | "traceId" | "type" | "nestingLevel"
+>;
+
+/** Thread message with the key it was deduplicated by; tool responses have none. */
+export type EmittedMessage = ThreadMessage & { key?: string };
export type ThreadState = {
- /** Every message of the thread in one list; `splitTurn` derives the public shape. */
- thread: AssembledTurn;
- messages: KeyedMessage[];
- shownCounts: Map<string, number>;
+ /** Every message in display order; `splitTurn` derives the public shape. */
+ messages: EmittedMessage[];
+ /** Observations in the order they first contributed a message. */
+ contributors: Contributor[];
+ /** Added reasoning from replayed content must not establish a turn boundary. */
+ replaySupplements: WeakSet<EmittedMessage>;
};
+export const createThread = (): ThreadState => ({
+ messages: [],
+ contributors: [],
+ replaySupplements: new WeakSet(),
+});
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === "object" && !Array.isArray(value);
-/** Object property order and observation provenance do not define identity. */
+const isReasoningPart = (part: NormalizedMessage["parts"][number]) =>
+ part.type === "reasoning" ||
+ (part.type === "file" && part.reasoning === true);
+
+/**
+ * Identity of a message: role and all parts, including reasoning. Provider
+ * annotations, property order, and provenance do not define identity.
+ */
export function messageKey(message: NormalizedMessage): string {
- return JSON.stringify(
- [message.role, message.parts],
- (_key, value: unknown) =>
- isRecord(value)
- ? Object.fromEntries(
- Object.keys(value)
- .sort()
- .map((key) => [key, value[key]]),
- )
- : value,
+ const parts = message.parts.map(
+ ({ providerMetadata: _metadata, ...part }) => {
+ if (part.type === "tool-call") {
+ const { toolType: _toolType, ...call } = part;
+ return call;
+ }
+ return part;
+ },
+ );
+ return JSON.stringify([message.role, parts], (_key, value: unknown) =>
+ isRecord(value)
+ ? Object.fromEntries(
+ Object.keys(value)
+ .sort()
+ .map((key) => [key, value[key]]),
+ )
+ : value,
);
}
-/** Find a thread that matches the input messages. */
-export function findThread(states: ThreadState[], input: KeyedMessage[]) {
- const inputKeys = new Set(input.map(({ key }) => key));
- return states.findLast(
- ({ messages }) =>
- messages.some(({ message }) => message.role !== "system") &&
- messages.every(
- ({ message, key }) => message.role === "system" || inputKeys.has(key),
- ),
+/** Reasoning can change without breaking conversational continuity. */
+function continuityKey(message: NormalizedMessage, fullKey?: string): string {
+ if (fullKey !== undefined && !message.parts.some(isReasoningPart))
+ return fullKey;
+ return messageKey({
+ ...message,
+ parts: message.parts.filter((part) => !isReasoningPart(part)),
+ });
+}
+
+function contributesToThreadContinuity(message: NormalizedMessage) {
+ return (
+ message.role !== "system" &&
+ message.parts.some((part) => !isReasoningPart(part))
);
}
-/** Append messages to a thread. */
+/** Find the newest thread whose continuity-defining messages all appear in the input. */
+export function findThread(threads: ThreadState[], input: KeyedMessage[]) {
+ const inputKeys = new Set(
+ input
+ .filter(({ message }) => contributesToThreadContinuity(message))
+ .map(({ message, key }) => continuityKey(message, key)),
+ );
+ return threads.findLast(({ messages }) => {
+ const defining = messages.filter(
+ (message) =>
+ message.key !== undefined && contributesToThreadContinuity(message),
+ );
+ return (
+ defining.length > 0 &&
+ defining.every((message) =>
+ inputKeys.has(continuityKey(message, message.key)),
+ )
+ );
+ });
+}
+
+/**
+ * Append a generation's messages. The n-th input occurrence of a key repeats
+ * the n-th message the thread already shows with that key. If only reasoning
+ * differs, retain the new reasoning at its arrival position. Other inputs and
+ * all outputs are emitted. Registered tool results attach to their calls.
+ */
export function append(
- state: ThreadState,
+ thread: ThreadState,
observation: TranscriptObservation,
input: KeyedMessage[],
output: KeyedMessage[],
- isNewThread: boolean,
- toolCalls: ReturnType<typeof createToolCallRegistry>,
+ toolCalls: ToolCallRegistry,
) {
- const { thread, messages, shownCounts } = state;
- const inputCounts = new Map<string, number>();
- const replayCalls = new Map<string, number>();
- const replayTotals = new Map<string, number>();
- // Count first so a truncated replay cannot attach a result to the wrong call.
- for (const { message } of input) {
+ const deduplicate = createMessageDeduplicator(thread.messages);
+ const calls = toolCalls.forGeneration(thread, observation, input, output);
+
+ for (const { message, key: fullKey } of [...input, ...output]) {
+ const results: NormalizedMessage["parts"] = [];
+ const parts: NormalizedMessage["parts"] = [];
for (const part of message.parts) {
- if (part.type === "tool-call" && part.toolCallId)
- replayTotals.set(
- part.toolCallId,
- (replayTotals.get(part.toolCallId) ?? 0) + 1,
- );
+ (calls.claims(part) ? results : parts).push(part);
}
- }
- for (const { message, key: originalKey } of [...input, ...output]) {
- const isOutput = message.source === "output";
- const emitted: ThreadMessage = {
- ...message,
- parts: [],
- observationId: observation.id,
- traceId: observation.traceId,
- startTime: observation.startTime,
- endTime: observation.endTime,
- };
- // Anchor output calls before attaching any results carried by the same message.
- if (isOutput) thread.messages.push(emitted);
- for (const part of message.parts) {
- if (
- !toolCalls.consumePart(
- observation,
- part,
- thread,
- emitted,
- replayCalls,
- replayTotals,
- )
- )
- emitted.parts.push(part);
- }
- if (!emitted.parts.length) {
- if (isOutput) thread.messages.splice(thread.messages.indexOf(emitted), 1);
- continue;
- }
- const key =
- emitted.parts.length === message.parts.length
- ? originalKey
- : messageKey(emitted);
- if (!isOutput) {
- const occurrence = (inputCounts.get(key) ?? 0) + 1;
- inputCounts.set(key, occurrence);
- if (!isNewThread && occurrence <= (shownCounts.get(key) ?? 0)) continue;
- thread.messages.push(emitted);
+ if (parts.length) {
+ const key = results.length ? messageKey({ ...message, parts }) : fullKey;
+ const retained = deduplicate({ message: { ...message, parts }, key });
+ if (retained) {
+ const emitted: EmittedMessage = {
+ ...message,
+ parts: retained.parts,
+ key: retained.key,
+ observationId: observation.id,
+ traceId: observation.traceId,
+ startTime: observation.startTime,
+ endTime: observation.endTime,
+ };
+ thread.messages.push(emitted);
+ if (retained.isSupplement) thread.replaySupplements.add(emitted);
+ addContributor(thread, observation);
+ calls.register(emitted);
+ }
}
- messages.push({ message: emitted, key });
- shownCounts.set(key, (shownCounts.get(key) ?? 0) + 1);
- addContributor(thread, observation);
+ calls.attach(results);
}
}
+/** Match each input occurrence to one already-shown occurrence. */
+function createMessageDeduplicator(messages: EmittedMessage[]) {
+ const shown = new Map<string, number>();
+ const seen = new Map<string, number>();
+
+ const isDuplicate = (key: string) => {
+ const occurrence = (seen.get(key) ?? 0) + 1;
+ seen.set(key, occurrence);
+ return occurrence <= (shown.get(key) ?? 0);
+ };
+
+ // An answer and its reasoning may later be replayed together or separately.
+ const recordContentAndReasoningSeparately = (message: EmittedMessage) => {
+ if (message.key === undefined) return;
+
+ const [reasoning, content] = partition(message.parts, isReasoningPart);
+ for (const parts of [content, reasoning]) {
+ if (!parts.length) continue;
+
+ const key =
+ parts.length === message.parts.length
+ ? message.key
+ : messageKey({ ...message, parts });
+ shown.set(key, (shown.get(key) ?? 0) + 1);
+ }
+ };
+
+ for (const message of messages) recordContentAndReasoningSeparately(message);
+
+ return ({ message, key }: KeyedMessage) => {
+ const whole = { parts: message.parts, key, isSupplement: false };
+ if (message.source === "output") return whole;
+
+ const [reasoning, content] = partition(message.parts, isReasoningPart);
+ const reasoningKey = content.length
+ ? messageKey({ ...message, parts: reasoning })
+ : key;
+ const repeatsContent =
+ !content.length ||
+ isDuplicate(reasoning.length ? continuityKey(message) : key);
+ const repeatsReasoning = !reasoning.length || isDuplicate(reasoningKey);
+
+ // New messages retain their reasoning; count it before checking later replays.
+ if (reasoning.length && (!repeatsContent || !repeatsReasoning))
+ shown.set(reasoningKey, (shown.get(reasoningKey) ?? 0) + 1);
+ if (!repeatsContent) return whole;
+
+ if (!repeatsReasoning)
+ return {
+ parts: reasoning,
+ key: reasoningKey,
+ isSupplement: content.length > 0,
+ };
+
+ return undefined;
+ };
+}
+
export function addContributor(
- thread: AssembledTurn,
+ thread: ThreadState,
observation: TranscriptObservation,
) {
if (
- !thread.observations.some(
+ !thread.contributors.some(
({ id, traceId }) =>
id === observation.id && traceId === observation.traceId,
)
) {
- thread.observations.push({
+ thread.contributors.push({
id: observation.id,
traceId: observation.traceId,
type: observation.type,
@@ -141,43 +227,53 @@ export function addContributor(
}
/** Split a thread into replayed history and the turn the last trace added. */
-export function splitTurn(thread: AssembledTurn): Thread {
- const { messages, observations } = thread;
- // Earlier traces of a session are history; the last contributing trace is
- // the current turn.
- const currentTraceId = observations.at(-1)?.traceId;
+export function splitTurn({
+ messages,
+ contributors,
+ replaySupplements,
+}: ThreadState): Thread {
+ // Earlier traces are history; the last contributing trace is the current turn.
+ const currentTraceId = contributors.at(-1)?.traceId;
const traceStart =
messages.findLastIndex(({ traceId }) => traceId !== currentTraceId) + 1;
- // Within that trace, input replayed before the first output is history up
- // to the previous turn's last assistant or tool message. What follows is new.
+ // Within it, input replayed before the first output is history up to the
+ // previous turn's last assistant or tool message.
const trace = messages.slice(traceStart);
const firstOutput = trace.findIndex(({ source }) => source === "output");
const replayed = trace.slice(0, firstOutput === -1 ? undefined : firstOutput);
- const turnStart =
+ let turnStart =
traceStart +
replayed.findLastIndex(
- ({ role }) => role === "assistant" || role === "tool",
+ (message) =>
+ (message.role === "assistant" || message.role === "tool") &&
+ !replaySupplements.has(message),
) +
1;
+ while (
+ turnStart < messages.length &&
+ replaySupplements.has(messages[turnStart]!)
+ )
+ turnStart++;
const current = messages.slice(turnStart);
- const currentObservations = observations.filter(({ id, traceId }) =>
+ const currentContributors = contributors.filter(({ id, traceId }) =>
current.some(
(message) => message.observationId === id && message.traceId === traceId,
),
);
- const firstGeneration = currentObservations.find(
+ const firstGeneration = currentContributors.find(
({ type }) => type === "GENERATION",
);
return {
conversationHistory: messages
.slice(0, turnStart)
.map(
- ({ observationId, traceId, startTime, endTime, ...message }) => message,
+ ({ key: _key, observationId, traceId, startTime, endTime, ...rest }) =>
+ rest,
),
currentTurn: {
- messages: current,
+ messages: current.map(({ key: _key, ...message }) => message),
nestingLevel: firstGeneration?.nestingLevel ?? 0,
- observations: currentObservations.map(({ id, traceId }) => ({
+ observations: currentContributors.map(({ id, traceId }) => ({
id,
traceId,
})),
diff --git a/packages/shared/src/server/transcript/tool-calls.ts b/packages/shared/src/server/transcript/tool-calls.ts
index 379e9711ef..5c51c1b745 100644
--- a/packages/shared/src/server/transcript/tool-calls.ts
+++ b/packages/shared/src/server/transcript/tool-calls.ts
@@ -5,35 +5,40 @@ import type {
import type { ThreadMessage } from "./types";
import {
addContributor,
- type AssembledTurn,
+ type EmittedMessage,
type KeyedMessage,
+ type ThreadState,
type TranscriptObservation,
} from "./threads";
type Call = {
- thread: AssembledTurn;
+ thread: ThreadState;
message: ThreadMessage;
response?: ThreadMessage;
fromTool?: boolean;
};
+type Part = NormalizedMessage["parts"][number];
const key = (traceId: string, id: string) => JSON.stringify([traceId, id]);
+export type ToolCallRegistry = ReturnType<typeof createToolCallRegistry>;
+
export function createToolCallRegistry() {
const calls = new Map<string, Call>();
- const callsByThread = new WeakMap<AssembledTurn, Map<string, Call[]>>();
+ const callsByThread = new WeakMap<ThreadState, Map<string, Call[]>>();
const pending = new Map<string, { calls: Call[]; next: number }>();
const responseTails = new WeakMap<ThreadMessage, ThreadMessage>();
function register(
observation: TranscriptObservation,
part: ToolCallPart,
- thread: AssembledTurn,
+ thread: ThreadState,
message: ThreadMessage,
) {
const id = part.toolCallId
? key(observation.traceId, part.toolCallId)
: undefined;
if (id && calls.has(id)) return;
+
const call: Call = { thread, message };
if (id) calls.set(id, call);
if (part.toolCallId) {
@@ -55,6 +60,7 @@ export function createToolCallRegistry() {
) {
const fromTool = observation.type === "TOOL";
if (call.response && (!fromTool || call.fromTool)) return;
+
const response: ThreadMessage = {
role: "tool",
source: "output",
@@ -79,48 +85,94 @@ export function createToolCallRegistry() {
addContributor(call.thread, observation);
}
- /** Register output calls or consume a result while its message is appended. */
- function consumePart(
+ /**
+ * Resolve which tool results of one generation belong to registered calls
+ * before any of its messages is emitted.
+ */
+ function forGeneration(
+ thread: ThreadState,
observation: TranscriptObservation,
- part: NormalizedMessage["parts"][number],
- thread: AssembledTurn,
- message: ThreadMessage,
- replayCalls: Map<string, number>,
- replayTotals: Map<string, number>,
- ): boolean {
- if (
- part.type === "tool-call" &&
- message.source === "input" &&
- part.toolCallId
- )
- replayCalls.set(
- part.toolCallId,
- (replayCalls.get(part.toolCallId) ?? 0) + 1,
- );
- if (part.type === "tool-call" && message.source === "output")
- register(observation, part, thread, message);
- if (part.type !== "tool-result" || !part.toolCallId) return false;
- const matches = callsByThread.get(thread)?.get(part.toolCallId);
+ input: KeyedMessage[],
+ output: KeyedMessage[],
+ ) {
+ // Input results of a resolved call; output results resolve on attach.
+ const claimed = new Map<Part, Call | undefined>();
+
// Reused IDs need complete, ordered call history to disambiguate results.
- const occurrence = replayCalls.get(part.toolCallId) ?? 0;
- let call: Call | undefined;
- if (message.source === "output") {
- call = calls.get(key(observation.traceId, part.toolCallId));
- } else if (
- matches?.length === 1 &&
- (replayTotals.get(part.toolCallId) ?? 0) <= 1
- ) {
- call = matches[0];
- } else if (
- matches &&
- replayTotals.get(part.toolCallId) === matches.length &&
- occurrence > 0
- ) {
- call = matches[occurrence - 1];
+ const totals = new Map<string, number>();
+ for (const { message } of input) {
+ for (const part of message.parts) {
+ if (part.type === "tool-call" && part.toolCallId)
+ totals.set(part.toolCallId, (totals.get(part.toolCallId) ?? 0) + 1);
+ }
+ }
+ const occurrences = new Map<string, number>();
+ const threadCalls = callsByThread.get(thread);
+ for (const { message } of input) {
+ for (const part of message.parts) {
+ if (part.type === "tool-call" && part.toolCallId)
+ occurrences.set(
+ part.toolCallId,
+ (occurrences.get(part.toolCallId) ?? 0) + 1,
+ );
+ if (part.type !== "tool-result" || !part.toolCallId) continue;
+
+ const matches = threadCalls?.get(part.toolCallId);
+ const total = totals.get(part.toolCallId) ?? 0;
+ const occurrence = occurrences.get(part.toolCallId) ?? 0;
+
+ let call: Call | undefined;
+ if (matches?.length === 1 && total <= 1) {
+ call = matches[0];
+ } else if (matches && total === matches.length && occurrence > 0) {
+ call = matches[occurrence - 1];
+ } else {
+ call = undefined;
+ }
+
+ if (call) claimed.set(part, call);
+ }
+ }
+
+ // Output results attach to calls registered earlier, including by a
+ // preceding part of the same generation's output.
+ const outputCallIds = new Set<string>();
+ for (const { message } of output) {
+ for (const part of message.parts) {
+ if (part.type === "tool-call" && part.toolCallId)
+ outputCallIds.add(part.toolCallId);
+ if (
+ part.type === "tool-result" &&
+ part.toolCallId &&
+ (outputCallIds.has(part.toolCallId) ||
+ calls.has(key(observation.traceId, part.toolCallId)))
+ )
+ claimed.set(part, undefined);
+ }
}
- if (!call) return false;
- setResponse(call, observation, [part]);
- return true;
+
+ return {
+ claims: (part: Part) => claimed.has(part),
+ /** Register an emitted output's tool calls as anchors for their responses. */
+ register(message: EmittedMessage) {
+ if (message.source !== "output") return;
+
+ for (const part of message.parts) {
+ if (part.type === "tool-call")
+ register(observation, part, thread, message);
+ }
+ },
+ attach(results: Part[]) {
+ for (const part of results) {
+ if (part.type !== "tool-result" || !part.toolCallId) continue;
+
+ const call =
+ claimed.get(part) ??
+ calls.get(key(observation.traceId, part.toolCallId));
+ if (call) setResponse(call, observation, [part]);
+ }
+ },
+ };
}
function attachToolOutput(
@@ -129,16 +181,20 @@ export function createToolCallRegistry() {
) {
const parts = output.flatMap(({ message }) => message.parts);
if (!parts.length) return;
+
let hasId = false;
for (const part of parts) {
if (part.type !== "tool-result" || !part.toolCallId) continue;
+
hasId = true;
const call = calls.get(key(observation.traceId, part.toolCallId));
if (call) setResponse(call, observation, [part]);
}
if (hasId || !observation.name) return;
+
const queue = pending.get(key(observation.traceId, observation.name));
if (!queue) return;
+
while (queue.calls[queue.next]?.fromTool) queue.next++;
const call = queue.calls[queue.next];
if (call) {
@@ -147,5 +203,5 @@ export function createToolCallRegistry() {
}
}
- return { consumePart, attachToolOutput };
+ return { forGeneration, attachToolOutput };
}
diff --git a/packages/shared/src/server/transcript/transcript.ts b/packages/shared/src/server/transcript/transcript.ts
index 6d1bea8f51..ecf0ba9552 100644
--- a/packages/shared/src/server/transcript/transcript.ts
+++ b/packages/shared/src/server/transcript/transcript.ts
@@ -4,6 +4,7 @@ import { normalizeIO } from "../normalized-io";
import type { Transcript } from "./types";
import {
append,
+ createThread,
findThread,
messageKey,
splitTurn,
@@ -52,7 +53,7 @@ export function assembleTranscript(
): Transcript | null {
const startedAt = onTimings ? performance.now() : 0;
let normalizationMs = 0;
- const states: ThreadState[] = [];
+ const threads: ThreadState[] = [];
const toolCalls = createToolCallRegistry();
for (const observation of orderedObservations.filter(isRelevantObservation)) {
@@ -65,25 +66,16 @@ export function assembleTranscript(
}
if (input.length === 0 && output.length === 0) continue;
- // Registered responses do not participate in thread selection.
- let state = findThread(states, input);
- const isNewThread = !state;
- if (!state) {
- // Open new thread
- state = {
- thread: { messages: [], observations: [] },
- messages: [],
- shownCounts: new Map(),
- };
- states.push(state);
+ let thread = findThread(threads, input);
+ if (!thread) {
+ thread = createThread();
+ threads.push(thread);
}
- append(state, observation, input, output, isNewThread, toolCalls);
+ append(thread, observation, input, output, toolCalls);
}
- const transcript = states.length
- ? {
- threads: states.map(({ thread }) => splitTurn(thread)),
- }
+ const transcript = threads.length
+ ? { threads: threads.map(splitTurn) }
: null;
onTimings?.({
normalizationMs,