Skip to content

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

feat(trace): render oversized JSON-Beta fields lazily (P2, LFE-11084) (#15322)

Nikita Kabardinbc6a9103ed46
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSON.clienttest.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSON.clienttest.tsx
index 0fb98b03f7..f6f88f729b 100644
--- a/web/src/components/trace/components/IOPreview/IOPreviewJSON.clienttest.tsx
+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSON.clienttest.tsx
@@ -1,11 +1,13 @@
/**
- * 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.
+ * The eager JSON Beta viewer builds the full node tree on the main thread, so a
+ * field with too many nodes freezes the tab (LFE-10847). These tests pin the
+ * node-count gate + its P2 resolution: an over-limit field renders as a
+ * `hideData` section (the eager viewer builds no tree for it) whose footer is
+ * the **lazy** byte-engine viewer (main thread, cost proportional to what's
+ * expanded) plus a download escape hatch β€” NOT the old "too large" dead-end.
+ * Normal fields (including a huge single string, which is only one node) render
+ * with their data as before. (A string is 1 node, so it is never node-gated
+ * here; gated ⟹ structured.)
*/
import { render, screen } from "@testing-library/react";
@@ -38,10 +40,39 @@ vi.mock(
}),
);
+// Capture the props CorrectedOutputField receives β€” the diff dialog it mounts
+// JSON.stringifies `actualOutput` unmemoized on every render, so an oversized
+// output must NOT be handed to it. `vi.hoisted` so the holder exists when the
+// hoisted mock factory runs.
+const correctedField = vi.hoisted(() => ({
+ props: undefined as
+ | { actualOutput?: unknown; actualOutputTooLarge?: boolean }
+ | undefined,
+}));
vi.mock("./components/CorrectedOutputField", () => ({
- CorrectedOutputField: () => <div data-testid="corrected-output" />,
+ CorrectedOutputField: (props: {
+ actualOutput?: unknown;
+ actualOutputTooLarge?: boolean;
+ }) => {
+ // Read each field explicitly (not the whole object) so the capture is
+ // exactly what the tests assert β€” and to satisfy react/no-unused-prop-types.
+ correctedField.props = {
+ actualOutput: props.actualOutput,
+ actualOutputTooLarge: props.actualOutputTooLarge,
+ };
+ return <div data-testid="corrected-output" />;
+ },
}));
+// The lazy renderer runs a byte engine + virtualizer; stub it to a marker so
+// these tests assert the gated field is routed to it, not its internals.
+vi.mock(
+ "@/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer",
+ () => ({
+ LazyJsonViewer: () => <div data-testid="lazy-json-viewer" />,
+ }),
+);
+
vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
usePostHogClientCapture: () => vi.fn(),
}));
@@ -66,10 +97,16 @@ 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).
+// Unicode decoding is orthogonal to the size gate; a spy that returns identity
+// keeps existing tests focused while letting one test assert the all-or-nothing
+// decode rule. A small MAX_NODES makes "over budget" cheap to trigger.
+const decodeMock = vi.hoisted(() => ({
+ spy: vi.fn((value: unknown) => value),
+ MAX_NODES: 10,
+}));
vi.mock("@/src/utils/decodeUnicodeInJson", () => ({
- decodeUnicodeInJson: (value: unknown) => value,
+ decodeUnicodeInJson: decodeMock.spy,
+ DECODE_UNICODE_MAX_NODES: decodeMock.MAX_NODES,
}));
import { IOPreviewJSON } from "./IOPreviewJSON";
@@ -82,8 +119,38 @@ const FALLBACK_TEXT = /too large to render in JSON view/i;
const manyRows = () =>
Array.from({ length: JSON_VIEW_RENDER_ROW_LIMIT }, (_, i) => i);
+// A field big enough to need windowing but well under the old 50k limit. This
+// "dead zone" (3,333–50,000 rows) used to fall to the eager virtualized viewer,
+// which synchronously builds+renders the whole node set β€” a 44k-row big-number
+// output pegged the main thread ~4 min (LFE-10847). It must now route to the
+// lazy viewer, same as any over-threshold field. Fixed count, independent of the
+// gate constant, so it keeps guarding the regression if the constant moves.
+const deadZoneRows = () => Array.from({ length: 5_000 }, (_, i) => i);
+
describe("IOPreviewJSON node-count gating", () => {
- it("renders an over-limit field as a hideData section with the fallback footer", () => {
+ it("routes a dead-zone field (thousands of rows) to the lazy viewer, not the eager tree", () => {
+ render(
+ <IOPreviewJSON
+ input={deadZoneRows()}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ // Gated β†’ lazy viewer + download hatch; the eager viewer builds no tree.
+ expect(screen.getByTestId("lazy-json-viewer")).toBeInTheDocument();
+ expect(screen.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();
+ expect(screen.getByTestId("section-input__oversized")).toHaveAttribute(
+ "data-hide-data",
+ "true",
+ );
+ expect(screen.queryByTestId("data-input")).not.toBeInTheDocument();
+ });
+
+ it("renders an over-limit field lazily with a download hatch (no dead-end)", () => {
render(
<IOPreviewJSON
input={manyRows()}
@@ -95,14 +162,16 @@ describe("IOPreviewJSON node-count gating", () => {
/>,
);
- // Fallback (with download) shown for the gated field...
- expect(screen.getByText(FALLBACK_TEXT)).toBeInTheDocument();
+ // The gated structured field is now RENDERED via the lazy viewer, with the
+ // download as a secondary escape hatch β€” not the old "too large" dead-end.
+ expect(screen.getByTestId("lazy-json-viewer")).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.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();
+ // Its section still carries NO data, so the EAGER 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",
@@ -131,7 +200,7 @@ describe("IOPreviewJSON node-count gating", () => {
expect(screen.queryByTestId("section-input")).not.toBeInTheDocument();
});
- it("reports the node/row count as the reason, not a character count", () => {
+ it("names the download-hatch size in rows (node-count gate), not characters", () => {
render(
<IOPreviewJSON
input={manyRows()}
@@ -142,11 +211,9 @@ describe("IOPreviewJSON node-count gating", () => {
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();
+ // Node-count gate β†’ the download hatch's size note names rows, not chars.
+ expect(screen.getByText(/\brows\b/i)).toBeInTheDocument();
+ expect(screen.queryByText(/\bcharacters\b/i)).not.toBeInTheDocument();
});
it("lets a huge single STRING through (one node) β€” no fallback, data rendered", () => {
@@ -201,6 +268,82 @@ describe("IOPreviewJSON node-count gating", () => {
]);
});
+ it("does not hand an oversized output to the correction diff (avoids per-render re-stringify)", () => {
+ // Regression (LFE-10847 review πŸ”΄): CorrectedOutputField always mounts the
+ // diff dialog, which JSON.stringifies `actualOutput` unmemoized in its
+ // render body β€” so handing it the full oversized output re-serializes
+ // megabytes on every render/keystroke. A gated output must reach it as
+ // undefined (actualOutputTooLarge=true drives the "too large to diff"
+ // branch); the decoded value still feeds the lazy viewer/probe separately.
+ render(
+ <IOPreviewJSON
+ output={manyRows()}
+ hideInput
+ hideIfNull={false}
+ showCorrections={true}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+ expect(correctedField.props?.actualOutputTooLarge).toBe(true);
+ expect(correctedField.props?.actualOutput).toBeUndefined();
+ });
+
+ it("still hands a small (non-gated) output to the correction diff", () => {
+ render(
+ <IOPreviewJSON
+ output={{ answer: "ok" }}
+ hideInput
+ hideIfNull={false}
+ showCorrections={true}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+ expect(correctedField.props?.actualOutputTooLarge).toBe(false);
+ expect(correctedField.props?.actualOutput).toEqual({ answer: "ok" });
+ });
+
+ it("decodes unicode for a field within the decode budget", () => {
+ decodeMock.spy.mockClear();
+ render(
+ <IOPreviewJSON
+ output={{ answer: "ok" }}
+ hideInput
+ hideIfNull={false}
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+ expect(decodeMock.spy).toHaveBeenCalledWith({ answer: "ok" });
+ });
+
+ it("skips decode for a field over the budget β€” shown raw, never partial/mixed", () => {
+ // decodeUnicodeInJson caps at DECODE_UNICODE_MAX_NODES and copies the rest
+ // un-decoded; since the same value backs the viewer AND the raw download, a
+ // larger field would export mixed decoded/escaped unicode. Over the budget
+ // (here 10) the field must NOT be decoded at all (LFE-10847 review 🟑).
+ decodeMock.spy.mockClear();
+ render(
+ <IOPreviewJSON
+ output={manyRows()} // 3,334 rows ≫ budget
+ hideInput
+ hideIfNull={false}
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+ const decodedArgs = decodeMock.spy.mock.calls.map((c) => c[0]);
+ // The oversized array was never handed to the decoder (all-or-nothing).
+ expect(
+ decodedArgs.some(
+ (v) => Array.isArray(v) && v.length > decodeMock.MAX_NODES,
+ ),
+ ).toBe(false);
+ });
+
it("renders normal small I/O with its data and no fallback", () => {
render(
<IOPreviewJSON
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx
index 4210dd0274..5b308b742f 100644
--- a/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx
+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx
@@ -25,15 +25,37 @@ import { InlineCommentBubble } from "@/src/features/comments/components/InlineCo
import { type CommentedPathsByField } from "@/src/components/ui/AdvancedJsonViewer/utils/commentRanges";
import { type ExpansionState } from "@/src/components/ui/AdvancedJsonViewer/types";
import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";
-import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";
+import {
+ decodeUnicodeInJson,
+ DECODE_UNICODE_MAX_NODES,
+} from "@/src/utils/decodeUnicodeInJson";
import { CorrectedOutputField } from "./components/CorrectedOutputField";
import { LargeJsonFieldFallback } from "./components/LargeJsonFieldFallback";
+import { LazyJsonViewer } from "@/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer";
import {
JSON_VIEW_RENDER_ROW_LIMIT,
probeJsonField,
} from "./lib/jsonViewSizeGate";
-const VIRTUALIZATION_THRESHOLD = 3333;
+// A field needing windowing is gated to the lazy byte-engine viewer, so the
+// gate row limit IS the virtualization threshold (single source of truth). The
+// eager virtualized viewer is therefore unreachable for trace I/O β€” see the
+// `needsVirtualization` note below.
+const VIRTUALIZATION_THRESHOLD = JSON_VIEW_RENDER_ROW_LIMIT;
+
+/**
+ * Decode a field's \uXXXX escapes, but only when it fits under the decoder's
+ * node budget. `decodeUnicodeInJson` caps at DECODE_UNICODE_MAX_NODES and copies
+ * the remainder through un-decoded; since the same value backs both the viewer
+ * and the raw download, a larger field would export a traversal-order-dependent
+ * MIX of decoded/escaped unicode. Past the budget, return it raw (fully
+ * un-decoded) β€” consistent and faithful β€” rather than partially decoded.
+ */
+function decodeIfWithinBudget(value: unknown, rowCount: number): unknown {
+ return rowCount > DECODE_UNICODE_MAX_NODES
+ ? value
+ : decodeUnicodeInJson(value);
+}
export interface IOPreviewJSONProps {
input?: Prisma.JsonValue;
@@ -164,26 +186,32 @@ function IOPreviewJSONInner({
// 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. Over-limit fields skip decode
- // and the tree entirely β€” they render the bounded fallback instead.
+ // offsets. Already-decoded strings are a no-op. We decode over-render-limit
+ // fields too (they render lazily over this decoded value), so a field's
+ // display doesn't change just because it crossed the render gate.
+ //
+ // BUT `decodeUnicodeInJson` caps its walk at DECODE_UNICODE_MAX_NODES and
+ // copies the remainder through un-decoded. A field bigger than that would be
+ // PARTIALLY decoded, and since the same value backs both the viewer and the
+ // raw download, the download would carry a traversal-order-dependent MIX of
+ // decoded/escaped unicode (LFE-10847 review). Decode all-or-nothing: past the
+ // budget, show it fully raw β€” consistent and faithful β€” rather than partial.
const effectiveInput = useMemo(
() =>
- isParsing || inputTooLarge ? undefined : decodeUnicodeInJson(inputParsed),
- [inputParsed, isParsing, inputTooLarge],
+ isParsing ? undefined : decodeIfWithinBudget(inputParsed, inputRows),
+ [inputParsed, inputRows, isParsing],
);
const effectiveOutput = useMemo(
() =>
- isParsing || outputTooLarge
- ? undefined
- : decodeUnicodeInJson(outputParsed),
- [outputParsed, isParsing, outputTooLarge],
+ isParsing ? undefined : decodeIfWithinBudget(outputParsed, outputRows),
+ [outputParsed, outputRows, isParsing],
);
const effectiveMetadata = useMemo(
() =>
- isParsing || metadataTooLarge
+ isParsing
? undefined
- : decodeUnicodeInJson(metadataParsed),
- [metadataParsed, isParsing, metadataTooLarge],
+ : decodeIfWithinBudget(metadataParsed, metadataRows),
+ [metadataParsed, metadataRows, isParsing],
);
// Probe over-limit fields once for the bounded fallback (preview + download).
@@ -191,17 +219,29 @@ function IOPreviewJSONInner({
// 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).
+ // Probe the DECODED value (the same one the lazy viewer renders), so its
+ // serialized string is reused for BOTH the download and the byte engine β€” one
+ // JSON.stringify, not two (the lazy branch below passes `probe.serialized`).
const inputProbe = useMemo(
- () => (inputTooLarge ? probeJsonField(inputParsed) : null),
- [inputParsed, inputTooLarge],
+ () =>
+ inputTooLarge && effectiveInput !== undefined
+ ? probeJsonField(effectiveInput)
+ : null,
+ [effectiveInput, inputTooLarge],
);
const outputProbe = useMemo(
- () => (outputTooLarge ? probeJsonField(outputParsed) : null),
- [outputParsed, outputTooLarge],
+ () =>
+ outputTooLarge && effectiveOutput !== undefined
+ ? probeJsonField(effectiveOutput)
+ : null,
+ [effectiveOutput, outputTooLarge],
);
const metadataProbe = useMemo(
- () => (metadataTooLarge ? probeJsonField(metadataParsed) : null),
- [metadataParsed, metadataTooLarge],
+ () =>
+ metadataTooLarge && effectiveMetadata !== undefined
+ ? probeJsonField(effectiveMetadata)
+ : null,
+ [effectiveMetadata, metadataTooLarge],
);
// A gated field parses to undefined above but is not empty β€” it is too big.
@@ -235,7 +275,13 @@ function IOPreviewJSONInner({
metadataRows,
]);
- // Determine if virtualization is needed based on threshold
+ // Whether the eager MultiSectionJsonViewer must virtualize its own DOM. This
+ // is now ALWAYS false: a field with more rows than VIRTUALIZATION_THRESHOLD is
+ // gated to the lazy viewer above (so it contributes 0 to rowCounts), and a
+ // field with fewer never crosses the threshold. The eager virtualized path is
+ // effectively retired for trace I/O (it froze the tab at tens of thousands of
+ // nodes β€” LFE-10847); the residual small data renders eagerly non-virtualized.
+ // Left in place until that path is removed wholesale in a follow-up.
const needsVirtualization = useMemo(() => {
return (
rowCounts.input > VIRTUALIZATION_THRESHOLD ||
@@ -375,18 +421,51 @@ function IOPreviewJSONInner({
<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,
+ renderFooter: () => {
+ if (!probe) return null;
+ // A huge STRING (e.g. a base64 image) is a single leaf β€” the lazy tree
+ // adds nothing, so keep the bounded preview + download. A huge
+ // STRUCTURED value is where the eager tree-build froze the tab: render
+ // it through the lazy byte-engine viewer (main thread, no eager tree,
+ // cost proportional to what's expanded), with download as a secondary
+ // escape hatch.
+ if (probe.isString) {
+ return (
+ <LargeJsonFieldFallback
+ title={title}
+ hideTitle
+ serialized={probe.serialized}
+ isString={probe.isString}
+ charCount={probe.size}
+ rowCount={rowCount}
+ downloadFileBase={`${fieldKey}-${downloadName}`}
+ />
+ );
+ }
+ return (
+ <div className="io-message-content flex flex-col gap-1">
+ <div
+ style={{ height: 400 }}
+ className="overflow-hidden rounded-md border"
+ >
+ {/* Feed the byte engine the probe's serialized JSON, so the field
+ is stringified once (probe) and reused here β€” not a second time
+ inside the viewer. */}
+ <LazyJsonViewer serialized={probe.serialized} />
+ </div>
+ <LargeJsonFieldFallback
+ title={title}
+ hideTitle
+ serialized={probe.serialized}
+ isString={probe.isString}
+ charCount={probe.size}
+ rowCount={rowCount}
+ downloadFileBase={`${fieldKey}-${downloadName}`}
+ downloadOnly
+ />
+ </div>
+ );
+ },
});
const result = [];
@@ -433,7 +512,14 @@ function IOPreviewJSONInner({
// Add corrected output as footer when corrections are enabled
renderFooter: () => (
<CorrectedOutputField
- actualOutput={effectiveOutput}
+ // Don't hand the full oversized object to the diff dialog: it
+ // `JSON.stringify`s `actualOutput` unmemoized in its render body on
+ // every render (incl. every keystroke while editing a correction),
+ // which would re-serialize megabytes on exactly the large-output
+ // case this viewer gates. `actualOutputTooLarge` drives the
+ // "too large to diff" branch, so `undefined` here is sufficient
+ // (and `effectiveOutput` stays decoded for the lazy viewer/probe).
+ actualOutput={outputTooLarge ? undefined : effectiveOutput}
actualOutputTooLarge={outputTooLarge}
existingCorrection={outputCorrection}
observationId={observationId}
diff --git a/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx b/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
index 92f1bb2be8..982c0bafa6 100644
--- a/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
+++ b/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
@@ -31,6 +31,7 @@ export function LargeJsonFieldFallback({
rowCount,
downloadFileBase,
hideTitle = false,
+ downloadOnly = false,
}: {
title: string;
/** Pre-serialized content: raw text for string fields, compact JSON for
@@ -49,6 +50,10 @@ export function LargeJsonFieldFallback({
/** Omit the field-name heading β€” used when the surrounding section already
* renders the title (JSON Beta section footer). */
hideTitle?: boolean;
+ /** Render just the download escape hatch (size note + button), no "too large"
+ * message or preview. Used when the field IS being rendered lazily above and
+ * the download is only a secondary escape hatch. */
+ downloadOnly?: boolean;
}) {
const capture = usePostHogClientCapture();
@@ -78,6 +83,22 @@ export function LargeJsonFieldFallback({
downloadTextFile(serialized, `${downloadFileBase}.${extension}`, mimeType);
};
+ if (downloadOnly) {
+ // The field is being rendered lazily above; this is only the secondary
+ // escape hatch (raw download), so no "too large" message or preview.
+ return (
+ <div className="io-message-content">
+ <div className="text-muted-foreground flex items-center gap-2 px-1 py-1 text-xs">
+ <span>{sizeSummary}</span>
+ <Button variant="outline" size="sm" onClick={onDownload}>
+ <Download className="mr-1 h-3.5 w-3.5" />
+ Download {title}
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
return (
<div className="io-message-content">
<div className="my-2 flex flex-col gap-2 rounded-sm border border-dashed p-3">
diff --git a/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
index 3379216184..674f297814 100644
--- a/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
+++ b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
@@ -38,25 +38,25 @@
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.
+ * Row threshold at/above which a field in the JSON Beta view renders through the
+ * lazy byte-engine viewer (AdvancedJsonViewer/lazy) instead of the eager tree.
+ * Measured in fully-expanded rows (`countJsonRows`), NOT chars β€” a char limit is
+ * the wrong metric: a 20 MB single string (e.g. a base64 data-URI) is one node
+ * and renders instantly, while 20 MB of nested JSON is ~1M nodes.
*
- * 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.
+ * This equals the viewer's virtualization threshold on purpose: any field big
+ * enough to need windowing goes to the lazy viewer, whose cost is bounded to
+ * what's expanded/visible. There is NO safe "eager but virtualized" middle band.
+ * The old eager virtualized path (`buildMultiSectionTree` materializes every
+ * node, then React renders the whole node set synchronously on mount) froze the
+ * tab for minutes at only tens of thousands of nodes β€” e.g. a 44k-row
+ * big-number payload pegged the main thread ~4 min in dev (LFE-10847). So above
+ * this threshold we ALWAYS render lazily; below it a field is small enough to
+ * render eagerly inline. The raw download stays available as a secondary hatch.
+ *
+ * Keep in sync with `VIRTUALIZATION_THRESHOLD` in IOPreviewJSON (imported there).
*/
-export const JSON_VIEW_RENDER_ROW_LIMIT = 50_000;
+export const JSON_VIEW_RENDER_ROW_LIMIT = 3_333;
export interface JsonFieldProbe {
/** Serialized length in UTF-16 chars; drives the gating decision. */
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts
index 390148fca9..2388208fcb 100644
--- a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts
@@ -5,9 +5,14 @@
* counts, wide-container pagination + load-more, revision bumps on structural
* change, and on-demand value materialization (LFE-11080).
*/
+// The store reports genuine byte-engine failures to Sentry via reportError;
+// stub it so the error-capture tests can assert without touching Sentry.
+vi.mock("@/src/utils/reportError", () => ({ reportError: vi.fn() }));
+
import { createRowModelStore } from "./rowModelStore";
import { PAGE_SIZE } from "../treeRowModel";
import type { JsonRow, RowModel, RowWindow } from "../rowModel";
+import { reportError } from "@/src/utils/reportError";
const visibleRows = (
store: ReturnType<typeof createRowModelStore>,
@@ -268,3 +273,62 @@ describe("rowModelStore async correctness", () => {
expect(bExpand).not.toHaveBeenCalled();
});
});
+
+describe("rowModelStore error capture", () => {
+ beforeEach(() => {
+ vi.mocked(reportError).mockClear();
+ });
+
+ const okModel = (over: Partial<RowModel>): RowModel => ({
+ getRevision: () => 0,
+ getTotalVisible: () => 2,
+ getRows: async () => ({ revision: 0, rows: [makeRow(0)] }),
+ expand: async () => {},
+ collapse: async () => {},
+ loadMore: async () => {},
+ getValue: async () => ({
+ ok: true as const,
+ value: {
+ nodeId: 0,
+ type: "number" as const,
+ value: 0,
+ lossyNumber: false,
+ truncated: false,
+ byteLength: 1,
+ },
+ }),
+ ...over,
+ });
+
+ it("captures a byte-engine throw on expand and surfaces the error state", async () => {
+ // The per-container scan is deferred to expand, so a malformed-slice throw
+ // happens HERE, not at init β€” it must be reported, not swallowed.
+ const model = okModel({
+ expand: async () => {
+ throw new Error("byte scan failed");
+ },
+ });
+ const store = createRowModelStore({ buildModel: async () => model });
+ await store.getState().init(null);
+ expect(store.getState().status).toBe("ready");
+
+ await store.getState().toggle(0, false); // expand throws
+
+ expect(reportError).toHaveBeenCalledTimes(1);
+ expect(store.getState().status).toBe("error");
+ });
+
+ it("captures a getValue failure WITHOUT tearing down the viewer", async () => {
+ const model = okModel({
+ getValue: async () => ({ ok: false as const, error: "bad slice" }),
+ });
+ const store = createRowModelStore({ buildModel: async () => model });
+ await store.getState().init(null);
+
+ await store.getState().materialize(0);
+
+ expect(reportError).toHaveBeenCalledTimes(1);
+ // One leaf failing must not nuke the whole viewer.
+ expect(store.getState().status).toBe("ready");
+ });
+});
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
index b2333caa77..1f46c4afe6 100644
--- a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
@@ -28,6 +28,7 @@ import { createStore, type StoreApi } from "zustand/vanilla";
import { TreeRowModel } from "../treeRowModel";
import { sourceFromValue } from "../asyncJsonSource";
import type { JsonRow, RowModel, ValueResult } from "../rowModel";
+import { reportError } from "@/src/utils/reportError";
/** Rows fetched for the first paint before the virtualizer reports a range. */
export const INITIAL_ROW_COUNT = 200;
@@ -131,6 +132,21 @@ export function createRowModelStore(
await get().ensureRange(lastStart, lastCount);
};
+ /**
+ * A byte-engine / model failure is an our-code failure (a malformed index /
+ * unexpected shape), not an expected state β€” capture it and surface the
+ * error UI. The per-container scan is DEFERRED until expand, so this must be
+ * reachable from every mutation, not just the initial build. (skill:
+ * sentry-instrumentation.)
+ */
+ const captureAndSetError = (e: unknown) => {
+ reportError(e, { area: "json-viewer" });
+ set({
+ status: "error",
+ error: e instanceof Error ? e.message : String(e),
+ });
+ };
+
return {
status: "loading",
error: null,
@@ -166,10 +182,7 @@ export function createRowModelStore(
set({ status: "ready" });
} catch (e) {
if (gen !== myGen) return;
- set({
- status: "error",
- error: e instanceof Error ? e.message : String(e),
- });
+ captureAndSetError(e);
}
},
@@ -242,6 +255,10 @@ export function createRowModelStore(
}
if (gen !== callGen) return;
await refreshAfterMutation();
+ } catch (e) {
+ // Deferred per-container scan threw on expand β€” don't let serialize's
+ // rejection handler swallow it silently.
+ if (gen === callGen) captureAndSetError(e);
} finally {
if (gen === callGen) setPending(nodeId, false);
}
@@ -257,6 +274,9 @@ export function createRowModelStore(
await model.loadMore(loadMoreId);
if (gen !== callGen) return;
await refreshAfterMutation();
+ } catch (e) {
+ // Deferred scan of the next page threw β€” capture, don't swallow.
+ if (gen === callGen) captureAndSetError(e);
} finally {
if (gen === callGen) setPending(loadMoreId, false);
}
@@ -266,11 +286,23 @@ export function createRowModelStore(
materialize: async (nodeId, maxBytes) => {
if (!model) return;
const myGen = gen;
- const result = await model.getValue(nodeId, maxBytes);
- if (gen !== myGen) return;
- const next = new Map(get().values);
- next.set(nodeId, result);
- set({ values: next });
+ try {
+ const result = await model.getValue(nodeId, maxBytes);
+ if (gen !== myGen) return;
+ // getValue reports failures as data (ok:false). Surface a genuine
+ // materialization failure to Sentry, but do NOT tear down the whole
+ // viewer for one leaf β€” store the result and let the caller react.
+ if (!result.ok) {
+ reportError(new Error(result.error), { area: "json-viewer" });
+ }
+ const next = new Map(get().values);
+ next.set(nodeId, result);
+ set({ values: next });
+ } catch (e) {
+ // Defensive: the seam says getValue never throws, but a future source
+ // might. Report without tearing the viewer down.
+ if (gen === myGen) reportError(e, { area: "json-viewer" });
+ }
},
dispose: () => {