Skip to content

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

chore(trace): optimize rendering for large traces (30K+ observations) (#10581)

Michael Fröhlicheb6fa1569e5c
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 494011e369..f3eda28a8c 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -21,7 +21,8 @@ import { cn } from "@/src/utils/tailwind";
import { NewDatasetItemFromExistingObject } from "@/src/features/datasets/components/NewDatasetItemFromExistingObject";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
-import { Fragment, useMemo, useState } from "react";
+import { Fragment, useState } from "react";
+import type Decimal from "decimal.js";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
import {
TabsBar,
@@ -51,6 +52,7 @@ export const ObservationPreview = ({
viewType = "detailed",
isTimeline,
showCommentButton = false,
+ precomputedCost,
}: {
observations: Array<ObservationReturnType>;
projectId: string;
@@ -61,6 +63,7 @@ export const ObservationPreview = ({
viewType?: "focused" | "detailed";
isTimeline?: boolean;
showCommentButton?: boolean;
+ precomputedCost: Decimal | undefined;
}) => {
const [selectedTab, setSelectedTab] = useQueryParam(
"view",
@@ -125,14 +128,7 @@ export const ObservationPreview = ({
})
: undefined;
- const totalCost = useMemo(
- () =>
- calculateDisplayTotalCost({
- allObservations: observations,
- rootObservationId: currentObservationId,
- }),
- [observations, currentObservationId],
- );
+ const totalCost = precomputedCost;
if (!preloadedObservation) return <div className="flex-1">Not found</div>;
diff --git a/web/src/components/trace/SpanItem.tsx b/web/src/components/trace/SpanItem.tsx
index 24d61cbd0c..fbe1c7cd60 100644
--- a/web/src/components/trace/SpanItem.tsx
+++ b/web/src/components/trace/SpanItem.tsx
@@ -5,11 +5,7 @@ import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";
import { cn } from "@/src/utils/tailwind";
import { formatIntervalSeconds } from "@/src/utils/dates";
import { usdFormatter, formatTokenCounts } from "@/src/utils/numbers";
-import {
- calculateDisplayTotalCost,
- heatMapTextColor,
- unnestObservation,
-} from "@/src/components/trace/lib/helpers";
+import { heatMapTextColor } from "@/src/components/trace/lib/helpers";
import { type ScoreDomain } from "@langfuse/shared";
import type Decimal from "decimal.js";
import React from "react";
@@ -42,19 +38,8 @@ export const SpanItem: React.FC<SpanItemProps> = ({
showComments = true,
className,
}) => {
- const convertTreeNodeToObservation = (treeNode: TreeNode): any => ({
- ...treeNode,
- children: treeNode.children.map(convertTreeNodeToObservation),
- });
-
- const totalCost = calculateDisplayTotalCost({
- allObservations:
- node.children.length > 0
- ? node.children.flatMap((child) =>
- unnestObservation(convertTreeNodeToObservation(child)),
- )
- : [convertTreeNodeToObservation(node)],
- });
+ // Use pre-computed cost from the TreeNode (computed during tree building)
+ const totalCost = node.totalCost;
const duration =
node.endTime && node.startTime
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 59f77c5574..f5122f96f1 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -20,8 +20,8 @@ import { NewDatasetItemFromExistingObject } from "@/src/features/datasets/compon
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
import { useMemo, useState, useEffect } from "react";
import { usdFormatter } from "@/src/utils/numbers";
-import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
+import type Decimal from "decimal.js";
import {
TabsBar,
TabsBarContent,
@@ -68,6 +68,7 @@ export const TracePreview = ({
commentCounts,
viewType = "detailed",
showCommentButton = false,
+ precomputedCost,
}: {
trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
latency?: number;
@@ -79,6 +80,7 @@ export const TracePreview = ({
commentCounts?: Map<string, number>;
viewType?: "detailed" | "focused";
showCommentButton?: boolean;
+ precomputedCost: Decimal | undefined;
}) => {
const [selectedTab, setSelectedTab] = useQueryParam(
"view",
@@ -112,13 +114,7 @@ export const TracePreview = ({
},
);
- const totalCost = useMemo(
- () =>
- calculateDisplayTotalCost({
- allObservations: observations,
- }),
- [observations],
- );
+ const totalCost = precomputedCost;
const usageDetails = useMemo(
() =>
diff --git a/web/src/components/trace/TraceSearchList.tsx b/web/src/components/trace/TraceSearchList.tsx
index 6d9a637778..946bbd8fe4 100644
--- a/web/src/components/trace/TraceSearchList.tsx
+++ b/web/src/components/trace/TraceSearchList.tsx
@@ -1,16 +1,11 @@
-import React from "react";
-import {
- CommandEmpty,
- CommandGroup,
- CommandItem,
- CommandList,
-} from "@/src/components/ui/command";
+import React, { useRef } from "react";
import { SpanItem } from "@/src/components/trace/SpanItem";
import { ItemBadge } from "@/src/components/ItemBadge";
import { type ScoreDomain } from "@langfuse/shared";
import type Decimal from "decimal.js";
import { type TreeNode } from "./lib/types";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
+import { useVirtualizer } from "@tanstack/react-virtual";
export interface TraceSearchListItem {
node: TreeNode;
@@ -32,6 +27,60 @@ export interface TraceSearchListProps {
onClearSearch?: () => void;
}
+// Individual search list row component for virtualization
+type SearchListRowProps = {
+ item: TraceSearchListItem;
+ scores: WithStringifiedMetadata<ScoreDomain>[];
+ onSelect: (observationId: string | undefined) => void;
+ comments?: Map<string, number>;
+ showDuration: boolean;
+ showCostTokens: boolean;
+ showScores: boolean;
+ colorCodeMetrics: boolean;
+ showComments: boolean;
+};
+
+const SearchListRow: React.FC<SearchListRowProps> = ({
+ item,
+ scores,
+ onSelect,
+ comments,
+ showDuration,
+ showCostTokens,
+ showScores,
+ colorCodeMetrics,
+ showComments,
+}) => {
+ const { node, parentTotalCost, parentTotalDuration, observationId } = item;
+
+ return (
+ <div
+ className="relative flex w-full cursor-pointer !rounded-lg !py-1.5 px-2 hover:bg-muted/40"
+ onClick={() => onSelect(observationId)}
+ >
+ <div className="flex w-full">
+ <div className="flex min-w-0 flex-1 items-start gap-2">
+ <div className="relative z-20 flex-shrink-0">
+ <ItemBadge type={node.type} isSmall className="!size-3" />
+ </div>
+ <SpanItem
+ node={node}
+ scores={scores}
+ comments={comments}
+ showDuration={showDuration}
+ showCostTokens={showCostTokens}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ parentTotalCost={parentTotalCost}
+ parentTotalDuration={parentTotalDuration}
+ showComments={showComments}
+ />
+ </div>
+ </div>
+ </div>
+ );
+};
+
export const TraceSearchList: React.FC<TraceSearchListProps> = ({
items,
// Note: displayScores are merged with client-side score cache; handling optimistic updates
@@ -45,53 +94,77 @@ export const TraceSearchList: React.FC<TraceSearchListProps> = ({
showComments = true,
onClearSearch,
}) => {
+ const parentRef = useRef<HTMLDivElement>(null);
+
+ // Set up virtualizer
+ const rowVirtualizer = useVirtualizer({
+ count: items.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => 48, // Approximate height of a search result row
+ overscan: 500, // Render 500 extra rows above/below viewport for smooth scrolling
+ });
+
+ // Handle empty state
+ if (items.length === 0) {
+ return (
+ <div className="w-full">
+ <div className="flex w-full justify-center">
+ <div className="flex w-48 flex-col py-4 text-muted-foreground">
+ <span className="mb-2 font-semibold">No results found</span>
+ <span className="text-xs">
+ Try searching by type, title, or id.
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
return (
- <div className="w-full">
- <CommandList className="max-h-none w-full overflow-x-hidden overflow-y-visible">
- <CommandGroup className="p-0">
- {items.map(
- ({ node, parentTotalCost, parentTotalDuration, observationId }) => (
- <CommandItem
- key={node.id}
- value={`${node.name} ${node.type} ${node.id}`}
- className="relative flex w-full !rounded-lg !py-1.5 px-2 hover:bg-muted/40 data-[selected=true]:!text-foreground"
- onSelect={() => onSelect(observationId)}
+ <div className="flex h-full w-full flex-col">
+ {/* Virtualized search results */}
+ <div ref={parentRef} className="flex-1 overflow-y-auto">
+ <div
+ style={{
+ height: `${rowVirtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {rowVirtualizer.getVirtualItems().map((virtualRow) => {
+ const item = items[virtualRow.index];
+ return (
+ <div
+ key={item.node.id}
+ data-index={virtualRow.index}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ height: `${virtualRow.size}px`,
+ transform: `translateY(${virtualRow.start}px)`,
+ }}
>
- <div className="flex w-full">
- <div className="flex min-w-0 flex-1 items-start gap-2">
- <div className="relative z-20 flex-shrink-0">
- <ItemBadge type={node.type} isSmall className="!size-3" />
- </div>
- <SpanItem
- node={node}
- scores={scores}
- comments={comments}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalCost={parentTotalCost}
- parentTotalDuration={parentTotalDuration}
- showComments={showComments}
- />
- </div>
- </div>
- </CommandItem>
- ),
- )}
- </CommandGroup>
- <CommandEmpty>
- <div className="flex w-full justify-center">
- <div className="flex w-48 flex-col py-4 text-muted-foreground">
- <span className="mb-2 font-semibold">No results found</span>
- <span className="text-xs">
- Try searching by type, title, or id.
- </span>
- </div>
- </div>
- </CommandEmpty>
- </CommandList>
- {onClearSearch && items.length > 0 ? (
+ <SearchListRow
+ item={item}
+ scores={scores}
+ onSelect={onSelect}
+ comments={comments}
+ showDuration={showDuration}
+ showCostTokens={showCostTokens}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ showComments={showComments}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Clear search button */}
+ {onClearSearch ? (
<button
type="button"
className="mt-1 inline-flex w-full items-center justify-center rounded-lg px-2 py-1 text-xs hover:bg-muted/70"
diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsx
index 2e6396f580..9740123ebd 100644
--- a/web/src/components/trace/TraceTimelineView.tsx
+++ b/web/src/components/trace/TraceTimelineView.tsx
@@ -13,9 +13,10 @@ import React, {
useState,
useLayoutEffect,
} from "react";
-import { SimpleTreeView, TreeItem } from "@mui/x-tree-view";
+import { TreeItem } from "@mui/x-tree-view";
import type Decimal from "decimal.js";
-import { InfoIcon } from "lucide-react";
+import { type TreeNode } from "./lib/types";
+import { InfoIcon, ChevronRight } from "lucide-react";
import {
heatMapTextColor,
nestObservations,
@@ -34,6 +35,7 @@ import { formatIntervalSeconds } from "@/src/utils/dates";
import { usdFormatter } from "@/src/utils/numbers";
import { getNumberFromMap, castToNumberMap } from "@/src/utils/map-utils";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
+import { useVirtualizer } from "@tanstack/react-virtual";
// Fixed widths for styling for v1
const SCALE_WIDTH = 900;
@@ -45,6 +47,116 @@ const PREDEFINED_STEP_SIZES = [
35, 40, 45, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500,
];
+// Virtualized timeline data structure
+type FlatTimelineItem = {
+ observation:
+ | NestedObservation
+ | {
+ id: string;
+ name: string;
+ type: "TRACE";
+ startTime: Date;
+ children: NestedObservation[];
+ };
+ depth: number;
+ treeLines: boolean[];
+ isLastSibling: boolean;
+ // Pre-computed timeline metrics
+ startOffset: number;
+ itemWidth: number;
+ firstTokenTimeOffset?: number;
+ latency?: number;
+ isTraceRoot?: boolean;
+ // Pre-computed cost for this observation + all descendants
+ totalCost?: Decimal;
+};
+
+/**
+ * Build a map of observation ID to pre-computed totalCost from the TreeNode structure
+ */
+function buildCostMap(tree: TreeNode): Map<string, Decimal> {
+ const costMap = new Map<string, Decimal>();
+
+ const traverse = (node: TreeNode) => {
+ if (node.totalCost) {
+ costMap.set(node.id, node.totalCost);
+ }
+ node.children.forEach(traverse);
+ };
+
+ traverse(tree);
+ return costMap;
+}
+
+/**
+ * Flatten nested observations into a flat array with pre-computed timeline metrics.
+ * Only includes expanded nodes based on expandedItems.
+ * This enables virtualization by converting the tree to a flat list.
+ */
+function flattenTimelineTree(
+ observations: NestedObservation[],
+ expandedItems: string[],
+ traceStartTime: Date,
+ totalScaleSpan: number,
+ costMap?: Map<string, Decimal>,
+): FlatTimelineItem[] {
+ const result: FlatTimelineItem[] = [];
+
+ const flatten = (
+ obs: NestedObservation,
+ depth: number,
+ treeLines: boolean[],
+ isLastSibling: boolean,
+ ) => {
+ // Calculate timeline metrics ONCE during flattening
+ const latency = obs.endTime
+ ? (obs.endTime.getTime() - obs.startTime.getTime()) / 1000
+ : undefined;
+ const startOffset =
+ ((obs.startTime.getTime() - traceStartTime.getTime()) /
+ totalScaleSpan /
+ 1000) *
+ SCALE_WIDTH;
+ const itemWidth = ((latency ?? 0) / totalScaleSpan) * SCALE_WIDTH;
+ const firstTokenTimeOffset = obs.completionStartTime
+ ? ((obs.completionStartTime.getTime() - traceStartTime.getTime()) /
+ totalScaleSpan /
+ 1000) *
+ SCALE_WIDTH
+ : undefined;
+
+ // Get pre-computed cost from the cost map
+ const totalCost = costMap?.get(obs.id);
+
+ result.push({
+ observation: obs,
+ depth,
+ treeLines,
+ isLastSibling,
+ startOffset,
+ itemWidth,
+ firstTokenTimeOffset,
+ latency,
+ totalCost,
+ });
+
+ // Only include children if this observation is expanded
+ const observationId = `observation-${obs.id}`;
+ if (obs.children.length > 0 && expandedItems.includes(observationId)) {
+ obs.children.forEach((child, index) => {
+ const isChildLast = index === obs.children.length - 1;
+ flatten(child, depth + 1, [...treeLines, !isChildLast], isChildLast);
+ });
+ }
+ };
+
+ observations.forEach((obs, index) => {
+ flatten(obs, 0, [], index === observations.length - 1);
+ });
+
+ return result;
+}
+
const calculateStepSize = (latency: number, scaleWidth: number) => {
const calculatedStepSize = latency / (scaleWidth / STEP_SIZE);
return (
@@ -260,6 +372,150 @@ function TreeItemInner({
);
}
+/**
+ * Virtualized timeline row component - replaces recursive TraceTreeItem.
+ * Renders a single timeline item with tree lines, expand/collapse button, and Gantt bar.
+ */
+function VirtualizedTimelineRow({
+ item,
+ totalScaleSpan,
+ isSelected,
+ onClick,
+ onToggleExpand,
+ hasChildren,
+ isExpanded,
+ scores,
+ commentCount,
+ parentTotalCost,
+ parentTotalDuration,
+ showDuration = true,
+ showCostTokens = true,
+ showScores = true,
+ showComments = true,
+ colorCodeMetrics = false,
+}: {
+ item: FlatTimelineItem;
+ totalScaleSpan: number;
+ isSelected: boolean;
+ onClick: () => void;
+ onToggleExpand: () => void;
+ hasChildren: boolean;
+ isExpanded: boolean;
+ scores?: WithStringifiedMetadata<ScoreDomain>[];
+ commentCount?: number;
+ parentTotalCost?: Decimal;
+ parentTotalDuration?: number;
+ showDuration?: boolean;
+ showCostTokens?: boolean;
+ showScores?: boolean;
+ showComments?: boolean;
+ colorCodeMetrics?: boolean;
+}) {
+ const {
+ observation,
+ depth,
+ treeLines,
+ isLastSibling,
+ startOffset,
+ firstTokenTimeOffset,
+ latency,
+ isTraceRoot,
+ } = item;
+
+ // Use pre-computed cost from the item (computed during tree building)
+ // For trace root, use the parent total cost passed from props
+ const totalCost = isTraceRoot ? parentTotalCost : item.totalCost;
+
+ return (
+ <div
+ className={cn(
+ "group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center",
+ )}
+ onClick={onClick}
+ >
+ {/* Tree lines for ancestor levels (depth - 1) */}
+ {depth > 0 && (
+ <div className="flex flex-shrink-0">
+ {Array.from({ length: depth - 1 }, (_, i) => (
+ <div
+ key={i}
+ className="relative"
+ style={{ width: `${TREE_INDENTATION}px` }}
+ >
+ {treeLines[i] && (
+ <div className="absolute bottom-0 left-1.5 top-0 w-px bg-border" />
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Current level tree connector */}
+ {depth > 0 && (
+ <div
+ className="relative flex-shrink-0"
+ style={{ width: `${TREE_INDENTATION}px` }}
+ >
+ {/* Vertical line up */}
+ <div
+ className={cn(
+ "absolute left-1.5 top-0 w-px bg-border",
+ isLastSibling ? "h-3" : "bottom-0",
+ )}
+ />
+ {/* Horizontal line to content */}
+ <div className="absolute left-1.5 top-3 h-px w-2 bg-border" />
+ </div>
+ )}
+
+ {/* Expand/collapse button (if has children) */}
+ {hasChildren && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleExpand();
+ }}
+ className="absolute z-10 rounded hover:bg-muted"
+ style={{
+ left: `${depth * TREE_INDENTATION + (startOffset > 0 ? startOffset + 4 : 4)}px`,
+ top: "50%",
+ transform: "translateY(-50%)",
+ }}
+ >
+ <ChevronRight
+ className={cn(
+ "h-4 w-4 transition-transform duration-200",
+ isExpanded && "rotate-90",
+ )}
+ />
+ </button>
+ )}
+
+ {/* Reuse existing TreeItemInner component */}
+ <TreeItemInner
+ latency={latency}
+ type={observation.type}
+ name={observation.name}
+ startOffset={startOffset}
+ firstTokenTimeOffset={firstTokenTimeOffset}
+ totalScaleSpan={totalScaleSpan}
+ hasChildren={hasChildren}
+ isSelected={isSelected}
+ showDuration={showDuration}
+ showCostTokens={showCostTokens}
+ showScores={showScores}
+ showComments={showComments}
+ colorCodeMetrics={colorCodeMetrics}
+ scores={scores}
+ commentCount={commentCount}
+ parentTotalDuration={parentTotalDuration}
+ totalCost={totalCost}
+ parentTotalCost={parentTotalCost}
+ />
+ </div>
+ );
+}
+
function TraceTreeItem({
observation,
level = 0,
@@ -420,6 +676,7 @@ export function TraceTimelineView({
minLevel,
setMinLevel,
containerWidth,
+ tree,
}: {
trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
latency?: number;
@@ -441,25 +698,30 @@ export function TraceTimelineView({
minLevel?: ObservationLevelType;
setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevelType>>;
containerWidth?: number;
+ tree: TreeNode;
}) {
- const { latency, name, id } = trace;
+ const { latency } = trace;
const { nestedObservations, hiddenObservationsCount } = useMemo(
() => nestObservations(observations, minLevel),
[observations, minLevel],
);
+ // Build cost map from tree
+ const costMap = useMemo(() => buildCostMap(tree), [tree]);
+
// Use containerWidth from parent or fallback to ResizeObserver if not provided
const [cardWidth, setCardWidth] = useState(0);
const parentRef = useRef<HTMLDivElement>(null);
- // Calculate total cost for all observations
+ // Use pre-computed cost from tree, or calculate if not available
const totalCost = useMemo(
() =>
+ tree?.totalCost ??
calculateDisplayTotalCost({
allObservations: observations,
}),
- [observations],
+ [tree?.totalCost, observations],
);
useEffect(() => {
@@ -547,12 +809,79 @@ export function TraceTimelineView({
}
}, [observations, expandedItems, contentWidth]);
- if (!latency) return null;
- const stepSize = calculateStepSize(latency, SCALE_WIDTH);
+ // Calculate step size and scale span
+ const stepSize = latency ? calculateStepSize(latency, SCALE_WIDTH) : 1;
const totalScaleSpan = stepSize * (SCALE_WIDTH / STEP_SIZE);
const traceScores = scores.filter((s) => s.observationId === null);
- const totalDuration = latency * 1000; // Convert to milliseconds for consistency
+ const totalDuration = latency ? latency * 1000 : 0; // Convert to milliseconds for consistency
+
+ // Flatten the tree for virtualization
+ const flattenedItems = useMemo(() => {
+ if (!latency) return [];
+
+ const traceStartTime = nestedObservations[0]?.startTime ?? trace.timestamp;
+
+ // Create trace root item
+ const traceRootItem: FlatTimelineItem = {
+ observation: {
+ id: trace.id,
+ name: trace.name ?? "",
+ type: "TRACE",
+ startTime: trace.timestamp,
+ children: nestedObservations,
+ },
+ depth: 0,
+ treeLines: [],
+ isLastSibling: true,
+ startOffset: 0,
+ itemWidth: (latency / totalScaleSpan) * SCALE_WIDTH,
+ latency,
+ isTraceRoot: true,
+ };
+
+ // Flatten all observations with pre-computed costs
+ const flatObservations = flattenTimelineTree(
+ nestedObservations,
+ expandedItems,
+ traceStartTime,
+ totalScaleSpan,
+ costMap,
+ );
+
+ return [traceRootItem, ...flatObservations];
+ }, [
+ nestedObservations,
+ expandedItems,
+ totalScaleSpan,
+ trace,
+ latency,
+ costMap,
+ ]);
+
+ // Calculate dynamic content width from flattened items
+ const dynamicContentWidth = useMemo(() => {
+ const maxEndOffset = flattenedItems.reduce((max, item) => {
+ const endOffset = item.startOffset + item.itemWidth;
+ return Math.max(max, endOffset);
+ }, SCALE_WIDTH);
+
+ return Math.max(SCALE_WIDTH, maxEndOffset + 100); // +100px padding
+ }, [flattenedItems]);
+
+ // Use dynamic content width instead of measured scrollWidth
+ const finalContentWidth = dynamicContentWidth;
+
+ // Set up virtualizer
+ const rowVirtualizer = useVirtualizer({
+ count: flattenedItems.length,
+ getScrollElement: () => timelineContentRef.current,
+ estimateSize: () => 42, // Approximate row height
+ overscan: 500,
+ });
+
+ // Early return after all hooks
+ if (!latency) return null;
return (
<div ref={parentRef} className="h-full w-full px-3">
@@ -575,7 +904,7 @@ export function TraceTimelineView({
}
}}
>
- <div style={{ width: `${contentWidth}px` }}>
+ <div style={{ width: `${finalContentWidth}px` }}>
<div className="mb-2 ml-2">
<div
className="relative mr-2 h-8"
@@ -626,91 +955,96 @@ export function TraceTimelineView({
}
}}
>
- <div className="h-full" style={{ width: `${contentWidth}px` }}>
- {/* Main timeline content */}
+ <div className="h-full" style={{ width: `${finalContentWidth}px` }}>
+ {/* Main timeline content - virtualized */}
<div
ref={timelineContentRef}
className="h-full overflow-y-auto"
- style={{ width: `${contentWidth}px` }}
+ style={{ width: `${finalContentWidth}px` }}
>
- <SimpleTreeView
- expandedItems={expandedItems}
- onExpandedItemsChange={(_, itemIds) =>
- setExpandedItems(itemIds)
- }
- itemChildrenIndentation={TREE_INDENTATION}
- expansionTrigger="iconContainer"
+ <div
+ style={{
+ height: `${rowVirtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
>
- <TreeItem
- key={`trace-${id}`}
- itemId={`trace-${id}`}
- classes={{
- content: `!min-w-fit hover:!bg-background`,
- selected: "!bg-background !important",
- label: "!min-w-fit",
- iconContainer:
- "absolute left-3 top-1/2 z-10 -translate-y-1/2",
- }}
- onClick={(e) => {
- e.stopPropagation();
- const isIconClick = (e.target as HTMLElement).closest(
- "svg.MuiSvgIcon-root",
- );
- if (!isIconClick) {
- setCurrentObservationId(null);
- }
- }}
- label={
- <TreeItemInner
- name={name}
- latency={latency}
- totalScaleSpan={totalScaleSpan}
- type="TRACE"
- hasChildren={!!nestedObservations.length}
- isSelected={currentObservationId === null}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetrics}
- scores={traceScores}
- commentCount={getNumberFromMap(
- traceCommentCounts.data,
- id,
- )}
- totalCost={totalCost}
- />
- }
- >
- {Boolean(nestedObservations.length)
- ? nestedObservations.map((observation) => (
- <TraceTreeItem
- key={`observation-${observation.id}`}
- observation={observation}
- level={1}
- traceStartTime={nestedObservations[0].startTime}
- totalScaleSpan={totalScaleSpan}
- projectId={projectId}
- scores={scores}
- observations={observations}
- cardWidth={cardWidth}
- commentCounts={castToNumberMap(
- observationCommentCounts.data,
- )}
- currentObservationId={currentObservationId}
- setCurrentObservationId={setCurrentObservationId}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- showComments={showComments}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalDuration={totalDuration}
- parentTotalCost={totalCost}
- />
- ))
- : null}
- </TreeItem>
- </SimpleTreeView>
+ {rowVirtualizer.getVirtualItems().map((virtualRow) => {
+ const item = flattenedItems[virtualRow.index];
+ const observationId =
+ item.observation.type === "TRACE"
+ ? `trace-${item.observation.id}`
+ : `observation-${item.observation.id}`;
+ const isExpanded = expandedItems.includes(observationId);
+ const isSelected =
+ item.observation.type === "TRACE"
+ ? currentObservationId === null
+ : item.observation.id === currentObservationId;
+
+ // Get scores for this observation
+ const itemScores =
+ item.observation.type === "TRACE"
+ ? traceScores
+ : scores.filter(
+ (s) => s.observationId === item.observation.id,
+ );
+
+ // Get comment count
+ const commentCount =
+ item.observation.type === "TRACE"
+ ? getNumberFromMap(
+ traceCommentCounts.data,
+ item.observation.id,
+ )
+ : castToNumberMap(observationCommentCounts.data)?.get(
+ item.observation.id,
+ );
+
+ return (
+ <div
+ key={item.observation.id}
+ data-index={virtualRow.index}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ transform: `translateY(${virtualRow.start}px)`,
+ }}
+ >
+ <VirtualizedTimelineRow
+ item={item}
+ totalScaleSpan={totalScaleSpan}
+ isSelected={isSelected}
+ onClick={() => {
+ if (item.observation.type === "TRACE") {
+ setCurrentObservationId(null);
+ } else {
+ setCurrentObservationId(item.observation.id);
+ }
+ }}
+ onToggleExpand={() => {
+ const newItems = expandedItems.includes(observationId)
+ ? expandedItems.filter((id) => id !== observationId)
+ : [...expandedItems, observationId];
+ setExpandedItems(newItems);
+ }}
+ hasChildren={item.observation.children?.length > 0}
+ isExpanded={isExpanded}
+ scores={itemScores}
+ commentCount={commentCount}
+ parentTotalCost={totalCost}
+ parentTotalDuration={totalDuration}
+ showDuration={showDuration}
+ showCostTokens={showCostTokens}
+ showScores={showScores}
+ showComments={showComments}
+ colorCodeMetrics={colorCodeMetrics}
+ />
+ </div>
+ );
+ })}
+ </div>
{minLevel && hiddenObservationsCount > 0 ? (
<div className="flex items-center gap-1 p-2 py-4">
diff --git a/web/src/components/trace/TraceTree.tsx b/web/src/components/trace/TraceTree.tsx
index d8ef018053..3ef4921b1f 100644
--- a/web/src/components/trace/TraceTree.tsx
+++ b/web/src/components/trace/TraceTree.tsx
@@ -5,7 +5,7 @@ import {
ObservationLevel,
type ObservationLevelType,
} from "@langfuse/shared";
-import { Fragment, useMemo, useRef, useEffect, useCallback } from "react";
+import { useMemo, useRef, useLayoutEffect, useCallback } from "react";
import { InfoIcon, ChevronRight } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { ItemBadge } from "@/src/components/ItemBadge";
@@ -18,6 +18,44 @@ import type Decimal from "decimal.js";
import { SpanItem } from "@/src/components/trace/SpanItem";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
import { api } from "@/src/utils/api";
+import { useVirtualizer } from "@tanstack/react-virtual";
+
+type FlatNode = {
+ node: TreeNode;
+ depth: number;
+ treeLines: boolean[];
+ isLastSibling: boolean;
+};
+
+const flattenTree = (
+ node: TreeNode,
+ collapsedNodes: string[],
+ depth = 0,
+ treeLines: boolean[] = [],
+ isLastSibling = true,
+): FlatNode[] => {
+ const flatList: FlatNode[] = [{ node, depth, treeLines, isLastSibling }];
+
+ if (node.children.length > 0 && !collapsedNodes.includes(node.id)) {
+ const sortedChildren = node.children.sort(
+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),
+ );
+ sortedChildren.forEach((child, index) => {
+ const isChildLast = index === sortedChildren.length - 1;
+
+ flatList.push(
+ ...flattenTree(
+ child,
+ collapsedNodes,
+ depth + 1,
+ [...treeLines, !isChildLast],
+ isChildLast,
+ ),
+ );
+ });
+ }
+ return flatList;
+};
export const TraceTree = ({
tree,
@@ -42,7 +80,6 @@ export const TraceTree = ({
tree: TreeNode;
collapsedNodes: string[];
toggleCollapsedNode: (id: string) => void;
- // Note: displayScores are merged with client-side score cache; handling optimistic updates
displayScores: WithStringifiedMetadata<ScoreDomain>[];
currentNodeId: string | undefined;
setCurrentNodeId: (id: string | undefined) => void;
@@ -60,6 +97,7 @@ export const TraceTree = ({
traceId: string;
}) => {
const utils = api.useUtils();
+ const parentRef = useRef<HTMLDivElement>(null);
const handleObservationHover = useCallback(
(node: TreeNode) => {
@@ -72,7 +110,7 @@ export const TraceTree = ({
projectId,
},
{
- staleTime: 5 * 60 * 1000, // don't refetch if data is <5min old
+ staleTime: 5 * 60 * 1000,
},
);
}
@@ -81,15 +119,12 @@ export const TraceTree = ({
);
const totalCost = useMemo(() => {
- // For unified tree, we need to calculate total cost differently
- // Convert TreeNode back to observation format for cost calculation
const convertTreeNodeToObservation = (node: TreeNode): any => ({
...node,
children: node.children.map(convertTreeNodeToObservation),
});
if (tree.type === "TRACE") {
- // For trace root, calculate from all children
const allObservations = tree.children.flatMap((child) =>
unnestObservation(convertTreeNodeToObservation(child)),
);
@@ -101,28 +136,103 @@ export const TraceTree = ({
});
}, [tree]);
+ const flattenedItems = useMemo(() => {
+ // The root node has depth 0, empty treeLines, and isLastSibling=true (it's the only root)
+ return flattenTree(tree, collapsedNodes, 0, [], true);
+ }, [tree, collapsedNodes]);
+
+ const rowVirtualizer = useVirtualizer({
+ count: flattenedItems.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => 37, // Approximate height of a row
+ overscan: 500,
+ });
+
+ // Track initial currentNodeId to detect URL-based navigation vs user clicks
+ const initialCurrentNodeIdRef = useRef(currentNodeId);
+ const hasScrolledOnInitialLoadRef = useRef(false);
+
+ // Handle scrolling to selected observation on initial page load only
+ useLayoutEffect(() => {
+ // Only scroll if:
+ // 1. We have a currentNodeId
+ // 2. We haven't scrolled yet
+ // 3. The currentNodeId matches the initial one (meaning it came from URL, not user click)
+ if (
+ currentNodeId &&
+ !hasScrolledOnInitialLoadRef.current &&
+ currentNodeId === initialCurrentNodeIdRef.current
+ ) {
+ // Find the index of the item with the matching node ID
+ const index = flattenedItems.findIndex(
+ (item) => item.node.id === currentNodeId,
+ );
+
+ if (index !== -1) {
+ // Use virtualizer's scrollToIndex to scroll to the item
+ // This works even if the item isn't rendered yet
+ rowVirtualizer.scrollToIndex(index, {
+ align: "center",
+ behavior: "smooth",
+ });
+ hasScrolledOnInitialLoadRef.current = true;
+ }
+ }
+ }, [currentNodeId, flattenedItems, rowVirtualizer]);
+
return (
- <div className={className}>
- <TreeNodeComponent
- node={tree}
- collapsedNodes={collapsedNodes}
- toggleCollapsedNode={toggleCollapsedNode}
- scores={scores}
- comments={nodeCommentCounts}
- indentationLevel={0}
- currentNodeId={currentNodeId}
- setCurrentNodeId={setCurrentNodeId}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalCost={totalCost}
- parentTotalDuration={tree.latency ? tree.latency * 1000 : undefined}
- showComments={showComments}
- treeLines={[]}
- isLastSibling={true}
- onObservationHover={handleObservationHover}
- />
+ <div
+ ref={parentRef}
+ className={cn("h-full overflow-y-auto", className)}
+ id="trace-tree"
+ >
+ <div
+ style={{
+ height: `${rowVirtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {rowVirtualizer.getVirtualItems().map((virtualRow) => {
+ const item = flattenedItems[virtualRow.index];
+ return (
+ <div
+ key={item.node.id}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ height: `${virtualRow.size}px`,
+ transform: `translateY(${virtualRow.start}px)`,
+ }}
+ >
+ <TraceTreeRow
+ node={item.node}
+ depth={item.depth}
+ treeLines={item.treeLines}
+ isLastSibling={item.isLastSibling}
+ collapsedNodes={collapsedNodes}
+ toggleCollapsedNode={toggleCollapsedNode}
+ scores={scores}
+ comments={nodeCommentCounts}
+ currentNodeId={currentNodeId}
+ setCurrentNodeId={setCurrentNodeId}
+ showDuration={showDuration}
+ showCostTokens={showCostTokens}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ parentTotalCost={totalCost}
+ parentTotalDuration={
+ tree.latency ? tree.latency * 1000 : undefined
+ }
+ showComments={showComments}
+ onObservationHover={handleObservationHover}
+ />
+ </div>
+ );
+ })}
+ </div>
{minLevel && hiddenObservationsCount && hiddenObservationsCount > 0 ? (
<span className="flex items-center gap-1 p-2 py-4">
@@ -146,13 +256,15 @@ export const TraceTree = ({
);
};
-type TreeNodeComponentProps = {
+type TraceTreeRowProps = {
node: TreeNode;
+ depth: number;
+ treeLines: boolean[];
+ isLastSibling: boolean;
collapsedNodes: string[];
toggleCollapsedNode: (id: string) => void;
scores: WithStringifiedMetadata<ScoreDomain>[];
comments?: Map<string, number>;
- indentationLevel: number;
currentNodeId: string | undefined;
setCurrentNodeId: (id: string | undefined) => void;
showDuration: boolean;
@@ -162,18 +274,18 @@ type TreeNodeComponentProps = {
parentTotalCost?: Decimal;
parentTotalDuration?: number;
showComments: boolean;
- treeLines: boolean[]; // Track which levels need vertical lines
- isLastSibling: boolean;
onObservationHover: (node: TreeNode) => void;
};
-const UnmemoizedTreeNodeComponent = ({
+const TraceTreeRow = ({
node,
+ depth,
+ treeLines,
+ isLastSibling,
collapsedNodes,
toggleCollapsedNode,
scores,
comments,
- indentationLevel,
currentNodeId,
setCurrentNodeId,
showDuration,
@@ -183,201 +295,139 @@ const UnmemoizedTreeNodeComponent = ({
parentTotalCost,
parentTotalDuration,
showComments,
- treeLines,
- isLastSibling,
onObservationHover,
-}: TreeNodeComponentProps) => {
+}: TraceTreeRowProps) => {
const capture = usePostHogClientCapture();
const collapsed = collapsedNodes.includes(node.id);
- // Convert TreeNode back to observation format for cost calculation (only for root parent totals outside)
-
- const currentNodeRef = useRef<HTMLButtonElement>(null);
-
- useEffect(() => {
- if (currentNodeId && currentNodeRef.current && currentNodeId === node.id) {
- currentNodeRef.current.scrollIntoView({
- behavior: "smooth",
- block: "center",
- });
- }
- }, [currentNodeId, node.id]);
-
const isSelected =
currentNodeId === node.id || (!currentNodeId && node.type === "TRACE");
return (
- <Fragment>
- <div
- className={cn(
- "relative flex w-full cursor-pointer rounded-md px-0",
- isSelected ? "bg-muted" : "hover:bg-muted/50",
+ <div
+ className={cn(
+ "relative flex w-full cursor-pointer rounded-md px-0",
+ isSelected ? "bg-muted" : "hover:bg-muted/50",
+ )}
+ style={{
+ paddingTop: 0,
+ paddingBottom: 0,
+ borderRadius: "0.5rem",
+ }}
+ onClick={(e) => {
+ if (!e.currentTarget?.closest("[data-expand-button]")) {
+ setCurrentNodeId(node.type === "TRACE" ? undefined : node.id);
+ }
+ }}
+ >
+ <div className="flex w-full pl-2">
+ {/* 1. Indents: ancestor level indicators */}
+ {depth > 0 && (
+ <div className="flex flex-shrink-0">
+ {Array.from({ length: depth - 1 }, (_, i) => (
+ <div key={i} className="relative w-5">
+ {treeLines[i] && (
+ <div className="absolute bottom-0 left-3 top-0 w-px bg-border" />
+ )}
+ </div>
+ ))}
+ </div>
)}
- style={{
- paddingTop: 0,
- paddingBottom: 0,
- borderRadius: "0.5rem",
- }}
- onClick={(e) => {
- // Only handle clicks that aren't on the expand/collapse button
- if (!e.currentTarget?.closest("[data-expand-button]")) {
- setCurrentNodeId(node.type === "TRACE" ? undefined : node.id);
- }
- }}
- >
- <div className="flex w-full pl-2">
- {/* 1. Indents: ancestor level indicators */}
- {indentationLevel > 0 && (
- <div className="flex flex-shrink-0">
- {Array.from({ length: indentationLevel - 1 }, (_, i) => (
- <div key={i} className="relative w-5">
- {treeLines[i] && (
- <div className="absolute bottom-0 left-3 top-0 w-px bg-border" />
- )}
- </div>
- ))}
- </div>
- )}
- {/* 2. Current element bars: up/down/horizontal connectors */}
- {indentationLevel > 0 && (
- <div className="relative w-5 flex-shrink-0">
- <>
- {/* Vertical bar connecting upwards */}
- <div
- className={cn(
- "absolute left-3 top-0 w-px bg-border",
- isLastSibling ? "h-3" : "bottom-3",
- )}
- />
- {/* Vertical bar connecting downwards if not last sibling */}
- {!isLastSibling && (
- <div className="absolute bottom-0 left-3 top-3 w-px bg-border" />
+ {/* 2. Current element bars: up/down/horizontal connectors */}
+ {depth > 0 && (
+ <div className="relative w-5 flex-shrink-0">
+ <>
+ {/* Vertical bar connecting upwards */}
+ <div
+ className={cn(
+ "absolute left-3 top-0 w-px bg-border",
+ isLastSibling ? "h-3" : "bottom-3",
)}
- {/* Horizontal bar connecting to icon */}
- <div className="absolute left-3 top-3 h-px w-2 bg-border" />
- </>
- </div>
- )}
-
- {/* 3. Icon + child connector: fixed width container */}
- <div className="relative flex w-6 flex-shrink-0 flex-col py-1.5">
- <div className="relative z-10 flex h-4 items-center justify-center">
- <ItemBadge type={node.type} isSmall className="!size-3" />
- </div>
- {/* Vertical bar downwards if there are expanded children */}
- {node.children.length > 0 && !collapsed && (
- <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />
- )}
- {/* Root node downward connector */}
- {indentationLevel === 0 &&
- node.children.length > 0 &&
- !collapsed && (
- <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />
+ />
+ {/* Vertical bar connecting downwards if not last sibling */}
+ {!isLastSibling && (
+ <div className="absolute bottom-0 left-3 top-3 w-px bg-border" />
)}
+ {/* Horizontal bar connecting to icon */}
+ <div className="absolute left-3 top-3 h-px w-2 bg-border" />
+ </>
</div>
+ )}
- {/* 4. Content button: just the text/metrics content */}
- {/* eslint-disable-next-line jsx-a11y/role-supports-aria-props */}
- <button
- type="button"
- aria-selected={isSelected}
- onClick={(e) => {
- e.stopPropagation();
- setCurrentNodeId(node.type === "TRACE" ? undefined : node.id);
- }}
- onMouseEnter={() => onObservationHover(node)}
- title={node.name}
- className={cn(
- "peer relative flex min-w-0 flex-1 items-start rounded-md py-0.5 pl-1 pr-2 text-left",
- )}
- ref={currentNodeRef}
- >
- <SpanItem
- node={node}
- scores={scores}
- comments={comments}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalCost={parentTotalCost}
- parentTotalDuration={parentTotalDuration}
- showComments={showComments}
- />
- </button>
-
- {/* 5. Expand/Collapse button */}
- {node.children.length > 0 && (
- <div className="flex items-center justify-end py-1 pr-1">
- <Button
- data-expand-button
- size="icon"
- variant="ghost"
- onClick={(ev) => {
- ev.stopPropagation();
- toggleCollapsedNode(node.id);
- capture(
- collapsed
- ? "trace_detail:observation_tree_expand"
- : "trace_detail:observation_tree_collapse",
- { type: "single", nodeType: node.type },
- );
- }}
- className="h-6 w-6 flex-shrink-0 hover:bg-primary/10"
- >
- <span
- className={cn(
- "inline-block h-4 w-4 transform transition-transform duration-200 ease-in-out",
- collapsed ? "rotate-0" : "rotate-90",
- )}
- >
- <ChevronRight className="h-4 w-4" />
- </span>
- </Button>
- </div>
+ {/* 3. Icon + child connector: fixed width container */}
+ <div className="relative flex w-6 flex-shrink-0 flex-col py-1.5">
+ <div className="relative z-10 flex h-4 items-center justify-center">
+ <ItemBadge type={node.type} isSmall className="!size-3" />
+ </div>
+ {/* Vertical bar downwards if there are expanded children */}
+ {node.children.length > 0 && !collapsed && (
+ <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />
+ )}
+ {/* Root node downward connector */}
+ {depth === 0 && node.children.length > 0 && !collapsed && (
+ <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />
)}
</div>
- </div>
- {/* Render children */}
- {node.children.length > 0 && (
- <div className={cn("flex w-full flex-col", collapsed && "hidden")}>
- {node.children
- .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
- .map((childNode, index) => {
- const isChildLastSibling = index === node.children.length - 1;
- // Add to treeLines: whether there are more children after this one (determines if vertical line should continue)
- const childTreeLines = [...treeLines, !isChildLastSibling];
+ {/* 4. Content button: just the text/metrics content */}
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ setCurrentNodeId(node.type === "TRACE" ? undefined : node.id);
+ }}
+ onMouseEnter={() => onObservationHover(node)}
+ title={node.name}
+ className={cn(
+ "peer relative flex min-w-0 flex-1 items-start rounded-md py-0.5 pl-1 pr-2 text-left",
+ )}
+ >
+ <SpanItem
+ node={node}
+ scores={scores}
+ comments={comments}
+ showDuration={showDuration}
+ showCostTokens={showCostTokens}
+ showScores={showScores}
+ colorCodeMetrics={colorCodeMetrics}
+ parentTotalCost={parentTotalCost}
+ parentTotalDuration={parentTotalDuration}
+ showComments={showComments}
+ />
+ </button>
- return (
- <TreeNodeComponent
- key={childNode.id}
- node={childNode}
- collapsedNodes={collapsedNodes}
- toggleCollapsedNode={toggleCollapsedNode}
- scores={scores}
- comments={comments}
- indentationLevel={indentationLevel + 1}
- currentNodeId={currentNodeId}
- setCurrentNodeId={setCurrentNodeId}
- showDuration={showDuration}
- showCostTokens={showCostTokens}
- showScores={showScores}
- colorCodeMetrics={colorCodeMetrics}
- parentTotalCost={parentTotalCost}
- parentTotalDuration={parentTotalDuration}
- showComments={showComments}
- treeLines={childTreeLines}
- isLastSibling={isChildLastSibling}
- onObservationHover={onObservationHover}
- />
- );
- })}
- </div>
- )}
- </Fragment>
+ {/* 5. Expand/Collapse button */}
+ {node.children.length > 0 && (
+ <div className="flex items-center justify-end py-1 pr-1">
+ <Button
+ data-expand-button
+ size="icon"
+ variant="ghost"
+ onClick={(ev) => {
+ ev.stopPropagation();
+ toggleCollapsedNode(node.id);
+ capture(
+ collapsed
+ ? "trace_detail:observation_tree_expand"
+ : "trace_detail:observation_tree_collapse",
+ { type: "single", nodeType: node.type },
+ );
+ }}
+ className="h-6 w-6 flex-shrink-0 hover:bg-primary/10"
+ >
+ <span
+ className={cn(
+ "inline-block h-4 w-4 transform transition-transform duration-200 ease-in-out",
+ collapsed ? "rotate-0" : "rotate-90",
+ )}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </span>
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
);
};
-
-const TreeNodeComponent = UnmemoizedTreeNodeComponent;
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 9ac90f4033..62861b2ec2 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -330,11 +330,14 @@ export function Trace(props: {
tree: traceTree,
hiddenObservationsCount,
searchItems,
- } = useMemo(
- () =>
- buildTraceUiData(props.trace, props.observations, minObservationLevel),
- [props.trace, props.observations, minObservationLevel],
- );
+ nodeMap,
+ } = useMemo(() => {
+ return buildTraceUiData(
+ props.trace,
+ props.observations,
+ minObservationLevel,
+ );
+ }, [props.trace, props.observations, minObservationLevel]);
// Compute these outside the component to avoid recreation
const hasQuery = (searchQuery ?? "").trim().length > 0;
@@ -392,6 +395,12 @@ export function Trace(props: {
/>
);
+ // Find the selected node to pass pre-computed cost to preview
+ const selectedNode = useMemo(() => {
+ if (!currentObservationId) return null;
+ return nodeMap.get(currentObservationId) ?? null;
+ }, [nodeMap, currentObservationId]);
+
const previewContent =
currentObservationId === undefined ||
currentObservationId === "" ||
@@ -403,6 +412,7 @@ export function Trace(props: {
serverScores={props.scores}
commentCounts={castToNumberMap(traceCommentCounts.data)}
viewType={viewType}
+ precomputedCost={traceTree.totalCost}
/>
) : isValidObservationId ? (
<ObservationPreview
@@ -414,6 +424,7 @@ export function Trace(props: {
commentCounts={castToNumberMap(observationCommentCounts.data)}
viewType={viewType}
isTimeline={props.selectedTab?.includes("timeline")}
+ precomputedCost={selectedNode?.totalCost}
/>
) : null;
@@ -435,14 +446,16 @@ export function Trace(props: {
Node display
</span>
) : (
- <CommandInput
- showBorder={false}
- placeholder="Search"
- className="-ml-2 h-9 min-w-20 border-0 focus:ring-0"
- value={searchInputValue}
- onValueChange={handleSearchInputChange}
- onKeyDown={handleSearchKeyDown}
- />
+ <div className="relative flex-1">
+ <CommandInput
+ showBorder={false}
+ placeholder="Search"
+ className="-ml-2 h-9 min-w-20 border-0 focus:ring-0"
+ value={searchInputValue}
+ onValueChange={handleSearchInputChange}
+ onKeyDown={handleSearchKeyDown}
+ />
+ </div>
)}
{viewType === "detailed" && (
<div className="flex flex-row items-center gap-0.5">
@@ -602,6 +615,7 @@ export function Trace(props: {
colorCodeMetrics={colorCodeMetricsOnObservationTree}
minLevel={minObservationLevel}
setMinLevel={setMinObservationLevel}
+ tree={traceTree}
/>
</div>
) : (
@@ -678,14 +692,16 @@ export function Trace(props: {
Node display
</span>
) : (
- <CommandInput
- showBorder={false}
- placeholder="Search"
- className="h-7 min-w-20 border-0 pr-0 focus:ring-0"
- value={searchInputValue}
- onValueChange={handleSearchInputChange}
- onKeyDown={handleSearchKeyDown}
- />
+ <div className="relative flex-1">
+ <CommandInput
+ showBorder={false}
+ placeholder="Search"
+ className="h-7 min-w-20 border-0 pr-0 focus:ring-0"
+ value={searchInputValue}
+ onValueChange={handleSearchInputChange}
+ onKeyDown={handleSearchKeyDown}
+ />
+ </div>
)}
{viewType === "detailed" && (
<div className="flex flex-row items-center gap-0.5">
@@ -902,6 +918,7 @@ export function Trace(props: {
}
minLevel={minObservationLevel}
setMinLevel={setMinObservationLevel}
+ tree={traceTree}
/>
</ResizablePanel>
@@ -944,6 +961,7 @@ export function Trace(props: {
}
minLevel={minObservationLevel}
setMinLevel={setMinObservationLevel}
+ tree={traceTree}
/>
</div>
)}
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
index beaf0f1816..7955b96494 100644
--- a/web/src/components/trace/lib/helpers.ts
+++ b/web/src/components/trace/lib/helpers.ts
@@ -28,10 +28,13 @@ export function nestObservations(
);
const hiddenObservationsCount = list.length - mutableList.length;
+ // Build a Set of all observation IDs for O(1) lookup instead of O(n) find
+ const observationIds = new Set(list.map((o) => o.id));
+
mutableList.forEach((observation) => {
if (
observation.parentObservationId &&
- !list.find((o) => o.id === observation.parentObservationId)
+ !observationIds.has(observation.parentObservationId)
) {
observation.parentObservationId = null;
}
@@ -194,6 +197,70 @@ export const unnestObservation = (nestedObservation: NestedObservation) => {
};
// Transform trace + observations into unified tree structure
+// Helper function to compute and enrich tree nodes with pre-computed costs
+// This is done bottom-up: compute children first, then sum up to parent
+// Also populates the nodeMap for O(1) lookup by ID
+function enrichTreeNodeWithCosts(
+ node: TreeNode,
+ nodeMap: Map<string, TreeNode>,
+): TreeNode {
+ // First, recursively enrich all children
+ const enrichedChildren = node.children.map((child) =>
+ enrichTreeNodeWithCosts(child, nodeMap),
+ );
+
+ // Calculate this node's own cost
+ let nodeCost: Decimal | undefined;
+
+ if (node.calculatedTotalCost != null) {
+ const cost = new Decimal(node.calculatedTotalCost);
+ if (!cost.isZero()) {
+ nodeCost = cost;
+ }
+ } else if (
+ node.calculatedInputCost != null ||
+ node.calculatedOutputCost != null
+ ) {
+ const inputCost =
+ node.calculatedInputCost != null
+ ? new Decimal(node.calculatedInputCost)
+ : new Decimal(0);
+ const outputCost =
+ node.calculatedOutputCost != null
+ ? new Decimal(node.calculatedOutputCost)
+ : new Decimal(0);
+ const combinedCost = inputCost.plus(outputCost);
+ if (!combinedCost.isZero()) {
+ nodeCost = combinedCost;
+ }
+ }
+
+ // Sum up all children's total costs
+ const childrenTotalCost = enrichedChildren.reduce<Decimal | undefined>(
+ (acc, child) => {
+ if (!child.totalCost) return acc;
+ return acc ? acc.plus(child.totalCost) : child.totalCost;
+ },
+ undefined,
+ );
+
+ // Total cost = this node's cost + all children's costs
+ const totalCost =
+ nodeCost && childrenTotalCost
+ ? nodeCost.plus(childrenTotalCost)
+ : nodeCost || childrenTotalCost;
+
+ const enrichedNode = {
+ ...node,
+ children: enrichedChildren,
+ totalCost,
+ };
+
+ nodeMap.set(enrichedNode.id, enrichedNode);
+
+ return enrichedNode;
+}
+
// This function is only used internally by buildTraceUiData
function buildTraceTree(
trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
@@ -206,6 +273,7 @@ function buildTraceTree(
): {
tree: TreeNode;
hiddenObservationsCount: number;
+ nodeMap: Map<string, TreeNode>;
} {
// First, nest the observations as before
const { nestedObservations, hiddenObservationsCount } = nestObservations(
@@ -213,6 +281,9 @@ function buildTraceTree(
minLevel,
);
+ // Create nodeMap for O(1) lookup by ID
+ const nodeMap = new Map<string, TreeNode>();
+
// Convert observations to TreeNodes
const convertObservationToTreeNode = (obs: NestedObservation): TreeNode => ({
id: obs.id,
@@ -225,16 +296,27 @@ function buildTraceTree(
inputUsage: obs.inputUsage,
outputUsage: obs.outputUsage,
totalUsage: obs.totalUsage,
- calculatedInputCost:
- "calculatedInputCost" in obs ? obs.calculatedInputCost : undefined,
- calculatedOutputCost:
- "calculatedOutputCost" in obs ? obs.calculatedOutputCost : undefined,
- calculatedTotalCost:
- "calculatedTotalCost" in obs ? obs.calculatedTotalCost : undefined,
+ calculatedInputCost: obs.inputCost,
+ calculatedOutputCost: obs.outputCost,
+ calculatedTotalCost: obs.totalCost,
parentObservationId: obs.parentObservationId,
traceId: obs.traceId,
});
+ // Convert and enrich children with pre-computed costs and populate nodeMap
+ const enrichedChildren = nestedObservations
+ .map(convertObservationToTreeNode)
+ .map((node) => enrichTreeNodeWithCosts(node, nodeMap));
+
+ // Calculate total cost for trace root (sum of all top-level children)
+ const traceTotalCost = enrichedChildren.reduce<Decimal | undefined>(
+ (acc, child) => {
+ if (!child.totalCost) return acc;
+ return acc ? acc.plus(child.totalCost) : child.totalCost;
+ },
+ undefined,
+ );
+
// Create the root tree node (trace)
// Use a unique ID for the trace root to avoid conflicts with observations that might have the same ID
const tree: TreeNode = {
@@ -243,11 +325,15 @@ function buildTraceTree(
name: trace.name ?? "",
startTime: trace.timestamp,
endTime: null, // traces don't have explicit end times
- children: nestedObservations.map(convertObservationToTreeNode),
+ children: enrichedChildren,
latency: trace.latency,
+ totalCost: traceTotalCost,
};
- return { tree, hiddenObservationsCount };
+ // Add trace root to nodeMap as well
+ nodeMap.set(tree.id, tree);
+
+ return { tree, hiddenObservationsCount, nodeMap };
}
// UI helper: build flat search items with per-node aggregated totals and root-level parent totals for heatmap scaling
@@ -264,8 +350,9 @@ export function buildTraceUiData(
tree: TreeNode;
hiddenObservationsCount: number;
searchItems: TraceSearchListItem[];
+ nodeMap: Map<string, TreeNode>;
} {
- const { tree, hiddenObservationsCount } = buildTraceTree(
+ const { tree, hiddenObservationsCount, nodeMap } = buildTraceTree(
trace,
observations,
minLevel,
@@ -278,7 +365,10 @@ export function buildTraceUiData(
let nodeCost: Decimal | undefined;
if (node.calculatedTotalCost != null) {
- nodeCost = new Decimal(node.calculatedTotalCost);
+ const cost = new Decimal(node.calculatedTotalCost);
+ if (!cost.isZero()) {
+ nodeCost = cost;
+ }
} else if (
node.calculatedInputCost != null ||
node.calculatedOutputCost != null
@@ -339,7 +429,7 @@ export function buildTraceUiData(
};
visit(tree);
- return { tree, hiddenObservationsCount, searchItems: out };
+ return { tree, hiddenObservationsCount, searchItems: out, nodeMap };
}
/**
diff --git a/web/src/components/trace/lib/types.ts b/web/src/components/trace/lib/types.ts
index beae64bb52..76be410caa 100644
--- a/web/src/components/trace/lib/types.ts
+++ b/web/src/components/trace/lib/types.ts
@@ -1,4 +1,5 @@
import { type ObservationType } from "@langfuse/shared";
+import type Decimal from "decimal.js";
// Unified tree node type for trace tree component
export type TreeNode = {
@@ -16,6 +17,10 @@ export type TreeNode = {
calculatedInputCost?: any;
calculatedOutputCost?: any;
calculatedTotalCost?: any;
+ // Pre-computed cost for this node + all descendants
+ // Calculated bottom-up during tree construction for O(1) access
+ // Will be undefined if neither this node nor any descendants have cost data
+ totalCost?: Decimal;
// Trace-specific properties (when type === 'TRACE')
latency?: number;
// Observation-specific properties (when type !== 'TRACE')
diff --git a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
index 82104007e7..14c2585ae5 100644
--- a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
@@ -6,13 +6,14 @@ import {
AnnotationQueueObjectType,
type ScoreConfigDomain,
} from "@langfuse/shared";
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { StringParam, useQueryParam } from "use-query-params";
import { AnnotationDrawerSection } from "../shared/AnnotationDrawerSection";
import { AnnotationProcessingLayout } from "../shared/AnnotationProcessingLayout";
import { api } from "@/src/utils/api";
import { castToNumberMap } from "@/src/utils/map-utils";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
+import { buildTraceUiData } from "@/src/components/trace/lib/helpers";
interface TraceAnnotationProcessorProps {
item: AnnotationQueueItem & {
@@ -80,6 +81,13 @@ export const TraceAnnotationProcessor: React.FC<
} else setCurrentObservationId(undefined);
}, [view, item, setCurrentObservationId]);
+ const { tree: traceTree, nodeMap } = useMemo(() => {
+ if (!data || !data.observations) {
+ return { tree: null, nodeMap: new Map() };
+ }
+ return buildTraceUiData(data, data.observations);
+ }, [data]);
+
if (!data) return <div className="p-3">Loading...</div>;
let isValidObservationId = false;
@@ -105,6 +113,7 @@ export const TraceAnnotationProcessor: React.FC<
viewType="focused"
showCommentButton={true}
commentCounts={castToNumberMap(traceCommentCounts.data)}
+ precomputedCost={traceTree?.totalCost}
/>
) : (
<ObservationPreview
@@ -112,6 +121,7 @@ export const TraceAnnotationProcessor: React.FC<
serverScores={data.scores}
projectId={item.projectId}
currentObservationId={item.objectId}
+ precomputedCost={nodeMap.get(item.objectId)?.totalCost}
traceId={traceId}
viewType="focused"
showCommentButton={true}