🪢 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
chore(events-table): more than 100 observations per trace through tRPC (#12048)
Nimare5ff2311b1f4
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex c22d3c3b89..ebeb846f54 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -1,4 +1,5 @@import { OBSERVATIONS_TO_TRACE_INTERVAL } from "../../repositories/constants";+import { FilterList, StringFilter } from "./clickhouse-filter";/*** Types for structured ORDER BY API@@ -697,6 +698,28 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<return this;}+ /**+ * Apply filters from a FilterList with automatic query optimizations.+ * When a trace_id equality filter is detected, adds xxHash32 optimization+ * for efficient ClickHouse partition pruning.+ */+ applyFilters(filterList: FilterList): this {+ const traceIdFilter = filterList.find(+ (f) =>+ // events_full / events_core proof+ f.clickhouseTable.startsWith("events") &&+ f.field === 'e."trace_id"' &&+ f.operator === "=",+ );+ if (traceIdFilter instanceof StringFilter) {+ this.whereRaw("xxHash32(trace_id) = xxHash32({traceIdXxHash: String})", {+ traceIdXxHash: traceIdFilter.value,+ });+ }+ this.where(filterList.apply());+ return this;+ }+/*** Add IO fields with optional truncation*/diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 55a46bcda1..b04e566cbf 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -283,6 +283,61 @@ const TRACES_ORDER_BY_COLUMNS = TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS.filter(queryPrefix: "t", // Use 't' prefix because we're selecting from traces CTE}));+// TODO: introduce pagination+export const MAX_OBSERVATIONS_PER_TRACE = 10_000;++export const getObservationsForTraceFromEventsTable = async (params: {+ projectId: string;+ traceId: string;+ timestamp?: Date;+}): Promise<{ observations: FullEventsObservations; totalCount: number }> => {+ const { projectId, traceId, timestamp } = params;++ const filter: FilterState = [+ {+ column: "traceId",+ operator: "=" as const,+ value: traceId,+ type: "string" as const,+ },+ ];++ if (timestamp) {+ filter.push({+ column: "startTime",+ operator: ">=" as const,+ // Equivalent to TRACE_TO_OBSERVATIONS_INTERVAL (INTERVAL 1 HOUR)+ value: new Date(timestamp.getTime() - 60 * 60 * 1000),+ type: "datetime" as const,+ });+ }++ const records =+ await getObservationsFromEventsTableInternal<ObservationsTableQueryResultWitouhtTraceFields>(+ {+ projectId,+ filter,+ orderBy: { column: "startTime", order: "ASC" },+ limit: MAX_OBSERVATIONS_PER_TRACE + 1,+ offset: 0,+ select: "rows",+ tags: { kind: "byTraceId" },+ },+ );++ const totalCount = records.length;++ const withModelData = await enrichObservationsWithModelData(+ records.slice(0, MAX_OBSERVATIONS_PER_TRACE),+ projectId,+ false,+ null,+ );+ const observations = await enrichObservationsWithTraceFields(withModelData);++ return { observations, totalCount };+};+export const getObservationsCountFromEventsTable = async (opts: ObservationTableQuery,) => {@@ -346,7 +401,6 @@ async function getObservationsFromEventsTableInternal<T>(const hasScoresFilter = filter.some((f) =>f.column.toLowerCase().includes("score"),);- const appliedObservationsFilter = observationsFilter.apply();const search = clickhouseSearchCondition(opts.searchQuery,opts.searchType,@@ -403,7 +457,7 @@ async function getObservationsFromEventsTableInternal<T>(.when(hasScoresFilter, (b) =>b.leftJoin("scores_agg AS s", "ON s.observation_id = e.span_id"),)- .where(appliedObservationsFilter)+ .applyFilters(observationsFilter).where(search).when(orderByEntries.length > 0, (b) => b.orderByColumns(orderByEntries)).limit(limit, offset);@@ -430,6 +484,7 @@ async function getObservationsFromEventsTableInternal<T>(params: input.params,tags: input.tags,clickhouseConfigs,+ preferredClickhouseService: "EventsReadOnly",});},});diff --git a/web/src/components/trace2/TracePage.tsx b/web/src/components/trace2/TracePage.tsxindex 7e96b06dfe..ac1b8515f2 100644--- a/web/src/components/trace2/TracePage.tsx+++ b/web/src/components/trace2/TracePage.tsx@@ -16,6 +16,8 @@ import { stripBasePath } from "@/src/utils/redirect";import { Badge } from "@/src/components/ui/badge";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { useEffect } from "react";export function TracePage({traceId,@@ -76,6 +78,16 @@ export function TracePage({withDefault(StringParam, "details"),);+ useEffect(() => {+ if (isBetaEnabled && eventsData.cutoffObservationsAfterMaxCount) {+ showErrorToast(+ "Trace truncated",+ "This trace has too many observations for the detail view. Only a subset is shown.",+ "WARNING",+ );+ }+ }, [isBetaEnabled, eventsData.cutoffObservationsAfterMaxCount]);+// Handle errors - for events path, we check if there's no data after loadingif (!isBetaEnabled && tracesQuery.error?.data?.code === "UNAUTHORIZED")return <ErrorPage message="You do not have access to this trace." />;diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.tsindex cfb2e7884e..c6f66ed95c 100644--- a/web/src/features/events/hooks/useEventsTableData.ts+++ b/web/src/features/events/hooks/useEventsTableData.ts@@ -66,7 +66,6 @@ export function useEventsTableData({],);- // Fetch observationsconst observations = api.events.all.useQuery(getAllPayload, {refetchOnWindowFocus: true,});diff --git a/web/src/features/events/hooks/useEventsTraceData.ts b/web/src/features/events/hooks/useEventsTraceData.tsindex 3d9b80cfbb..027df06747 100644--- a/web/src/features/events/hooks/useEventsTraceData.ts+++ b/web/src/features/events/hooks/useEventsTraceData.ts@@ -10,6 +10,7 @@ import {ScoreDataTypeEnum,type ScoreDomain,} from "@langfuse/shared";+import type { FullEventsObservations } from "@langfuse/shared/src/server";import {type WithStringifiedMetadata,toDomainArrayWithStringifiedMetadata,@@ -33,6 +34,7 @@ interface UseEventsTraceDataResult {| undefined;isLoading: boolean;error: unknown;+ cutoffObservationsAfterMaxCount: boolean;}/**@@ -52,19 +54,11 @@ export function useEventsTraceData(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(+ const eventsQuery = api.events.byTraceId.useQuery({projectId,- filter: [- { column: "traceId", operator: "=", value: traceId, type: "string" },- ],- searchQuery: null,- searchType: [],- orderBy: { column: "startTime", order: "ASC" },- page: 1,- limit: 100,+ traceId,+ timestamp: props.timestamp,},{enabled: enabled && !!traceId,@@ -77,21 +71,23 @@ export function useEventsTraceData();// Step 2: Find root observation and calculate time range for batchIO+ const observations = eventsQuery.data?.observations as+ | FullEventsObservations+ | undefined;+const rootObservation = useMemo(() => {- if (!eventsQuery.data?.observations?.length) return null;- return eventsQuery.data.observations.find((o) => !o.parentObservationId);- }, [eventsQuery.data]);+ if (!observations?.length) return null;+ return observations.find((o) => !o.parentObservationId);+ }, [observations]);const timeRange = useMemo(() => {- if (!eventsQuery.data?.observations?.length) return null;- const times = eventsQuery.data.observations.map((o) =>- o.startTime.getTime(),- );+ if (!observations?.length) return null;+ const times = observations.map((o) => o.startTime.getTime());return {min: new Date(Math.min(...times)),max: new Date(Math.max(...times)),};- }, [eventsQuery.data]);+ }, [observations]);// Step 3: Fetch I/O for root observation (for trace-level I/O display)const rootIOQuery = api.events.batchIO.useQuery(@@ -112,7 +108,7 @@ export function useEventsTraceData(// Step 4: Fetch scores for the traceconst scoresQuery = api.events.scoresForTrace.useQuery(- { traceId, projectId },+ { traceId, projectId, timestamp: props.timestamp },{enabled: enabled && !!traceId,staleTime: 60 * 1000,@@ -121,7 +117,7 @@ export function useEventsTraceData(// Step 5: Transform and merge dataconst transformed = useMemo(() => {- if (!eventsQuery.data?.observations?.length) return null;+ if (!observations?.length) return null;// Validate and partition scoresconst validatedScores = filterAndValidateDbScoreList({@@ -143,7 +139,7 @@ export function useEventsTraceData(// Adapt events to trace formatconst adapted = adaptEventsToTraceFormat({- events: eventsQuery.data.observations,+ events: observations,traceId,rootIO: rootIO? { input: rootIO.input, output: rootIO.output }@@ -156,11 +152,15 @@ export function useEventsTraceData(scores: scoresDomain,corrections,};- }, [eventsQuery.data, traceId, rootIOQuery.data, scoresQuery.data]);+ }, [observations, traceId, rootIOQuery.data, scoresQuery.data]);++ const cutoffObservationsAfterMaxCount =+ eventsQuery.data?.cutoffObservationsAfterMaxCount ?? false;return {data: transformed ?? undefined,isLoading: eventsQuery.isLoading || scoresQuery.isLoading,error: eventsQuery.error || scoresQuery.error,+ cutoffObservationsAfterMaxCount,};}diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex 636b692187..22636c940e 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -22,7 +22,10 @@ import {getScoresAndCorrectionsForTraces,convertDateToClickhouseDateTime,getAgentGraphDataFromEventsTable,+ getObservationsForTraceFromEventsTable,+ MAX_OBSERVATIONS_PER_TRACE,} from "@langfuse/shared/src/server";+import {AgentGraphDataSchema,type AgentGraphDataResponse,@@ -176,6 +179,41 @@ export const eventsRouter = createTRPCRouter({},);}),+ /**+ * Fetch all observations for a trace from the events table.+ * Returns up to MAX_OBSERVATIONS_PER_TRACE observations.+ * Sets cutoffObservationsAfterMaxCount=true if trace exceeds the cap.+ */+ byTraceId: protectedProjectProcedure+ .input(+ zodSchema.object({+ projectId: zodSchema.string(),+ traceId: zodSchema.string(),+ timestamp: zodSchema.date().optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ return instrumentAsync(+ { name: "get-events-by-trace-id-trpc" },+ async (span) => {+ span.setAttribute("project_id", ctx.session.projectId);+ span.setAttribute("trace_id", input.traceId);++ const { observations, totalCount } =+ await getObservationsForTraceFromEventsTable({+ projectId: ctx.session.projectId,+ traceId: input.traceId,+ timestamp: input.timestamp,+ });++ return {+ observations,+ cutoffObservationsAfterMaxCount:+ totalCount > MAX_OBSERVATIONS_PER_TRACE,+ };+ },+ );+ }),/*** Fetch agent graph data from events table.* Used by v4 events-based trace detail view for graph visualization.