🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(batch-export): read observations from events table for v4 users (#14216)
Niklas Semmler870b849327ef
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.tsindex cacc12443b..3ee13d9b27 100644--- a/worker/src/__tests__/batchExport.test.ts+++ b/worker/src/__tests__/batchExport.test.ts@@ -14,8 +14,13 @@ import {createEvent,createEventsCh,getEventsForBlobStorageExport,+ streamTransformations,} from "@langfuse/shared/src/server";-import { BatchExportTableName, DatasetStatus } from "@langfuse/shared";+import {+ BatchExportFileFormat,+ BatchExportTableName,+ DatasetStatus,+} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { getDatabaseReadStreamPaginated } from "../features/database-read-stream/getDatabaseReadStream";import { getObservationStream } from "../features/database-read-stream/observation-stream";@@ -2500,6 +2505,293 @@ describe("batch export test suite", () => {expect(session2Row?.totalTokens).toBeGreaterThan(0n);});+ it("should export observations from the events table when useEventsTable is true", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = randomUUID();+ const now = Date.now() * 1000; // Events use microseconds++ const events = [+ createEvent({+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "events-generation",+ trace_name: "events-trace",+ user_id: "events-user",+ tags: ["tag-a", "tag-b"],+ start_time: now,+ end_time: now + 1000000,+ }),+ createEvent({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "SPAN",+ name: "events-span",+ start_time: now,+ end_time: now + 2000000,+ }),+ ];++ await createEventsCh(events);++ const score = createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: events[0].span_id,+ name: "quality",+ value: 42,+ });+ await createScoresCh([score]);++ const stream = await getObservationStream({+ projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [],+ useEventsTable: true,+ });++ const rows: any[] = [];+ for await (const chunk of stream) {+ rows.push(chunk);+ }++ expect(rows).toHaveLength(2);+ // Rows keep the legacy observation export field names so the export+ // schema is stable across the legacy and events read paths.+ expect(rows).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: events[0].span_id,+ name: "events-generation",+ type: "GENERATION",+ traceId: traceId,+ traceName: "events-trace",+ traceTags: ["tag-a", "tag-b"],+ userId: "events-user",+ model: "gpt-3.5-turbo",+ input: "Hello World",+ output: "Hello John",+ metadata: expect.objectContaining({+ source: "API",+ server: "Node",+ }),+ quality: [score.value],+ comments: [],+ }),+ expect.objectContaining({+ id: events[1].span_id,+ name: "events-span",+ type: "SPAN",+ latency: 2,+ quality: null,+ }),+ ]),+ );+ // Concrete usage check: a regression that silently zeroed the usage+ // aggregates read from the events table would surface here.+ const generationRow = rows.find((r) => r.id === events[0].span_id);+ expect(generationRow?.totalUsage).toBeGreaterThan(0);+ });++ it("should apply observation-level score filters and ignore trace-level score filters when useEventsTable is true", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = randomUUID();+ const now = Date.now() * 1000;++ const events = [+ createEvent({+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "high-accuracy",+ start_time: now,+ }),+ createEvent({+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "medium-accuracy",+ start_time: now,+ }),+ createEvent({+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "low-accuracy",+ start_time: now,+ }),+ ];+ await createEventsCh(events);++ const scores = [+ createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: events[0].span_id,+ name: "accuracy",+ value: 0.95,+ data_type: "NUMERIC",+ }),+ createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: events[1].span_id,+ name: "accuracy",+ value: 0.75,+ data_type: "NUMERIC",+ }),+ createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: events[2].span_id,+ name: "accuracy",+ value: 0.45,+ data_type: "NUMERIC",+ }),+ ];+ await createScoresCh(scores);++ // Observation-level score filter applies (accuracy >= 0.7); the+ // trace-level score filter references the trace_scores_agg CTE that the+ // export does not join, so it is dropped rather than failing the export.+ const stream = await getObservationStream({+ projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [+ {+ type: "numberObject",+ column: "Scores",+ key: "accuracy",+ operator: ">=",+ value: 0.7,+ },+ {+ type: "numberObject",+ column: "Trace Scores (numeric)",+ key: "accuracy",+ operator: "<",+ value: 0,+ },+ ],+ useEventsTable: true,+ });++ const rows: any[] = [];+ for await (const chunk of stream) {+ rows.push(chunk);+ }++ expect(rows).toHaveLength(2);+ expect(rows.map((row) => row.name).sort()).toEqual([+ "high-accuracy",+ "medium-accuracy",+ ]);+ expect(rows.find((r) => r.name === "high-accuracy")?.accuracy).toEqual([+ 0.95,+ ]);+ expect(rows.find((r) => r.name === "medium-accuracy")?.accuracy).toEqual([+ 0.75,+ ]);+ });++ it("should not read the legacy observations table when useEventsTable is true", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ // One row only in the legacy observations table, one only in events+ const legacyObservation = createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "GENERATION",+ });+ await createObservationsCh([legacyObservation]);++ const event = createEvent({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "GENERATION",+ start_time: Date.now() * 1000,+ });+ await createEventsCh([event]);++ const streamParams = {+ projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [],+ };++ const eventsRows: any[] = [];+ for await (const chunk of await getObservationStream({+ ...streamParams,+ useEventsTable: true,+ })) {+ eventsRows.push(chunk);+ }+ expect(eventsRows).toHaveLength(1);+ expect(eventsRows[0].id).toBe(event.span_id);++ const legacyRows: any[] = [];+ for await (const chunk of await getObservationStream(streamParams)) {+ legacyRows.push(chunk);+ }+ expect(legacyRows).toHaveLength(1);+ expect(legacyRows[0].id).toBe(legacyObservation.id);++ // Schema parity: both read paths must emit exactly the same columns in+ // the same order, since CSV headers are derived from the first row's+ // keys in insertion order. No .sort() here — order is part of the+ // contract.+ expect(Object.keys(eventsRows[0])).toEqual(Object.keys(legacyRows[0]));+ });++ it("should produce byte-identical CSV headers across legacy and events read paths", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ await createObservationsCh([+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "GENERATION",+ }),+ ]);+ await createEventsCh([+ createEvent({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "GENERATION",+ start_time: Date.now() * 1000,+ }),+ ]);++ // End-to-end through the same CSV transform handleBatchExportJob uses:+ // the header line is built from the first row's key order, and export+ // consumers pin columns by index, so the two read paths must produce+ // byte-identical header lines.+ const readCsvHeader = async (useEventsTable: boolean) => {+ const stream = await getObservationStream({+ projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [],+ fileFormat: BatchExportFileFormat.CSV,+ useEventsTable,+ });+ const csvStream = stream.pipe(+ streamTransformations[BatchExportFileFormat.CSV](),+ );+ let csv = "";+ for await (const chunk of csvStream) {+ csv += chunk.toString();+ }+ return csv.split("\n")[0];+ };++ const legacyHeader = await readCsvHeader(false);+ const eventsHeader = await readCsvHeader(true);++ expect(eventsHeader).toBe(legacyHeader);+ });+it("routes events exports through getEventsStream, not the paginated reader", async () => {// Path A contract: the events-table export is served by getEventsStream// (wired in handleBatchExportJob). The paginated reader intentionally hasdiff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex d15aa693fe..14e092a4bb 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -44,7 +44,7 @@ const EVENT_SEARCH_COLUMNS = ["trace_id",] as const;-const eventSearchCondition = (opts: {+export const eventSearchCondition = (opts: {query?: string;searchType?: TracingSearchType[];}) =>diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.tsindex f15a6f7c1a..03833f1823 100644--- a/worker/src/features/database-read-stream/observation-stream.ts+++ b/worker/src/features/database-read-stream/observation-stream.ts@@ -5,20 +5,26 @@ import {TimeFilter,TracingSearchType,observationsTableCols,+ eventsTableCols,} from "@langfuse/shared";import {getDistinctScoreNames,queryClickhouseStream,ObservationRecordReadType,+ EventsObservationRecordReadType,StringFilter,FilterList,createFilterFromFilterState,observationsTableUiColumnDefinitions,+ eventsTableUiColumnDefinitions,enrichObservationWithModelData,createModelCache,clickhouseSearchCondition,convertObservation,+ convertEventsObservation,shouldSkipObservationsFinal,+ EventsQueryBuilder,+ eventsScoresAggregation,} from "@langfuse/shared/src/server";import { Readable } from "stream";import { env } from "../../env";@@ -27,11 +33,12 @@ import {prepareScoresForOutput,} from "./getDatabaseReadStream";import { fetchCommentsForExport } from "./fetchCommentsForExport";+import { eventSearchCondition } from "./event-stream";const DEFAULT_BATCH_SIZE = 1000;const REDUCED_BATCH_SIZE = 200; // Smaller batch for JSON/JSONL which hold parsed objects in memory-export const getObservationStream = async (props: {+type ObservationStreamProps = {projectId: string;cutoffCreatedAt: Date;filter: FilterCondition[] | null;@@ -39,7 +46,19 @@ export const getObservationStream = async (props: {searchType?: TracingSearchType[];rowLimit?: number;fileFormat?: BatchExportFileFormat;-}): Promise<Readable> => {+ // Snapshotted at dispatch time from the user's v4 beta flag (see+ // BatchExportQuerySchema). When true, read from the ClickHouse events table+ // instead of the legacy observations/traces tables.+ useEventsTable?: boolean;+};++export const getObservationStream = async (+ props: ObservationStreamProps,+): Promise<Readable> => {+ if (props.useEventsTable) {+ return getObservationStreamFromEvents(props);+ }+const {projectId,cutoffCreatedAt,@@ -397,3 +416,279 @@ export const getObservationStream = async (props: {})(),);};++/**+ * Events-table variant of getObservationStream for v4 users (useEventsTable+ * snapshot). Queries the denormalized ClickHouse events table — no joins to+ * the legacy observations/traces tables — and maps rows to the same field+ * names as the legacy observation export so the export schema stays stable.+ * traceTimestamp is not carried by the events table and is exported as null,+ * matching getObservationsWithModelDataFromEventsTable.+ */+const getObservationStreamFromEvents = async (+ props: ObservationStreamProps,+): Promise<Readable> => {+ const {+ projectId,+ cutoffCreatedAt,+ filter = [],+ searchQuery,+ searchType,+ rowLimit = env.BATCH_EXPORT_ROW_LIMIT,+ } = props;++ const isCsv = props.fileFormat === BatchExportFileFormat.CSV;+ const batchSize = isCsv ? DEFAULT_BATCH_SIZE : REDUCED_BATCH_SIZE;++ const clickhouseConfigs = {+ request_timeout: 180_000, // 3 minutes+ clickhouse_settings: {+ join_algorithm: "partial_merge" as const,+ // Increase HTTP timeouts to prevent Code 209 errors during slow blob storage uploads+ // See: https://github.com/ClickHouse/ClickHouse/issues/64731+ http_send_timeout: 300,+ http_receive_timeout: 300,+ },+ };++ // Trace-level filters are kept: the events table carries trace fields+ // denormalized, so they apply directly. Observation-level score filters are+ // kept too — they map to the scores_agg CTE (s.*) joined below, matching the+ // legacy export. Dropped are trace-level score filters (they reference a+ // trace_scores_agg CTE this query does not join) and comment filters+ // (comments live in Postgres and are resolved before the stream via+ // applyCommentFilters).+ const exportableFilters = (filter ?? []).filter((f) => {+ const columnDef = eventsTableUiColumnDefinitions.find(+ (col) => col.uiTableName === f.column || col.uiTableId === f.column,+ );+ if (columnDef?.clickhouseTableName === "comments") return false;+ if (columnDef?.clickhouseTableName === "scores") {+ // Observation-level score columns select from the "s." alias,+ // trace-level ones from "ts.".+ return columnDef.clickhouseSelect.startsWith("s.");+ }+ return true;+ });++ const distinctScoreNames = await getDistinctScoreNames({+ projectId,+ cutoffCreatedAt,+ filter: exportableFilters,+ isTimestampFilter: (+ filterItem: FilterCondition,+ ): filterItem is TimeFilter =>+ filterItem.column === "Start Time" && filterItem.type === "datetime",+ clickhouseConfigs,+ });++ const emptyScoreColumns = distinctScoreNames.reduce(+ (acc, name) => ({ ...acc, [name]: null }),+ {} as Record<string, null>,+ );++ const eventsFilter = new FilterList(+ createFilterFromFilterState(+ [+ ...exportableFilters,+ {+ column: "startTime",+ operator: "<" as const,+ value: cutoffCreatedAt,+ type: "datetime" as const,+ },+ ],+ eventsTableUiColumnDefinitions,+ eventsTableCols,+ ),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const search = eventSearchCondition({+ query: searchQuery,+ searchType,+ });++ const eventsQuery = new EventsQueryBuilder({ projectId })+ .selectFieldSet("base")+ .selectIO(false) // Full I/O, no truncation+ .selectMetadataExpanded() // Full metadata values from events_full+ .selectRaw(+ "s.scores_avg as scores_avg",+ "s.score_categories as score_categories",+ "s.score_categories_tuples as score_categories_tuples",+ )+ .withCTE(+ "scores_agg",+ eventsScoresAggregation({ projectId, includeTupleEncoding: true }),+ )+ .leftJoin(+ "scores_agg s",+ "ON s.trace_id = e.trace_id AND s.observation_id = e.span_id",+ )+ .when(search.requiresEventsFull, (b) => b.forceFullTable())+ .where(appliedEventsFilter)+ .where(search)+ .whereRaw("e.is_deleted = 0")+ .orderByDefault()+ .limitBy("e.span_id", "e.project_id")+ .limit(rowLimit);++ const { query, params: queryParams } = eventsQuery.buildWithParams();++ type EventsObservationRow = EventsObservationRecordReadType & {+ scores_avg:+ | {+ name: string;+ value: number;+ dataType: ScoreDataTypeType;+ stringValue: string;+ }[]+ | undefined;+ score_categories: string[] | undefined;+ score_categories_tuples: [string, string | null, string][] | undefined;+ };++ const asyncGenerator = queryClickhouseStream<EventsObservationRow>({+ query,+ params: queryParams,+ clickhouseConfigs,+ tags: {+ feature: "batch-export",+ type: "observation",+ kind: "export",+ projectId,+ },+ preferredClickhouseService: "EventsReadOnly",+ });++ const modelCache = createModelCache(projectId);++ const processEventsObservationRow = async (+ bufferedRow: EventsObservationRow,+ commentsByObservation: Map<string, any[]>,+ ) => {+ const converted = convertEventsObservation(+ bufferedRow,+ {+ truncated: false,+ shouldJsonParse: props.fileFormat !== BatchExportFileFormat.CSV,+ },+ true,+ );++ // Fetch model pricing from cache (or database if not cached)+ const model = await modelCache.getModel(converted.internalModelId);+ const modelData = enrichObservationWithModelData(model);++ // Process numeric/boolean scores (tuples from ClickHouse)+ const numericScores = (bufferedRow.scores_avg ?? []).map((score: any) => ({+ name: score[0],+ value: score[1],+ dataType: score[2],+ stringValue: score[3],+ }));++ // Process categorical scores (tuples from ClickHouse)+ const categoricalScores = (bufferedRow.score_categories_tuples ?? []).map(+ (cat) => ({+ name: cat[0],+ value: null,+ dataType: cat[2],+ stringValue: cat[1],+ }),+ );++ const outputScores: Record<string, string[] | number[]> =+ prepareScoresForOutput([...numericScores, ...categoricalScores]);++ const observationComments = commentsByObservation.get(bufferedRow.id) ?? [];++ // Drop events-only fields so the exported row matches the legacy export+ // schema exactly: CSV headers are derived from the first row's keys in+ // insertion order, so both the column set and the column order must match+ // the legacy path. userId and traceName are destructured out here and+ // re-inserted below at their legacy positions; raw trace tags are exported+ // as traceTags instead, matching the legacy row shape.+ const {+ tags: _tags,+ sessionId: _sessionId,+ release: _release,+ bookmarked: _bookmarked,+ public: _public,+ userId,+ traceName,+ ...observationFields+ } = converted;++ return getChunkWithFlattenedScores(+ [+ {+ ...observationFields,+ traceName,+ traceTags: converted.tags ?? [],+ traceTimestamp: null,+ userId,+ toolDefinitionsCount: converted.toolDefinitions+ ? Object.keys(converted.toolDefinitions).length+ : null,+ toolCallsCount: converted.toolCalls+ ? converted.toolCalls.length+ : null,+ ...modelData,+ scores: outputScores,+ comments: observationComments,+ },+ ],+ emptyScoreColumns,+ )[0];+ };++ return Readable.from(+ (async function* () {+ let rowBuffer: EventsObservationRow[] = [];+ let observationIds: string[] = [];++ for await (const row of asyncGenerator) {+ rowBuffer.push(row);+ observationIds.push(row.id);++ // Process in batches+ if (rowBuffer.length >= batchSize) {+ const commentsByObservation = await fetchCommentsForExport(+ projectId,+ "OBSERVATION",+ observationIds,+ );++ for (const bufferedRow of rowBuffer) {+ yield await processEventsObservationRow(+ bufferedRow,+ commentsByObservation,+ );+ }++ rowBuffer = [];+ observationIds = [];+ }+ }++ // Process remaining rows in buffer+ if (rowBuffer.length > 0) {+ const commentsByObservation = await fetchCommentsForExport(+ projectId,+ "OBSERVATION",+ observationIds,+ );++ for (const bufferedRow of rowBuffer) {+ yield await processEventsObservationRow(+ bufferedRow,+ commentsByObservation,+ );+ }+ }+ })(),+ );+};