🪢 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
feat(trace): events based observation/trace table (#11519)
Nimar99562dbc6d60
diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.tsindex 535bdeecd8..db87bbf15a 100644--- a/packages/shared/src/eventsTable.ts+++ b/packages/shared/src/eventsTable.ts@@ -73,6 +73,14 @@ export const eventsTableCols: ColumnDefinition[] = [internal: "e.session_id",nullable: true,},+ {+ name: "Trace Name",+ id: "traceName",+ type: "stringOptions",+ internal: "e.trace_name",+ options: [], // to be added at runtime+ nullable: true,+ },{name: "Level",id: "level",@@ -235,4 +243,10 @@ export const eventsTableCols: ColumnDefinition[] = [type: "string",internal: "", // handled by comment filter helpers},+ {+ name: "Has Parent Observation",+ id: "hasParentObservation",+ type: "boolean",+ internal: "e.parent_span_id != ''",+ },];diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex f30d2c91ba..161b702a0f 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -1373,6 +1373,45 @@ export const getEventsGroupedByName = async (return res;};+/**+ * Get grouped trace names from events table+ * Used for filter options+ */+export const getEventsGroupedByTraceName = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: "e.trace_name",+ selectExpression: "e.trace_name as traceName, count() as count",+ })+ .where(appliedEventsFilter)+ .whereRaw("e.trace_name IS NOT NULL AND length(e.trace_name) > 0")+ .orderBy("ORDER BY count() DESC")+ .limit(1000, 0);++ const { query, params } = queryBuilder.buildWithParams();++ const res = await queryClickhouse<{ traceName: string; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ });+ return res;+};+/*** Get grouped prompt names from events table* Used for filter options@@ -1753,6 +1792,54 @@ export const deleteEventsByProjectId = async (return true;};+export async function getAgentGraphDataFromEventsTable(params: {+ projectId: string;+ traceId: string;+ chMinStartTime: string;+ chMaxStartTime: string;+}) {+ const { projectId, traceId, chMinStartTime, chMaxStartTime } = params;++ const query = `+ SELECT+ e.span_id as id,+ e.parent_span_id as parent_observation_id,+ e.type as type,+ e.name as name,+ e.start_time as start_time,+ e.end_time as end_time,+ mapFromArrays(e.metadata_names, e.metadata_prefixes)['langgraph_node'] AS node,+ mapFromArrays(e.metadata_names, e.metadata_prefixes)['langgraph_step'] AS step+ FROM events e+ WHERE+ e.project_id = {projectId: String}+ AND e.trace_id = {traceId: String}+ AND e.start_time >= {chMinStartTime: DateTime64(3)}+ AND e.start_time <= {chMaxStartTime: DateTime64(3)}+ `;++ return measureAndReturn({+ operationName: "getAgentGraphDataFromEventsTable",+ projectId,+ input: {+ params: { projectId, traceId, chMinStartTime, chMaxStartTime },+ tags: {+ feature: "tracing",+ type: "events",+ kind: "agentGraphData",+ projectId,+ },+ },+ fn: async (input) => {+ return queryClickhouse({+ query,+ params: input.params,+ tags: input.tags,+ });+ },+ });+}+export const hasAnyEventOlderThan = async (projectId: string,beforeDate: Date,@@ -1828,6 +1915,7 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {}>;minStartTime: Date;maxStartTime: Date;+ truncated?: boolean; // Default true for performance, false for full data}): Promise<Array<Pick<Observation, "id" | "input" | "output" | "metadata">>> => {@@ -1835,6 +1923,8 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {return [];}+ const truncated = opts.truncated ?? true;+// Extract IDs and trace IDs for filteringconst observationIds = opts.observations.map((o) => o.id);const traceIds = [...new Set(opts.observations.map((o) => o.traceId))];@@ -1843,11 +1933,18 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {const minTimestamp = new Date(opts.minStartTime.getTime() - 1000); // -1 second bufferconst maxTimestamp = new Date(opts.maxStartTime.getTime() + 1000); // +1 second buffer+ const inputSelect = truncated+ ? `leftUTF8(e.input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input`+ : `e.input as input`;+ const outputSelect = truncated+ ? `leftUTF8(e.output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as output`+ : `e.output as output`;+const query = `SELECTe.span_id as id,- leftUTF8(e.input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input,- leftUTF8(e.output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as output,+ ${inputSelect},+ ${outputSelect},mapFromArrays(e.metadata_names, e.metadata_prefixes) as metadataFROM events eWHERE e.project_id = {projectId: String}diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.tsindex eaab2b049a..cba84e7f1d 100644--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts@@ -221,6 +221,12 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [clickhouseTableName: "events",clickhouseSelect: 'e."environment"',},+ {+ uiTableName: "Has Parent Observation",+ uiTableId: "hasParentObservation",+ clickhouseTableName: "events",+ clickhouseSelect: "e.parent_span_id != ''",+ },];export const eventsTableUiColumnDefinitions: UiColumnMappings = [diff --git a/web/src/components/table/peek/hooks/usePeekData.ts b/web/src/components/table/peek/hooks/usePeekData.tsindex 06e99bcd78..d4a72021ec 100644--- a/web/src/components/table/peek/hooks/usePeekData.ts+++ b/web/src/components/table/peek/hooks/usePeekData.ts@@ -1,4 +1,6 @@import { api } from "@/src/utils/api";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";+import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";type UsePeekDataProps = {projectId: string;@@ -11,14 +13,17 @@ export const usePeekData = ({traceId,timestamp,}: UsePeekDataProps) => {- return api.traces.byIdWithObservationsAndScores.useQuery(+ const { isBetaEnabled } = useObservationListBeta();++ // Old path: fetch from traces table (beta OFF)+ const tracesQuery = api.traces.byIdWithObservationsAndScores.useQuery({traceId: traceId as string,projectId,timestamp,},{- enabled: !!traceId,+ enabled: !!traceId && !isBetaEnabled,retry(failureCount, error) {if (error.data?.code === "UNAUTHORIZED") return false;return failureCount < 3;@@ -26,4 +31,26 @@ export const usePeekData = ({staleTime: 60 * 1000, // 1 minute},);++ // New path: fetch from events table (beta ON)+ const eventsData = useEventsTraceData({+ projectId,+ traceId: traceId ?? "",+ timestamp,+ enabled: !!traceId && isBetaEnabled,+ });++ // Return the appropriate data based on beta toggle+ if (isBetaEnabled) {+ return {+ data: eventsData.data,+ isLoading: eventsData.isLoading,+ error: eventsData.error,+ // Provide stub for other fields to match tracesQuery return type+ isError: !!eventsData.error,+ isFetching: eventsData.isLoading,+ };+ }++ return tracesQuery;};diff --git a/web/src/components/trace2/ObservationPreview.tsx b/web/src/components/trace2/ObservationPreview.tsxindex d3533e9493..e4a2a99ef6 100644--- a/web/src/components/trace2/ObservationPreview.tsx+++ b/web/src/components/trace2/ObservationPreview.tsx@@ -120,7 +120,7 @@ export const ObservationPreview = ({// Fetch and parse observation input/output in background (Web Worker)const {- observation: observationWithIO,+ observation: observationWithIORaw,parsedInput,parsedOutput,parsedMetadata,@@ -131,8 +131,16 @@ export const ObservationPreview = ({traceId: traceId,projectId: projectId,startTime: currentObservation?.startTime,+ baseObservation: currentObservation,});+ // Type narrowing: when baseObservation is provided, result has full observation fields+ // (EventBatchIOOutput case only occurs when baseObservation is missing)+ const observationWithIO =+ observationWithIORaw && "type" in observationWithIORaw+ ? observationWithIORaw+ : undefined;+const observationMedia = api.media.getByTraceOrObservationId.useQuery({traceId: traceId,diff --git a/web/src/components/trace2/TracePage.tsx b/web/src/components/trace2/TracePage.tsxindex a6f2edf1fd..231ccebee4 100644--- a/web/src/components/trace2/TracePage.tsx+++ b/web/src/components/trace2/TracePage.tsx@@ -14,6 +14,8 @@ import { Button } from "@/src/components/ui/button";import Link from "next/link";import { stripBasePath } from "@/src/utils/redirect";import { Badge } from "@/src/components/ui/badge";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";+import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";export function TracePage({traceId,@@ -25,14 +27,17 @@ export function TracePage({const router = useRouter();const session = useSession();const routeProjectId = (router.query.projectId as string) ?? "";+ const { isBetaEnabled } = useObservationListBeta();- const trace = api.traces.byIdWithObservationsAndScores.useQuery(+ // Old path: fetch from traces table (beta OFF)+ const tracesQuery = api.traces.byIdWithObservationsAndScores.useQuery({traceId,timestamp,projectId: routeProjectId,},{+ enabled: !isBetaEnabled,retry(failureCount, error) {if (error.data?.code === "UNAUTHORIZED" ||@@ -44,6 +49,23 @@ export function TracePage({},);+ // New path: fetch from events table (beta ON)+ const eventsData = useEventsTraceData({+ projectId: routeProjectId,+ traceId,+ timestamp,+ enabled: isBetaEnabled,+ });++ // Use the appropriate data source based on beta toggle+ const trace = isBetaEnabled+ ? {+ data: eventsData.data,+ isLoading: eventsData.isLoading,+ error: eventsData.error as typeof tracesQuery.error,+ }+ : tracesQuery;+const projectIdForAccessCheck = trace.data?.projectId ?? routeProjectId;const hasProjectAccess = useIsAuthenticatedAndProjectMember(projectIdForAccessCheck,@@ -54,10 +76,11 @@ export function TracePage({withDefault(StringParam, "details"),);- if (trace.error?.data?.code === "UNAUTHORIZED")+ // Handle errors - for events path, we check if there's no data after loading+ if (!isBetaEnabled && tracesQuery.error?.data?.code === "UNAUTHORIZED")return <ErrorPage message="You do not have access to this trace." />;- if (trace.error?.data?.code === "NOT_FOUND")+ if (!isBetaEnabled && tracesQuery.error?.data?.code === "NOT_FOUND")return (<ErrorPagetitle="Trace not found"@@ -69,6 +92,19 @@ export function TracePage({/>);+ // For events path: show not found if no observations found after loading+ if (isBetaEnabled && !eventsData.isLoading && !eventsData.data)+ return (+ <ErrorPage+ title="Trace not found"+ message="No observations found for this trace. The trace may still be processing or has been deleted."+ additionalButton={{+ label: "Retry",+ onClick: () => void window.location.reload(),+ }}+ />+ );+if (!trace.data) return <div className="p-3">Loading...</div>;const isSharedTrace = trace.data.public;diff --git a/web/src/components/trace2/api/usePrefetchObservation.ts b/web/src/components/trace2/api/usePrefetchObservation.tsindex c8c8cf34af..1fde54c952 100644--- a/web/src/components/trace2/api/usePrefetchObservation.ts+++ b/web/src/components/trace2/api/usePrefetchObservation.ts@@ -1,4 +1,5 @@import { api } from "@/src/utils/api";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";export type UsePrefetchObservationParams = {projectId: string;@@ -12,23 +13,42 @@ export function usePrefetchObservation({projectId,}: UsePrefetchObservationParams) {const utils = api.useUtils();+ const { isBetaEnabled } = useObservationListBeta();const prefetch = (observationId: string,traceId: string,startTime?: Date,) => {- void utils.observations.byId.prefetch(- {- observationId,- traceId,- projectId,- startTime,- },- {- staleTime: 5 * 60 * 1000, // 5 minutes - matches old trace behavior- },- );+ if (isBetaEnabled) {+ // Beta ON: prefetch from events table via batchIO+ if (!startTime) return;+ void utils.events.batchIO.prefetch(+ {+ projectId,+ observations: [{ id: observationId, traceId }],+ minStartTime: startTime,+ maxStartTime: startTime,+ truncated: false, // Must match useLogViewObservationIO for cache hit+ },+ {+ staleTime: 5 * 60 * 1000, // 5 minutes+ },+ );+ } else {+ // Beta OFF: prefetch from observations table+ void utils.observations.byId.prefetch(+ {+ observationId,+ traceId,+ projectId,+ startTime,+ },+ {+ staleTime: 5 * 60 * 1000, // 5 minutes+ },+ );+ }};return { prefetch };diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsxindex c0c1ed91dc..1bedb80593 100644--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx@@ -49,12 +49,19 @@ export interface ObservationDetailViewProps {observation: ObservationReturnTypeWithMetadata;projectId: string;traceId: string;+ // shows trace-like properties (userId, sessionId) if true+ isRoot?: boolean;+ sessionId?: string | null;+ userId?: string | null;}export function ObservationDetailView({observation,projectId,traceId,+ isRoot = false,+ sessionId,+ userId,}: ObservationDetailViewProps) {// Tab and view state from URL (via SelectionContext)// For observations, "log" tab doesn't apply - map to "preview"@@ -147,7 +154,7 @@ export function ObservationDetailView({// Fetch and parse observation input/output in background (Web Worker)// This combines tRPC fetch + non-blocking JSON parsingconst {- observation: observationWithIO,+ observation: observationWithIORaw,parsedInput,parsedOutput,parsedMetadata,@@ -158,8 +165,16 @@ export function ObservationDetailView({traceId: traceId,projectId: projectId,startTime: observation.startTime,+ baseObservation: observation,});+ // Type narrowing: when baseObservation is provided, result has full observation fields+ // (EventBatchIOOutput case only occurs when baseObservation is missing)+ const observationWithIO =+ observationWithIORaw && "type" in observationWithIORaw+ ? observationWithIORaw+ : undefined;+// For backward compatibility, create observationWithIO query-like objectconst observationWithIOCompat = {data: observationWithIO,@@ -214,6 +229,9 @@ export function ObservationDetailView({onSelectionUsed={handleSelectionUsed}isCommentDrawerOpen={isCommentDrawerOpen}onCommentDrawerOpenChange={setIsCommentDrawerOpen}+ isRoot={isRoot}+ sessionId={sessionId}+ userId={userId}/>{/* Tabs section */}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsxindex 3cd5131383..5813a1b737 100644--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx@@ -34,6 +34,10 @@ import {LevelBadge,StatusMessageBadge,} from "./ObservationMetadataBadgesSimple";+import {+ SessionBadge,+ UserIdBadge,+} from "../TraceDetailView/TraceMetadataBadges";import { CostBadge, UsageBadge } from "./ObservationMetadataBadgesTooltip";import { ModelBadge } from "./ObservationMetadataBadgeModel";import { ModelParametersBadges } from "./ObservationMetadataBadgeModelParameters";@@ -63,6 +67,10 @@ export interface ObservationDetailViewHeaderProps {onSelectionUsed?: () => void;isCommentDrawerOpen?: boolean;onCommentDrawerOpenChange?: (open: boolean) => void;+ // shows trace-like properties (userId, sessionId) if true+ isRoot?: boolean;+ sessionId?: string | null;+ userId?: string | null;}export const ObservationDetailViewHeader = memo(@@ -78,6 +86,9 @@ export const ObservationDetailViewHeader = memo(onSelectionUsed,isCommentDrawerOpen,onCommentDrawerOpenChange,+ isRoot = false,+ sessionId,+ userId,}: ObservationDetailViewHeaderProps) {// Format cost and usage valuesconst totalCost = observation.totalCost;@@ -179,6 +190,16 @@ export const ObservationDetailViewHeader = memo(<TimeToFirstTokenBadgetimeToFirstToken={observation.timeToFirstToken}/>+ {/* Trace-like badges shown when this is root observation */}+ {isRoot && (+ <SessionBadge+ sessionId={sessionId ?? null}+ projectId={projectId}+ />+ )}+ {isRoot && (+ <UserIdBadge userId={userId ?? null} projectId={projectId} />+ )}<EnvironmentBadge environment={observation.environment} /><CostBadgetotalCost={totalCost}diff --git a/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx b/web/src/components/trace2/components/TraceLogView/TraceLogView.tsxindex ee59d5cf19..2bbe4bbb68 100644--- a/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx+++ b/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx@@ -75,7 +75,7 @@ export const TraceLogView = ({projectId,currentView = "pretty",}: TraceLogViewProps) => {- const { tree, observations } = useTraceData();+ const { roots, observations } = useTraceData();const { logViewMode, logViewTreeStyle } = useViewPreferences();const { formattedExpansion, setFormattedFieldExpansion } = useJsonExpansion();@@ -134,16 +134,20 @@ export const TraceLogView = ({setShowMilliseconds,} = useLogViewPreferences();- // Disable indent when tree is too deep- const indentDisabled = tree.childrenDepth > INDENT_DEPTH_THRESHOLD;+ // Disable indent when tree is too deep (max childrenDepth across all roots)+ const maxChildrenDepth = useMemo(() => {+ if (roots.length === 0) return 0;+ return Math.max(...roots.map((r) => r.childrenDepth));+ }, [roots]);+ const indentDisabled = maxChildrenDepth > INDENT_DEPTH_THRESHOLD;const indentEnabled = indentEnabledPref && !indentDisabled;// Flatten tree based on modeconst allItems = useMemo(() => {return logViewMode === "chronological"- ? flattenChronological(tree)- : flattenTreeOrder(tree);- }, [tree, logViewMode]);+ ? flattenChronological(roots)+ : flattenTreeOrder(roots);+ }, [roots, logViewMode]);// Apply search filterconst flatItems = useMemo(() => {diff --git a/web/src/components/trace2/components/TraceLogView/log-view-flattening.clienttest.ts b/web/src/components/trace2/components/TraceLogView/log-view-flattening.clienttest.tsindex ecd562fffd..3c2ff5cfe4 100644--- a/web/src/components/trace2/components/TraceLogView/log-view-flattening.clienttest.ts+++ b/web/src/components/trace2/components/TraceLogView/log-view-flattening.clienttest.ts@@ -46,7 +46,7 @@ describe("log-view-flattening", () => {describe("flattenChronological", () => {it("should return empty array for trace with no observations", () => {const root = createTraceRoot([]);- const result = flattenChronological(root);+ const result = flattenChronological([root]);expect(result).toHaveLength(0);});@@ -74,7 +74,7 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([obs1, obs2, obs3]);- const result = flattenChronological(root);+ const result = flattenChronological([root]);expect(result).toHaveLength(3);expect(result[0].node.id).toBe("obs-2"); // earliest@@ -100,7 +100,7 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([parent]);- const result = flattenChronological(root);+ const result = flattenChronological([root]);expect(result).toHaveLength(2);// Child started before parent, so comes first chronologically@@ -124,7 +124,7 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([parent]);- const result = flattenChronological(root);+ const result = flattenChronological([root]);// All items should have empty treeLines (flat view)result.forEach((item) => {@@ -136,7 +136,7 @@ describe("log-view-flattening", () => {describe("flattenTreeOrder", () => {it("should return empty array for trace with no observations", () => {const root = createTraceRoot([]);- const result = flattenTreeOrder(root);+ const result = flattenTreeOrder([root]);expect(result).toHaveLength(0);});@@ -163,7 +163,7 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([parent]);- const result = flattenTreeOrder(root);+ const result = flattenTreeOrder([root]);expect(result).toHaveLength(3);expect(result[0].node.id).toBe("parent");@@ -193,7 +193,7 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([parent]);- const result = flattenTreeOrder(root);+ const result = flattenTreeOrder([root]);expect(result).toHaveLength(3);expect(result[0].node.id).toBe("parent");@@ -223,15 +223,15 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([parent]);- const result = flattenTreeOrder(root);+ const result = flattenTreeOrder([root]);expect(result[0].treeLines).toEqual([]); // parent - no ancestorsexpect(result[0].isLastSibling).toBe(true); // only root child- expect(result[1].treeLines).toEqual([false]); // child-1: parent is last sibling, so no line+ expect(result[1].treeLines).toEqual([true]); // child-1: has sibling below (child-2)expect(result[1].isLastSibling).toBe(false); // not last child- expect(result[2].treeLines).toEqual([false]); // child-2: parent is last sibling+ expect(result[2].treeLines).toEqual([false]); // child-2: no siblings belowexpect(result[2].isLastSibling).toBe(true); // last child});@@ -250,7 +250,7 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([obs1, obs2]);- const result = flattenTreeOrder(root);+ const result = flattenTreeOrder([root]);expect(result).toHaveLength(2);expect(result[0].node.id).toBe("obs-2"); // earlier@@ -286,7 +286,7 @@ describe("log-view-flattening", () => {});const root = createTraceRoot([level0]);- const result = flattenTreeOrder(root);+ const result = flattenTreeOrder([root]);expect(result).toHaveLength(4);expect(result.map((r) => r.node.id)).toEqual([@@ -324,7 +324,7 @@ describe("log-view-flattening", () => {depth: 0,});const root = createTraceRoot([obs1, obs2, obs3]);- return flattenChronological(root);+ return flattenChronological([root]);};it("should return all items for empty query", () => {@@ -397,7 +397,7 @@ describe("log-view-flattening", () => {depth: 0,});const root = createTraceRoot([obs]);- const items = flattenChronological(root);+ const items = flattenChronological([root]);// Should not throwconst result = filterBySearch(items, "GENERATION");@@ -422,7 +422,7 @@ describe("log-view-flattening", () => {const root = createTraceRoot(observations);const start = performance.now();- const result = flattenChronological(root);+ const result = flattenChronological([root]);const duration = performance.now() - start;expect(result).toHaveLength(1000);@@ -443,7 +443,7 @@ describe("log-view-flattening", () => {const root = createTraceRoot([current!]);// Should not throw (stack overflow)- const result = flattenTreeOrder(root);+ const result = flattenTreeOrder([root]);expect(result).toHaveLength(100);});});diff --git a/web/src/components/trace2/components/TraceLogView/log-view-flattening.ts b/web/src/components/trace2/components/TraceLogView/log-view-flattening.tsindex 6693084d9b..f64e03e453 100644--- a/web/src/components/trace2/components/TraceLogView/log-view-flattening.ts+++ b/web/src/components/trace2/components/TraceLogView/log-view-flattening.ts@@ -12,12 +12,14 @@ import { type TreeNode } from "@/src/components/trace2/lib/types";import { type FlatLogItem } from "./log-view-types";/**- * Collects all observation nodes from a tree (excludes TRACE root).+ * Collects all observation nodes from roots (excludes TRACE root if present).* Used internally by both flattening functions.*/-function collectObservations(root: TreeNode): TreeNode[] {+function collectObservations(roots: TreeNode[]): TreeNode[] {+ if (roots.length === 0) return [];+const observations: TreeNode[] = [];- const stack: TreeNode[] = [root];+ const stack: TreeNode[] = [...roots];while (stack.length > 0) {const node = stack.pop()!;@@ -40,11 +42,11 @@ function collectObservations(root: TreeNode): TreeNode[] {* Flattens tree into chronological order (sorted by startTime).* All observations are at the same visual level (no indentation).*- * @param root - Root TreeNode (typically the TRACE node)+ * @param roots - Root TreeNodes (supports multiple roots)* @returns Flat list of observations sorted by startTime*/-export function flattenChronological(root: TreeNode): FlatLogItem[] {- const observations = collectObservations(root);+export function flattenChronological(roots: TreeNode[]): FlatLogItem[] {+ const observations = collectObservations(roots);// Sort by startTimeobservations.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());@@ -63,10 +65,12 @@ export function flattenChronological(root: TreeNode): FlatLogItem[] {** Uses iterative approach to avoid stack overflow with deep trees.*- * @param root - Root TreeNode (typically the TRACE node)+ * @param roots - Root TreeNodes (supports multiple roots)* @returns Flat list of observations in DFS order with tree metadata*/-export function flattenTreeOrder(root: TreeNode): FlatLogItem[] {+export function flattenTreeOrder(roots: TreeNode[]): FlatLogItem[] {+ if (roots.length === 0) return [];+const flatList: FlatLogItem[] = [];// Stack entry type for iterative DFS@@ -77,21 +81,40 @@ export function flattenTreeOrder(root: TreeNode): FlatLogItem[] {isLastSibling: boolean;}- // Start with root's children (skip TRACE node itself)const stack: StackEntry[] = [];- // Sort root children by startTime and push in reverse order- const sortedRootChildren = [...root.children].sort(- (a, b) => a.startTime.getTime() - b.startTime.getTime(),- );-- for (let i = sortedRootChildren.length - 1; i >= 0; i--) {- stack.push({- node: sortedRootChildren[i],- depth: 0,- treeLines: [],- isLastSibling: i === sortedRootChildren.length - 1,- });+ // For TRACE-rooted trees, start with root's children (skip TRACE node itself)+ // For multiple observation roots (events-based), use roots directly+ const isTraceRooted = roots.length === 1 && roots[0].type === "TRACE";++ if (isTraceRooted) {+ // Sort root children by startTime and push in reverse order+ const sortedRootChildren = [...roots[0].children].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ for (let i = sortedRootChildren.length - 1; i >= 0; i--) {+ stack.push({+ node: sortedRootChildren[i],+ depth: 0,+ treeLines: [],+ isLastSibling: i === sortedRootChildren.length - 1,+ });+ }+ } else {+ // Multiple observation roots - sort and push in reverse order+ const sortedRoots = [...roots].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ for (let i = sortedRoots.length - 1; i >= 0; i--) {+ stack.push({+ node: sortedRoots[i],+ depth: 0,+ treeLines: [],+ isLastSibling: i === sortedRoots.length - 1,+ });+ }}// Process stack (LIFO - depth-first traversal)@@ -120,7 +143,7 @@ export function flattenTreeOrder(root: TreeNode): FlatLogItem[] {stack.push({node: child,depth: current.depth + 1,- treeLines: [...current.treeLines, !current.isLastSibling],+ treeLines: [...current.treeLines, !isChildLast],isLastSibling: isChildLast,});}diff --git a/web/src/components/trace2/components/TraceLogView/useLogViewObservationIO.ts b/web/src/components/trace2/components/TraceLogView/useLogViewObservationIO.tsindex 78b4d61e6d..01d78fa00f 100644--- a/web/src/components/trace2/components/TraceLogView/useLogViewObservationIO.ts+++ b/web/src/components/trace2/components/TraceLogView/useLogViewObservationIO.ts@@ -9,6 +9,7 @@ import { useMemo } from "react";import { useQueryClient } from "@tanstack/react-query";import { api } from "@/src/utils/api";import { type FlatLogItem } from "./log-view-types";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";export interface UseLogViewObservationIOParams {observationId: string;@@ -32,7 +33,10 @@ export function useLogViewObservationIO({startTime,enabled,}: UseLogViewObservationIOParams) {- return api.observations.byId.useQuery(+ const { isBetaEnabled } = useObservationListBeta();++ // Old path: fetch from observations table (beta OFF)+ const observationsQuery = api.observations.byId.useQuery({observationId,traceId,@@ -40,13 +44,39 @@ export function useLogViewObservationIO({startTime,},{- enabled,- // Cache indefinitely within session - data doesn't change+ enabled: enabled && !isBetaEnabled,+ staleTime: Infinity,+ refetchOnWindowFocus: false,+ },+ );++ // New path: fetch from events table (beta ON)+ const eventsQuery = api.events.batchIO.useQuery(+ {+ projectId,+ observations: [{ id: observationId, traceId }],+ minStartTime: startTime,+ maxStartTime: startTime,+ truncated: false,+ },+ {+ enabled: enabled && isBetaEnabled,staleTime: Infinity,- // Don't refetch on window focusrefetchOnWindowFocus: false,+ select: (data) => data[0], // Extract single result from batch},);++ if (isBetaEnabled) {+ return {+ data: eventsQuery.data,+ isLoading: eventsQuery.isLoading,+ error: eventsQuery.error,+ isError: eventsQuery.isError,+ };+ }++ return observationsQuery;}/**diff --git a/web/src/components/trace2/components/TraceTimeline/index.tsx b/web/src/components/trace2/components/TraceTimeline/index.tsxindex c0d81614aa..4fa322f437 100644--- a/web/src/components/trace2/components/TraceTimeline/index.tsx+++ b/web/src/components/trace2/components/TraceTimeline/index.tsx@@ -15,7 +15,7 @@ import { TimelineScale } from "./TimelineScale";import { TimelineRow } from "./TimelineRow";export function TraceTimeline() {- const { tree, serverScores: scores, comments } = useTraceData();+ const { roots, serverScores: scores, comments } = useTraceData();const { collapsedNodes, toggleCollapsed, selectedNodeId, setSelectedNodeId } =useSelection();const {@@ -30,15 +30,18 @@ export function TraceTimeline() {const timeIndexRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);- // Calculate trace duration from tree root+ // TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTree.tsx+ // Calculate trace duration from roots (max latency across all roots)const traceDuration = useMemo(() => {- // Use tree's latency (already calculated in buildTraceUiData)- return tree.latency ?? 0;- }, [tree.latency]);+ if (roots.length === 0) return 0;+ return Math.max(...roots.map((r) => r.latency ?? 0));+ }, [roots]);const traceStartTime = useMemo(() => {- return tree.startTime;- }, [tree.startTime]);+ if (roots.length === 0) return new Date();+ // Use earliest start time among roots+ return new Date(Math.min(...roots.map((r) => r.startTime.getTime())));+ }, [roots]);// Calculate step size for time axisconst stepSize = useMemo(() => {@@ -48,13 +51,13 @@ export function TraceTimeline() {// Flatten tree with pre-computed timeline metricsconst flattenedItems = useMemo(() => {return flattenTreeWithTimelineMetrics(- tree,+ roots,collapsedNodes,traceStartTime,traceDuration,SCALE_WIDTH,);- }, [tree, collapsedNodes, traceStartTime, traceDuration]);+ }, [roots, collapsedNodes, traceStartTime, traceDuration]);// Calculate content width (max offset + max width)const contentWidth = useMemo(() => {@@ -117,8 +120,17 @@ export function TraceTimeline() {}};- // Get parent totals for heatmap coloring- const parentTotalCost = tree.totalCost;+ // Get parent totals for heatmap coloring (aggregate across all roots)+ const parentTotalCost = useMemo(() => {+ return roots.reduce(+ (acc, r) => {+ if (!r.totalCost) return acc;+ return acc ? acc.plus(r.totalCost) : r.totalCost;+ },+ // TODO: make it nice+ undefined as (typeof roots)[0]["totalCost"],+ );+ }, [roots]);const parentTotalDuration = traceDuration;return (diff --git a/web/src/components/trace2/components/TraceTimeline/timeline-flattening.ts b/web/src/components/trace2/components/TraceTimeline/timeline-flattening.tsindex f9b2124c12..6e7372c167 100644--- a/web/src/components/trace2/components/TraceTimeline/timeline-flattening.ts+++ b/web/src/components/trace2/components/TraceTimeline/timeline-flattening.ts@@ -17,35 +17,45 @@ import {** Uses iterative approach to avoid stack overflow with deep trees.*- * @param node - Root node to flatten+ * @param roots - Root nodes to flatten (supports multiple roots)* @param collapsedNodes - Set of node IDs that are collapsed* @param traceStartTime - When the trace started (for offset calculation)* @param totalScaleSpan - Total duration of the trace in seconds* @param scaleWidth - Width of the timeline scale in pixels (default: SCALE_WIDTH)- * @param depth - Current depth (0 for root)- * @param treeLines - Which ancestor levels have vertical lines- * @param isLastSibling - Whether this node is the last child of its parent* @returns Flat list of nodes with timeline metrics*/export function flattenTreeWithTimelineMetrics(- node: TreeNode,+ roots: TreeNode[],collapsedNodes: Set<string>,traceStartTime: Date,totalScaleSpan: number,scaleWidth: number = SCALE_WIDTH,- depth = 0,- treeLines: boolean[] = [],- isLastSibling = true,): FlatTimelineItem[] {+ if (roots.length === 0) return [];+const flatList: FlatTimelineItem[] = [];- // Initialize stack with root node+ // Sort roots by startTime+ const sortedRoots = [...roots].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ // Initialize stack with all roots at depth 0 (in reverse order for correct DFS)const stack: Array<{node: TreeNode;depth: number;treeLines: boolean[];isLastSibling: boolean;- }> = [{ node, depth, treeLines, isLastSibling }];+ }> = [];++ for (let i = sortedRoots.length - 1; i >= 0; i--) {+ stack.push({+ node: sortedRoots[i]!,+ depth: 0,+ treeLines: [],+ isLastSibling: i === sortedRoots.length - 1,+ });+ }// Process stack (LIFO - depth-first traversal)while (stack.length > 0) {diff --git a/web/src/components/trace2/components/TraceTree.tsx b/web/src/components/trace2/components/TraceTree.tsxindex b8d7b87c3c..ae0c786cea 100644--- a/web/src/components/trace2/components/TraceTree.tsx+++ b/web/src/components/trace2/components/TraceTree.tsx@@ -18,20 +18,31 @@ import { useHandlePrefetchObservation } from "../hooks/useHandlePrefetchObservatimport { type TreeNode } from "../lib/types";export function TraceTree() {- const { tree, comments } = useTraceData();+ const { roots, comments } = useTraceData();const { selectedNodeId, setSelectedNodeId, collapsedNodes, toggleCollapsed } =useSelection();const { handleHover } = useHandlePrefetchObservation();- // Calculate root totals for heatmap color scaling- // These values are used as the "max" reference for all nodes- const rootTotalCost = tree.totalCost;+ // TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTimeline/index.tsx+ // Calculate aggregated totals across all roots for heatmap color scaling+ const rootTotalCost = roots.reduce(+ (acc, r) => {+ if (!r.totalCost) return acc;+ return acc ? acc.plus(r.totalCost) : r.totalCost;+ },+ undefined as (typeof roots)[0]["totalCost"],+ );+const rootTotalDuration =- tree.latency != null ? tree.latency * 1000 : undefined;+ roots.length > 0+ ? Math.max(+ ...roots.map((r) => (r.latency != null ? r.latency * 1000 : 0)),+ )+ : undefined;return (<VirtualizedTree- tree={tree}+ roots={roots}collapsedNodes={collapsedNodes}selectedNodeId={selectedNodeId}onToggleCollapse={toggleCollapsed}diff --git a/web/src/components/trace2/components/_layout/TracePanelDetail.tsx b/web/src/components/trace2/components/_layout/TracePanelDetail.tsxindex e124216440..bab6f4adc2 100644--- a/web/src/components/trace2/components/_layout/TracePanelDetail.tsx+++ b/web/src/components/trace2/components/_layout/TracePanelDetail.tsx@@ -19,18 +19,27 @@ import { useSelection } from "../../contexts/SelectionContext";import { useTraceData } from "../../contexts/TraceDataContext";import { TraceDetailView } from "../TraceDetailView/TraceDetailView";import { ObservationDetailView } from "../ObservationDetailView/ObservationDetailView";-import { useMemo } from "react";+import { useMemo, useEffect } from "react";export function TracePanelDetail() {- const { selectedNodeId } = useSelection();+ const { selectedNodeId, setSelectedNodeId } = useSelection();const {trace,+ roots,nodeMap,observations,serverScores: scores,corrections,} = useTraceData();+ // Auto-select first root observation when roots are observations (not TRACE wrapped)+ // This happens for events-based traces with observation roots+ useEffect(() => {+ if (!selectedNodeId && roots.length > 0 && roots[0].type !== "TRACE") {+ setSelectedNodeId(roots[0].id);+ }+ }, [selectedNodeId, roots, setSelectedNodeId]);+// Memoize to prevent recreation when deps haven't changedconst content = useMemo(() => {const selectedNode = selectedNodeId ? nodeMap.get(selectedNodeId) : null;@@ -53,11 +62,17 @@ export function TracePanelDetail() {);}+ // Check if this observation is one of the roots (events-based trace)+ const isRoot = roots.some((r) => r.id === selectedNodeId);+return (<ObservationDetailViewobservation={observationData}projectId={trace.projectId}traceId={trace.id}+ isRoot={isRoot}+ sessionId={trace.sessionId}+ userId={trace.userId}/>);}@@ -71,7 +86,15 @@ export function TracePanelDetail() {projectId={trace.projectId}/>);- }, [selectedNodeId, nodeMap, trace, observations, scores, corrections]);+ }, [+ selectedNodeId,+ nodeMap,+ trace,+ roots,+ observations,+ scores,+ corrections,+ ]);return (<div className="h-full w-full overflow-y-auto bg-background">{content}</div>diff --git a/web/src/components/trace2/components/_layout/TracePanelNavigationHeader.tsx b/web/src/components/trace2/components/_layout/TracePanelNavigationHeader.tsxindex 4c19924ad9..a7894c0af1 100644--- a/web/src/components/trace2/components/_layout/TracePanelNavigationHeader.tsx+++ b/web/src/components/trace2/components/_layout/TracePanelNavigationHeader.tsx@@ -62,7 +62,7 @@ function TracePanelNavigationHeaderExpanded({const { searchInputValue, setSearchInputValue, setSearchQueryImmediate } =useSearch();const { expandAll, collapseAll, collapsedNodes } = useSelection();- const { tree, trace, observations } = useTraceData();+ const { roots, trace, observations } = useTraceData();const { isGraphViewAvailable } = useTraceGraphData();const [viewMode, setViewMode] = useQueryParam("view", StringParam);@@ -73,11 +73,12 @@ function TracePanelNavigationHeaderExpanded({}};- // Check if everything is collapsed- const isEverythingCollapsed = collapsedNodes.has(tree.id);+ // Check if everything is collapsed (all roots collapsed)+ const isEverythingCollapsed =+ roots.length > 0 && roots.every((r) => collapsedNodes.has(r.id));- // Collect all node IDs for collapse all- const getAllNodeIds = useCallback((node: typeof tree): string[] => {+ // Collect all node IDs for collapse all (from all roots)+ const getAllNodeIds = useCallback((node: (typeof roots)[0]): string[] => {const ids = [node.id];node.children.forEach((child) => {ids.push(...getAllNodeIds(child));@@ -89,10 +90,10 @@ function TracePanelNavigationHeaderExpanded({if (isEverythingCollapsed) {expandAll();} else {- const allIds = getAllNodeIds(tree);+ const allIds = roots.flatMap((root) => getAllNodeIds(root));collapseAll(allIds);}- }, [isEverythingCollapsed, expandAll, collapseAll, getAllNodeIds, tree]);+ }, [isEverythingCollapsed, expandAll, collapseAll, getAllNodeIds, roots]);const handleDownload = useCallback(() => {downloadTraceAsJson({diff --git a/web/src/components/trace2/components/_shared/VirtualizedTree.tsx b/web/src/components/trace2/components/_shared/VirtualizedTree.tsxindex 24809afe89..0caac4947e 100644--- a/web/src/components/trace2/components/_shared/VirtualizedTree.tsx+++ b/web/src/components/trace2/components/_shared/VirtualizedTree.tsx@@ -12,7 +12,7 @@ import { cn } from "@/src/utils/tailwind";import { type TreeNodeMetadata } from "./VirtualizedTreeNodeWrapper";interface VirtualizedTreeProps<T extends { id: string; children: T[] }> {- tree: T;+ roots: T[];collapsedNodes: Set<string>;selectedNodeId: string | null;renderNode: (params: {@@ -32,7 +32,7 @@ interface VirtualizedTreeProps<T extends { id: string; children: T[] }> {}export function VirtualizedTree<T extends { id: string; children: T[] }>({- tree,+ roots,collapsedNodes,selectedNodeId,renderNode,@@ -46,8 +46,8 @@ export function VirtualizedTree<T extends { id: string; children: T[] }>({const parentRef = useRef<HTMLDivElement>(null);const flattenedItems = useMemo(- () => flattenTree(tree, collapsedNodes, 0, [], true),- [tree, collapsedNodes],+ () => flattenTree(roots, collapsedNodes),+ [roots, collapsedNodes],);const defaultEstimateSize = () => defaultRowHeight;diff --git a/web/src/components/trace2/components/_shared/tree-flattening.clienttest.ts b/web/src/components/trace2/components/_shared/tree-flattening.clienttest.tsindex e8bddeb80d..61aa7f3caa 100644--- a/web/src/components/trace2/components/_shared/tree-flattening.clienttest.ts+++ b/web/src/components/trace2/components/_shared/tree-flattening.clienttest.ts@@ -19,6 +19,11 @@ interface TestNode {describe("flattenTree", () => {describe("basic flattening", () => {+ it("should return empty array for empty roots", () => {+ const result = flattenTree([], new Set());+ expect(result).toEqual([]);+ });+it("should flatten single node with no children", () => {const tree: TestNode = {id: "root",@@ -26,7 +31,7 @@ describe("flattenTree", () => {children: [],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());expect(result).toEqual([{@@ -46,7 +51,7 @@ describe("flattenTree", () => {children: [child],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());expect(result).toHaveLength(2);expect(result[0]).toEqual({@@ -73,7 +78,7 @@ describe("flattenTree", () => {children: [child1, child2, child3],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());expect(result).toHaveLength(4);@@ -118,7 +123,7 @@ describe("flattenTree", () => {children: [child],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());expect(result).toHaveLength(3);@@ -136,6 +141,79 @@ describe("flattenTree", () => {});});+ describe("multiple root nodes", () => {+ it("flattens multiple roots with children, sorted by startTime", () => {+ // root2 (09:00) root1 (10:00) root3 (11:00, last)+ // | |+ // child2 child1+ // |+ // grandchild++ const grandchild: TestNode = { id: "grandchild", name: "", children: [] };+ const child1: TestNode = {+ id: "child1",+ name: "",+ children: [grandchild],+ };+ const child2: TestNode = { id: "child2", name: "", children: [] };+ const root1: TestNode = {+ id: "root1",+ name: "",+ children: [child1],+ startTime: new Date("2024-01-01T10:00Z"),+ };+ const root2: TestNode = {+ id: "root2",+ name: "",+ children: [child2],+ startTime: new Date("2024-01-01T09:00Z"),+ };+ const root3: TestNode = {+ id: "root3",+ name: "",+ children: [],+ startTime: new Date("2024-01-01T11:00Z"),+ };++ const result = flattenTree([root1, root2, root3], new Set());++ // Verify DFS order with sorting: root2 first (earliest), then root1, then root3 (latest)+ expect(result).toMatchObject([+ {+ node: { id: "root2" },+ depth: 0,+ isLastSibling: false,+ treeLines: [],+ },+ {+ node: { id: "child2" },+ depth: 1,+ isLastSibling: true,+ treeLines: [false],+ },+ {+ node: { id: "root1" },+ depth: 0,+ isLastSibling: false,+ treeLines: [],+ },+ {+ node: { id: "child1" },+ depth: 1,+ isLastSibling: true,+ treeLines: [false],+ },+ {+ node: { id: "grandchild" },+ depth: 2,+ isLastSibling: true,+ treeLines: [false, false],+ },+ { node: { id: "root3" }, depth: 0, isLastSibling: true, treeLines: [] },+ ]);+ });+ });+describe("collapsed nodes", () => {it("should not include children of collapsed node", () => {const child1: TestNode = { id: "child1", name: "Child 1", children: [] };@@ -147,7 +225,7 @@ describe("flattenTree", () => {};const collapsed = new Set(["root"]);- const result = flattenTree(tree, collapsed);+ const result = flattenTree([tree], collapsed);// Only root should be in the result, children hiddenexpect(result).toHaveLength(1);@@ -172,7 +250,7 @@ describe("flattenTree", () => {};const collapsed = new Set(["child"]);- const result = flattenTree(tree, collapsed);+ const result = flattenTree([tree], collapsed);// Root and child, but not grandchildexpect(result).toHaveLength(2);@@ -208,7 +286,7 @@ describe("flattenTree", () => {};const collapsed = new Set(["child1", "child2"]);- const result = flattenTree(tree, collapsed);+ const result = flattenTree([tree], collapsed);// Root and two children, no grandchildrenexpect(result).toHaveLength(3);@@ -216,6 +294,30 @@ describe("flattenTree", () => {expect(result[1]?.node.id).toBe("child1");expect(result[2]?.node.id).toBe("child2");});++ it("should handle collapsed root in multiple roots scenario", () => {+ const child1: TestNode = { id: "child1", name: "Child 1", children: [] };+ const child2: TestNode = { id: "child2", name: "Child 2", children: [] };+ const root1: TestNode = {+ id: "root1",+ name: "Root 1",+ children: [child1],+ };+ const root2: TestNode = {+ id: "root2",+ name: "Root 2",+ children: [child2],+ };++ const collapsed = new Set(["root1"]);+ const result = flattenTree([root1, root2], collapsed);++ // root1 collapsed (no child1), root2 expanded (with child2)+ expect(result).toHaveLength(3);+ expect(result[0]?.node.id).toBe("root1");+ expect(result[1]?.node.id).toBe("root2");+ expect(result[2]?.node.id).toBe("child2");+ });});describe("tree lines calculation", () => {@@ -247,7 +349,7 @@ describe("flattenTree", () => {children: [child1, child2],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());// child1 should have tree line (not last sibling)const child1Result = result.find((n) => n.node.id === "child1");@@ -299,7 +401,7 @@ describe("flattenTree", () => {children: [child1, child2],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());// ggc1 should have tree lines showing:// - depth 0: true (child1 is not last at level 1)@@ -337,7 +439,7 @@ describe("flattenTree", () => {children: [child1, child2, child3], // Unsorted};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());// Should be sorted by startTimeexpect(result[1]?.node.id).toBe("child2"); // 09:00@@ -363,7 +465,7 @@ describe("flattenTree", () => {children: [child1, child2],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());// Should not throw, nodes without startTime get 0expect(result).toHaveLength(3);@@ -380,7 +482,7 @@ describe("flattenTree", () => {children: [],};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());expect(result).toHaveLength(1);expect(result[0]?.node.id).toBe("root");@@ -402,7 +504,7 @@ describe("flattenTree", () => {};}- const result = flattenTree(current, new Set());+ const result = flattenTree([current], new Set());expect(result).toHaveLength(10);expect(result[0]?.depth).toBe(0);@@ -418,12 +520,26 @@ describe("flattenTree", () => {};const originalChildren = tree.children;- flattenTree(tree, new Set());+ flattenTree([tree], new Set());// Original tree should not be modifiedexpect(tree.children).toBe(originalChildren);expect(tree.children).toHaveLength(1);});++ it("should preserve original roots array (immutability)", () => {+ const root1: TestNode = { id: "root1", name: "Root 1", children: [] };+ const root2: TestNode = { id: "root2", name: "Root 2", children: [] };+ const roots = [root1, root2];+ const originalLength = roots.length;++ flattenTree(roots, new Set());++ // Original roots array should not be modified+ expect(roots.length).toBe(originalLength);+ expect(roots[0]).toBe(root1);+ expect(roots[1]).toBe(root2);+ });});describe("complex real-world scenarios", () => {@@ -456,7 +572,7 @@ describe("flattenTree", () => {};const collapsed = new Set(["child1"]);- const result = flattenTree(tree, collapsed);+ const result = flattenTree([tree], collapsed);// root, child1 (collapsed), child2, gc3expect(result).toHaveLength(4);@@ -481,7 +597,7 @@ describe("flattenTree", () => {children,};- const result = flattenTree(tree, new Set());+ const result = flattenTree([tree], new Set());expect(result).toHaveLength(101); // root + 100 children@@ -624,7 +740,7 @@ describe("flattenTree", () => {const collapsedNodes = new Set<string>();if (collapsedPercent > 0) {// Collect all node IDs via flattening first- const allFlattened = flattenTree(tree, new Set());+ const allFlattened = flattenTree([tree], new Set());const collapseCount = Math.floor(allFlattened.length * (collapsedPercent / 100),);@@ -635,7 +751,7 @@ describe("flattenTree", () => {}const start = Date.now();- const result = flattenTree(tree, collapsedNodes);+ const result = flattenTree([tree], collapsedNodes);const duration = Date.now() - start;// Verify result is validdiff --git a/web/src/components/trace2/components/_shared/tree-flattening.ts b/web/src/components/trace2/components/_shared/tree-flattening.tsindex e3af8a4d4d..6961e378ad 100644--- a/web/src/components/trace2/components/_shared/tree-flattening.ts+++ b/web/src/components/trace2/components/_shared/tree-flattening.ts@@ -19,29 +19,41 @@ export interface FlatNode<T> {* Uses an explicit stack instead of recursion to avoid stack overflow* with deeply nested trees (10k+ levels).*- * @param node - Root node to flatten+ * @param roots - Root nodes to flatten (supports multiple roots)* @param collapsedNodes - Set of node IDs that are collapsed- * @param depth - Current depth (0 for root)- * @param treeLines - Which ancestor levels have vertical lines- * @param isLastSibling - Whether this node is the last child of its parent* @returns Flat list of nodes with rendering metadata*/-export function flattenTree<T extends { id: string; children: T[] }>(- node: T,- collapsedNodes: Set<string>,- depth = 0,- treeLines: boolean[] = [],- isLastSibling = true,-): FlatNode<T>[] {+export function flattenTree<+ T extends { id: string; children: T[]; startTime?: Date },+>(roots: T[], collapsedNodes: Set<string>): FlatNode<T>[] {+ if (roots.length === 0) return [];+const flatList: FlatNode<T>[] = [];- // Initialize stack with root node+ // Sort roots by startTime for consistent ordering+ const sortedRoots = [...roots].sort((a, b) => {+ const aStart = a.startTime?.getTime() ?? 0;+ const bStart = b.startTime?.getTime() ?? 0;+ return aStart - bStart;+ });++ // Initialize stack with all roots at depth 0+ // Push in REVERSE order to maintain left-to-right DFS traversalconst stack: Array<{node: T;depth: number;treeLines: boolean[];isLastSibling: boolean;- }> = [{ node, depth, treeLines, isLastSibling }];+ }> = [];++ for (let i = sortedRoots.length - 1; i >= 0; i--) {+ stack.push({+ node: sortedRoots[i]!,+ depth: 0,+ treeLines: [],+ isLastSibling: i === sortedRoots.length - 1,+ });+ }// Process stack (LIFO - depth-first traversal)while (stack.length > 0) {@@ -60,11 +72,10 @@ export function flattenTree<T extends { id: string; children: T[] }>(current.node.children.length > 0 &&!collapsedNodes.has(current.node.id)) {- // Sort children by startTime if available (assumes TreeNode structure)+ // Sort children by startTime for consistent orderingconst sortedChildren = [...current.node.children].sort((a, b) => {- // Safe type assertion - TreeNode has startTime- const aStart = (a as any).startTime?.getTime?.() ?? 0;- const bStart = (b as any).startTime?.getTime?.() ?? 0;+ const aStart = a.startTime?.getTime() ?? 0;+ const bStart = b.startTime?.getTime() ?? 0;return aStart - bStart;});@@ -74,10 +85,12 @@ export function flattenTree<T extends { id: string; children: T[] }>(const child = sortedChildren[i];const isChildLast = i === sortedChildren.length - 1;+ // treeLines[i] = does the node at depth i+1 have siblings below?+ // We add !isChildLast to indicate whether this child has siblings.stack.push({node: child,depth: current.depth + 1,- treeLines: [...current.treeLines, !isChildLast], // Add line if not last child+ treeLines: [...current.treeLines, !isChildLast],isLastSibling: isChildLast,});}diff --git a/web/src/components/trace2/contexts/TraceDataContext.tsx b/web/src/components/trace2/contexts/TraceDataContext.tsxindex 7028aa4dd5..cee65ee44d 100644--- a/web/src/components/trace2/contexts/TraceDataContext.tsx+++ b/web/src/components/trace2/contexts/TraceDataContext.tsx@@ -34,7 +34,7 @@ interface TraceDataContextValue {serverScores: WithStringifiedMetadata<ScoreDomain>[];mergedScores: WithStringifiedMetadata<ScoreDomain>[];corrections: ScoreDomain[];- tree: TreeNode;+ roots: TreeNode[];nodeMap: Map<string, TreeNode>;searchItems: TraceSearchListItem[];hiddenObservationsCount: number;@@ -95,7 +95,7 @@ export function TraceDataProvider({serverScores: serverScores,mergedScores,corrections,- tree: uiData.tree,+ roots: uiData.roots,nodeMap: uiData.nodeMap,searchItems: uiData.searchItems,hiddenObservationsCount: uiData.hiddenObservationsCount,diff --git a/web/src/components/trace2/contexts/TraceGraphDataContext.tsx b/web/src/components/trace2/contexts/TraceGraphDataContext.tsxindex 0c77bda27d..6c1c992579 100644--- a/web/src/components/trace2/contexts/TraceGraphDataContext.tsx+++ b/web/src/components/trace2/contexts/TraceGraphDataContext.tsx@@ -10,6 +10,7 @@import { createContext, useContext, useMemo, type ReactNode } from "react";import { api } from "@/src/utils/api";import { type AgentGraphDataResponse } from "@/src/features/trace-graph-view/types";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";const MAX_NODES_FOR_GRAPH_UI = 5000;@@ -49,6 +50,8 @@ export function TraceGraphDataProvider({traceId,observations,}: TraceGraphDataProviderProps) {+ const { isBetaEnabled } = useObservationListBeta();+// Skip graph data entirely for large traces to avoid performance issuesconst exceedsThreshold = observations.length >= MAX_NODES_FOR_GRAPH_UI;@@ -73,25 +76,40 @@ export function TraceGraphDataProvider({};}, [observations, exceedsThreshold]);- const query = api.traces.getAgentGraphData.useQuery(- {- projectId,- traceId,- minStartTime: minStartTime ?? "",- maxStartTime: maxStartTime ?? "",- },- {- enabled:- !exceedsThreshold &&- observations.length > 0 &&- minStartTime !== null &&- maxStartTime !== null,- refetchOnWindowFocus: false,- refetchOnMount: false,- refetchOnReconnect: false,- staleTime: 50 * 60 * 1000, // 50 minutes- },- );+ const queryEnabled =+ !exceedsThreshold &&+ observations.length > 0 &&+ minStartTime !== null &&+ maxStartTime !== null;++ const queryInput = {+ projectId,+ traceId,+ minStartTime: minStartTime ?? "",+ maxStartTime: maxStartTime ?? "",+ };++ const queryOptions = {+ refetchOnWindowFocus: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ staleTime: 50 * 60 * 1000, // 50 minutes+ };++ // Beta OFF: Query from observations table (existing behavior)+ const tracesQuery = api.traces.getAgentGraphData.useQuery(queryInput, {+ ...queryOptions,+ enabled: queryEnabled && !isBetaEnabled,+ });++ // Beta ON: Query from events table (v4)+ const eventsQuery = api.events.getAgentGraphData.useQuery(queryInput, {+ ...queryOptions,+ enabled: queryEnabled && isBetaEnabled,+ });++ // Use appropriate query based on beta toggle+ const query = isBetaEnabled ? eventsQuery : tracesQuery;const agentGraphData = useMemo(() => query.data ?? [], [query.data]);diff --git a/web/src/components/trace2/lib/tree-building.clienttest.ts b/web/src/components/trace2/lib/tree-building.clienttest.tsindex 749bbde46b..f735cf640e 100644--- a/web/src/components/trace2/lib/tree-building.clienttest.ts+++ b/web/src/components/trace2/lib/tree-building.clienttest.ts@@ -76,165 +76,278 @@ const createMockTrace = (overrides: Record<string, unknown> = {}) => ({});describe("buildTraceUiData", () => {- it("creates tree with trace as root and observations as children", () => {- const trace = createMockTrace({ id: "trace-1", name: "Test Trace" });- const observations: ObservationReturnType[] = [- createMockObservation({- id: "obs-1",- name: "Observation 1",- parentObservationId: null,- startTime: new Date("2024-01-01T00:00:00.100Z"),- }),- createMockObservation({- id: "obs-2",- name: "Observation 2",- parentObservationId: null,- startTime: new Date("2024-01-01T00:00:00.200Z"),- }),- ];-- const result = buildTraceUiData(trace, observations);-- // Tree root should be the trace- expect(result.tree.id).toBe("trace-trace-1");- expect(result.tree.type).toBe("TRACE");- expect(result.tree.name).toBe("Test Trace");-- // Should have 2 child observations- expect(result.tree.children).toHaveLength(2);- expect(result.tree.children[0].id).toBe("obs-1");- expect(result.tree.children[1].id).toBe("obs-2");- });+ describe("Traditional traces (single TRACE root)", () => {+ it("creates roots array with TRACE as single root and observations as children", () => {+ const trace = createMockTrace({ id: "trace-1", name: "Test Trace" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ name: "Observation 1",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.100Z"),+ }),+ createMockObservation({+ id: "obs-2",+ name: "Observation 2",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.200Z"),+ }),+ ];- it("nests child observations under parent observations", () => {- const trace = createMockTrace();- const observations: ObservationReturnType[] = [- createMockObservation({- id: "parent",- name: "Parent",- parentObservationId: null,- startTime: new Date("2024-01-01T00:00:00.000Z"),- }),- createMockObservation({- id: "child-1",- name: "Child 1",- parentObservationId: "parent",- startTime: new Date("2024-01-01T00:00:01.000Z"),- }),- createMockObservation({- id: "child-2",- name: "Child 2",- parentObservationId: "parent",- startTime: new Date("2024-01-01T00:00:02.000Z"),- }),- ];-- const result = buildTraceUiData(trace, observations);-- // Should have 1 root observation under trace- expect(result.tree.children).toHaveLength(1);- const parent = result.tree.children[0];- expect(parent.id).toBe("parent");-- // Parent should have 2 children- expect(parent.children).toHaveLength(2);- expect(parent.children[0].id).toBe("child-1");- expect(parent.children[1].id).toBe("child-2");- });+ const result = buildTraceUiData(trace, observations);- it("populates nodeMap for O(1) lookup", () => {- const trace = createMockTrace({ id: "trace-1" });- const observations: ObservationReturnType[] = [- createMockObservation({- id: "obs-1",- parentObservationId: null,- }),- createMockObservation({- id: "obs-2",- parentObservationId: "obs-1",- }),- ];-- const result = buildTraceUiData(trace, observations);-- // nodeMap should contain trace and both observations- expect(result.nodeMap.size).toBe(3);- expect(result.nodeMap.has("trace-trace-1")).toBe(true);- expect(result.nodeMap.has("obs-1")).toBe(true);- expect(result.nodeMap.has("obs-2")).toBe(true);-- // Should be able to get nodes by ID- const obs1 = result.nodeMap.get("obs-1");- expect(obs1?.name).toBe("Mock Observation");- });+ // Should have single root (TRACE wrapper)+ expect(result.roots).toHaveLength(1);+ expect(result.roots[0].id).toBe("trace-trace-1");+ expect(result.roots[0].type).toBe("TRACE");+ expect(result.roots[0].name).toBe("Test Trace");- it("generates searchItems list with all nodes", () => {- const trace = createMockTrace({ id: "trace-1", latency: 2.0 });- const observations: ObservationReturnType[] = [- createMockObservation({- id: "obs-1",- parentObservationId: null,- }),- createMockObservation({- id: "obs-2",- parentObservationId: "obs-1",- }),- ];-- const result = buildTraceUiData(trace, observations);-- // searchItems should contain trace + all observations (flattened)- expect(result.searchItems).toHaveLength(3);-- // First item should be trace (undefined observationId)- expect(result.searchItems[0].node.type).toBe("TRACE");- expect(result.searchItems[0].observationId).toBeUndefined();-- // Other items should have observationId set- expect(result.searchItems[1].observationId).toBe("obs-1");- expect(result.searchItems[2].observationId).toBe("obs-2");-- // All items should have parent duration for heatmap- expect(result.searchItems[0].parentTotalDuration).toBe(2000); // 2s * 1000ms- });+ // Should have 2 child observations+ expect(result.roots[0].children).toHaveLength(2);+ expect(result.roots[0].children[0].id).toBe("obs-1");+ expect(result.roots[0].children[1].id).toBe("obs-2");+ });- it("returns empty children for trace with no observations", () => {- const trace = createMockTrace();- const observations: ObservationReturnType[] = [];+ it("nests child observations under parent observations", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ name: "Parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ createMockObservation({+ id: "child-1",+ name: "Child 1",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ createMockObservation({+ id: "child-2",+ name: "Child 2",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:02.000Z"),+ }),+ ];- const result = buildTraceUiData(trace, observations);+ const result = buildTraceUiData(trace, observations);++ // Should have 1 root observation under trace+ expect(result.roots[0].children).toHaveLength(1);+ const parent = result.roots[0].children[0];+ expect(parent.id).toBe("parent");++ // Parent should have 2 children+ expect(parent.children).toHaveLength(2);+ expect(parent.children[0].id).toBe("child-1");+ expect(parent.children[1].id).toBe("child-2");+ });- expect(result.tree.children).toHaveLength(0);- expect(result.searchItems).toHaveLength(1); // Just the trace- expect(result.hiddenObservationsCount).toBe(0);+ it("populates nodeMap for O(1) lookup", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "obs-2",+ parentObservationId: "obs-1",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // nodeMap should contain trace and both observations+ expect(result.nodeMap.size).toBe(3);+ expect(result.nodeMap.has("trace-trace-1")).toBe(true);+ expect(result.nodeMap.has("obs-1")).toBe(true);+ expect(result.nodeMap.has("obs-2")).toBe(true);++ // Should be able to get nodes by ID+ const obs1 = result.nodeMap.get("obs-1");+ expect(obs1?.name).toBe("Mock Observation");+ });++ it("generates searchItems list with all nodes", () => {+ const trace = createMockTrace({ id: "trace-1", latency: 2.0 });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "obs-2",+ parentObservationId: "obs-1",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // searchItems should contain trace + all observations (flattened)+ expect(result.searchItems).toHaveLength(3);++ // First item should be trace (undefined observationId)+ expect(result.searchItems[0].node.type).toBe("TRACE");+ expect(result.searchItems[0].observationId).toBeUndefined();++ // Other items should have observationId set+ expect(result.searchItems[1].observationId).toBe("obs-1");+ expect(result.searchItems[2].observationId).toBe("obs-2");++ // All items should have parent duration for heatmap+ expect(result.searchItems[0].parentTotalDuration).toBe(2000); // 2s * 1000ms+ });++ it("returns empty children for trace with no observations", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [];++ const result = buildTraceUiData(trace, observations);++ expect(result.roots).toHaveLength(1);+ expect(result.roots[0].children).toHaveLength(0);+ expect(result.searchItems).toHaveLength(1); // Just the trace+ expect(result.hiddenObservationsCount).toBe(0);+ });++ it("sorts children by startTime", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-late",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:02.000Z"),+ }),+ createMockObservation({+ id: "obs-early",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ createMockObservation({+ id: "obs-middle",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Children should be sorted by startTime+ expect(result.roots[0].children[0].id).toBe("obs-early");+ expect(result.roots[0].children[1].id).toBe("obs-middle");+ expect(result.roots[0].children[2].id).toBe("obs-late");+ });++ it("preserves all TRACE node properties", () => {+ const trace = createMockTrace({+ id: "trace-1",+ name: "Test Trace",+ latency: 2.5,+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({ id: "obs-1", totalCost: 0.5 }),+ ];++ const result = buildTraceUiData(trace, observations);+ const traceNode = result.roots[0];++ expect(traceNode.name).toBe("Test Trace");+ expect(traceNode.latency).toBe(2.5);+ expect(traceNode.totalCost?.toNumber()).toBe(0.5);+ expect(traceNode.depth).toBe(-1);+ expect(traceNode.startTimeSinceTrace).toBe(0);+ });});- it("sorts children by startTime", () => {- const trace = createMockTrace();- const observations: ObservationReturnType[] = [- createMockObservation({- id: "obs-late",- parentObservationId: null,- startTime: new Date("2024-01-01T00:00:02.000Z"),- }),- createMockObservation({- id: "obs-early",- parentObservationId: null,- startTime: new Date("2024-01-01T00:00:00.000Z"),- }),- createMockObservation({- id: "obs-middle",- parentObservationId: null,- startTime: new Date("2024-01-01T00:00:01.000Z"),- }),- ];-- const result = buildTraceUiData(trace, observations);-- // Children should be sorted by startTime- expect(result.tree.children[0].id).toBe("obs-early");- expect(result.tree.children[1].id).toBe("obs-middle");- expect(result.tree.children[2].id).toBe("obs-late");+ describe("Events-based traces (multiple roots)", () => {+ it("returns single observation as root when rootObservationType is set", () => {+ const trace = createMockTrace({+ id: "trace-1",+ rootObservationType: "GENERATION",+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "gen-1",+ name: "Generation",+ type: "GENERATION",+ parentObservationId: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Should have single root (the observation, NOT a TRACE wrapper)+ expect(result.roots).toHaveLength(1);+ expect(result.roots[0].id).toBe("gen-1");+ expect(result.roots[0].type).toBe("GENERATION");+ expect(result.roots[0].name).toBe("Generation");+ });++ it("returns empty roots array for events-based trace with no observations", () => {+ const trace = createMockTrace({+ id: "trace-1",+ rootObservationType: "SPAN",+ });+ const observations: ObservationReturnType[] = [];++ const result = buildTraceUiData(trace, observations);++ expect(result.roots).toHaveLength(0);+ expect(result.searchItems).toHaveLength(0);+ });++ it("builds multiple roots with children, sorted by startTime", () => {+ // root-late (02:00) root-early (00:00)+ // | |+ // child-late child-early++ const trace = createMockTrace({+ id: "trace-1",+ rootObservationType: "SPAN",+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root-late",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:02.000Z"),+ }),+ createMockObservation({+ id: "child-late",+ parentObservationId: "root-late",+ startTime: new Date("2024-01-01T00:00:02.100Z"),+ }),+ createMockObservation({+ id: "root-early",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ createMockObservation({+ id: "child-early",+ parentObservationId: "root-early",+ startTime: new Date("2024-01-01T00:00:00.100Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Roots sorted by startTime (no TRACE wrapper), with children+ expect(result.roots).toMatchObject([+ { id: "root-early", children: [{ id: "child-early" }] },+ { id: "root-late", children: [{ id: "child-late" }] },+ ]);++ // nodeMap has all observations, no TRACE entry+ expect(result.nodeMap.has("root-early")).toBe(true);+ expect(result.nodeMap.has("child-late")).toBe(true);+ expect(result.nodeMap.has("trace-trace-1")).toBe(false);++ // searchItems has no TRACE node+ expect(result.searchItems.every((s) => s.node.type !== "TRACE")).toBe(+ true,+ );+ });});describe("Cost Aggregation - Fundamentals", () => {@@ -253,7 +366,7 @@ describe("buildTraceUiData", () => {const obs = result.nodeMap.get("obs-1");expect(obs?.totalCost).toBeUndefined();- expect(result.tree.totalCost).toBeUndefined();+ expect(result.roots[0].totalCost).toBeUndefined();});it("treats zero costs as undefined", () => {@@ -596,8 +709,8 @@ describe("buildTraceUiData", () => {const result = buildTraceUiData(trace, observations);// Trace root should sum all top-level observations- expect(result.tree.totalCost).toBeDefined();- expect(result.tree.totalCost?.equals(new Decimal(0.8))).toBe(true);+ expect(result.roots[0].totalCost).toBeDefined();+ expect(result.roots[0].totalCost?.equals(new Decimal(0.8))).toBe(true);});it("propagates trace totalCost to all searchItems as parentTotalCost", () => {@@ -618,7 +731,7 @@ describe("buildTraceUiData", () => {const result = buildTraceUiData(trace, observations);// All searchItems should have the trace's total cost as parentTotalCost- const traceTotalCost = result.tree.totalCost;+ const traceTotalCost = result.roots[0].totalCost;expect(traceTotalCost).toBeDefined();result.searchItems.forEach((item) => {@@ -650,7 +763,7 @@ describe("buildTraceUiData", () => {// Both should have undefined totalCost (zero is treated as undefined)expect(child?.totalCost).toBeUndefined();expect(parent?.totalCost).toBeUndefined();- expect(result.tree.totalCost).toBeUndefined();+ expect(result.roots[0].totalCost).toBeUndefined();});});@@ -1004,9 +1117,9 @@ describe("buildTraceUiData", () => {const result = buildTraceUiData(trace, observations);- expect(result.tree.startTimeSinceTrace).toBe(0);- expect(result.tree.startTimeSinceParentStart).toBeNull();- expect(result.tree.depth).toBe(-1);+ expect(result.roots[0].startTimeSinceTrace).toBe(0);+ expect(result.roots[0].startTimeSinceParentStart).toBeNull();+ expect(result.roots[0].depth).toBe(-1);});});@@ -1137,7 +1250,7 @@ describe("buildTraceUiData", () => {// A has chain of depth 2: childrenDepth = 2expect(result.nodeMap.get("A")?.childrenDepth).toBe(2);// Trace root has chain of depth 3: childrenDepth = 3- expect(result.tree.childrenDepth).toBe(3);+ expect(result.roots[0].childrenDepth).toBe(3);});it("calculates childrenDepth for wide tree (parent with 3 children)", () => {@@ -1170,7 +1283,7 @@ describe("buildTraceUiData", () => {// Parent has children at depth 1: childrenDepth = 1expect(result.nodeMap.get("parent")?.childrenDepth).toBe(1);// Trace root: childrenDepth = 2- expect(result.tree.childrenDepth).toBe(2);+ expect(result.roots[0].childrenDepth).toBe(2);});it("takes max childrenDepth when branches have different depths", () => {@@ -1207,7 +1320,7 @@ describe("buildTraceUiData", () => {// root takes max(1, 0) + 1 = 2expect(result.nodeMap.get("root")?.childrenDepth).toBe(2);// Trace root: childrenDepth = 3- expect(result.tree.childrenDepth).toBe(3);+ expect(result.roots[0].childrenDepth).toBe(3);});it("calculates childrenDepth 0 for empty trace", () => {@@ -1216,7 +1329,7 @@ describe("buildTraceUiData", () => {const result = buildTraceUiData(trace, observations);- expect(result.tree.childrenDepth).toBe(0);+ expect(result.roots[0].childrenDepth).toBe(0);});it("calculates correct childrenDepth for deep nesting (5+ levels)", () => {@@ -1242,7 +1355,7 @@ describe("buildTraceUiData", () => {expect(result.nodeMap.get("L1")?.childrenDepth).toBe(5);expect(result.nodeMap.get("L0")?.childrenDepth).toBe(6);// Trace root: 7 levels deep- expect(result.tree.childrenDepth).toBe(7);+ expect(result.roots[0].childrenDepth).toBe(7);});it("calculates childrenDepth with multiple root observations", () => {@@ -1275,7 +1388,7 @@ describe("buildTraceUiData", () => {expect(result.nodeMap.get("root2")?.childrenDepth).toBe(1);expect(result.nodeMap.get("root3")?.childrenDepth).toBe(0);// Trace root takes max(2, 1, 0) + 1 = 3- expect(result.tree.childrenDepth).toBe(3);+ expect(result.roots[0].childrenDepth).toBe(3);});});diff --git a/web/src/components/trace2/lib/tree-building.ts b/web/src/components/trace2/lib/tree-building.tsindex d9bf3f7984..a3a2e02c12 100644--- a/web/src/components/trace2/lib/tree-building.ts+++ b/web/src/components/trace2/lib/tree-building.ts@@ -33,6 +33,9 @@ type TraceType = Omit<input: string | null;output: string | null;latency?: number;+ // For events-based traces: when set, root observation becomes tree root+ rootObservationType?: string;+ rootObservationId?: string;};/**@@ -323,13 +326,17 @@ function buildTreeNodesBottomUp(* Builds hierarchical tree from trace and observations (ITERATIVE - optimal).* Uses topological sort for bottom-up cost aggregation.* Handles unlimited tree depth without stack overflow.+ *+ * Returns `roots` array:+ * - Traditional traces: [TRACE node] with observations as children+ * - Events-based traces (rootObservationType set): [obs1, obs2, ...] directly. Array because there could be multiple roots now*/function buildTraceTree(trace: TraceType,observations: ObservationReturnType[],minLevel?: ObservationLevelType,): {- tree: TreeNode;+ roots: TreeNode[];hiddenObservationsCount: number;nodeMap: Map<string, TreeNode>;} {@@ -339,6 +346,12 @@ function buildTraceTree(// Handle empty caseif (sortedObservations.length === 0) {+ // For events-based traces with no observations, return empty roots+ if (trace.rootObservationType) {+ return { roots: [], hiddenObservationsCount, nodeMap: new Map() };+ }++ // Traditional traces: return TRACE node with no childrenconst emptyTree: TreeNode = {id: `trace-${trace.id}`,type: "TRACE",@@ -350,12 +363,13 @@ function buildTraceTree(totalCost: undefined,startTimeSinceTrace: 0,startTimeSinceParentStart: null,+ // depth: -1 for TRACE wrapper so its children (observations) start at depth 0depth: -1,childrenDepth: 0,};const nodeMap = new Map<string, TreeNode>();nodeMap.set(emptyTree.id, emptyTree);- return { tree: emptyTree, hiddenObservationsCount, nodeMap };+ return { roots: [emptyTree], hiddenObservationsCount, nodeMap };}// Phase 2: Build dependency graph@@ -370,7 +384,7 @@ function buildTraceTree(trace.timestamp,);- // Phase 4: Build trace root+ // Phase 4: Build roots arrayconst rootTreeNodes: TreeNode[] = [];for (const rootId of rootIds) {const rootNode = nodeRegistry.get(rootId)!;@@ -379,6 +393,16 @@ function buildTraceTree(}}+ // Sort roots by startTime for consistent ordering+ rootTreeNodes.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());++ // Events-based traces (rootObservationType set): return observations as roots directly+ if (trace.rootObservationType) {+ return { roots: rootTreeNodes, hiddenObservationsCount, nodeMap };+ }++ // Traditional traces: wrap in TRACE node+// Calculate trace root total costconst traceTotalCost = rootTreeNodes.reduce<Decimal | undefined>((acc, child) => {@@ -395,7 +419,7 @@ function buildTraceTree(: 0;// Create trace root node- const tree: TreeNode = {+ const traceNode: TreeNode = {id: `trace-${trace.id}`,type: "TRACE",name: trace.name ?? "",@@ -406,20 +430,21 @@ function buildTraceTree(totalCost: traceTotalCost,startTimeSinceTrace: 0,startTimeSinceParentStart: null,+ // depth: -1 for TRACE wrapper so its children (observations) start at depth 0depth: -1,childrenDepth: traceChildrenDepth,};- nodeMap.set(tree.id, tree);+ nodeMap.set(traceNode.id, traceNode);- return { tree, hiddenObservationsCount, nodeMap };+ return { roots: [traceNode], hiddenObservationsCount, nodeMap };}/*** Main entry point: builds complete UI data from trace and observations.** Returns:- * - tree: Hierarchical TreeNode structure with trace as root+ * - roots: Array of root TreeNodes (single TRACE root for traditional, multiple obs roots for events-based)* - nodeMap: Map<id, TreeNode> for O(1) lookup* - searchItems: Flattened list for search/virtualized rendering* - hiddenObservationsCount: Number filtered by minLevel@@ -429,24 +454,50 @@ export function buildTraceUiData(observations: ObservationReturnType[],minLevel?: ObservationLevelType,): {- tree: TreeNode;+ roots: TreeNode[];hiddenObservationsCount: number;searchItems: TraceSearchListItem[];nodeMap: Map<string, TreeNode>;} {- const { tree, hiddenObservationsCount, nodeMap } = buildTraceTree(+ const { roots, hiddenObservationsCount, nodeMap } = buildTraceTree(trace,observations,minLevel,);- // Use pre-computed totals for heatmap scaling (computed in buildTreeNodesBottomUp)- const rootTotalCost = tree.totalCost;- const rootDuration = tree.latency ? tree.latency * 1000 : undefined;+ // Handle empty roots case+ if (roots.length === 0) {+ return { roots, hiddenObservationsCount, searchItems: [], nodeMap };+ }++ // TODO: Extract aggregation logic to shared utility - duplicated in TraceTree.tsx and TraceTimeline/index.tsx+ // Calculate aggregated totals across all roots for heatmap scaling+ const rootTotalCost = roots.reduce<Decimal | undefined>((acc, r) => {+ if (!r.totalCost) return acc;+ return acc ? acc.plus(r.totalCost) : r.totalCost;+ }, undefined);++ const rootDuration =+ roots.length > 0+ ? Math.max(+ ...roots.map((r) =>+ r.latency+ ? r.latency * 1000+ : r.endTime+ ? r.endTime.getTime() - r.startTime.getTime()+ : 0,+ ),+ )+ : undefined;// Build flat search items list (iterative to avoid stack overflow on deep trees)const searchItems: TraceSearchListItem[] = [];- const stack: TreeNode[] = [tree];++ // Initialize stack with all roots (in reverse order for correct DFS traversal)+ const stack: TreeNode[] = [];+ for (let i = roots.length - 1; i >= 0; i--) {+ stack.push(roots[i]!);+ }while (stack.length > 0) {const node = stack.pop()!;@@ -462,5 +513,5 @@ export function buildTraceUiData(}}- return { tree, hiddenObservationsCount, searchItems, nodeMap };+ return { roots, hiddenObservationsCount, searchItems, nodeMap };}diff --git a/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsxindex 915433740b..23934b1e39 100644--- a/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx@@ -93,7 +93,8 @@ export const SimpleMultiSectionViewer = memo(if (!container) return;const updateWidth = () => {- setContainerWidth(container.clientWidth);+ const newWidth = container.clientWidth;+ setContainerWidth((prev) => (prev === newWidth ? prev : newWidth));};updateWidth(); // Initial measurement@@ -106,7 +107,7 @@ export const SimpleMultiSectionViewer = memo(resizeObserver.observe(container);return () => resizeObserver.disconnect();}- }); // Remove dependency array - run on every render+ }, [scrollContainerRef]);// Get all visible nodesconst allNodes = useMemo(() => {diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex bfa9b9f195..6da3f70e58 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -62,6 +62,12 @@ import { MemoizedIOTableCell } from "@/src/components/ui/IOTableCell";import { useEventsTableData } from "@/src/features/events/hooks/useEventsTableData";import { useEventsFilterOptions } from "@/src/features/events/hooks/useEventsFilterOptions";import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";+import {+ type RefreshInterval,+ REFRESH_INTERVALS,+} from "@/src/components/table/data-table-refresh-button";+import useSessionStorage from "@/src/components/useSessionStorage";+import { api } from "@/src/utils/api";export type EventsTableRow = {// Identity fields@@ -187,10 +193,55 @@ export default function ObservationsEventsTable({const { timeRange, setTimeRange } = useTableDateRange(projectId);+ // for auto data refresh+ const utils = api.useUtils();+ const [rawRefreshInterval, setRawRefreshInterval] =+ useSessionStorage<RefreshInterval>(+ `tableRefreshInterval-events-${projectId}`,+ null,+ );++ // Validate session storage value against allowed intervals+ const allowedValues = REFRESH_INTERVALS.map((i) => i.value);+ const refreshInterval = allowedValues.includes(rawRefreshInterval)+ ? rawRefreshInterval+ : null;+ const setRefreshInterval = useCallback(+ (value: RefreshInterval) => {+ if (allowedValues.includes(value)) {+ setRawRefreshInterval(value);+ }+ },+ [allowedValues, setRawRefreshInterval],+ );++ const [refreshTick, setRefreshTick] = useState(0);++ // Auto-increment refresh tick to force date range recalculation+ useEffect(() => {+ if (!refreshInterval) return;+ const id = setInterval(() => {+ setRefreshTick((t) => t + 1);+ }, refreshInterval);+ return () => clearInterval(id);+ }, [refreshInterval]);++ const handleRefresh = useCallback(() => {+ setRefreshTick((t) => t + 1);+ void Promise.all([+ utils.events.all.invalidate(),+ utils.events.countAll.invalidate(),+ utils.events.filterOptions.invalidate(),+ ]);+ }, [utils]);+// Convert timeRange to absolute date range for compatibility+ // Include refreshTick to force recalculation on refreshconst dateRange = useMemo(() => {+ // refreshTick forces recalculation but isn't used in computation+ void refreshTick;return toAbsoluteTimeRange(timeRange) ?? undefined;- }, [timeRange]);+ }, [timeRange, refreshTick]);const dateRangeFilter: FilterState = dateRange? [@@ -998,6 +1049,12 @@ export default function ObservationsEventsTable({setRowHeight={setRowHeight}timeRange={timeRange}setTimeRange={setTimeRange}+ refreshConfig={{+ onRefresh: handleRefresh,+ isRefreshing: observations.status === "loading",+ interval: refreshInterval,+ setInterval: setRefreshInterval,+ }}actionButtons={[<BatchExportTableButton{...{diff --git a/web/src/features/events/config/filter-config.ts b/web/src/features/events/config/filter-config.tsindex 6a43944d33..3647741850 100644--- a/web/src/features/events/config/filter-config.ts+++ b/web/src/features/events/config/filter-config.ts@@ -27,6 +27,11 @@ export const observationEventsFilterConfig: FilterConfig = {defaultExpanded: ["environment", "name"],facets: [+ {+ type: "boolean" as const,+ column: "hasParentObservation",+ label: "Has Parent Observation",+ },{type: "categorical" as const,column: "environment",@@ -37,6 +42,11 @@ export const observationEventsFilterConfig: FilterConfig = {column: "type",label: getEventsColumnName("type"),},+ {+ type: "categorical" as const,+ column: "traceName",+ label: getEventsColumnName("traceName"),+ },{type: "categorical" as const,column: "name",diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.tsindex 75a42a595f..ce48a42ace 100644--- a/web/src/features/events/hooks/useEventsFilterOptions.ts+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts@@ -62,6 +62,7 @@ export function useEventsFilterOptions({modelId: filterOptions.data?.modelId ?? undefined,promptName: filterOptions.data?.promptName ?? undefined,traceTags: filterOptions.data?.traceTags ?? undefined,+ traceName: filterOptions.data?.traceName ?? undefined,userId: filterOptions.data?.userId ?? undefined,sessionId: filterOptions.data?.sessionId ?? undefined,version: filterOptions.data?.version ?? undefined,diff --git a/web/src/features/events/hooks/useEventsTraceData.ts b/web/src/features/events/hooks/useEventsTraceData.tsnew file mode 100644index 0000000000..3d9b80cfbb--- /dev/null+++ b/web/src/features/events/hooks/useEventsTraceData.ts@@ -0,0 +1,166 @@+import { useMemo } from "react";+import { api } from "@/src/utils/api";+import {+ adaptEventsToTraceFormat,+ type AdaptedTraceData,+} from "@/src/features/events/lib/eventsToTraceAdapter";+import {+ filterAndValidateDbScoreList,+ AGGREGATABLE_SCORE_TYPES,+ ScoreDataTypeEnum,+ type ScoreDomain,+} from "@langfuse/shared";+import {+ type WithStringifiedMetadata,+ toDomainArrayWithStringifiedMetadata,+} from "@/src/utils/clientSideDomainTypes";+import { partition } from "lodash";++interface UseEventsTraceDataProps {+ projectId: string;+ traceId: string;+ timestamp?: Date;+ enabled?: boolean;+}++interface UseEventsTraceDataResult {+ data:+ | (AdaptedTraceData["trace"] & {+ observations: AdaptedTraceData["observations"];+ scores: WithStringifiedMetadata<ScoreDomain>[];+ corrections: ScoreDomain[];+ })+ | undefined;+ isLoading: boolean;+ error: unknown;+}++/**+ * Hook to fetch trace data from the events table instead of traces table.+ * Used when v4 beta mode is enabled.+ *+ * Data flow:+ * 1. Fetch all observations for the trace via events.all (without I/O)+ * 2. Find root observation (no parentObservationId)+ * 3. Fetch root observation's I/O via events.batchIO+ * 4. Fetch scores via getScoresAndCorrectionsForTraces+ * 5. Synthesize trace object from observations+ */+export function useEventsTraceData(+ props: UseEventsTraceDataProps,+): UseEventsTraceDataResult {+ const { projectId, traceId, enabled = true } = props;++ // Step 1: Fetch all observations for this trace (without I/O for performance)+ // TODO: paginationZod caps limit at 100 - for traces with >100 observations,+ // implement pagination or create a dedicated byTraceId endpoint with higher limit+ const eventsQuery = api.events.all.useQuery(+ {+ projectId,+ filter: [+ { column: "traceId", operator: "=", value: traceId, type: "string" },+ ],+ searchQuery: null,+ searchType: [],+ orderBy: { column: "startTime", order: "ASC" },+ page: 1,+ limit: 100,+ },+ {+ enabled: enabled && !!traceId,+ retry(failureCount, error) {+ if (error.data?.code === "UNAUTHORIZED") return false;+ return failureCount < 3;+ },+ staleTime: 60 * 1000, // 1 minute+ },+ );++ // Step 2: Find root observation and calculate time range for batchIO+ const rootObservation = useMemo(() => {+ if (!eventsQuery.data?.observations?.length) return null;+ return eventsQuery.data.observations.find((o) => !o.parentObservationId);+ }, [eventsQuery.data]);++ const timeRange = useMemo(() => {+ if (!eventsQuery.data?.observations?.length) return null;+ const times = eventsQuery.data.observations.map((o) =>+ o.startTime.getTime(),+ );+ return {+ min: new Date(Math.min(...times)),+ max: new Date(Math.max(...times)),+ };+ }, [eventsQuery.data]);++ // Step 3: Fetch I/O for root observation (for trace-level I/O display)+ const rootIOQuery = api.events.batchIO.useQuery(+ {+ projectId,+ observations: rootObservation+ ? [{ id: rootObservation.id, traceId }]+ : [],+ minStartTime: timeRange?.min ?? new Date(),+ maxStartTime: timeRange?.max ?? new Date(),+ },+ {+ enabled:+ enabled && !!rootObservation && !!timeRange && !!eventsQuery.data,+ staleTime: 60 * 1000,+ },+ );++ // Step 4: Fetch scores for the trace+ const scoresQuery = api.events.scoresForTrace.useQuery(+ { traceId, projectId },+ {+ enabled: enabled && !!traceId,+ staleTime: 60 * 1000,+ },+ );++ // Step 5: Transform and merge data+ const transformed = useMemo(() => {+ if (!eventsQuery.data?.observations?.length) return null;++ // Validate and partition scores+ const validatedScores = filterAndValidateDbScoreList({+ scores: scoresQuery.data ?? [],+ dataTypes: [...AGGREGATABLE_SCORE_TYPES, ScoreDataTypeEnum.CORRECTION],+ onParseError: (e) => {+ console.error("[useEventsTraceData] Score validation error:", e);+ },+ });++ const [corrections, scores] = partition(+ validatedScores,+ (s) => s.dataType === ScoreDataTypeEnum.CORRECTION,+ );++ const scoresDomain = toDomainArrayWithStringifiedMetadata(scores);++ const rootIO = rootIOQuery.data?.[0];++ // Adapt events to trace format+ const adapted = adaptEventsToTraceFormat({+ events: eventsQuery.data.observations,+ traceId,+ rootIO: rootIO+ ? { input: rootIO.input, output: rootIO.output }+ : undefined,+ });++ return {+ ...adapted.trace,+ observations: adapted.observations,+ scores: scoresDomain,+ corrections,+ };+ }, [eventsQuery.data, traceId, rootIOQuery.data, scoresQuery.data]);++ return {+ data: transformed ?? undefined,+ isLoading: eventsQuery.isLoading || scoresQuery.isLoading,+ error: eventsQuery.error || scoresQuery.error,+ };+}diff --git a/web/src/features/events/hooks/useObservationListBeta.ts b/web/src/features/events/hooks/useObservationListBeta.tsnew file mode 100644index 0000000000..8db5a77d83--- /dev/null+++ b/web/src/features/events/hooks/useObservationListBeta.ts@@ -0,0 +1,35 @@+import { useEffect } from "react";+import { useRouter } from "next/router";+import useLocalStorage from "@/src/components/useLocalStorage";++export function useObservationListBeta() {+ const router = useRouter();+ const [isBetaEnabled, setIsBetaEnabled] = useLocalStorage<boolean>(+ "observationListBetaEnabled",+ false,+ );++ // Clear hasParentObservation filter whenever beta is OFF+ useEffect(() => {+ if (isBetaEnabled || !router.isReady) return;+ const filter = router.query.filter as string | undefined;+ if (!filter?.includes("hasParentObservation")) return;++ const cleaned = filter+ .split(",")+ .filter((s) => !s.startsWith("hasParentObservation"));+ void router.replace(+ {+ pathname: router.pathname,+ query: {+ ...router.query,+ filter: cleaned.length ? cleaned.join(",") : undefined,+ },+ },+ undefined,+ { shallow: true },+ );+ }, [isBetaEnabled, router.isReady]); // eslint-disable-line react-hooks/exhaustive-deps++ return { isBetaEnabled, setBetaEnabled: setIsBetaEnabled };+}diff --git a/web/src/features/events/lib/eventsToTraceAdapter.ts b/web/src/features/events/lib/eventsToTraceAdapter.tsnew file mode 100644index 0000000000..d3cf37bbd2--- /dev/null+++ b/web/src/features/events/lib/eventsToTraceAdapter.ts@@ -0,0 +1,91 @@+import { type EventsObservation, type TraceDomain } from "@langfuse/shared";+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";++export type SyntheticTrace = WithStringifiedMetadata<+ Omit<TraceDomain, "input" | "output">+> & {+ input: string | null;+ output: string | null;+ latency?: number;+ rootObservationType?: string;+ rootObservationId?: string;+};++export interface AdaptedTraceData {+ trace: SyntheticTrace;+ observations: ObservationReturnTypeWithMetadata[];+}++/**+ * Adapts events (observations from events table) to the trace format expected by the Trace component.+ *+ * In v4, traces don't exist as separate entities - we synthesize a "trace" object from observations.+ * The root observation (no parentObservationId) provides trace-level properties like name.+ */+export function adaptEventsToTraceFormat(params: {+ events: EventsObservation[];+ traceId: string;+ rootIO?: { input: unknown; output: unknown } | null;+}): AdaptedTraceData {+ const { events, traceId, rootIO } = params;++ if (events.length === 0) {+ throw new Error("Cannot adapt empty events array to trace format");+ }++ // Sort by startTime to find earliest+ const sorted = [...events].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );+ const earliest = sorted[0]!;++ // TODO: think, how to determine root span?+ const root = events.find((e) => !e.parentObservationId);++ const endTimes = events+ .map((e) => e.endTime)+ .filter((t): t is Date => t !== null);+ const latestEnd =+ endTimes.length > 0 ? Math.max(...endTimes.map((d) => d.getTime())) : null;+ const latencyMs = latestEnd+ ? latestEnd - earliest.startTime.getTime()+ : undefined;++ // Create synthetic trace from observations+ const trace: SyntheticTrace = {+ id: traceId,+ projectId: earliest.projectId,+ name: root?.name ?? earliest.name ?? null,+ timestamp: earliest.startTime,+ input: rootIO?.input ? JSON.stringify(rootIO.input) : null,+ output: rootIO?.output ? JSON.stringify(rootIO.output) : null,+ metadata: JSON.stringify(root?.metadata ?? {}),+ tags: [], // Events have tags on each observation, not trace-level+ bookmarked: false,+ public: false,+ release: earliest.version ?? null,+ version: earliest.version ?? null,+ userId: earliest.userId ?? null,+ sessionId: earliest.sessionId ?? null,+ environment: earliest.environment,+ latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,+ createdAt: earliest.createdAt,+ updatedAt: earliest.updatedAt,+ rootObservationType: root?.type,+ rootObservationId: root?.id,+ };++ // Map events to ObservationReturnTypeWithMetadata+ // Input/output are undefined - they're fetched separately when observation is selected+ const observations: ObservationReturnTypeWithMetadata[] = events.map((e) => ({+ ...e,+ traceId: traceId,+ metadata:+ typeof e.metadata === "string" ? e.metadata : JSON.stringify(e.metadata),+ input: undefined,+ output: undefined,+ }));++ return { trace, observations };+}diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex cd8ef5f57c..5812e020b1 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -17,7 +17,16 @@ import {getEventFilterOptions,getEventBatchIO,} from "./eventsService";-import { instrumentAsync } from "@langfuse/shared/src/server";+import {+ instrumentAsync,+ getScoresAndCorrectionsForTraces,+ convertDateToClickhouseDateTime,+ getAgentGraphDataFromEventsTable,+} from "@langfuse/shared/src/server";+import {+ AgentGraphDataSchema,+ type AgentGraphDataResponse,+} from "@/src/features/trace-graph-view/types";import type * as opentelemetry from "@opentelemetry/api";const GetAllEventsInput = EventsTableOptions.extend({@@ -50,6 +59,7 @@ export const BatchIOInput = zodSchema.object({),minStartTime: zodSchema.date(),maxStartTime: zodSchema.date(),+ truncated: zodSchema.boolean().optional(), // Defaults to true for performance});export type BatchIOInput = z.infer<typeof BatchIOInput>;@@ -132,10 +142,123 @@ export const eventsRouter = createTRPCRouter({observations: input.observations,minStartTime: input.minStartTime,maxStartTime: input.maxStartTime,+ truncated: input.truncated,+ });+ },+ );+ }),+ /**+ * Fetch scores and corrections for a trace.+ * Used by the v4 trace detail view where trace data comes from events table.+ */+ scoresForTrace: protectedProjectProcedure+ .input(+ zodSchema.object({+ projectId: zodSchema.string(),+ traceId: zodSchema.string(),+ timestamp: zodSchema.date().optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ return instrumentAsync(+ { name: "get-events-scores-for-trace-trpc" },+ async (span) => {+ span.setAttribute("project_id", input.projectId);+ span.setAttribute("trace_id", input.traceId);++ return getScoresAndCorrectionsForTraces({+ projectId: ctx.session.projectId,+ traceIds: [input.traceId],+ timestamp: input.timestamp,});},);}),+ /**+ * Fetch agent graph data from events table.+ * Used by v4 events-based trace detail view for graph visualization.+ * Returns same shape as traces.getAgentGraphData for frontend compatibility.+ */+ getAgentGraphData: protectedProjectProcedure+ .input(+ zodSchema.object({+ projectId: zodSchema.string(),+ traceId: zodSchema.string(),+ minStartTime: zodSchema.string(),+ maxStartTime: zodSchema.string(),+ }),+ )+ .query(+ async ({ input, ctx }): Promise<Required<AgentGraphDataResponse>[]> => {+ return instrumentAsync(+ { name: "get-events-agent-graph-data-trpc" },+ async (span) => {+ span.setAttribute("project_id", input.projectId);+ span.setAttribute("trace_id", input.traceId);++ const { traceId, minStartTime, maxStartTime } = input;++ const chMinStartTime = convertDateToClickhouseDateTime(+ new Date(minStartTime),+ );+ const chMaxStartTime = convertDateToClickhouseDateTime(+ new Date(maxStartTime),+ );++ const records = await getAgentGraphDataFromEventsTable({+ projectId: ctx.session.projectId,+ traceId,+ chMinStartTime,+ chMaxStartTime,+ });++ // Transform to AgentGraphDataResponse format+ // TODO: Extract this transformation logic into a shared utility+ // (duplicated from traces.getAgentGraphData in traces.ts)+ const result = records+ .map((r) => {+ const parsed = AgentGraphDataSchema.safeParse(r);+ if (!parsed.success) {+ return null;+ }++ const data = parsed.data;+ const hasLangGraphData = data.step != null && data.node != null;+ const hasAgentData = data.type !== "EVENT";++ if (hasLangGraphData) {+ return {+ id: data.id,+ node: data.node,+ step: data.step,+ parentObservationId: data.parent_observation_id || null,+ name: data.name,+ startTime: data.start_time,+ endTime: data.end_time || undefined,+ observationType: data.type,+ };+ } else if (hasAgentData) {+ return {+ id: data.id,+ node: data.name,+ step: 0,+ parentObservationId: data.parent_observation_id || null,+ name: data.name,+ startTime: data.start_time,+ endTime: data.end_time || undefined,+ observationType: data.type,+ };+ }++ return null;+ })+ .filter((r): r is Required<AgentGraphDataResponse> => Boolean(r));++ return result;+ },+ );+ },+ ),});export const addAttributesToSpan = ({diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex 0dfb700294..53c3f17a82 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -6,6 +6,7 @@ import {getEventsGroupedByModel,getEventsGroupedByModelId,getEventsGroupedByName,+ getEventsGroupedByTraceName,getEventsGroupedByPromptName,getEventsGroupedByType,getEventsGroupedByUserId,@@ -120,6 +121,7 @@ export async function getEventFilterOptions(name,promptNames,traceTags,+ traceNames,modelId,types,userIds,@@ -134,6 +136,7 @@ export async function getEventFilterOptions(getEventsGroupedByName(projectId, startTimeFilter ?? []),getEventsGroupedByPromptName(projectId, startTimeFilter ?? []),getClickhouseTraceTags(),+ getEventsGroupedByTraceName(projectId, startTimeFilter ?? []),getEventsGroupedByModelId(projectId, startTimeFilter ?? []),getEventsGroupedByType(projectId, startTimeFilter ?? []),getEventsGroupedByUserId(projectId, startTimeFilter ?? []),@@ -169,6 +172,12 @@ export async function getEventFilterOptions(.map((i) => ({value: i.tag as string,})),+ traceName: traceNames+ .filter((i) => i.traceName !== null)+ .map((i) => ({+ value: i.traceName as string,+ count: i.count,+ })),type: types.filter((i) => i.type !== null).map((i) => ({@@ -216,6 +225,7 @@ interface GetEventBatchIOParams {}>;minStartTime: Date;maxStartTime: Date;+ truncated?: boolean;}/**@@ -229,5 +239,6 @@ export async function getEventBatchIO(observations: params.observations,minStartTime: params.minStartTime,maxStartTime: params.maxStartTime,+ truncated: params.truncated,});}diff --git a/web/src/hooks/useParsedObservation.ts b/web/src/hooks/useParsedObservation.tsindex 9054d3c1c5..3ebbb0efac 100644--- a/web/src/hooks/useParsedObservation.ts+++ b/web/src/hooks/useParsedObservation.ts@@ -12,7 +12,14 @@*/import { useQuery } from "@tanstack/react-query";+import { useMemo, useEffect } from "react";import { api } from "@/src/utils/api";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";+import {+ type ObservationReturnTypeWithMetadata,+ type ObservationReturnType,+} from "@/src/server/api/routers/traces";+import { stringifyMetadata } from "@/src/utils/clientSideDomainTypes";import type {ParseRequest,ParseResponse,@@ -84,6 +91,8 @@ interface UseParsedObservationParams {traceId: string;projectId: string;startTime?: Date;+ // Base observation to merge IO data into (for events path when beta ON)+ baseObservation?: ObservationReturnType | ObservationReturnTypeWithMetadata;}interface ParsedData {@@ -183,8 +192,11 @@ export function useParsedObservation({traceId,projectId,startTime,+ baseObservation,}: UseParsedObservationParams) {- // Step 1: Fetch raw observation data via tRPC (React Query caches this)+ const { isBetaEnabled } = useObservationListBeta();++ // Step 1a: Fetch raw observation data from observations table (beta OFF)const observationQuery = api.observations.byId.useQuery({observationId,@@ -193,39 +205,89 @@ export function useParsedObservation({startTime,},{+ enabled: !isBetaEnabled,+ staleTime: 5 * 60 * 1000, // 5 minutes+ },+ );++ // Step 1b: Fetch raw observation data from events table (beta ON)+ const eventsQuery = api.events.batchIO.useQuery(+ {+ projectId,+ observations: [{ id: observationId, traceId }],+ minStartTime: startTime ?? new Date(0),+ maxStartTime: startTime ?? new Date(),+ truncated: false,+ },+ {+ enabled: isBetaEnabled,staleTime: 5 * 60 * 1000, // 5 minutes+ select: (data) => data[0], // Extract single result from batch},);+ const mergedObservation = useMemo(() => {+ if (isBetaEnabled) {+ if (baseObservation && eventsQuery.data) {+ return {+ ...baseObservation,+ input: eventsQuery.data.input as string,+ output: eventsQuery.data.output as string,+ // Stringify metadata to match ObservationReturnTypeWithMetadata format+ metadata: stringifyMetadata(eventsQuery.data.metadata),+ };+ }+ // No base observation provided: return events data as-is (incomplete type)+ return eventsQuery.data;+ }+ // Beta OFF: return full observation from observations table+ return observationQuery.data;+ }, [isBetaEnabled, baseObservation, eventsQuery.data, observationQuery.data]);++ // TODO: remove when going into prod+ // Log warning if baseObservation missing when beta ON (helps catch issues in testing)+ useEffect(() => {+ if (isBetaEnabled && eventsQuery.data && !baseObservation) {+ console.warn(+ "[useParsedObservation] baseObservation missing - JumpToPlaygroundButton may not work correctly",+ { observationId },+ );+ }+ }, [isBetaEnabled, eventsQuery.data, baseObservation, observationId]);++ const isLoadingRaw = isBetaEnabled+ ? eventsQuery.isLoading+ : observationQuery.isLoading;+// Step 2: Parse the data in Web Worker (React Query caches THIS too!)const parseQuery = useQuery({queryKey: ["parsed-observation",observationId,// Include data hash to detect changes- observationQuery.data?.input,- observationQuery.data?.output,- observationQuery.data?.metadata,+ mergedObservation?.input,+ mergedObservation?.output,+ mergedObservation?.metadata,],queryFn: async () => {- if (!observationQuery.data) {+ if (!mergedObservation) {throw new Error("No observation data to parse");}return parseObservationData(- observationQuery.data.input,- observationQuery.data.output,- observationQuery.data.metadata,+ mergedObservation.input,+ mergedObservation.output,+ mergedObservation.metadata,);},- enabled: !!observationQuery.data, // Only run when we have data+ enabled: !!mergedObservation, // Only run when we have datastaleTime: Infinity, // Parsed data never goes stale (input data is the source of truth)gcTime: 10 * 60 * 1000, // Keep in cache for 10 minutes after unmount});return {- // Original observation data (cached by tRPC/React Query)- observation: observationQuery.data,+ // Observation data (merged with base when beta ON, or from observations table when beta OFF)+ observation: mergedObservation,// Parsed data (cached by React Query)parsedInput: parseQuery.data?.input,@@ -233,15 +295,13 @@ export function useParsedObservation({parsedMetadata: parseQuery.data?.metadata,// Loading states- isLoadingObservation: observationQuery.isLoading,+ isLoadingObservation: isLoadingRaw,isParsing: parseQuery.isLoading,isReady:- !observationQuery.isLoading &&- !parseQuery.isLoading &&- parseQuery.data !== undefined,- // True when we have raw data but parsing hasn't completed yet+ !isLoadingRaw && !parseQuery.isLoading && parseQuery.data !== undefined,+ // True when we have observation data but parsing hasn't completed yetisWaitingForParsing:- !!observationQuery.data &&+ !!mergedObservation &&(parseQuery.isLoading || parseQuery.data === undefined),// Debug infodiff --git a/web/src/pages/project/[projectId]/observations.tsx b/web/src/pages/project/[projectId]/observations.tsxindex 69c00fde9c..e245c0f4b3 100644--- a/web/src/pages/project/[projectId]/observations.tsx+++ b/web/src/pages/project/[projectId]/observations.tsx@@ -1,5 +1,6 @@import React from "react";import { useRouter } from "next/router";+import { useSession } from "next-auth/react";import ObservationsTable from "@/src/components/table/use-cases/observations";import Page from "@/src/components/layouts/page";import { api } from "@/src/utils/api";@@ -8,10 +9,25 @@ import {getTracingTabs,TRACING_TABS,} from "@/src/features/navigation/utils/tracing-tabs";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";+import ObservationsEventsTable from "@/src/features/events/components/EventsTable";+import { Switch } from "@/src/components/ui/switch";+import { Label } from "@/src/components/ui/label";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";export default function Generations() {const router = useRouter();const projectId = router.query.projectId as string;+ const { data: session } = useSession();+ const { isBetaEnabled, setBetaEnabled } = useObservationListBeta();++ // TODO: remove for prod go-live+ const showBetaToggle = session?.user?.email?.endsWith("@langfuse.com");// Check if the user has tracing configuredconst { data: hasTracingConfigured, isLoading } =@@ -30,6 +46,28 @@ export default function Generations() {const showOnboarding = !isLoading && !hasTracingConfigured;+ const betaToggle = showBetaToggle ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center gap-2">+ <Switch+ id="beta-toggle"+ checked={isBetaEnabled}+ onCheckedChange={setBetaEnabled}+ />+ <Label htmlFor="beta-toggle" className="cursor-pointer text-xs">+ Beta+ </Label>+ </div>+ </TooltipTrigger>+ <TooltipContent>+ <p>Try the high performance events based observation view</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : null;+return (<PageheaderProps={{@@ -39,16 +77,21 @@ export default function Generations() {"An observation captures a single function call in an application. See docs to learn more.",href: "https://langfuse.com/docs/observability/data-model",},- tabsProps: {- tabs: getTracingTabs(projectId),- activeTab: TRACING_TABS.OBSERVATIONS,- },+ actionButtonsLeft: betaToggle,+ tabsProps: isBetaEnabled+ ? undefined+ : {+ tabs: getTracingTabs(projectId),+ activeTab: TRACING_TABS.OBSERVATIONS,+ },}}scrollable={showOnboarding}>{/* Show onboarding screen if user has no traces */}{showOnboarding ? (<TracesOnboarding projectId={projectId} />+ ) : isBetaEnabled ? (+ <ObservationsEventsTable projectId={projectId} />) : (<ObservationsTable projectId={projectId} />)}diff --git a/web/src/pages/project/[projectId]/traces.tsx b/web/src/pages/project/[projectId]/traces.tsxindex e01c53f6fe..c5e5f371c0 100644--- a/web/src/pages/project/[projectId]/traces.tsx+++ b/web/src/pages/project/[projectId]/traces.tsx@@ -1,5 +1,6 @@-import React from "react";+import React, { useEffect, useRef } from "react";import { useRouter } from "next/router";+import { useSession } from "next-auth/react";import TracesTable from "@/src/components/table/use-cases/traces";import Page from "@/src/components/layouts/page";import { api } from "@/src/utils/api";@@ -8,10 +9,58 @@ import {getTracingTabs,TRACING_TABS,} from "@/src/features/navigation/utils/tracing-tabs";+import { useObservationListBeta } from "@/src/features/events/hooks/useObservationListBeta";+import ObservationsEventsTable from "@/src/features/events/components/EventsTable";+import { Switch } from "@/src/components/ui/switch";+import { Label } from "@/src/components/ui/label";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";export default function Traces() {const router = useRouter();const projectId = router.query.projectId as string;+ const { data: session } = useSession();+ const { isBetaEnabled, setBetaEnabled } = useObservationListBeta();+ const hasAppliedDefaultFilter = useRef(false);++ // TODO: remove for prod go-live+ const showBetaToggle = session?.user?.email?.endsWith("@langfuse.com");++ // Apply default filter when beta is enabled on traces page+ useEffect(() => {+ if (!isBetaEnabled || !projectId) return;++ // Only apply on fresh navigation (not on back button)+ if (hasAppliedDefaultFilter.current) return;+ hasAppliedDefaultFilter.current = true;++ const currentFilter = router.query.filter as string | undefined;+ if (currentFilter?.includes("hasParentObservation")) return;++ // Apply default filter: hasParentObservation = false+ const defaultFilter = "hasParentObservation;boolean;;=;false";+ const newFilter = currentFilter+ ? `${currentFilter},${defaultFilter}`+ : defaultFilter;++ void router.replace(+ {+ pathname: router.pathname,+ query: { ...router.query, filter: newFilter },+ },+ undefined,+ { shallow: true },+ );+ }, [isBetaEnabled, projectId, router]);++ // Reset ref on beta toggle or unmount+ useEffect(() => {+ if (!isBetaEnabled) hasAppliedDefaultFilter.current = false;+ }, [isBetaEnabled]);// Check if the user has tracing configuredconst { data: hasTracingConfigured, isLoading } =@@ -30,6 +79,29 @@ export default function Traces() {const showOnboarding = !isLoading && !hasTracingConfigured;+ const betaToggle = showBetaToggle ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center gap-2">+ <Switch+ id="beta-toggle"+ checked={isBetaEnabled}+ onCheckedChange={setBetaEnabled}+ />+ <Label htmlFor="beta-toggle" className="cursor-pointer text-xs">+ Beta+ </Label>+ </div>+ </TooltipTrigger>+ <TooltipContent>+ Try the new unified observations view powered by the events table+ <p>Try the high performance events based observation view</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : null;+if (showOnboarding) {return (<Page@@ -40,6 +112,7 @@ export default function Traces() {"A trace represents a single function/api invocation. Traces contain observations. See docs to learn more.",href: "https://langfuse.com/docs/observability/data-model",},+ actionButtonsLeft: betaToggle,}}scrollable>@@ -57,13 +130,20 @@ export default function Traces() {"A trace represents a single function/api invocation. Traces contain observations. See docs to learn more.",href: "https://langfuse.com/docs/observability/data-model",},- tabsProps: {- tabs: getTracingTabs(projectId),- activeTab: TRACING_TABS.TRACES,- },+ actionButtonsLeft: betaToggle,+ tabsProps: isBetaEnabled+ ? undefined+ : {+ tabs: getTracingTabs(projectId),+ activeTab: TRACING_TABS.TRACES,+ },}}>- <TracesTable projectId={projectId} />+ {isBetaEnabled ? (+ <ObservationsEventsTable projectId={projectId} />+ ) : (+ <TracesTable projectId={projectId} />+ )}</Page>);}