Skip to content

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

fix: serialize session observation metadata safely (#15727)

Valery Meleshkin549e6a91040e
diff --git a/web/src/__tests__/server/sessions-observations-io-cap.servertest.ts b/web/src/__tests__/server/sessions-observations-io-cap.servertest.ts
index 784db16755..7459c47e14 100644
--- a/web/src/__tests__/server/sessions-observations-io-cap.servertest.ts
+++ b/web/src/__tests__/server/sessions-observations-io-cap.servertest.ts
@@ -20,6 +20,7 @@ import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { createEvent, createEventsCh } from "@langfuse/shared/src/server";
import waitForExpect from "wait-for-expect";
import { randomUUID } from "crypto";
+import superjson from "superjson";
// The events_full table is created only by the ClickHouse dev-tables setup,
// which runs in the default deploy-mode where .env.dev.example enables the v4
@@ -45,6 +46,8 @@ const PER_TRACE_LIMIT = 50;
// PER_TRACE_LIMIT real rows means the trace has more than the card shows.
const hasMore = (observations: { id: string }[], traceId: string) =>
observations.filter((o) => o.id !== `t-${traceId}`).length > PER_TRACE_LIMIT;
+const parseMetadata = (metadata: string | null) =>
+ JSON.parse(metadata ?? "{}") as Record<string, unknown>;
maybe("sessions observations bounded I/O (events)", () => {
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -194,11 +197,46 @@ maybe("sessions observations bounded I/O (events)", () => {
const observation = observations[0];
expect(observation.metadataTruncated).toBe(true);
- const metadata = observation.metadata as Record<string, unknown>;
+ const metadata = parseMetadata(observation.metadata);
expect(String(metadata.big).length).toBe(PREVIEW_LIMIT);
expect(metadata.small).toBe("tiny");
});
+ it("serializes metadata containing a constructor key", async () => {
+ const { sessionId, traceId, baseTime } = await seedObservations([
+ {
+ input: "x".repeat(INLINE_LIMIT + 1),
+ metadataNames: ["constructor"],
+ metadataValues: ["test"],
+ },
+ ]);
+
+ const observations = await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ // createCaller bypasses the tRPC transformer, so exercise the production
+ // response serialization boundary explicitly.
+ expect(() => superjson.serialize(observations)).not.toThrow();
+ expect(observations[0]?.metadata).toBe(
+ JSON.stringify({ constructor: "test" }),
+ );
+
+ const full = await caller.sessions.observationFullIOFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ observationId: `${traceId}-o0`,
+ startTime: new Date(baseTime),
+ });
+
+ expect(() => superjson.serialize(full)).not.toThrow();
+ expect(full.metadata).toBe(JSON.stringify({ constructor: "test" }));
+ });
+
it("caps observations per card and signals more exist via the +1 sentinel", async () => {
const { sessionId, traceId } = await seedObservations(
Array.from({ length: PER_TRACE_LIMIT + 2 }, () => ({})),
@@ -375,9 +413,7 @@ maybe("sessions observations bounded I/O (events)", () => {
});
const observation = observations[0];
- expect((observation.metadata as Record<string, unknown>).k).toBe(
- "small-winner",
- );
+ expect(parseMetadata(observation.metadata).k).toBe("small-winner");
expect(observation.metadataTruncated).toBe(false);
});
@@ -404,13 +440,11 @@ maybe("sessions observations bounded I/O (events)", () => {
const first = observations[0];
expect(first.metadataTruncated).toBe(false);
- expect(
- String((first.metadata as Record<string, unknown>).payload).length,
- ).toBe(290_000);
+ expect(String(parseMetadata(first.metadata).payload).length).toBe(290_000);
const last = observations[observations.length - 1];
expect(last.metadataTruncated).toBe(true);
- expect(last.metadata).toEqual({});
+ expect(last.metadata).toBe("{}");
});
it("serves full I/O for one observation via observationFullIOFromEvents, scoped to the session", async () => {
diff --git a/web/src/components/session/SessionObservationIO.clienttest.tsx b/web/src/components/session/SessionObservationIO.clienttest.tsx
index 243ef78595..c19ab6d444 100644
--- a/web/src/components/session/SessionObservationIO.clienttest.tsx
+++ b/web/src/components/session/SessionObservationIO.clienttest.tsx
@@ -45,7 +45,7 @@ const baseObservation = {
startTime: new Date("2026-07-15T10:00:00Z"),
input: '{"messages":[{"role":"user","content":"hi"}]}',
output: "hello",
- metadata: {},
+ metadata: "{}",
inputLength: 45,
outputLength: 5,
inputTruncated: false,
@@ -119,7 +119,7 @@ describe("SessionObservationIO", () => {
id: "obs-1",
input: "full-input",
output: "full-output",
- metadata: {},
+ metadata: JSON.stringify({ constructor: "test" }),
});
renderComponent({
...baseObservation,
@@ -139,7 +139,10 @@ describe("SessionObservationIO", () => {
expect(downloadJsonFile).toHaveBeenCalledWith(
expect.objectContaining({
fileName: "observation-obs-1.json",
- data: expect.objectContaining({ input: "full-input" }),
+ data: expect.objectContaining({
+ input: "full-input",
+ metadata: { constructor: "test" },
+ }),
}),
);
});
@@ -148,7 +151,7 @@ describe("SessionObservationIO", () => {
renderComponent({
...baseObservation,
inputTruncated: true,
- metadata: { key: "value" },
+ metadata: JSON.stringify({ key: "value" }),
metadataLength: 15,
metadataTruncated: false,
} as SessionTraceObservation);
diff --git a/web/src/components/session/SessionObservationIO.tsx b/web/src/components/session/SessionObservationIO.tsx
index ff367f1b89..9d11f7ad93 100644
--- a/web/src/components/session/SessionObservationIO.tsx
+++ b/web/src/components/session/SessionObservationIO.tsx
@@ -12,6 +12,7 @@ import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { compactNumberFormatter } from "@/src/utils/numbers";
import { type ChatMLParserResult } from "@/src/components/trace/components/IOPreview/hooks/useChatMLParser";
+import { parseJsonIfString } from "@langfuse/shared";
export type SessionTraceObservation =
RouterOutputs["sessions"]["observationsForTraceFromEvents"][number];
@@ -124,15 +125,16 @@ export const SessionObservationIO = ({
observationId: observation.id,
startTime: observation.startTime,
});
- // I/O stays embedded as raw strings: parsing multi-megabyte JSON just
- // to pretty-print it risks the same freeze this card exists to avoid.
+ // I/O stays raw. Metadata is stringified only to cross tRPC safely; parse
+ // that server-produced envelope once so the JSON download keeps its
+ // original object shape. The parsed value is never rendered or merged.
downloadJsonFile({
data: {
observationId: observation.id,
traceId,
input: full.input,
output: full.output,
- metadata: full.metadata,
+ metadata: parseJsonIfString(full.metadata),
},
fileName: `observation-${observation.id}.json`,
});
@@ -194,6 +196,18 @@ export const SessionObservationIO = ({
);
}
+ // Metadata uses the same stringified tRPC contract as trace/observation
+ // detail. Prefer the value already parsed by TraceEventsRow; the serialized
+ // value remains a safe bounded fallback when this component is used alone.
+ const metadataForDisplay = parsedMetadata ?? observation.metadata;
+ const hasMetadataForDisplay =
+ metadataForDisplay !== null &&
+ metadataForDisplay !== undefined &&
+ metadataForDisplay !== "" &&
+ metadataForDisplay !== "{}" &&
+ (typeof metadataForDisplay !== "object" ||
+ Object.keys(metadataForDisplay).length > 0);
+
return (
<div className="flex flex-col gap-2 rounded-md border border-dashed p-3">
<p className="text-muted-foreground text-xs">
@@ -214,16 +228,14 @@ export const SessionObservationIO = ({
/>
{/* Metadata stays visible when I/O is truncated — it shipped with the
observation and was always shown alongside I/O before the cap. */}
- {observation.metadata !== null &&
- typeof observation.metadata === "object" &&
- Object.keys(observation.metadata).length > 0 && (
- <TruncatedIOSection
- label="Metadata"
- value={observation.metadata}
- fullLength={observation.metadataLength}
- truncated={observation.metadataTruncated}
- />
- )}
+ {hasMetadataForDisplay && (
+ <TruncatedIOSection
+ label="Metadata"
+ value={metadataForDisplay}
+ fullLength={observation.metadataLength}
+ truncated={observation.metadataTruncated}
+ />
+ )}
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" onClick={openInTraceView}>
<ExternalLinkIcon className="mr-1 h-3.5 w-3.5" />
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index dfdea12e0d..1359afe250 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -53,7 +53,10 @@ import {
} from "@langfuse/shared/src/server";
import chunk from "lodash/chunk";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
-import { toDomainArrayWithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
+import {
+ toDomainArrayWithStringifiedMetadata,
+ toDomainWithStringifiedMetadata,
+} from "@/src/utils/clientSideDomainTypes";
const SessionCountOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -966,7 +969,7 @@ export const sessionRouter = createTRPCRouter({
};
});
- return observations;
+ return toDomainArrayWithStringifiedMetadata(observations);
}),
/**
* Full raw I/O for one observation, for the session card's download
@@ -1001,7 +1004,7 @@ export const sessionRouter = createTRPCRouter({
});
}
- return observation;
+ return toDomainWithStringifiedMetadata(observation);
}),
bookmark: protectedProjectProcedure
.input(