Skip to content

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

fix(trace): budget aggregated graph layout so dense traces can't freeze the tab (LFE-10988) (#15153)

Nikita Kabardin0febc33a0fb4
diff --git a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx
index 87daa7e072..5f13038148 100644
--- a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx
+++ b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx
@@ -38,6 +38,12 @@ type ElkGraphRendererProps = {
activeNodeNames?: ReadonlySet<string> | null;
/** Layer direction: DOWN (default) or RIGHT (long expanded chains). */
layoutDirection?: GraphLayoutDirection;
+ /**
+ * Recovery action for the "too large to lay out" notice: switch to the
+ * budget-exempt expanded view, which can render the same trace. Omitted when
+ * no view switch is available (or the view is already expanded).
+ */
+ onShowExpanded?: (() => void) | null;
};
type Transform = { x: number; y: number; k: number };
@@ -85,6 +91,7 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({
currentObservationIndices = {},
activeNodeNames = null,
layoutDirection = "DOWN",
+ onShowExpanded = null,
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const worldRef = useRef<HTMLDivElement>(null);
@@ -352,8 +359,39 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({
</Button>
</div>
)}
+ {layout?.tooLarge && (
+ // Budget exceeded: ELK was skipped rather than freeze the tab. No retry
+ // β€” it would just wedge again. Point the user at the tree/timeline.
+ <div className="text-muted-foreground absolute inset-0 flex flex-col items-center justify-center gap-1 px-4 text-center text-sm">
+ <span>
+ This graph is too large to lay out
+ {layout.nodeCount != null && layout.edgeCount != null
+ ? ` (${layout.nodeCount.toLocaleString()} nodes, ${layout.edgeCount.toLocaleString()} connections)`
+ : ""}
+ .
+ </span>
+ <span>
+ Try the{" "}
+ {onShowExpanded ? (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation(); // don't treat as a canvas deselect
+ onShowExpanded();
+ }}
+ className="text-primary underline underline-offset-2 hover:opacity-80"
+ >
+ expanded graph
+ </button>
+ ) : (
+ "expanded graph"
+ )}
+ , tree, or timeline view to explore this trace.
+ </span>
+ </div>
+ )}
- {layout && (
+ {layout && !layout.tooLarge && (
<div
ref={worldRef}
className="absolute top-0 left-0 origin-top-left"
diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
index beb9433e90..b134550194 100644
--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx
+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
@@ -337,6 +337,14 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
// Expanded runs are long chains — left→right reads like a
// timeline and fits the wide graph panel far better than top-down.
layoutDirection={isExpanded ? "RIGHT" : "DOWN"}
+ // Only the aggregated (DOWN) layout hits the size budget; when it
+ // does, offer the budget-exempt expanded view as the in-place
+ // recovery (it renders the same trace as an acyclic DAG).
+ onShowExpanded={
+ onViewModeChange && !isExpanded
+ ? () => onViewModeChange("expanded")
+ : null
+ }
/>
)}
{onViewModeChange && (
diff --git a/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts b/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts
index 21ccb31273..f235418956 100644
--- a/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts
+++ b/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts
@@ -1,5 +1,10 @@
import { type GraphCanvasData, type GraphNodeData } from "../types";
-import { computeGraphLayout } from "./elkLayout";
+import {
+ computeGraphLayout,
+ dedupeEdges,
+ MAX_GRAPH_LAYOUT_EDGES,
+ MAX_GRAPH_LAYOUT_NODES,
+} from "./elkLayout";
const node = (id: string): GraphNodeData => ({ id, label: id, type: "AGENT" });
@@ -74,3 +79,139 @@ describe("computeGraphLayout", () => {
expect(multiWidth).toBeGreaterThan(singleWidth);
});
});
+
+describe("dedupeEdges", () => {
+ it("collapses duplicate (from,to) pairs and drops self-loops", () => {
+ const result = dedupeEdges([
+ { from: "a", to: "b" },
+ { from: "a", to: "b" },
+ { from: "b", to: "a" }, // reverse is distinct
+ { from: "c", to: "c" }, // self-loop
+ ]);
+ expect(result).toEqual([
+ { from: "a", to: "b" },
+ { from: "b", to: "a" },
+ ]);
+ });
+
+ it("does not collide edges whose ids would merge when space-joined", () => {
+ const result = dedupeEdges([
+ { from: "a b", to: "c" },
+ { from: "a", to: "b c" },
+ ]);
+ expect(result).toHaveLength(2);
+ });
+});
+
+describe("computeGraphLayout layout budget", () => {
+ // A dense cyclic aggregated graph freezes ELK (measured: 100 nodes/800 edges
+ // β‰ˆ 177s on the main thread, a real trace fed ~1,400 edges froze >110s). ELK
+ // is synchronous, so the only safe fix is to refuse the layout up front.
+
+ // `edgeCount` distinct directed edges among the first `nodeCount` node ids
+ // (no self-loops) β€” a dense graph, but edge endpoints stay within the nodes.
+ const denseEdges = (
+ nodeCount: number,
+ edgeCount: number,
+ ): GraphCanvasData["edges"] => {
+ const edges: GraphCanvasData["edges"] = [];
+ for (let a = 0; a < nodeCount && edges.length < edgeCount; a++) {
+ for (let b = 0; b < nodeCount && edges.length < edgeCount; b++) {
+ if (a !== b) edges.push({ from: `n${a}`, to: `n${b}` });
+ }
+ }
+ return edges;
+ };
+
+ // A sparse acyclic chain of `edgeCount` edges over edgeCount+1 nodes β€” lays
+ // out in milliseconds even past the edge budget, so boundary/exempt cases
+ // stay fast.
+ const chain = (edgeCount: number): GraphCanvasData => ({
+ nodes: Array.from({ length: edgeCount + 1 }, (_, i) => node(`n${i}`)),
+ edges: Array.from({ length: edgeCount }, (_, i) => ({
+ from: `n${i}`,
+ to: `n${i + 1}`,
+ })),
+ });
+
+ it("refuses an over-budget aggregated (DOWN) graph without running ELK", async () => {
+ const count = MAX_GRAPH_LAYOUT_EDGES + 10;
+ const nodes = Array.from({ length: 60 }, (_, i) => node(`n${i}`));
+ const graph: GraphCanvasData = { nodes, edges: denseEdges(60, count) };
+
+ // If ELK actually ran on this dense graph the test would hang for minutes;
+ // the budget must make it return near-instantly.
+ const start = Date.now();
+ const layout = await computeGraphLayout(graph, {}, "DOWN");
+ expect(Date.now() - start).toBeLessThan(1000);
+
+ expect(layout.tooLarge).toBe(true);
+ expect(layout.nodes).toHaveLength(0);
+ expect(layout.edges).toHaveLength(0);
+ expect(layout.edgeCount).toBe(count);
+ });
+
+ it("refuses an aggregated graph with too many nodes", async () => {
+ const nodes = Array.from({ length: MAX_GRAPH_LAYOUT_NODES + 1 }, (_, i) =>
+ node(`n${i}`),
+ );
+ const graph: GraphCanvasData = {
+ nodes,
+ edges: [{ from: "n0", to: "n1" }],
+ };
+
+ const layout = await computeGraphLayout(graph, {}, "DOWN");
+ expect(layout.tooLarge).toBe(true);
+ expect(layout.nodeCount).toBe(MAX_GRAPH_LAYOUT_NODES + 1);
+ });
+
+ it("lays out a DOWN graph exactly AT the edge budget (the > boundary)", async () => {
+ // The gate is strictly greater-than, so exactly MAX edges is allowed.
+ const layout = await computeGraphLayout(
+ chain(MAX_GRAPH_LAYOUT_EDGES),
+ {},
+ "DOWN",
+ );
+ expect(layout.tooLarge).toBeFalsy();
+ expect(layout.nodes.length).toBeGreaterThan(0);
+ });
+
+ it("lays out a DOWN graph exactly AT the node budget (the > boundary)", async () => {
+ const nodes = Array.from({ length: MAX_GRAPH_LAYOUT_NODES }, (_, i) =>
+ node(`n${i}`),
+ );
+ // Sparse (well under the edge budget) so ELK stays fast.
+ const edges = Array.from({ length: 20 }, (_, i) => ({
+ from: `n${i}`,
+ to: `n${i + 1}`,
+ }));
+ const layout = await computeGraphLayout({ nodes, edges }, {}, "DOWN");
+ expect(layout.tooLarge).toBeFalsy();
+ expect(layout.nodes).toHaveLength(MAX_GRAPH_LAYOUT_NODES);
+ });
+
+ it("does not flag a small DOWN graph as too large", async () => {
+ const graph: GraphCanvasData = {
+ nodes: [node("a"), node("b"), node("c")],
+ edges: [
+ { from: "a", to: "b" },
+ { from: "b", to: "c" },
+ ],
+ };
+ const layout = await computeGraphLayout(graph, {}, "DOWN");
+ expect(layout.tooLarge).toBeFalsy();
+ expect(layout.nodes).toHaveLength(3);
+ });
+
+ it("still lays out an over-budget expanded (RIGHT) chain β€” exempt from the budget", async () => {
+ // Expanded graphs are acyclic and bounded upstream; a long thin chain of
+ // more than MAX_GRAPH_LAYOUT_EDGES edges lays out in milliseconds.
+ const layout = await computeGraphLayout(
+ chain(MAX_GRAPH_LAYOUT_EDGES + 5),
+ {},
+ "RIGHT",
+ );
+ expect(layout.tooLarge).toBeFalsy();
+ expect(layout.nodes.length).toBeGreaterThan(0);
+ });
+});
diff --git a/web/src/features/trace-graph-view/layout/elkLayout.ts b/web/src/features/trace-graph-view/layout/elkLayout.ts
index 3c237a4f18..4d3150a724 100644
--- a/web/src/features/trace-graph-view/layout/elkLayout.ts
+++ b/web/src/features/trace-graph-view/layout/elkLayout.ts
@@ -31,6 +31,15 @@ export interface GraphLayout {
/** Bounding size of the laid-out graph. */
width: number;
height: number;
+ /**
+ * Set when the graph exceeded the layout budget: ELK was NOT run (it would
+ * freeze the tab), `nodes`/`edges` are empty, and the renderer shows a
+ * "too large to lay out" notice instead. See MAX_GRAPH_LAYOUT_* below.
+ */
+ tooLarge?: boolean;
+ /** Distinct node / deduped-edge counts β€” surfaced in the "too large" notice. */
+ nodeCount?: number;
+ edgeCount?: number;
}
export type GraphLayoutDirection = "DOWN" | "RIGHT";
@@ -63,9 +72,62 @@ const LAYOUT_OPTIONS: Record<string, string> = {
*/
const MAX_WRAP_NODES = 300;
-/** Map our {nodes, edges} into an ELK graph, deduping edges and dropping self-loops. */
+/**
+ * Layout budget for the aggregated (DOWN) graph. Aggregation collapses repeated
+ * step names into one node, which turns a large trace into a small-but-DENSE,
+ * often CYCLIC multigraph β€” the pathological input for ELK's layered algorithm
+ * (cycle breaking + crossing minimization + orthogonal routing all blow up
+ * super-linearly with edge density). Measured with the app's exact layout
+ * options on dense cyclic graphs: ~40 nodes/200 edges β‰ˆ 1.4s, 50/250 β‰ˆ 5.8s,
+ * 60/300 β‰ˆ 10s, 80/600 β‰ˆ 70s, 100/800 β‰ˆ 177s β€” and a real reported trace fed
+ * ELK 1,422 distinct edges and froze the tab for >110s (indefinite wedge /
+ * "too much recursion" on small-stack browsers). elkjs runs synchronously on
+ * the main thread, so once started it can't be interrupted or caught β€” the ONLY
+ * safe fix is to not start it. Above the budget we skip layout and the renderer
+ * shows a "too large" notice.
+ *
+ * Sized to sit well below the danger zone (worst-case dense layout at the cap
+ * stays a few seconds, never minutes) while leaving large headroom over real
+ * aggregated graphs, which have far fewer distinct name-pairs. SPARSE/acyclic
+ * graphs of any size are cheap (3,840 acyclic edges lay out in ~0.6s), but the
+ * aggregated view rarely reaches this many distinct nodes/edges without also
+ * being dense β€” exactly the case we must protect against.
+ *
+ * The expanded (RIGHT) path is exempt: it unrolls loops into an ACYCLIC DAG and
+ * is already bounded upstream (MAX_EXPANDED_EDGES + the MAX_WRAP_NODES wrapping
+ * cap), so it lays out in ~2.5s even at its own limits.
+ */
+export const MAX_GRAPH_LAYOUT_EDGES = 250;
+export const MAX_GRAPH_LAYOUT_NODES = 500;
+
+/**
+ * Distinct, self-loop-free edges keyed by (from, to). The aggregated graph
+ * hands ELK the same name-pair edge many times over (measured: ~23k raw β†’ ~1.4k
+ * distinct, 16Γ—), so deduping before the layout call is the cheapest single win
+ * β€” and gives us the true edge count the budget is measured against.
+ *
+ * JSON key, not a space-joined one: node ids are SDK-supplied names that
+ * commonly contain spaces, so two distinct edges must not collide.
+ */
+export function dedupeEdges(
+ edges: GraphCanvasData["edges"],
+): GraphCanvasData["edges"] {
+ const seen = new Set<string>();
+ const out: GraphCanvasData["edges"] = [];
+ for (const edge of edges) {
+ if (edge.from === edge.to) continue; // self-loop
+ const key = JSON.stringify([edge.from, edge.to]);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(edge);
+ }
+ return out;
+}
+
+/** Map our {nodes, edges} into an ELK graph. Edges are pre-deduped by the caller. */
function buildElkGraph(
graph: GraphCanvasData,
+ dedupedEdges: GraphCanvasData["edges"],
counterReserve: Map<string, number>,
direction: GraphLayoutDirection,
): ElkNode {
@@ -100,22 +162,11 @@ function buildElkGraph(
};
});
- const seen = new Set<string>();
- const edges = graph.edges
- .filter((edge) => {
- if (edge.from === edge.to) return false; // self-loop
- // JSON key, not a space-joined one: node ids are SDK-supplied names that
- // commonly contain spaces, so two distinct edges must not collide.
- const key = JSON.stringify([edge.from, edge.to]);
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
- })
- .map((edge, index) => ({
- id: `edge-${index}`,
- sources: [edge.from],
- targets: [edge.to],
- }));
+ const edges = dedupedEdges.map((edge, index) => ({
+ id: `edge-${index}`,
+ sources: [edge.from],
+ targets: [edge.to],
+ }));
return {
id: "root",
@@ -189,11 +240,42 @@ export async function computeGraphLayout(
return { nodes: [], edges: [], width: 0, height: 0 };
}
+ const dedupedEdges = dedupeEdges(graph.edges);
+
+ // Budget gate (aggregated DOWN layout only β€” see MAX_GRAPH_LAYOUT_* and the
+ // RIGHT-path exemption). elkjs is synchronous and uninterruptible, so a graph
+ // past the budget is refused BEFORE the layout call β€” the only way to avoid a
+ // multi-minute main-thread freeze / stack overflow.
+ if (
+ direction === "DOWN" &&
+ (graph.nodes.length > MAX_GRAPH_LAYOUT_NODES ||
+ dedupedEdges.length > MAX_GRAPH_LAYOUT_EDGES)
+ ) {
+ return {
+ nodes: [],
+ edges: [],
+ width: 0,
+ height: 0,
+ tooLarge: true,
+ nodeCount: graph.nodes.length,
+ edgeCount: dedupedEdges.length,
+ };
+ }
+
const elk = await getElk();
const counterReserve = buildCounterReserve(nodeToObservationsMap);
- const result = await elk.layout(
- buildElkGraph(graph, counterReserve, direction),
- );
+ // Defensive guard around the synchronous elkjs call: a graph that slips past
+ // the budget could still throw (e.g. RangeError "too much recursion"). Rethrow
+ // so the renderer surfaces a recoverable error state instead of an unhandled
+ // rejection.
+ let result: ElkNode;
+ try {
+ result = await elk.layout(
+ buildElkGraph(graph, dedupedEdges, counterReserve, direction),
+ );
+ } catch (error) {
+ throw error instanceof Error ? error : new Error(String(error));
+ }
const nodes: PositionedNode[] = (result.children ?? []).map((child) => ({
id: child.id,