Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(trace): deduplicate observations by id so colliding ids can't crash trace load (LFE-10588) (#14669)

Nikita Kabardind2a0ab55ae27
diff --git a/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx b/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx
index 6a9717c35f..7984365745 100644
--- a/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx
+++ b/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx
@@ -11,8 +11,18 @@ export function TimelineScale({
scaleWidth,
stepSize,
}: TimelineScaleProps) {
- // Calculate how many markers to show
- const numMarkers = Math.ceil(scaleWidth / STEP_SIZE) + 1;
+ // Calculate how many markers to show. scaleWidth is expected to be the finite
+ // SCALE_WIDTH constant, but guard against a non-finite / absurd value ever
+ // reaching here: Array.from({ length }) throws "RangeError: Invalid array
+ // length" for Infinity and OOMs for an enormous finite length, so clamp to a
+ // finite, sane upper bound.
+ const safeScaleWidth = Number.isFinite(scaleWidth)
+ ? Math.max(0, scaleWidth)
+ : 0;
+ const numMarkers = Math.min(
+ Math.ceil(safeScaleWidth / STEP_SIZE) + 1,
+ 10_000,
+ );
return (
// No left margin: the 0s tick must sit exactly at the track origin so the
diff --git a/web/src/components/trace/components/_shared/VirtualizedTreeNodeWrapper.tsx b/web/src/components/trace/components/_shared/VirtualizedTreeNodeWrapper.tsx
index bd329fc191..930f975ed7 100644
--- a/web/src/components/trace/components/_shared/VirtualizedTreeNodeWrapper.tsx
+++ b/web/src/components/trace/components/_shared/VirtualizedTreeNodeWrapper.tsx
@@ -78,7 +78,9 @@ export function VirtualizedTreeNodeWrapper({
{/* 1. Indents: ancestor level indicators */}
{depth > 0 && (
<div className="flex shrink-0">
- {Array.from({ length: depth - 1 }, (_, i) => (
+ {/* Math.max floors the length at 0 so a stray non-positive/NaN depth
+ can never reach Array.from as a value that throws RangeError. */}
+ {Array.from({ length: Math.max(0, depth - 1) }, (_, i) => (
<div key={i} className="relative w-5">
{treeLines[i] && (
<div className="bg-border absolute top-0 bottom-0 left-3 w-px" />
diff --git a/web/src/components/trace/lib/tree-building.clienttest.ts b/web/src/components/trace/lib/tree-building.clienttest.ts
index 528b50a21b..4ff4896920 100644
--- a/web/src/components/trace/lib/tree-building.clienttest.ts
+++ b/web/src/components/trace/lib/tree-building.clienttest.ts
@@ -2182,3 +2182,107 @@ describe("getSubtreeDurationOverflowMs", () => {
expect(getSubtreeDurationOverflowMs(64_000, 65_000)).toBe(65_000);
});
});
+
+describe("Duplicate / colliding observation IDs (LFE-10588)", () => {
+ // Regression guard for a prod trace crash. Real traces can contain multiple
+ // rows that share the same observation id (colliding / reused ids in ingested
+ // data), and those rows may each carry a DIFFERENT parentObservationId. The
+ // tree builder keys nodes by id, so duplicate rows wire one node under several
+ // parents — turning the parent→child graph into a dense multi-parent DAG whose
+ // root→node path count grows exponentially. The depth-propagation BFS then grew
+ // its queue without bound, so loading such a trace threw
+ // "RangeError: Invalid array length" / ran out of memory. The builder must
+ // collapse to one row per id so the structure stays a proper forest.
+
+ it("collapses duplicate rows for the same id to a single node", () => {
+ const trace = createMockTrace({ id: "t" });
+ const observations: ObservationReturnType[] = [
+ createMockObservation({
+ id: "a",
+ parentObservationId: null,
+ startTime: new Date("2024-01-01T00:00:00.100Z"),
+ }),
+ createMockObservation({
+ id: "b",
+ parentObservationId: "a",
+ startTime: new Date("2024-01-01T00:00:00.200Z"),
+ }),
+ // duplicate row for child "b" — must not be double-wired under "a"
+ createMockObservation({
+ id: "b",
+ parentObservationId: "a",
+ startTime: new Date("2024-01-01T00:00:00.250Z"),
+ }),
+ ];
+
+ const result = buildTraceUiData(trace, observations);
+
+ // one node per distinct id (+ TRACE wrapper); each appears exactly once.
+ expect(result.nodeMap.size).toBe(3); // trace + a + b
+ expect(result.searchItems).toHaveLength(3);
+ expect(result.searchItems.filter((i) => i.node.id === "b")).toHaveLength(1);
+ // "a" must survive: pre-fix a duplicated child inflated a's in-degree so it
+ // never hit zero in the topological sort and the whole subtree was dropped.
+ expect(result.roots[0].children.map((c) => c.id)).toEqual(["a"]);
+ });
+
+ it("does not explode on colliding ids that form a multi-parent DAG", () => {
+ // Shortcut ladder: node i is a child of BOTH i-1 and i-2, each via a separate
+ // row that reuses id `n{i}`. Without deduplication the root→node path count
+ // is Fibonacci-large and the depth BFS / flatten grow without bound (the prod
+ // crash). Sized so the pre-fix blowup stays finite (~Fib(24)) rather than
+ // OOM-ing the test worker, while still being orders of magnitude too big.
+ const trace = createMockTrace({ id: "t" });
+ const N = 22;
+ const observations: ObservationReturnType[] = [];
+ let clock = 0;
+ const nextStart = () =>
+ new Date(`2024-01-01T00:00:00.${String(clock++).padStart(3, "0")}Z`);
+
+ observations.push(
+ createMockObservation({
+ id: "n0",
+ parentObservationId: null,
+ startTime: nextStart(),
+ }),
+ );
+ observations.push(
+ createMockObservation({
+ id: "n1",
+ parentObservationId: "n0",
+ startTime: nextStart(),
+ }),
+ );
+ for (let i = 2; i <= N; i++) {
+ // primary edge (earlier startTime → survives dedup): parent = i-1
+ observations.push(
+ createMockObservation({
+ id: `n${i}`,
+ parentObservationId: `n${i - 1}`,
+ startTime: nextStart(),
+ }),
+ );
+ // shortcut edge (duplicate id, later startTime): parent = i-2
+ observations.push(
+ createMockObservation({
+ id: `n${i}`,
+ parentObservationId: `n${i - 2}`,
+ startTime: nextStart(),
+ }),
+ );
+ }
+ const distinctIds = N + 1; // n0..nN
+
+ const result = buildTraceUiData(trace, observations);
+
+ // Dedup keeps the earliest-startTime row per id → a clean chain
+ // n0→n1→…→nN. Every distinct id survives exactly once (+ TRACE wrapper), and
+ // the flattened list is bounded — pre-fix the duplicated edges either dropped
+ // nodes (in-degree never hit zero) or blew the traversal up Fibonacci-large.
+ expect(result.nodeMap.size).toBe(distinctIds + 1);
+ expect(result.searchItems).toHaveLength(distinctIds + 1);
+ for (let i = 0; i <= N; i++) {
+ expect(result.nodeMap.has(`n${i}`)).toBe(true);
+ }
+ });
+});
diff --git a/web/src/components/trace/lib/tree-building.ts b/web/src/components/trace/lib/tree-building.ts
index 8317ae9667..c532f391d8 100644
--- a/web/src/components/trace/lib/tree-building.ts
+++ b/web/src/components/trace/lib/tree-building.ts
@@ -86,11 +86,30 @@ function prepareObservations(list: ObservationReturnType[]): {
} {
if (list.length === 0) return { sortedObservations: [] };
+ // Deduplicate by observation id. The tree builder assumes ids are unique, but
+ // real traces can contain multiple rows sharing the same id (colliding /
+ // reused ids in ingested data) — and those rows may each carry a DIFFERENT
+ // parentObservationId. Left un-deduped, one node gets wired under several
+ // parents, turning the parent→child graph into a dense multi-parent DAG whose
+ // root→node path count is exponential; the depth-propagation BFS below then
+ // grows its queue without bound, so loading such a trace crashed the client
+ // with "RangeError: Invalid array length" / out of memory. Collapse to one row
+ // per id (earliest by startTime, deterministic) so the structure stays a
+ // proper forest. No-op for well-formed traces (all ids already unique).
+ const byId = new Map<string, ObservationReturnType>();
+ for (const o of list) {
+ const existing = byId.get(o.id);
+ if (!existing || o.startTime.getTime() < existing.startTime.getTime()) {
+ byId.set(o.id, o);
+ }
+ }
+ const dedupedList = Array.from(byId.values());
+
// Build a Set of all observation IDs for O(1) lookup
- const observationIds = new Set(list.map((o) => o.id));
+ const observationIds = new Set(dedupedList.map((o) => o.id));
// Remove parentObservationId if parent doesn't exist in the list
- const mutableList = list.map((o) => {
+ const mutableList = dedupedList.map((o) => {
if (o.parentObservationId && !observationIds.has(o.parentObservationId)) {
return { ...o, parentObservationId: null };
}
@@ -147,14 +166,25 @@ function buildDependencyGraph(sortedObservations: ObservationReturnType[]): {
}
}
- // BFS to propagate depth down the tree
+ // BFS to propagate depth down the tree.
+ //
+ // Defense in depth: track visited nodes so a node is enqueued at most once.
+ // prepareObservations already dedupes by id (making the graph a proper forest),
+ // but guarding here means even a pathological multi-parent / cyclic graph can
+ // never grow the queue without bound — the failure mode that crashed the trace
+ // peek with "RangeError: Invalid array length" / OOM. For a well-formed forest
+ // each node has a single parent, so it is visited exactly once and depths are
+ // unchanged.
const queue = [...rootIds];
+ const visited = new Set(rootIds);
let queueIndex = 0;
while (queueIndex < queue.length) {
const currentId = queue[queueIndex++];
const currentNode = nodeRegistry.get(currentId)!;
for (const childId of currentNode.childrenIds) {
+ if (visited.has(childId)) continue;
+ visited.add(childId);
const childNode = nodeRegistry.get(childId)!;
childNode.depth = currentNode.depth + 1;
queue.push(childId);