Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(api): Traces public API v1 re-implementation (#10029)

Valery Meleshkin7112d229f3ee
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index a946f58e9b..4b573028b5 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -48,7 +48,7 @@ const EVENTS_FIELDS = {
// I/O & metadata fields
input: "e.input",
output: "e.output",
- metadata: "e.metadata",
+ metadata: "mapFromArrays(e.metadata_names, e.metadata_values) as metadata",
// Calculated fields
latency:
@@ -140,22 +140,24 @@ const EVENTS_AGGREGATION_FIELDS = {
projectId: "project_id",
// Aggregated fields
- name: "argMaxIf(name, event_ts, isNull(parent_span_id)) AS name",
+ name: "argMaxIf(name, event_ts, parent_span_id = '') AS name",
timestamp: "min(start_time) as timestamp",
- environment: "argMax(environment, event_ts) AS environment",
- version: "argMax(version, event_ts) AS version",
- session_id: "argMax(session_id, event_ts) AS session_id",
- user_id: "argMax(user_id, event_ts) AS user_id",
- input: "argMax(input, event_ts) AS input",
- output: "argMax(output, event_ts) AS output",
- metadata: "argMax(metadata, event_ts) AS metadata",
+ environment:
+ "argMaxIf(environment, event_ts, environment <> '') AS environment",
+ version: "argMaxIf(version, event_ts, version <> '') AS version",
+ session_id: "argMaxIf(session_id, event_ts, session_id <> '') AS session_id",
+ user_id: "argMaxIf(user_id, event_ts, user_id <> '') AS user_id",
+ input: "argMaxIf(input, event_ts, parent_span_id = '') AS input",
+ output: "argMaxIf(output, event_ts, parent_span_id = '') AS output",
+ metadata:
+ "argMaxIf(mapFromArrays(e.metadata_names, e.metadata_values), event_ts, parent_span_id = '') AS metadata",
created_at: "min(created_at) AS created_at",
updated_at: "max(updated_at) AS updated_at",
total_cost: "sum(total_cost) AS total_cost",
latency_milliseconds:
- "date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) AS latency_milliseconds",
+ "date_diff('millisecond', min(start_time), greatest(max(start_time), max(end_time))) AS latency_milliseconds",
observation_ids:
- "groupUniqArrayIf(span_id, isNotNull(span_id) AND span_id != '') AS observation_ids",
+ "groupUniqArrayIf(span_id, span_id <> '') AS observation_ids",
// Legacy fields for backward compatibility
tags: "array() AS tags",
@@ -494,7 +496,7 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
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`,
+ `leftUTF8(input_truncated, ${this.ioFields.charLimit}) as input, leftUTF8(output_truncated, ${this.ioFields.charLimit}) as output`,
);
} else {
fieldExpressions.push("input, output");
diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
index 22be40863c..1d46bfb593 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
@@ -98,3 +98,42 @@ export const eventsScoresAggregation = (
return { query, params: queryParams };
};
+
+interface EventsTracesScoresAggregationParams {
+ projectId: string;
+ startTimeFrom?: string | null;
+}
+
+/**
+ * Scores CTE for trace-level queries.
+ * Aggregates scores that belong to traces (not observations).
+ *
+ * Returns a query and params object that can be passed directly to withCTE.
+ */
+export const eventsTracesScoresAggregation = (
+ params: EventsTracesScoresAggregationParams,
+): { query: string; params: Record<string, any> } => {
+ const queryParams: Record<string, any> = {
+ projectId: params.projectId,
+ };
+
+ if (params.startTimeFrom) {
+ queryParams.startTimeFrom = params.startTimeFrom;
+ }
+
+ const query = `
+ SELECT
+ trace_id,
+ project_id,
+ groupUniqArray(id) as score_ids
+ FROM scores
+ WHERE project_id = {projectId: String}
+ AND observation_id IS NULL
+ ${params.startTimeFrom ? `AND timestamp >= {startTimeFrom: DateTime64(3)}` : ""}
+ GROUP BY
+ trace_id,
+ project_id
+ `.trim();
+
+ return { query, params: queryParams };
+};
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index c67f787126..d46d29ddc1 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -23,6 +23,8 @@ export { clickhouseSearchCondition } from "./clickhouse-sql/search";
export {
convertApiProvidedFilterToClickhouseFilter,
createPublicApiObservationsColumnMapping,
+ createPublicApiTracesColumnMapping,
+ createTracesUiColumnDefinitions,
deriveFilters,
type ApiColumnMapping,
} from "./public-api-filter-builder";
diff --git a/packages/shared/src/server/queries/public-api-filter-builder.ts b/packages/shared/src/server/queries/public-api-filter-builder.ts
index 8067389829..5576ec340c 100644
--- a/packages/shared/src/server/queries/public-api-filter-builder.ts
+++ b/packages/shared/src/server/queries/public-api-filter-builder.ts
@@ -23,6 +23,124 @@ export type ApiColumnMapping = {
clickhousePrefix?: string;
};
+/**
+ * Base column definition for traces table mappings
+ * Single source of truth for all trace column mappings
+ */
+const TRACES_COLUMN_DEFINITIONS = [
+ {
+ id: "timestamp",
+ name: "Timestamp",
+ column: "timestamp",
+ filterType: "DateTimeFilter",
+ },
+ {
+ id: "userId",
+ name: "User ID",
+ column: "user_id",
+ filterType: "StringFilter",
+ },
+ { id: "name", name: "Name", column: "name", filterType: "StringFilter" },
+ {
+ id: "environment",
+ name: "Environment",
+ column: "environment",
+ filterType: "StringOptionsFilter",
+ },
+ {
+ id: "metadata",
+ name: "Metadata",
+ column: "metadata",
+ filterType: "StringObjectFilter",
+ },
+ {
+ id: "sessionId",
+ name: "Session ID",
+ column: "session_id",
+ filterType: "StringFilter",
+ },
+ {
+ id: "version",
+ name: "Version",
+ column: "version",
+ filterType: "StringFilter",
+ },
+ {
+ id: "release",
+ name: "Release",
+ column: "release",
+ filterType: "StringFilter",
+ },
+ {
+ id: "tags",
+ name: "Tags",
+ column: "tags",
+ filterType: "ArrayOptionsFilter",
+ },
+] as const;
+
+/**
+ * Convenience function: Get just the simple filter mappings for public API
+ */
+export function createPublicApiTracesColumnMapping(
+ tableName: "traces" | "events",
+ tablePrefix: "t" | "e",
+): ApiColumnMapping[] {
+ const timestampColumn = "timestamp";
+ const simpleFilters: ApiColumnMapping[] = [];
+ for (const def of TRACES_COLUMN_DEFINITIONS) {
+ // For timestamp filters, create fromTimestamp and toTimestamp
+ if (def.id === "timestamp") {
+ simpleFilters.push(
+ {
+ id: "fromTimestamp",
+ clickhouseSelect: timestampColumn,
+ operator: ">=" as const,
+ filterType: def.filterType,
+ clickhouseTable: tableName,
+ clickhousePrefix: tablePrefix,
+ },
+ {
+ id: "toTimestamp",
+ clickhouseSelect: timestampColumn,
+ operator: "<" as const,
+ filterType: def.filterType,
+ clickhouseTable: tableName,
+ clickhousePrefix: tablePrefix,
+ },
+ );
+ } else {
+ // Regular column mapping for simple filters
+ simpleFilters.push({
+ id: def.id,
+ clickhouseSelect: def.column,
+ filterType: def.filterType,
+ clickhouseTable: tableName,
+ clickhousePrefix: tablePrefix,
+ });
+ }
+ }
+ return simpleFilters;
+}
+
+/**
+ * Convenience function: Get just the UI column definitions for advanced filters
+ */
+export function createTracesUiColumnDefinitions(
+ tableName: "traces" | "events",
+ tablePrefix: "t" | "e",
+) {
+ return TRACES_COLUMN_DEFINITIONS.map((def) => {
+ return {
+ uiTableName: def.name,
+ uiTableId: def.id,
+ clickhouseTableName: tableName,
+ clickhouseSelect: def.column,
+ queryPrefix: tablePrefix,
+ };
+ });
+}
+
/**
* Factory function to create public API column mappings for events/observations tables.
* Eliminates duplication between events and observations filter mappings.
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index 6f57d155b4..a6e2e39370 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -114,6 +114,16 @@ export const traceRecordBaseSchema = z.object({
is_deleted: z.number(),
});
+export const traceRecordExtraFields = z.object({
+ observations: z.array(z.string()).optional(),
+ scores: z.array(z.string()).optional(),
+ totalCost: z.number().optional(),
+ latency: z.number().optional(),
+ htmlPath: z.string().nullable(),
+});
+
+export type TraceRecordExtraFieldsType = z.infer<typeof traceRecordExtraFields>;
+
export const traceRecordReadSchema = traceRecordBaseSchema.extend({
timestamp: clickhouseStringDateSchema,
created_at: clickhouseStringDateSchema,
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 9be90b9b3f..a877ca0e63 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -9,12 +9,15 @@ import {
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { recordDistribution } from "../instrumentation";
import { logger } from "../logger";
+import { convertClickhouseTracesListToDomain } from "./traces_converters";
import {
DateTimeFilter,
FilterList,
FullObservations,
orderByToClickhouseSql,
createPublicApiObservationsColumnMapping,
+ createPublicApiTracesColumnMapping,
+ createTracesUiColumnDefinitions,
deriveFilters,
type ApiColumnMapping,
ObservationPriceFields,
@@ -24,6 +27,7 @@ import type { FilterState } from "../../types";
import {
eventsScoresAggregation,
eventsTracesAggregation,
+ eventsTracesScoresAggregation,
} from "../queries/clickhouse-sql/query-fragments";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
@@ -38,7 +42,10 @@ import {
ObservationTableQuery,
} from "./observations";
import { convertObservation } from "./observations_converters";
-import { EventsQueryBuilder } from "../queries/clickhouse-sql/event-query-builder";
+import {
+ EventsQueryBuilder,
+ CTEQueryBuilder,
+} from "../queries/clickhouse-sql/event-query-builder";
type ObservationsTableQueryResultWitouhtTraceFields = Omit<
ObservationsTableQueryResult,
@@ -111,11 +118,15 @@ const enrichObservationsWithTraceFields = async (
* 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 extractTimeFilter = (
+ filter: FilterList,
+ tableName: "events" | "traces" = "events",
+ fieldName: "start_time" | "timestamp" = "start_time",
+): string | null => {
const timeFilter = filter.find(
(f) =>
- f.clickhouseTable === "events" &&
- f.field === "start_time" &&
+ f.clickhouseTable === tableName &&
+ f.field === fieldName &&
(f.operator === ">=" || f.operator === ">"),
);
@@ -125,11 +136,44 @@ const extractTimeFilter = (filter: FilterList): string | null => {
};
/**
- * Column mapping for public API filters on events table
+ * Column mapping for public API filters on events table (observations)
*/
const PUBLIC_API_EVENTS_COLUMN_MAPPING: ApiColumnMapping[] =
createPublicApiObservationsColumnMapping("events", "e", "parent_span_id");
+/**
+ * Column mappings for traces aggregated from events table
+ */
+const PUBLIC_API_TRACES_COLUMN_MAPPING = createPublicApiTracesColumnMapping(
+ "traces",
+ "t",
+);
+
+const TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS =
+ createTracesUiColumnDefinitions("traces", "t");
+
+/**
+ * Order by columns for traces CTE (post-aggregation)
+ */
+const allowedOrderByIds = [
+ "timestamp",
+ "name",
+ "userId",
+ "sessionId",
+ "environment",
+ "version",
+ "release",
+];
+const TRACES_ORDER_BY_COLUMNS = TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS.filter(
+ (col) => allowedOrderByIds.includes(col.uiTableId),
+).map((col) => ({
+ ...col,
+ // Adjust column names that change after aggregation (start_time -> timestamp)
+ clickhouseSelect:
+ col.uiTableId === "timestamp" ? "timestamp" : col.clickhouseSelect,
+ queryPrefix: "t", // Use 't' prefix because we're selecting from traces CTE
+}));
+
export const getObservationsCountFromEventsTable = async (
opts: ObservationTableQuery,
) => {
@@ -368,7 +412,6 @@ const getObservationByIdFromEventsTableInternal = async ({
renderingProps?: RenderingProps;
preferredClickhouseService?: PreferredClickhouseService;
}) => {
- // Build query using EventsQueryBuilder with automatic param tracking
const queryBuilder = new EventsQueryBuilder({ projectId })
.selectFieldSet("byIdBase", "byIdModel", "byIdPrompt", "byIdTimestamps")
.when(fetchWithInputOutput, (b) =>
@@ -534,3 +577,220 @@ export const getObservationsCountFromEventsTableForPublicApi = async (
});
return Number(countResult[0].count);
};
+
+type PublicApiTracesQuery = {
+ projectId: string;
+ page: number;
+ limit: number;
+ userId?: string;
+ name?: string;
+ tags?: string | string[];
+ sessionId?: string;
+ version?: string;
+ release?: string;
+ environment?: string | string[];
+ fromTimestamp?: string;
+ toTimestamp?: string;
+ fields?: string[];
+ advancedFilters?: FilterState;
+ orderBy?: { column: string; order: "ASC" | "DESC" } | null;
+};
+
+/**
+ * Internal implementation for public API traces queries.
+ * Uses eventsTracesAggregation to create a traces CTE that
+ * behaves similarly to the old traces table.
+ */
+const getTracesFromEventsTableForPublicApiInternal = async <T>(
+ opts: PublicApiTracesQuery & { select: "rows" | "count" },
+): Promise<Array<T>> => {
+ const {
+ projectId,
+ page,
+ limit,
+ advancedFilters,
+ fields,
+ orderBy,
+ ...filterParams
+ } = opts;
+
+ // Determine which field groups are requested
+ const includeIO = Boolean(fields?.includes("io"));
+ const includeScores = Boolean(fields?.includes("scores"));
+ const includeObservations = Boolean(fields?.includes("observations"));
+ const includeMetrics = Boolean(fields?.includes("metrics"));
+
+ // Convert and merge simple and advanced filters
+ const tracesFilter = deriveFilters(
+ { ...filterParams, projectId, page, limit },
+ PUBLIC_API_TRACES_COLUMN_MAPPING,
+ advancedFilters,
+ TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS,
+ );
+
+ // Extract time filter for cut-off point in eventsTracesAggregation
+ // After aggregation, the time column is "timestamp" (not "start_time")
+ const startTimeFrom = extractTimeFilter(tracesFilter, "traces", "timestamp");
+
+ const appliedFilter = tracesFilter.apply();
+
+ // Build traces CTE using eventsTracesAggregation WITHOUT filters
+ // Filters must be applied AFTER aggregation to ensure filters on aggregated
+ // fields (like timestamp or version) are applied correctly
+ const tracesBuilder = eventsTracesAggregation({
+ projectId,
+ startTimeFrom,
+ });
+
+ // Build the final query using CTEQueryBuilder
+ let queryBuilder = new CTEQueryBuilder()
+ .withCTEFromBuilder("traces", tracesBuilder)
+ .from("traces", "t")
+ .where(appliedFilter);
+
+ if (includeScores) {
+ const scoresCTE = eventsTracesScoresAggregation({
+ projectId,
+ startTimeFrom,
+ });
+ queryBuilder = queryBuilder
+ .withCTE("score_stats", {
+ ...scoresCTE,
+ schema: ["trace_id", "project_id", "score_ids"],
+ })
+ .leftJoin(
+ "score_stats",
+ "s",
+ "ON s.trace_id = t.id AND s.project_id = t.project_id",
+ );
+ }
+
+ // Select fields based on query type and field groups
+ if (opts.select === "count") {
+ queryBuilder.select("count() as count");
+ } else {
+ // Build select list
+ queryBuilder = queryBuilder.selectColumns(
+ "t.id",
+ "t.project_id",
+ "t.timestamp",
+ "t.name",
+ "t.environment",
+ "t.session_id",
+ "t.user_id",
+ "t.version",
+ "t.created_at",
+ "t.updated_at",
+ "t.tags",
+ "t.bookmarked",
+ "t.public",
+ "t.release",
+ );
+
+ queryBuilder.select(
+ "CONCAT('/project/', t.project_id, '/traces/', t.id) as htmlPath",
+ );
+
+ // Conditionally include other field groups
+ if (includeIO) {
+ queryBuilder = queryBuilder.selectColumns(
+ "t.input",
+ "t.output",
+ "t.metadata",
+ );
+ }
+ if (includeScores) {
+ queryBuilder.select("s.score_ids as scores");
+ }
+ if (includeObservations) {
+ queryBuilder.select("t.observation_ids as observations");
+ }
+ if (includeMetrics) {
+ queryBuilder.select(
+ "t.total_cost as totalCost",
+ "COALESCE(t.latency_milliseconds / 1000, 0) as latency",
+ );
+ }
+
+ const chOrderBy =
+ orderByToClickhouseSql(
+ orderBy ? [orderBy] : [],
+ TRACES_ORDER_BY_COLUMNS,
+ ) || "ORDER BY t.timestamp DESC";
+
+ queryBuilder.orderBy(chOrderBy).limit(limit, (page - 1) * limit);
+ }
+
+ const { query, params } = queryBuilder.buildWithParams();
+
+ const result = await measureAndReturn({
+ operationName: `getTracesFromEventsTableForPublicApi_${opts.select}`,
+ projectId,
+ input: {
+ params,
+ tags: {
+ feature: "tracing",
+ type: "traces",
+ 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 traces list from events table for public API.
+ * Aggregates events by trace_id to rebuild traces with observation metrics.
+ */
+export const getTracesFromEventsTableForPublicApi = async (
+ opts: PublicApiTracesQuery,
+): Promise<Array<any>> => {
+ const requestedFields = opts.fields ?? [
+ "core",
+ "io",
+ "scores",
+ "observations",
+ "metrics",
+ ];
+ const includeScores = requestedFields.includes("scores");
+ const includeObservations = requestedFields.includes("observations");
+ const includeMetrics = requestedFields.includes("metrics");
+
+ const result = await getTracesFromEventsTableForPublicApiInternal<any>({
+ ...opts,
+ select: "rows",
+ });
+
+ // Convert ClickHouse format to domain format and handle field groups
+ return convertClickhouseTracesListToDomain(result, {
+ scores: includeScores,
+ observations: includeObservations,
+ metrics: includeMetrics,
+ });
+};
+
+/**
+ * Get count of traces from events table for public API.
+ * Uses same aggregation as list query to ensure consistent filtering.
+ */
+export const getTracesCountFromEventsTableForPublicApi = async (
+ opts: PublicApiTracesQuery,
+): Promise<number> => {
+ const countResult = await getTracesFromEventsTableForPublicApiInternal<{
+ count: string;
+ }>({
+ ...opts,
+ select: "count",
+ });
+ return Number(countResult[0].count);
+};
diff --git a/packages/shared/src/server/repositories/traces_converters.ts b/packages/shared/src/server/repositories/traces_converters.ts
index aa52f19161..57f38804bb 100644
--- a/packages/shared/src/server/repositories/traces_converters.ts
+++ b/packages/shared/src/server/repositories/traces_converters.ts
@@ -1,5 +1,5 @@
import { parseClickhouseUTCDateTimeFormat } from "./clickhouse";
-import { TraceRecordReadType } from "./definitions";
+import { TraceRecordExtraFieldsType, TraceRecordReadType } from "./definitions";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
import { TraceDomain } from "../../domain";
import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
@@ -59,3 +59,24 @@ export const convertClickhouseToDomain = (
updatedAt: parseClickhouseUTCDateTimeFormat(record.updated_at),
};
};
+
+export const convertClickhouseTracesListToDomain = (
+ result: Array<TraceRecordReadType & TraceRecordExtraFieldsType>,
+ include: { observations: boolean; scores: boolean; metrics: boolean },
+): Array<TraceDomain & TraceRecordExtraFieldsType> => {
+ return result.map((trace) => {
+ return {
+ ...convertClickhouseToDomain(trace, DEFAULT_RENDERING_PROPS),
+ // Conditionally include additional fields based on request
+ // We need to return empty list on excluded scores / observations
+ // and -1 on excluded metrics to not break the SDK API clients
+ // that expect those fields if they have not been excluded via 'fields' property
+ // See LFE-6361
+ observations: include.observations ? trace.observations : [],
+ scores: include.scores ? trace.scores : [],
+ totalCost: include.metrics ? trace.totalCost : -1,
+ latency: include.metrics ? trace.latency : -1,
+ htmlPath: trace.htmlPath,
+ };
+ });
+};
diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.ts
index ad092e7892..eb9e280bd5 100644
--- a/web/src/__tests__/async/traces-api.servertest.ts
+++ b/web/src/__tests__/async/traces-api.servertest.ts
@@ -5,10 +5,13 @@ import {
createScoresCh,
createTrace,
getTraceById,
+ createEvent,
+ type EventRecordInsertType,
} from "@langfuse/shared/src/server";
import {
createObservationsCh,
createTracesCh,
+ createEventsCh,
} from "@langfuse/shared/src/server";
import {
makeZodVerifiedAPICall,
@@ -22,10 +25,129 @@ import {
} from "@/src/features/public-api/types/traces";
import { randomUUID } from "crypto";
import { snakeCase } from "lodash";
+import { env } from "@/src/env.mjs";
import waitForExpect from "wait-for-expect";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+// Helper type for creating observation/event data
+// Times are always in milliseconds, conversion handled internally
+type ObservationEventData = {
+ id?: string;
+ trace_id: string;
+ project_id: string;
+ name: string;
+ type?: string;
+ level?: string;
+ start_time: number; // milliseconds
+ end_time?: number | null; // milliseconds
+ input?: string | null;
+ output?: string | null;
+ metadata?: Record<string, any>;
+ provided_model_name?: string;
+ provided_usage_details?: Record<string, number>;
+ provided_cost_details?: Record<string, number>;
+ total_cost?: number;
+};
+
+// Helper to create observation/event data in the appropriate format
+// Handles time conversion internally: milliseconds -> microseconds for events table
+const createObservationOrEvent = (
+ useEventsTable: boolean,
+ data: ObservationEventData & Partial<EventRecordInsertType>,
+) => {
+ const id = data.id ?? randomUUID();
+ const timeMultiplier = useEventsTable ? 1000 : 1; // microseconds vs milliseconds
+
+ if (useEventsTable) {
+ // For events table: microseconds, requires span_id
+ return createEvent({
+ ...data,
+ id,
+ span_id: id,
+ parent_span_id: data.trace_id, // Observations have trace as parent
+ type: data.type ?? "SPAN",
+ level: data.level ?? "DEFAULT",
+ start_time: data.start_time * timeMultiplier, // Convert ms to microseconds
+ end_time:
+ data.end_time === null
+ ? null
+ : data.end_time
+ ? data.end_time * timeMultiplier
+ : null,
+ });
+ } else {
+ // For observations table: milliseconds
+ return createObservation({
+ id,
+ trace_id: data.trace_id,
+ project_id: data.project_id,
+ name: data.name,
+ type: data.type ?? "SPAN",
+ level: data.level ?? "DEFAULT",
+ 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,
+ total_cost: data.total_cost,
+ });
+ }
+};
+
+// Helper to create trace with observations/events
+const createTraceWithObservations = async (
+ useEventsTable: boolean,
+ trace: ReturnType<typeof createTrace>,
+ observations: ObservationEventData[],
+) => {
+ await createTracesCh([trace]);
+
+ if (useEventsTable) {
+ // For events table: create root trace event + observation events
+ const id = randomUUID();
+ const rootTraceEvent = createEvent({
+ id: id,
+ span_id: id, // Root trace event has no span_id
+ parent_span_id: null, // Root trace event - this is key!
+ trace_id: trace.id,
+ project_id: trace.project_id,
+ name: trace.name ?? "trace",
+ type: "GENERATION", // Trace events are typically GENERATION type
+ start_time: trace.timestamp * 1000, // Convert ms to microseconds
+ end_time: null,
+ environment: trace.environment ?? "default",
+ version: trace.version ?? null,
+ session_id: trace.session_id ?? null,
+ user_id: trace.user_id ?? null,
+ input: trace.input ?? null,
+ output: trace.output ?? null,
+ metadata: trace.metadata ?? {},
+ total_cost: 0, // Root trace event has no cost
+ });
+
+ const observationEvents = observations.map((obs) =>
+ createObservationOrEvent(useEventsTable, {
+ ...obs,
+ environment: rootTraceEvent.environment,
+ user_id: rootTraceEvent.user_id,
+ session_id: rootTraceEvent.session_id,
+ }),
+ );
+
+ await createEventsCh([rootTraceEvent, ...observationEvents] as any);
+ } else {
+ // For observations table: just create observations
+ const data = observations.map((obs) =>
+ createObservationOrEvent(useEventsTable, obs),
+ );
+ await createObservationsCh(data as any);
+ }
+};
+
describe("/api/public/traces API Endpoint", () => {
it("should create and get a trace via /traces", async () => {
const createdTrace = createTrace({
@@ -955,347 +1077,833 @@ describe("/api/public/traces API Endpoint", () => {
});
});
- describe("Advanced Filtering", () => {
- const testTraceId = randomUUID();
- const testTraceId2 = randomUUID();
-
- beforeAll(async () => {
- // Create test traces with different metadata for filtering
- const trace1 = createTrace({
- id: testTraceId,
- name: "filter-test-trace-1",
- user_id: "filter-user-1",
- project_id: projectId,
- metadata: {
- environment: "production",
- model: "gpt-4",
- priority: "high",
- },
- tags: ["important", "customer-facing"],
- environment: "production",
- release: "v1.0.0",
- version: "1.0.0",
- timestamp: new Date("2024-01-01T00:00:00Z").getTime(),
- });
-
- const trace2 = createTrace({
- id: testTraceId2,
- name: "filter-test-trace-2",
- user_id: "filter-user-2",
- project_id: projectId,
- metadata: {
- environment: "staging",
- model: "gpt-3.5-turbo",
- priority: "low",
- },
- tags: ["test", "internal"],
- environment: "staging",
- release: "v0.9.0",
- version: "0.9.0",
- timestamp: new Date("2024-01-02T00:00:00Z").getTime(),
+ describe("Advanced Filtering - Dual Path Tests", () => {
+ const runTestSuite = (useEventsTable: boolean) => {
+ const suiteName = useEventsTable
+ ? "with events table"
+ : "with traces table";
+ const basePath = "/api/public/traces";
+ const buildUrl = (params: string) => {
+ if (!params) return basePath;
+ const prefix = useEventsTable
+ ? `${basePath}?useEventsTable=true&`
+ : `${basePath}?`;
+ return prefix + params;
+ };
+
+ describe(`${suiteName}`, () => {
+ const testTraceId = randomUUID();
+ const testTraceId2 = randomUUID();
+
+ beforeAll(async () => {
+ // Create test traces with different metadata for filtering
+ const trace1 = createTrace({
+ id: testTraceId,
+ name: "filter-test-trace-1",
+ user_id: "filter-user-1",
+ project_id: projectId,
+ metadata: {
+ environment: "production",
+ model: "gpt-4",
+ priority: "high",
+ },
+ tags: ["important", "customer-facing"],
+ environment: "production",
+ release: "v1.0.0",
+ version: "1.0.0",
+ timestamp: new Date("2024-01-01T00:00:00Z").getTime(),
+ });
+
+ const trace2 = createTrace({
+ id: testTraceId2,
+ name: "filter-test-trace-2",
+ user_id: "filter-user-2",
+ project_id: projectId,
+ metadata: {
+ environment: "staging",
+ model: "gpt-3.5-turbo",
+ priority: "low",
+ },
+ tags: ["test", "internal"],
+ environment: "staging",
+ release: "v0.9.0",
+ version: "0.9.0",
+ timestamp: new Date("2024-01-02T00:00:00Z").getTime(),
+ });
+
+ await createTraceWithObservations(useEventsTable, trace1, []);
+ await createTraceWithObservations(useEventsTable, trace2, []);
+
+ // Simple wait to ensure data is available
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }, 10000);
+
+ it("should support basic metadata filtering", async () => {
+ const filterParam = JSON.stringify([
+ {
+ type: "stringObject",
+ column: "metadata",
+ key: "environment",
+ operator: "=",
+ value: "production",
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId,
+ );
+ const nonMatchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId2,
+ );
+
+ expect(matchingTrace).toBeTruthy();
+ expect(nonMatchingTrace).toBeFalsy();
+ });
+
+ it("should support multiple metadata filters with AND logic", async () => {
+ const filterParam = JSON.stringify([
+ {
+ type: "stringObject",
+ column: "metadata",
+ key: "environment",
+ operator: "=",
+ value: "production",
+ },
+ {
+ type: "stringObject",
+ column: "metadata",
+ key: "model",
+ operator: "contains",
+ value: "gpt-4",
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId,
+ );
+ const nonMatchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId2,
+ );
+
+ expect(matchingTrace).toBeTruthy();
+ expect(nonMatchingTrace).toBeFalsy();
+ });
+
+ it("should support array tag filtering", async () => {
+ // Skip for events table - tags are always empty in the events table
+ if (useEventsTable) {
+ return;
+ }
+
+ const filterParam = JSON.stringify([
+ {
+ type: "arrayOptions",
+ column: "tags",
+ operator: "any of",
+ value: ["important", "customer-facing"],
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId,
+ );
+
+ expect(matchingTrace).toBeTruthy();
+ if (matchingTrace) {
+ expect(matchingTrace.tags).toContain("important");
+ }
+ });
+
+ it("should support backward compatibility with simple parameters", async () => {
+ // Test multiple simple parameters
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`userId=filter-user-1&environment=production`),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId,
+ );
+ const nonMatchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId2,
+ );
+
+ expect(matchingTrace).toBeTruthy();
+ expect(nonMatchingTrace).toBeFalsy();
+ });
+
+ it("should give precedence to advanced filter over simple parameters", async () => {
+ // simple param would match trace2, but filter should match trace1
+ const filterParam = JSON.stringify([
+ {
+ type: "string",
+ column: "userId",
+ operator: "=",
+ value: "filter-user-1",
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(
+ `userId=filter-user-2&filter=${encodeURIComponent(filterParam)}`,
+ ),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId,
+ );
+ const nonMatchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId2,
+ );
+
+ // Should match trace1 (filter takes precedence) not trace2 (simple param)
+ expect(matchingTrace).toBeTruthy();
+ expect(nonMatchingTrace).toBeFalsy();
+ });
+
+ it("should merge non-conflicting simple and advanced filters", async () => {
+ // simple environment + advanced metadata filter
+ const filterParam = JSON.stringify([
+ {
+ type: "stringObject",
+ column: "metadata",
+ key: "model",
+ operator: "contains",
+ value: "gpt-4",
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(
+ `userId=filter-user-1&filter=${encodeURIComponent(filterParam)}`,
+ ),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId,
+ );
+ const nonMatchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId2,
+ );
+
+ expect(matchingTrace).toBeTruthy();
+ expect(nonMatchingTrace).toBeFalsy();
+ });
+
+ it("should return validation error for malformed filter JSON", async () => {
+ const malformedFilter = "invalid-json";
+
+ const traces = await makeZodVerifiedAPICallSilent(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(malformedFilter)}`),
+ );
+
+ expect(traces.status).toBe(400);
+ });
+
+ it("should return validation error for invalid filter schema", async () => {
+ const invalidFilterParam = JSON.stringify([
+ {
+ type: "invalid-type", // Invalid filter type
+ column: "metadata",
+ operator: "=",
+ value: "test",
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICallSilent(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(invalidFilterParam)}`),
+ );
+
+ expect(traces.status).toBe(400);
+ });
+
+ it("should return validation error for empty string as filter", async () => {
+ const traces = await makeZodVerifiedAPICallSilent(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=`),
+ );
+
+ expect(traces.status).toBe(200); // Empty string should be treated as undefined
+ });
+
+ it("should return validation error for invalid FilterState structure", async () => {
+ const invalidStructure = JSON.stringify([
+ {
+ // Missing required fields for a valid FilterState condition
+ column: "userId",
+ value: "test",
+ // Missing type and operator
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICallSilent(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(invalidStructure)}`),
+ );
+
+ expect(traces.status).toBe(400);
+ });
+
+ it("should return validation error for FilterState with invalid operator", async () => {
+ const invalidOperator = JSON.stringify([
+ {
+ type: "string",
+ column: "userId",
+ operator: "invalid-operator", // Invalid operator
+ value: "test",
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICallSilent(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(invalidOperator)}`),
+ );
+
+ expect(traces.status).toBe(400);
+ });
+
+ it("should support advanced timestamp filtering with multiple operators", async () => {
+ // Test range filter (>= AND <) - should match only trace1
+ const filterRange = JSON.stringify([
+ {
+ type: "datetime",
+ column: "timestamp",
+ operator: ">=",
+ value: "2024-01-01T00:00:00Z",
+ },
+ {
+ type: "datetime",
+ column: "timestamp",
+ operator: "<",
+ value: "2024-01-01T24:00:00Z",
+ },
+ ]);
+
+ const tracesRange = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(filterRange)}`),
+ );
+
+ expect(tracesRange.status).toBe(200);
+ const matchingRange = tracesRange.body.data.find(
+ (t) => t.id === testTraceId,
+ );
+ const nonMatchingRange = tracesRange.body.data.find(
+ (t) => t.id === testTraceId2,
+ );
+ expect(matchingRange).toBeTruthy();
+ expect(nonMatchingRange).toBeFalsy();
+ });
+
+ it("should give precedence to advanced timestamp filter over simple fromTimestamp/toTimestamp parameters", async () => {
+ // simple params would match none of the traces (2023 dates)
+ // But advanced filter should match trace2 (timestamp >= 2024-01-01T12:00:00Z)
+ const filterParam = JSON.stringify([
+ {
+ type: "datetime",
+ column: "timestamp",
+ operator: ">=",
+ value: "2024-01-01T12:00:00Z",
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(
+ `orderBy=timestamp.asc&fromTimestamp=2023-01-01T00:00:00Z&toTimestamp=2023-01-02T00:00:00Z&filter=${encodeURIComponent(filterParam)}`,
+ ),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === testTraceId2,
+ );
+ // Should match trace2 (advanced filter wins)
+ expect(matchingTrace).toBeTruthy();
+ });
+
+ it("should filter aggregated fields correctly", async () => {
+ // Skip for traces table - this test is specific to events table aggregation
+ if (!useEventsTable) {
+ return;
+ }
+
+ // This test verifies that filtering on trace-levevel fields works correctly.
+ // E.g. version field is defined as: argMaxIf(version, event_ts, version <> '')
+
+ const traceWithVersionChange = randomUUID();
+ const baseTimestamp = Date.now();
+ const trace = createTrace({
+ id: traceWithVersionChange,
+ name: "version-aggregation-test",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ version: "1.0",
+ environment: "test",
+ });
+
+ // Create multiple events for the same trace with different versions
+ // at increasing timestamps. The latest event has version="2.0"
+ const events = [
+ {
+ trace_id: traceWithVersionChange,
+ parent_span_id: traceWithVersionChange,
+ project_id: projectId,
+ name: "event-1",
+ type: "GENERATION" as const,
+ start_time: baseTimestamp,
+ end_time: baseTimestamp + 100,
+ version: "1.0",
+ environment: "test",
+ event_ts: baseTimestamp * 1000 + 1000000,
+ },
+ {
+ trace_id: traceWithVersionChange,
+ parent_span_id: traceWithVersionChange,
+ project_id: projectId,
+ name: "event-3",
+ type: "GENERATION" as const,
+ start_time: baseTimestamp + 400,
+ end_time: baseTimestamp + 500,
+ version: "2.0",
+ environment: "test",
+ event_ts: baseTimestamp * 1000 + 5000000,
+ },
+ ];
+
+ await createTraceWithObservations(useEventsTable, trace, events);
+
+ // Simple wait to ensure data is available
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // The trace should NOT be returned because after aggregation,
+ // it has version=2.0 (from the latest event)
+ const filterParam = JSON.stringify([
+ {
+ type: "string",
+ column: "version",
+ operator: "=",
+ value: "1.0",
+ },
+ {
+ type: "datetime",
+ column: "timestamp",
+ operator: ">=",
+ value: new Date(baseTimestamp).toISOString(),
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ );
+
+ expect(traces.status).toBe(200);
+ const matchingTrace = traces.body.data.find(
+ (t) => t.id === traceWithVersionChange,
+ );
+
+ // The trace should NOT be found because its aggregated version is 2.0, not 1.0
+ expect(matchingTrace).toBeUndefined();
+
+ // Verify that filtering by version=2.0 DOES return the trace
+ const filterParam2 = JSON.stringify([
+ {
+ type: "string",
+ column: "version",
+ operator: "=",
+ value: "2.0",
+ },
+ {
+ type: "datetime",
+ column: "timestamp",
+ operator: ">=",
+ value: new Date(baseTimestamp).toISOString(),
+ },
+ ]);
+
+ const traces2 = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`filter=${encodeURIComponent(filterParam2)}`),
+ );
+
+ expect(traces2.status).toBe(200);
+ const matchingTrace2 = traces2.body.data.find(
+ (t) => t.id === traceWithVersionChange,
+ );
+
+ // The trace SHOULD be found because its aggregated version is 2.0
+ expect(matchingTrace2).toBeTruthy();
+ expect(matchingTrace2?.version).toBe("2.0");
+ });
});
+ };
- await createTracesCh([trace1, trace2]);
-
- // Simple wait to ensure data is available
- await new Promise((resolve) => setTimeout(resolve, 100));
- }, 10000);
-
- it("should support basic metadata filtering", async () => {
- const filterParam = JSON.stringify([
- {
- type: "stringObject",
- column: "metadata",
- key: "environment",
- operator: "=",
- value: "production",
- },
- ]);
-
- const traces = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(filterParam)}`,
- );
-
- expect(traces.status).toBe(200);
- const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);
- const nonMatchingTrace = traces.body.data.find(
- (t) => t.id === testTraceId2,
- );
-
- expect(matchingTrace).toBeTruthy();
- expect(nonMatchingTrace).toBeFalsy();
- });
-
- it("should support multiple metadata filters with AND logic", async () => {
- const filterParam = JSON.stringify([
- {
- type: "stringObject",
- column: "metadata",
- key: "environment",
- operator: "=",
- value: "production",
- },
- {
- type: "stringObject",
- column: "metadata",
- key: "model",
- operator: "contains",
- value: "gpt-4",
- },
- ]);
-
- const traces = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(filterParam)}`,
- );
-
- expect(traces.status).toBe(200);
- const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);
- const nonMatchingTrace = traces.body.data.find(
- (t) => t.id === testTraceId2,
- );
-
- expect(matchingTrace).toBeTruthy();
- expect(nonMatchingTrace).toBeFalsy();
- });
-
- it("should support array tag filtering", async () => {
- const filterParam = JSON.stringify([
- {
- type: "arrayOptions",
- column: "tags",
- operator: "any of",
- value: ["important", "customer-facing"],
- },
- ]);
-
- const traces = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(filterParam)}`,
- );
-
- expect(traces.status).toBe(200);
- const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);
-
- expect(matchingTrace).toBeTruthy();
- if (matchingTrace) {
- expect(matchingTrace.tags).toContain("important");
- }
- });
-
- it("should support backward compatibility with simple parameters", async () => {
- // Test multiple simple parameters
- const traces = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?userId=filter-user-1&environment=production`,
- );
-
- expect(traces.status).toBe(200);
- const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);
- const nonMatchingTrace = traces.body.data.find(
- (t) => t.id === testTraceId2,
- );
-
- expect(matchingTrace).toBeTruthy();
- expect(nonMatchingTrace).toBeFalsy();
- });
-
- it("should give precedence to advanced filter over simple parameters", async () => {
- // simple param would match trace2, but filter should match trace1
- const filterParam = JSON.stringify([
- {
- type: "string",
- column: "userId",
- operator: "=",
- value: "filter-user-1",
- },
- ]);
-
- const traces = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?userId=filter-user-2&filter=${encodeURIComponent(filterParam)}`,
- );
-
- expect(traces.status).toBe(200);
- const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);
- const nonMatchingTrace = traces.body.data.find(
- (t) => t.id === testTraceId2,
- );
-
- // Should match trace1 (filter takes precedence) not trace2 (simple param)
- expect(matchingTrace).toBeTruthy();
- expect(nonMatchingTrace).toBeFalsy();
- });
-
- it("should merge non-conflicting simple and advanced filters", async () => {
- // simple environment + advanced metadata filter
- const filterParam = JSON.stringify([
- {
- type: "stringObject",
- column: "metadata",
- key: "model",
- operator: "contains",
- value: "gpt-4",
- },
- ]);
-
- const traces = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?userId=filter-user-1&filter=${encodeURIComponent(filterParam)}`,
- );
-
- expect(traces.status).toBe(200);
- const matchingTrace = traces.body.data.find((t) => t.id === testTraceId);
- const nonMatchingTrace = traces.body.data.find(
- (t) => t.id === testTraceId2,
- );
-
- expect(matchingTrace).toBeTruthy();
- expect(nonMatchingTrace).toBeFalsy();
- });
-
- it("should return validation error for malformed filter JSON", async () => {
- const malformedFilter = "invalid-json";
-
- const traces = await makeZodVerifiedAPICallSilent(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(malformedFilter)}`,
- );
-
- expect(traces.status).toBe(400);
- });
-
- it("should return validation error for invalid filter schema", async () => {
- const invalidFilterParam = JSON.stringify([
- {
- type: "invalid-type", // Invalid filter type
- column: "metadata",
- operator: "=",
- value: "test",
- },
- ]);
-
- const traces = await makeZodVerifiedAPICallSilent(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(invalidFilterParam)}`,
- );
-
- expect(traces.status).toBe(400);
- });
-
- it("should return validation error for empty string as filter", async () => {
- const traces = await makeZodVerifiedAPICallSilent(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=`,
- );
-
- expect(traces.status).toBe(200); // Empty string should be treated as undefined
- });
-
- it("should return validation error for invalid FilterState structure", async () => {
- const invalidStructure = JSON.stringify([
- {
- // Missing required fields for a valid FilterState condition
- column: "userId",
- value: "test",
- // Missing type and operator
- },
- ]);
-
- const traces = await makeZodVerifiedAPICallSilent(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(invalidStructure)}`,
- );
-
- expect(traces.status).toBe(400);
- });
-
- it("should return validation error for FilterState with invalid operator", async () => {
- const invalidOperator = JSON.stringify([
- {
- type: "string",
- column: "userId",
- operator: "invalid-operator", // Invalid operator
- value: "test",
- },
- ]);
-
- const traces = await makeZodVerifiedAPICallSilent(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(invalidOperator)}`,
- );
-
- expect(traces.status).toBe(400);
- });
-
- it("should support advanced timestamp filtering with multiple operators", async () => {
- // Test range filter (>= AND <) - should match only trace1
- const filterRange = JSON.stringify([
- {
- type: "datetime",
- column: "timestamp",
- operator: ">=",
- value: "2024-01-01T00:00:00Z",
- },
- {
- type: "datetime",
- column: "timestamp",
- operator: "<",
- value: "2024-01-01T24:00:00Z",
- },
- ]);
-
- const tracesRange = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?filter=${encodeURIComponent(filterRange)}`,
- );
-
- expect(tracesRange.status).toBe(200);
- const matchingRange = tracesRange.body.data.find(
- (t) => t.id === testTraceId,
- );
- const nonMatchingRange = tracesRange.body.data.find(
- (t) => t.id === testTraceId2,
- );
- expect(matchingRange).toBeTruthy();
- expect(nonMatchingRange).toBeFalsy();
- });
-
- it("should give precedence to advanced timestamp filter over simple fromTimestamp/toTimestamp parameters", async () => {
- // simple params would match none of the traces (2023 dates)
- // But advanced filter should match trace2 (timestamp >= 2024-01-01T12:00:00Z)
- const filterParam = JSON.stringify([
- {
- type: "datetime",
- column: "timestamp",
- operator: ">=",
- value: "2024-01-01T12:00:00Z",
- },
- ]);
+ // Run test suite twice - once for each implementation
+ runTestSuite(false); // old traces table
+ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {
+ runTestSuite(true); // Events table
+ }
+ });
- const traces = await makeZodVerifiedAPICall(
- GetTracesV1Response,
- "GET",
- `/api/public/traces?orderBy=timestamp.asc&fromTimestamp=2023-01-01T00:00:00Z&toTimestamp=2023-01-02T00:00:00Z&filter=${encodeURIComponent(filterParam)}`,
- );
+ // Dual-path tests for events table migration
+ describe("GET /api/public/traces - Events Table Migration Tests", () => {
+ const runTestSuite = (useEventsTable: boolean) => {
+ const suiteName = useEventsTable
+ ? "with events table"
+ : "with traces table";
+ const basePath = "/api/public/traces";
+ const buildUrl = (params: string) => {
+ if (!params) return basePath;
+ const prefix = useEventsTable
+ ? `${basePath}?useEventsTable=true&`
+ : `${basePath}?`;
+ return prefix + params;
+ };
+
+ describe(`${suiteName}`, () => {
+ it("should fetch traces with all field groups", async () => {
+ const timestamp = new Date();
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "test-trace-fields",
+ user_id: "user-field-test",
+ session_id: "session-field-test",
+ timestamp: timestamp.getTime(),
+ project_id: projectId,
+ metadata: { testKey: "testValue" },
+ release: "1.0.0",
+ version: "2.0.0",
+ environment: "production",
+ });
+
+ // Create observations/events with cost to test metrics
+ await createTraceWithObservations(useEventsTable, createdTrace, [
+ {
+ trace_id: traceId,
+ project_id: projectId,
+ name: "generation-1",
+ type: "GENERATION",
+ start_time: timestamp.getTime(),
+ end_time: timestamp.getTime() + 1000,
+ input: "What is the capital of France?",
+ output: "The capital of France is Paris.",
+ total_cost: 0.05,
+ metadata: { testKey: "testValue" },
+ },
+ {
+ trace_id: traceId,
+ project_id: projectId,
+ name: "span-1",
+ type: "SPAN",
+ start_time: timestamp.getTime() + 500,
+ end_time: timestamp.getTime() + 2000,
+ total_cost: 0.03,
+ metadata: { testKey: "testValue" },
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`fields=core,io,observations,metrics`),
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ if (!trace) return;
+
+ // Core fields
+ expect(trace.name).toBe("test-trace-fields");
+ expect(trace.userId).toBe("user-field-test");
+ expect(trace.sessionId).toBe("session-field-test");
+ expect(trace.version).toBe("2.0.0");
+ expect(trace.environment).toBe("production");
+
+ // IO fields
+ expect(trace.metadata).toMatchObject({ testKey: "testValue" });
+
+ // Events table aggregates observation_ids
+ expect(trace.observations).toBeDefined();
+ expect(trace.observations?.length).toBeGreaterThan(0);
+ expect(trace.totalCost).toBeCloseTo(0.08, 2); // 0.05 + 0.03
+ expect(trace.latency).toBeGreaterThan(0);
+ });
+
+ it("should filter traces by userId", async () => {
+ const userId = randomUUID();
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "user-filter-test",
+ user_id: userId,
+ project_id: projectId,
+ });
+
+ // Create dummy trace that should not be returned
+ const dummyTraceId = randomUUID();
+ const dummyTrace = createTrace({
+ id: dummyTraceId,
+ name: "dummy-trace",
+ user_id: "other-user",
+ project_id: projectId,
+ });
+
+ await createTraceWithObservations(useEventsTable, createdTrace, []);
+ await createTraceWithObservations(useEventsTable, dummyTrace, []);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`userId=${userId}`),
+ );
+
+ expect(traces.body.meta.totalItems).toBeGreaterThanOrEqual(1);
+ const matchingTrace = traces.body.data.find((t) => t.id === traceId);
+ const nonMatchingTrace = traces.body.data.find(
+ (t) => t.id === dummyTraceId,
+ );
+
+ expect(matchingTrace).toBeTruthy();
+ expect(nonMatchingTrace).toBeUndefined();
+ expect(matchingTrace?.userId).toBe(userId);
+ });
+
+ it("should filter traces by name", async () => {
+ const traceName = `test-trace-${randomUUID()}`;
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: traceName,
+ project_id: projectId,
+ });
+
+ await createTraceWithObservations(useEventsTable, createdTrace, []);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`name=${traceName}`),
+ );
+
+ const matchingTrace = traces.body.data.find((t) => t.id === traceId);
+ expect(matchingTrace).toBeTruthy();
+ expect(matchingTrace?.name).toBe(traceName);
+ });
+
+ it("should filter traces by environment", async () => {
+ const environment = `env-${randomUUID()}`;
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "env-test",
+ environment,
+ project_id: projectId,
+ });
+
+ await createTraceWithObservations(useEventsTable, createdTrace, []);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`environment=${environment}`),
+ );
+
+ const matchingTrace = traces.body.data.find((t) => t.id === traceId);
+ expect(matchingTrace).toBeTruthy();
+ expect(matchingTrace?.environment).toBe(environment);
+ });
+
+ it("should support pagination", async () => {
+ const traceIds = Array.from({ length: 5 }, () => randomUUID());
+ const traces = traceIds.map((id, index) =>
+ createTrace({
+ id,
+ name: `pagination-test-${index}`,
+ project_id: projectId,
+ timestamp: new Date().getTime() + index,
+ }),
+ );
+
+ for (const trace of traces) {
+ await createTraceWithObservations(useEventsTable, trace, []);
+ }
+
+ // Get page 1
+ const page1 = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`page=1&limit=2`),
+ );
+
+ // Get page 2
+ const page2 = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`page=2&limit=2`),
+ );
+
+ expect(page1.body.data.length).toBeLessThanOrEqual(2);
+ expect(page2.body.data.length).toBeLessThanOrEqual(2);
+
+ // Ensure pages are different
+ const page1Ids = page1.body.data.map((t) => t.id);
+ const page2Ids = page2.body.data.map((t) => t.id);
+ const intersection = page1Ids.filter((id) => page2Ids.includes(id));
+ expect(intersection.length).toBe(0);
+ });
+
+ it("should filter traces by timestamp range", async () => {
+ const now = new Date();
+ const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
+ const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
+
+ const traceInRange = createTrace({
+ id: randomUUID(),
+ name: "in-range-trace",
+ project_id: projectId,
+ timestamp: now.getTime(),
+ });
+
+ const traceOutOfRange = createTrace({
+ id: randomUUID(),
+ name: "out-of-range-trace",
+ project_id: projectId,
+ timestamp: yesterday.getTime() - 24 * 60 * 60 * 1000,
+ });
+
+ await createTraceWithObservations(useEventsTable, traceInRange, []);
+ await createTraceWithObservations(
+ useEventsTable,
+ traceOutOfRange,
+ [],
+ );
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(
+ `fromTimestamp=${yesterday.toISOString()}&toTimestamp=${tomorrow.toISOString()}`,
+ ),
+ );
+
+ const inRangeFound = traces.body.data.find(
+ (t) => t.id === traceInRange.id,
+ );
+ const outOfRangeFound = traces.body.data.find(
+ (t) => t.id === traceOutOfRange.id,
+ );
+
+ expect(inRangeFound).toBeTruthy();
+ expect(outOfRangeFound).toBeUndefined();
+ });
+
+ it("should handle field group: scores", async () => {
+ const traceId = randomUUID();
+ const createdTrace = createTrace({
+ id: traceId,
+ name: "scores-test",
+ project_id: projectId,
+ });
+
+ await createTraceWithObservations(useEventsTable, createdTrace, []);
+
+ // Create trace-level score
+ const score = createTraceScore({
+ trace_id: traceId,
+ project_id: projectId,
+ name: "quality",
+ value: 0.9,
+ });
+
+ await createScoresCh([score]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`fields=core,scores`),
+ );
+
+ const trace = traces.body.data.find((t) => t.id === traceId);
+ expect(trace).toBeTruthy();
+ expect(trace?.scores).toBeDefined();
+ });
+
+ it("should count traces correctly", async () => {
+ const prefix = randomUUID();
+ const traceIds = Array.from({ length: 3 }, () => randomUUID());
+ const traces = traceIds.map((id) =>
+ createTrace({
+ id,
+ name: `count-test-${prefix}`,
+ project_id: projectId,
+ }),
+ );
+
+ for (const trace of traces) {
+ await createTraceWithObservations(useEventsTable, trace, []);
+ }
+
+ const result = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`name=count-test-${prefix}`),
+ );
+
+ expect(result.body.meta.totalItems).toBeGreaterThanOrEqual(3);
+ const matchingTraces = result.body.data.filter((t) =>
+ t.name?.startsWith("count-test-"),
+ );
+ expect(matchingTraces.length).toBeGreaterThanOrEqual(3);
+ });
+ });
+ };
- expect(traces.status).toBe(200);
- const matchingTrace = traces.body.data.find((t) => t.id === testTraceId2);
- // Should match trace2 (advanced filter wins)
- expect(matchingTrace).toBeTruthy();
- });
+ // Run test suite twice - once for each implementation
+ runTestSuite(false); // Good old traces table
+ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {
+ runTestSuite(true); // Events table
+ }
});
});
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 3d1be85246..597c712b69 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -2,17 +2,16 @@ import {
convertDateToClickhouseDateTime,
queryClickhouse,
TRACE_TO_OBSERVATIONS_INTERVAL,
- DEFAULT_RENDERING_PROPS,
orderByToClickhouseSql,
type DateTimeFilter,
- convertClickhouseToDomain,
+ convertClickhouseTracesListToDomain,
type TraceRecordReadType,
measureAndReturn,
- tracesTableUiColumnDefinitions,
deriveFilters,
+ createPublicApiTracesColumnMapping,
+ createTracesUiColumnDefinitions,
} from "@langfuse/shared/src/server";
import { type OrderByState } from "@langfuse/shared";
-import { snakeCase } from "lodash";
import {
TRACE_FIELD_GROUPS,
type TraceFieldGroup,
@@ -20,6 +19,7 @@ import {
import { env } from "@/src/env.mjs";
import type { FilterState } from "@langfuse/shared";
+import { snakeCase } from "lodash";
export type TraceQueryType = {
page: number;
@@ -37,6 +37,7 @@ export type TraceQueryType = {
fromTimestamp?: string;
toTimestamp?: string;
fields?: TraceFieldGroup[];
+ useEventsTable?: boolean | null;
};
export const generateTracesForPublicApi = async ({
@@ -64,7 +65,7 @@ export const generateTracesForPublicApi = async ({
props,
filterParams,
advancedFilters,
- tracesTableUiColumnDefinitions,
+ tracesUiColumnDefinitions,
);
const appliedFilter = filter.apply();
@@ -246,20 +247,10 @@ export const generateTracesForPublicApi = async ({
},
});
- return result.map((trace) => {
- return {
- ...convertClickhouseToDomain(trace, DEFAULT_RENDERING_PROPS),
- // Conditionally include additional fields based on request
- // We need to return empty list on excluded scores / observations
- // and -1 on excluded metrics to not break the SDK API clients
- // that expect those fields if they have not been excluded via 'fields' property
- // See LFE-6361
- observations: includeObservations ? trace.observations : [],
- scores: includeScores ? trace.scores : [],
- totalCost: includeMetrics ? trace.totalCost : -1,
- latency: includeMetrics ? trace.latency : -1,
- htmlPath: trace.htmlPath,
- };
+ return convertClickhouseTracesListToDomain(result, {
+ metrics: includeMetrics,
+ scores: includeScores,
+ observations: includeObservations,
});
};
@@ -274,7 +265,7 @@ export const getTracesCountForPublicApi = async ({
props,
filterParams,
advancedFilters,
- tracesTableUiColumnDefinitions,
+ tracesUiColumnDefinitions,
);
const appliedFilter = filter.apply();
@@ -333,70 +324,9 @@ const orderByColumns = [
queryPrefix: "t",
}));
-const filterParams = [
- {
- id: "userId",
- clickhouseSelect: "user_id",
- filterType: "StringFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "name",
- clickhouseSelect: "name",
- filterType: "StringFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "tags",
- clickhouseSelect: "tags",
- filterType: "ArrayOptionsFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "sessionId",
- clickhouseSelect: "session_id",
- filterType: "StringFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "version",
- clickhouseSelect: "version",
- filterType: "StringFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "release",
- clickhouseSelect: "release",
- filterType: "StringFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "environment",
- clickhouseSelect: "environment",
- filterType: "StringOptionsFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "fromTimestamp",
- clickhouseSelect: "timestamp",
- operator: ">=" as const,
- filterType: "DateTimeFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "toTimestamp",
- clickhouseSelect: "timestamp",
- operator: "<" as const,
- filterType: "DateTimeFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
-];
+// Use factory functions to create column mappings (eliminates duplication with events table)
+const filterParams = createPublicApiTracesColumnMapping("traces", "t");
+const tracesUiColumnDefinitions = createTracesUiColumnDefinitions(
+ "traces",
+ "t",
+);
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index 71a97a6502..4ad8c93eb1 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -13,6 +13,7 @@ import {
type ObservationPriceFields,
} from "@langfuse/shared/src/server";
import { z } from "zod/v4";
+import { useEventsTableSchema } from "../../query/types";
/**
* Objects
@@ -162,11 +163,6 @@ export const transformDbToApiObservation = (
* Endpoints
*/
-const useEventsTableSchema = z
- .union([z.literal("true"), z.literal("false"), z.boolean()])
- .optional()
- .transform((val) => val === "true" || val === true);
-
// GET /observations
export const GetObservationsV1Query = z.object({
...publicApiPaginationZod,
diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.ts
index 2cd1d3b699..36d1d852dd 100644
--- a/web/src/features/public-api/types/traces.ts
+++ b/web/src/features/public-api/types/traces.ts
@@ -9,6 +9,7 @@ import {
} from "@langfuse/shared";
import { stringDateTime, TraceBody } from "@langfuse/shared/src/server";
import { z } from "zod/v4";
+import { useEventsTableSchema } from "../../query";
/**
* Field groups for selective field fetching
@@ -94,6 +95,7 @@ export const GetTracesV1Query = z.object({
.filter((f) => TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup));
})
.pipe(z.array(z.enum(TRACE_FIELD_GROUPS)).nullable()),
+ useEventsTable: useEventsTableSchema,
filter: z
.string()
.optional()
diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.ts
index 0a5969a3d4..b885c20421 100644
--- a/web/src/features/query/types.ts
+++ b/web/src/features/query/types.ts
@@ -128,3 +128,8 @@ export const query = z
// Ensure fromTimestamp is before toTimestamp
new Date(query.fromTimestamp) < new Date(query.toTimestamp),
);
+
+export const useEventsTableSchema = z
+ .union([z.literal("true"), z.literal("false"), z.boolean()])
+ .optional()
+ .transform((val) => val === "true" || val === true);
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index 59d69b5bfd..c258ee5c1c 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -13,6 +13,8 @@ import {
eventTypes,
logger,
traceDeletionProcessor,
+ getTracesFromEventsTableForPublicApi,
+ getTracesCountFromEventsTableForPublicApi,
} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
import { telemetry } from "@/src/features/telemetry";
@@ -21,6 +23,7 @@ import {
generateTracesForPublicApi,
getTracesCountForPublicApi,
} from "@/src/features/public-api/server/traces";
+import { env } from "@/src/env.mjs";
export default withMiddlewares({
POST: createAuthedProjectAPIRoute({
@@ -76,6 +79,40 @@ export default withMiddlewares({
toTimestamp: query.toTimestamp ?? 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 === "true";
+
+ if (useEventsTable) {
+ const [items, count] = await Promise.all([
+ getTracesFromEventsTableForPublicApi({
+ ...filterProps,
+ advancedFilters: query.filter,
+ orderBy: query.orderBy ?? null,
+ }),
+ getTracesCountFromEventsTableForPublicApi({
+ ...filterProps,
+ advancedFilters: query.filter,
+ }),
+ ]);
+
+ return {
+ data: items.map((item) => ({
+ ...item,
+ externalId: null,
+ })),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: count,
+ totalPages: Math.ceil(count / query.limit),
+ },
+ };
+ }
+
+ // Legacy code path using traces table
const [items, count] = await Promise.all([
generateTracesForPublicApi({
props: filterProps,