🪢 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(api): implement observations v1 endpoints on top of events table. (#9781)
Valery Meleshkin3dc228ca3c01
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex d7a2899043..d980f0b53d 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -31,6 +31,7 @@ export * from "../server/ingestion/types";export * from "../server/ingestion/modelMatch";export * from "./ingestion/processEventBatch";export * from "../server/ingestion/validateAndInflateScore";+export * from "../server/queries/public-api-filter-builder";export * from "./redis/redis";export * from "./redis/traceUpsert";export * from "./redis/createEvalQueue";diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.tsindex d1d1a078b6..da18765ff1 100644--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts@@ -28,15 +28,15 @@ export const eventsTracesAggregation = (SELECTtrace_id AS id,project_id,- any(name) AS name,+ argMax(name, event_ts) 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,+ argMax(environment, event_ts) AS environment,+ argMax(version, event_ts) AS version,+ argMax(session_id, event_ts) AS session_id,+ argMax(user_id, event_ts) AS user_id,+ argMax(input, event_ts) AS input,+ argMax(output, event_ts) AS output,+ argMax(metadata, event_ts) AS metadata,min(created_at) AS created_at,max(updated_at) AS updated_at,-- TODO remove legacy fields@@ -52,3 +52,61 @@ export const eventsTracesAggregation = (ORDER BY timestamp DESC`.trim();};++interface EventsScoresAggregationParams {+ projectId: string;+ startTimeFrom?: string | null;+}++/**+ * Scores CTE for events table queries.+ * Aggregates numeric and categorical scores for observations.+ *+ * 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 eventsScoresAggregation = (+ params: EventsScoresAggregationParams,+) => {+ return `+ 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 project_id = {projectId: String}+ ${params.startTimeFrom ? `AND timestamp >= {startTimeFrom: DateTime64(3)}` : ""}+ GROUP BY+ trace_id,+ observation_id,+ name,+ string_value,+ data_type,+ comment+ ORDER BY+ trace_id+ ) tmp+ GROUP BY+ trace_id,+ observation_id+ `.trim();+};diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex 25ab62c255..a5e79dbe4a 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -20,3 +20,8 @@ export {export { orderByToClickhouseSql } from "./clickhouse-sql/orderby-factory";export { createFilterFromFilterState } from "./clickhouse-sql/factory";export { clickhouseSearchCondition } from "./clickhouse-sql/search";+export {+ convertApiProvidedFilterToClickhouseFilter,+ createPublicApiObservationsColumnMapping,+ type ApiColumnMapping,+} from "./public-api-filter-builder";diff --git a/web/src/features/public-api/server/filter-builder.ts b/packages/shared/src/server/queries/public-api-filter-builder.tssimilarity index 66%rename from web/src/features/public-api/server/filter-builder.tsrename to packages/shared/src/server/queries/public-api-filter-builder.tsindex cb6f0f676b..96c7354a16 100644--- a/web/src/features/public-api/server/filter-builder.ts+++ b/packages/shared/src/server/queries/public-api-filter-builder.ts@@ -1,4 +1,4 @@-import { filterOperators } from "@langfuse/shared";+import { filterOperators } from "../../interfaces/filters";import {FilterList,DateTimeFilter,@@ -8,7 +8,7 @@ import {StringFilter,NumberFilter,type ClickhouseOperator,-} from "@langfuse/shared/src/server";+} from "./clickhouse-sql/clickhouse-filter";import { z } from "zod/v4";export type ApiColumnMapping = {@@ -20,6 +20,91 @@ export type ApiColumnMapping = {clickhousePrefix?: string;};+/**+ * Factory function to create public API column mappings for events/observations tables.+ * Eliminates duplication between events and observations filter mappings.+ */+export function createPublicApiObservationsColumnMapping(+ tableName: "events" | "observations",+ tablePrefix: "e" | "o",+ parentFieldName: "parent_span_id" | "parent_observation_id",+): ApiColumnMapping[] {+ return [+ {+ id: "userId",+ clickhouseSelect: "user_id",+ filterType: "StringFilter",+ clickhouseTable: "traces",+ clickhousePrefix: "t",+ },+ {+ id: "traceId",+ clickhouseSelect: "trace_id",+ filterType: "StringFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "name",+ clickhouseSelect: "name",+ filterType: "StringFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "level",+ clickhouseSelect: "level",+ filterType: "StringFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "type",+ clickhouseSelect: "type",+ filterType: "StringFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "parentObservationId",+ clickhouseSelect: parentFieldName,+ filterType: "StringFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "fromStartTime",+ clickhouseSelect: "start_time",+ operator: ">=",+ filterType: "DateTimeFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "toStartTime",+ clickhouseSelect: "start_time",+ operator: "<",+ filterType: "DateTimeFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "version",+ clickhouseSelect: "version",+ filterType: "StringFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ {+ id: "environment",+ clickhouseSelect: "environment",+ filterType: "StringFilter",+ clickhouseTable: tableName,+ clickhousePrefix: tablePrefix,+ },+ ];+}+type BaseQueryType = {page: number;limit: number;@@ -38,7 +123,7 @@ export function convertApiProvidedFilterToClickhouseFilter(if (value) {let filterInstance;switch (columnMapping.filterType) {- case "DateTimeFilter":+ case "DateTimeFilter": {// get filter options from the filterOperators// validate that the user provided operator is in the list of available operatorsconst availableOperators = z.enum(filterOperators.datetime);@@ -62,6 +147,7 @@ export function convertApiProvidedFilterToClickhouseFilter(: undefined;break;+ }case "ArrayOptionsFilter":if (Array.isArray(value) || typeof value === "string") {filterInstance = new ArrayOptionsFilter({@@ -120,7 +206,7 @@ export function convertApiProvidedFilterToClickhouseFilter(});}break;- case "NumberFilter":+ case "NumberFilter": {const availableOperatorsNum = z.enum([...filterOperators.number,"!=",@@ -139,6 +225,7 @@ export function convertApiProvidedFilterToClickhouseFilter(});}break;+ }}filterInstance && filterList.push(filterInstance);diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex bda17c765b..052d6b87f2 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -1,5 +1,5 @@import { prisma } from "../../db";-import { ObservationType } from "../../domain";+import { Observation, ObservationType } from "../../domain";import { env } from "../../env";import { InternalServerError, LangfuseNotFoundError } from "../../errors";import {@@ -14,10 +14,16 @@ import {FilterList,FullObservations,orderByToClickhouseSql,- StringFilter,+ convertApiProvidedFilterToClickhouseFilter,+ createPublicApiObservationsColumnMapping,+ type ApiColumnMapping,+ ObservationPriceFields,} from "../queries";import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";-import { eventsTracesAggregation } from "../queries/clickhouse-sql/query-fragments";+import {+ eventsScoresAggregation,+ eventsTracesAggregation,+} from "../queries/clickhouse-sql/query-fragments";import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";import {eventsTableLegacyTraceUiColumnDefinitions,@@ -32,34 +38,432 @@ import {} 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" },- });+type ObservationsTableQueryResultWitouhtTraceFields = Omit<+ ObservationsTableQueryResult,+ "trace_tags" | "trace_name" | "trace_user_id"+>;- return Number(count[0].count);-};+/**+ * Field mapping: each field defined once with its full SELECT expression+ * All queries use `FROM events e` with alias, so all fields use `e.` prefix+ */+const EVENTS_FIELDS = {+ // Aggregates+ count: "count(*) as 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" },- });+ // Identity & basic fields+ id: "e.span_id as id",+ traceId: 'e.trace_id as "trace_id"',+ projectId: 'e.project_id as "project_id"',+ environment: 'e.environment as "environment"',+ type: "e.type as type",+ parentObservationId: 'e.parent_span_id as "parent_observation_id"',+ name: "e.name as name",+ level: "e.level as level",+ statusMessage: 'e.status_message as "status_message"',+ version: "e.version as version",++ // Time fields+ startTime: 'e.start_time as "start_time"',+ endTime: 'e.end_time as "end_time"',+ completionStartTime: 'e.completion_start_time as "completion_start_time"',+ createdAt: 'e.created_at as "created_at"',+ updatedAt: 'e.updated_at as "updated_at"',+ eventTs: "e.event_ts",++ // Model fields+ providedModelName: 'e.provided_model_name as "provided_model_name"',+ internalModelId: 'e.model_id as "internal_model_id"',+ modelParameters: 'e."model_parameters" as model_parameters',++ // Usage & cost fields+ providedUsageDetails: 'e.provided_usage_details as "provided_usage_details"',+ usageDetails: 'e.usage_details as "usage_details"',+ providedCostDetails: 'e.provided_cost_details as "provided_cost_details"',+ costDetails: 'e.cost_details as "cost_details"',+ totalCost: 'e.total_cost as "total_cost"',++ // Prompt fields+ promptId: 'e.prompt_id as "prompt_id"',+ promptName: 'e.prompt_name as "prompt_name"',+ promptVersion: 'e.prompt_version as "prompt_version"',++ // I/O & metadata fields+ input: "e.input",+ output: "e.output",+ metadata: "e.metadata",++ // Calculated fields+ latency:+ "if(isNull(end_time), NULL, date_diff('millisecond', start_time, end_time)) as latency",+ timeToFirstToken:+ "if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time)) as \"time_to_first_token\"",+} as const;++/**+ * Predefined field sets for common query patterns+ * Maps set names to arrays of field keys from EVENTS_FIELDS+ */+const FIELD_SETS = {+ // Aggregates+ count: ["count"],++ // List query field sets (for getObservationsWithModelDataFromEventsTable)+ base: [+ "id",+ "type",+ "projectId",+ "name",+ "modelParameters",+ "startTime",+ "endTime",+ "traceId",+ "completionStartTime",+ "providedUsageDetails",+ "usageDetails",+ "providedCostDetails",+ "costDetails",+ "level",+ "environment",+ "statusMessage",+ "version",+ "parentObservationId",+ "createdAt",+ "updatedAt",+ "providedModelName",+ "totalCost",+ "promptId",+ "promptName",+ "promptVersion",+ "internalModelId",+ ],+ calculated: ["latency", "timeToFirstToken"],+ io: ["input", "output"],+ metadata: ["metadata"],+ eventTs: ["eventTs"],++ // getById field sets (reuse the same fields - all queries use `FROM events e`)+ byIdBase: [+ "id",+ "traceId",+ "projectId",+ "environment",+ "type",+ "parentObservationId",+ "startTime",+ "endTime",+ "name",+ "metadata",+ "level",+ "statusMessage",+ "version",+ ],+ byIdModel: [+ "providedModelName",+ "internalModelId",+ "modelParameters",+ "providedUsageDetails",+ "usageDetails",+ "providedCostDetails",+ "costDetails",+ "totalCost",+ "completionStartTime",+ ],+ byIdPrompt: ["promptId", "promptName", "promptVersion"],+ byIdTimestamps: ["createdAt", "updatedAt", "eventTs"],+} as const;++/**+ * Special symbol to explicitly opt-out of automatic project_id filtering+ *+ * @example+ * // Use when you need to query across all projects (use with caution!)+ * const builder = new EventsQueryBuilder({ projectId: NoProjectId });+ */+export const NoProjectId = Symbol("NoProjectId");+export type NoProjectIdType = typeof NoProjectId;++/**+ * EventsQueryBuilder - A fluent query builder for events table queries+ *+ * When project_id is provided in the constructor it is automatically+ * added to the WHERE clause during build().+ *+ * @example+ * // Standard usage with automatic project_id filtering+ * const builder = new EventsQueryBuilder({ projectId: "my-project-id" })+ * .selectFieldSet("base", "calculated")+ * .selectIO(true, 1000)+ * .whereRaw("span_id = {id: String}", { id: "abc123" })+ * .orderBy("ORDER BY start_time DESC")+ * .limit(100, 0);+ *+ * const { query, params } = builder.buildWithParams();+ */+class EventsQueryBuilder {+ private selectFields: Set<string> = new Set();+ private ioFields: { truncated: boolean; charLimit?: number } | null = null;+ private ctes: string[] = [];+ private joins: string[] = [];+ private whereClauses: string[] = [];+ private orderByClause: string = "";+ private limitClause: string = "";+ private params: Record<string, any> = {};+ private projectId: string | NoProjectIdType;++ /**+ * Constructor+ * @param options.projectId - Project ID to automatically filter by, or NoProjectId to opt-out+ *+ * @example+ * // Explicit opt-out (use sparingly!)+ * const builder = new EventsQueryBuilder({ projectId: NoProjectId })+ * .selectFieldSet("base")+ * .whereRaw("span_id = {id: String}", { id: "abc123" });+ * // No project_id filter will be added+ */+ constructor(options: { projectId: string | NoProjectIdType }) {+ this.projectId = options.projectId;+ }++ /**+ * Add SELECT fields from predefined field sets+ */+ selectFieldSet(...setNames: Array<keyof typeof FIELD_SETS>): this {+ setNames+ .flatMap((s) => {+ return FIELD_SETS[s];+ })+ .forEach((s) => {+ this.selectFields.add(s);+ });+ return this;+ }++ /**+ * Add IO fields with optional truncation+ */+ selectIO(truncated: boolean = false, charLimit?: number): this {+ this.ioFields = { truncated, charLimit };+ return this;+ }++ /**+ * Conditionally apply builder operations+ */+ when<T extends EventsQueryBuilder>(+ this: T,+ condition: boolean,+ // eslint-disable-next-line no-unused-vars+ fn: (builder: T) => T,+ ): T {+ return condition ? fn(this) : this;+ }++ /**+ * Add a CTE (WITH clause) and track its parameters+ */+ withCTE(+ name: string,+ // eslint-disable-next-line no-unused-vars+ generator: (params: {+ projectId: string;+ startTimeFrom: string | null;+ }) => string,+ options?: {+ projectId?: string;+ startTimeFrom?: string | null;+ },+ ): this {+ const params = {+ projectId: options?.projectId ?? "",+ startTimeFrom: options?.startTimeFrom ?? null,+ };++ if (generator && !!options) {+ this.ctes.push(`${name} AS (${generator(params)})`);++ // Track CTE parameters+ if (params.projectId) {+ this.params.projectId = params.projectId;+ }+ if (params.startTimeFrom) {+ this.params.startTimeFrom = params.startTimeFrom;+ }+ }++ return this;+ }++ /**+ * Add a LEFT JOIN+ */+ leftJoin(table: string, onClause: string): this {+ this.joins.push(`LEFT JOIN ${table} ${onClause}`);+ return this;+ }++ /**+ * Add WHERE conditions from FilterList+ * Accepts the output from FilterList.apply() or clickhouseSearchCondition()+ */+ where(condition: { query: string; params?: Record<string, any> }): this {+ if (condition.query.trim()) {+ // Strip leading AND/OR if present (e.g., from clickhouseSearchCondition)+ const trimmedQuery = condition.query.trim().replace(/^(AND|OR)\s+/i, "");+ this.whereClauses.push(`(${trimmedQuery})`);+ }+ // Merge parameters from FilterCondition+ if (condition.params) {+ this.params = { ...this.params, ...condition.params };+ }+ return this;+ }++ /**+ * Add raw WHERE condition with optional parameters+ * Use ClickHouse parameter syntax: {paramName: Type}+ *+ * Example:+ * .whereRaw("span_id = {id: String}", { id: "abc123" })+ */+ whereRaw(condition: string, params?: Record<string, any>): this {+ if (condition.trim()) {+ this.whereClauses.push(condition);+ }+ // Merge provided parameters+ if (params) {+ this.params = { ...this.params, ...params };+ }+ return this;+ }++ /**+ * Add ORDER BY clause+ */+ orderBy(clause: string): this {+ if (clause.trim()) {+ this.orderByClause = clause;+ }+ return this;+ }++ /**+ * Add LIMIT and OFFSET+ *+ * @param limit - Maximum number of rows to return+ * @param offset - Number of rows to skip+ *+ * Examples:+ * .limit(100, 0) - Parameterized: "LIMIT {limit: Int32} OFFSET {offset: Int32}"+ */+ limit(limit?: number, offset?: number): this {+ if (limit !== undefined && offset !== undefined) {+ this.limitClause = "LIMIT {limit: Int32} OFFSET {offset: Int32}";+ if (limit !== undefined) this.params.limit = limit;+ if (offset !== undefined) this.params.offset = offset;+ } else {+ this.limitClause = "LIMIT 1000";+ }+ return this;+ }++ /**+ * Build the final query string+ */+ private build(): string {+ const parts: string[] = [];++ // CTEs (WITH clause)+ if (this.ctes.length > 0) {+ parts.push(`WITH ${this.ctes.join(",\n")}`);+ }++ // Build field expressions from field keys+ // If ioFields are configured, exclude regular input/output from selectFields+ const fieldsToProcess = this.ioFields+ ? [...this.selectFields].filter((f) => f !== "input" && f !== "output")+ : [...this.selectFields];++ const fieldExpressions: string[] = fieldsToProcess.flatMap((fieldKey) => {+ const fieldExpr = EVENTS_FIELDS[fieldKey as keyof typeof EVENTS_FIELDS];+ return fieldExpr ? [fieldExpr] : [];+ });++ // Add I/O fields if configured+ if (this.ioFields) {+ if (this.ioFields.truncated && this.ioFields.charLimit !== undefined) {+ fieldExpressions.push(+ `leftUTF8(input, ${this.ioFields.charLimit}) as input, leftUTF8(output, ${this.ioFields.charLimit}) as output`,+ );+ } else {+ fieldExpressions.push("input, output");+ }+ }++ // SELECT+ parts.push(`SELECT\n ${fieldExpressions.join(",\n ")}`);++ // FROM+ parts.push("FROM events e");++ // JOINs+ if (this.joins.length > 0) {+ parts.push(this.joins.join("\n"));+ }++ // WHERE+ const allWhereClauses = [...this.whereClauses];++ // Automatically add project_id filter if projectId is provided+ if (this.projectId !== NoProjectId) {+ allWhereClauses.unshift("e.project_id = {projectId: String}");+ this.params.projectId = this.projectId;+ }++ if (allWhereClauses.length > 0) {+ const whereExpression = allWhereClauses.join("\n AND ");+ parts.push(`WHERE ${whereExpression}`);+ }++ // ORDER BY+ if (this.orderByClause) {+ parts.push(this.orderByClause);+ }++ // LIMIT/OFFSET+ if (this.limitClause) {+ parts.push(this.limitClause);+ }+ return parts.join("\n");+ }++ /**+ * Build the final query string along with accumulated parameters+ *+ * Returns both the query and all parameters that have been accumulated+ * from FilterConditions, raw conditions, CTEs, and limit/offset.+ *+ * Example:+ * const { query, params } = queryBuilder.buildWithParams();+ * await queryClickhouse({ query, params });+ */+ buildWithParams(): { query: string; params: Record<string, any> } {+ return {+ query: this.build(),+ params: this.params,+ };+ }+}++/**+ * Internal helper: enrich observations with model pricing data+ */+const enrichObservationsWithModelData = async (+ observationRecords: Array<ObservationsTableQueryResultWitouhtTraceFields>,+ projectId: string,+): Promise<Array<Observation & ObservationPriceFields>> => {const uniqueModels: string[] = Array.from(new Set(observationRecords@@ -75,7 +479,7 @@ export const getObservationsWithModelDataFromEventsTable = async (id: {in: uniqueModels,},- OR: [{ projectId: opts.projectId }, { projectId: null }],+ OR: [{ projectId: projectId }, { projectId: null }],},include: {Price: true,@@ -91,9 +495,6 @@ export const getObservationsWithModelDataFromEventsTable = async (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,@@ -105,45 +506,79 @@ export const getObservationsWithModelDataFromEventsTable = async (});};+const enrichObservationsWithTraceFields = async (+ observationRecords: Array<Observation & ObservationPriceFields>,+): Promise<FullObservations> => {+ return observationRecords.map((o) => {+ return {+ ...o,+ traceName: o.name ?? null,+ traceTags: [], // TODO pull from PG+ traceTimestamp: null,+ };+ });+};++/**+ * Internal helper: extract and convert time filter from FilterList+ * Common pattern: find time filter and convert to ClickHouse DateTime format+ */+const extractTimeFilter = (filter: FilterList): string | null => {+ const timeFilter = filter.find(+ (f) =>+ f.clickhouseTable === "events" &&+ f.field === "start_time" &&+ (f.operator === ">=" || f.operator === ">"),+ );++ return timeFilter+ ? convertDateToClickhouseDateTime((timeFilter as DateTimeFilter).value)+ : null;+};++/**+ * Column mapping for public API filters on events table+ */+const PUBLIC_API_EVENTS_COLUMN_MAPPING: ApiColumnMapping[] =+ createPublicApiObservationsColumnMapping("events", "e", "parent_span_id");++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<ObservationsTableQueryResultWitouhtTraceFields>(+ {+ ...opts,+ select: "rows",+ tags: { kind: "list" },+ },+ );++ return enrichObservationsWithTraceFields(+ await enrichObservationsWithModelData(observationRecords, opts.projectId),+ );+};+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,@@ -154,131 +589,39 @@ const getObservationsFromEventsTableInternal = async <T>(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 === ">"),+ // Build filter list+ const observationsFilter = new FilterList(+ createFilterFromFilterState(filter, eventsTableUiColumnDefinitions),);- const scoresFilter = new FilterList([- new StringFilter({- clickhouseTable: "scores",- field: "project_id",- operator: "=",- value: projectId,- }),- ]);-+ const startTimeFrom = extractTimeFilter(observationsFilter);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.+ // Query optimization: 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 orderByTraces = orderBy+ ? eventsTableLegacyTraceUiColumnDefinitions.some(+ (c) =>+ c.uiTableId === orderBy.column || c.uiTableName === orderBy.column,+ )+ : undefined;+ const needsTraceJoin =+ traceTableFilter.length > 0 || orderByTraces || search.query;- 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)+ // When we have default ordering by time, we order by toUnixTimestamp(e.start_time)// This way, clickhouse is able to read more efficiently directly from disk without orderingconst newDefaultOrder =orderBy?.column === "startTime"@@ -295,34 +638,52 @@ const getObservationsFromEventsTableInternal = async <T>(},]);- 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"};`;+ // Build query using EventsQueryBuilder+ const queryBuilder = new EventsQueryBuilder({ projectId });++ if (opts.select === "count") {+ queryBuilder.selectFieldSet("count");+ } else {+ queryBuilder.selectFieldSet("base", "calculated");+ if (selectIOAndMetadata) {+ queryBuilder.selectFieldSet("io", "metadata");+ }+ }++ queryBuilder+ .when(hasScoresFilter, (b) =>+ b.withCTE("scores_agg", eventsScoresAggregation, {+ projectId,+ startTimeFrom,+ }),+ )+ .when(!!needsTraceJoin, (b) =>+ b.withCTE("traces", eventsTracesAggregation, {+ projectId,+ startTimeFrom,+ }),+ )+ .when(!!needsTraceJoin, (b) =>+ b.leftJoin(+ "traces t",+ "ON t.id = e.trace_id AND t.project_id = e.project_id",+ ),+ )+ .when(hasScoresFilter, (b) =>+ b.leftJoin("scores_agg AS s", "ON s.observation_id = e.span_id"),+ )+ .where(appliedObservationsFilter)+ .where(search)+ .orderBy(chOrderBy)+ .limit(limit, offset);++ const { query, params } = queryBuilder.buildWithParams();return measureAndReturn({operationName: "getObservationsFromEventsTableInternal",projectId,input: {- params: {- projectId,- startTimeFrom,- ...appliedScoresFilter.params,- ...appliedObservationsFilter.params,- ...search.params,- },+ params,tags: {...(opts.tags ?? {}),feature: "tracing",@@ -419,56 +780,33 @@ const getObservationByIdFromEventsTableInternal = async ({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`;+ // Build query using EventsQueryBuilder with automatic param tracking+ const queryBuilder = new EventsQueryBuilder({ projectId })+ .selectFieldSet("byIdBase", "byIdModel", "byIdPrompt", "byIdTimestamps")+ .when(fetchWithInputOutput, (b) =>+ b.selectIO(+ renderingProps.truncated,+ env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT,+ ),+ )+ .whereRaw("span_id = {id: String}", { id })+ .when(Boolean(startTime), (b) =>+ b.whereRaw("toDate(start_time) = toDate({startTime: DateTime64(3)})", {+ startTime: convertDateToClickhouseDateTime(startTime!),+ }),+ )+ .when(Boolean(type), (b) => b.whereRaw("type = {type: String}", { type }))+ .when(Boolean(traceId), (b) =>+ b.whereRaw("trace_id = {traceId: String}", { traceId }),+ )+ .orderBy("ORDER BY toUnixTimestamp(start_time) DESC, event_ts DESC")+ .limit(1, 0);++ const { query, params } = queryBuilder.buildWithParams();+return await queryClickhouse<ObservationRecordReadType>({query,- params: {- id,- projectId,- ...(startTime- ? { startTime: convertDateToClickhouseDateTime(startTime) }- : {}),- ...(type ? { type } : {}),- ...(traceId ? { traceId } : {}),- },+ params,tags: {feature: "tracing",type: "events",@@ -478,3 +816,130 @@ const getObservationByIdFromEventsTableInternal = async ({preferredClickhouseService,});};++type PublicApiObservationsQuery = {+ projectId: string;+ page: number;+ limit: number;+ traceId?: string;+ userId?: string;+ name?: string;+ type?: string;+ level?: string;+ parentObservationId?: string;+ fromStartTime?: string;+ toStartTime?: string;+ version?: string;+ environment?: string | string[];+};++/**+ * Internal implementation for public API observations queries.+ * Consolidates count and list queries into a single implementation.+ */+const getObservationsFromEventsTableForPublicApiInternal = async <T>(+ opts: PublicApiObservationsQuery & { select: "rows" | "count" },+): Promise<Array<T>> => {+ const { projectId, page, limit, ...filterParams } = opts;++ // Convert public API filters to FilterList using column mapping+ const observationsFilter = convertApiProvidedFilterToClickhouseFilter(+ { ...filterParams, projectId, page, limit },+ PUBLIC_API_EVENTS_COLUMN_MAPPING,+ );++ // Determine if we need to join traces (for userId filter)+ const hasTraceFilter = Boolean(filterParams.userId);++ // Extract time filter using helper+ const startTimeFrom = extractTimeFilter(observationsFilter);+ const appliedFilter = observationsFilter.apply();++ // Build query using EventsQueryBuilder+ const queryBuilder = new EventsQueryBuilder({ projectId });++ if (opts.select === "count") {+ queryBuilder.selectFieldSet("count");+ } else {+ queryBuilder.selectFieldSet("base", "calculated", "io", "metadata");+ }++ queryBuilder+ .when(hasTraceFilter, (b) =>+ b.withCTE("traces", eventsTracesAggregation, {+ projectId,+ startTimeFrom,+ }),+ )+ .when(hasTraceFilter, (b) =>+ b.leftJoin(+ "traces t",+ "ON t.id = e.trace_id AND t.project_id = e.project_id",+ ),+ )+ .where(appliedFilter);++ if (opts.select === "rows") {+ queryBuilder+ .orderBy("ORDER BY toUnixTimestamp(e.start_time) DESC")+ .limit(limit, (page - 1) * limit);+ }++ const { query, params } = queryBuilder.buildWithParams();++ const result = await measureAndReturn({+ operationName: `getObservationsFromEventsTableForPublicApi_${opts.select}`,+ projectId,+ input: {+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: opts.select === "count" ? "publicApiCount" : "publicApiRows",+ projectId,+ },+ },+ fn: async (input) => {+ return await queryClickhouse<T>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",+ });+ },+ });++ return result;+};++/**+ * Get observations list from events table for public API.+ * Includes model enrichment and supports public API filter format.+ */+export const getObservationsFromEventsTableForPublicApi = async (+ opts: PublicApiObservationsQuery,+): Promise<Array<Observation & ObservationPriceFields>> => {+ const observationRecords =+ await getObservationsFromEventsTableForPublicApiInternal<ObservationsTableQueryResultWitouhtTraceFields>(+ {+ ...opts,+ select: "rows",+ },+ );+ return enrichObservationsWithModelData(observationRecords, opts.projectId);+};++/**+ * Get count of observations from events table for public API.+ */+export const getObservationsCountFromEventsTableForPublicApi = async (+ opts: PublicApiObservationsQuery,+): Promise<number> => {+ const countResult = await getObservationsFromEventsTableForPublicApiInternal<{+ count: string;+ }>({+ ...opts,+ select: "count",+ });+ return Number(countResult[0].count);+};diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.tsindex 527b5f5364..41df794ded 100644--- a/packages/shared/src/server/repositories/observations_converters.ts+++ b/packages/shared/src/server/repositories/observations_converters.ts@@ -102,7 +102,7 @@ export const convertObservation = (model: record.provided_model_name ?? null,internalModelId: record.internal_model_id ?? null,promptName: record.prompt_name ?? null,- promptVersion: record.prompt_version ?? null,+ promptVersion: record.prompt_version ? Number(record.prompt_version) : null,latency: record.end_time? parseClickhouseUTCDateTimeFormat(record.end_time).getTime() -parseClickhouseUTCDateTimeFormat(record.start_time).getTime()diff --git a/web/src/__tests__/async/observation-api.servertest.ts b/web/src/__tests__/async/observation-api.servertest.tsindex f29ba9bb94..0289a12c8c 100644--- a/web/src/__tests__/async/observation-api.servertest.ts+++ b/web/src/__tests__/async/observation-api.servertest.ts@@ -1,366 +1,471 @@import {- createObservation as createObservationObject,+ createEvent,+ createObservation,createTrace,createTracesCh,} from "@langfuse/shared/src/server";-import { createObservationsCh as createObservationsInClickhouse } from "@langfuse/shared/src/server";+import {+ createEventsCh,+ createObservationsCh,+} from "@langfuse/shared/src/server";import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";import { GetObservationV1Response } from "@/src/features/public-api/types/observations";import { v4 as uuidv4 } from "uuid";import { GetObservationsV1Response } from "@/src/features/public-api/types/observations";import { snakeCase } from "lodash";+import { env } from "@/src/env.mjs";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";+// Helper type for observation data+type ObservationData = {+ id: string;+ span_id?: string;+ trace_id: string;+ project_id: string;+ type: string;+ name?: string;+ model_id?: string;+ internal_model_id?: string;+ provided_model_name?: string;+ input?: string;+ output?: string;+ start_time?: number;+ end_time?: number;+ event_ts?: number;+ usage_details?: Record<string, number>;+ version?: string;+ [key: string]: any;+};++// Helper to create observation in the appropriate format+const createObservationData = (+ useEventsTable: boolean,+ data: ObservationData,+) => {+ if (useEventsTable) {+ // Events table: use microseconds, requires span_id+ return createEvent({+ ...data,+ span_id: data.span_id || data.id,+ model_id: data.model_id || data.internal_model_id,+ // Convert millisecond timestamps to microseconds if present+ start_time: data.start_time ? data.start_time : undefined,+ end_time: data.end_time ? data.end_time : undefined,+ event_ts: data.event_ts ? data.event_ts : undefined,+ });+ } else {+ // Observations table: use milliseconds, requires internal_model_id+ const { model_id, ...rest } = data;+ return createObservation({+ ...rest,+ internal_model_id: model_id || data.internal_model_id,+ // Timestamps already in milliseconds+ });+ }+};++// Helper to insert observations into the correct table+const insertObservations = async (+ useEventsTable: boolean,+ observations: any[],+) => {+ if (useEventsTable) {+ await createEventsCh(observations);+ } else {+ await createObservationsCh(observations);+ }+};+describe("/api/public/observations API Endpoint", () => {- describe("GET /api/public/observations/:id", () => {- it("should GET an observation", async () => {- const observationId = uuidv4();- const traceId = uuidv4();-- const observation = createObservationObject({- id: observationId,- project_id: projectId,- trace_id: traceId,- internal_model_id: "b9854a5c92dc496b997d99d21",- provided_model_name: "gpt-4o-2024-05-13",- input: "input",- output: "output",- });+ // Test suite factory to run tests against both implementations+ const runTestSuite = (useEventsTable: boolean) => {+ const suiteName = useEventsTable+ ? "with events table"+ : "with observations table";+ const queryParam = useEventsTable+ ? "&useEventsTable=true"+ : "&useEventsTable=false";+ const timeMultiplier = useEventsTable ? 1000 : 1; // microseconds vs milliseconds++ describe(`${suiteName}`, () => {+ describe("GET /api/public/observations/:id", () => {+ it("should GET an observation", async () => {+ const observationId = uuidv4();+ const traceId = uuidv4();++ const observation = createObservationData(useEventsTable, {+ id: observationId,+ project_id: projectId,+ trace_id: traceId,+ model_id: "b9854a5c92dc496b997d99d21",+ provided_model_name: "gpt-4o-2024-05-13",+ input: "input",+ output: "output",+ type: "GENERATION",+ });- await createObservationsInClickhouse([observation]);-- const getEventRes = await makeZodVerifiedAPICall(- GetObservationV1Response,- "GET",- "/api/public/observations/" + observationId,- );- expect(getEventRes.body).toMatchObject({- id: observationId,- traceId: traceId,- type: observation.type,- modelId: observation.internal_model_id,- inputPrice: 0.000005,- input: observation.input,- output: observation.output,- });- });+ await insertObservations(useEventsTable, [observation]);++ const getEventRes = await makeZodVerifiedAPICall(+ GetObservationV1Response,+ "GET",+ `/api/public/observations/${observationId}?useEventsTable=${useEventsTable}`,+ );+ expect(getEventRes.body).toMatchObject({+ id: observationId,+ traceId: traceId,+ type: observation.type,+ modelId: useEventsTable+ ? observation.model_id+ : observation.internal_model_id,+ inputPrice: 0.000005,+ input: observation.input,+ output: observation.output,+ });+ });- it.each([- ["AGENT", "agent-observation"],- ["TOOL", "tool-observation"],- ["CHAIN", "chain-observation"],- ["RETRIEVER", "retriever-observation"],- ["EVALUATOR", "evaluator-observation"],- ["EMBEDDING", "embedding-observation"],- ["GUARDRAIL", "guardrail-observation"],- ])("should GET observation with type %s", async (type, name) => {- const observationId = uuidv4();- const traceId = uuidv4();-- const observation = createObservationObject({- id: observationId,- project_id: projectId,- trace_id: traceId,- type: type,- name: name,- });+ it.each([+ ["AGENT", "agent-observation"],+ ["TOOL", "tool-observation"],+ ["CHAIN", "chain-observation"],+ ["RETRIEVER", "retriever-observation"],+ ["EVALUATOR", "evaluator-observation"],+ ["EMBEDDING", "embedding-observation"],+ ["GUARDRAIL", "guardrail-observation"],+ ])("should GET observation with type %s", async (type, name) => {+ const observationId = uuidv4();+ const traceId = uuidv4();++ const observation = createObservationData(useEventsTable, {+ id: observationId,+ project_id: projectId,+ trace_id: traceId,+ type: type,+ name: name,+ });- await createObservationsInClickhouse([observation]);-- const getEventRes = await makeZodVerifiedAPICall(- GetObservationV1Response,- "GET",- "/api/public/observations/" + observationId,- );- expect(getEventRes.body).toMatchObject({- id: observationId,- traceId: traceId,- type: type,- name: name,- });- });- });-- describe("GET /api/public/observations", () => {- it("should fetch all observations", async () => {- const traceId = uuidv4();-- const observation = createObservationObject({- id: uuidv4(),- trace_id: traceId,- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- internal_model_id: "clrkwk4cb000408l576jl7koo",- provided_model_name: "gpt-3.5-turbo",- input: JSON.stringify({ key: "input" }),- output: JSON.stringify({ key: "output" }),- usage_details: {- input: 10,- output: 20,- total: 30,- },- version: "2.0.0",- type: "GENERATION",+ await insertObservations(useEventsTable, [observation]);++ const getEventRes = await makeZodVerifiedAPICall(+ GetObservationV1Response,+ "GET",+ `/api/public/observations/${observationId}?useEventsTable=${useEventsTable}`,+ );+ expect(getEventRes.body).toMatchObject({+ id: observationId,+ traceId: traceId,+ type: type,+ name: name,+ });+ });});- await createObservationsInClickhouse([observation]);+ describe("GET /api/public/observations", () => {+ it("should fetch all observations", async () => {+ const traceId = uuidv4();+ const observationId = uuidv4();- const fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- "/api/public/observations?traceId=" + traceId,- undefined,- );+ const observation = createObservationData(useEventsTable, {+ id: observationId,+ trace_id: traceId,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ model_id: "clrkwk4cb000408l576jl7koo",+ provided_model_name: "gpt-3.5-turbo",+ input: JSON.stringify({ key: "input" }),+ output: JSON.stringify({ key: "output" }),+ usage_details: {+ input: 10,+ output: 20,+ total: 30,+ },+ version: "2.0.0",+ type: "GENERATION",+ });- expect(fetchedObservations.status).toBe(200);+ await insertObservations(useEventsTable, [observation]);- expect(fetchedObservations.body.data.length).toBe(1);- expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);- expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });- expect(fetchedObservations.body.data[0]?.output).toEqual({- key: "output",- });- expect(fetchedObservations.body.data[0]?.model).toEqual("gpt-3.5-turbo");- expect(fetchedObservations.body.data[0]?.modelId).toEqual(- "clrkwk4cb000408l576jl7koo",- );- expect(- fetchedObservations.body.data[0]?.calculatedInputCost,- ).toBeGreaterThan(0);- expect(- fetchedObservations.body.data[0]?.calculatedOutputCost,- ).toBeGreaterThan(0);- expect(- fetchedObservations.body.data[0]?.calculatedTotalCost,- ).toBeGreaterThan(0);- });+ const fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?traceId=${traceId}${queryParam}`,+ undefined,+ );- it("should fetch all observations, filtered by generations", async () => {- const traceId = uuidv4();-- const generationObservation = createObservationObject({- id: uuidv4(),- trace_id: traceId,- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- internal_model_id: "model-1",- provided_model_name: "gpt-3.5-turbo",- input: JSON.stringify({ key: "input" }),- output: JSON.stringify({ key: "output" }),- usage_details: {- input: 10,- output: 20,- total: 30,- },- version: "2.0.0",- type: "GENERATION",- });+ expect(fetchedObservations.status).toBe(200);- const spanObservation = createObservationObject({- id: uuidv4(),- trace_id: traceId,- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- input: JSON.stringify({ key: "input" }),- output: JSON.stringify({ key: "output" }),- version: "2.0.0",- type: "SPAN",- });+ expect(fetchedObservations.body.data.length).toBe(1);+ expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);+ expect(fetchedObservations.body.data[0]?.input).toEqual({+ key: "input",+ });+ expect(fetchedObservations.body.data[0]?.output).toEqual({+ key: "output",+ });+ expect(fetchedObservations.body.data[0]?.model).toEqual(+ "gpt-3.5-turbo",+ );+ expect(fetchedObservations.body.data[0]?.modelId).toEqual(+ "clrkwk4cb000408l576jl7koo",+ );+ expect(+ fetchedObservations.body.data[0]?.calculatedInputCost,+ ).toBeGreaterThan(0);+ expect(+ fetchedObservations.body.data[0]?.calculatedOutputCost,+ ).toBeGreaterThan(0);+ expect(+ fetchedObservations.body.data[0]?.calculatedTotalCost,+ ).toBeGreaterThan(0);+ });- await createObservationsInClickhouse([- generationObservation,- spanObservation,- ]);-- const fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- "/api/public/observations?type=GENERATION&traceId=" + traceId,- undefined,- );-- expect(fetchedObservations.status).toBe(200);-- expect(fetchedObservations.body.data.length).toBe(1);- expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);- expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });- expect(fetchedObservations.body.data[0]?.output).toEqual({- key: "output",- });- expect(fetchedObservations.body.data[0]?.type).toEqual("GENERATION");- });+ it("should fetch all observations, filtered by generations", async () => {+ const traceId = uuidv4();+ const generationId = uuidv4();+ const spanId = uuidv4();- it.each([- ["userId", uuidv4()],- ["traceId", uuidv4()],- ["name", uuidv4()],- ["version", uuidv4()],- ["environment", uuidv4()],- ])(- "should fetch all observations filtered by a value (%s, %s)",- async (prop: string, value: string) => {- const traceId = uuidv4();-- if (prop === "userId" || prop === "environment") {- const createdTrace = createTrace({- id: traceId,- [snakeCase(prop)]: value,+ const generationObservation = createObservationData(useEventsTable, {+ id: generationId,+ trace_id: traceId,project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ model_id: "model-1",+ provided_model_name: "gpt-3.5-turbo",+ input: JSON.stringify({ key: "input" }),+ output: JSON.stringify({ key: "output" }),+ usage_details: {+ input: 10,+ output: 20,+ total: 30,+ },+ version: "2.0.0",+ type: "GENERATION",});- await createTracesCh([createdTrace]);- }-- const observation = createObservationObject({- id: uuidv4(),- trace_id: traceId,- start_time: new Date("2021-01-01T00:00:00.000Z").getTime(),- end_time: new Date("2021-01-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "GENERATION",- [snakeCase(prop)]: value,- });+ const spanObservation = createObservationData(useEventsTable, {+ id: spanId,+ trace_id: traceId,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ input: JSON.stringify({ key: "input" }),+ output: JSON.stringify({ key: "output" }),+ version: "2.0.0",+ type: "SPAN",+ });- await createObservationsInClickhouse([observation]);+ await insertObservations(useEventsTable, [+ generationObservation,+ spanObservation,+ ]);- const observations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?${prop}=${value}`,- );+ const fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?type=GENERATION&traceId=${traceId}${queryParam}`,+ undefined,+ );++ expect(fetchedObservations.status).toBe(200);++ expect(fetchedObservations.body.data.length).toBe(1);+ expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);+ expect(fetchedObservations.body.data[0]?.input).toEqual({+ key: "input",+ });+ expect(fetchedObservations.body.data[0]?.output).toEqual({+ key: "output",+ });+ expect(fetchedObservations.body.data[0]?.type).toEqual("GENERATION");+ });- expect(observations.body.meta.totalItems).toBe(1);- expect(observations.body.data.length).toBe(1);- const obsResult = observations.body.data[0];- expect(obsResult.projectId).toBe(- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ it.each([+ ["userId", uuidv4()],+ ["traceId", uuidv4()],+ ["name", uuidv4()],+ ["version", uuidv4()],+ ["environment", uuidv4()],+ ])(+ "should fetch all observations filtered by a value (%s, %s)",+ async (prop: string, value: string) => {+ const traceId = uuidv4();+ const observationId = uuidv4();+ const timestamp = new Date("2021-01-01T00:00:00.000Z").getTime();++ if (prop === "userId" || prop === "environment") {+ const createdTrace = createTrace({+ id: traceId,+ [snakeCase(prop)]: value,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ });++ await createTracesCh([createdTrace]);+ }++ const observation = createObservationData(useEventsTable, {+ id: observationId,+ trace_id: traceId,+ start_time: timestamp * timeMultiplier,+ end_time: timestamp * timeMultiplier,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "GENERATION",+ [snakeCase(prop)]: value,+ });++ await insertObservations(useEventsTable, [observation]);++ const observations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?${prop}=${value}${queryParam}`,+ );++ expect(observations.body.meta.totalItems).toBe(1);+ expect(observations.body.data.length).toBe(1);+ const obsResult = observations.body.data[0];+ expect(obsResult.projectId).toBe(+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ );+ if (prop === "userId") return;+ expect((obsResult as any)[prop]).toBe(value);+ },);- if (prop === "userId") return;- expect((obsResult as any)[prop]).toBe(value);- },- );-- it("GET /observations with timestamp filters and pagination", async () => {- const traceId = uuidv4();- const obs1 = createObservationObject({- id: "observation-2021-01-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-01-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-01-01T00:00:00.000Z").getTime(),- end_time: new Date("2021-01-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "GENERATION",- });- const obs2 = createObservationObject({- id: "observation-2021-02-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-02-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-02-01T00:00:00.000Z").getTime(),- end_time: new Date("2021-02-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "SPAN",- });- const obs3 = createObservationObject({- id: "observation-2021-03-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-03-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-03-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "EVENT",- });- const obs4 = createObservationObject({- id: "observation-2021-04-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-04-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-04-01T00:00:00.000Z").getTime(),- end_time: new Date("2021-04-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "GENERATION",- });+ it("GET /observations with timestamp filters and pagination", async () => {+ const traceId = uuidv4();+ const timestamp1 = new Date("2021-01-01T00:00:00.000Z").getTime();+ const timestamp2 = new Date("2021-02-01T00:00:00.000Z").getTime();+ const timestamp3 = new Date("2021-03-01T00:00:00.000Z").getTime();+ const timestamp4 = new Date("2021-04-01T00:00:00.000Z").getTime();++ const obs1 = createObservationData(useEventsTable, {+ id: "observation-2021-01-01",+ trace_id: traceId,+ name: "generation-name",+ start_time: timestamp1 * timeMultiplier,+ event_ts: timestamp1 * timeMultiplier,+ end_time: timestamp1 * timeMultiplier,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "GENERATION",+ });++ const obs2 = createObservationData(useEventsTable, {+ id: "observation-2021-02-01",+ trace_id: traceId,+ name: "generation-name",+ start_time: timestamp2 * timeMultiplier,+ event_ts: timestamp2 * timeMultiplier,+ end_time: timestamp2 * timeMultiplier,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "SPAN",+ });++ const obs3 = createObservationData(useEventsTable, {+ id: "observation-2021-03-01",+ trace_id: traceId,+ name: "generation-name",+ start_time: timestamp3 * timeMultiplier,+ event_ts: timestamp3 * timeMultiplier,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "EVENT",+ });- await createObservationsInClickhouse([obs1, obs2, obs3, obs4]);-- const fromTimestamp = "2021-02-01T00:00:00.000Z";- const toTimestamp = "2021-04-01T00:00:00.000Z";-- // Test with both fromTimestamp and toTimestamp- let fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?fromStartTime=${fromTimestamp}&toStartTime=${toTimestamp}&traceId=${traceId}`,- undefined,- );-- expect(fetchedObservations.body.data.length).toBe(2);- expect(fetchedObservations.body.data[0]?.id).toBe(- "observation-2021-03-01",- );- expect(fetchedObservations.body.data[1]?.id).toBe(- "observation-2021-02-01",- );- expect(fetchedObservations.body.meta.totalItems).toBe(2);-- // Test with only fromTimestamp- fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?fromStartTime=${fromTimestamp}&traceId=${traceId}`,- undefined,- );-- expect(fetchedObservations.body.data.length).toBe(3);- expect(fetchedObservations.body.data[0]?.id).toBe(- "observation-2021-04-01",- );- expect(fetchedObservations.body.data[1]?.id).toBe(- "observation-2021-03-01",- );- expect(fetchedObservations.body.data[2]?.id).toBe(- "observation-2021-02-01",- );- expect(fetchedObservations.body.meta.totalItems).toBe(3);-- // Test with only toTimestamp- fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?toStartTime=${toTimestamp}&traceId=${traceId}`,- undefined,- );-- expect(fetchedObservations.body.data.length).toBe(3);- expect(fetchedObservations.body.data[0]?.id).toBe(- "observation-2021-03-01",- );- expect(fetchedObservations.body.data[1]?.id).toBe(- "observation-2021-02-01",- );- expect(fetchedObservations.body.data[2]?.id).toBe(- "observation-2021-01-01",- );- expect(fetchedObservations.body.meta.totalItems).toBe(3);-- // test pagination only- fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?limit=1&page=2&traceId=${traceId}`,- undefined,- );-- expect(fetchedObservations.body.data.length).toBe(1);- expect(fetchedObservations.body.data[0]?.id).toBe(- "observation-2021-03-01",- );- expect(fetchedObservations.body.meta).toMatchObject({- totalItems: 4,- totalPages: 4,- page: 2,- limit: 1,+ const obs4 = createObservationData(useEventsTable, {+ id: "observation-2021-04-01",+ trace_id: traceId,+ name: "generation-name",+ start_time: timestamp4 * timeMultiplier,+ event_ts: timestamp4 * timeMultiplier,+ end_time: timestamp4 * timeMultiplier,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "GENERATION",+ });++ await insertObservations(useEventsTable, [obs1, obs2, obs3, obs4]);++ const fromTimestamp = "2021-02-01T00:00:00.000Z";+ const toTimestamp = "2021-04-01T00:00:00.000Z";++ // Test with both fromTimestamp and toTimestamp+ let fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?fromStartTime=${fromTimestamp}&toStartTime=${toTimestamp}&traceId=${traceId}${queryParam}`,+ undefined,+ );++ expect(fetchedObservations.body.data.length).toBe(2);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.data[1]?.id).toBe(+ "observation-2021-02-01",+ );+ expect(fetchedObservations.body.meta.totalItems).toBe(2);++ // Test with only fromTimestamp+ fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?fromStartTime=${fromTimestamp}&traceId=${traceId}${queryParam}`,+ undefined,+ );++ expect(fetchedObservations.body.data.length).toBe(3);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-04-01",+ );+ expect(fetchedObservations.body.data[1]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.data[2]?.id).toBe(+ "observation-2021-02-01",+ );+ expect(fetchedObservations.body.meta.totalItems).toBe(3);++ // Test with only toTimestamp+ fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?toStartTime=${toTimestamp}&traceId=${traceId}${queryParam}`,+ undefined,+ );++ expect(fetchedObservations.body.data.length).toBe(3);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.data[1]?.id).toBe(+ "observation-2021-02-01",+ );+ expect(fetchedObservations.body.data[2]?.id).toBe(+ "observation-2021-01-01",+ );+ expect(fetchedObservations.body.meta.totalItems).toBe(3);++ // test pagination only+ fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?limit=1&page=2&traceId=${traceId}${queryParam}`,+ undefined,+ );++ expect(fetchedObservations.body.data.length).toBe(1);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.meta).toMatchObject({+ totalItems: 4,+ totalPages: 4,+ page: 2,+ limit: 1,+ });+ });});});- });+ };++ // Run tests with both implementations+ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ runTestSuite(true); // with events table+ }+ runTestSuite(false); // with observations table});diff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/async/observations-api.servertest.tsindex 2c560e7bb6..605701658a 100644--- a/web/src/__tests__/async/observations-api.servertest.ts+++ b/web/src/__tests__/async/observations-api.servertest.ts@@ -2,442 +2,558 @@ import {createObservation,createTrace,createTracesCh,+ createEvent,+} from "@langfuse/shared/src/server";+import {+ createObservationsCh,+ createEventsCh,} from "@langfuse/shared/src/server";-import { createObservationsCh } from "@langfuse/shared/src/server";import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";import { GetObservationsV1Response } from "@/src/features/public-api/types/observations";import { randomUUID } from "crypto";+import { env } from "@/src/env.mjs";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-describe("/api/public/observations API Endpoint", () => {- describe("GET /api/public/observations", () => {- it("should fetch all observations with basic data structure", async () => {- const traceId = randomUUID();- const timestamp = new Date();-- // Create a trace first- const createdTrace = createTrace({- id: traceId,- name: "test-trace",- user_id: "user-1",- timestamp: timestamp.getTime(),- project_id: projectId,- metadata: { testKey: "testValue" },- release: "1.0.0",- version: "2.0.0",- });+// Helper type for creating observation data+type ObservationData = {+ id?: string;+ trace_id: string;+ project_id: string;+ name: string;+ type: string;+ level: string;+ start_time: number;+ end_time?: number | null;+ input?: string | null;+ output?: string | null;+ metadata?: Record<string, string>;+ provided_model_name?: string;+ provided_usage_details?: Record<string, number>;+ provided_cost_details?: Record<string, number>;+};++// Helper to create observation data in the appropriate format (events or observations table)+const createObservationData = (+ useEventsTable: boolean,+ data: ObservationData,+) => {+ const id = data.id ?? randomUUID();++ if (useEventsTable) {+ // For events table: microseconds, requires span_id and metadata arrays+ return createEvent({+ id,+ span_id: id,+ trace_id: data.trace_id,+ project_id: data.project_id,+ name: data.name,+ type: data.type,+ level: data.level,+ start_time: data.start_time,+ end_time: data.end_time === null ? null : data.end_time,+ input: data.input !== undefined ? data.input : "Hello World",+ output: data.output !== undefined ? data.output : "Hello John",+ metadata: data.metadata ?? { source: "API", server: "Node" },+ metadata_string_names: data.metadata+ ? Object.keys(data.metadata)+ : undefined,+ metadata_string_values: data.metadata+ ? Object.values(data.metadata)+ : undefined,+ provided_model_name: data.provided_model_name,+ provided_usage_details: data.provided_usage_details,+ provided_cost_details: data.provided_cost_details,+ usage_details: data.provided_usage_details,+ cost_details: data.provided_cost_details,+ });+ } else {+ // For observations table: milliseconds, simpler structure+ return createObservation({+ id,+ trace_id: data.trace_id,+ project_id: data.project_id,+ name: data.name,+ type: data.type,+ level: data.level,+ start_time: data.start_time,+ end_time: data.end_time === null ? null : data.end_time,+ input: data.input,+ output: data.output,+ metadata: data.metadata,+ provided_model_name: data.provided_model_name,+ provided_usage_details: data.provided_usage_details,+ provided_cost_details: data.provided_cost_details,+ });+ }+};++// Helper to create trace and observations in one go+const createAndInsertObservations = async (+ useEventsTable: boolean,+ trace: ReturnType<typeof createTrace>,+ observations: ObservationData[],+) => {+ await createTracesCh([trace]);++ const data = observations.map((obs) =>+ createObservationData(useEventsTable, obs),+ );++ if (useEventsTable) {+ await createEventsCh(data as any);+ } else {+ await createObservationsCh(data as any);+ }+};- // Create multiple observations with different types and levels- const observations = [- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "generation-observation",- type: "GENERATION",- level: "DEFAULT",- start_time: timestamp.getTime(),- end_time: timestamp.getTime() + 1000,- input: "What is the capital of France?",- output: "The capital of France is Paris.",- provided_model_name: "gpt-4",- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "span-observation",- type: "SPAN",- level: "DEBUG",- start_time: timestamp.getTime() + 500,- end_time: timestamp.getTime() + 2000,- input: "Processing request",- output: "Request processed successfully",- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "event-observation",- type: "EVENT",- level: "WARNING",- start_time: timestamp.getTime() + 1500,- input: "User action recorded",- metadata: { eventType: "click", target: "submit-button" },- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "agent-observation",- type: "AGENT",- level: "DEFAULT",- start_time: timestamp.getTime() + 2000,- end_time: timestamp.getTime() + 2500,- provided_model_name: "claude-3-haiku",- provided_usage_details: { input: 100, output: 50, total: 150 },- provided_cost_details: { input: 0.001, output: 0.002, total: 0.003 },- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "tool-observation",- type: "TOOL",- level: "DEFAULT",- start_time: timestamp.getTime() + 2500,- end_time: timestamp.getTime() + 3000,- input: "Search web for information",- output: "Found relevant results",- provided_model_name: "gpt-4o-mini",- provided_usage_details: { input: 200, output: 100, total: 300 },- provided_cost_details: { input: 0.002, output: 0.004, total: 0.006 },- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "chain-observation",- type: "CHAIN",- level: "DEFAULT",- start_time: timestamp.getTime() + 3000,- end_time: timestamp.getTime() + 3500,- input: "Process multi-step workflow",- output: "Workflow completed",- provided_model_name: "gpt-4",- provided_usage_details: { input: 500, output: 300, total: 800 },- provided_cost_details: { input: 0.015, output: 0.03, total: 0.045 },- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "retriever-observation",- type: "RETRIEVER",- level: "DEFAULT",- start_time: timestamp.getTime() + 3500,- end_time: timestamp.getTime() + 4000,- input: "Query document database",- output: "Retrieved 5 relevant documents",- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "evaluator-observation",- type: "EVALUATOR",- level: "DEFAULT",- start_time: timestamp.getTime() + 4000,- input: null,- output: null,- end_time: null,- }),- createObservation({- id: randomUUID(),- trace_id: traceId,+describe("/api/public/observations API Endpoint", () => {+ // Test suite factory to run tests against both implementations+ const runTestSuite = (useEventsTable: boolean) => {+ const suiteName = useEventsTable+ ? "with events table"+ : "with observations table";+ const queryParam = useEventsTable+ ? "?useEventsTable=true"+ : "?useEventsTable=false";++ describe(`GET /api/public/observations ${suiteName}`, () => {+ it("should fetch all observations with basic data structure", async () => {+ const traceId = randomUUID();+ const timestamp = new Date();+ const timeValue = useEventsTable+ ? timestamp.getTime() * 1000+ : timestamp.getTime();+ const timeMultiplier = useEventsTable ? 1000 : 1;++ // Create a trace first+ const createdTrace = createTrace({+ id: traceId,+ name: "test-trace",+ user_id: "user-1",+ timestamp: timestamp.getTime(),project_id: projectId,- name: "embedding-observation",- type: "EMBEDDING",- level: "DEFAULT",- start_time: timestamp.getTime() + 4500,- end_time: timestamp.getTime() + 4750,- input: "Text to embed",- output: "Vector embedding generated",- provided_model_name: "text-embedding-ada-002",- provided_usage_details: { input: 10, output: 0, total: 10 },- provided_cost_details: { input: 0.0001, output: 0, total: 0.0001 },- }),- createObservation({- id: randomUUID(),- trace_id: traceId,+ metadata: { testKey: "testValue" },+ release: "1.0.0",+ version: "2.0.0",+ });++ // Create observations using helper+ await createAndInsertObservations(useEventsTable, createdTrace, [+ {+ trace_id: traceId,+ project_id: projectId,+ name: "generation-observation",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue,+ end_time: timeValue + 1000 * timeMultiplier,+ input: "What is the capital of France?",+ output: "The capital of France is Paris.",+ provided_model_name: "gpt-4",+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "span-observation",+ type: "SPAN",+ level: "DEBUG",+ start_time: timeValue + 500 * timeMultiplier,+ end_time: timeValue + 2000 * timeMultiplier,+ input: "Processing request",+ output: "Request processed successfully",+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "event-observation",+ type: "EVENT",+ level: "WARNING",+ start_time: timeValue + 1500 * timeMultiplier,+ input: "User action recorded",+ metadata: { eventType: "click", target: "submit-button" },+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "agent-observation",+ type: "AGENT",+ level: "DEFAULT",+ start_time: timeValue + 2000 * timeMultiplier,+ end_time: timeValue + 2500 * timeMultiplier,+ input: "Hello World",+ output: "Hello John",+ provided_model_name: "claude-3-haiku",+ provided_usage_details: { input: 100, output: 50, total: 150 },+ provided_cost_details: {+ input: 0.001,+ output: 0.002,+ total: 0.003,+ },+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "tool-observation",+ type: "TOOL",+ level: "DEFAULT",+ start_time: timeValue + 2500 * timeMultiplier,+ end_time: timeValue + 3000 * timeMultiplier,+ input: "Search web for information",+ output: "Found relevant results",+ provided_model_name: "gpt-4o-mini",+ provided_usage_details: { input: 200, output: 100, total: 300 },+ provided_cost_details: {+ input: 0.002,+ output: 0.004,+ total: 0.006,+ },+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "chain-observation",+ type: "CHAIN",+ level: "DEFAULT",+ start_time: timeValue + 3000 * timeMultiplier,+ end_time: timeValue + 3500 * timeMultiplier,+ input: "Process multi-step workflow",+ output: "Workflow completed",+ provided_model_name: "gpt-4",+ provided_usage_details: { input: 500, output: 300, total: 800 },+ provided_cost_details: { input: 0.015, output: 0.03, total: 0.045 },+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "retriever-observation",+ type: "RETRIEVER",+ level: "DEFAULT",+ start_time: timeValue + 3500 * timeMultiplier,+ end_time: timeValue + 4000 * timeMultiplier,+ input: "Query document database",+ output: "Retrieved 5 relevant documents",+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "evaluator-observation",+ type: "EVALUATOR",+ level: "DEFAULT",+ start_time: timeValue + 4000 * timeMultiplier,+ input: null,+ output: null,+ end_time: null,+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "embedding-observation",+ type: "EMBEDDING",+ level: "DEFAULT",+ start_time: timeValue + 4500 * timeMultiplier,+ end_time: timeValue + 4750 * timeMultiplier,+ input: "Text to embed",+ output: "Vector embedding generated",+ provided_model_name: "text-embedding-ada-002",+ provided_usage_details: { input: 10, output: 0, total: 10 },+ provided_cost_details: { input: 0.0001, output: 0, total: 0.0001 },+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "guardrail-observation",+ type: "GUARDRAIL",+ level: "DEFAULT",+ start_time: timeValue + 5000 * timeMultiplier,+ provided_cost_details: { input: 0.0001, output: 0, total: 0.0001 },+ },+ ]);++ const response = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations${queryParam}`,+ );++ expect(response.status).toBe(200);+ expect(response.body.data).toBeDefined();+ expect(response.body.meta).toBeDefined();+ expect(response.body.meta.totalItems).toBeGreaterThanOrEqual(10);+ expect(response.body.data.length).toBeGreaterThanOrEqual(10);++ // Find our created observations in the response+ const createdObservations = response.body.data.filter(+ (obs) => obs.traceId === traceId,+ );+ expect(createdObservations.length).toBe(10);++ // Verify data structure and content+ const generationObs = createdObservations.find(+ (obs) => obs.type === "GENERATION",+ );+ expect(generationObs).toBeDefined();+ expect(generationObs?.name).toBe("generation-observation");+ expect(generationObs?.level).toBe("DEFAULT");+ expect(generationObs?.input).toBe("What is the capital of France?");+ expect(generationObs?.output).toBe("The capital of France is Paris.");+ expect(generationObs?.model).toBe("gpt-4");+ expect(generationObs?.projectId).toBe(projectId);+ expect(generationObs?.traceId).toBe(traceId);++ const spanObs = createdObservations.find((obs) => obs.type === "SPAN");+ expect(spanObs).toBeDefined();+ expect(spanObs?.name).toBe("span-observation");+ expect(spanObs?.level).toBe("DEBUG");+ expect(spanObs?.input).toBe("Processing request");+ expect(spanObs?.output).toBe("Request processed successfully");++ const eventObs = createdObservations.find(+ (obs) => obs.type === "EVENT",+ );+ expect(eventObs).toBeDefined();+ expect(eventObs?.name).toBe("event-observation");+ expect(eventObs?.level).toBe("WARNING");+ expect(eventObs?.input).toBe("User action recorded");+ expect(eventObs?.metadata).toEqual({+ eventType: "click",+ target: "submit-button",+ });++ // Verify new observation types exist and have correct type+ const agentObs = createdObservations.find(+ (obs) => obs.type === "AGENT",+ );+ expect(agentObs).toBeDefined();+ expect(agentObs?.name).toBe("agent-observation");++ const toolObs = createdObservations.find((obs) => obs.type === "TOOL");+ expect(toolObs).toBeDefined();+ expect(toolObs?.name).toBe("tool-observation");++ const chainObs = createdObservations.find(+ (obs) => obs.type === "CHAIN",+ );+ expect(chainObs).toBeDefined();+ expect(chainObs?.name).toBe("chain-observation");++ const retrieverObs = createdObservations.find(+ (obs) => obs.type === "RETRIEVER",+ );+ expect(retrieverObs).toBeDefined();+ expect(retrieverObs?.name).toBe("retriever-observation");++ const evaluatorObs = createdObservations.find(+ (obs) => obs.type === "EVALUATOR",+ );+ expect(evaluatorObs).toBeDefined();+ expect(evaluatorObs?.name).toBe("evaluator-observation");+ // Test that input, output, and endTime can be null (optional fields)+ expect(evaluatorObs?.input).toBeNull();+ expect(evaluatorObs?.output).toBeNull();+ expect(evaluatorObs?.endTime).toBeNull();++ const embeddingObs = createdObservations.find(+ (obs) => obs.type === "EMBEDDING",+ );+ expect(embeddingObs).toBeDefined();+ expect(embeddingObs?.name).toBe("embedding-observation");++ const guardrailObs = createdObservations.find(+ (obs) => obs.type === "GUARDRAIL",+ );+ expect(guardrailObs).toBeDefined();+ expect(guardrailObs?.name).toBe("guardrail-observation");++ // Verify new observation types support model and cost attributes+ // The key verification is that new observation types now have model and cost fields populated+ // (even if with default values from the factory, proving the schema changes work)+ expect(agentObs?.model).toBe("claude-3-haiku");+ expect(agentObs?.input).toBe("Hello World");+ expect(agentObs?.output).toBe("Hello John");+ // Verify that model/cost fields are present (core functionality test)+ expect(agentObs?.usageDetails).toBeDefined();+ expect(agentObs?.costDetails).toBeDefined();++ expect(toolObs?.model).toBe("gpt-4o-mini");+ expect(toolObs?.input).toBe("Search web for information");+ expect(toolObs?.output).toBe("Found relevant results");+ expect(toolObs?.usageDetails).toBeDefined();+ expect(toolObs?.costDetails).toBeDefined();++ expect(chainObs?.model).toBe("gpt-4");+ expect(chainObs?.input).toBe("Process multi-step workflow");+ expect(chainObs?.output).toBe("Workflow completed");+ expect(chainObs?.usageDetails).toBeDefined();+ expect(chainObs?.costDetails).toBeDefined();++ expect(embeddingObs?.model).toBe("text-embedding-ada-002");+ expect(embeddingObs?.input).toBe("Text to embed");+ expect(embeddingObs?.output).toBe("Vector embedding generated");+ expect(embeddingObs?.usageDetails).toBeDefined();+ expect(embeddingObs?.costDetails).toBeDefined();+ }, 20_000);++ it("should filter observations by level parameter", async () => {+ const traceId = randomUUID();+ const timestamp = new Date();+ const timeValue = useEventsTable+ ? timestamp.getTime() * 1000+ : timestamp.getTime();+ const timeMultiplier = useEventsTable ? 1000 : 1;++ // Create a trace+ const createdTrace = createTrace({+ id: traceId,project_id: projectId,- name: "guardrail-observation",- type: "GUARDRAIL",- level: "DEFAULT",- start_time: timestamp.getTime() + 5000,- provided_cost_details: { input: 0.0001, output: 0, total: 0.0001 },- }),- ];-- await createTracesCh([createdTrace]);- await createObservationsCh(observations);-- const response = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- "/api/public/observations",- );-- expect(response.status).toBe(200);- expect(response.body.data).toBeDefined();- expect(response.body.meta).toBeDefined();- expect(response.body.meta.totalItems).toBeGreaterThanOrEqual(10);- expect(response.body.data.length).toBeGreaterThanOrEqual(10);-- // Find our created observations in the response- const createdObservations = response.body.data.filter(- (obs) => obs.traceId === traceId,- );- expect(createdObservations.length).toBe(10);-- // Verify data structure and content- const generationObs = createdObservations.find(- (obs) => obs.type === "GENERATION",- );- expect(generationObs).toBeDefined();- expect(generationObs?.name).toBe("generation-observation");- expect(generationObs?.level).toBe("DEFAULT");- expect(generationObs?.input).toBe("What is the capital of France?");- expect(generationObs?.output).toBe("The capital of France is Paris.");- expect(generationObs?.model).toBe("gpt-4");- expect(generationObs?.projectId).toBe(projectId);- expect(generationObs?.traceId).toBe(traceId);-- const spanObs = createdObservations.find((obs) => obs.type === "SPAN");- expect(spanObs).toBeDefined();- expect(spanObs?.name).toBe("span-observation");- expect(spanObs?.level).toBe("DEBUG");- expect(spanObs?.input).toBe("Processing request");- expect(spanObs?.output).toBe("Request processed successfully");-- const eventObs = createdObservations.find((obs) => obs.type === "EVENT");- expect(eventObs).toBeDefined();- expect(eventObs?.name).toBe("event-observation");- expect(eventObs?.level).toBe("WARNING");- expect(eventObs?.input).toBe("User action recorded");- expect(eventObs?.metadata).toEqual({- eventType: "click",- target: "submit-button",- });-- // Verify new observation types exist and have correct type- const agentObs = createdObservations.find((obs) => obs.type === "AGENT");- expect(agentObs).toBeDefined();- expect(agentObs?.name).toBe("agent-observation");-- const toolObs = createdObservations.find((obs) => obs.type === "TOOL");- expect(toolObs).toBeDefined();- expect(toolObs?.name).toBe("tool-observation");-- const chainObs = createdObservations.find((obs) => obs.type === "CHAIN");- expect(chainObs).toBeDefined();- expect(chainObs?.name).toBe("chain-observation");-- const retrieverObs = createdObservations.find(- (obs) => obs.type === "RETRIEVER",- );- expect(retrieverObs).toBeDefined();- expect(retrieverObs?.name).toBe("retriever-observation");-- const evaluatorObs = createdObservations.find(- (obs) => obs.type === "EVALUATOR",- );- expect(evaluatorObs).toBeDefined();- expect(evaluatorObs?.name).toBe("evaluator-observation");- // Test that input, output, and endTime can be null (optional fields)- expect(evaluatorObs?.input).toBeNull();- expect(evaluatorObs?.output).toBeNull();- expect(evaluatorObs?.endTime).toBeNull();-- const embeddingObs = createdObservations.find(- (obs) => obs.type === "EMBEDDING",- );- expect(embeddingObs).toBeDefined();- expect(embeddingObs?.name).toBe("embedding-observation");-- const guardrailObs = createdObservations.find(- (obs) => obs.type === "GUARDRAIL",- );- expect(guardrailObs).toBeDefined();- expect(guardrailObs?.name).toBe("guardrail-observation");-- // Verify new observation types support model and cost attributes- // The key verification is that new observation types now have model and cost fields populated- // (even if with default values from the factory, proving the schema changes work)- expect(agentObs?.model).toBe("claude-3-haiku");- expect(agentObs?.input).toBe("Hello World");- expect(agentObs?.output).toBe("Hello John");- // Verify that model/cost fields are present (core functionality test)- expect(agentObs?.usageDetails).toBeDefined();- expect(agentObs?.costDetails).toBeDefined();-- expect(toolObs?.model).toBe("gpt-4o-mini");- expect(toolObs?.input).toBe("Search web for information");- expect(toolObs?.output).toBe("Found relevant results");- expect(toolObs?.usageDetails).toBeDefined();- expect(toolObs?.costDetails).toBeDefined();-- expect(chainObs?.model).toBe("gpt-4");- expect(chainObs?.input).toBe("Process multi-step workflow");- expect(chainObs?.output).toBe("Workflow completed");- expect(chainObs?.usageDetails).toBeDefined();- expect(chainObs?.costDetails).toBeDefined();-- expect(embeddingObs?.model).toBe("text-embedding-ada-002");- expect(embeddingObs?.input).toBe("Text to embed");- expect(embeddingObs?.output).toBe("Vector embedding generated");- expect(embeddingObs?.usageDetails).toBeDefined();- expect(embeddingObs?.costDetails).toBeDefined();- }, 20_000);-- it("should filter observations by level parameter", async () => {- const traceId = randomUUID();- const timestamp = new Date();-- // Create a trace- const createdTrace = createTrace({- id: traceId,- project_id: projectId,- timestamp: timestamp.getTime(),+ timestamp: timestamp.getTime(),+ });++ // Create observations with different levels+ await createAndInsertObservations(useEventsTable, createdTrace, [+ {+ trace_id: traceId,+ project_id: projectId,+ name: "debug-observation",+ type: "EVENT",+ level: "DEBUG",+ start_time: timeValue,+ input: "Debug information",+ output: "Debug output",+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "default-observation",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue + 1000 * timeMultiplier,+ input: "Regular operation",+ output: "Operation completed",+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "warning-observation",+ type: "SPAN",+ level: "WARNING",+ start_time: timeValue + 2000 * timeMultiplier,+ input: "Warning condition detected",+ output: "Warning handled",+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "error-observation",+ type: "EVENT",+ level: "ERROR",+ start_time: timeValue + 3000 * timeMultiplier,+ input: "Error occurred",+ output: "Error logged",+ },+ ]);++ // Test filtering by DEBUG level+ const debugResponse = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations${queryParam}&traceId=${traceId}&level=DEBUG`,+ );++ expect(debugResponse.body.data.length).toBe(1);+ expect(debugResponse.body.data[0]?.level).toBe("DEBUG");+ expect(debugResponse.body.data[0]?.name).toBe("debug-observation");+ expect(debugResponse.body.data[0]?.input).toBe("Debug information");++ // Test filtering by DEFAULT level+ const defaultResponse = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations${queryParam}&traceId=${traceId}&level=DEFAULT`,+ );++ expect(defaultResponse.body.data.length).toBe(1);+ expect(defaultResponse.body.data[0]?.level).toBe("DEFAULT");+ expect(defaultResponse.body.data[0]?.name).toBe("default-observation");+ expect(defaultResponse.body.data[0]?.type).toBe("GENERATION");++ // Test filtering by WARNING level+ const warningResponse = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations${queryParam}&traceId=${traceId}&level=WARNING`,+ );++ expect(warningResponse.body.data.length).toBe(1);+ expect(warningResponse.body.data[0]?.level).toBe("WARNING");+ expect(warningResponse.body.data[0]?.name).toBe("warning-observation");+ expect(warningResponse.body.data[0]?.type).toBe("SPAN");++ // Test filtering by ERROR level+ const errorResponse = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations${queryParam}&traceId=${traceId}&level=ERROR`,+ );++ expect(errorResponse.body.data.length).toBe(1);+ expect(errorResponse.body.data[0]?.level).toBe("ERROR");+ expect(errorResponse.body.data[0]?.name).toBe("error-observation");+ expect(errorResponse.body.data[0]?.input).toBe("Error occurred");});- // Create observations with different levels- const observations = [- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "debug-observation",- type: "EVENT",- level: "DEBUG",- start_time: timestamp.getTime(),- input: "Debug information",- output: "Debug output",- }),- createObservation({- id: randomUUID(),- trace_id: traceId,+ it("should return empty results when filtering by level with no matches", async () => {+ const traceId = randomUUID();+ const timestamp = new Date();+ const timeValue = useEventsTable+ ? timestamp.getTime() * 1000+ : timestamp.getTime();+ const timeMultiplier = useEventsTable ? 1000 : 1;++ // Create a trace+ const createdTrace = createTrace({+ id: traceId,project_id: projectId,- name: "default-observation",- type: "GENERATION",- level: "DEFAULT",- start_time: timestamp.getTime() + 1000,- input: "Regular operation",- output: "Operation completed",- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "warning-observation",- type: "SPAN",- level: "WARNING",- start_time: timestamp.getTime() + 2000,- input: "Warning condition detected",- output: "Warning handled",- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "error-observation",- type: "EVENT",- level: "ERROR",- start_time: timestamp.getTime() + 3000,- input: "Error occurred",- output: "Error logged",- }),- ];-- await createTracesCh([createdTrace]);- await createObservationsCh(observations);-- // Test filtering by DEBUG level- const debugResponse = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?traceId=${traceId}&level=DEBUG`,- );-- expect(debugResponse.body.data.length).toBe(1);- expect(debugResponse.body.data[0]?.level).toBe("DEBUG");- expect(debugResponse.body.data[0]?.name).toBe("debug-observation");- expect(debugResponse.body.data[0]?.input).toBe("Debug information");-- // Test filtering by DEFAULT level- const defaultResponse = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?traceId=${traceId}&level=DEFAULT`,- );-- expect(defaultResponse.body.data.length).toBe(1);- expect(defaultResponse.body.data[0]?.level).toBe("DEFAULT");- expect(defaultResponse.body.data[0]?.name).toBe("default-observation");- expect(defaultResponse.body.data[0]?.type).toBe("GENERATION");-- // Test filtering by WARNING level- const warningResponse = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?traceId=${traceId}&level=WARNING`,- );-- expect(warningResponse.body.data.length).toBe(1);- expect(warningResponse.body.data[0]?.level).toBe("WARNING");- expect(warningResponse.body.data[0]?.name).toBe("warning-observation");- expect(warningResponse.body.data[0]?.type).toBe("SPAN");-- // Test filtering by ERROR level- const errorResponse = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?traceId=${traceId}&level=ERROR`,- );-- expect(errorResponse.body.data.length).toBe(1);- expect(errorResponse.body.data[0]?.level).toBe("ERROR");- expect(errorResponse.body.data[0]?.name).toBe("error-observation");- expect(errorResponse.body.data[0]?.input).toBe("Error occurred");- });-- it("should return empty results when filtering by level with no matches", async () => {- const traceId = randomUUID();- const timestamp = new Date();-- // Create a trace- const createdTrace = createTrace({- id: traceId,- project_id: projectId,- timestamp: timestamp.getTime(),+ timestamp: timestamp.getTime(),+ });++ // Create observations with only DEFAULT level+ await createAndInsertObservations(useEventsTable, createdTrace, [+ {+ trace_id: traceId,+ project_id: projectId,+ name: "default-observation-1",+ type: "EVENT",+ level: "DEFAULT",+ start_time: timeValue,+ },+ {+ trace_id: traceId,+ project_id: projectId,+ name: "default-observation-2",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue + 1000 * timeMultiplier,+ },+ ]);++ // Test filtering by ERROR level (should return no results)+ const errorResponse = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations${queryParam}&traceId=${traceId}&level=ERROR`,+ );++ expect(errorResponse.body.data.length).toBe(0);+ expect(errorResponse.body.meta.totalItems).toBe(0);+ expect(errorResponse.body.meta.totalPages).toBe(0);});-- // Create observations with only DEFAULT level- const observations = [- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "default-observation-1",- type: "EVENT",- level: "DEFAULT",- start_time: timestamp.getTime(),- }),- createObservation({- id: randomUUID(),- trace_id: traceId,- project_id: projectId,- name: "default-observation-2",- type: "GENERATION",- level: "DEFAULT",- start_time: timestamp.getTime() + 1000,- }),- ];-- await createTracesCh([createdTrace]);- await createObservationsCh(observations);-- // Test filtering by ERROR level (should return no results)- const errorResponse = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?traceId=${traceId}&level=ERROR`,- );-- expect(errorResponse.body.data.length).toBe(0);- expect(errorResponse.body.meta.totalItems).toBe(0);- expect(errorResponse.body.meta.totalPages).toBe(0);});- });+ };++ // Run tests with both implementations+ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ runTestSuite(true); // with events table+ }+ runTestSuite(false); // with observations table});diff --git a/web/src/__tests__/async/repositories/event-repository.servertest.ts b/web/src/__tests__/async/repositories/event-repository.servertest.tsindex 587c58d16b..a0f75c96ac 100644--- a/web/src/__tests__/async/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/event-repository.servertest.ts@@ -4,6 +4,8 @@ import {getObservationsWithModelDataFromEventsTable,getObservationsCountFromEventsTable,getObservationByIdFromEventsTable,+ getObservationsFromEventsTableForPublicApi,+ getObservationsCountFromEventsTableForPublicApi,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { randomUUID } from "crypto";@@ -332,6 +334,7 @@ describe("Clickhouse Events Repository Test", () => {maybe("Filter Tests", () => {describe("Timestamp Filters", () => {it("should filter observations by start time with >= operator", async () => {+ const uniqueProjectId = randomUUID();const traceId = randomUUID();const now = Date.now();const filterTime = new Date(now - 5000);@@ -340,7 +343,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "old-event-gte",@@ -349,7 +352,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "exact-event-gte",@@ -358,7 +361,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "new-event-gte",@@ -369,7 +372,7 @@ describe("Clickhouse Events Repository Test", () => {await createEventsCh(events);const result = await getObservationsWithModelDataFromEventsTable({- projectId,+ projectId: uniqueProjectId,filter: [{type: "datetime",@@ -382,15 +385,13 @@ describe("Clickhouse Events Repository Test", () => {offset: 0,});- const filteredObservations = result.filter(- (o) => o.traceId === traceId,- );- expect(filteredObservations.length).toBe(2);- const names = filteredObservations.map((o) => o.name).sort();+ expect(result.length).toBe(2);+ const names = result.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 uniqueProjectId = randomUUID();const traceId = randomUUID();const now = Date.now();const filterTime = new Date(now - 5000);@@ -399,7 +400,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "old-event-lte",@@ -408,7 +409,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "exact-event-lte",@@ -417,7 +418,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "new-event-lte",@@ -428,7 +429,7 @@ describe("Clickhouse Events Repository Test", () => {await createEventsCh(events);const result = await getObservationsWithModelDataFromEventsTable({- projectId,+ projectId: uniqueProjectId,filter: [{type: "datetime",@@ -441,15 +442,13 @@ describe("Clickhouse Events Repository Test", () => {offset: 0,});- const filteredObservations = result.filter(- (o) => o.traceId === traceId,- );- expect(filteredObservations.length).toBe(2);- const names = filteredObservations.map((o) => o.name).sort();+ expect(result.length).toBe(2);+ const names = result.map((o) => o.name).sort();expect(names).toEqual(["exact-event-lte", "old-event-lte"]);});it("should filter observations by end time", async () => {+ const uniqueProjectId = randomUUID();const traceId = randomUUID();const now = Date.now();const filterTime = new Date(now - 2000);@@ -458,7 +457,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "event-no-end",@@ -468,7 +467,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "event-old-end",@@ -478,7 +477,7 @@ describe("Clickhouse Events Repository Test", () => {createEvent({id: randomUUID(),span_id: randomUUID(),- project_id: projectId,+ project_id: uniqueProjectId,trace_id: traceId,type: "SPAN",name: "event-recent-end",@@ -490,7 +489,7 @@ describe("Clickhouse Events Repository Test", () => {await createEventsCh(events);const result = await getObservationsWithModelDataFromEventsTable({- projectId,+ projectId: uniqueProjectId,filter: [{type: "datetime",@@ -503,11 +502,8 @@ describe("Clickhouse Events Repository Test", () => {offset: 0,});- const filteredObservations = result.filter(- (o) => o.traceId === traceId,- );- expect(filteredObservations.length).toBe(1);- expect(filteredObservations[0].name).toBe("event-recent-end");+ expect(result.length).toBe(1);+ expect(result[0].name).toBe("event-recent-end");});});@@ -686,9 +682,9 @@ describe("Clickhouse Events Repository Test", () => {const traceId1 = randomUUID();const traceId2 = randomUUID();const traceId3 = randomUUID();- const userId1 = "user-exclude-1";- const userId2 = "user-exclude-2";- const userId3 = "user-include";+ const userId1 = `user-exclude-1-${randomUUID()}`;+ const userId2 = `user-exclude-2-${randomUUID()}`;+ const userId3 = `user-include-${randomUUID()}`;const events = [createEvent({@@ -725,6 +721,12 @@ describe("Clickhouse Events Repository Test", () => {const result = await getObservationsWithModelDataFromEventsTable({projectId,filter: [+ {+ type: "stringOptions",+ column: "traceId",+ operator: "any of",+ value: [traceId1, traceId2, traceId3],+ },{type: "stringOptions",column: "userId",@@ -736,11 +738,9 @@ describe("Clickhouse Events Repository Test", () => {offset: 0,});- const filteredObservations = result.filter((o) =>- [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),- );- expect(filteredObservations.length).toBe(1);- expect(filteredObservations[0].name).toBe("included");+ expect(result.length).toBe(1);+ expect(result[0].name).toBe("included");+ expect(result[0].traceId).toBe(traceId3);});it("should handle observations with null user IDs", async () => {@@ -1099,4 +1099,334 @@ describe("Clickhouse Events Repository Test", () => {).rejects.toThrow();});});++ maybe("getObservationsFromEventsTableForPublicApi", () => {+ it("should return observations with pagination", async () => {+ const uniqueProjectId = randomUUID();+ const traceId = randomUUID();++ const events = Array.from({ length: 5 }, (_, i) =>+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "GENERATION",+ name: `pub-api-test-${i}`,+ start_time: (Date.now() + i * 1000) * 1000,+ }),+ );++ await createEventsCh(events);++ const result = await getObservationsFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 1,+ limit: 3,+ });++ expect(result).toBeDefined();+ expect(result.length).toBeLessThanOrEqual(3);++ // Fetching the second page+ const resultPage2 = await getObservationsFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 2,+ limit: 3,+ });++ expect(resultPage2).toBeDefined();+ expect(resultPage2.length).toBeLessThanOrEqual(2);++ // Count should ignore pagination+ const count = await getObservationsCountFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 1,+ limit: 3,+ });++ expect(count).toBe(5);+ });++ it("should filter by traceId", async () => {+ const uniqueProjectId = randomUUID();+ const traceId1 = randomUUID();+ const traceId2 = randomUUID();++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId1,+ type: "GENERATION",+ name: "trace-1-obs",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId2,+ type: "GENERATION",+ name: "trace-2-obs",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 1,+ limit: 10,+ traceId: traceId1,+ });++ expect(result.length).toBe(1);+ expect(result[0]?.traceId).toBe(traceId1);+ expect(result[0]?.name).toBe("trace-1-obs");+ });++ it("should filter by type", async () => {+ const uniqueProjectId = randomUUID();+ const traceId = randomUUID();++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "generation-obs",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "SPAN",+ name: "span-obs",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 1,+ limit: 10,+ type: "GENERATION",+ });++ expect(result.length).toBe(1);+ expect(result[0]?.type).toBe("GENERATION");+ expect(result[0]?.name).toBe("generation-obs");+ });++ it("should filter by level", async () => {+ const uniqueProjectId = randomUUID();+ const traceId = randomUUID();++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "EVENT",+ level: "ERROR",+ name: "error-obs",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "EVENT",+ level: "DEFAULT",+ name: "default-obs",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 1,+ limit: 10,+ level: "ERROR",+ });++ expect(result.length).toBe(1);+ expect(result[0]?.level).toBe("ERROR");+ expect(result[0]?.name).toBe("error-obs");+ });++ it("should filter by time range", async () => {+ const uniqueProjectId = randomUUID();+ const traceId = randomUUID();+ const now = Date.now();+ const fromTime = new Date(now - 5000).toISOString();+ const toTime = new Date(now + 5000).toISOString();++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "SPAN",+ name: "old-obs",+ start_time: (now - 10000) * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "SPAN",+ name: "recent-obs",+ start_time: now * 1000,+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "SPAN",+ name: "future-obs",+ start_time: (now + 10000) * 1000,+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 1,+ limit: 10,+ fromStartTime: fromTime,+ toStartTime: toTime,+ });++ expect(result.length).toBe(1);+ expect(result[0]?.name).toBe("recent-obs");+ });++ it("should combine multiple filters", async () => {+ const uniqueProjectId = randomUUID();+ const userId = "test-user";++ // Create events in different traces so userId filtering works at trace level+ const trace1 = randomUUID();+ const trace2 = randomUUID();++ const events = [+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: trace1,+ user_id: userId,+ type: "GENERATION",+ level: "ERROR",+ name: "matching-obs",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: trace1,+ user_id: userId,+ type: "SPAN",+ level: "ERROR",+ name: "wrong-type",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: trace2,+ user_id: "other-user",+ type: "GENERATION",+ level: "ERROR",+ name: "wrong-user",+ }),+ ];++ await createEventsCh(events);++ const result = await getObservationsFromEventsTableForPublicApi({+ projectId: uniqueProjectId,+ page: 1,+ limit: 10,+ userId,+ type: "GENERATION",+ level: "ERROR",+ });++ // Should only return "matching-obs" because:+ // - userId filters at trace level (excludes trace2 with "other-user")+ // - type="GENERATION" excludes "wrong-type" (SPAN)+ expect(result.length).toBe(1);+ expect(result[0]?.name).toBe("matching-obs");+ });++ it("should enrich observations with model data", async () => {+ const traceId = randomUUID();+ const modelId = randomUUID();++ // Create a model with pricing+ await prisma.model.create({+ data: {+ id: modelId,+ projectId: projectId,+ modelName: `test-model-${modelId}`,+ matchPattern: `(?i)^(test-model-${modelId})$`,+ startDate: new Date("2023-01-01"),+ unit: "TOKENS",+ Price: {+ create: [+ {+ usageType: "input",+ price: 0.01,+ },+ {+ usageType: "output",+ price: 0.02,+ },+ ],+ },+ },+ });++ const event = createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "model-enriched-obs",+ model_id: modelId,+ provided_model_name: `test-model-${modelId}`,+ });++ await createEventsCh([event]);++ const result = await getObservationsFromEventsTableForPublicApi({+ projectId: projectId,+ traceId: traceId,+ page: 1,+ limit: 10,+ });++ expect(result.length).toBe(1);+ expect(result[0]?.internalModelId).toBe(modelId);+ expect(Number(result[0]?.inputPrice)).toBeCloseTo(0.01, 5);+ expect(Number(result[0]?.outputPrice)).toBeCloseTo(0.02, 5);++ // Cleanup+ await prisma.model.delete({ where: { id: modelId } });+ });+ });});diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.tsindex eb7325d779..b54375f257 100644--- a/web/src/features/public-api/server/dailyMetrics.ts+++ b/web/src/features/public-api/server/dailyMetrics.ts@@ -1,4 +1,4 @@-import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";+import { convertApiProvidedFilterToClickhouseFilter } from "@langfuse/shared/src/server";import {convertDateToClickhouseDateTime,queryClickhouse,diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.tsindex ef1656642a..468490b95f 100644--- a/web/src/features/public-api/server/observations.ts+++ b/web/src/features/public-api/server/observations.ts@@ -1,4 +1,7 @@-import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";+import {+ convertApiProvidedFilterToClickhouseFilter,+ createPublicApiObservationsColumnMapping,+} from "@langfuse/shared/src/server";import {StringFilter,type ObservationRecordReadType,@@ -147,80 +150,11 @@ export const getObservationsCountForPublicApi = async (props: QueryType) => {});};-const filterParams = [- {- id: "userId",- clickhouseSelect: "user_id",- filterType: "StringFilter",- clickhouseTable: "traces",- clickhousePrefix: "t",- },- {- id: "traceId",- clickhouseSelect: "trace_id",- filterType: "StringFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "name",- clickhouseSelect: "name",- filterType: "StringFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "level",- clickhouseSelect: "level",- filterType: "StringFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "type",- clickhouseSelect: "type",- filterType: "StringFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "parentObservationId",- clickhouseSelect: "parent_observation_id",- filterType: "StringFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "fromStartTime",- clickhouseSelect: "start_time",- operator: ">=" as const,- filterType: "DateTimeFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "toStartTime",- clickhouseSelect: "start_time",- operator: "<" as const,- filterType: "DateTimeFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "version",- clickhouseSelect: "version",- filterType: "StringFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },- {- id: "environment",- clickhouseSelect: "environment",- filterType: "StringFilter",- clickhouseTable: "observations",- clickhousePrefix: "o",- },-];+const filterParams = createPublicApiObservationsColumnMapping(+ "observations",+ "o",+ "parent_observation_id",+);const generateFilter = (filter: QueryType) => {const observationsFilter = convertApiProvidedFilterToClickhouseFilter(diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.tsindex bb41048333..59c9922094 100644--- a/web/src/features/public-api/server/scores.ts+++ b/web/src/features/public-api/server/scores.ts@@ -1,4 +1,4 @@-import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";+import { convertApiProvidedFilterToClickhouseFilter } from "@langfuse/shared/src/server";import {convertToScore,StringFilter,diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsindex b76681851e..daf1be6bca 100644--- a/web/src/features/public-api/server/traces.ts+++ b/web/src/features/public-api/server/traces.ts@@ -1,4 +1,4 @@-import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";+import { convertApiProvidedFilterToClickhouseFilter } from "@langfuse/shared/src/server";import {convertDateToClickhouseDateTime,queryClickhouse,diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.tsindex f590e08123..06466b2a0e 100644--- a/web/src/features/public-api/types/observations.ts+++ b/web/src/features/public-api/types/observations.ts@@ -160,6 +160,11 @@ export const transformDbToApiObservation = (* Endpoints*/+const useEventsTableSchema = z+ .union([z.literal("true"), z.literal("false"), z.boolean()])+ .transform((val) => val === "true" || val === true)+ .nullish();+// GET /observationsexport const GetObservationsV1Query = z.object({...publicApiPaginationZod,@@ -173,6 +178,7 @@ export const GetObservationsV1Query = z.object({environment: z.union([z.array(z.string()), z.string()]).nullish(),fromStartTime: stringDateTime,toStartTime: stringDateTime,+ useEventsTable: useEventsTableSchema,});export const GetObservationsV1Response = z.object({@@ -184,5 +190,6 @@ export const GetObservationsV1Response = z// GET /observations/{observationId}export const GetObservationV1Query = z.object({observationId: z.string(),+ useEventsTable: useEventsTableSchema,});export const GetObservationV1Response = APIObservation;diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].tsindex 3aff0e7116..8d862840df 100644--- a/web/src/pages/api/public/observations/[observationId].ts+++ b/web/src/pages/api/public/observations/[observationId].ts@@ -10,7 +10,9 @@ import { LangfuseNotFoundError } from "@langfuse/shared";import {enrichObservationWithModelData,getObservationById,+ getObservationByIdFromEventsTable,} from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";export default withMiddlewares({GET: createAuthedProjectAPIRoute({@@ -18,12 +20,26 @@ export default withMiddlewares({querySchema: GetObservationV1Query,responseSchema: GetObservationV1Response,fn: async ({ query, auth }) => {- const clickhouseObservation = await getObservationById({- id: query.observationId,- projectId: auth.scope.projectId,- fetchWithInputOutput: true,- preferredClickhouseService: "ReadOnly",- });+ // Use events table if query parameter is explicitly set, otherwise use environment variable+ const useEventsTable =+ query.useEventsTable !== undefined && query.useEventsTable !== null+ ? query.useEventsTable === true+ : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;++ const clickhouseObservation = useEventsTable+ ? await getObservationByIdFromEventsTable({+ id: query.observationId,+ projectId: auth.scope.projectId,+ fetchWithInputOutput: true,+ preferredClickhouseService: "ReadOnly",+ })+ : await getObservationById({+ id: query.observationId,+ projectId: auth.scope.projectId,+ fetchWithInputOutput: true,+ preferredClickhouseService: "ReadOnly",+ });+if (!clickhouseObservation) {throw new LangfuseNotFoundError("Observation not found within authorized project",diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.tsindex 55c01f7c28..95a553951c 100644--- a/web/src/pages/api/public/observations/index.ts+++ b/web/src/pages/api/public/observations/index.ts@@ -1,4 +1,9 @@import { prisma } from "@langfuse/shared/src/db";+import {+ getObservationsFromEventsTableForPublicApi,+ getObservationsCountFromEventsTableForPublicApi,+} from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";@@ -21,8 +26,8 @@ export default withMiddlewares({fn: async ({ query, auth }) => {const filterProps = {projectId: auth.scope.projectId,- page: query.page ?? undefined,- limit: query.limit ?? undefined,+ page: query.page,+ limit: query.limit,traceId: query.traceId ?? undefined,userId: query.userId ?? undefined,level: query.level ?? undefined,@@ -34,6 +39,31 @@ export default withMiddlewares({toStartTime: query.toStartTime ?? undefined,version: query.version ?? undefined,};++ // Use events table if query parameter is explicitly set, otherwise use environment variable+ const useEventsTable =+ query.useEventsTable !== undefined && query.useEventsTable !== null+ ? query.useEventsTable === true+ : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;++ if (useEventsTable) {+ const [items, count] = await Promise.all([+ getObservationsFromEventsTableForPublicApi(filterProps),+ getObservationsCountFromEventsTableForPublicApi(filterProps),+ ]);++ return {+ data: items.map(transformDbToApiObservation),+ meta: {+ page: query.page,+ limit: query.limit,+ totalItems: count,+ totalPages: Math.ceil(count / query.limit),+ },+ };+ }++ // Legacy code path using observations tableconst [items, count] = await Promise.all([generateObservationsForPublicApi(filterProps),getObservationsCountForPublicApi(filterProps),