🪢 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: introducing events repository that can serve observations UI table (#9651)
Valery Meleshkin37dc8c83e01b
diff --git a/.env.dev.example b/.env.dev.exampleindex 01503dcad4..350348fdc6 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -101,3 +101,6 @@ AWS_ACCESS_KEY_ID="A123456789"AWS_SECRET_ACCESS_KEY="SAK123456789"LANGFUSE_AWS_BEDROCK_REGION="eu-west-1"LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-3-haiku-20240307-v1:0"++# Events table migration+LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS=truediff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 1d9f392892..de245563e3 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -266,6 +266,20 @@ jobs:run: |pnpm run db:migratepnpm --filter=shared ch:up+ - name: Download and extract ClickHouse client for dev-tables setup+ if: matrix.deploy-mode == ''+ run: |+ CH_VERSION="24.9.3.128"+ ARCH="amd64"+ wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CH_VERSION}_${ARCH}.deb" -O clickhouse-client.deb++ # The binary is usually located in ./usr/bin/clickhouse in the archive+ dpkg-deb -x clickhouse-client.deb ch_client_dir+ sudo cp ch_client_dir/usr/bin/clickhouse /usr/local/bin/+ - name: Setup Dev Tables+ if: matrix.deploy-mode == ''+ run: |+ pnpm --filter=shared ch:dev-tables- name: Buildrun: pnpm run buildenv:diff --git a/packages/shared/src/server/clickhouse/schema.ts b/packages/shared/src/server/clickhouse/schema.tsindex f0205c3e65..576c2d7c2f 100644--- a/packages/shared/src/server/clickhouse/schema.ts+++ b/packages/shared/src/server/clickhouse/schema.ts@@ -2,6 +2,7 @@ export const ClickhouseTableNames = {traces: "traces",observations: "observations",scores: "scores",+ events: "events",dataset_run_items_rmt: "dataset_run_items_rmt",// Virtual tables for dashboardsdiff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.tsnew file mode 100644index 0000000000..d1d1a078b6--- /dev/null+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts@@ -0,0 +1,54 @@+/**+ * Reusable ClickHouse query fragments and CTEs+ */++import { OBSERVATIONS_TO_TRACE_INTERVAL } from "../../repositories";++interface EventsTracesAggregationParams {+ projectId: string;+ traceIds?: string[];+ startTimeFrom?: string | null;+}++/**+ * Rebuilds traces from events table by aggregating events with the same trace_id.+ * Groups events by trace_id and project_id, selecting representative fields+ * and aggregating timestamps.+ *+ * Note: This is a temporary solution until we fully migrate to using only the events table.+ * Some legacy fields are still included for compatibility and should be removed in the future.+ *+ * Parameters are not injected directly, but used to conditionally include parts of the query.+ * They still need to be passed to the query execution function.+ */+export const eventsTracesAggregation = (+ params: EventsTracesAggregationParams,+) => {+ return `+ SELECT+ trace_id AS id,+ project_id,+ any(name) AS name,+ min(start_time) as timestamp,+ any(environment) AS environment,+ any(version) AS version,+ any(session_id) AS session_id,+ any(user_id) AS user_id,+ any(input) AS input,+ any(output) AS output,+ any(metadata) AS metadata,+ min(created_at) AS created_at,+ max(updated_at) AS updated_at,+ -- TODO remove legacy fields+ array() AS tags,+ false AS bookmarked,+ false AS public,+ '' AS release+ FROM events+ WHERE project_id = {projectId: String}+ ${params.traceIds ? `AND trace_id IN ({traceIds: Array(String)})` : ""}+ ${params.startTimeFrom ? `AND start_time >= {startTimeFrom: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}+ GROUP BY trace_id, project_id+ ORDER BY timestamp DESC+ `.trim();+};diff --git a/packages/shared/src/server/queries/createGenerationsQuery.ts b/packages/shared/src/server/queries/createGenerationsQuery.tsindex 45acc61593..8f56c47a10 100644--- a/packages/shared/src/server/queries/createGenerationsQuery.ts+++ b/packages/shared/src/server/queries/createGenerationsQuery.ts@@ -1,10 +1,17 @@+import Decimal from "decimal.js";import { Observation } from "../../domain";+export type ObservationPriceFields = {+ inputPrice: Decimal | null;+ outputPrice: Decimal | null;+ totalPrice: Decimal | null;+};+type AdditionalObservationFields = {traceName: string | null;traceTags: Array<string>;traceTimestamp: Date | null;-};+} & ObservationPriceFields;export type FullObservation = AdditionalObservationFields & Observation;diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex e90285bda9..2b4f1adb64 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -1,6 +1,7 @@export {type FullObservations,type FullObservationsWithScores,+ type ObservationPriceFields,} from "./createGenerationsQuery";export {FilterList,diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsnew file mode 100644index 0000000000..bda17c765b--- /dev/null+++ b/packages/shared/src/server/repositories/events.ts@@ -0,0 +1,480 @@+import { prisma } from "../../db";+import { ObservationType } from "../../domain";+import { env } from "../../env";+import { InternalServerError, LangfuseNotFoundError } from "../../errors";+import {+ convertDateToClickhouseDateTime,+ PreferredClickhouseService,+} from "../clickhouse/client";+import { measureAndReturn } from "../clickhouse/measureAndReturn";+import { recordDistribution } from "../instrumentation";+import { logger } from "../logger";+import {+ DateTimeFilter,+ FilterList,+ FullObservations,+ orderByToClickhouseSql,+ StringFilter,+} from "../queries";+import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";+import { eventsTracesAggregation } from "../queries/clickhouse-sql/query-fragments";+import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";+import {+ eventsTableLegacyTraceUiColumnDefinitions,+ eventsTableUiColumnDefinitions,+} from "../tableMappings/mapEventsTable";+import { DEFAULT_RENDERING_PROPS, RenderingProps } from "../utils/rendering";+import { queryClickhouse } from "./clickhouse";+import { ObservationRecordReadType } from "./definitions";+import {+ ObservationsTableQueryResult,+ ObservationTableQuery,+} from "./observations";+import { convertObservation } from "./observations_converters";++export const getObservationsCountFromEventsTable = async (+ opts: ObservationTableQuery,+) => {+ const count = await getObservationsFromEventsTableInternal<{+ count: string;+ }>({+ ...opts,+ select: "count",+ tags: { kind: "count" },+ });++ return Number(count[0].count);+};++export const getObservationsWithModelDataFromEventsTable = async (+ opts: ObservationTableQuery,+): Promise<FullObservations> => {+ const observationRecords = await getObservationsFromEventsTableInternal<+ Omit<+ ObservationsTableQueryResult,+ "trace_tags" | "trace_name" | "trace_user_id"+ >+ >({+ ...opts,+ select: "rows",+ tags: { kind: "list" },+ });++ const uniqueModels: string[] = Array.from(+ new Set(+ observationRecords+ .map((r) => r.internal_model_id)+ .filter((r): r is string => Boolean(r)),+ ),+ );++ const models =+ uniqueModels.length > 0+ ? await prisma.model.findMany({+ where: {+ id: {+ in: uniqueModels,+ },+ OR: [{ projectId: opts.projectId }, { projectId: null }],+ },+ include: {+ Price: true,+ },+ })+ : [];++ return observationRecords.map((o) => {+ const model = models.find((m) => m.id === o.internal_model_id);+ return {+ ...convertObservation(o),+ latency: o.latency ? Number(o.latency) / 1000 : null,+ timeToFirstToken: o.time_to_first_token+ ? Number(o.time_to_first_token) / 1000+ : null,+ traceName: o.name ?? null,+ traceTags: [], // TODO pull from PG+ traceTimestamp: null,+ modelId: model?.id ?? null,+ inputPrice:+ model?.Price?.find((m) => m.usageType === "input")?.price ?? null,+ outputPrice:+ model?.Price?.find((m) => m.usageType === "output")?.price ?? null,+ totalPrice:+ model?.Price?.find((m) => m.usageType === "total")?.price ?? null,+ };+ });+};++const getObservationsFromEventsTableInternal = async <T>(+ opts: ObservationTableQuery & {+ select: "count" | "rows";+ tags: Record<string, string>;+ },+): Promise<Array<T>> => {+ const select =+ opts.select === "count"+ ? "count(*) as count"+ : `+ e.span_id as id,+ e.type as type,+ e.project_id as "project_id",+ e.name as name,+ e."model_parameters" as model_parameters,+ e.start_time as "start_time",+ e.end_time as "end_time",+ e.trace_id as "trace_id",+ e.completion_start_time as "completion_start_time",+ e.provided_usage_details as "provided_usage_details",+ e.usage_details as "usage_details",+ e.provided_cost_details as "provided_cost_details",+ e.cost_details as "cost_details",+ e.level as level,+ e.environment as "environment",+ e.status_message as "status_message",+ e.version as version,+ e.parent_span_id as "parent_observation_id",+ e.created_at as "created_at",+ e.updated_at as "updated_at",+ e.provided_model_name as "provided_model_name",+ e.total_cost as "total_cost",+ e.prompt_id as "prompt_id",+ e.prompt_name as "prompt_name",+ e.prompt_version as "prompt_version",+ e.model_id as "internal_model_id",+ if(isNull(end_time), NULL, date_diff('millisecond', start_time, end_time)) as latency,+ if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time)) as "time_to_first_token"`;++ const {+ projectId,+ filter,+ selectIOAndMetadata,+ limit,+ offset,+ orderBy,+ clickhouseConfigs,+ } = opts;++ const selectString = selectIOAndMetadata+ ? `${select}, e.input, e.output, e.metadata`+ : select;++ const timeFilter = filter.find(+ (f) =>+ (f.column === "Start Time" || f.column === "startTime") &&+ (f.operator === ">=" || f.operator === ">"),+ );++ const scoresFilter = new FilterList([+ new StringFilter({+ clickhouseTable: "scores",+ field: "project_id",+ operator: "=",+ value: projectId,+ }),+ ]);++ const hasScoresFilter = filter.some((f) =>+ f.column.toLowerCase().includes("scores"),+ );++ const orderByTraces = orderBy+ ? eventsTableLegacyTraceUiColumnDefinitions.some(+ (c) =>+ c.uiTableId === orderBy.column || c.uiTableName === orderBy.column,+ )+ : undefined;++ timeFilter+ ? scoresFilter.push(+ new DateTimeFilter({+ clickhouseTable: "scores",+ field: "timestamp",+ operator: ">=",+ value: timeFilter.value as Date,+ }),+ )+ : undefined;++ const observationsFilter = new FilterList([+ new StringFilter({+ clickhouseTable: "events",+ field: "project_id",+ operator: "=",+ value: projectId,+ tablePrefix: "e",+ }),+ ]);++ observationsFilter.push(+ ...createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),+ );++ const appliedScoresFilter = scoresFilter.apply();+ const appliedObservationsFilter = observationsFilter.apply();++ const search = clickhouseSearchCondition(+ opts.searchQuery,+ opts.searchType,+ "e",+ );++ const scoresCte = `WITH scores_agg AS (+ SELECT+ trace_id,+ observation_id,+ -- For numeric scores, use tuples of (name, avg_value)+ groupArrayIf(+ tuple(name, avg_value),+ data_type IN ('NUMERIC', 'BOOLEAN')+ ) AS scores_avg,+ -- For categorical scores, use name:value format for improved query performance+ groupArrayIf(+ concat(name, ':', string_value),+ data_type = 'CATEGORICAL' AND notEmpty(string_value)+ ) AS score_categories+ FROM (+ SELECT+ trace_id,+ observation_id,+ name,+ avg(value) avg_value,+ string_value,+ data_type,+ comment+ FROM+ scores FINAL+ WHERE ${appliedScoresFilter.query}+ GROUP BY+ trace_id,+ observation_id,+ name,+ string_value,+ data_type,+ comment+ ORDER BY+ trace_id+ ) tmp+ GROUP BY+ trace_id,+ observation_id+ )`;++ // Query optimisation: joining traces onto observations is expensive.+ // Hence, only join if the UI table contains filters on traces.+ // Joins with traces are very expensive. We need to filter by time as well.+ // We assume that a trace has to have been within the last 2 days to be relevant.+ const traceTableFilter = filter.filter((f) =>+ eventsTableLegacyTraceUiColumnDefinitions.some(+ (c) => c.uiTableId === f.column || c.uiTableName === f.column,+ ),+ );++ const startTimeFrom = timeFilter+ ? convertDateToClickhouseDateTime(timeFilter.value as Date)+ : null;++ const tracesCte = `traces AS (${eventsTracesAggregation({+ projectId,+ startTimeFrom,+ })})`;++ // When we have default ordering by time, we order by toUnixTimestamp(o.start_time)+ // This way, clickhouse is able to read more efficiently directly from disk without ordering+ const newDefaultOrder =+ orderBy?.column === "startTime"+ ? [{ column: "order_by_unix", order: orderBy.order }]+ : [orderBy ?? null];++ const chOrderBy = orderByToClickhouseSql(newDefaultOrder, [+ ...eventsTableUiColumnDefinitions,+ {+ uiTableName: "order_by_unix",+ uiTableId: "order_by_unix",+ clickhouseTableName: "events",+ clickhouseSelect: "toUnixTimestamp(e.start_time)",+ },+ ]);++ const query = `+ ${scoresCte},+ ${tracesCte}+ SELECT+ ${selectString}+ FROM events e+ ${+ traceTableFilter.length > 0 || orderByTraces || search.query+ ? "LEFT JOIN traces t ON t.id = e.trace_id AND t.project_id = e.project_id"+ : ""+ }+ ${hasScoresFilter ? `LEFT JOIN scores_agg AS s ON s.trace_id = e.trace_id and s.observation_id = e.span_id` : ""}+ WHERE ${appliedObservationsFilter.query}+ ${search.query}+ ${chOrderBy}+ ${limit !== undefined && offset !== undefined ? `LIMIT ${limit} OFFSET ${offset}` : "LIMIT 1000"};`;++ return measureAndReturn({+ operationName: "getObservationsFromEventsTableInternal",+ projectId,+ input: {+ params: {+ projectId,+ startTimeFrom,+ ...appliedScoresFilter.params,+ ...appliedObservationsFilter.params,+ ...search.params,+ },+ tags: {+ ...(opts.tags ?? {}),+ feature: "tracing",+ type: "events",+ projectId,+ kind: opts.select,+ operation_name: "getObservationsTableInternal",+ },+ },+ fn: async (input) => {+ return queryClickhouse<T>({+ query,+ params: input.params,+ tags: input.tags,+ clickhouseConfigs,+ });+ },+ });+};++export const getObservationByIdFromEventsTable = async ({+ id,+ projectId,+ fetchWithInputOutput = false,+ startTime,+ type,+ traceId,+ renderingProps = DEFAULT_RENDERING_PROPS,+ preferredClickhouseService,+}: {+ id: string;+ projectId: string;+ fetchWithInputOutput?: boolean;+ startTime?: Date;+ type?: ObservationType;+ traceId?: string;+ renderingProps?: RenderingProps;+ preferredClickhouseService?: PreferredClickhouseService;+}) => {+ const records = await getObservationByIdFromEventsTableInternal({+ id,+ projectId,+ fetchWithInputOutput,+ startTime,+ type,+ traceId,+ renderingProps,+ preferredClickhouseService,+ });+ const mapped = records.map((record) =>+ convertObservation(record, renderingProps),+ );++ mapped.forEach((observation) => {+ recordDistribution(+ "langfuse.query_by_id_age",+ new Date().getTime() - observation.startTime.getTime(),+ {+ table: "events",+ },+ );+ });+ if (mapped.length === 0) {+ throw new LangfuseNotFoundError(`Observation with id ${id} not found`);+ }++ if (mapped.length > 1) {+ logger.error(+ `Multiple observations found for id ${id} and project ${projectId}`,+ );+ throw new InternalServerError(+ `Multiple observations found for id ${id} and project ${projectId}`,+ );+ }+ return mapped.shift();+};++const getObservationByIdFromEventsTableInternal = async ({+ id,+ projectId,+ fetchWithInputOutput = false,+ startTime,+ type,+ traceId,+ renderingProps = DEFAULT_RENDERING_PROPS,+ preferredClickhouseService,+}: {+ id: string;+ projectId: string;+ fetchWithInputOutput?: boolean;+ startTime?: Date;+ type?: ObservationType;+ traceId?: string;+ renderingProps?: RenderingProps;+ preferredClickhouseService?: PreferredClickhouseService;+}) => {+ const query = `+ SELECT+ span_id as id,+ trace_id,+ project_id,+ environment,+ type,+ parent_span_id as parent_observation_id,+ start_time,+ end_time,+ name,+ metadata,+ level,+ status_message,+ version,+ ${fetchWithInputOutput ? (renderingProps.truncated ? `leftUTF8(input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input, leftUTF8(output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as output,` : "input, output,") : ""}+ provided_model_name,+ model_id as internal_model_id,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ total_cost,+ completion_start_time,+ prompt_id,+ prompt_name,+ prompt_version,+ created_at,+ updated_at,+ event_ts+ FROM events+ WHERE span_id = {id: String}+ AND project_id = {projectId: String}+ ${startTime ? `AND toDate(start_time) = toDate({startTime: DateTime64(3)})` : ""}+ ${type ? `AND type = {type: String}` : ""}+ ${traceId ? `AND trace_id = {traceId: String}` : ""}+ ORDER BY toUnixTimestamp(start_time) DESC, event_ts DESC+ LIMIT 1`;+ return await queryClickhouse<ObservationRecordReadType>({+ query,+ params: {+ id,+ projectId,+ ...(startTime+ ? { startTime: convertDateToClickhouseDateTime(startTime) }+ : {}),+ ...(type ? { type } : {}),+ ...(traceId ? { traceId } : {}),+ },+ tags: {+ feature: "tracing",+ type: "events",+ kind: "byId",+ projectId,+ },+ preferredClickhouseService,+ });+};diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex 2a24d57126..0012e4bbe2 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -1,6 +1,7 @@export * from "./scores";export * from "./traces";export * from "./observations";+export * from "./events";export * from "./types";export * from "./dashboards";export * from "./traces_converters";diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex a54a7bc48d..87a7e2836c 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -740,7 +740,7 @@ const getObservationsTableInternal = async <T>(data_type,commentFROM- scores final+ scores FINALWHERE ${appliedScoresFilter.query}GROUP BYtrace_id,diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.tsnew file mode 100644index 0000000000..25c1b434c5--- /dev/null+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts@@ -0,0 +1,233 @@+// This structure is maintained to relate the frontend table definitions with the clickhouse table definitions.+// The frontend only sends the column names to the backend. This needs to be changed in the future to send column IDs.++import { UiColumnMappings } from "../../tableDefinitions";++// TODO+// Leaving these here for temporary compatibility with legacy traces UI (this may require fixing search condition)+// user_id should be moved to the main list, and the rest removed.+export const eventsTableLegacyTraceUiColumnDefinitions: UiColumnMappings = [+ {+ uiTableName: "Trace Tags",+ uiTableId: "traceTags",+ clickhouseTableName: "traces",+ clickhouseSelect: "t.tags",+ },+ {+ uiTableName: "User ID",+ uiTableId: "userId",+ clickhouseTableName: "traces",+ clickhouseSelect: 't."user_id"',+ },+ {+ uiTableName: "Trace Name",+ uiTableId: "traceName",+ clickhouseTableName: "traces",+ clickhouseSelect: 't."name"',+ },+ {+ uiTableName: "Trace Environment",+ uiTableId: "traceEnvironment",+ clickhouseTableName: "traces",+ clickhouseSelect: 't."environment"',+ },+];++export const eventsTableUiColumnDefinitions: UiColumnMappings = [+ ...eventsTableLegacyTraceUiColumnDefinitions,+ {+ uiTableName: "Environment",+ uiTableId: "environment",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."environment"',+ },+ {+ uiTableName: "type",+ uiTableId: "type",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."type"',+ },+ {+ uiTableName: "ID",+ uiTableId: "id",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."span_id"',+ },+ {+ uiTableName: "Type",+ uiTableId: "type",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."type"',+ },+ {+ uiTableName: "Name",+ uiTableId: "name",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."name"',+ },+ {+ uiTableName: "Trace ID",+ uiTableId: "traceId",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."trace_id"',+ },++ {+ uiTableName: "Start Time",+ uiTableId: "startTime",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."start_time"',+ },+ {+ uiTableName: "End Time",+ uiTableId: "endTime",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."end_time"',+ },+ {+ uiTableName: "Time To First Token (s)",+ uiTableId: "timeToFirstToken",+ clickhouseTableName: "events",+ clickhouseSelect:+ "if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time) / 1000)",+ // If we use the default of Decimal64(12), we cannot filter for more than ~40min due to an overflow+ clickhouseTypeOverwrite: "Decimal64(3)",+ },+ {+ uiTableName: "Latency (s)",+ uiTableId: "latency",+ clickhouseTableName: "events",+ clickhouseSelect:+ "if(isNull(end_time), NULL, date_diff('millisecond', start_time, end_time) / 1000)",+ // If we use the default of Decimal64(12), we cannot filter for more than ~40min due to an overflow+ clickhouseTypeOverwrite: "Decimal64(3)",+ },+ {+ uiTableName: "Tokens per second",+ uiTableId: "tokensPerSecond",+ clickhouseTableName: "events",+ clickhouseSelect:+ "(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details))) / (date_diff('millisecond', start_time, end_time) / 1000))",+ },+ {+ uiTableName: "Input Cost ($)",+ uiTableId: "inputCost",+ clickhouseTableName: "events",+ clickhouseSelect:+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details)))",+ },+ {+ uiTableName: "Output Cost ($)",+ uiTableId: "outputCost",+ clickhouseTableName: "events",+ clickhouseSelect:+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details)))",+ },+ {+ uiTableName: "Total Cost ($)",+ uiTableId: "totalCost",+ clickhouseTableName: "events",+ clickhouseSelect:+ "if(mapExists((k, v) -> (k = 'total'), cost_details), cost_details['total'], NULL)",+ },+ {+ uiTableName: "Level",+ uiTableId: "level",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."level"',+ },+ {+ uiTableName: "Status Message",+ uiTableId: "statusMessage",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."status_message"',+ },+ {+ uiTableName: "Model",+ uiTableId: "model",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."provided_model_name"',+ },+ {+ uiTableName: "Model ID",+ uiTableId: "modelId",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."model_id"',+ },+ {+ uiTableName: "Input Tokens",+ uiTableId: "inputTokens",+ clickhouseTableName: "events",+ clickhouseSelect:+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))",+ clickhouseTypeOverwrite: "Decimal64(3)",+ },+ {+ uiTableName: "Output Tokens",+ uiTableId: "outputTokens",+ clickhouseTableName: "events",+ clickhouseSelect:+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))",+ clickhouseTypeOverwrite: "Decimal64(3)",+ },+ {+ uiTableName: "Total Tokens",+ uiTableId: "totalTokens",+ clickhouseTableName: "events",+ clickhouseSelect:+ "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",+ clickhouseTypeOverwrite: "Decimal64(3)",+ },+ {+ uiTableName: "Tokens",+ uiTableId: "tokens",+ clickhouseTableName: "events",+ clickhouseSelect:+ "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",+ clickhouseTypeOverwrite: "Decimal64(3)",+ },+ {+ uiTableName: "Metadata",+ uiTableId: "metadata",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."metadata"',+ },+ // Scores column duplicated to allow renaming column name. Will be removed once session storage cache is outdated+ // Column names are cached in user sessions - changing them breaks existing filters+ {+ uiTableName: "Scores",+ uiTableId: "scores",+ clickhouseTableName: "scores",+ clickhouseSelect: "s.scores_avg",+ },+ {+ uiTableName: "Scores (numeric)",+ uiTableId: "scores",+ clickhouseTableName: "scores",+ clickhouseSelect: "s.scores_avg",+ },+ {+ uiTableName: "Scores (categorical)",+ uiTableId: "scores",+ clickhouseTableName: "scores",+ clickhouseSelect: "s.score_categories",+ },+ {+ uiTableName: "Version",+ uiTableId: "version",+ clickhouseTableName: "events",+ clickhouseSelect: 'e."version"',+ },+ {+ uiTableName: "Prompt Name",+ uiTableId: "promptName",+ clickhouseTableName: "events",+ clickhouseSelect: "o.prompt_name",+ },+ {+ uiTableName: "Prompt Version",+ uiTableId: "promptVersion",+ clickhouseTableName: "events",+ clickhouseSelect: "o.prompt_version",+ },+];diff --git a/packages/shared/src/server/test-utils/clickhouse-helpers.ts b/packages/shared/src/server/test-utils/clickhouse-helpers.tsindex 709b01aa2c..0192dbd4ff 100644--- a/packages/shared/src/server/test-utils/clickhouse-helpers.ts+++ b/packages/shared/src/server/test-utils/clickhouse-helpers.ts@@ -4,6 +4,7 @@ import {ObservationRecordInsertType,ScoreRecordInsertType,DatasetRunItemRecordInsertType,+ EventRecordInsertType,} from "../repositories/definitions";export const createTracesCh = async (trace: TraceRecordInsertType[]) => {@@ -24,6 +25,14 @@ export const createObservationsCh = async (});};+export const createEventsCh = async (events: EventRecordInsertType[]) => {+ return await clickhouseClient().insert({+ table: "events",+ format: "JSONEachRow",+ values: events,+ });+};+export const createScoresCh = async (scores: ScoreRecordInsertType[]) => {return await clickhouseClient().insert({table: "scores",diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex 78d2d6a953..da8394bdf1 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -4,6 +4,7 @@ import {ObservationRecordInsertType,ScoreRecordInsertType,DatasetRunItemRecordInsertType,+ EventRecordInsertType,} from "../repositories/definitions";export const createTrace = (@@ -178,3 +179,89 @@ export const createDatasetRunScore = (session_id: null,};};++export const createEvent = (+ event: Partial<EventRecordInsertType>,+): EventRecordInsertType => {+ const spanId = v4();+ const now = Date.now() * 1000; // Convert to micro+ return {+ // Identifiers+ org_id: null,+ project_id: v4(),+ trace_id: v4(),+ span_id: spanId,+ id: spanId,+ parent_span_id: null,++ // Core properties+ name: "test-event" + v4(),+ type: "GENERATION",+ environment: "default",+ version: null,++ user_id: null,+ session_id: null,++ level: "DEFAULT",+ status_message: null,++ // Prompt+ prompt_id: null,+ prompt_name: null,+ prompt_version: null,++ // Model+ model_id: null,+ provided_model_name: "gpt-3.5-turbo",+ model_parameters: null,++ // Usage & Cost+ provided_usage_details: { input: 1234, output: 5678, total: 6912 },+ usage_details: { input: 1234, output: 5678, total: 6912 },+ provided_cost_details: { input: 100, output: 200, total: 300 },+ cost_details: { input: 100, output: 200, total: 300 },+ total_cost: 300,++ // I/O+ input: "Hello World",+ output: "Hello John",++ // Metadata+ metadata: { source: "API", server: "Node" },+ metadata_names: [],+ metadata_values: [],+ metadata_string_names: [],+ metadata_string_values: [],+ metadata_number_names: [],+ metadata_number_values: [],+ metadata_bool_names: [],+ metadata_bool_values: [],++ // Source metadata (Instrumentation)+ source: "API",+ service_name: null,+ service_version: null,+ scope_name: null,+ scope_version: null,+ telemetry_sdk_language: null,+ telemetry_sdk_name: null,+ telemetry_sdk_version: null,++ // Generic props+ blob_storage_file_path: "",+ event_raw: "{}",+ event_bytes: 2,+ is_deleted: 0,++ // Timestamps+ start_time: now,+ end_time: now,+ completion_start_time: null,+ created_at: now,+ updated_at: now,+ event_ts: now,++ ...event,+ };+};diff --git a/web/src/__tests__/async/observations-trpc.servertest.ts b/web/src/__tests__/async/observations-trpc.servertest.tsindex b7dae5ae11..103131702f 100644--- a/web/src/__tests__/async/observations-trpc.servertest.ts+++ b/web/src/__tests__/async/observations-trpc.servertest.ts@@ -32,6 +32,7 @@ describe("traces trpc", () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,projects: [{id: projectId,@@ -53,7 +54,7 @@ describe("traces trpc", () => {environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });describe("generations.all", () => {diff --git a/web/src/__tests__/async/repositories/event-repository.servertest.ts b/web/src/__tests__/async/repositories/event-repository.servertest.tsnew file mode 100644index 0000000000..587c58d16b--- /dev/null+++ b/web/src/__tests__/async/repositories/event-repository.servertest.ts@@ -0,0 +1,1102 @@+import {+ createEvent,+ createEventsCh,+ getObservationsWithModelDataFromEventsTable,+ getObservationsCountFromEventsTable,+ getObservationByIdFromEventsTable,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { randomUUID } from "crypto";+import { type FilterCondition } from "@langfuse/shared";+import { env } from "@/src/env.mjs";++const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++const maybe =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ ? describe+ : describe.skip;++function idFilter(id: string): FilterCondition {+ return {+ type: "string",+ column: "id",+ operator: "=",+ value: id,+ };+}++describe("Clickhouse Events Repository Test", () => {+ it("should kill redis connection", () => {+ // we need at least one test case to avoid hanging+ // redis connection when everything else is skipped.+ });++ maybe("getObservationsWithModelDataFromEventsTable", () => {+ it("should return observations with model data", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();+ const modelId = randomUUID();++ // Create a model with pricing+ await prisma.model.create({+ data: {+ id: modelId,+ projectId,+ modelName: `gpt-4-${modelId}`,+ matchPattern: `(?i)^(gpt-?4-${modelId})$`,+ startDate: new Date("2023-01-01"),+ unit: "TOKENS",+ Price: {+ create: [+ {+ usageType: "input",+ price: 0.03,+ },+ {+ usageType: "output",+ price: 0.06,+ },+ {+ usageType: "total",+ price: 0.09,+ },+ ],+ },+ },+ });++ const nowMicro = Date.now() * 1000;+ // Create event with model reference+ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: `test-generation-${generationId}`,+ input: "Hello world, this is a test input",+ output: "This is a test response output",+ model_id: modelId,+ provided_model_name: `gpt-4-${modelId}`,+ start_time: nowMicro,+ end_time: nowMicro + 2000000, // +2 seconds+ completion_start_time: nowMicro + 2000000, // +2 seconds+ });++ await createEventsCh([event]);++ // Query observations+ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [idFilter(generationId)],+ limit: 1000,+ offset: 0,+ selectIOAndMetadata: true,+ });++ expect(result).toBeDefined();+ expect(result.length).toBeGreaterThan(0);+ const observation = result.find((o) => o.id === generationId);+ expect(observation).toBeDefined();+ expect(observation?.id).toBe(generationId);+ expect(observation?.traceId).toBe(traceId);+ expect(observation?.name).toBe(`test-generation-${generationId}`);+ expect(observation?.type).toBe("GENERATION");+ expect(observation?.internalModelId).toBe(modelId);+ expect(Number(observation?.inputPrice)).toBeCloseTo(0.03, 5);+ expect(Number(observation?.outputPrice)).toBeCloseTo(0.06, 5);+ expect(Number(observation?.totalPrice)).toBeCloseTo(0.09, 5);+ expect(observation?.latency).toBeGreaterThan(0);+ expect(observation?.timeToFirstToken).toBeGreaterThan(0);++ // Cleanup+ await prisma.model.delete({ where: { id: modelId } });+ });++ it("should return observations without model data when model is not found", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();++ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "test-generation-no-model",+ input: "Test input",+ output: "Test output",+ model_id: null,+ provided_model_name: "unknown-model",+ });++ await createEventsCh([event]);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [idFilter(generationId)],+ limit: 1000,+ offset: 0,+ selectIOAndMetadata: true,+ });++ const observation = result.find((o) => o.id === generationId);+ expect(observation).toBeDefined();+ expect(observation?.id).toBe(generationId);+ expect(observation?.internalModelId).toBeNull();+ expect(observation?.inputPrice).toBeNull();+ expect(observation?.outputPrice).toBeNull();+ expect(observation?.totalPrice).toBeNull();+ });++ it("should respect limit and offset parameters", async () => {+ const traceId = randomUUID();+ const events = Array.from({ length: 5 }, (_, i) =>+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: `test-event-${i}`,+ start_time: Date.now() + i * 1000,+ }),+ );++ await createEventsCh(events);++ const result1 = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [],+ limit: 2,+ offset: 0,+ });++ const result2 = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [],+ limit: 2,+ offset: 2,+ });++ expect(result1.length).toBeLessThanOrEqual(2);+ expect(result2.length).toBeLessThanOrEqual(2);+ });++ it("should handle events without end_time (null latency)", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();++ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "no-end-time",+ end_time: null,+ });++ await createEventsCh([event]);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [idFilter(generationId)],+ limit: 1000,+ offset: 0,+ });++ const observation = result.find((o) => o.id === generationId);+ expect(observation).toBeDefined();+ expect(observation?.latency).toBeNull();+ });++ it("should handle events without completion_start_time (null ttft)", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();++ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "no-completion-start",+ completion_start_time: null,+ });++ await createEventsCh([event]);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [idFilter(generationId)],+ limit: 1000,+ offset: 0,+ });++ const observation = result.find((o) => o.id === generationId);+ expect(observation).toBeDefined();+ expect(observation?.timeToFirstToken).toBeNull();+ });++ it("should respect selectIOAndMetadata parameter", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();++ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "io-metadata-test",+ input: "Test input content",+ output: "Test output content",+ metadata: { key: "value" },+ });++ await createEventsCh([event]);++ const resultWithIO = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [idFilter(generationId)],+ limit: 1000,+ offset: 0,+ selectIOAndMetadata: true,+ });++ const resultWithoutIO = await getObservationsWithModelDataFromEventsTable(+ {+ projectId,+ filter: [idFilter(generationId)],+ limit: 1000,+ offset: 0,+ selectIOAndMetadata: false,+ },+ );++ expect(resultWithIO.length).toBeGreaterThanOrEqual(1);+ expect(resultWithoutIO.length).toBeGreaterThanOrEqual(1);+ expect(resultWithIO[0]?.input).toBeDefined();+ expect(resultWithoutIO[0]?.output).toBeDefined();+ });+ });++ maybe("getObservationsCountFromEventsTable", () => {+ it("should return 0 for non-existent project", async () => {+ const nonExistentProjectId = randomUUID();++ const count = await getObservationsCountFromEventsTable({+ projectId: nonExistentProjectId,+ filter: [],+ });++ expect(count).toBe(0);+ });++ it("should match the length of observations returned by getObservationsWithModelDataFromEventsTable", async () => {+ const uniqueProjectId = randomUUID();+ const uniqueTraceId = randomUUID();+ const events = Array.from({ length: 5 }, (_, i) =>+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: uniqueTraceId,+ type: "GENERATION",+ name: `matching-count-test-${i}`,+ }),+ );++ await createEventsCh(events);++ // Use the unique project ID to isolate our test data (no filters needed)+ const observations = await getObservationsWithModelDataFromEventsTable({+ projectId: uniqueProjectId,+ filter: [],+ limit: 100,+ offset: 0,+ });++ const count = await getObservationsCountFromEventsTable({+ projectId: uniqueProjectId,+ filter: [],+ });++ expect(count).toBe(5);+ expect(observations.length).toBe(5);+ });+ });++ maybe("Filter Tests", () => {+ describe("Timestamp Filters", () => {+ it("should filter observations by start time with >= operator", async () => {+ const traceId = randomUUID();+ const now = Date.now();+ const filterTime = new Date(now - 5000);++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "old-event-gte",+ start_time: (now - 10000) * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "exact-event-gte",+ start_time: filterTime.getTime() * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "new-event-gte",+ start_time: now * 1000,+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "datetime",+ column: "startTime",+ operator: ">=",+ value: filterTime,+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter(+ (o) => o.traceId === traceId,+ );+ expect(filteredObservations.length).toBe(2);+ const names = filteredObservations.map((o) => o.name).sort();+ expect(names).toEqual(["exact-event-gte", "new-event-gte"]);+ });++ it("should filter observations by start time with <= operator", async () => {+ const traceId = randomUUID();+ const now = Date.now();+ const filterTime = new Date(now - 5000);++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "old-event-lte",+ start_time: (now - 10000) * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "exact-event-lte",+ start_time: filterTime.getTime() * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "new-event-lte",+ start_time: now * 1000,+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "datetime",+ column: "startTime",+ operator: "<=",+ value: filterTime,+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter(+ (o) => o.traceId === traceId,+ );+ expect(filteredObservations.length).toBe(2);+ const names = filteredObservations.map((o) => o.name).sort();+ expect(names).toEqual(["exact-event-lte", "old-event-lte"]);+ });++ it("should filter observations by end time", async () => {+ const traceId = randomUUID();+ const now = Date.now();+ const filterTime = new Date(now - 2000);++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "event-no-end",+ start_time: (now - 10000) * 1000,+ end_time: null,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "event-old-end",+ start_time: (now - 10000) * 1000,+ end_time: (now - 5000) * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "event-recent-end",+ start_time: (now - 5000) * 1000,+ end_time: now * 1000,+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "datetime",+ column: "endTime",+ operator: ">",+ value: filterTime,+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter(+ (o) => o.traceId === traceId,+ );+ expect(filteredObservations.length).toBe(1);+ expect(filteredObservations[0].name).toBe("event-recent-end");+ });+ });++ describe("Trace ID Filters", () => {+ it("should filter observations by multiple trace IDs with 'any of' operator", async () => {+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();+ const traceId3 = randomUUID();++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId1,+ type: "SPAN",+ name: "trace-1-event",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId2,+ type: "SPAN",+ name: "trace-2-event",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId3,+ type: "SPAN",+ name: "trace-3-event",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "stringOptions",+ column: "traceId",+ operator: "any of",+ value: [traceId1, traceId2],+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter((o) =>+ [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),+ );+ expect(filteredObservations.length).toBe(2);+ const traceIds = filteredObservations.map((o) => o.traceId).sort();+ expect(traceIds).toEqual([traceId1, traceId2].sort());+ });+ });++ describe("User ID Filters", () => {+ it("should filter observations by single user ID with stringOptions", async () => {+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();+ const userId1 = "user-123";+ const userId2 = "user-456";++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId1,+ user_id: userId1,+ type: "SPAN",+ name: "user-1-event",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId2,+ user_id: userId2,+ type: "SPAN",+ name: "user-2-event",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "stringOptions",+ column: "userId",+ operator: "any of",+ value: [userId1],+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter(+ (o) => o.traceId === traceId1 || o.traceId === traceId2,+ );+ expect(filteredObservations.length).toBe(1);+ expect(filteredObservations[0].name).toBe("user-1-event");+ });++ it("should filter observations by multiple user IDs with 'any of' operator", async () => {+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();+ const traceId3 = randomUUID();+ const userId1 = "user-alpha";+ const userId2 = "user-beta";+ const userId3 = "user-gamma";++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId1,+ user_id: userId1,+ type: "SPAN",+ name: "user-alpha-event",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId2,+ user_id: userId2,+ type: "SPAN",+ name: "user-beta-event",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId3,+ user_id: userId3,+ type: "SPAN",+ name: "user-gamma-event",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "stringOptions",+ column: "userId",+ operator: "any of",+ value: [userId1, userId2],+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter((o) =>+ [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),+ );+ expect(filteredObservations.length).toBe(2);+ const names = filteredObservations.map((o) => o.name).sort();+ expect(names).toEqual(["user-alpha-event", "user-beta-event"]);+ });++ it("should filter observations by user ID with 'none of' operator", async () => {+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();+ const traceId3 = randomUUID();+ const userId1 = "user-exclude-1";+ const userId2 = "user-exclude-2";+ const userId3 = "user-include";++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId1,+ user_id: userId1,+ type: "SPAN",+ name: "excluded-1",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId2,+ user_id: userId2,+ type: "SPAN",+ name: "excluded-2",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId3,+ user_id: userId3,+ type: "SPAN",+ name: "included",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "stringOptions",+ column: "userId",+ operator: "none of",+ value: [userId1, userId2],+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter((o) =>+ [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),+ );+ expect(filteredObservations.length).toBe(1);+ expect(filteredObservations[0].name).toBe("included");+ });++ it("should handle observations with null user IDs", async () => {+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();+ const userId = "user-with-id";++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId1,+ user_id: userId,+ type: "SPAN",+ name: "event-with-user",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId2,+ user_id: null,+ type: "SPAN",+ name: "event-without-user",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "stringOptions",+ column: "userId",+ operator: "any of",+ value: [userId],+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter(+ (o) => o.traceId === traceId1 || o.traceId === traceId2,+ );+ expect(filteredObservations.length).toBe(1);+ expect(filteredObservations[0].name).toBe("event-with-user");+ });+ });++ describe("Combined Filters", () => {+ it("should filter observations by timestamp AND user ID", async () => {+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();+ const traceId3 = randomUUID();+ const userId1 = "combined-user-1";+ const userId2 = "combined-user-2";+ const now = Date.now();+ const filterTime = new Date(now - 5000);++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId1,+ user_id: userId1,+ type: "SPAN",+ name: "old-user-1",+ start_time: (now - 10000) * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId2,+ user_id: userId1,+ type: "SPAN",+ name: "new-user-1",+ start_time: now * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId3,+ user_id: userId2,+ type: "SPAN",+ name: "new-user-2",+ start_time: now * 1000,+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsWithModelDataFromEventsTable({+ projectId,+ filter: [+ {+ type: "datetime",+ column: "startTime",+ operator: ">",+ value: filterTime,+ },+ {+ type: "stringOptions",+ column: "userId",+ operator: "any of",+ value: [userId1],+ },+ ],+ limit: 1000,+ offset: 0,+ });++ const filteredObservations = result.filter((o) =>+ [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),+ );+ expect(filteredObservations.length).toBe(1);+ expect(filteredObservations[0].name).toBe("new-user-1");+ });+ });+ });++ maybe("getObservationByIdFromEventsTable", () => {+ it("should return observation by id with input and output", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();++ const nowMicro = Date.now() * 1000;+ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "test-generation-byid",+ input: "Test input for byId",+ output: "Test output for byId",+ provided_model_name: "gpt-4",+ start_time: nowMicro,+ end_time: nowMicro + 1000000,+ });++ await createEventsCh([event]);++ const observation = await getObservationByIdFromEventsTable({+ id: generationId,+ projectId,+ fetchWithInputOutput: true,+ });++ expect(observation).toBeDefined();+ expect(observation?.id).toBe(generationId);+ expect(observation?.traceId).toBe(traceId);+ expect(observation?.name).toBe("test-generation-byid");+ expect(observation?.type).toBe("GENERATION");+ expect(observation?.input).toBeDefined();+ expect(observation?.output).toBeDefined();+ });++ it("should return observation by id without input and output", async () => {+ const traceId = randomUUID();+ const spanId = randomUUID();++ const event = createEvent({+ id: spanId,+ span_id: spanId,+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "test-span-byid",+ input: "Should not be returned",+ output: "Should not be returned",+ });++ await createEventsCh([event]);++ const observation = await getObservationByIdFromEventsTable({+ id: spanId,+ projectId,+ fetchWithInputOutput: false,+ });++ expect(observation).toBeDefined();+ expect(observation?.id).toBe(spanId);+ expect(observation?.input).toBeNull();+ expect(observation?.output).toBeNull();+ });++ it("should return observation by id with truncated input and output", async () => {+ const traceId = randomUUID();+ const generationId = randomUUID();++ const longInput = "x".repeat(50000);+ const longOutput = "y".repeat(50000);++ const event = createEvent({+ id: generationId,+ span_id: generationId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "test-generation-truncated",+ input: longInput,+ output: longOutput,+ provided_model_name: "gpt-4",+ });++ await createEventsCh([event]);++ const observation = await getObservationByIdFromEventsTable({+ id: generationId,+ projectId,+ fetchWithInputOutput: true,+ renderingProps: {+ truncated: true,+ shouldJsonParse: false,+ },+ });++ expect(observation).toBeDefined();+ expect(observation?.id).toBe(generationId);+ expect(observation?.input).toBeDefined();+ expect(observation?.output).toBeDefined();+ // Input and output should be truncated+ if (typeof observation?.input === "string") {+ expect(observation.input.length).toBeLessThan(longInput.length);+ }+ if (typeof observation?.output === "string") {+ expect(observation.output.length).toBeLessThan(longOutput.length);+ }+ });++ it("should filter by traceId when provided", async () => {+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();+ const spanId = randomUUID();++ // Create observation in trace1+ const event = createEvent({+ id: spanId,+ span_id: spanId,+ project_id: projectId,+ trace_id: traceId1,+ type: "SPAN",+ name: "test-span-trace-filter",+ });++ await createEventsCh([event]);++ // Should find with correct traceId+ const observation = await getObservationByIdFromEventsTable({+ id: spanId,+ projectId,+ traceId: traceId1,+ });++ expect(observation).toBeDefined();+ expect(observation?.traceId).toBe(traceId1);++ // Should not find with wrong traceId+ await expect(+ getObservationByIdFromEventsTable({+ id: spanId,+ projectId,+ traceId: traceId2,+ }),+ ).rejects.toThrow();+ });++ it("should filter by type when provided", async () => {+ const traceId = randomUUID();+ const spanId = randomUUID();++ const event = createEvent({+ id: spanId,+ span_id: spanId,+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "test-type-filter",+ });++ await createEventsCh([event]);++ // Should find with correct type+ const observation = await getObservationByIdFromEventsTable({+ id: spanId,+ projectId,+ type: "SPAN",+ });++ expect(observation).toBeDefined();+ expect(observation?.type).toBe("SPAN");++ // Should not find with wrong type+ await expect(+ getObservationByIdFromEventsTable({+ id: spanId,+ projectId,+ type: "GENERATION",+ }),+ ).rejects.toThrow();+ });++ it("should throw error when observation not found", async () => {+ const nonExistentId = randomUUID();++ await expect(+ getObservationByIdFromEventsTable({+ id: nonExistentId,+ projectId,+ }),+ ).rejects.toThrow("Observation with id");+ });++ it("should filter by startTime when provided", async () => {+ const traceId = randomUUID();+ const spanId = randomUUID();++ const startTime = new Date("2024-01-15T12:00:00Z");+ const startTimeMicro = startTime.getTime() * 1000;++ const event = createEvent({+ id: spanId,+ span_id: spanId,+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "test-starttime-filter",+ start_time: startTimeMicro,+ });++ await createEventsCh([event]);++ // Should find with correct startTime+ const observation = await getObservationByIdFromEventsTable({+ id: spanId,+ projectId,+ startTime,+ });++ expect(observation).toBeDefined();++ // Should not find with different date+ const wrongDate = new Date("2024-01-16T12:00:00Z");+ await expect(+ getObservationByIdFromEventsTable({+ id: spanId,+ projectId,+ startTime: wrongDate,+ }),+ ).rejects.toThrow();+ });+ });+});diff --git a/web/src/env.mjs b/web/src/env.mjsindex de4a5c9a41..1507dd8124 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -126,7 +126,10 @@ export const env = createEnv({AUTH_KEYCLOAK_CLIENT_AUTH_METHOD: zAuthMethod,AUTH_KEYCLOAK_CHECKS: zAuthChecks,AUTH_KEYCLOAK_SCOPE: z.string().optional(),- AUTH_KEYCLOAK_ID_TOKEN: z.enum(["true", "false"]).optional().default("true"),+ AUTH_KEYCLOAK_ID_TOKEN: z+ .enum(["true", "false"])+ .optional()+ .default("true"),AUTH_CUSTOM_CLIENT_ID: z.string().optional(),AUTH_CUSTOM_CLIENT_SECRET: z.string().optional(),AUTH_CUSTOM_ISSUER: z.string().url().optional(),@@ -286,6 +289,11 @@ export const env = createEnv({LANGFUSE_AI_FEATURES_PUBLIC_KEY: z.string().optional(),LANGFUSE_AI_FEATURES_SECRET_KEY: z.string().optional(),LANGFUSE_AI_FEATURES_PROJECT_ID: z.string().optional(),++ // Events table migration+ LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS: z+ .enum(["true", "false"])+ .default("false"),},/**@@ -572,6 +580,9 @@ export const env = createEnv({process.env.LANGFUSE_AI_FEATURES_SECRET_KEY,LANGFUSE_AI_FEATURES_PROJECT_ID:process.env.LANGFUSE_AI_FEATURES_PROJECT_ID,+ // Events table migration+ LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS:+ process.env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS,},// Skip validation in Docker builds// DOCKER_BUILD is set in Dockerfilediff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.tsindex 780c6d2ad0..f590e08123 100644--- a/web/src/features/public-api/types/observations.ts+++ b/web/src/features/public-api/types/observations.ts@@ -8,8 +8,8 @@ import {import {reduceUsageOrCostDetails,stringDateTime,+ type ObservationPriceFields,} from "@langfuse/shared/src/server";-import type Decimal from "decimal.js";import { z } from "zod/v4";/**@@ -101,11 +101,7 @@ export const APIObservation = z* @returns API Observation as defined in the public API*/export const transformDbToApiObservation = (- observation: Observation & {- inputPrice: Decimal | null;- outputPrice: Decimal | null;- totalPrice: Decimal | null;- },+ observation: Observation & ObservationPriceFields,): z.infer<typeof APIObservation> => {const reducedUsageDetails = reduceUsageOrCostDetails(observation.usageDetails,diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.tsindex 5c9d527814..6c1c9f446e 100644--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts@@ -1,11 +1,13 @@+import { env } from "@/src/env.mjs";import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";import { filterAndValidateDbScoreList } from "@langfuse/shared";-import { type GetAllGenerationsInput } from "../getAllQueries";import {getObservationsTableWithModelData,+ getObservationsWithModelDataFromEventsTable,getScoresForObservations,traceException,} from "@langfuse/shared/src/server";+import { type GetAllGenerationsInput } from "../getAllQueries";export async function getAllGenerations({input,@@ -14,7 +16,7 @@ export async function getAllGenerations({input: GetAllGenerationsInput;selectIOAndMetadata: boolean;}) {- const generations = await getObservationsTableWithModelData({+ const queryOpts = {projectId: input.projectId,filter: input.filter,orderBy: input.orderBy,@@ -23,7 +25,11 @@ export async function getAllGenerations({selectIOAndMetadata: selectIOAndMetadata,offset: input.page * input.limit,limit: input.limit,- });+ };+ let generations =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ ? await getObservationsWithModelDataFromEventsTable(queryOpts)+ : await getObservationsTableWithModelData(queryOpts);const scores = await getScoresForObservations({projectId: input.projectId,diff --git a/web/src/server/api/routers/generations/getAllQueries.ts b/web/src/server/api/routers/generations/getAllQueries.tsindex a9e0ff9ffc..768e28153d 100644--- a/web/src/server/api/routers/generations/getAllQueries.ts+++ b/web/src/server/api/routers/generations/getAllQueries.ts@@ -3,7 +3,11 @@ import { protectedProjectProcedure } from "@/src/server/api/trpc";import { paginationZod } from "@langfuse/shared";import { GenerationTableOptions } from "./utils/GenerationTableOptions";import { getAllGenerations } from "@/src/server/api/routers/generations/db/getAllGenerationsSqlQuery";-import { getObservationsTableCount } from "@langfuse/shared/src/server";+import {+ getObservationsCountFromEventsTable,+ getObservationsTableCount,+} from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";const GetAllGenerationsInput = GenerationTableOptions.extend({...paginationZod,@@ -24,12 +28,16 @@ export const getAllQueries = {countAll: protectedProjectProcedure.input(GetAllGenerationsInput).query(async ({ input, ctx }) => {- const countQuery = await getObservationsTableCount({+ const queryOpts = {projectId: ctx.session.projectId,filter: input.filter ?? [],limit: 1,offset: 0,- });+ };+ const countQuery =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ ? await getObservationsCountFromEventsTable(queryOpts)+ : await getObservationsTableCount(queryOpts);return {totalCount: countQuery,};diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.tsindex 9cd090988d..593c595e82 100644--- a/web/src/server/api/routers/observations.ts+++ b/web/src/server/api/routers/observations.ts@@ -1,9 +1,13 @@+import { env } from "@/src/env.mjs";import {createTRPCRouter,protectedGetTraceProcedure,} from "@/src/server/api/trpc";import { LangfuseNotFoundError } from "@langfuse/shared";-import { getObservationById } from "@langfuse/shared/src/server";+import {+ getObservationById,+ getObservationByIdFromEventsTable,+} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";import { z } from "zod/v4";@@ -20,7 +24,7 @@ export const observationsRouter = createTRPCRouter({).query(async ({ input }) => {try {- const obs = await getObservationById({+ const queryOpts = {id: input.observationId,projectId: input.projectId,fetchWithInputOutput: true,@@ -30,7 +34,11 @@ export const observationsRouter = createTRPCRouter({truncated: input.truncated,shouldJsonParse: false,},- });+ };+ const obs =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ ? await getObservationByIdFromEventsTable(queryOpts)+ : await getObservationById(queryOpts);if (!obs) {throw new TRPCError({code: "NOT_FOUND",