🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): treat elkjs stack overflow as too-large graph (#16572)
cursor[bot]1d14a4ec1812
diff --git a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsxindex e8ba0caf7d..33facaca18 100644--- a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx+++ b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx@@ -21,6 +21,7 @@ import { type GraphCanvasData, type GraphNodeData } from "../types";import {type GraphLayout,type GraphLayoutDirection,+ isElkCallStackOverflow,} from "../layout/elkLayout";import { requestGraphLayout } from "../layout/graphLayoutWorkerClient";import { GraphNode } from "./GraphNode";@@ -186,8 +187,18 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({.catch((error) => {clearTimeout(slowTimer);if (cancelled) return; // superseded — the rejection IS the cancellation- // No warnMessage: the console line must carry ELK's own reason (e.g.- // "too much recursion"), which is the whole diagnostic.+ // Stack overflow is converted to `tooLarge` inside runGraphLayout.+ // If a wrapper still rejects with that signature, treat it as the+ // same expected "cannot lay out" state — do not page Sentry.+ if (isElkCallStackOverflow(error)) {+ reportError(error, {+ area: "trace-graph-layout",+ expected: true,+ });+ setLayoutError(true);+ return;+ }+ // No warnMessage: the console line must carry ELK's own reason.reportError(error, { area: "trace-graph-layout" });setLayoutError(true);});diff --git a/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts b/web/src/features/trace-graph-view/layout/elkLayout.clienttest.tsindex 9200aad92d..42ab36ec1c 100644--- a/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts+++ b/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts@@ -1,11 +1,15 @@// @vitest-environment node+import type { ELK } from "elkjs";+import { type GraphCanvasData, type GraphNodeData } from "../types";import {computeGraphLayout,dedupeEdges,MAX_GRAPH_LAYOUT_EDGES,MAX_GRAPH_LAYOUT_NODES,+ runGraphLayout,+ type GraphLayoutRequest,} from "./elkLayout";const node = (id: string): GraphNodeData => ({ id, label: id, type: "AGENT" });@@ -217,3 +221,47 @@ describe("computeGraphLayout layout budget", () => {expect(layout.nodes.length).toBeGreaterThan(0);});});++describe("runGraphLayout elkjs stack overflow", () => {+ // elkjs's layered algorithm recurses per layer. Inside the count budget a+ // deep/cyclic graph can still overflow the (especially worker) stack —+ // Chrome/Safari RangeError, Firefox InternalError "too much recursion".+ // That is the same user-visible "too large" state as the count/deadline+ // gates, not an actionable app crash.++ const request: GraphLayoutRequest = {+ nodes: [node("a"), node("b")],+ edges: [{ from: "a", to: "b" }],+ counterReserve: [],+ direction: "DOWN",+ };++ const fakeElk = (error: unknown) =>+ ({+ layout: async () => {+ throw error;+ },+ }) as unknown as ELK;++ it.each([+ new RangeError("Maximum call stack size exceeded"),+ new RangeError("Maximum call stack size exceeded."),+ Object.assign(new Error("too much recursion"), { name: "InternalError" }),+ "Maximum call stack size exceeded",+ { message: "Maximum call stack size exceeded" },+ ])("returns tooLarge instead of throwing on %s", async (error) => {+ const layout = await runGraphLayout(fakeElk(error), request);++ expect(layout.tooLarge).toBe(true);+ expect(layout.nodes).toHaveLength(0);+ expect(layout.edges).toHaveLength(0);+ expect(layout.nodeCount).toBe(2);+ expect(layout.edgeCount).toBe(1);+ });++ it("still throws unexpected ELK failures", async () => {+ await expect(+ runGraphLayout(fakeElk(new Error("elk failed: bad graph")), request),+ ).rejects.toThrow("elk failed: bad graph");+ });+});diff --git a/web/src/features/trace-graph-view/layout/elkLayout.ts b/web/src/features/trace-graph-view/layout/elkLayout.tsindex 58d901b35c..624207a657 100644--- a/web/src/features/trace-graph-view/layout/elkLayout.ts+++ b/web/src/features/trace-graph-view/layout/elkLayout.ts@@ -33,10 +33,11 @@ export interface GraphLayout {width: number;height: number;/**- * Set when the graph got no layout: either past the count ceiling- * (MAX_GRAPH_LAYOUT_*, so ELK never ran) or past the worker's wall-clock- * deadline. `nodes`/`edges` are empty and the renderer shows a "too large to- * lay out" notice.+ * Set when the graph got no layout: past the count ceiling+ * (MAX_GRAPH_LAYOUT_*, so ELK never ran), past the worker's wall-clock+ * deadline, or elkjs overflowed its call stack on a graph still inside the+ * count budget (deep/cyclic layered graphs). `nodes`/`edges` are empty and+ * the renderer shows a "too large to lay out" notice.*/tooLarge?: boolean;/** Distinct node / deduped-edge counts — surfaced in the "too large" notice. */@@ -138,6 +139,48 @@ export function exceedsMainThreadBudget(request: GraphLayoutRequest): boolean {);}+function elkErrorMessage(error: unknown): string {+ if (typeof error === "string") return error;+ if (error instanceof Error) return error.message;+ if (+ error &&+ typeof error === "object" &&+ "message" in error &&+ typeof (error as { message: unknown }).message === "string"+ ) {+ return (error as { message: string }).message;+ }+ return "";+}++/**+ * elkjs's layered algorithm recurses per layer. On a deep or cyclic graph that+ * still fits the count budget, that DFS overflows the (especially worker)+ * stack: Chrome/Safari `RangeError: Maximum call stack size exceeded`,+ * Firefox `InternalError: too much recursion`.+ *+ * Same user-visible outcome as the count/deadline gates — not an app crash.+ */+export function isElkCallStackOverflow(error: unknown): boolean {+ const message = elkErrorMessage(error);+ return (+ /maximum call stack size exceeded/i.test(message) ||+ /too much recursion/i.test(message)+ );+}++function tooLargeLayout(request: GraphLayoutRequest): GraphLayout {+ return {+ nodes: [],+ edges: [],+ width: 0,+ height: 0,+ tooLarge: true,+ nodeCount: request.nodes.length,+ edgeCount: request.edges.length,+ };+}+/*** 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@@ -330,13 +373,18 @@ export async function runGraphLayout(elk: ELK,request: GraphLayoutRequest,): Promise<GraphLayout> {- // Defensive guard: elkjs can still throw on a graph inside the budget (e.g.- // RangeError "too much recursion"). Rethrow a real Error so the caller — the- // worker's message handler or the renderer — surfaces a recoverable state.+ // Defensive guard: elkjs can still throw on a graph inside the budget.+ // Stack overflow is an expected ELK limitation — same "too large" state as+ // the count/deadline gates, so the renderer does not treat it as a crash.+ // Any other throw is rethrown as a real Error so the caller surfaces a+ // recoverable layoutError.let result: ElkNode;try {result = await elk.layout(buildElkGraph(request));} catch (error) {+ if (isElkCallStackOverflow(error)) {+ return tooLargeLayout(request);+ }throw error instanceof Error ? error : new Error(String(error));}diff --git a/web/src/features/trace-graph-view/layout/graphLayoutWorkerClient.clienttest.ts b/web/src/features/trace-graph-view/layout/graphLayoutWorkerClient.clienttest.tsindex 59d4c74dda..767b97dfc5 100644--- a/web/src/features/trace-graph-view/layout/graphLayoutWorkerClient.clienttest.ts+++ b/web/src/features/trace-graph-view/layout/graphLayoutWorkerClient.clienttest.ts@@ -63,6 +63,10 @@ class FakeWorker {answer(message: ElkMessage, data: unknown) {this.onmessage?.({ data: { id: message.id, data } } as MessageEvent);}++ fail(message: ElkMessage, error: unknown) {+ this.onmessage?.({ data: { id: message.id, error } } as MessageEvent);+ }}// The client keeps the worker in module state, so every test needs its own copy.@@ -130,6 +134,21 @@ describe("requestGraphLayout", () => {await expect(fresh).resolves.toMatchObject({ width: 2 });});+ it("gives up with the too-large notice when elkjs overflows the worker stack", async () => {+ const client = await loadClient();+ const pending = client.requestGraphLayout(graph, {}, "DOWN");+ const worker = FakeWorker.instances[0];+ await flush();++ worker.fail(worker.layoutRequests[0], "Maximum call stack size exceeded");++ await expect(pending).resolves.toMatchObject({+ tooLarge: true,+ nodeCount: 2,+ edgeCount: 1,+ });+ });+it("gives up with the too-large notice when a layout blows the deadline", async () => {vi.useFakeTimers();const client = await loadClient();