🪢 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(trace): dedupe observations at the source so the detail panel matches the timeline (LFE-10588) (#14678)
Nikita Kabardin8baa92c44097
diff --git a/web/src/components/trace/contexts/TraceDataContext.tsx b/web/src/components/trace/contexts/TraceDataContext.tsxindex 1de4527d48..c35f3c8c34 100644--- a/web/src/components/trace/contexts/TraceDataContext.tsx+++ b/web/src/components/trace/contexts/TraceDataContext.tsx@@ -22,6 +22,7 @@ import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes"import { type TreeNode, type TraceSearchListItem } from "../lib/types";import {buildTraceUiData,+ dedupeObservationsById,getObservationLevels,removeHiddenNodes,} from "../lib/tree-building";@@ -74,7 +75,7 @@ interface TraceDataProviderProps {*/export function TraceDataProvider({trace,- observations,+ observations: rawObservations,serverScores,corrections,comments,@@ -82,6 +83,18 @@ export function TraceDataProvider({}: TraceDataProviderProps) {const { minObservationLevel } = useViewPreferences();+ // Collapse duplicate/colliding observation ids to one row per id up front, so+ // the SAME de-duped set feeds the tree builder AND every consumer that resolves+ // a row from `observations` (notably the detail panel's `observations.find`).+ // Without this the tree picks the earliest-startTime row while the panel's+ // `.find` returns the first row in the raw array — on corrupt traces those can+ // differ, so the timeline and the opened detail panel could silently show+ // different data. No-op (same reference) for well-formed traces.+ const observations = useMemo(+ () => dedupeObservationsById(rawObservations),+ [rawObservations],+ );+// Build full tree (no level filtering) — only rebuilds when data changesconst uiData = useMemo(() => {return buildTraceUiData(trace, observations);diff --git a/web/src/components/trace/lib/tree-building.clienttest.ts b/web/src/components/trace/lib/tree-building.clienttest.tsindex 4ff4896920..392a351b24 100644--- a/web/src/components/trace/lib/tree-building.clienttest.ts+++ b/web/src/components/trace/lib/tree-building.clienttest.ts@@ -6,6 +6,7 @@import {buildTraceUiData,+ dedupeObservationsById,removeHiddenNodes,getObservationLevels,} from "./tree-building";@@ -2285,4 +2286,73 @@ describe("Duplicate / colliding observation IDs (LFE-10588)", () => {expect(result.nodeMap.has(`n${i}`)).toBe(true);}});++ // The detail panel resolves the clicked observation via+ // `observations.find(o => o.id === id)`. The tree node is built from the+ // de-duped set (earliest-startTime row), so the array the panel searches must+ // be de-duped the same way — otherwise, on a corrupt trace, the timeline row+ // and the opened detail panel can silently show different data.++ it("keeps the earliest-startTime row per id, independent of array order", () => {+ // Array order lists the LATER row first, so a naive `.find` would pick it.+ const later = createMockObservation({+ id: "x",+ name: "later",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.200Z"),+ });+ const earlier = createMockObservation({+ id: "x",+ name: "earlier",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.100Z"),+ });++ const deduped = dedupeObservationsById([later, earlier]);++ expect(deduped).toHaveLength(1);+ expect(deduped[0].name).toBe("earlier");+ });++ it("returns the same array reference when all ids are unique (no-op)", () => {+ const list = [+ createMockObservation({ id: "a" }),+ createMockObservation({ id: "b" }),+ ];+ expect(dedupeObservationsById(list)).toBe(list);+ });++ it("resolves the same row for the tree node and a find() on the deduped list", () => {+ const trace = createMockTrace({ id: "t" });+ // Two colliding rows for id "x" differing on a user-visible field, with the+ // later-startTime row first in array order.+ const raw: ObservationReturnType[] = [+ createMockObservation({+ id: "x",+ name: "later",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.200Z"),+ }),+ createMockObservation({+ id: "x",+ name: "earlier",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.100Z"),+ }),+ ];+ // On the RAW array the panel's `.find` returns the first (wrong) row.+ expect(raw.find((o) => o.id === "x")?.name).toBe("later");++ // De-dup once (as TraceDataProvider now does), then feed both.+ const deduped = dedupeObservationsById(raw);+ const result = buildTraceUiData(trace, deduped);++ const treeNodeName = result.nodeMap.get("x")?.name;+ const panelRowName = deduped.find((o) => o.id === "x")?.name;++ expect(treeNodeName).toBe("earlier");+ expect(panelRowName).toBe("earlier");+ // The invariant: timeline (tree node) and detail panel (find) agree.+ expect(panelRowName).toBe(treeNodeName);+ });});diff --git a/web/src/components/trace/lib/tree-building.ts b/web/src/components/trace/lib/tree-building.tsindex c532f391d8..39c10f2bd4 100644--- a/web/src/components/trace/lib/tree-building.ts+++ b/web/src/components/trace/lib/tree-building.ts@@ -77,33 +77,55 @@ export function getObservationLevels(}/**- * Prepares observations for tree building.- * Cleans orphaned parent references and sorts by startTime.- * Returns flat array (nesting happens in buildDependencyGraph).+ * Collapse observations sharing the same id to a single row per id, keeping the+ * earliest by startTime (deterministic).+ *+ * The tree builder assumes observation ids are unique, but real traces can+ * contain multiple rows with the same id (colliding / reused ids in ingested+ * data, or un-merged event rows), 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 then grows its+ * queue without bound and the trace crashes the client with "RangeError:+ * Invalid array length" / out of memory.+ *+ * The trace detail panel resolves the selected row from this same observation+ * list, so tree and panel MUST agree on which duplicate wins — hence a single+ * shared de-dup used both here (via prepareObservations) and by TraceDataContext+ * for the array the panel searches.+ *+ * Generic over the row shape so ObservationReturnType and the with-metadata+ * variant used by the UI context share one implementation. Returns the input+ * array unchanged (same reference) when all ids are already unique — a no-op for+ * well-formed traces that also preserves referential identity for memoization.*/-function prepareObservations(list: ObservationReturnType[]): {- sortedObservations: 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>();+export function dedupeObservationsById<+ T extends { id: string; startTime: Date },+>(list: T[]): T[] {+ const byId = new Map<string, T>();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());+ return byId.size === list.length ? list : Array.from(byId.values());+}++/**+ * Prepares observations for tree building.+ * De-duplicates colliding ids, cleans orphaned parent references, sorts by+ * startTime. Returns flat array (nesting happens in buildDependencyGraph).+ */+function prepareObservations(list: ObservationReturnType[]): {+ sortedObservations: ObservationReturnType[];+} {+ if (list.length === 0) return { sortedObservations: [] };++ // One row per id (earliest by startTime) so the parent→child graph stays a+ // proper forest — see dedupeObservationsById for why duplicates crash the+ // builder. No-op for well-formed traces.+ const dedupedList = dedupeObservationsById(list);// Build a Set of all observation IDs for O(1) lookupconst observationIds = new Set(dedupedList.map((o) => o.id));