Skip to content

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

fix(trace): gate oversized fields in the JSON Beta IO viewer (LFE-10847) (#15230)

Nikita Kabardinfc8827c3b003
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSON.clienttest.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSON.clienttest.tsx
new file mode 100644
index 0000000000..0fb98b03f7
--- /dev/null
+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSON.clienttest.tsx
@@ -0,0 +1,219 @@
+/**
+ * The JSON Beta viewer virtualizes the DOM but still builds the full node tree
+ * on the main thread, so a field with too many nodes (a large conversation /
+ * deeply nested JSON) freezes the tab even here (LFE-10847). These tests pin the
+ * node-count gate in IOPreviewJSON: over-limit fields render as a `hideData`
+ * section (so the viewer builds no tree) whose footer is the bounded fallback,
+ * while normal fields (including a huge single string, which is only one node)
+ * render with their data as before.
+ */
+import { render, screen } from "@testing-library/react";
+
+// Mock MultiSectionJsonViewer: expose each section's key, whether it carries
+// data (hideData=false) vs. is gated (hideData=true, tree never built), and
+// render its footer so the fallback is observable.
+vi.mock(
+ "@/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer",
+ () => ({
+ MultiSectionJsonViewer: (props: {
+ sections: {
+ key: string;
+ hideData?: boolean;
+ renderFooter?: (ctx: unknown) => React.ReactNode;
+ }[];
+ }) => (
+ <div data-testid="multi-section-viewer">
+ {props.sections.map((s) => (
+ <div
+ key={s.key}
+ data-testid={`section-${s.key}`}
+ data-hide-data={String(!!s.hideData)}
+ >
+ {!s.hideData && <span data-testid={`data-${s.key}`}>data</span>}
+ {s.renderFooter ? s.renderFooter({}) : null}
+ </div>
+ ))}
+ </div>
+ ),
+ }),
+);
+
+vi.mock("./components/CorrectedOutputField", () => ({
+ CorrectedOutputField: () => <div data-testid="corrected-output" />,
+}));
+
+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
+ usePostHogClientCapture: () => vi.fn(),
+}));
+
+vi.mock("next-themes", () => ({
+ useTheme: () => ({ resolvedTheme: "light" }),
+}));
+
+vi.mock(
+ "@/src/components/ui/AdvancedJsonViewer/hooks/useJsonViewPreferences",
+ () => ({
+ useJsonViewPreferences: () => ({
+ stringWrapMode: "truncate",
+ setStringWrapMode: vi.fn(),
+ }),
+ }),
+);
+
+// deepParseJson is the only runtime import from the shared barrel here; stub it
+// to identity so the test stays light and deterministic.
+vi.mock("@langfuse/shared", () => ({
+ deepParseJson: (value: unknown) => value,
+}));
+
+// Unicode decoding is orthogonal to the size gate under test; identity keeps
+// the test focused (and avoids pulling shared's decode helper through the mock).
+vi.mock("@/src/utils/decodeUnicodeInJson", () => ({
+ decodeUnicodeInJson: (value: unknown) => value,
+}));
+
+import { IOPreviewJSON } from "./IOPreviewJSON";
+import { JSON_VIEW_RENDER_ROW_LIMIT } from "./lib/jsonViewSizeGate";
+
+const FALLBACK_TEXT = /too large to render in JSON view/i;
+
+// An array of N primitives is N+1 rows (array node + N elements) and is cheap
+// to build β€” no giant nested object needed to cross the node limit.
+const manyRows = () =>
+ Array.from({ length: JSON_VIEW_RENDER_ROW_LIMIT }, (_, i) => i);
+
+describe("IOPreviewJSON node-count gating", () => {
+ it("renders an over-limit field as a hideData section with the fallback footer", () => {
+ render(
+ <IOPreviewJSON
+ input={manyRows()}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ // Fallback (with download) shown for the gated field...
+ expect(screen.getByText(FALLBACK_TEXT)).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /Download Input/i }),
+ ).toBeInTheDocument();
+ // ...and its section carries NO data, so the viewer builds no tree for it.
+ // The gated section uses a collapse-isolated key (`__oversized`), never the
+ // plain field key, so it cannot inherit a persisted collapsed state.
+ expect(screen.getByTestId("section-input__oversized")).toHaveAttribute(
+ "data-hide-data",
+ "true",
+ );
+ expect(screen.queryByTestId("data-input")).not.toBeInTheDocument();
+ });
+
+ it("gates under a collapse-isolated key, not the plain field key", () => {
+ // The fallback's download escape hatch lives in the section footer, which
+ // the viewer hides when the section is collapsed and persists that collapse
+ // per section key. Reusing the plain field key would let a collapse from an
+ // earlier trace (where the field rendered normally) silently hide the
+ // fallback here. A distinct `__oversized` key keeps the two states separate.
+ render(
+ <IOPreviewJSON
+ input={manyRows()}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ expect(screen.getByTestId("section-input__oversized")).toBeInTheDocument();
+ expect(screen.queryByTestId("section-input")).not.toBeInTheDocument();
+ });
+
+ it("reports the node/row count as the reason, not a character count", () => {
+ render(
+ <IOPreviewJSON
+ input={manyRows()}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+ // Node-count gate β†’ the summary names rows, not characters.
+ expect(screen.getByText(/rows β€” too large to render/i)).toBeInTheDocument();
+ expect(
+ screen.queryByText(/characters β€” too large to render/i),
+ ).not.toBeInTheDocument();
+ });
+
+ it("lets a huge single STRING through (one node) β€” no fallback, data rendered", () => {
+ // A 20 MB base64-style string is a single node: cheap for the virtualized
+ // viewer (renders as a media chip). A char-based gate would wrongly gate it.
+ const hugeString = "A".repeat(20_000_000);
+ render(
+ <IOPreviewJSON
+ input={hugeString}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ expect(screen.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();
+ expect(screen.getByTestId("section-input")).toHaveAttribute(
+ "data-hide-data",
+ "false",
+ );
+ expect(screen.getByTestId("data-input")).toBeInTheDocument();
+ });
+
+ it("gates only the over-limit field and keeps its position among sections", () => {
+ render(
+ <IOPreviewJSON
+ input={manyRows()}
+ output={{ answer: "ok" }}
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ // Input fallback shown, input section is gated (no data)...
+ expect(
+ screen.getByRole("button", { name: /Download Input/i }),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("section-input__oversized")).toHaveAttribute(
+ "data-hide-data",
+ "true",
+ );
+ // ...output still renders its data, and Input precedes Output (order kept).
+ expect(screen.getByTestId("data-output")).toBeInTheDocument();
+ const sections = screen.getAllByTestId(/^section-/);
+ expect(sections.map((el) => el.getAttribute("data-testid"))).toEqual([
+ "section-input__oversized",
+ "section-output",
+ ]);
+ });
+
+ it("renders normal small I/O with its data and no fallback", () => {
+ render(
+ <IOPreviewJSON
+ input={{ messages: [{ role: "user", content: "hi" }] }}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ expect(screen.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();
+ expect(screen.getByTestId("data-input")).toBeInTheDocument();
+ });
+});
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx
index 825795da00..4210dd0274 100644
--- a/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx
+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx
@@ -27,6 +27,11 @@ import { type ExpansionState } from "@/src/components/ui/AdvancedJsonViewer/type
import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";
import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";
import { CorrectedOutputField } from "./components/CorrectedOutputField";
+import { LargeJsonFieldFallback } from "./components/LargeJsonFieldFallback";
+import {
+ JSON_VIEW_RENDER_ROW_LIMIT,
+ probeJsonField,
+} from "./lib/jsonViewSizeGate";
const VIRTUALIZATION_THRESHOLD = 3333;
@@ -122,40 +127,113 @@ function IOPreviewJSONInner({
);
// Fall back to raw values when caller does not provide pre-parsed fields
- // (e.g. session events rows in v4 mode).
+ // (e.g. session events rows in v4 mode). Parse once here, BEFORE the decode
+ // and tree-build, so the node-count gate below can act on the parsed shape.
+ const inputParsed = useMemo(
+ () => (isParsing ? undefined : (parsedInput ?? deepParseJson(input))),
+ [parsedInput, input, isParsing],
+ );
+ const outputParsed = useMemo(
+ () => (isParsing ? undefined : (parsedOutput ?? deepParseJson(output))),
+ [parsedOutput, output, isParsing],
+ );
+ const metadataParsed = useMemo(
+ () => (isParsing ? undefined : (parsedMetadata ?? deepParseJson(metadata))),
+ [parsedMetadata, metadata, isParsing],
+ );
+
+ // Node-count gate (LFE-10847): the Beta viewer virtualizes the DOM but still
+ // builds the full node tree on the main thread, so a field with too many
+ // nodes (a large conversation / deeply nested JSON) freezes the tab even
+ // here. Count rows once per field β€” cheap (~integer add per node) and, unlike
+ // a char limit, correctly lets a huge single string (one node, e.g. a base64
+ // data-URI) through while gating million-node payloads. `countJsonRows` also
+ // feeds the virtualization decision below, so a gated field contributes 0.
+ const inputRows = useMemo(() => countJsonRows(inputParsed), [inputParsed]);
+ const outputRows = useMemo(() => countJsonRows(outputParsed), [outputParsed]);
+ const metadataRows = useMemo(
+ () => countJsonRows(metadataParsed),
+ [metadataParsed],
+ );
+
+ const inputTooLarge = inputRows > JSON_VIEW_RENDER_ROW_LIMIT;
+ const outputTooLarge = outputRows > JSON_VIEW_RENDER_ROW_LIMIT;
+ const metadataTooLarge = metadataRows > JSON_VIEW_RENDER_ROW_LIMIT;
+
// Decode \uXXXX escapes (e.g. Japanese ingested with Python
// ensure_ascii=True) at the data source so that search-match offsets, comment
// ranges, rendering and copy-to-clipboard all operate on the same decoded
// strings. Decoding at the leaf renderer instead would desync highlight
- // offsets. Already-decoded strings are a no-op.
- const effectiveInput = useMemo(() => {
- if (isParsing) return undefined;
- return decodeUnicodeInJson(parsedInput ?? deepParseJson(input));
- }, [parsedInput, input, isParsing]);
-
- const effectiveOutput = useMemo(() => {
- if (isParsing) return undefined;
- return decodeUnicodeInJson(parsedOutput ?? deepParseJson(output));
- }, [parsedOutput, output, isParsing]);
-
- const effectiveMetadata = useMemo(() => {
- if (isParsing) return undefined;
- return decodeUnicodeInJson(parsedMetadata ?? deepParseJson(metadata));
- }, [parsedMetadata, metadata, isParsing]);
-
- const showInput = !hideInput && !(hideIfNull && effectiveInput === undefined);
+ // offsets. Already-decoded strings are a no-op. Over-limit fields skip decode
+ // and the tree entirely β€” they render the bounded fallback instead.
+ const effectiveInput = useMemo(
+ () =>
+ isParsing || inputTooLarge ? undefined : decodeUnicodeInJson(inputParsed),
+ [inputParsed, isParsing, inputTooLarge],
+ );
+ const effectiveOutput = useMemo(
+ () =>
+ isParsing || outputTooLarge
+ ? undefined
+ : decodeUnicodeInJson(outputParsed),
+ [outputParsed, isParsing, outputTooLarge],
+ );
+ const effectiveMetadata = useMemo(
+ () =>
+ isParsing || metadataTooLarge
+ ? undefined
+ : decodeUnicodeInJson(metadataParsed),
+ [metadataParsed, isParsing, metadataTooLarge],
+ );
+
+ // Probe over-limit fields once for the bounded fallback (preview + download).
+ // Probe the PARSED value β€” the same value the row-count gate ran on β€” so the
+ // preview, download and reported size all reflect what tripped the gate (a
+ // string field that deep-parses into a large tree would otherwise show its
+ // short raw length).
+ const inputProbe = useMemo(
+ () => (inputTooLarge ? probeJsonField(inputParsed) : null),
+ [inputParsed, inputTooLarge],
+ );
+ const outputProbe = useMemo(
+ () => (outputTooLarge ? probeJsonField(outputParsed) : null),
+ [outputParsed, outputTooLarge],
+ );
+ const metadataProbe = useMemo(
+ () => (metadataTooLarge ? probeJsonField(metadataParsed) : null),
+ [metadataParsed, metadataTooLarge],
+ );
+
+ // A gated field parses to undefined above but is not empty β€” it is too big.
+ // Treat it as present so hideIfNull callers still show the fallback instead
+ // of silently dropping the field.
+ const showInput =
+ !hideInput &&
+ (inputTooLarge || !(hideIfNull && effectiveInput === undefined));
const showOutput =
- !hideOutput && !(hideIfNull && effectiveOutput === undefined);
- const showMetadata = !(hideIfNull && effectiveMetadata === undefined);
+ !hideOutput &&
+ (outputTooLarge || !(hideIfNull && effectiveOutput === undefined));
+ const showMetadata =
+ metadataTooLarge || !(hideIfNull && effectiveMetadata === undefined);
- // Count rows for each section to determine if virtualization is needed
+ const downloadName = observationId ?? traceId;
+
+ // Row counts drive the virtualization decision. Gated fields render as a
+ // fallback (not inside the viewer), so they contribute 0.
const rowCounts = useMemo(() => {
return {
- input: countJsonRows(effectiveInput),
- output: countJsonRows(effectiveOutput),
- metadata: countJsonRows(effectiveMetadata),
+ input: inputTooLarge ? 0 : inputRows,
+ output: outputTooLarge ? 0 : outputRows,
+ metadata: metadataTooLarge ? 0 : metadataRows,
};
- }, [effectiveInput, effectiveOutput, effectiveMetadata]);
+ }, [
+ inputTooLarge,
+ outputTooLarge,
+ metadataTooLarge,
+ inputRows,
+ outputRows,
+ metadataRows,
+ ]);
// Determine if virtualization is needed based on threshold
const needsVirtualization = useMemo(() => {
@@ -225,16 +303,25 @@ function IOPreviewJSONInner({
}, []);
const handleCopy = useCallback(() => {
+ // Gated fields have no materialized value (effective* is undefined), so
+ // copy a placeholder rather than silently dropping the key β€” the field is
+ // visibly present on screen (fallback + download), it just can't be inlined.
+ const TOO_LARGE = "<omitted: too large to render β€” use the field download>";
const dataObj: Record<string, unknown> = {};
- if (showInput) dataObj.input = effectiveInput;
- if (showOutput) dataObj.output = effectiveOutput;
- if (showMetadata) dataObj.metadata = effectiveMetadata;
+ if (showInput) dataObj.input = inputTooLarge ? TOO_LARGE : effectiveInput;
+ if (showOutput)
+ dataObj.output = outputTooLarge ? TOO_LARGE : effectiveOutput;
+ if (showMetadata)
+ dataObj.metadata = metadataTooLarge ? TOO_LARGE : effectiveMetadata;
const jsonString = JSON.stringify(dataObj, null, 2);
navigator.clipboard.writeText(jsonString);
}, [
showInput,
showOutput,
showMetadata,
+ inputTooLarge,
+ outputTooLarge,
+ metadataTooLarge,
effectiveInput,
effectiveOutput,
effectiveMetadata,
@@ -252,26 +339,88 @@ function IOPreviewJSONInner({
[stringWrapMode],
);
- // Build sections - memoized to prevent re-creation
+ // Build sections - memoized to prevent re-creation. A gated field renders as
+ // a section with no data (hideData β†’ the viewer builds no tree for it, so it
+ // can't freeze) whose footer is the bounded fallback. Keeping it a section β€”
+ // rather than a block outside the viewer β€” preserves the natural
+ // Input β†’ Output β†’ Metadata order and the shared search/scroll. The section
+ // header shows the field name, so the fallback hides its own title.
const sections = useMemo(() => {
+ const gatedSection = (
+ fieldKey: string,
+ title: string,
+ backgroundColor: string,
+ probe: ReturnType<typeof probeJsonField> | null,
+ rowCount: number,
+ ) => ({
+ // Use a key distinct from the field's normal section key so the fallback
+ // does not inherit a persisted collapsed state from an earlier trace
+ // where the same field rendered normally β€” that would silently hide the
+ // download escape hatch (its collapse persists per section key). A gated
+ // field gets its own key, so it always defaults to expanded.
+ key: `${fieldKey}__oversized`,
+ title,
+ data: null,
+ hideData: true,
+ backgroundColor,
+ minHeight: "4px",
+ // A gated field has no tree to expand/collapse β€” only the download escape
+ // hatch below. Render a header WITHOUT a collapse toggle, so the section
+ // can never be collapsed: its collapse is therefore never persisted, and
+ // the download can't be hidden β€” not silently (inherited state) and not
+ // by a user collapsing one gated field then viewing another of the same
+ // name (the gated→gated leak the plain key still allowed).
+ renderHeader: () => (
+ <div className="flex items-center px-2 py-1.5">
+ <span className="text-xs font-bold">{title}</span>
+ </div>
+ ),
+ renderFooter: () =>
+ probe ? (
+ <LargeJsonFieldFallback
+ title={title}
+ hideTitle
+ serialized={probe.serialized}
+ isString={probe.isString}
+ charCount={probe.size}
+ rowCount={rowCount}
+ downloadFileBase={`${fieldKey}-${downloadName}`}
+ />
+ ) : null,
+ });
+
const result = [];
if (showInput) {
- result.push({
- key: "input",
- title: "Input",
- data: effectiveInput,
- backgroundColor: inputBgColor,
- minHeight: "200px",
- });
+ result.push(
+ inputTooLarge
+ ? gatedSection("input", "Input", inputBgColor, inputProbe, inputRows)
+ : {
+ key: "input",
+ title: "Input",
+ data: effectiveInput,
+ backgroundColor: inputBgColor,
+ minHeight: "200px",
+ },
+ );
}
if (showOutput) {
- result.push({
- key: "output",
- title: "Output",
- data: effectiveOutput,
- backgroundColor: outputBgColor,
- minHeight: "200px",
- });
+ result.push(
+ outputTooLarge
+ ? gatedSection(
+ "output",
+ "Output",
+ outputBgColor,
+ outputProbe,
+ outputRows,
+ )
+ : {
+ key: "output",
+ title: "Output",
+ data: effectiveOutput,
+ backgroundColor: outputBgColor,
+ minHeight: "200px",
+ },
+ );
}
if (showCorrections) {
result.push({
@@ -285,6 +434,7 @@ function IOPreviewJSONInner({
renderFooter: () => (
<CorrectedOutputField
actualOutput={effectiveOutput}
+ actualOutputTooLarge={outputTooLarge}
existingCorrection={outputCorrection}
observationId={observationId}
projectId={projectId}
@@ -296,22 +446,42 @@ function IOPreviewJSONInner({
});
}
if (showMetadata) {
- result.push({
- key: "metadata",
- title: "Metadata",
- data: effectiveMetadata,
- backgroundColor: metadataBgColor,
- minHeight: "200px",
- });
+ result.push(
+ metadataTooLarge
+ ? gatedSection(
+ "metadata",
+ "Metadata",
+ metadataBgColor,
+ metadataProbe,
+ metadataRows,
+ )
+ : {
+ key: "metadata",
+ title: "Metadata",
+ data: effectiveMetadata,
+ backgroundColor: metadataBgColor,
+ minHeight: "200px",
+ },
+ );
}
return result;
}, [
showInput,
showOutput,
showMetadata,
+ inputTooLarge,
+ outputTooLarge,
+ metadataTooLarge,
effectiveInput,
effectiveOutput,
effectiveMetadata,
+ inputProbe,
+ outputProbe,
+ metadataProbe,
+ inputRows,
+ outputRows,
+ metadataRows,
+ downloadName,
inputBgColor,
outputBgColor,
metadataBgColor,
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx
index 21af5943bf..ac8a19f67e 100644
--- a/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx
+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx
@@ -184,10 +184,13 @@ export function IOPreviewJSONSimple({
))}
{/* When the output is over-limit, effectiveOutput is undefined, so the
correction editor opens without a baseline actual-output to diff
- against β€” an acceptable degradation for payloads too large to render. */}
+ against β€” an acceptable degradation for payloads too large to render.
+ We flag it as too-large so the diff dialog says so, rather than
+ reporting "no original output". */}
{showCorrections && (
<CorrectedOutputField
actualOutput={effectiveOutput}
+ actualOutputTooLarge={outputTooLarge}
existingCorrection={outputCorrection}
observationId={observationId}
projectId={projectId}
diff --git a/web/src/components/trace/components/IOPreview/components/CorrectedOutputDiffDialog.clienttest.tsx b/web/src/components/trace/components/IOPreview/components/CorrectedOutputDiffDialog.clienttest.tsx
new file mode 100644
index 0000000000..5c5aff923c
--- /dev/null
+++ b/web/src/components/trace/components/IOPreview/components/CorrectedOutputDiffDialog.clienttest.tsx
@@ -0,0 +1,102 @@
+/**
+ * The output-correction diff dialog has three states, and gated (too-large)
+ * output must not be conflated with genuinely-absent output (LFE-10847 review):
+ * - `actualOutputTooLarge` β†’ the original exists but was gated out of the view,
+ * so we say it is too large to diff (NOT "no original output").
+ * - original output null/undefined and not gated β†’ "No original output".
+ * - original output present β†’ render the diff.
+ *
+ * The Dialog primitives (Radix portal + layer container) and DiffViewer are
+ * stubbed to inline renders so these tests pin the branch logic, not the
+ * overlay plumbing.
+ */
+import { render, screen } from "@testing-library/react";
+
+vi.mock("@/src/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogHeader: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogBody: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogFooter: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: React.ReactNode }) => (
+ <h2>{children}</h2>
+ ),
+ DialogDescription: ({ children }: { children: React.ReactNode }) => (
+ <p>{children}</p>
+ ),
+}));
+
+vi.mock("@/src/components/DiffViewer", () => ({
+ default: (props: { oldString: string; newString: string }) => (
+ <div
+ data-testid="diff-viewer"
+ data-old={props.oldString}
+ data-new={props.newString}
+ />
+ ),
+}));
+
+import { CorrectedOutputDiffDialog } from "./CorrectedOutputDiffDialog";
+
+const noop = () => {};
+
+describe("CorrectedOutputDiffDialog original-output state", () => {
+ it("reports too-large output as such, not as missing", () => {
+ render(
+ <CorrectedOutputDiffDialog
+ isOpen
+ setIsOpen={noop}
+ actualOutput={undefined}
+ actualOutputTooLarge
+ correctedOutput='{"answer":"fixed"}'
+ strictJsonMode={false}
+ />,
+ );
+
+ expect(screen.getByText(/too large to diff/i)).toBeInTheDocument();
+ expect(screen.queryByText(/^No original output$/i)).not.toBeInTheDocument();
+ expect(screen.queryByTestId("diff-viewer")).not.toBeInTheDocument();
+ });
+
+ it("reports genuinely-absent output as 'No original output'", () => {
+ render(
+ <CorrectedOutputDiffDialog
+ isOpen
+ setIsOpen={noop}
+ actualOutput={undefined}
+ correctedOutput='{"answer":"fixed"}'
+ strictJsonMode={false}
+ />,
+ );
+
+ expect(screen.getByText(/^No original output$/i)).toBeInTheDocument();
+ expect(screen.queryByText(/too large to diff/i)).not.toBeInTheDocument();
+ expect(screen.queryByTestId("diff-viewer")).not.toBeInTheDocument();
+ });
+
+ it("renders the diff when an original output is present", () => {
+ render(
+ <CorrectedOutputDiffDialog
+ isOpen
+ setIsOpen={noop}
+ actualOutput="original"
+ correctedOutput="corrected"
+ strictJsonMode={false}
+ />,
+ );
+
+ expect(screen.getByTestId("diff-viewer")).toBeInTheDocument();
+ expect(screen.queryByText(/No original output/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/too large to diff/i)).not.toBeInTheDocument();
+ });
+});
diff --git a/web/src/components/trace/components/IOPreview/components/CorrectedOutputDiffDialog.tsx b/web/src/components/trace/components/IOPreview/components/CorrectedOutputDiffDialog.tsx
index e226c9db93..88305c7790 100644
--- a/web/src/components/trace/components/IOPreview/components/CorrectedOutputDiffDialog.tsx
+++ b/web/src/components/trace/components/IOPreview/components/CorrectedOutputDiffDialog.tsx
@@ -17,6 +17,11 @@ type CorrectedOutputDiffDialogProps = {
actualOutput?: unknown;
correctedOutput: string;
strictJsonMode: boolean;
+ /**
+ * True when the original output exists but was too large to load into the
+ * view (gated). Distinguishes "too large to diff" from "no output at all".
+ */
+ actualOutputTooLarge?: boolean;
};
/**
@@ -55,7 +60,14 @@ const formatOutputForDiff = (
export const CorrectedOutputDiffDialog: React.FC<
CorrectedOutputDiffDialogProps
-> = ({ isOpen, setIsOpen, actualOutput, correctedOutput, strictJsonMode }) => {
+> = ({
+ isOpen,
+ setIsOpen,
+ actualOutput,
+ correctedOutput,
+ strictJsonMode,
+ actualOutputTooLarge = false,
+}) => {
// Format both outputs for comparison
const formattedActualOutput = formatOutputForDiff(
actualOutput,
@@ -66,9 +78,12 @@ export const CorrectedOutputDiffDialog: React.FC<
strictJsonMode,
);
- // Check if there's no original output to compare
+ // Check if there's no original output to compare. When the output exists but
+ // was too large to load into the view, we cannot diff it β€” but that is not
+ // the same as there being no original output.
const hasNoOriginalOutput =
- actualOutput === null || actualOutput === undefined;
+ !actualOutputTooLarge &&
+ (actualOutput === null || actualOutput === undefined);
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
@@ -81,7 +96,26 @@ export const CorrectedOutputDiffDialog: React.FC<
</DialogHeader>
<DialogBody>
- {hasNoOriginalOutput ? (
+ {actualOutputTooLarge ? (
+ <div className="space-y-4">
+ <div className="text-muted-foreground rounded-md border border-dashed p-4 text-sm">
+ <p className="text-foreground font-bold">
+ Original output too large to diff
+ </p>
+ <p className="mt-1">
+ The original output is too large to load here, so it cannot be
+ compared side by side. Your correction is shown below and will
+ be saved as-is.
+ </p>
+ </div>
+ <div>
+ <p className="mb-1 text-sm font-bold">Corrected Output</p>
+ <pre className="bg-muted/30 max-h-[50vh] overflow-auto rounded-md border p-3 text-xs break-words whitespace-pre-wrap">
+ {formattedCorrectedOutput}
+ </pre>
+ </div>
+ </div>
+ ) : hasNoOriginalOutput ? (
<div className="flex flex-col items-center justify-center p-8 text-center">
<div className="text-muted-foreground">
<p className="text-lg font-bold">No original output</p>
diff --git a/web/src/components/trace/components/IOPreview/components/CorrectedOutputField.tsx b/web/src/components/trace/components/IOPreview/components/CorrectedOutputField.tsx
index e3b73e116b..43b1ea224d 100644
--- a/web/src/components/trace/components/IOPreview/components/CorrectedOutputField.tsx
+++ b/web/src/components/trace/components/IOPreview/components/CorrectedOutputField.tsx
@@ -24,6 +24,12 @@ interface CorrectedOutputFieldProps {
traceId: string;
environment: string;
actualOutput?: unknown;
+ /**
+ * True when the original output exists but was gated out of the view for
+ * being too large. It is then unavailable as `actualOutput`, but that must
+ * not be reported to the user as "no original output".
+ */
+ actualOutputTooLarge?: boolean;
existingCorrection?: ScoreDomain | null;
observationId?: string;
compact?: boolean; // Use smaller font size for JSON Beta view
@@ -31,6 +37,7 @@ interface CorrectedOutputFieldProps {
export function CorrectedOutputField({
actualOutput,
+ actualOutputTooLarge = false,
existingCorrection,
observationId,
projectId,
@@ -154,6 +161,7 @@ export function CorrectedOutputField({
isOpen={isDiffDialogOpen}
setIsOpen={setIsDiffDialogOpen}
actualOutput={actualOutput}
+ actualOutputTooLarge={actualOutputTooLarge}
correctedOutput={value}
strictJsonMode={strictJsonMode}
/>
diff --git a/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx b/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
index bffb274ba8..92f1bb2be8 100644
--- a/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
+++ b/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
@@ -10,11 +10,13 @@ const PREVIEW_DISPLAY_CHARS = 4_000;
/**
* Fallback for a single JSON-view field (Input / Output / Metadata) whose
- * payload is too large to render in the unvirtualized react18-json-view
- * (LFE-10989). Instead of parsing + rendering the full tree on the main thread
- * β€” which freezes for seconds and crashes the renderer around ~20 MB β€” it
- * shows a bounded preview head plus escape hatches: a raw download, and a
- * pointer to the Formatted (lazy) and JSON Beta (virtualized) views that scale.
+ * payload is too large to render. Used by both JSON views: the plain view when
+ * a field exceeds the char limit (unvirtualized react18-json-view, LFE-10989),
+ * and the Beta viewer when a field exceeds the node/row limit (its O(N)
+ * tree-build freezes the tab even though the DOM is virtualized, LFE-10847).
+ * Instead of building the full tree on the main thread β€” which freezes for
+ * seconds and crashes the renderer β€” it shows a bounded preview head plus
+ * escape hatches: a raw download, and a pointer to the Formatted (lazy) view.
*
* This component never serializes the payload: the caller's size probe already
* did that once and passes the `serialized` string in, reused here for both the
@@ -26,7 +28,9 @@ export function LargeJsonFieldFallback({
serialized,
isString,
charCount,
+ rowCount,
downloadFileBase,
+ hideTitle = false,
}: {
title: string;
/** Pre-serialized content: raw text for string fields, compact JSON for
@@ -36,11 +40,25 @@ export function LargeJsonFieldFallback({
* base64/plain payloads are not quote/escape-wrapped; objects use .json. */
isString: boolean;
charCount: number;
+ /** When set, the field was gated on node/row count (JSON Beta viewer), so the
+ * summary names rows β€” the actual trigger β€” instead of characters. Omit for
+ * the plain view's char-based gate. */
+ rowCount?: number;
/** File name without extension. */
downloadFileBase: string;
+ /** Omit the field-name heading β€” used when the surrounding section already
+ * renders the title (JSON Beta section footer). */
+ hideTitle?: boolean;
}) {
const capture = usePostHogClientCapture();
+ // Name the metric that actually tripped the gate: rows for the virtualized
+ // Beta viewer (node/tree-build cost), characters for the plain view.
+ const sizeSummary =
+ rowCount != null
+ ? `${compactNumberFormatter(rowCount, 1)} rows`
+ : `${compactNumberFormatter(charCount, 1)} characters`;
+
const previewText = useMemo(
() =>
serialized.length > PREVIEW_DISPLAY_CHARS
@@ -64,16 +82,14 @@ export function LargeJsonFieldFallback({
<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">
- <span className="text-foreground font-bold">{title}</span>
- <span>
- {compactNumberFormatter(charCount, 1)} characters β€” too large to
- render in JSON view
- </span>
+ {!hideTitle && (
+ <span className="text-foreground font-bold">{title}</span>
+ )}
+ <span>{sizeSummary} β€” too large to render in JSON view</span>
</div>
<p className="text-muted-foreground text-xs">
Rendering this much JSON at once freezes the tab. Use the{" "}
- <span className="font-bold">Formatted</span> or{" "}
- <span className="font-bold">JSON Beta</span> view for the full
+ <span className="font-bold">Formatted</span> view for the full
payload, or download it below.
</p>
<pre className="bg-muted/50 max-h-40 overflow-hidden rounded-md border p-2 font-mono text-xs break-all whitespace-pre-wrap">
diff --git a/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
index 9b200c3e15..3379216184 100644
--- a/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
+++ b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
@@ -37,6 +37,27 @@
*/
export const JSON_VIEW_RENDER_CHAR_LIMIT = 2_000_000;
+/**
+ * Node ceiling for rendering a field in the *virtualized* JSON Beta viewer
+ * (AdvancedJsonViewer). Measured in fully-expanded rows (`countJsonRows`), NOT
+ * chars β€” the Beta viewer virtualizes the DOM, so its cost is the O(N)
+ * tree-build (`buildMultiSectionTree` materializes every node) + row-count, not
+ * the visible DOM. A char limit is the wrong metric here: a 20 MB single string
+ * (e.g. a base64 data-URI) is one node and renders instantly as a media chip,
+ * while 20 MB of nested JSON is ~1M nodes and freezes the tab building the tree
+ * (LFE-10847 β€” matches the "freezes switching to JSON view on large
+ * conversations" report). Above this limit the field renders the same bounded
+ * preview + download fallback the plain JSON view uses.
+ *
+ * 50k is chosen deliberately:
+ * - 15Γ— the viewer's own `VIRTUALIZATION_THRESHOLD` (3333), so ordinary large
+ * traces (a few thousand rows) are never gated and keep rendering.
+ * - Far below the measured ~1M-node freeze; a 50k-node tree builds in tens of
+ * ms and virtualizes fine.
+ * Users keep full access via the Formatted (lazy) view and the raw download.
+ */
+export const JSON_VIEW_RENDER_ROW_LIMIT = 50_000;
+
export interface JsonFieldProbe {
/** Serialized length in UTF-16 chars; drives the gating decision. */
size: number;
diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.clienttest.ts b/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.clienttest.ts
new file mode 100644
index 0000000000..74d2385fbb
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.clienttest.ts
@@ -0,0 +1,37 @@
+/**
+ * countJsonRows feeds the JSON-view size gate (LFE-10847): it decides whether a
+ * field is too large to render. It must therefore never itself crash on the
+ * payloads the gate exists to catch β€” in particular a deeply *nested* payload
+ * (a single-branch chain thousands of levels deep), which overflows the call
+ * stack under plain recursion (worse in Firefox, cf. the deep-chain shapes in
+ * LFE-10959). These tests pin the counts and the deep-nesting safety.
+ */
+import { countJsonRows, exceedsRowThreshold } from "./rowCount";
+
+describe("countJsonRows", () => {
+ it("counts primitives, objects, and arrays per the node model", () => {
+ expect(countJsonRows(null)).toBe(0);
+ expect(countJsonRows(undefined)).toBe(0);
+ expect(countJsonRows("hello")).toBe(1);
+ expect(countJsonRows(42)).toBe(1);
+ expect(countJsonRows(true)).toBe(1);
+ expect(countJsonRows({ a: 1, b: 2 })).toBe(3); // object + 2 props
+ expect(countJsonRows([1, 2, 3])).toBe(4); // array + 3 elements
+ expect(countJsonRows({ a: { b: { c: 1 } } })).toBe(4); // 3 objects + 1 number
+ expect(countJsonRows([])).toBe(1);
+ expect(countJsonRows({})).toBe(1);
+ });
+
+ it("does not stack-overflow on a deeply nested chain", () => {
+ const depth = 200_000;
+ let deep: unknown = 1;
+ for (let i = 0; i < depth; i++) deep = { next: deep };
+ // depth objects + the leaf primitive.
+ expect(countJsonRows(deep)).toBe(depth + 1);
+ });
+
+ it("exceedsRowThreshold compares the total against the limit", () => {
+ expect(exceedsRowThreshold([1, 2, 3], 2)).toBe(true);
+ expect(exceedsRowThreshold([1, 2, 3], 10)).toBe(false);
+ });
+});
diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.ts b/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.ts
index cd2a4a1373..0522da61b4 100644
--- a/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.ts
+++ b/web/src/components/ui/AdvancedJsonViewer/utils/rowCount.ts
@@ -21,42 +21,55 @@
* countJsonRows({ a: { b: { c: 1 } } }) // 4 (3 objects + 1 number)
*/
export function countJsonRows(data: unknown): number {
- // null/undefined β†’ no rows
- if (data === null || data === undefined) {
- return 0;
- }
+ // Iterative DFS with an explicit stack β€” NOT plain recursion. A deeply nested
+ // payload (a single-branch chain thousands of levels deep) is exactly the
+ // shape this gate exists to catch, and one JS call frame per level would
+ // stack-overflow the counter itself (worse in Firefox). The counts are
+ // identical to the node model: null/undefined β†’ 0, primitive β†’ 1,
+ // array/object β†’ 1 + children.
+ let count = 0;
+ const stack: unknown[] = [data];
- // Primitives (string, number, boolean) β†’ 1 row
- const type = typeof data;
- if (type === "string" || type === "number" || type === "boolean") {
- return 1;
- }
+ while (stack.length > 0) {
+ const node = stack.pop();
- // Arrays
- if (Array.isArray(data)) {
- // 1 for array itself + sum of all elements
- let count = 1;
- for (const element of data) {
- count += countJsonRows(element);
+ // null/undefined β†’ no rows
+ if (node === null || node === undefined) {
+ continue;
+ }
+
+ const type = typeof node;
+ if (type === "string" || type === "number" || type === "boolean") {
+ count += 1;
+ continue;
}
- return count;
- }
- // Objects
- if (type === "object" && data !== null) {
- // 1 for object itself + sum of all properties
- let count = 1;
- const obj = data as Record<string, unknown>;
- for (const key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
- count += countJsonRows(obj[key]);
+ if (Array.isArray(node)) {
+ // 1 for the array itself + each element (pushed for later counting).
+ count += 1;
+ for (let i = 0; i < node.length; i++) {
+ stack.push(node[i]);
}
+ continue;
}
- return count;
+
+ if (type === "object") {
+ // 1 for the object itself + each own property.
+ count += 1;
+ const obj = node as Record<string, unknown>;
+ for (const key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ stack.push(obj[key]);
+ }
+ }
+ continue;
+ }
+
+ // Fallback for other types (functions, symbols, etc.) β†’ 1 row
+ count += 1;
}
- // Fallback for other types (functions, symbols, etc.) β†’ 1 row
- return 1;
+ return count;
}
/**