Skip to content

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

feat(topics): render and measure dedicated trace transcripts (#17925)

Lysander Kiesel51c9fa704ba0
diff --git a/packages/shared/src/server/transcript/README.md b/packages/shared/src/server/transcript/README.md
index 3e023dca1d..fd0decf35a 100644
--- a/packages/shared/src/server/transcript/README.md
+++ b/packages/shared/src/server/transcript/README.md
@@ -43,6 +43,31 @@ without I/O, once for the `GENERATION` and `TOOL` observations with I/O, then
merge the two by id so the walk order comes from the structure and the
messages from the content.
+### Why a trace renderer also needs observations
+
+`assembleTranscript` returns normalized conversation threads, not a complete
+trace. It retains the messages and minimal observation references needed to
+connect them, but does not retain the fields a trace-level view needs:
+
+- A root `SPAN` or `AGENT` can carry the trace input and final application
+ output, including output produced after the last model or tool call. Those
+ fields are absent from the assembled conversation.
+- Non-generation operations, unmatched tool observations, and observation
+ type/name/level/status are not represented as conversation messages. A
+ renderer needs them to show the operation sequence and inline failures.
+- Available tool definitions can occur in generation input or metadata. They
+ are not part of the normalized messages returned by the assembler.
+
+The Topics renderer therefore accepts both the assembled transcript and the
+already loaded, ordered observations. It uses the transcript for roles, threads,
+replayed history, and matched tool results; it uses observations for trace-level
+context and for locating messages among operations. This adds no repository
+read. If other consumers need the same trace context, an explicit optional
+context field or richer observation references on the assembled result could
+remove that second input. Such an extension should keep conversation assembly
+and trace-level facts distinct, so root I/O and operation metadata do not become
+duplicate conversation messages.
+
## Ordering
The transcript walks observations the way the trace tree does: depth first,
@@ -180,7 +205,11 @@ and observation provenance are excluded. All fields inside parts are included.
```
transcript/
├── README.md
-├── index.ts public surface: assembleTranscript, orderObservations, types
+├── index.ts public surface: assembly, renderers, types
+├── topics-renderer.ts Topics trace-level layout
+├── topics-renderer-config.ts Topics block caps and inclusions
+├── topics-renderer.test.ts Topics layout behavior
+├── generic-renderer.ts preserved plain-text comparison layout
├── ordering.ts orderObservations, the trace tree walk
├── ordering.test.ts ordering rules
├── transcript.ts assembleTranscript
diff --git a/packages/shared/src/server/transcript/generic-renderer.ts b/packages/shared/src/server/transcript/generic-renderer.ts
new file mode 100644
index 0000000000..21fde15795
--- /dev/null
+++ b/packages/shared/src/server/transcript/generic-renderer.ts
@@ -0,0 +1,169 @@
+import type { Observation } from "../../domain";
+import type {
+ NormalizedMessage,
+ NormalizedMessagePart,
+} from "../../utils/normalized-io";
+import { normalizeIO } from "../normalized-io";
+import {
+ topicsTranscriptConfig,
+ transcriptRenderConfigSchema,
+} from "./topics-renderer-config";
+import type { Transcript } from "./types";
+
+/** Preserve the original plain-text layout as a measurement baseline. */
+export function renderGenericTranscript(
+ transcript: Transcript | null,
+ observations: Observation[],
+): string {
+ const config = transcriptRenderConfigSchema.parse(topicsTranscriptConfig);
+ const json = (value: unknown) =>
+ typeof value === "string" ? value : (JSON.stringify(value) ?? "");
+ const labeled = (label: string, raw: string, maxChars: number) => {
+ if (maxChars === 0) return `[${label}]`;
+ let content = raw.replace(
+ /data:[^:;,\s]+;base64,[A-Za-z0-9+/=_-]+/g,
+ "[media omitted]",
+ );
+ if (config.collapseWhitespace)
+ content = content.replace(/\s+/g, " ").trim();
+ if (content.length > maxChars) {
+ const head = Math.round(maxChars * config.headRatio);
+ const tail = maxChars - head;
+ const omitted = (content.length - maxChars).toLocaleString("en-US");
+ content =
+ `${content.slice(0, head)} … [${omitted} chars omitted] … ${tail ? content.slice(-tail) : ""}`.trim();
+ }
+ return `[${label}] ${content}`;
+ };
+ const partLine = (
+ message: NormalizedMessage,
+ part: NormalizedMessagePart,
+ ): string | null => {
+ const role =
+ message.role === "tool" ? config.toolResults : config[message.role];
+ const roleLabel = message.senderName
+ ? `${message.role} (${message.senderName})`
+ : message.role;
+ switch (part.type) {
+ case "text":
+ return role.include
+ ? labeled(roleLabel, part.text, role.maxChars)
+ : null;
+ case "reasoning":
+ return config.reasoning.include && part.content.kind === "text"
+ ? labeled(
+ `${roleLabel} · reasoning`,
+ part.content.text,
+ config.reasoning.maxChars,
+ )
+ : null;
+ case "tool-call":
+ return config.toolCalls.include
+ ? labeled(
+ `${roleLabel} → ${part.toolName}${part.invalid ? " (invalid)" : ""}`,
+ json(part.input),
+ config.toolCalls.maxChars,
+ )
+ : null;
+ case "tool-result":
+ return config.toolResults.include
+ ? labeled(
+ `tool ${part.toolName ?? ""} ←${part.isError ? " ERROR" : ""}`.replace(
+ " ",
+ " ",
+ ),
+ json(part.output),
+ config.toolResults.maxChars,
+ )
+ : null;
+ case "file":
+ return role.include && !part.reasoning
+ ? `[${roleLabel}] [${part.mediaType ?? "file"} omitted]`
+ : null;
+ case "data":
+ case "custom":
+ return role.include
+ ? labeled(
+ roleLabel,
+ json(
+ part.type === "data" ? part.value : { [part.kind]: part.value },
+ ),
+ role.maxChars,
+ )
+ : null;
+ }
+ };
+ const messageLines = (messages: NormalizedMessage[]): string[] =>
+ messages.flatMap((message) =>
+ message.parts.flatMap((part) => {
+ const line = partLine(message, part);
+ return line ? [line] : [];
+ }),
+ );
+
+ const lines: string[] = [];
+ if (config.toolDefinitions.include) {
+ const definitions = new Map<string, string>();
+ for (const observation of observations) {
+ if (observation.type !== "GENERATION") continue;
+ const io = {
+ input: observation.input,
+ output: undefined,
+ metadata: observation.metadata,
+ };
+ for (const definition of normalizeIO({ kind: "io", io })
+ .toolDefinitions) {
+ if (!definitions.has(definition.name))
+ definitions.set(
+ definition.name,
+ definition.description?.split(/(?<=\.)\s/)[0] ?? "",
+ );
+ }
+ }
+ if (definitions.size) {
+ lines.push(`AVAILABLE TOOLS (${definitions.size}):`);
+ for (const [name, description] of definitions)
+ lines.push(
+ labeled(name, description, config.toolDefinitions.maxChars).replace(
+ /^\[(.*?)\]/,
+ "- $1:",
+ ),
+ );
+ }
+ }
+
+ const threads = transcript?.threads ?? [];
+ threads.forEach((thread, index) => {
+ if (threads.length > 1) lines.push(`=== thread ${index + 1} ===`);
+ const history =
+ config.history === "include"
+ ? messageLines(thread.conversationHistory)
+ : [];
+ if (history.length) {
+ lines.push(
+ "--- earlier conversation ---",
+ ...history,
+ "--- this trace ---",
+ );
+ }
+ lines.push(...messageLines(thread.currentTurn.messages));
+ });
+
+ if (config.errors.include) {
+ const errors = observations.filter(
+ (observation) =>
+ observation.level === "ERROR" ||
+ (observation.level === "WARNING" && observation.statusMessage),
+ );
+ if (errors.length) lines.push("ERRORS:");
+ for (const observation of errors)
+ lines.push(
+ labeled(
+ `${observation.level} ${observation.type} ${observation.name ?? ""}`.trim(),
+ observation.statusMessage ?? "",
+ config.errors.maxChars,
+ ),
+ );
+ }
+ return lines.join("\n");
+}
diff --git a/packages/shared/src/server/transcript/index.ts b/packages/shared/src/server/transcript/index.ts
index 29831c68f5..69956333bf 100644
--- a/packages/shared/src/server/transcript/index.ts
+++ b/packages/shared/src/server/transcript/index.ts
@@ -1,3 +1,15 @@
export { orderObservations } from "./ordering";
export { assembleTranscript } from "./transcript";
+export {
+ renderTranscript,
+ renderTranscriptFromObservations,
+ transcriptBlockTypes,
+} from "./topics-renderer";
+export { renderGenericTranscript } from "./generic-renderer";
+export {
+ topicsTranscriptConfig,
+ transcriptRenderConfigSchema,
+} from "./topics-renderer-config";
+export type { TranscriptRenderConfig } from "./topics-renderer-config";
+export type { TranscriptBlockType } from "./topics-renderer";
export type * from "./types";
diff --git a/packages/shared/src/server/transcript/topics-renderer-config.ts b/packages/shared/src/server/transcript/topics-renderer-config.ts
new file mode 100644
index 0000000000..7b3b29d9fe
--- /dev/null
+++ b/packages/shared/src/server/transcript/topics-renderer-config.ts
@@ -0,0 +1,47 @@
+import { z } from "zod";
+
+// maxChars 0 keeps the label (e.g. tool name) and drops the content.
+const block = (include: boolean, maxChars: number) =>
+ z
+ .object({
+ include: z.boolean().default(include),
+ maxChars: z.number().int().min(0).default(maxChars),
+ })
+ .prefault({});
+
+// Shared defaults use per-block character caps and an optional total token budget.
+export const transcriptRenderConfigSchema = z.object({
+ system: block(true, 600),
+ user: block(true, 1500),
+ assistant: block(true, 1000),
+ reasoning: block(false, 600),
+ toolCalls: block(true, 300),
+ toolResults: block(true, 400),
+ toolDefinitions: block(false, 120),
+ errors: block(true, 300),
+ runIO: block(true, 10000),
+ observations: block(true, 120),
+ history: z.enum(["include", "omit"]).default("include"),
+ collapseWhitespace: z.boolean().default(true),
+ headRatio: z.number().min(0).max(1).default(0.6),
+ maxTokens: z.number().int().positive().nullable().default(6000),
+});
+
+export type TranscriptRenderConfig = z.input<
+ typeof transcriptRenderConfigSchema
+>;
+
+// Topics measures all block types with per-block caps and no total token budget.
+export const topicsTranscriptConfig = {
+ system: { maxChars: 600 },
+ user: { maxChars: 2000 },
+ assistant: { maxChars: 1500 },
+ reasoning: { include: true, maxChars: 600 },
+ toolCalls: { maxChars: 400 },
+ toolResults: { maxChars: 500 },
+ toolDefinitions: { include: true, maxChars: 120 },
+ errors: { maxChars: 500 },
+ runIO: { maxChars: 10000 },
+ observations: { maxChars: 120 },
+ maxTokens: null,
+} satisfies TranscriptRenderConfig;
diff --git a/packages/shared/src/server/transcript/topics-renderer.test.ts b/packages/shared/src/server/transcript/topics-renderer.test.ts
new file mode 100644
index 0000000000..ad4f4298cf
--- /dev/null
+++ b/packages/shared/src/server/transcript/topics-renderer.test.ts
@@ -0,0 +1,644 @@
+import { describe, expect, it } from "vitest";
+import { convertObservation } from "../repositories/observations_converters";
+import { createObservation } from "../test-utils";
+import { inheritedConversationHistoryFixture } from "./fixtures/trace/inherited-conversation-history";
+import { standaloneToolObservationFixture } from "./fixtures/trace/standalone-tool-observation";
+import { orderObservations } from "./ordering";
+import {
+ renderTranscript,
+ renderTranscriptFromObservations,
+} from "./topics-renderer";
+import { topicsTranscriptConfig } from "./topics-renderer-config";
+import { assembleTranscript } from "./transcript";
+import type { Transcript } from "./types";
+
+const observation = (
+ id: string,
+ type: "SPAN" | "AGENT" | "GENERATION" | "TOOL",
+ second: number,
+) => ({
+ ...convertObservation(createObservation({})),
+ id,
+ traceId: "trace",
+ projectId: "project",
+ type,
+ name: id,
+ parentObservationId: type === "SPAN" ? null : "root",
+ startTime: new Date(`2026-01-01T00:00:${String(second).padStart(2, "0")}Z`),
+ input: null,
+ output: null,
+});
+
+describe("Topics transcript renderer", () => {
+ it("renders an existing assembly identically to the observations-only path", () => {
+ const observations = inheritedConversationHistoryFixture.observations.map(
+ (observation) => convertObservation(createObservation(observation)),
+ );
+ const assembled = assembleTranscript(orderObservations(observations));
+ const result = renderTranscript(
+ assembled,
+ observations,
+ topicsTranscriptConfig,
+ );
+
+ expect(result).toEqual(
+ renderTranscriptFromObservations(observations, topicsTranscriptConfig),
+ );
+ expect(result.text).toBe(
+ [
+ "<run_facts>",
+ "threads: 1 · rendered user entries: 1 · rendered tool calls: 0 · error signals: 0 · omitted lines: 0",
+ "</run_facts>",
+ '<earlier_conversation source="replayed input">',
+ "[user] Initial request",
+ "[assistant] First response",
+ "</earlier_conversation>",
+ "<this_run>",
+ "[generation] Session turn 2",
+ "[user · request] Follow-up request",
+ "[assistant · final output] Second response",
+ "</this_run>",
+ "<end_of_run>",
+ "last action: assistant text",
+ "final output: assistant",
+ "</end_of_run>",
+ ].join("\n"),
+ );
+ expect(result.stats.historyCharacters).toBeGreaterThan(0);
+ expect(result.stats.currentTurnCharacters).toBeGreaterThan(0);
+ expect(result.tokens).toBeNull();
+
+ const reversedObservations = standaloneToolObservationFixture.observations
+ .map((observation) => convertObservation(createObservation(observation)))
+ .reverse();
+ const ordered = orderObservations(reversedObservations);
+ expect(
+ renderTranscriptFromObservations(
+ reversedObservations,
+ topicsTranscriptConfig,
+ ),
+ ).toEqual(
+ renderTranscript(
+ assembleTranscript(ordered),
+ ordered,
+ topicsTranscriptConfig,
+ ),
+ );
+ });
+
+ it("counts characters before and after the Topics block cap", () => {
+ const userText = "x".repeat(2200);
+ const observations = [
+ convertObservation(
+ createObservation({
+ type: "GENERATION",
+ input: JSON.stringify([{ role: "user", content: userText }]),
+ output: JSON.stringify({ role: "assistant", content: "Done" }),
+ }),
+ ),
+ ];
+ const result = renderTranscript(
+ assembleTranscript(orderObservations(observations)),
+ observations,
+ topicsTranscriptConfig,
+ );
+
+ expect(result.stats.blockCharacters.user.raw).toBe(userText.length);
+ expect(result.stats.blockCharacters.user.clipped).toBeLessThan(
+ userText.length,
+ );
+ expect(result.stats.blocksCut).toBe(1);
+ expect(result.stats.messagesOmitted).toBe(0);
+ expect(result.text).toContain("[200 chars omitted]");
+ expect(result.text).toContain("[assistant · final output] Done");
+ });
+
+ it("keeps trace I/O outside chronological threads and labels replayed input", () => {
+ const root = {
+ ...observation("root", "SPAN", 0),
+ input: "Task",
+ output: "Published",
+ };
+ const first = observation("first", "GENERATION", 1);
+ const second = {
+ ...observation("second", "GENERATION", 2),
+ level: "WARNING" as const,
+ statusMessage: "retry",
+ };
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: [
+ {
+ role: "user",
+ source: "input",
+ parts: [{ type: "text", text: "Task" }],
+ observationId: first.id,
+ traceId: "trace",
+ },
+ {
+ role: "assistant",
+ source: "output",
+ parts: [{ type: "text", text: "Draft" }],
+ observationId: first.id,
+ traceId: "trace",
+ },
+ ],
+ observations: [{ id: first.id, traceId: "trace" }],
+ },
+ },
+ {
+ conversationHistory: [
+ {
+ role: "user",
+ source: "input",
+ parts: [{ type: "text", text: "Replayed context" }],
+ },
+ ],
+ currentTurn: {
+ messages: [
+ {
+ role: "assistant",
+ source: "output",
+ parts: [{ type: "text", text: "Second" }],
+ observationId: second.id,
+ traceId: "trace",
+ },
+ ],
+ observations: [{ id: second.id, traceId: "trace" }],
+ },
+ },
+ ],
+ };
+ const text = renderTranscript(
+ transcript,
+ [root, first, second],
+ topicsTranscriptConfig,
+ ).text;
+
+ expect(text).toContain(
+ '<earlier_conversation source="replayed input">\n<thread n="2">\n[user] Replayed context\n</thread>\n</earlier_conversation>',
+ );
+ expect(text).toContain("[user · request] Task");
+ expect(text).not.toContain("[input · request] Task");
+ expect(text).toContain("[generation] first");
+ expect(text).toContain("[generation] second");
+ expect(text).toContain("[warning GENERATION second] retry");
+ expect(text).toContain("[final output] Published");
+ expect(text.indexOf("<run_facts>")).toBeLessThan(
+ text.indexOf("<earlier_conversation"),
+ );
+ expect(text.indexOf("<earlier_conversation")).toBeLessThan(
+ text.indexOf("<this_run>"),
+ );
+ expect(text.indexOf("<this_run>")).toBeLessThan(
+ text.indexOf("<end_of_run>"),
+ );
+ expect(text).toContain(
+ "last action: assistant text\nfinal output: application output",
+ );
+ });
+
+ it("shows trace I/O for a pipeline without a user and notes only a distinct output", () => {
+ const root = {
+ ...observation("root", "SPAN", 0),
+ parentObservationId: "",
+ input: "Timer fired",
+ output: "Final report",
+ };
+ const generation = observation("generation", "GENERATION", 1);
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: [
+ {
+ role: "system",
+ source: "input",
+ parts: [{ type: "text", text: "Summarize the data" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "assistant",
+ source: "output",
+ parts: [{ type: "text", text: "Draft" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ ],
+ observations: [{ id: generation.id, traceId: "trace" }],
+ },
+ },
+ ],
+ };
+
+ const distinct = renderTranscript(
+ transcript,
+ [root, generation],
+ topicsTranscriptConfig,
+ ).text;
+ expect(distinct).toContain("[input · request] Timer fired");
+ expect(distinct).toContain("[final output] Final report");
+ expect(distinct).not.toContain("[user · request]");
+ expect(distinct).toContain("final output: application output");
+
+ const matching = renderTranscript(
+ transcript,
+ [{ ...root, output: "Draft" }, generation],
+ topicsTranscriptConfig,
+ ).text;
+ expect(matching).toContain("[assistant · final output] Draft");
+ expect(matching).not.toContain("[final output] Draft");
+ expect(matching).toContain("final output: assistant");
+ });
+
+ it("keeps an unassigned operation marker inside the active thread", () => {
+ const first = observation("first", "GENERATION", 1);
+ const marker = observation("validate", "SPAN", 2);
+ const second = observation("second", "GENERATION", 3);
+ const other = observation("other", "GENERATION", 4);
+ const message = (observationId: string, value: string) => ({
+ role: "assistant" as const,
+ source: "output" as const,
+ parts: [{ type: "text" as const, text: value }],
+ observationId,
+ traceId: "trace",
+ });
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: [
+ message(first.id, "First"),
+ message(second.id, "Second"),
+ ],
+ observations: [first, second].map(({ id }) => ({
+ id,
+ traceId: "trace",
+ })),
+ },
+ },
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: [message(other.id, "Other")],
+ observations: [{ id: other.id, traceId: "trace" }],
+ },
+ },
+ ],
+ };
+
+ const text = renderTranscript(
+ transcript,
+ [first, marker, second, other],
+ topicsTranscriptConfig,
+ ).text;
+ expect(text).toContain(
+ "[assistant] First\n[span] validate\n[generation] second",
+ );
+ expect(text.match(/<thread n="1">/g)).toHaveLength(1);
+ });
+
+ it("numbers a failing tool pair, places its error inline, and distinguishes a pending call", () => {
+ const root = { ...observation("root", "SPAN", 0), input: "Search" };
+ const generation = observation("generation", "GENERATION", 1);
+ const tool = {
+ ...observation("tool", "TOOL", 2),
+ name: "search",
+ level: "ERROR" as const,
+ statusMessage: "timeout",
+ };
+ const messages: Transcript["threads"][number]["currentTurn"]["messages"] = [
+ {
+ role: "user",
+ source: "input",
+ parts: [{ type: "text", text: "Search" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "assistant",
+ source: "output",
+ parts: [
+ {
+ type: "tool-call",
+ toolCallId: "call-1",
+ toolName: "search",
+ input: { query: "x" },
+ },
+ ],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "tool",
+ source: "output",
+ parts: [
+ {
+ type: "tool-result",
+ toolCallId: "call-1",
+ toolName: "search",
+ output: "timeout",
+ isError: true,
+ },
+ ],
+ observationId: tool.id,
+ traceId: "trace",
+ },
+ ];
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages,
+ observations: [
+ { id: generation.id, traceId: "trace" },
+ { id: tool.id, traceId: "trace" },
+ ],
+ },
+ },
+ ],
+ };
+
+ const failed = renderTranscript(
+ transcript,
+ [root, generation, tool],
+ topicsTranscriptConfig,
+ ).text;
+ expect(failed).toContain(
+ '[assistant → search #1] {"query":"x"}\n[tool search #1 ← ERROR] timeout\n[error TOOL search] timeout',
+ );
+ expect(failed).toContain("last action: tool result");
+
+ const pending: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: messages.slice(0, 2),
+ observations: [{ id: generation.id, traceId: "trace" }],
+ },
+ },
+ ],
+ };
+ expect(
+ renderTranscript(pending, [root, generation], topicsTranscriptConfig)
+ .text,
+ ).toContain("last action: assistant tool call");
+ });
+
+ it("marks the request after supplied context without repeating trace input", () => {
+ const root = {
+ ...observation("root", "SPAN", 0),
+ input: "System instructions",
+ output: "Done",
+ };
+ const generation = observation("generation", "GENERATION", 1);
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: [
+ {
+ role: "system",
+ source: "input",
+ parts: [{ type: "text", text: "System instructions" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "user",
+ source: "input",
+ parts: [{ type: "text", text: "Project data" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "user",
+ source: "input",
+ parts: [{ type: "text", text: "Find the errors" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "assistant",
+ source: "output",
+ parts: [{ type: "text", text: "Done" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ ],
+ observations: [{ id: generation.id, traceId: "trace" }],
+ },
+ },
+ ],
+ };
+
+ const text = renderTranscript(
+ transcript,
+ [root, generation],
+ topicsTranscriptConfig,
+ ).text;
+ expect(text).toContain(
+ "[user] Project data\n[user · request] Find the errors",
+ );
+ expect(text).not.toContain("[input · request]");
+ expect(text).toContain("[assistant · final output] Done");
+ expect(text).not.toContain("[final output] Done");
+ });
+
+ it("keeps distinct trace input alongside a user request", () => {
+ const root = {
+ ...observation("root", "SPAN", 0),
+ input: "Triggered by a scheduled import",
+ };
+ const generation = observation("generation", "GENERATION", 1);
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: [
+ {
+ role: "user",
+ source: "input",
+ parts: [{ type: "text", text: "Summarize the import" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "assistant",
+ source: "output",
+ parts: [{ type: "text", text: "Summary" }],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ ],
+ observations: [{ id: generation.id, traceId: "trace" }],
+ },
+ },
+ ],
+ };
+
+ const text = renderTranscript(
+ transcript,
+ [root, generation],
+ topicsTranscriptConfig,
+ ).text;
+ expect(text).toContain(
+ "[trace input · context] Triggered by a scheduled import",
+ );
+ expect(text).toContain("[user · request] Summarize the import");
+ });
+
+ it("marks observation kinds and attributes a matching final output to a tool", () => {
+ const root = {
+ ...observation("root", "SPAN", 0),
+ output: "Result",
+ };
+ const agent = observation("agent", "AGENT", 1);
+ const generation = observation("generation", "GENERATION", 2);
+ const tool = { ...observation("tool", "TOOL", 3), name: "lookup" };
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [],
+ currentTurn: {
+ messages: [
+ {
+ role: "assistant",
+ source: "output",
+ parts: [
+ {
+ type: "tool-call",
+ toolCallId: "call-1",
+ toolName: "lookup",
+ input: { query: "x" },
+ },
+ ],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "tool",
+ source: "output",
+ parts: [
+ {
+ type: "tool-result",
+ toolCallId: "call-1",
+ toolName: "lookup",
+ output: "Result",
+ },
+ ],
+ observationId: tool.id,
+ traceId: "trace",
+ },
+ ],
+ observations: [
+ { id: generation.id, traceId: "trace" },
+ { id: tool.id, traceId: "trace" },
+ ],
+ },
+ },
+ ],
+ };
+
+ const text = renderTranscript(
+ transcript,
+ [root, agent, generation, tool],
+ topicsTranscriptConfig,
+ ).text;
+ expect(text).toContain(
+ "[span] root\n[agent] agent\n[generation] generation",
+ );
+ expect(text).toContain("[tool lookup #1 ← FINAL OUTPUT] Result");
+ expect(text).not.toContain("[tool] lookup");
+ expect(text).not.toContain("[final output] Result");
+ expect(text).toContain("final output: tool result");
+ });
+
+ it("pairs a result with the current call when replayed history reused its ID", () => {
+ const generation = observation("generation", "GENERATION", 1);
+ const tool = { ...observation("tool", "TOOL", 2), name: "lookup" };
+ const call = {
+ type: "tool-call" as const,
+ toolCallId: "same-id",
+ toolName: "lookup",
+ input: { query: "x" },
+ };
+ const transcript: Transcript = {
+ threads: [
+ {
+ conversationHistory: [
+ {
+ role: "assistant",
+ source: "output",
+ parts: [call],
+ },
+ ],
+ currentTurn: {
+ messages: [
+ {
+ role: "assistant",
+ source: "output",
+ parts: [call],
+ observationId: generation.id,
+ traceId: "trace",
+ },
+ {
+ role: "tool",
+ source: "output",
+ parts: [
+ {
+ type: "tool-result",
+ toolCallId: "same-id",
+ toolName: "lookup",
+ output: "Found",
+ },
+ ],
+ observationId: tool.id,
+ traceId: "trace",
+ },
+ ],
+ observations: [
+ { id: generation.id, traceId: "trace" },
+ { id: tool.id, traceId: "trace" },
+ ],
+ },
+ },
+ ],
+ };
+
+ const text = renderTranscript(
+ transcript,
+ [generation, tool],
+ topicsTranscriptConfig,
+ ).text;
+ expect(text).toContain('[assistant → lookup #1] {"query":"x"}');
+ expect(text).toContain("[tool lookup #1 ←] Found");
+
+ const withoutIds = structuredClone(transcript);
+ for (const message of [
+ ...withoutIds.threads[0]!.conversationHistory,
+ ...withoutIds.threads[0]!.currentTurn.messages,
+ ]) {
+ for (const part of message.parts) {
+ if (part.type === "tool-call" || part.type === "tool-result")
+ part.toolCallId = null;
+ }
+ }
+ const withoutIdsText = renderTranscript(
+ withoutIds,
+ [generation, tool],
+ topicsTranscriptConfig,
+ ).text;
+ expect(withoutIdsText).toContain("[tool lookup #1 ←] Found");
+ });
+});
diff --git a/packages/shared/src/server/transcript/topics-renderer.ts b/packages/shared/src/server/transcript/topics-renderer.ts
new file mode 100644
index 0000000000..ab16339530
--- /dev/null
+++ b/packages/shared/src/server/transcript/topics-renderer.ts
@@ -0,0 +1,703 @@
+import type { Observation } from "../../domain";
+import type {
+ NormalizedMessage,
+ NormalizedMessagePart,
+} from "../../utils/normalized-io";
+import { normalizeIO } from "../normalized-io";
+import { orderObservations } from "./ordering";
+import { assembleTranscript } from "./transcript";
+import type { Transcript } from "./types";
+import {
+ transcriptRenderConfigSchema,
+ type TranscriptRenderConfig,
+} from "./topics-renderer-config";
+
+export const transcriptBlockTypes = [
+ "user",
+ "assistant",
+ "system",
+ "reasoning",
+ "tool_calls",
+ "tool_results",
+ "tool_definitions",
+ "errors",
+ "run_io",
+ "observations",
+] as const;
+
+export type TranscriptBlockType = (typeof transcriptBlockTypes)[number];
+type BlockCharacters = { raw: number; clipped: number };
+type Line = { text: string; removable: boolean; history?: boolean };
+type PartEvent = {
+ kind: "part";
+ thread: number;
+ message: NormalizedMessage;
+ part: NormalizedMessagePart;
+ observationIndex: number;
+ sequence: number;
+ history: boolean;
+ callNumber?: number;
+ toolName?: string;
+ finalOutput?: boolean;
+};
+type ErrorEvent = {
+ kind: "error";
+ observation: Observation;
+ observationIndex: number;
+ thread: number | null;
+};
+type ObservationEvent = {
+ kind: "observation";
+ observation: Observation;
+ observationIndex: number;
+ thread: number | null;
+};
+type CurrentEvent = PartEvent | ErrorEvent | ObservationEvent;
+type RenderedEvent = { event: CurrentEvent; text: string };
+
+const redactInlineMedia = (text: string): string =>
+ text.replace(/data:[^:;,\s]+;base64,[A-Za-z0-9+/=_-]+/g, "[media omitted]");
+
+/**
+ * Render an assembled trace for Topics without assembling it a second time.
+ * Observations provide root I/O and operation context omitted by assembly.
+ */
+export function renderTranscript(
+ transcript: Transcript | null,
+ observations: Observation[],
+ configInput: TranscriptRenderConfig,
+ countTokens?: (text: string) => number,
+): {
+ text: string;
+ tokens: number | null;
+ stats: {
+ blocksCut: number;
+ messagesOmitted: number;
+ blockCharacters: Record<TranscriptBlockType, BlockCharacters>;
+ historyCharacters: number;
+ currentTurnCharacters: number;
+ };
+} {
+ const config = transcriptRenderConfigSchema.parse(configInput);
+ let blocksCut = 0;
+ const blockCharacters = Object.fromEntries(
+ transcriptBlockTypes.map((block) => [block, { raw: 0, clipped: 0 }]),
+ ) as Record<TranscriptBlockType, BlockCharacters>;
+
+ const clip = (raw: string, maxChars: number, block: TranscriptBlockType) => {
+ let text = redactInlineMedia(raw);
+ if (config.collapseWhitespace) text = text.replace(/\s+/g, " ").trim();
+ blockCharacters[block].raw += text.length;
+ if (text.length > maxChars) {
+ blocksCut++;
+ const head = Math.round(maxChars * config.headRatio);
+ const tail = maxChars - head;
+ const omitted = (text.length - maxChars).toLocaleString("en-US");
+ text =
+ `${text.slice(0, head)} … [${omitted} chars omitted] … ${tail ? text.slice(-tail) : ""}`.trim();
+ }
+ blockCharacters[block].clipped += text.length;
+ return text;
+ };
+ const json = (value: unknown) =>
+ typeof value === "string" ? value : (JSON.stringify(value) ?? "");
+ const labeled = (
+ label: string,
+ content: string,
+ maxChars: number,
+ block: TranscriptBlockType,
+ ) =>
+ maxChars === 0
+ ? `[${label}]`
+ : `[${label}] ${clip(content, maxChars, block)}`.trimEnd();
+ const partContent = (part: NormalizedMessagePart): string => {
+ switch (part.type) {
+ case "text":
+ return part.text;
+ case "reasoning":
+ return part.content.kind === "text" ? part.content.text : "";
+ case "tool-call":
+ return `${part.toolName} ${json(part.input)}`;
+ case "tool-result":
+ return json(part.output);
+ case "file":
+ return `[${part.mediaType ?? "file"} omitted]`;
+ case "data":
+ return json(part.value);
+ case "custom":
+ return json({ [part.kind]: part.value });
+ }
+ };
+ const rootContent = (
+ observation: Observation,
+ source: "input" | "output",
+ ) => {
+ const value = observation[source];
+ const parts = normalizeIO({
+ kind: "io",
+ io: {
+ input: source === "input" ? value : undefined,
+ output: source === "output" ? value : undefined,
+ metadata: observation.metadata,
+ },
+ })
+ .messages.filter((message) => message.source === source)
+ .flatMap((message) => message.parts.map(partContent))
+ .filter(Boolean);
+ return parts.length ? parts.join("\n") : json(value);
+ };
+
+ const observationIndices = new Map(
+ observations.map((observation, index) => [observation.id, index]),
+ );
+ const observationById = new Map(
+ observations.map((observation) => [observation.id, observation]),
+ );
+ const threads = transcript?.threads ?? [];
+ const historyEvents: PartEvent[] = [];
+ const currentEvents: PartEvent[] = [];
+ let sequence = 0;
+ threads.forEach((thread, threadIndex) => {
+ for (const message of config.history === "include"
+ ? thread.conversationHistory
+ : []) {
+ for (const part of message.parts)
+ historyEvents.push({
+ kind: "part",
+ thread: threadIndex,
+ message,
+ part,
+ observationIndex: -1,
+ sequence: sequence++,
+ history: true,
+ });
+ }
+ for (const message of thread.currentTurn.messages) {
+ for (const part of message.parts)
+ currentEvents.push({
+ kind: "part",
+ thread: threadIndex,
+ message,
+ part,
+ observationIndex:
+ observationIndices.get(message.observationId) ??
+ Number.MAX_SAFE_INTEGER,
+ sequence: sequence++,
+ history: false,
+ });
+ }
+ });
+ currentEvents.sort(
+ (a, b) =>
+ a.observationIndex - b.observationIndex || a.sequence - b.sequence,
+ );
+
+ // Match each result to a preceding call in its thread. Replayed calls can
+ // share IDs with current calls, so an ID match uses the most recent call.
+ const allPartEvents = [...historyEvents, ...currentEvents];
+ let nextCallNumber = 0;
+ const callsById = new Map<string, PartEvent[]>();
+ const callsByName = new Map<string, PartEvent[]>();
+ const callKey = (thread: number, value: string) => `${thread}:${value}`;
+ const matchedCalls = new Set<PartEvent>();
+ const resultMessages = new WeakMap<NormalizedMessage, number | null>();
+ const takeCall = (
+ calls: PartEvent[] | undefined,
+ newest: boolean,
+ history: boolean,
+ ) => {
+ const available = calls?.filter(
+ (candidate) => !matchedCalls.has(candidate),
+ );
+ const sameSection = available?.filter(
+ (candidate) => candidate.history === history,
+ );
+ const candidates = sameSection?.length ? sameSection : available;
+ const call = newest ? candidates?.at(-1) : candidates?.[0];
+ if (call) matchedCalls.add(call);
+ return call?.callNumber;
+ };
+ for (const event of allPartEvents) {
+ if (event.part.type === "tool-call" && config.toolCalls.include) {
+ if (!event.history) event.callNumber = ++nextCallNumber;
+ const name = callKey(event.thread, event.part.toolName);
+ callsByName.set(name, [...(callsByName.get(name) ?? []), event]);
+ if (event.part.toolCallId) {
+ const id = callKey(event.thread, event.part.toolCallId);
+ callsById.set(id, [...(callsById.get(id) ?? []), event]);
+ }
+ continue;
+ }
+ const isResult =
+ event.part.type === "tool-result" || event.message.role === "tool";
+ if (!isResult) continue;
+ event.toolName =
+ (event.part.type === "tool-result" ? event.part.toolName : undefined) ??
+ ("observationId" in event.message
+ ? observationById.get(event.message.observationId as string)?.name
+ : undefined) ??
+ event.message.senderName ??
+ "";
+ if (event.message.role === "tool" && resultMessages.has(event.message)) {
+ event.callNumber = resultMessages.get(event.message) ?? undefined;
+ continue;
+ }
+ const id = event.part.type === "tool-result" ? event.part.toolCallId : null;
+ event.callNumber = id
+ ? takeCall(callsById.get(callKey(event.thread, id)), true, event.history)
+ : takeCall(
+ callsByName.get(callKey(event.thread, event.toolName)),
+ false,
+ event.history,
+ );
+ if (event.message.role === "tool")
+ resultMessages.set(event.message, event.callNumber ?? null);
+ }
+
+ const comparable = (value: string) => value.replace(/\s+/g, " ").trim();
+ const firstResponse = currentEvents.findIndex(
+ (event) =>
+ event.message.role === "assistant" || event.part.type === "tool-result",
+ );
+ const requestMessage = (
+ firstResponse < 0 ? currentEvents : currentEvents.slice(0, firstResponse)
+ )
+ .filter((event) => event.message.role === "user")
+ .at(-1)?.message;
+ const root = observations.find(
+ (observation) =>
+ observation.parentObservationId === null ||
+ !observationById.has(observation.parentObservationId),
+ );
+ const rootInputValue =
+ config.runIO.include && root?.input != null
+ ? rootContent(root, "input")
+ : null;
+ let rootInput = rootInputValue;
+ if (rootInput) {
+ const comparableRootInput = comparable(rootInput);
+ const inputMessages = [
+ ...new Set(
+ [...historyEvents, ...currentEvents]
+ .filter((event) => event.message.source === "input")
+ .map((event) => event.message),
+ ),
+ ];
+ const inputContents = inputMessages
+ .map((message) =>
+ message.parts.map(partContent).filter(Boolean).join("\n"),
+ )
+ .filter(Boolean);
+ if (
+ inputContents.some(
+ (content) => comparable(content) === comparableRootInput,
+ ) ||
+ comparable(inputContents.join("\n")) === comparableRootInput
+ )
+ rootInput = null;
+ }
+ const rootOutput =
+ config.runIO.include && root?.output != null
+ ? rootContent(root, "output")
+ : null;
+ const finalEvent = [...currentEvents]
+ .reverse()
+ .find(
+ (event) =>
+ event.part.type === "tool-result" ||
+ ((event.message.role === "assistant" ||
+ event.message.role === "tool") &&
+ (event.part.type === "text" ||
+ event.part.type === "data" ||
+ event.part.type === "custom")),
+ );
+ const finalMessageText = finalEvent?.message.parts
+ .filter(
+ (part) =>
+ part.type === "text" ||
+ part.type === "data" ||
+ part.type === "custom" ||
+ part.type === "tool-result",
+ )
+ .map(partContent)
+ .join("\n");
+ const outputMatchesMessage =
+ !!rootOutput &&
+ !!finalMessageText &&
+ comparable(rootOutput) === comparable(finalMessageText);
+ if (outputMatchesMessage && finalEvent) finalEvent.finalOutput = true;
+ const partLine = (event: PartEvent): string | null => {
+ const { message, part } = event;
+ const role =
+ message.role === "tool" ? config.toolResults : config[message.role];
+ const roleLabel = message.senderName
+ ? `${message.role} (${message.senderName})`
+ : message.role;
+ let userLabel = roleLabel;
+ if (message.role === "user" && message === requestMessage)
+ userLabel = `${roleLabel} · request`;
+ else if (event.finalOutput && message.role === "assistant")
+ userLabel = `${roleLabel} · final output`;
+ const resultLabel =
+ `tool ${event.toolName ?? ""}${event.callNumber ? ` #${event.callNumber}` : ""} ←${event.finalOutput ? " FINAL OUTPUT" : ""}`
+ .replace(/\s+/g, " ")
+ .trim();
+ if (message.role === "tool" && part.type !== "tool-result") {
+ return role.include && !(part.type === "file" && part.reasoning)
+ ? labeled(resultLabel, partContent(part), role.maxChars, "tool_results")
+ : null;
+ }
+ switch (part.type) {
+ case "text":
+ return role.include
+ ? labeled(
+ userLabel,
+ part.text,
+ role.maxChars,
+ message.role === "tool" ? "tool_results" : message.role,
+ )
+ : null;
+ case "reasoning":
+ return config.reasoning.include && part.content.kind === "text"
+ ? labeled(
+ `${roleLabel} · reasoning`,
+ part.content.text,
+ config.reasoning.maxChars,
+ "reasoning",
+ )
+ : null;
+ case "tool-call":
+ return config.toolCalls.include
+ ? labeled(
+ `${roleLabel} → ${part.toolName}${event.callNumber ? ` #${event.callNumber}` : ""}${part.invalid ? " (invalid)" : ""}`,
+ json(part.input),
+ config.toolCalls.maxChars,
+ "tool_calls",
+ )
+ : null;
+ case "tool-result":
+ return config.toolResults.include
+ ? labeled(
+ `${resultLabel}${part.isError ? " ERROR" : ""}`,
+ json(part.output),
+ config.toolResults.maxChars,
+ "tool_results",
+ )
+ : null;
+ case "file":
+ return role.include && !part.reasoning
+ ? `[${userLabel}] [${part.mediaType ?? "file"} omitted]`
+ : null;
+ case "data":
+ case "custom":
+ return role.include
+ ? labeled(
+ userLabel,
+ partContent(part),
+ role.maxChars,
+ message.role === "tool" ? "tool_results" : message.role,
+ )
+ : null;
+ }
+ };
+
+ const history = historyEvents
+ .map((event): RenderedEvent | null => {
+ const text = partLine(event);
+ return text ? { event, text } : null;
+ })
+ .filter((event): event is RenderedEvent => event !== null);
+ const currentWithErrors: CurrentEvent[] = [...currentEvents];
+ const threadByObservation = new Map(
+ currentEvents.map((event) => [event.observationIndex, event.thread]),
+ );
+ const representedTools = new Set(
+ currentEvents
+ .filter(
+ (event) =>
+ event.message.role === "tool" || event.part.type === "tool-result",
+ )
+ .flatMap((event) =>
+ "observationId" in event.message
+ ? [event.message.observationId as string]
+ : [],
+ ),
+ );
+ if (config.observations.include) {
+ observations.forEach((observation, observationIndex) => {
+ if (observation.type === "TOOL" && representedTools.has(observation.id))
+ return;
+ currentWithErrors.push({
+ kind: "observation",
+ observation,
+ observationIndex,
+ thread: threadByObservation.get(observationIndex) ?? null,
+ });
+ });
+ }
+ if (config.errors.include) {
+ observations.forEach((observation, observationIndex) => {
+ if (
+ observation.level === "ERROR" ||
+ (observation.level === "WARNING" && observation.statusMessage)
+ )
+ currentWithErrors.push({
+ kind: "error",
+ observation,
+ observationIndex,
+ thread: threadByObservation.get(observationIndex) ?? null,
+ });
+ });
+ }
+ currentWithErrors.sort(
+ (a, b) =>
+ a.observationIndex - b.observationIndex ||
+ { observation: 0, part: 1, error: 2 }[a.kind] -
+ { observation: 0, part: 1, error: 2 }[b.kind] ||
+ (a.kind === "part" && b.kind === "part" ? a.sequence - b.sequence : 0),
+ );
+ const current = currentWithErrors
+ .map((event): RenderedEvent | null => {
+ let text: string | null;
+ if (event.kind === "part") text = partLine(event);
+ else if (event.kind === "observation")
+ text = labeled(
+ event.observation.type.toLowerCase(),
+ event.observation.name ?? "",
+ config.observations.maxChars,
+ "observations",
+ );
+ else
+ text = labeled(
+ `${event.observation.level === "WARNING" ? "warning" : "error"} ${event.observation.type} ${event.observation.name ?? ""}`.trim(),
+ event.observation.statusMessage ?? "",
+ config.errors.maxChars,
+ "errors",
+ );
+ return text ? { event, text } : null;
+ })
+ .filter((event): event is RenderedEvent => event !== null);
+
+ const rootInputLine = rootInput
+ ? labeled(
+ requestMessage ? "trace input · context" : "input · request",
+ rootInput,
+ requestMessage
+ ? Math.min(config.runIO.maxChars, config.user.maxChars)
+ : config.runIO.maxChars,
+ "run_io",
+ )
+ : null;
+ const rootOutputLine =
+ rootOutput && !outputMatchesMessage
+ ? labeled("final output", rootOutput, config.runIO.maxChars, "run_io")
+ : null;
+
+ const errorObservations = new Set(
+ currentWithErrors
+ .filter((event): event is ErrorEvent => event.kind === "error")
+ .map((event) => event.observation.id),
+ );
+ for (const event of currentEvents) {
+ if (
+ config.toolResults.include &&
+ event.part.type === "tool-result" &&
+ event.part.isError
+ ) {
+ if ("observationId" in event.message)
+ errorObservations.add(event.message.observationId as string);
+ }
+ }
+ const userMessages = new Set(
+ config.user.include
+ ? currentEvents
+ .filter((event) => event.message.role === "user")
+ .map((event) => event.message)
+ : [],
+ );
+ const runToolCalls = config.toolCalls.include
+ ? currentEvents.filter((event) => event.part.type === "tool-call").length
+ : 0;
+ const facts = (omitted: number) =>
+ `threads: ${threads.length} · rendered user entries: ${userMessages.size} · rendered tool calls: ${runToolCalls} · error signals: ${errorObservations.size} · omitted lines: ${omitted}`;
+
+ const lines: Line[] = [];
+ const header = (text: string) => lines.push({ text, removable: false });
+ header("<run_facts>");
+ const factsLine: Line = { text: facts(0), removable: false };
+ lines.push(factsLine);
+ header("</run_facts>");
+
+ if (config.toolDefinitions.include) {
+ const definitions = new Map<string, string>();
+ for (const observation of observations) {
+ if (observation.type !== "GENERATION") continue;
+ const io = {
+ input: observation.input,
+ output: undefined,
+ metadata: observation.metadata,
+ };
+ for (const definition of normalizeIO({ kind: "io", io })
+ .toolDefinitions) {
+ if (!definitions.has(definition.name))
+ definitions.set(
+ definition.name,
+ definition.description?.split(/(?<=\.)\s/)[0] ?? "",
+ );
+ }
+ }
+ if (definitions.size) {
+ header("<tools>");
+ for (const [name, description] of definitions)
+ header(
+ labeled(
+ name,
+ description,
+ config.toolDefinitions.maxChars,
+ "tool_definitions",
+ ).replace(/^\[(.*?)\]/, "- $1:"),
+ );
+ header("</tools>");
+ }
+ }
+
+ const addEvents = (events: RenderedEvent[], historySection: boolean) => {
+ let activeThread: number | null = null;
+ for (const { event, text } of events) {
+ const thread = event.thread;
+ if (threads.length > 1 && thread !== null && thread !== activeThread) {
+ if (activeThread !== null) header("</thread>");
+ header(`<thread n="${thread + 1}">`);
+ activeThread = thread;
+ }
+ lines.push({
+ text,
+ removable: event.kind === "part",
+ history: historySection,
+ });
+ }
+ if (threads.length > 1 && activeThread !== null) header("</thread>");
+ };
+ if (history.length) {
+ header('<earlier_conversation source="replayed input">');
+ addEvents(history, true);
+ header("</earlier_conversation>");
+ }
+ if (rootInputLine || current.length || rootOutputLine) {
+ header("<this_run>");
+ if (rootInputLine)
+ lines.push({ text: rootInputLine, removable: false, history: false });
+ addEvents(current, false);
+ if (rootOutputLine)
+ lines.push({ text: rootOutputLine, removable: false, history: false });
+ header("</this_run>");
+ }
+
+ const lastPart = [...current]
+ .reverse()
+ .find(({ event }) => event.kind === "part")?.event;
+ let lastAction = "none";
+ if (lastPart?.kind === "part") {
+ if (lastPart.part.type === "tool-call") lastAction = "assistant tool call";
+ else if (
+ lastPart.part.type === "tool-result" ||
+ lastPart.message.role === "tool"
+ )
+ lastAction = "tool result";
+ else if (lastPart.message.role === "user") lastAction = "user message";
+ else if (lastPart.part.type === "reasoning")
+ lastAction = "assistant reasoning";
+ else if (lastPart.message.role === "assistant")
+ lastAction = "assistant text";
+ else lastAction = `${lastPart.message.role} message`;
+ }
+ header("<end_of_run>");
+ header(`last action: ${lastAction}`);
+ if (rootOutputLine) header("final output: application output");
+ else if (outputMatchesMessage)
+ header(
+ `final output: ${finalEvent?.part.type === "tool-result" || finalEvent?.message.role === "tool" ? "tool result" : "assistant"}`,
+ );
+ header("</end_of_run>");
+
+ // Keep headings and trace-level I/O; drop ordinary lines from the middle.
+ const removable = lines.filter((line) => line.removable);
+ const select = (keep: number): Line[] => {
+ const kept = new Set([
+ ...removable.slice(0, Math.ceil(keep / 2)),
+ ...removable.slice(removable.length - Math.floor(keep / 2)),
+ ]);
+ const selected: Line[] = [];
+ let marked = false;
+ for (const line of lines) {
+ if (!line.removable || kept.has(line)) selected.push(line);
+ else if (!marked) {
+ selected.push({
+ text: `[… ${removable.length - keep} lines omitted …]`,
+ removable: false,
+ });
+ marked = true;
+ }
+ }
+ return selected.map((line) =>
+ line === factsLine
+ ? { ...line, text: facts(removable.length - keep) }
+ : line,
+ );
+ };
+ const tokensOf = (keep: number) =>
+ countTokens!(
+ select(keep)
+ .map((line) => line.text)
+ .join("\n"),
+ );
+ let keep = removable.length;
+ if (
+ countTokens &&
+ config.maxTokens !== null &&
+ tokensOf(keep) > config.maxTokens
+ ) {
+ let low = 0;
+ let high = keep - 1;
+ while (low < high) {
+ const middle = low + Math.ceil((high - low) / 2);
+ if (tokensOf(middle) <= config.maxTokens) low = middle;
+ else high = middle - 1;
+ }
+ keep = low;
+ }
+ const selected = select(keep);
+ const text = selected.map((line) => line.text).join("\n");
+ const historyCharacters = selected
+ .filter((line) => line.history === true)
+ .reduce((sum, line) => sum + line.text.length, 0);
+ const currentTurnCharacters = selected
+ .filter((line) => line.history === false)
+ .reduce((sum, line) => sum + line.text.length, 0);
+ return {
+ text,
+ tokens: countTokens ? countTokens(text) : null,
+ stats: {
+ blocksCut,
+ messagesOmitted: removable.length - keep,
+ blockCharacters,
+ historyCharacters,
+ currentTurnCharacters,
+ },
+ };
+}
+
+/** Assemble only for callers that do not already have the shared transcript. */
+export function renderTranscriptFromObservations(
+ observations: Observation[],
+ configInput: TranscriptRenderConfig,
+ countTokens?: (text: string) => number,
+) {
+ const orderedObservations = orderObservations(observations);
+ return renderTranscript(
+ assembleTranscript(orderedObservations),
+ orderedObservations,
+ configInput,
+ countTokens,
+ );
+}
diff --git a/worker/AGENTS.md b/worker/AGENTS.md
index 121f68cdc9..09c3590986 100644
--- a/worker/AGENTS.md
+++ b/worker/AGENTS.md
@@ -30,9 +30,11 @@
and Redis snapshots independently of dispatch/consumption when either role is
enabled. Global snapshot gauges must not be summed across worker reporters.
`src/features/traceBatching/traceBatchTranscript.ts` measures per-trace assembly
- phases, thread count, current-turn/history token estimates and their sum.
- Token partitions run sequentially; tool-response size uses comparable character
- counts over message parts, without another tokenizer pass.
+ phases, thread count, current-turn/history token estimates and their sum. Each
+ admitted trace records full assembled-transcript JSON lengths, renders the
+ previous generic text as a comparison, then renders Topics text and its block
+ metrics. Token estimates run sequentially;
+ tool-response size uses comparable character counts over message parts.
Allow one pending tokenization promise per batch while
buffering the next trace, and drain it even on read failure. Never flush a failed
stream's partial final trace; completion covers the query window, not future arrivals.
diff --git a/worker/src/features/traceBatching/README.md b/worker/src/features/traceBatching/README.md
index a4d5655a1a..4753e34379 100644
--- a/worker/src/features/traceBatching/README.md
+++ b/worker/src/features/traceBatching/README.md
@@ -122,13 +122,62 @@ These distributions use the `langfuse.trace_batch` prefix:
| Metric | Sample |
| --- | --- |
| `transcript_assembly_duration_ms` | One trace's ordering and assembly time, excluding I/O conversion, stream waits and tokenization; `has_transcript:true\|false`. |
-| `transcript_message_tokens` | Sum of current-turn and history token estimates; zero when empty, omitted if either estimate is unavailable. Replaces full-transcript JSON tokenization under a different name. |
+| `transcript_json_characters` | UTF-16 length of `JSON.stringify(assembleTranscript(...))`, including thread/message wrappers and provenance; zero for a null transcript. Same admitted traces as the Topics length metrics. |
+| `transcript_json_tokens` | o200k estimate of that complete JSON string, tagged `tokenizer:o200k_base`; zero for a null transcript. Attempted on the same admitted traces as `topics_transcript_tokens`; unavailable estimates are omitted. |
+| `generic_transcript_characters` | UTF-16 length of the previous generic plain-text layout, rendered with the same Topics block caps and inclusions. Tool definitions or errors may still render when assembly returns null. |
+| `generic_transcript_tokens` | o200k estimate of that generic text, tagged `tokenizer:o200k_base`. |
+| `transcript_message_tokens` | Sum of current-turn and history message-projection token estimates; zero when empty, omitted if either estimate is unavailable. Distinct from full-transcript JSON. |
| `transcript_current_turn_tokens` | Token estimate of current-turn messages across all threads, using role and parts only; zero when empty. |
| `transcript_history_tokens` | Token estimate of history messages across all threads, using the same role/parts representation; zero when empty. |
| `transcript_content_characters` | Sum of JSON-serialized message-part lengths across history and current turn, in UTF-16 code units; excludes message wrappers and provenance. |
| `transcript_tool_response_characters` | The subset of content characters belonging to tool-role messages or unmatched tool-result parts; zero when absent. |
| `transcript_thread_count` | Number of assembled conversation threads, or zero for a null transcript. |
+| `transcript_observation_count` | Ordered, deduplicated observations passed to assembly and the Topics renderer. The `observation_count` span attribute is the raw row count before deduplication. |
+| `transcript_history_message_count`, `transcript_history_part_count` | Replayed messages and their normalized parts across all assembled threads. |
+| `transcript_current_turn_message_count`, `transcript_current_turn_part_count` | This-trace messages and their normalized parts across all assembled threads. |
+| `transcript_current_turn_tool_call_count`, `transcript_current_turn_tool_result_count` | Tool-call parts and tool-result parts in this trace; a tool-role part also counts as a result. |
| `transcript_assembly_phase_duration_ms` | Two non-overlapping samples per trace tagged `phase:normalization` or `phase:matching`. Normalization includes initial message-key construction and partitioning; matching covers remaining assembly work, including tool matching, deduplication, any rebuilt keys and finalization. Observation ordering is outside these phases but remains in total assembly time. |
+| `topics_transcript_characters` | UTF-16 length of the complete rendered Topics text, including labels, section headings and line breaks; admitted traces only. |
+| `topics_transcript_tokens` | o200k estimate of that same text, tagged `tokenizer:o200k_base`; admitted traces only. |
+| `transcript_comparison_render_duration_ms` | Time to serialize assembled JSON and render generic and Topics text, excluding tokenization. |
+| `transcript_comparison_tokenization_duration_ms` | Wall time for the three sequential JSON, generic and Topics token estimates, excluding the existing current-turn/history estimates. |
+| `topics_transcript_block_characters` | Present block content length tagged `block:user\|assistant\|system\|reasoning\|tool_calls\|tool_results\|tool_definitions\|errors\|run_io\|observations` and `stage:raw\|clipped`; absent blocks emit no sample. |
+| `topics_transcript_blocks_cut` | Number of content blocks cut by their per-block character caps. |
+| `topics_transcript_history_characters`, `topics_transcript_current_turn_characters`, `topics_transcript_history_share` | Rendered content-line characters from replayed input and this run, plus replayed input divided by their sum (0 when both are empty). This-run content includes fallback trace-level I/O, observation markers, and inline errors. |
+
+Topics measurement uses the existing assembled transcript and the inclusive
+Topics preset in `packages/shared/src/server/transcript/topics-renderer-config.ts`. It
+does not call a model or store the text. The preset includes all block types and
+history, caps fallback trace-level input and output at 10,000 characters each,
+and caps each system message at 600 characters. These are separate per-block
+limits, not a combined trace budget. The preset has no total token budget. It
+omits no middle lines. The rendered text has
+`<run_facts>`, optional `<tools>` and `<earlier_conversation source="replayed input">`,
+`<this_run>`, and `<end_of_run>` sections in that order. Observation markers show
+the Langfuse operation type and name in walk order; matched tool results already
+identify their operation. Trace input appears as the request when no current-run
+user message exists. If it differs from the rendered input messages, it appears
+as trace context alongside the user request, capped at the user block limit
+(2,000 characters in this preset). A trace output matching the last assistant
+message or tool
+result labels that message as final output; distinct application output appears
+once as `[final output]`. Thread segments follow observation
+order; the replayed prefix does not claim to come from a previous trace. Tool
+calls and results share a number, and observation errors appear after the last
+message emitted at or before their position in the observation walk. The facts
+line counts rendered user entries and tool calls across threads; repeated
+content in separate threads is not necessarily a distinct user turn. `raw` block
+characters are counted after media redaction and whitespace collapse but before
+a block cap; `clipped` counts the resulting content including any omission marker.
+Block values exclude
+role labels, section headings, run facts and line breaks; media placeholders
+can add characters to the complete text without adding to a block metric. The
+history share uses content lines including role labels, tool exchanges, fallback
+root I/O, observation markers and inline errors, excluding section headings and
+tool definitions. Keep
+numerator and denominator on the same basis when calculating shares. Ingestion
+applies `LANGFUSE_TRACE_BATCH_SAMPLING_RATE` by trace ID before the dispatcher
+and worker; every admitted trace receives Topics measurements.
Transcript token counts use the existing local worker-thread pool and bundled
tiktoken WASM, without a network or model API call. The `gpt-4o` configuration
@@ -139,8 +188,24 @@ billing counts or a model's full request framing.
Current turn and history use identical `{ messages: [{ role, parts }] }` JSON
framing, without observation provenance. Only nonempty partitions are tokenized,
at most twice per trace. Their sum is `transcript_message_tokens`; it is not
-directly comparable to the retired `transcript_tokens` full-transcript JSON metric.
-Empty transcripts report zero. Thread counts are numeric samples, never metric tags.
+directly comparable to the full assembled-transcript JSON or rendered text. The
+`transcript_json_*`, `generic_transcript_*`, and `topics_transcript_*` length
+distributions are attempted on the same admitted trace cohort and can be
+compared at p50/p90/p99 after checking their sample counts. The generic
+renderer preserves the previous plain-text layout under the same Topics
+per-block preset; it has no trace-root I/O or run-state sections. Empty
+transcripts have zero JSON length and tokens. Thread counts are numeric
+samples, never metric tags.
+
+To diagnose large Topics texts, compare `topics_transcript_tokens` with
+`transcript_observation_count`, the history/current-turn message and part counts,
+current-turn tool-call/result counts, `topics_transcript_history_share`, and
+raw/clipped characters by block type. Structure counts describe the assembled
+source, before the renderer's per-block character caps; they are not a count of
+visible lines. A last-N history policy can use each thread's
+`conversationHistory`, but a per-thread N would still grow with the number of
+threads. A future total history budget should account for all threads; tool
+loops should retain call/result pairs and errors when shortened.
For rough tool-response size share, divide `transcript_tool_response_characters`
by `transcript_content_characters` (when nonzero). Both sum serialized parts on
@@ -153,7 +218,19 @@ Rejected estimates increment `token_estimation_failed` and stop the remaining
estimates for that trace; successful earlier samples are retained. Unknown
estimates do not stop later estimates. The summed estimate is omitted unless
both partitions are known. Neither failure retries the batch.
-Only current-turn and history message projections are tokenized.
+Current-turn and history message projections are tokenized first. Each admitted
+trace then adds one full-JSON, one generic plain-text, and one Topics plain-text
+tokenization call.
+Missing or failed JSON estimates increment `transcript_json_token_estimation_unavailable`
+or `transcript_json_failed` without stopping later measurements. Generic text
+rendering or token failures increment `generic_transcript_failed`, while an
+unavailable token estimate increments
+`generic_transcript_token_estimation_unavailable`. These do not stop Topics.
+Topics rendering failures increment `topics_transcript_failed` and leave the
+batch successful. An
+unavailable Topics token estimate increments
+`topics_transcript_token_estimation_unavailable`; a rejected estimate increments
+`topics_transcript_failed`. Character metrics remain available in either case.
The worker submits one transcript for tokenization while streaming the next
trace's observations. Before submitting another transcript it awaits the previous
@@ -164,10 +241,10 @@ partial final trace. Assembly itself remains synchronous. `read_duration_ms`
includes all this processing.
Memory includes the current trace, the previous transcript being tokenized and
-stream buffers, multiplied by active batch jobs. A single trace remains unbounded.
-The transcript remains referenced until both partitions finish. Each message
-belongs to one partition; there is no additional full-transcript or tool-response
-tokenization pass.
+stream buffers, multiplied by active batch jobs. Each trace also retains its
+assembled JSON, generic text, and Topics text for sequential tokenizer calls.
+A single trace remains unbounded. Each message belongs to one JSON partition;
+there is no additional tool-response tokenization pass.
The default two-thread tokenizer pool is shared with ingestion; overlap hides
waiting time but does not remove CPU use or contention. Its existing 30-second
timeout rejects the promise without cancelling queued/running encoding, so the
@@ -190,19 +267,27 @@ Each completed trace emits a `trace-batch-transcript` child span under the batch
processing span. Its attributes include `langfuse.project.id`, `langfuse.trace.id`,
and `langfuse.trace.url` (a peek link using the configured product base URL).
Under `langfuse.trace_batch`, the span records `transcript_message_tokens`, `transcript_characters`,
+`transcript_json_characters`, `transcript_json_tokens`,
+`generic_transcript_characters`, `generic_transcript_tokens`,
+`topics_transcript_characters`, `topics_transcript_tokens`,
+`transcript_comparison_render_duration_ms`,
+`transcript_comparison_tokenization_duration_ms`,
`transcript_assembly_duration_ms`, `observation_count` (rows before observation
deduplication), `has_transcript`, `tokenizer`, and `experiment_id`.
It also records the token breakdown and content/tool-response character metrics,
`transcript_thread_count`,
and each phase as `transcript_assembly_<phase>_duration_ms`.
+It also records the remaining Topics metrics above. Block character attributes use
+`topics_transcript_block_<block>_<stage>_characters`. Topics character metrics
+are absent if rendering failed; the token metric can also be absent if its
+estimate failed.
No transcript content is attached, and IDs are not distribution metric tags.
-`transcript_characters` measures the complete transcript JSON's JavaScript string
-length (UTF-16 code units, including JSON syntax), or zero for a null transcript.
-This legacy span-only field uses a different basis from the content character
-metrics; use `transcript_content_characters` as the tool-response denominator.
-It is recorded before tokenization, so remains available if token estimation fails.
-Only recording spans serialize this extra temporary copy; it is not retained
-while tokenization runs or included in the assembly-duration measurement.
+`transcript_characters` is the legacy span-only name for the same value as
+`transcript_json_characters`. The full JSON includes syntax and provenance, so
+use `transcript_content_characters` as the tool-response denominator. JSON
+characters are recorded before tokenization and remain available if an estimate
+fails. The JSON string is retained only until its sequential token count settles;
+it is not included in the assembly-duration measurement.
The span stays open until token estimation settles, so its duration includes
tokenization and pool waits. Use the assembly-duration attribute for assembly
diff --git a/worker/src/features/traceBatching/traceBatchTranscript.ts b/worker/src/features/traceBatching/traceBatchTranscript.ts
index a0ebfbaede..babde8d7c4 100644
--- a/worker/src/features/traceBatching/traceBatchTranscript.ts
+++ b/worker/src/features/traceBatching/traceBatchTranscript.ts
@@ -8,6 +8,10 @@ import {
orderObservations,
recordDistribution,
recordIncrement,
+ renderGenericTranscript,
+ renderTranscript,
+ topicsTranscriptConfig,
+ transcriptBlockTypes,
type Transcript,
} from "@langfuse/shared/src/server";
import { env } from "../../env";
@@ -49,16 +53,35 @@ function recordTokens(
span.setAttribute(`langfuse.trace_batch.${metric}`, tokens);
}
-function recordCharacterCounts(transcript: Transcript | null, span: Span) {
+function recordContentAndStructureCounts(
+ transcript: Transcript | null,
+ observationCount: number,
+ span: Span,
+) {
let total = 0;
let toolResponses = 0;
+ let historyMessages = 0;
+ let historyParts = 0;
+ let currentTurnMessages = 0;
+ let currentTurnParts = 0;
+ let currentTurnToolCalls = 0;
+ let currentTurnToolResults = 0;
for (const thread of transcript?.threads ?? []) {
- for (const messages of [
- thread.conversationHistory,
- thread.currentTurn.messages,
- ]) {
+ for (const [section, messages] of [
+ ["history", thread.conversationHistory],
+ ["current_turn", thread.currentTurn.messages],
+ ] as const) {
+ if (section === "history") historyMessages += messages.length;
+ else currentTurnMessages += messages.length;
for (const message of messages) {
for (const part of message.parts) {
+ if (section === "history") historyParts++;
+ else {
+ currentTurnParts++;
+ if (part.type === "tool-call") currentTurnToolCalls++;
+ if (message.role === "tool" || part.type === "tool-result")
+ currentTurnToolResults++;
+ }
// Use the same serialized-part basis for numerator and denominator;
// exclude message wrappers and observation provenance from both.
const characters = JSON.stringify(part).length;
@@ -77,6 +100,18 @@ function recordCharacterCounts(transcript: Transcript | null, span: Span) {
recordDistribution(`langfuse.trace_batch.${metric}`, characters);
span.setAttribute(`langfuse.trace_batch.${metric}`, characters);
}
+ for (const [metric, count] of [
+ ["transcript_observation_count", observationCount],
+ ["transcript_history_message_count", historyMessages],
+ ["transcript_history_part_count", historyParts],
+ ["transcript_current_turn_message_count", currentTurnMessages],
+ ["transcript_current_turn_part_count", currentTurnParts],
+ ["transcript_current_turn_tool_call_count", currentTurnToolCalls],
+ ["transcript_current_turn_tool_result_count", currentTurnToolResults],
+ ] as const) {
+ recordDistribution(`langfuse.trace_batch.${metric}`, count);
+ span.setAttribute(`langfuse.trace_batch.${metric}`, count);
+ }
}
async function recordTokenEstimates(transcript: Transcript, span: Span) {
@@ -122,6 +157,133 @@ async function recordTokenEstimates(transcript: Transcript, span: Span) {
}
}
+function recordTopicsRendering(
+ transcript: Transcript | null,
+ observations: Observation[],
+ span: Span,
+): string | undefined {
+ try {
+ const { text, stats } = renderTranscript(
+ transcript,
+ observations,
+ topicsTranscriptConfig,
+ );
+ const metric = (name: string, value: number) => {
+ recordDistribution(`langfuse.trace_batch.${name}`, value);
+ span.setAttribute(`langfuse.trace_batch.${name}`, value);
+ };
+ metric("topics_transcript_characters", text.length);
+ metric("topics_transcript_blocks_cut", stats.blocksCut);
+ metric("topics_transcript_history_characters", stats.historyCharacters);
+ metric(
+ "topics_transcript_current_turn_characters",
+ stats.currentTurnCharacters,
+ );
+ const messageCharacters =
+ stats.historyCharacters + stats.currentTurnCharacters;
+ metric(
+ "topics_transcript_history_share",
+ messageCharacters ? stats.historyCharacters / messageCharacters : 0,
+ );
+ for (const block of transcriptBlockTypes) {
+ if (stats.blockCharacters[block].raw === 0) continue;
+ for (const stage of ["raw", "clipped"] as const) {
+ const characters = stats.blockCharacters[block][stage];
+ recordDistribution(
+ "langfuse.trace_batch.topics_transcript_block_characters",
+ characters,
+ { block, stage },
+ );
+ span.setAttribute(
+ `langfuse.trace_batch.topics_transcript_block_${block}_${stage}_characters`,
+ characters,
+ );
+ }
+ }
+ return text;
+ } catch {
+ recordIncrement("langfuse.trace_batch.topics_transcript_failed", 1);
+ span.setAttribute("langfuse.trace_batch.topics_transcript", "failed");
+ return undefined;
+ }
+}
+
+async function recordTopicsTokens(text: string, span: Span) {
+ const tokens = text
+ ? await tokenCountAsync({ model: TOKENIZER_MODEL, text })
+ : 0;
+ if (tokens === undefined) {
+ recordIncrement(
+ "langfuse.trace_batch.topics_transcript_token_estimation_unavailable",
+ 1,
+ );
+ span.setAttribute("langfuse.trace_batch.topics_transcript", "unavailable");
+ return;
+ }
+ recordDistribution("langfuse.trace_batch.topics_transcript_tokens", tokens, {
+ tokenizer: "o200k_base",
+ });
+ span.setAttribute("langfuse.trace_batch.topics_transcript_tokens", tokens);
+}
+
+async function recordTranscriptJsonTokens(text: string | null, span: Span) {
+ const tokens =
+ text === null ? 0 : await tokenCountAsync({ model: TOKENIZER_MODEL, text });
+ if (tokens === undefined) {
+ recordIncrement(
+ "langfuse.trace_batch.transcript_json_token_estimation_unavailable",
+ 1,
+ );
+ span.setAttribute("langfuse.trace_batch.transcript_json", "unavailable");
+ return;
+ }
+ recordDistribution("langfuse.trace_batch.transcript_json_tokens", tokens, {
+ tokenizer: "o200k_base",
+ });
+ span.setAttribute("langfuse.trace_batch.transcript_json_tokens", tokens);
+}
+
+async function recordGenericTranscriptTokens(text: string, span: Span) {
+ const tokens = text
+ ? await tokenCountAsync({ model: TOKENIZER_MODEL, text })
+ : 0;
+ if (tokens === undefined) {
+ recordIncrement(
+ "langfuse.trace_batch.generic_transcript_token_estimation_unavailable",
+ 1,
+ );
+ span.setAttribute("langfuse.trace_batch.generic_transcript", "unavailable");
+ return;
+ }
+ recordDistribution("langfuse.trace_batch.generic_transcript_tokens", tokens, {
+ tokenizer: "o200k_base",
+ });
+ span.setAttribute("langfuse.trace_batch.generic_transcript_tokens", tokens);
+}
+
+function recordGenericRendering(
+ transcript: Transcript | null,
+ observations: Observation[],
+ span: Span,
+): string | undefined {
+ try {
+ const text = renderGenericTranscript(transcript, observations);
+ recordDistribution(
+ "langfuse.trace_batch.generic_transcript_characters",
+ text.length,
+ );
+ span.setAttribute(
+ "langfuse.trace_batch.generic_transcript_characters",
+ text.length,
+ );
+ return text;
+ } catch {
+ recordIncrement("langfuse.trace_batch.generic_transcript_failed", 1);
+ span.setAttribute("langfuse.trace_batch.generic_transcript", "failed");
+ return undefined;
+ }
+}
+
export function recordTraceBatchTranscript(
observations: Observation[],
): Promise<void> {
@@ -149,12 +311,10 @@ export function recordTraceBatchTranscript(
}
const startedAt = performance.now();
let phaseTimings = { normalizationMs: 0, matchingMs: 0 };
- const transcript = assembleTranscript(
- orderObservations(observations),
- (timings) => {
- phaseTimings = timings;
- },
- );
+ const orderedObservations = orderObservations(observations);
+ const transcript = assembleTranscript(orderedObservations, (timings) => {
+ phaseTimings = timings;
+ });
const assemblyDurationMs = performance.now() - startedAt;
recordDistribution(
"langfuse.trace_batch.transcript_assembly_duration_ms",
@@ -189,29 +349,103 @@ export function recordTraceBatchTranscript(
"langfuse.trace_batch.transcript_thread_count",
threadCount,
);
- recordCharacterCounts(transcript, span);
- if (span.isRecording()) {
- // JSON string length in UTF-16 code units; do not retain the serialized copy.
+ recordContentAndStructureCounts(
+ transcript,
+ orderedObservations.length,
+ span,
+ );
+ const comparisonRenderStart = performance.now();
+ const transcriptJson =
+ transcript === null ? null : JSON.stringify(transcript);
+ const transcriptJsonCharacters = transcriptJson?.length ?? 0;
+ recordDistribution(
+ "langfuse.trace_batch.transcript_json_characters",
+ transcriptJsonCharacters,
+ );
+ span.setAttribute(
+ "langfuse.trace_batch.transcript_json_characters",
+ transcriptJsonCharacters,
+ );
+ if (span.isRecording())
span.setAttribute(
"langfuse.trace_batch.transcript_characters",
- transcript === null ? 0 : JSON.stringify(transcript).length,
+ transcriptJsonCharacters,
);
- }
+
+ const genericText = recordGenericRendering(
+ transcript,
+ orderedObservations,
+ span,
+ );
+
+ const topicsText = recordTopicsRendering(
+ transcript,
+ orderedObservations,
+ span,
+ );
+ const comparisonRenderDurationMs =
+ performance.now() - comparisonRenderStart;
+ recordDistribution(
+ "langfuse.trace_batch.transcript_comparison_render_duration_ms",
+ comparisonRenderDurationMs,
+ );
+ span.setAttribute(
+ "langfuse.trace_batch.transcript_comparison_render_duration_ms",
+ comparisonRenderDurationMs,
+ );
if (transcript === null) {
for (const metric of TOKEN_METRICS) recordTokens(span, metric, 0);
- span.end();
- return Promise.resolve();
}
- // Callbacks capture only the span, releasing observations while the next trace streams.
- return recordTokenEstimates(transcript, span)
- .catch(() => {
- // A missing experiment metric must not retry all reads in the batch.
- recordIncrement("langfuse.trace_batch.token_estimation_failed", 1);
- span.setAttribute("langfuse.trace_batch.token_estimation", "failed");
- })
- .finally(() => span.end());
+ // Text estimates run sequentially while the next trace streams.
+ return (async () => {
+ if (transcript !== null) {
+ try {
+ await recordTokenEstimates(transcript, span);
+ } catch {
+ // A missing experiment metric must not retry all reads in the batch.
+ recordIncrement("langfuse.trace_batch.token_estimation_failed", 1);
+ span.setAttribute("langfuse.trace_batch.token_estimation", "failed");
+ }
+ }
+ const comparisonTokenizationStart = performance.now();
+ try {
+ await recordTranscriptJsonTokens(transcriptJson, span);
+ } catch {
+ recordIncrement("langfuse.trace_batch.transcript_json_failed", 1);
+ span.setAttribute("langfuse.trace_batch.transcript_json", "failed");
+ }
+ if (genericText !== undefined) {
+ try {
+ await recordGenericTranscriptTokens(genericText, span);
+ } catch {
+ recordIncrement("langfuse.trace_batch.generic_transcript_failed", 1);
+ span.setAttribute(
+ "langfuse.trace_batch.generic_transcript",
+ "failed",
+ );
+ }
+ }
+ if (topicsText !== undefined) {
+ try {
+ await recordTopicsTokens(topicsText, span);
+ } catch {
+ recordIncrement("langfuse.trace_batch.topics_transcript_failed", 1);
+ span.setAttribute("langfuse.trace_batch.topics_transcript", "failed");
+ }
+ }
+ const comparisonTokenizationDurationMs =
+ performance.now() - comparisonTokenizationStart;
+ recordDistribution(
+ "langfuse.trace_batch.transcript_comparison_tokenization_duration_ms",
+ comparisonTokenizationDurationMs,
+ );
+ span.setAttribute(
+ "langfuse.trace_batch.transcript_comparison_tokenization_duration_ms",
+ comparisonTokenizationDurationMs,
+ );
+ })().finally(() => span.end());
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
diff --git a/worker/src/queues/__tests__/traceBatchQueue.test.ts b/worker/src/queues/__tests__/traceBatchQueue.test.ts
index 11ad2ba802..ae96d882a1 100644
--- a/worker/src/queues/__tests__/traceBatchQueue.test.ts
+++ b/worker/src/queues/__tests__/traceBatchQueue.test.ts
@@ -83,6 +83,145 @@ afterEach(() => {
});
describe("trace batch queue", () => {
+ it("measures rendered Topics text for an admitted trace", async () => {
+ const observations = [
+ convertObservation(
+ createObservation({
+ type: "GENERATION",
+ name: "explain",
+ trace_id: "topics-sample",
+ input: JSON.stringify([
+ { role: "user", content: "Explain the result" },
+ ]),
+ output: JSON.stringify({ role: "assistant", content: "The answer" }),
+ }),
+ ),
+ ];
+
+ await recordTraceBatchTranscript(observations);
+
+ expect(tokenCountAsync).toHaveBeenCalledTimes(4);
+ const baselineJson = vi.mocked(tokenCountAsync).mock.calls[1][0]
+ .text as string;
+ expect(
+ JSON.parse(baselineJson).threads[0].currentTurn.observations,
+ ).toEqual([expect.objectContaining({ traceId: "topics-sample" })]);
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.transcript_json_characters",
+ baselineJson.length,
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.transcript_json_tokens",
+ tokenCount({
+ model: vi.mocked(tokenCountAsync).mock.calls[1][0].model,
+ text: baselineJson,
+ }),
+ { tokenizer: "o200k_base" },
+ );
+ const genericText = vi.mocked(tokenCountAsync).mock.calls[2][0].text;
+ expect(genericText).toBe(
+ "[user] Explain the result\n[assistant] The answer",
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.generic_transcript_characters",
+ genericText.length,
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.generic_transcript_tokens",
+ tokenCount({
+ model: vi.mocked(tokenCountAsync).mock.calls[2][0].model,
+ text: genericText,
+ }),
+ { tokenizer: "o200k_base" },
+ );
+ const renderedText = vi.mocked(tokenCountAsync).mock.calls[3][0].text;
+ expect(renderedText).toBe(
+ [
+ "<run_facts>",
+ "threads: 1 · rendered user entries: 1 · rendered tool calls: 0 · error signals: 0 · omitted lines: 0",
+ "</run_facts>",
+ "<this_run>",
+ "[generation] explain",
+ "[user · request] Explain the result",
+ "[assistant · final output] The answer",
+ "</this_run>",
+ "<end_of_run>",
+ "last action: assistant text",
+ "final output: assistant",
+ "</end_of_run>",
+ ].join("\n"),
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.topics_transcript_tokens",
+ tokenCount({
+ model: vi.mocked(tokenCountAsync).mock.calls[3][0].model,
+ text: renderedText,
+ }),
+ { tokenizer: "o200k_base" },
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.topics_transcript_block_characters",
+ "Explain the result".length,
+ { block: "user", stage: "raw" },
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.topics_transcript_block_characters",
+ "explain".length,
+ { block: "observations", stage: "raw" },
+ );
+ expect(exporter.getFinishedSpans()[0].attributes).toMatchObject({
+ "langfuse.trace_batch.topics_transcript_characters": renderedText.length,
+ "langfuse.trace_batch.topics_transcript_blocks_cut": 0,
+ "langfuse.trace_batch.topics_transcript_history_share": 0,
+ "langfuse.trace_batch.topics_transcript_tokens": expect.any(Number),
+ "langfuse.trace_batch.transcript_observation_count": 1,
+ "langfuse.trace_batch.transcript_history_message_count": 0,
+ "langfuse.trace_batch.transcript_current_turn_message_count": 2,
+ "langfuse.trace_batch.transcript_current_turn_part_count": 2,
+ });
+ });
+
+ it("keeps the batch successful when Topics token estimation fails", async () => {
+ vi.mocked(tokenCountAsync)
+ .mockResolvedValueOnce(10)
+ .mockResolvedValueOnce(20)
+ .mockResolvedValueOnce(30)
+ .mockRejectedValueOnce(new Error("tokenizer unavailable"));
+
+ await expect(
+ recordTraceBatchTranscript([
+ convertObservation(
+ createObservation({
+ type: "GENERATION",
+ trace_id: "topics-failure",
+ input: JSON.stringify([{ role: "user", content: "Question" }]),
+ output: JSON.stringify({ role: "assistant", content: "Answer" }),
+ }),
+ ),
+ ]),
+ ).resolves.toBeUndefined();
+
+ expect(recordIncrement).toHaveBeenCalledWith(
+ "langfuse.trace_batch.topics_transcript_failed",
+ 1,
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.topics_transcript_characters",
+ expect.any(Number),
+ );
+ expect(recordDistribution).not.toHaveBeenCalledWith(
+ "langfuse.trace_batch.topics_transcript_tokens",
+ expect.any(Number),
+ expect.anything(),
+ );
+ expect(exporter.getFinishedSpans()[0].attributes).toMatchObject({
+ "langfuse.trace_batch.topics_transcript": "failed",
+ "langfuse.trace_batch.transcript_message_tokens": 10,
+ "langfuse.trace_batch.transcript_json_tokens": 20,
+ "langfuse.trace_batch.generic_transcript_tokens": 30,
+ });
+ });
+
it("measures history, current turn, threads and deduplicated tool responses", async () => {
const history = [
{ role: "user", content: "earlier question" },
@@ -140,10 +279,10 @@ describe("trace batch queue", () => {
const estimates = vi
.mocked(tokenCountAsync)
.mock.calls.map(([params]) => params);
- expect(estimates).toHaveLength(2);
- const [current, historyOnly] = estimates.map(({ text }) =>
- JSON.stringify(text),
- );
+ expect(estimates).toHaveLength(5);
+ const [current, historyOnly] = estimates
+ .slice(0, 2)
+ .map(({ text }) => JSON.stringify(text));
expect(current.split("tool payload")).toHaveLength(2);
expect(current).not.toContain("earlier question");
expect(current).toContain("current question");
@@ -154,6 +293,26 @@ describe("trace batch queue", () => {
"langfuse.trace_batch.transcript_thread_count",
2,
);
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.transcript_observation_count",
+ 4,
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.transcript_history_message_count",
+ 2,
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.transcript_history_part_count",
+ 2,
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.transcript_current_turn_tool_call_count",
+ 1,
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.trace_batch.transcript_current_turn_tool_result_count",
+ 1,
+ );
for (const [index, suffix] of [
"current_turn_tokens",
"history_tokens",
@@ -224,7 +383,7 @@ describe("trace batch queue", () => {
}),
),
]);
- expect(tokenCountAsync).toHaveBeenCalledTimes(1);
+ expect(tokenCountAsync).toHaveBeenCalledTimes(4);
const toolCharacters = JSON.stringify({
type: "tool-result",
toolCallId: "unmatched",
@@ -306,6 +465,9 @@ describe("trace batch queue", () => {
.mockImplementationOnce(
() => new Promise<number>((resolve) => (resolveFirst = resolve)),
)
+ .mockImplementationOnce(() => Promise.resolve(0))
+ .mockImplementationOnce(() => Promise.resolve(0))
+ .mockImplementationOnce(() => Promise.resolve(0))
.mockImplementationOnce(() =>
cleaningUp
? Promise.resolve(0)
@@ -374,7 +536,7 @@ describe("trace batch queue", () => {
expect(exporter.getFinishedSpans()).toHaveLength(0);
resolveFirst(100);
await vi.waitFor(() => expect(reachedEnd).toBe(true));
- expect(tokenCountAsync).toHaveBeenCalledTimes(2);
+ expect(tokenCountAsync).toHaveBeenCalledTimes(5);
expect(settled).toBe(false);
// An unavailable token estimate must not retry a whole batch or mask
// the original stream failure; its promise is drained before returning.
@@ -423,7 +585,7 @@ describe("trace batch queue", () => {
}
},
);
- it("assembles each tenant's trace at the boundary and EOF, tokenizing only the transcript", async () => {
+ it("assembles each tenant's trace at the boundary and EOF", async () => {
const userMessage = { role: "user", content: "first question" };
const answer = { role: "assistant", content: "first answer" };
const row = {
@@ -480,7 +642,7 @@ describe("trace batch queue", () => {
} as Job<TQueueJobTypes[QueueName.TraceBatch]>;
await traceBatchQueueProcessor(job, undefined);
const estimates = vi.mocked(tokenCountAsync).mock.calls;
- expect(estimates).toHaveLength(1);
+ expect(estimates).toHaveLength(5);
const serializedTranscript = JSON.stringify(estimates[0][0].text);
for (const content of [
"first question",