Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(trace): gate multi-MB single strings in the Pretty IO view (LFE-10991) (#15159)

Nikita Kabardine45abdd9ccc9
diff --git a/web/src/components/ui/LargeStringFallback.tsx b/web/src/components/ui/LargeStringFallback.tsx
new file mode 100644
index 0000000000..cc8a75ce47
--- /dev/null
+++ b/web/src/components/ui/LargeStringFallback.tsx
@@ -0,0 +1,94 @@
+import { useMemo } from "react";
+import { Download } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import { compactNumberFormatter } from "@/src/utils/numbers";
+import { LARGE_STRING_PREVIEW_CHARS } from "@/src/components/ui/largeStringGate";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";
+
+/**
+ * Head slice bounded to `maxChars` UTF-16 units, backed off by one unit if the
+ * boundary would split a surrogate pair (which renders as a stray U+FFFD).
+ * O(1) β€” never materializes the full multi-MB string.
+ */
+function codePointSafeSlice(value: string, maxChars: number): string {
+ if (value.length <= maxChars) return value;
+ const lastUnit = value.charCodeAt(maxChars - 1);
+ const isHighSurrogate = lastUnit >= 0xd800 && lastUnit <= 0xdbff;
+ return value.slice(0, isHighSurrogate ? maxChars - 1 : maxChars);
+}
+
+/**
+ * Bounded fallback for a single top-level string value too large to render in
+ * the Pretty / JSON viewers (LFE-10991, part of the LFE-10152 large-traces
+ * work). Instead of running several full-length parse/decode/stringify passes
+ * on the main thread and mounting the unvirtualized JSON tree with the whole
+ * multi-MB string β€” which blocks the tab and inflates memory β€” it shows a
+ * bounded preview head plus a raw download for the full value. The header's
+ * copy button (in PrettyJsonView) still copies the whole string.
+ *
+ * This never re-serializes the payload: the value is already a plain string,
+ * reused as-is for the preview slice and the download.
+ */
+export function LargeStringFallback({
+ title,
+ value,
+}: {
+ title?: string;
+ value: string;
+}) {
+ const capture = usePostHogClientCapture();
+
+ const previewText = useMemo(() => {
+ // Decode \uXXXX escapes so the preview matches the normal viewer β€” but only
+ // over the bounded slice, never the full multi-MB value (keeps the perf
+ // win). The download stays raw/faithful to the stored value.
+ const sliced = codePointSafeSlice(value, LARGE_STRING_PREVIEW_CHARS);
+ return decodeUnicodeInJson(sliced) as string;
+ }, [value]);
+
+ const onDownload = () => {
+ capture("trace_detail:large_string_field_download");
+ // Raw .txt: the source value is already a plain string, so it must never be
+ // JSON-quote/escape-wrapped.
+ const base = (title ?? "value").toLowerCase().replace(/\s+/g, "-");
+ downloadTextFile(value, `${base}.txt`, "text/plain; charset=utf-8");
+ };
+
+ return (
+ <div className="io-message-content">
+ <div className="my-2 flex flex-col gap-2 rounded-sm border border-dashed p-3">
+ <div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
+ {title ? (
+ <span className="text-foreground font-medium">{title}</span>
+ ) : null}
+ <span>
+ Large string β€” {compactNumberFormatter(value.length, 1)} characters,
+ truncated to keep the tab responsive
+ </span>
+ </div>
+ <pre className="bg-muted/50 max-h-40 overflow-hidden rounded-md border p-2 font-mono text-xs break-all whitespace-pre-wrap">
+ {previewText}
+ </pre>
+ <div>
+ <Button variant="outline" size="sm" onClick={onDownload}>
+ <Download className="mr-1 h-3.5 w-3.5" />
+ Download full value
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function downloadTextFile(content: string, fileName: string, mimeType: string) {
+ const blob = new Blob([content], { type: mimeType });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = fileName;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
diff --git a/web/src/components/ui/PrettyJsonView.gate.clienttest.tsx b/web/src/components/ui/PrettyJsonView.gate.clienttest.tsx
new file mode 100644
index 0000000000..8546ff2457
--- /dev/null
+++ b/web/src/components/ui/PrettyJsonView.gate.clienttest.tsx
@@ -0,0 +1,99 @@
+/**
+ * PrettyJsonView must short-circuit a multi-MB top-level string to the bounded
+ * LargeStringFallback and NEVER mount the unvirtualized JSON viewer (JSONView /
+ * react18-json-view) or the lazy table with it (LFE-10991). These tests pin
+ * that branch selection: over-limit strings render the fallback only, while a
+ * normal small string still mounts the viewer.
+ */
+import { render, screen } from "@testing-library/react";
+import type * as CodeJsonViewerModule from "@/src/components/ui/CodeJsonViewer";
+
+// LargeStringFallback's only provider-bound dependency β€” stub it so the test
+// needs no PostHogProvider.
+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
+ usePostHogClientCapture: () => vi.fn(),
+}));
+
+// JSONView is the unvirtualized react18-json-view path we must NOT reach for an
+// over-limit string. Stub only it (keep the module's other exports) so its
+// mounting is observable by test id.
+vi.mock("@/src/components/ui/CodeJsonViewer", async (importOriginal) => {
+ const actual = await importOriginal<typeof CodeJsonViewerModule>();
+ return {
+ ...actual,
+ JSONView: (props: { title?: string }) => (
+ <div data-testid="json-view">{props.title}</div>
+ ),
+ };
+});
+
+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
+import { LARGE_STRING_RENDER_CHAR_LIMIT } from "@/src/components/ui/largeStringGate";
+
+describe("PrettyJsonView large-string gate (LFE-10991)", () => {
+ it("renders the bounded fallback and mounts neither the JSON viewer nor the table for an over-limit string", () => {
+ const huge = "x".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1);
+ const { container } = render(<PrettyJsonView json={huge} title="Input" />);
+
+ // Bounded fallback + download affordance are shown...
+ expect(screen.getByText(/Large string β€”/i)).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /Download full value/i }),
+ ).toBeInTheDocument();
+
+ // ...and the unvirtualized viewer + lazy table were never mounted.
+ expect(screen.queryByTestId("json-view")).not.toBeInTheDocument();
+ expect(container.querySelector("table")).toBeNull();
+
+ // The multi-MB string is not dumped into the DOM (only the bounded preview).
+ expect(container.textContent?.length ?? 0).toBeLessThan(10_000);
+ });
+
+ it("renders normally (JSON viewer mounted, no fallback) for small I/O", () => {
+ render(<PrettyJsonView json={{ foo: "bar", n: 1 }} title="Input" />);
+
+ expect(screen.queryByText(/Large string β€”/i)).not.toBeInTheDocument();
+ expect(screen.getByTestId("json-view")).toBeInTheDocument();
+ });
+
+ it("shows the loading/parsing state (not the fallback) while a parse is in-flight, even if the raw json string is over the limit", () => {
+ // The JSON tab passes the raw `json` (a stringified payload) alongside a
+ // not-yet-ready `parsedJson` during the worker-parse window. Its JSON-quoted
+ // form can itself exceed the limit β€” but gating on it would flash the
+ // fallback and offer a quoted-form download before the parse settles.
+ const hugeRawJson = JSON.stringify({
+ x: "y".repeat(LARGE_STRING_RENDER_CHAR_LIMIT),
+ });
+ expect(hugeRawJson.length).toBeGreaterThan(LARGE_STRING_RENDER_CHAR_LIMIT);
+
+ render(
+ <PrettyJsonView
+ json={hugeRawJson}
+ parsedJson={undefined}
+ isParsing
+ title="Input"
+ />,
+ );
+
+ // No fallback, no quoted-form download β€” the normal parsing state shows.
+ expect(screen.queryByText(/Large string β€”/i)).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Download full value/i }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText(/Parsing in background/i)).toBeInTheDocument();
+ });
+
+ it("still gates a genuinely huge SETTLED top-level string (parse finished)", () => {
+ const hugePlainString = "z".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1);
+ render(
+ <PrettyJsonView
+ json="ignored-raw"
+ parsedJson={hugePlainString}
+ title="Input"
+ />,
+ );
+
+ expect(screen.getByText(/Large string β€”/i)).toBeInTheDocument();
+ expect(screen.queryByTestId("json-view")).not.toBeInTheDocument();
+ });
+});
diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsx
index 543f6e8718..d76c344a02 100644
--- a/web/src/components/ui/PrettyJsonView.tsx
+++ b/web/src/components/ui/PrettyJsonView.tsx
@@ -60,6 +60,8 @@ import {
type MetadataFilterActions,
} from "@/src/components/table/ValueCell";
import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";
+import { isLargeRenderString } from "@/src/components/ui/largeStringGate";
+import { LargeStringFallback } from "@/src/components/ui/LargeStringFallback";
// Constants for table layout
const INDENTATION_PER_LEVEL = 16;
@@ -791,8 +793,37 @@ export function PrettyJsonView(props: {
since the title can carry a message `name` instead of the role). */
isSystemPrompt?: boolean;
}) {
+ // Large plain-string gate (LFE-10991): a multi-MB top-level string skips
+ // deepParseJson's object-only `maxSize` guard, so without this it would run
+ // several full-length main-thread passes (parse, the markdown-probe
+ // `JSON.stringify`, unicode decode β€” some of them twice, including inside the
+ // always-mounted hidden JSON viewer) and mount the unvirtualized react18-json
+ // tree with the whole string, blocking the tab and inflating memory. The body
+ // renders a bounded preview + download instead.
+ //
+ // Gate on the SETTLED value only. During an async worker parse the parsed
+ // value is not ready (`parsedJson === undefined`, `isParsing` true) and the
+ // raw `json` may be a *stringified* payload whose JSON-quoted form is itself
+ // >2M chars (e.g. the JSON tab passes raw `json` alongside a not-yet-ready
+ // `parsedJson`). Gating on that raw form would flash the fallback β€” and offer
+ // a quoted-form download β€” before the parse settles to the real value. The
+ // unvirtualized render we protect against does not run during parse anyway,
+ // so fall through to the normal loading/parsing state in that window.
+ const largeStringValue = useMemo(() => {
+ if (props.isParsing) return null;
+ const settled =
+ props.parsedJson !== undefined ? props.parsedJson : props.json;
+ return isLargeRenderString(settled) ? settled : null;
+ }, [props.parsedJson, props.json, props.isParsing]);
+
// Use pre-parsed data if available, otherwise parse on-demand
const parsedJson = useMemo(() => {
+ // Skip all parse/decode work on very large plain strings (see gate above);
+ // the raw string is rendered through the bounded fallback, not decoded.
+ if (largeStringValue !== null) {
+ return largeStringValue;
+ }
+
// If pre-parsed data is provided, use it directly (skip parsing)
if (props.parsedJson !== undefined) {
return decodeUnicodeInJson(props.parsedJson);
@@ -817,7 +848,7 @@ export function PrettyJsonView(props: {
// Decode \uXXXX escapes so Python SDK (ensure_ascii=True) traces display
// non-ASCII characters correctly in the trace detail view.
return decodeUnicodeInJson(result);
- }, [props.json, props.parsedJson, props.isParsing]);
+ }, [props.json, props.parsedJson, props.isParsing, largeStringValue]);
// JSONView internally calls deepParseJson (with maxDepth:3) which mutates
// nested string fields in place. Because baseTableData[].rawChildData holds
@@ -877,13 +908,19 @@ export function PrettyJsonView(props: {
const isChatML = useMemo(() => isChatMLFormat(parsedJson), [parsedJson]);
const { isMarkdown, content: markdownContent } = useMemo(
- () => isMarkdownContent(parsedJson),
- [parsedJson],
+ // Skip the markdown probe for gated large strings: isMarkdownContent runs
+ // `JSON.stringify` on the whole value, an O(n) pass over the multi-MB string.
+ () =>
+ largeStringValue !== null
+ ? { isMarkdown: false as const, content: undefined }
+ : isMarkdownContent(parsedJson),
+ [parsedJson, largeStringValue],
);
const baseTableData = useMemo(() => {
try {
if (
+ largeStringValue === null &&
actualCurrentView === "pretty" &&
parsedJson !== null &&
parsedJson !== undefined &&
@@ -948,7 +985,7 @@ export function PrettyJsonView(props: {
console.error("Error transforming JSON to table data:", error);
return [];
}
- }, [parsedJson, isChatML, isMarkdown, actualCurrentView]);
+ }, [parsedJson, isChatML, isMarkdown, actualCurrentView, largeStringValue]);
// state precedence: external state before smart expansion
const finalExpansionState: ExpandedState = useMemo(() => {
@@ -1217,7 +1254,11 @@ export function PrettyJsonView(props: {
}),
);
const shouldUseTableView =
- isPrettyView && !isChatML && !isMarkdown && !emptyValueDisplay;
+ largeStringValue === null &&
+ isPrettyView &&
+ !isChatML &&
+ !isMarkdown &&
+ !emptyValueDisplay;
const getBackgroundColorClass = () =>
cn(
@@ -1229,7 +1270,9 @@ export function PrettyJsonView(props: {
const body = (
<>
- {props.isLoading || props.isParsing ? (
+ {largeStringValue !== null ? (
+ <LargeStringFallback title={props.title} value={largeStringValue} />
+ ) : props.isLoading || props.isParsing ? (
<div className="io-message-content">
<div
className={cn(
@@ -1423,7 +1466,7 @@ export function PrettyJsonView(props: {
)}
</Button>
)}
- {!shouldUseTableView && !isMarkdownMode && (
+ {!shouldUseTableView && !isMarkdownMode && !largeStringValue && (
<Button
variant="ghost"
size="icon-xs"
diff --git a/web/src/components/ui/largeStringGate.clienttest.ts b/web/src/components/ui/largeStringGate.clienttest.ts
new file mode 100644
index 0000000000..b2c3bbe86c
--- /dev/null
+++ b/web/src/components/ui/largeStringGate.clienttest.ts
@@ -0,0 +1,38 @@
+import {
+ LARGE_STRING_RENDER_CHAR_LIMIT,
+ isLargeRenderString,
+} from "@/src/components/ui/largeStringGate";
+
+describe("isLargeRenderString", () => {
+ it("returns false for typical, KB-scale strings", () => {
+ expect(isLargeRenderString("")).toBe(false);
+ expect(isLargeRenderString("hello world")).toBe(false);
+ expect(isLargeRenderString("a".repeat(100_000))).toBe(false);
+ expect(isLargeRenderString("a".repeat(500_000))).toBe(false);
+ });
+
+ it("is bounded exactly at the limit (inclusive) and fires just above it", () => {
+ // At the limit: still rendered normally (not gated).
+ expect(
+ isLargeRenderString("a".repeat(LARGE_STRING_RENDER_CHAR_LIMIT)),
+ ).toBe(false);
+ // One char over the limit: gated.
+ expect(
+ isLargeRenderString("a".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1)),
+ ).toBe(true);
+ });
+
+ it("gates multi-megabyte plain strings", () => {
+ expect(isLargeRenderString("x".repeat(5_000_000))).toBe(true);
+ });
+
+ it("only gates strings β€” objects/arrays keep their own size guards", () => {
+ expect(isLargeRenderString(null)).toBe(false);
+ expect(isLargeRenderString(undefined)).toBe(false);
+ expect(isLargeRenderString(42)).toBe(false);
+ expect(isLargeRenderString(true)).toBe(false);
+ // A huge object is handled by deepParseJson's object maxSize guard, not here.
+ expect(isLargeRenderString({ a: "x".repeat(5_000_000) })).toBe(false);
+ expect(isLargeRenderString(["x".repeat(5_000_000)])).toBe(false);
+ });
+});
diff --git a/web/src/components/ui/largeStringGate.ts b/web/src/components/ui/largeStringGate.ts
new file mode 100644
index 0000000000..bcba66d046
--- /dev/null
+++ b/web/src/components/ui/largeStringGate.ts
@@ -0,0 +1,45 @@
+/**
+ * Size gate for very large *plain string* values in the IO render path
+ * (LFE-10991, part of the LFE-10152 large-traces work).
+ *
+ * The parse guards that protect structured JSON only fire for object payloads:
+ * `deepParseJson`'s `maxSize` check is `if (typeof json === "object")` (see
+ * packages/shared/src/utils/json.ts), and the Pretty view's 500K / 300K limits
+ * feed into it. A top-level *string* skips the size check entirely, so a
+ * multi-megabyte single string flows unbounded into the Pretty view's render
+ * machinery: several full-length O(n) main-thread passes (deepParseJson, the
+ * markdown probe's `JSON.stringify`, and `decodeUnicodeInJson` β€” each run more
+ * than once, including inside the always-mounted hidden JSON viewer) plus an
+ * unvirtualized react18-json-view that holds the whole string. On a multi-MB
+ * string this blocks the tab and inflates memory.
+ *
+ * This gate lets `PrettyJsonView` short-circuit such strings to a bounded
+ * preview + download, matching the JSON-tab field size gate (LFE-10989).
+ */
+
+/**
+ * Character ceiling for rendering a single top-level string through the Pretty
+ * / JSON viewers. Mirrors the JSON view's field limit (LFE-10989): the safe
+ * main-thread parse bounds elsewhere are 300–500K, and this sits ~4–6Γ— above
+ * them while staying 100–1000Γ— larger than typical trace I/O (KB-scale), so
+ * real traces are never gated. Measures UTF-16 length (`.length` = chars).
+ */
+export const LARGE_STRING_RENDER_CHAR_LIMIT = 2_000_000;
+
+/**
+ * How much of the string the bounded preview head shows. Fixed regardless of
+ * payload size β€” the full value is reachable via download (and the header copy
+ * button).
+ */
+export const LARGE_STRING_PREVIEW_CHARS = 4_000;
+
+/**
+ * Whether `value` is a plain string large enough to bypass the Pretty / JSON
+ * render machinery in favour of a bounded preview + download. Non-strings and
+ * strings at or below the limit return `false` and render normally.
+ */
+export function isLargeRenderString(value: unknown): value is string {
+ return (
+ typeof value === "string" && value.length > LARGE_STRING_RENDER_CHAR_LIMIT
+ );
+}
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 4adaea0ad3..2358381b47 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -44,6 +44,10 @@ export const events = {
// Fired from the tree, timeline, graph, and search-result click handlers;
// `source` says which surface drove the navigation.
"node_selected",
+ // Download from the large-string IO fallback (LFE-10991): a top-level
+ // string over the render limit is shown as a bounded preview + download
+ // instead of the full Pretty/JSON viewer. Measures how often users hit it.
+ "large_string_field_download",
// Raw download from the JSON-view fallback shown when a field is too large
// to render in the unvirtualized viewer (LFE-10989).
"json_view_large_field_download",