Skip to content

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

fix(trace): size-gate the unvirtualized JSON IO view (LFE-10989) (#15155)

Nikita Kabardin49420934cbe0
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx
new file mode 100644
index 0000000000..653d6c5923
--- /dev/null
+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.clienttest.tsx
@@ -0,0 +1,145 @@
+/**
+ * The JSON view must never hand a multi-MB field to the unvirtualized
+ * react18-json-view (LFE-10989). These tests pin the branch selection in
+ * IOPreviewJSONSimple: over-limit fields render the bounded fallback and skip
+ * PrettyJsonView entirely, while normal fields render exactly as before.
+ */
+import { fireEvent, render, screen } from "@testing-library/react";
+
+// PrettyJsonView is the unvirtualized render path we must NOT reach for
+// over-limit fields β€” mock it so its presence is observable by test id.
+vi.mock("@/src/components/ui/PrettyJsonView", () => ({
+ PrettyJsonView: (props: { title?: string }) => (
+ <div data-testid="pretty-json-view">{props.title}</div>
+ ),
+}));
+
+vi.mock("./components/CorrectedOutputField", () => ({
+ CorrectedOutputField: () => <div data-testid="corrected-output" />,
+}));
+
+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
+ usePostHogClientCapture: () => vi.fn(),
+}));
+
+// deepParseJson is the only runtime import from the shared barrel here; stub it
+// so the test stays light and deterministic (identity is fine for these cases).
+vi.mock("@langfuse/shared", () => ({
+ deepParseJson: (value: unknown) => value,
+}));
+
+import { IOPreviewJSONSimple } from "./IOPreviewJSONSimple";
+import { JSON_VIEW_RENDER_CHAR_LIMIT } from "./lib/jsonViewSizeGate";
+
+const FALLBACK_TEXT = /too large to render in JSON view/i;
+
+describe("IOPreviewJSONSimple size gating", () => {
+ it("renders the fallback and NOT PrettyJsonView for an over-limit field", () => {
+ const huge = "x".repeat(JSON_VIEW_RENDER_CHAR_LIMIT + 1);
+ render(
+ <IOPreviewJSONSimple
+ input={huge}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ // Fallback shown for the input field...
+ expect(screen.getByText(FALLBACK_TEXT)).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /Download Input/i }),
+ ).toBeInTheDocument();
+ // ...and the unvirtualized viewer was never mounted.
+ expect(screen.queryByTestId("pretty-json-view")).not.toBeInTheDocument();
+ });
+
+ it("downloads a string field as raw text (.txt), not JSON-wrapped", () => {
+ // The huge-IO seed is a base64 string; JSON.stringify-ing it would add
+ // quotes + escapes and over-encode the download. The fallback must write
+ // the raw text.
+ const rawString = "eyJhIjoxfQ==" + "A".repeat(JSON_VIEW_RENDER_CHAR_LIMIT);
+ const blobCalls: { part: string; type: string }[] = [];
+ let downloadName = "";
+
+ // Capture the exact content handed to the Blob (jsdom's Blob has no
+ // readable .text() in this env, so intercept at construction).
+ class MockBlob {
+ type: string;
+ constructor(parts: BlobPart[], opts?: BlobPropertyBag) {
+ this.type = opts?.type ?? "";
+ blobCalls.push({ part: String(parts[0]), type: this.type });
+ }
+ }
+ vi.stubGlobal("Blob", MockBlob);
+ vi.stubGlobal("URL", {
+ ...URL,
+ createObjectURL: vi.fn(() => "blob:mock"),
+ revokeObjectURL: vi.fn(),
+ });
+ // Capture the download filename and neutralize navigation.
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (
+ this: HTMLAnchorElement,
+ ) {
+ downloadName = this.download;
+ });
+
+ render(
+ <IOPreviewJSONSimple
+ input={rawString}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /Download Input/i }));
+
+ expect(blobCalls).toHaveLength(1);
+ expect(blobCalls[0].part).toBe(rawString); // raw, no surrounding quotes
+ expect(blobCalls[0].part.startsWith('"')).toBe(false);
+ expect(blobCalls[0].type).toContain("text/plain");
+ expect(downloadName).toBe("input-t.txt");
+
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("hides a null field with hideIfNull and shows no fallback", () => {
+ render(
+ <IOPreviewJSONSimple
+ input={null}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ expect(screen.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();
+ expect(screen.queryByTestId("pretty-json-view")).not.toBeInTheDocument();
+ });
+
+ it("renders PrettyJsonView (not the fallback) for normal small I/O", () => {
+ render(
+ <IOPreviewJSONSimple
+ input={{ messages: [{ role: "user", content: "hi" }] }}
+ hideOutput
+ hideIfNull
+ showCorrections={false}
+ projectId="p"
+ traceId="t"
+ />,
+ );
+
+ const viewers = screen.getAllByTestId("pretty-json-view");
+ expect(viewers).toHaveLength(1);
+ expect(viewers[0]).toHaveTextContent("Input");
+ expect(screen.queryByText(FALLBACK_TEXT)).not.toBeInTheDocument();
+ });
+});
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx
index 30992df3a2..21af5943bf 100644
--- a/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx
+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSONSimple.tsx
@@ -3,6 +3,11 @@ import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
import { type MediaReturnType } from "@/src/features/media/validation";
import { CorrectedOutputField } from "./components/CorrectedOutputField";
+import { LargeJsonFieldFallback } from "./components/LargeJsonFieldFallback";
+import {
+ JSON_VIEW_RENDER_CHAR_LIMIT,
+ probeJsonField,
+} from "./lib/jsonViewSizeGate";
export interface IOPreviewJSONSimpleProps {
input?: Prisma.JsonValue;
@@ -74,64 +79,112 @@ export function IOPreviewJSONSimple({
environment = "default",
showCorrections = true,
}: IOPreviewJSONSimpleProps) {
+ // Size-gate each field: the JSON view renders through react18-json-view,
+ // which is not virtualized, so multi-MB payloads freeze and crash the tab
+ // (LFE-10989). Probe the raw prop β€” it drives both the main-thread parse
+ // below and the tree the viewer would build β€” and above the limit render a
+ // bounded preview + download instead. The probe serializes an object field
+ // exactly once (memoized) and the resulting string is reused for the size
+ // check, the preview, and the download, so we never re-serialize the payload.
+ const inputProbe = useMemo(() => probeJsonField(input), [input]);
+ const outputProbe = useMemo(() => probeJsonField(output), [output]);
+ const metadataProbe = useMemo(() => probeJsonField(metadata), [metadata]);
+
+ const inputTooLarge = inputProbe.size > JSON_VIEW_RENDER_CHAR_LIMIT;
+ const outputTooLarge = outputProbe.size > JSON_VIEW_RENDER_CHAR_LIMIT;
+ const metadataTooLarge = metadataProbe.size > JSON_VIEW_RENDER_CHAR_LIMIT;
+
// Parse data if not pre-parsed
// IMPORTANT: Don't parse while isParsing=true to avoid double-parsing with different object references
+ // Skip parsing entirely for over-limit fields: parsing a ~20 MB string in
+ // deepParseJson (parsePreservingPrecision) blocks the main thread for seconds.
const effectiveInput = useMemo(() => {
if (isParsing) return undefined; // Wait for Web Worker to finish
+ if (inputTooLarge) return undefined;
return parsedInput ?? deepParseJson(input);
- }, [parsedInput, input, isParsing]);
+ }, [parsedInput, input, isParsing, inputTooLarge]);
const effectiveOutput = useMemo(() => {
if (isParsing) return undefined;
+ if (outputTooLarge) return undefined;
return parsedOutput ?? deepParseJson(output);
- }, [parsedOutput, output, isParsing]);
+ }, [parsedOutput, output, isParsing, outputTooLarge]);
const effectiveMetadata = useMemo(() => {
if (isParsing) return undefined;
+ if (metadataTooLarge) return undefined;
return parsedMetadata ?? deepParseJson(metadata);
- }, [parsedMetadata, metadata, isParsing]);
+ }, [parsedMetadata, metadata, isParsing, metadataTooLarge]);
+
+ // An over-limit field parses to `undefined` above, but it 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));
+ const showOutput =
+ !hideOutput && (outputTooLarge || !(hideIfNull && !effectiveOutput));
+ const showMetadata = metadataTooLarge || !(hideIfNull && !effectiveMetadata);
- const showInput = !hideInput && !(hideIfNull && !effectiveInput);
- const showOutput = !hideOutput && !(hideIfNull && !effectiveOutput);
- const showMetadata = !(hideIfNull && !effectiveMetadata);
+ const downloadName = observationId ?? traceId;
return (
<div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
- {showInput && (
- <PrettyJsonView
- title="Input"
- json={input}
- parsedJson={effectiveInput}
- isLoading={isLoading}
- isParsing={isParsing}
- media={media?.filter((m) => m.field === "input") ?? []}
- currentView="json"
- externalExpansionState={inputExpanded}
- // Cast: PrettyJsonView accepts union type, but JSON view only uses boolean
- onExternalExpansionChange={
- onInputExpandedChange as (
- expansion: boolean | Record<string, boolean>,
- ) => void
- }
- />
- )}
- {showOutput && (
- <PrettyJsonView
- title="Output"
- json={output}
- parsedJson={effectiveOutput}
- isLoading={isLoading}
- isParsing={isParsing}
- media={media?.filter((m) => m.field === "output") ?? []}
- currentView="json"
- externalExpansionState={outputExpanded}
- onExternalExpansionChange={
- onOutputExpandedChange as (
- expansion: boolean | Record<string, boolean>,
- ) => void
- }
- />
- )}
+ {showInput &&
+ (inputTooLarge ? (
+ <LargeJsonFieldFallback
+ title="Input"
+ serialized={inputProbe.serialized}
+ isString={inputProbe.isString}
+ charCount={inputProbe.size}
+ downloadFileBase={`input-${downloadName}`}
+ />
+ ) : (
+ <PrettyJsonView
+ title="Input"
+ json={input}
+ parsedJson={effectiveInput}
+ isLoading={isLoading}
+ isParsing={isParsing}
+ media={media?.filter((m) => m.field === "input") ?? []}
+ currentView="json"
+ externalExpansionState={inputExpanded}
+ // Cast: PrettyJsonView accepts union type, but JSON view only uses boolean
+ onExternalExpansionChange={
+ onInputExpandedChange as (
+ expansion: boolean | Record<string, boolean>,
+ ) => void
+ }
+ />
+ ))}
+ {showOutput &&
+ (outputTooLarge ? (
+ <LargeJsonFieldFallback
+ title="Output"
+ serialized={outputProbe.serialized}
+ isString={outputProbe.isString}
+ charCount={outputProbe.size}
+ downloadFileBase={`output-${downloadName}`}
+ />
+ ) : (
+ <PrettyJsonView
+ title="Output"
+ json={output}
+ parsedJson={effectiveOutput}
+ isLoading={isLoading}
+ isParsing={isParsing}
+ media={media?.filter((m) => m.field === "output") ?? []}
+ currentView="json"
+ externalExpansionState={outputExpanded}
+ onExternalExpansionChange={
+ onOutputExpandedChange as (
+ expansion: boolean | Record<string, boolean>,
+ ) => void
+ }
+ />
+ ))}
+ {/* 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. */}
{showCorrections && (
<CorrectedOutputField
actualOutput={effectiveOutput}
@@ -142,23 +195,32 @@ export function IOPreviewJSONSimple({
environment={environment}
/>
)}
- {showMetadata && (
- <PrettyJsonView
- title="Metadata"
- json={metadata}
- parsedJson={effectiveMetadata}
- isLoading={isLoading}
- isParsing={isParsing}
- media={media?.filter((m) => m.field === "metadata") ?? []}
- currentView="json"
- externalExpansionState={metadataExpanded}
- onExternalExpansionChange={
- onMetadataExpandedChange as (
- expansion: boolean | Record<string, boolean>,
- ) => void
- }
- />
- )}
+ {showMetadata &&
+ (metadataTooLarge ? (
+ <LargeJsonFieldFallback
+ title="Metadata"
+ serialized={metadataProbe.serialized}
+ isString={metadataProbe.isString}
+ charCount={metadataProbe.size}
+ downloadFileBase={`metadata-${downloadName}`}
+ />
+ ) : (
+ <PrettyJsonView
+ title="Metadata"
+ json={metadata}
+ parsedJson={effectiveMetadata}
+ isLoading={isLoading}
+ isParsing={isParsing}
+ media={media?.filter((m) => m.field === "metadata") ?? []}
+ currentView="json"
+ externalExpansionState={metadataExpanded}
+ onExternalExpansionChange={
+ onMetadataExpandedChange as (
+ expansion: boolean | Record<string, boolean>,
+ ) => void
+ }
+ />
+ ))}
</div>
);
}
diff --git a/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx b/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
new file mode 100644
index 0000000000..c0fb5dabc8
--- /dev/null
+++ b/web/src/components/trace/components/IOPreview/components/LargeJsonFieldFallback.tsx
@@ -0,0 +1,103 @@
+import { useMemo } from "react";
+import { Download } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import { compactNumberFormatter } from "@/src/utils/numbers";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+
+/** How much of the raw payload the preview head shows. Bounded regardless of
+ * payload size β€” the full value is reachable via download or the other views. */
+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.
+ *
+ * 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
+ * preview slice and the download. Re-serializing a ~20 MB object here would
+ * partly defeat the gate.
+ */
+export function LargeJsonFieldFallback({
+ title,
+ serialized,
+ isString,
+ charCount,
+ downloadFileBase,
+}: {
+ title: string;
+ /** Pre-serialized content: raw text for string fields, compact JSON for
+ * objects. Used as-is for both the preview and the download. */
+ serialized: string;
+ /** True when the source value was a string β€” downloads as raw .txt so
+ * base64/plain payloads are not quote/escape-wrapped; objects use .json. */
+ isString: boolean;
+ charCount: number;
+ /** File name without extension. */
+ downloadFileBase: string;
+}) {
+ const capture = usePostHogClientCapture();
+
+ const previewText = useMemo(
+ () =>
+ serialized.length > PREVIEW_DISPLAY_CHARS
+ ? serialized.slice(0, PREVIEW_DISPLAY_CHARS)
+ : serialized,
+ [serialized],
+ );
+
+ const onDownload = () => {
+ capture("trace_detail:json_view_large_field_download");
+ // Reuse the already-serialized string as-is: raw text for strings (never
+ // JSON-quoted), compact JSON for objects. No re-serialization here.
+ const extension = isString ? "txt" : "json";
+ const mimeType = isString
+ ? "text/plain; charset=utf-8"
+ : "application/json; charset=utf-8";
+ downloadTextFile(serialized, `${downloadFileBase}.${extension}`, mimeType);
+ };
+
+ 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">
+ <span className="text-foreground font-medium">{title}</span>
+ <span>
+ {compactNumberFormatter(charCount, 1)} characters β€” 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-medium">Formatted</span> or{" "}
+ <span className="font-medium">JSON Beta</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">
+ {previewText}
+ </pre>
+ <div>
+ <Button variant="outline" size="sm" onClick={onDownload}>
+ <Download className="mr-1 h-3.5 w-3.5" />
+ Download {title}
+ </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/trace/components/IOPreview/lib/jsonViewSizeGate.clienttest.ts b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.clienttest.ts
new file mode 100644
index 0000000000..2a3084d40d
--- /dev/null
+++ b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.clienttest.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ JSON_VIEW_RENDER_CHAR_LIMIT,
+ probeJsonField,
+} from "./jsonViewSizeGate";
+
+// The component gates a field with `probeJsonField(x).size > JSON_VIEW_RENDER_CHAR_LIMIT`.
+const isTooLarge = (value: unknown): boolean =>
+ probeJsonField(value).size > JSON_VIEW_RENDER_CHAR_LIMIT;
+
+describe("jsonViewSizeGate", () => {
+ describe("probeJsonField", () => {
+ it("reports size 0 and no serialization for null / undefined", () => {
+ expect(probeJsonField(null)).toEqual({
+ size: 0,
+ serialized: "",
+ isString: false,
+ });
+ expect(probeJsonField(undefined)).toEqual({
+ size: 0,
+ serialized: "",
+ isString: false,
+ });
+ });
+
+ it("passes strings through raw, without JSON-quoting", () => {
+ expect(probeJsonField("hello")).toEqual({
+ size: 5,
+ serialized: "hello",
+ isString: true,
+ });
+ // A base64-ish string is returned verbatim (no surrounding quotes).
+ const b64 = "eyJhIjoxfQ==";
+ const probe = probeJsonField(b64);
+ expect(probe.serialized).toBe(b64);
+ expect(probe.isString).toBe(true);
+ });
+
+ it("serializes objects and arrays exactly once (compact JSON)", () => {
+ const obj = { a: 1, b: "two" };
+ const probe = probeJsonField(obj);
+ expect(probe.serialized).toBe(JSON.stringify(obj));
+ expect(probe.size).toBe(JSON.stringify(obj).length);
+ expect(probe.isString).toBe(false);
+
+ const arr = [1, 2, 3];
+ expect(probeJsonField(arr).serialized).toBe(JSON.stringify(arr));
+ });
+
+ it("calls JSON.stringify only once per object (no double serialization)", () => {
+ const spy = vi.spyOn(JSON, "stringify");
+ const obj = { nested: { deep: [1, 2, 3] } };
+ probeJsonField(obj);
+ expect(spy).toHaveBeenCalledTimes(1);
+ spy.mockRestore();
+ });
+
+ it("reports size 0 for values that cannot be serialized (circular)", () => {
+ const circular: Record<string, unknown> = {};
+ circular.self = circular;
+ expect(probeJsonField(circular)).toEqual({
+ size: 0,
+ serialized: "",
+ isString: false,
+ });
+ });
+ });
+
+ describe("gating decision (size vs JSON_VIEW_RENDER_CHAR_LIMIT)", () => {
+ it("does not gate normal, small I/O", () => {
+ expect(isTooLarge(null)).toBe(false);
+ expect(isTooLarge("short string")).toBe(false);
+ expect(isTooLarge({ messages: [{ role: "user" }] })).toBe(false);
+ });
+
+ it("gates a payload over the limit", () => {
+ const huge = "x".repeat(JSON_VIEW_RENDER_CHAR_LIMIT + 1);
+ expect(isTooLarge(huge)).toBe(true);
+ });
+
+ it("does not gate exactly at the limit (strictly greater-than)", () => {
+ const atLimit = "x".repeat(JSON_VIEW_RENDER_CHAR_LIMIT);
+ expect(isTooLarge(atLimit)).toBe(false);
+ });
+
+ it("gates a ~20 MB payload (the measured crash target)", () => {
+ const twentyMb = "x".repeat(20_000_000);
+ expect(isTooLarge(twentyMb)).toBe(true);
+ });
+
+ it("keeps the limit conservative (well above KB-scale, safely below ~20 MB)", () => {
+ expect(JSON_VIEW_RENDER_CHAR_LIMIT).toBe(2_000_000);
+ expect(JSON_VIEW_RENDER_CHAR_LIMIT).toBeGreaterThan(500_000);
+ expect(JSON_VIEW_RENDER_CHAR_LIMIT).toBeLessThan(20_000_000);
+ });
+ });
+});
diff --git a/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
new file mode 100644
index 0000000000..9b200c3e15
--- /dev/null
+++ b/web/src/components/trace/components/IOPreview/lib/jsonViewSizeGate.ts
@@ -0,0 +1,70 @@
+/**
+ * Size gate for the unvirtualized "JSON" IO view (LFE-10989, part of the
+ * LFE-10152 large-traces work).
+ *
+ * The plain "JSON" view renders the whole payload through react18-json-view,
+ * which is NOT virtualized: every node becomes DOM. Multi-megabyte I/O both
+ * blocks the main thread while parsing (`parsePreservingPrecision`) and builds
+ * enough nodes to crash the renderer. Measured on the `lfe10152-json-trace`
+ * seed: ~20 MB I/O deterministically crashes the tab, with multi-second parse
+ * freezes.
+ *
+ * This helper decides, from a single serialized probe, whether a field is too
+ * large to render in that unvirtualized viewer. Above the limit the caller
+ * shows a bounded fallback (preview head + download) and skips both the
+ * main-thread parse and the full render. Normal I/O (KB-scale) is untouched.
+ *
+ * `probeJsonField` serializes an object field exactly once and returns that
+ * string alongside its length, so the size check, the preview head, and the
+ * download all share one `JSON.stringify` β€” never re-serializing the payload
+ * (which would partly defeat the gate). String fields are never serialized.
+ */
+
+/**
+ * Character ceiling for rendering a single field in the unvirtualized JSON
+ * view. This measures UTF-16 string length (`.length`), i.e. chars, not bytes.
+ * 2M chars is chosen deliberately:
+ * - The codebase's own safe main-thread parse bounds are 300–500 KB
+ * (`PrettyJsonView` / worker `maxSize`); 2M is ~4–6Γ— above those, so it stays
+ * well inside "the main thread can survive this once" territory.
+ * - Still 100–1000Γ— larger than typical trace I/O (KB-scale), so real traces
+ * are never gated and keep rendering instantly.
+ * - Below the size where the unvirtualized clone + re-parse + DOM render
+ * becomes a perceptible (~1s+) freeze, and far below the measured ~20 MB
+ * deterministic-crash point.
+ * Users keep full access to large payloads via the Formatted view (lazy
+ * table), the JSON Beta view (virtualized), and the raw download.
+ */
+export const JSON_VIEW_RENDER_CHAR_LIMIT = 2_000_000;
+
+export interface JsonFieldProbe {
+ /** Serialized length in UTF-16 chars; drives the gating decision. */
+ size: number;
+ /** The value as text β€” the raw string for string fields, compact JSON for
+ * objects/arrays, "" for null/undefined or on serialization failure. Reused
+ * for the fallback's preview slice and download so nothing re-serializes. */
+ serialized: string;
+ /** Whether the source value was already a string (raw text, no JSON quotes). */
+ isString: boolean;
+}
+
+/**
+ * Serialize a field once and report its size. Strings pass through as-is
+ * (instant, no JSON quoting); objects/arrays are `JSON.stringify`-d a single
+ * time. Null/undefined and unserializable values (e.g. circular) report size 0,
+ * so they are never gated and never produce an empty download.
+ */
+export function probeJsonField(value: unknown): JsonFieldProbe {
+ if (value === null || value === undefined) {
+ return { size: 0, serialized: "", isString: false };
+ }
+ if (typeof value === "string") {
+ return { size: value.length, serialized: value, isString: true };
+ }
+ try {
+ const serialized = JSON.stringify(value) ?? "";
+ return { size: serialized.length, serialized, isString: false };
+ } catch {
+ return { size: 0, serialized: "", isString: false };
+ }
+}
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 1b13834d9d..4adaea0ad3 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -44,6 +44,9 @@ export const events = {
// Fired from the tree, timeline, graph, and search-result click handlers;
// `source` says which surface drove the navigation.
"node_selected",
+ // 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",
],
// The shared table peek panel (opened via the `peek` URL param). Props carry
// `routePattern` (the Next.js route pattern, never a concrete URL) so opens