Skip to content

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

feat(trace): perf telemetry for the lazy JSON viewer (LFE-14419) (#15422)

Nikita Kabardinf6ce268248cb
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer.tsx
index 9afcaa9336..2fd93216ed 100644
--- a/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/LazyJsonViewer.tsx
@@ -19,9 +19,68 @@ import { useStore } from "zustand";
import Spinner from "@/src/components/design-system/Spinner/Spinner";
import { cn } from "@/src/utils/tailwind";
import { LazyJsonList } from "./LazyJsonList";
-import { createRowModelStore } from "./rowModelStore";
+import { createRowModelStore, type LazyViewerMetric } from "./rowModelStore";
import { TreeRowModel } from "../treeRowModel";
import { sourceFromSerialized } from "../asyncJsonSource";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { reportError } from "@/src/utils/reportError";
+
+// Provisional main-thread budgets (LFE-14419) β€” the telemetry exists to LEARN
+// the right thresholds from prod, so treat these as starting guesses. An index
+// or expand slower than these means our size gate let through more than the main
+// thread handles comfortably.
+const MAIN_THREAD_INDEX_BUDGET_MS = 1000;
+const SLOW_EXPAND_BUDGET_MS = 500;
+
+// A main-thread build blowing its budget means the size gate is miscalibrated β€”
+// an actionable, our-code signal. This is the sentry skill's one allowed bend of
+// "expected states are not events": it fires only when our heuristic was wrong,
+// and is rate-limited to once per session (module scope) so it never floods.
+let miscalibrationReported = false;
+
+/** Turn the store's raw perf signals into analytics + a miscalibration alarm.
+ * Metadata only β€” sizes/durations/counts, never payload content. */
+function handleMetric(
+ capture: ReturnType<typeof usePostHogClientCapture>,
+ sizeChars: number | undefined,
+ metric: LazyViewerMetric,
+): void {
+ if (metric.kind === "indexed") {
+ capture("json_viewer:indexed", {
+ buildMs: Math.round(metric.buildMs),
+ rowCount: metric.rowCount,
+ sizeChars,
+ tier: "main",
+ });
+ if (
+ metric.buildMs > MAIN_THREAD_INDEX_BUDGET_MS &&
+ !miscalibrationReported
+ ) {
+ miscalibrationReported = true;
+ reportError(
+ new Error("lazy JSON viewer: main-thread index exceeded budget"),
+ {
+ area: "json-viewer",
+ extra: {
+ buildMs: Math.round(metric.buildMs),
+ sizeChars,
+ rowCount: metric.rowCount,
+ budgetMs: MAIN_THREAD_INDEX_BUDGET_MS,
+ },
+ },
+ );
+ }
+ return;
+ }
+ // expand β€” capture only slow ones (budget-gated β†’ naturally rare, not noise).
+ if (metric.ms > SLOW_EXPAND_BUDGET_MS) {
+ capture("json_viewer:slow_expand", {
+ expandMs: Math.round(metric.ms),
+ sizeChars,
+ tier: "main",
+ });
+ }
+}
export interface LazyJsonViewerProps {
/**
@@ -51,16 +110,25 @@ export function LazyJsonViewer({
// document passed to init is that string (see below). `useState` reads props
// once on mount, which is fine: a given mount is one mode.
const usesSerialized = serialized !== undefined;
- const [store] = useState(() =>
- createRowModelStore(
- usesSerialized
+ // `capture` is a stable useCallback, so capturing it once in the store's lazy
+ // initializer is safe (no stale-closure risk).
+ const capture = usePostHogClientCapture();
+ const [store] = useState(() => {
+ const sizeChars = usesSerialized
+ ? (serialized as string).length
+ : undefined;
+ const onMetric = (metric: LazyViewerMetric) =>
+ handleMetric(capture, sizeChars, metric);
+ return createRowModelStore({
+ ...(usesSerialized
? {
- buildModel: (doc) =>
+ buildModel: (doc: unknown) =>
TreeRowModel.create(sourceFromSerialized(doc as string)),
}
- : undefined,
- ),
- );
+ : {}),
+ onMetric,
+ });
+ });
// The document identity re-init keys on: the serialized string, or the value.
const doc = usesSerialized ? serialized : value;
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 2388208fcb..ebfb009f1c 100644
--- a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.clienttest.ts
@@ -9,7 +9,7 @@
// 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 { createRowModelStore, type LazyViewerMetric } from "./rowModelStore";
import { PAGE_SIZE } from "../treeRowModel";
import type { JsonRow, RowModel, RowWindow } from "../rowModel";
import { reportError } from "@/src/utils/reportError";
@@ -71,6 +71,36 @@ describe("rowModelStore", () => {
expect(store.getState().totalVisible).toBe(3);
});
+ it("emits an `indexed` perf metric once the first window is ready (LFE-14419)", async () => {
+ const metrics: LazyViewerMetric[] = [];
+ const store = createRowModelStore({ onMetric: (m) => metrics.push(m) });
+ await store.getState().init({ a: 1, b: [10, 20, 30] });
+
+ const indexed = metrics.filter((m) => m.kind === "indexed");
+ expect(indexed).toHaveLength(1);
+ expect(indexed[0]).toMatchObject({ kind: "indexed", rowCount: 3 });
+ // buildMs is a real, non-negative duration (time-to-first-row).
+ expect((indexed[0] as { buildMs: number }).buildMs).toBeGreaterThanOrEqual(
+ 0,
+ );
+ });
+
+ it("emits an `expand` metric on expand but not on collapse (LFE-14419)", async () => {
+ const metrics: LazyViewerMetric[] = [];
+ const store = createRowModelStore({ onMetric: (m) => metrics.push(m) });
+ await store.getState().init({ a: 1, b: [10, 20, 30] });
+
+ const b = findRow(store, "b")!;
+ await store.getState().toggle(b.nodeId, false); // expand
+ await store.getState().toggle(b.nodeId, true); // collapse
+
+ // Expand pays the deferred per-container scan and is measured; collapse has
+ // no scan and emits nothing.
+ const expands = metrics.filter((m) => m.kind === "expand");
+ expect(expands).toHaveLength(1);
+ expect((expands[0] as { ms: number }).ms).toBeGreaterThanOrEqual(0);
+ });
+
it("load-more reveals the next page and drops the load-more row when drained", async () => {
const store = createRowModelStore();
await store.getState().init(Array.from({ length: 150 }, (_, i) => i));
diff --git a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
index 1f46c4afe6..090420138d 100644
--- a/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
+++ b/web/src/components/ui/AdvancedJsonViewer/lazy/react/rowModelStore.ts
@@ -67,6 +67,20 @@ export interface RowModelState {
export type RowModelStore = StoreApi<RowModelState>;
+/**
+ * Perf signals the store measures and hands to the view boundary (LFE-14419).
+ * The store only MEASURES; what to do with the numbers (PostHog capture, a
+ * miscalibration alarm) is a telemetry policy that lives in the React boundary.
+ * - `indexed`: emitted once when the first window is ready β€” `buildMs` is
+ * effectively time-to-first-row (build + first page) on whatever tier ran.
+ * - `expand`: emitted per container expand β€” `ms` covers the byte engine's
+ * deferred per-container scan, i.e. the cost a wide container pays on first
+ * open. The boundary decides which are "slow" enough to report.
+ */
+export type LazyViewerMetric =
+ | { kind: "indexed"; buildMs: number; rowCount: number }
+ | { kind: "expand"; ms: number };
+
export interface RowModelStoreOptions {
/**
* How to build the model for a value. Defaults to the in-memory path
@@ -76,6 +90,11 @@ export interface RowModelStoreOptions {
* responses the in-process source cannot express.
*/
buildModel?: (value: unknown) => Promise<RowModel>;
+ /**
+ * Perf-signal sink (LFE-14419). Called with timing facts; the boundary turns
+ * them into analytics/alarms. No-op by default.
+ */
+ onMetric?: (metric: LazyViewerMetric) => void;
}
export function createRowModelStore(
@@ -84,6 +103,7 @@ export function createRowModelStore(
const buildModel =
options.buildModel ??
((value: unknown) => TreeRowModel.create(sourceFromValue(value)));
+ const emitMetric = options.onMetric ?? (() => {});
// Non-reactive internals live in the factory closure, not in store state:
// they must not trigger renders and must survive across actions.
let model: RowModel | null = null;
@@ -159,6 +179,7 @@ export function createRowModelStore(
init: async (value) => {
const myGen = ++gen;
model = null;
+ const startedAt = performance.now();
set({
status: "loading",
error: null,
@@ -180,6 +201,13 @@ export function createRowModelStore(
await get().ensureRange(0, INITIAL_ROW_COUNT);
if (gen !== myGen) return;
set({ status: "ready" });
+ // Build + first window = time-to-first-row; the boundary retunes the
+ // size gate from this and alarms if it blew the main-thread budget.
+ emitMetric({
+ kind: "indexed",
+ buildMs: performance.now() - startedAt,
+ rowCount: get().totalVisible,
+ });
} catch (e) {
if (gen !== myGen) return;
captureAndSetError(e);
@@ -247,6 +275,7 @@ export function createRowModelStore(
return serialize(async () => {
if (!model || gen !== callGen) return;
setPending(nodeId, true);
+ const startedAt = performance.now();
try {
if (currentlyExpanded) {
await model.collapse(nodeId);
@@ -255,6 +284,12 @@ export function createRowModelStore(
}
if (gen !== callGen) return;
await refreshAfterMutation();
+ // Expand pays the byte engine's deferred per-container scan (a wide
+ // container's O(N) cost lands here); measure it so the boundary can
+ // flag slow expands. Collapse has no scan β€” don't bother.
+ if (!currentlyExpanded) {
+ emitMetric({ kind: "expand", ms: performance.now() - startedAt });
+ }
} catch (e) {
// Deferred per-container scan threw on expand β€” don't let serialize's
// rejection handler swallow it silently.
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 18389e3905..b9b1ccd5ef 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -57,6 +57,10 @@ export const events = {
// can be sliced by surface without leaking ids.
peek: ["opened", "closed", "expand_toggle", "resized", "open_in_new_tab"],
generations: ["export"],
+ // Lazy JSON viewer perf telemetry (LFE-14419): learn whether the size gate
+ // and main-thread assumptions hold on real payloads. Metadata only β€”
+ // durations, char counts, tier; never payload content.
+ json_viewer: ["indexed", "slow_expand"],
saved_views: [
"create",
"update",