Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(public-api): move DB queries from web/server into shared repositories (#14125)

Niklas Semmler1c87a349a474
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 044e826527..226a539fc9 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -459,6 +459,11 @@ const EnvSchema = z.object({
.enum(["true", "false"])
.default("true"),
+ // API ClickHouse query options
+ LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS: z
+ .enum(["true", "false"])
+ .default("false"),
+
// EE License
LANGFUSE_EE_LICENSE_KEY: z.string().optional(),
diff --git a/packages/shared/src/server/repositories/daily-metrics.ts b/packages/shared/src/server/repositories/daily-metrics.ts
new file mode 100644
index 0000000000..9c474a17b4
--- /dev/null
+++ b/packages/shared/src/server/repositories/daily-metrics.ts
@@ -0,0 +1,266 @@
+import {
+ convertApiProvidedFilterToClickhouseFilter,
+ type DateTimeFilter,
+} from "../queries";
+import { queryClickhouse } from "./clickhouse";
+import { TRACE_TO_OBSERVATIONS_INTERVAL } from "./constants";
+import { convertDateToClickhouseDateTime } from "../clickhouse/client";
+import { measureAndReturn } from "../clickhouse/measureAndReturn";
+
+type QueryType = {
+ page: number;
+ limit: number;
+ projectId: string;
+ userId?: string;
+ tags?: string | string[];
+ traceName?: string;
+ fromTimestamp?: string;
+ toTimestamp?: string;
+};
+
+export const generateDailyMetrics = async (props: QueryType) => {
+ const filter = convertApiProvidedFilterToClickhouseFilter(
+ props,
+ filterParams,
+ );
+ const hasTracesFilter = filter.some((f) => f.clickhouseTable === "traces");
+ const tracesFilter = filter.filter((f) => f.clickhouseTable === "traces");
+ const appliedFilter = filter.apply();
+ const appliedTracesFilter = tracesFilter.apply();
+
+ const timeFilter = filter.find(
+ (f) =>
+ f.clickhouseTable === "traces" &&
+ f.field.includes("timestamp") &&
+ (f.operator === ">=" || f.operator === ">"),
+ ) as DateTimeFilter | undefined;
+
+ const hasNonTimestampsFilter =
+ (timeFilter && filter.length() > 1) || (!timeFilter && filter.length() > 0);
+
+ const query = `
+ WITH model_usage AS (
+ SELECT
+ toDate(o.start_time) as date,
+ o.provided_model_name as model,
+ count(o.id) as countObservations,
+ count(distinct o.trace_id) as countTraces,
+ sum(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, o.usage_details)))) as inputUsage,
+ sum(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, o.usage_details)))) as outputUsage,
+ sumMap(o.usage_details)['total'] as totalUsage,
+ sum(coalesce(o.total_cost, 0)) as totalCost
+ FROM observations o FINAL ${hasNonTimestampsFilter ? " LEFT JOIN __TRACE_TABLE__ t FINAL on o.trace_id = t.id AND o.project_id = t.project_id" : ""}
+ WHERE o.project_id = {projectId: String}
+ ${hasNonTimestampsFilter ? `AND t.project_id = {projectId: String} AND ${appliedFilter.query}` : ""}
+ ${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ GROUP BY date, model
+ ), daily_model_usage AS (
+ SELECT
+ "date",
+ sum(mu.countObservations) as countObservations,
+ sum(mu.totalCost) as totalCost,
+ groupArray(tuple(
+ mu.model,
+ mu.inputUsage,
+ mu.outputUsage,
+ mu.totalUsage,
+ mu.totalCost,
+ mu.countObservations,
+ mu.countTraces
+ )) as daily_usage_tuple
+ FROM model_usage mu
+ GROUP BY date
+ ), trace_usage AS (
+ SELECT
+ toDate(t.timestamp) as date,
+ count(t.id) as countTraces
+ FROM __TRACE_TABLE__ t FINAL
+ WHERE t.project_id = {projectId: String}
+ ${hasTracesFilter ? `AND ${appliedTracesFilter.query}` : ""}
+ GROUP BY date
+ )
+
+ SELECT
+ COALESCE(dmu.date, tu.date) as date,
+ COALESCE(tu.countTraces, 0) as countTraces,
+ COALESCE(dmu.countObservations, 0) as countObservations,
+ COALESCE(dmu.totalCost, 0) as totalCost,
+ dmu.daily_usage_tuple as usage
+ FROM daily_model_usage dmu
+ FULL OUTER JOIN trace_usage tu ON dmu.date = tu.date
+ ORDER BY date DESC
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
+
+ const timestamp = props.fromTimestamp
+ ? new Date(props.fromTimestamp)
+ : timeFilter?.value;
+
+ return measureAndReturn({
+ operationName: "generateDailyMetrics",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedTracesFilter.params,
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ ...(timeFilter
+ ? {
+ cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),
+ }
+ : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "daily_metrics",
+ projectId: props.projectId,
+ operation_name: "generateDailyMetrics",
+ },
+ timestamp,
+ },
+ fn: async (input: {
+ params: Record<string, unknown>;
+ tags: Record<string, string>;
+ timestamp?: Date;
+ }) => {
+ const result = await queryClickhouse<{
+ date: string;
+ countTraces: number;
+ countObservations: number;
+ totalCost: number;
+ usage: (string | null)[][];
+ }>({
+ query: query.replaceAll("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs: {
+ request_timeout: 60_000,
+ },
+ });
+
+ return result.map((record) => ({
+ date: record.date,
+ countTraces: Number(record.countTraces),
+ countObservations: Number(record.countObservations),
+ totalCost: Number(record.totalCost),
+ usage: record.usage.map((u) => ({
+ model: u[0],
+ inputUsage: Number(u[1]),
+ outputUsage: Number(u[2]),
+ totalUsage: Number(u[3]),
+ totalCost: Number(u[4]),
+ countObservations: Number(u[5]),
+ countTraces: Number(u[6]),
+ })),
+ }));
+ },
+ });
+};
+
+export const getDailyMetricsCount = async (props: QueryType) => {
+ const filter = convertApiProvidedFilterToClickhouseFilter(
+ props,
+ filterParams,
+ );
+ const appliedFilter = filter
+ .filter((f) => f.clickhouseTable === "traces")
+ .apply();
+
+ const query = `
+ SELECT count(distinct toDate(timestamp)) as count
+ FROM __TRACE_TABLE__ t
+ WHERE project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ `;
+
+ const timestamp = props.fromTimestamp
+ ? new Date(props.fromTimestamp)
+ : undefined;
+
+ return measureAndReturn({
+ operationName: "getDailyMetricsCount",
+ projectId: props.projectId,
+ input: {
+ params: { ...appliedFilter.params, projectId: props.projectId },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "daily_metrics_count",
+ projectId: props.projectId,
+ operation_name: "getDailyMetricsCount",
+ },
+ timestamp,
+ },
+ fn: async (input: {
+ params: Record<string, unknown>;
+ tags: Record<string, string>;
+ timestamp?: Date;
+ }) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
+ });
+};
+
+const filterParams = [
+ {
+ id: "userId",
+ clickhouseSelect: "user_id",
+ filterType: "StringFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "traceName",
+ clickhouseSelect: "name",
+ filterType: "StringFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "tags",
+ clickhouseSelect: "tags",
+ filterType: "ArrayOptionsFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "traceEnvironment",
+ clickhouseSelect: "environment",
+ filterType: "StringOptionsFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "observationEnvironment",
+ clickhouseSelect: "environment",
+ filterType: "StringOptionsFilter",
+ clickhouseTable: "observations",
+ clickhousePrefix: "o",
+ },
+ {
+ 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",
+ },
+];
diff --git a/packages/shared/src/server/repositories/dataset-runs.ts b/packages/shared/src/server/repositories/dataset-runs.ts
new file mode 100644
index 0000000000..51a36ac1ed
--- /dev/null
+++ b/packages/shared/src/server/repositories/dataset-runs.ts
@@ -0,0 +1,97 @@
+import { type jsonSchema } from "../../utils/zod";
+import { prisma } from "../../db";
+import { v4 } from "uuid";
+import type z from "zod";
+
+type Json = z.infer<typeof jsonSchema>;
+
+const isUniqueConstraintError = (error: any): boolean => {
+ return (
+ error.code === "P2002" || // Prisma unique constraint
+ error.message?.includes("duplicate key") ||
+ error.message?.toLowerCase().includes("unique constraint") ||
+ error.message?.includes("violates unique constraint")
+ );
+};
+
+/**
+ * Create or fetch a dataset run with optimistic concurrency handling.
+ *
+ * Behavior:
+ * - First tries to find an existing run by (projectId, datasetId, name).
+ * - If not found, attempts to create it.
+ * - If creation fails due to a unique constraint (likely created concurrently),
+ * fetches and returns the existing run.
+ * - If all steps fail, throws an error.
+ *
+ * Rationale: The public API can receive many POST requests almost simultaneously,
+ * which is not concurrency-safe without this guard.
+ */
+export const createOrFetchDatasetRun = async ({
+ projectId,
+ datasetId,
+ name,
+ description,
+ metadata,
+ createdAt,
+}: {
+ projectId: string;
+ datasetId: string;
+ name: string;
+ description?: string;
+ metadata?: Json | null;
+ createdAt?: Date;
+}) => {
+ try {
+ // Attempt to fetch existing run
+ const existingRun = await prisma.datasetRuns.findUnique({
+ where: {
+ datasetId_projectId_name: {
+ datasetId,
+ projectId,
+ name: name,
+ },
+ },
+ });
+ if (existingRun) {
+ return existingRun;
+ }
+
+ // Attempt creation
+ const datasetRun = await prisma.datasetRuns.create({
+ data: {
+ id: v4(),
+ datasetId,
+ projectId,
+ name,
+ description: description ?? null,
+ metadata: metadata ?? {},
+ createdAt: createdAt ?? new Date(),
+ updatedAt: createdAt ?? new Date(),
+ },
+ });
+ return datasetRun;
+ } catch (error) {
+ // Check if it's a unique constraint violation
+ if (isUniqueConstraintError(error)) {
+ // Fetch existing run
+ const existingRun = await prisma.datasetRuns.findUnique({
+ where: {
+ datasetId_projectId_name: {
+ datasetId,
+ projectId,
+ name: name,
+ },
+ },
+ });
+
+ if (existingRun) {
+ return existingRun;
+ }
+ } else {
+ throw error;
+ }
+ }
+
+ throw new Error("Failed to create or fetch dataset run");
+};
diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.ts
index e19e7ae546..9c7e59ef0b 100644
--- a/packages/shared/src/server/repositories/index.ts
+++ b/packages/shared/src/server/repositories/index.ts
@@ -21,3 +21,6 @@ export * from "./dataset-items";
export * from "./comments";
export * from "./experiments";
export * from "./job-executions";
+export * from "./daily-metrics";
+export * from "./dataset-runs";
+export * from "./score-configs";
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 19bfc51580..be9acd535f 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -16,6 +16,8 @@ import {
StringFilter,
FullObservations,
orderByToClickhouseSql,
+ createPublicApiObservationsColumnMapping,
+ deriveFilters,
} from "../queries";
import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";
import {
@@ -2114,3 +2116,191 @@ export const getCostByEvaluatorIds = async (
totalCost: Number(row.total_cost),
}));
};
+
+// ─── Public-API observation query helpers ─────────────────────────────────────
+
+type PublicApiObservationQueryType = {
+ page: number;
+ limit: number;
+ projectId: string;
+ traceId?: string;
+ userId?: string;
+ name?: string;
+ type?: string;
+ parentObservationId?: string;
+ fromStartTime?: string;
+ toStartTime?: string;
+ version?: string;
+ advancedFilters?: FilterState;
+};
+
+export const generateObservationsForPublicApi = async (
+ props: PublicApiObservationQueryType,
+) => {
+ const chFilter = generatePublicApiObservationFilter(props);
+ const appliedFilter = chFilter.apply();
+ const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
+
+ const disableObservationsFinal = await shouldSkipObservationsFinal(
+ props.projectId,
+ );
+
+ const query = `
+ with clickhouse_keys as (
+ SELECT DISTINCT
+ id,
+ trace_id,
+ project_id,
+ type,
+ toDate(start_time)
+ FROM observations o
+ ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
+ WHERE o.project_id = {projectId: String}
+ ${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
+ AND ${appliedFilter.query}
+ ORDER BY start_time DESC
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ )
+ SELECT
+ id,
+ trace_id,
+ project_id,
+ type,
+ parent_observation_id,
+ environment,
+ start_time,
+ end_time,
+ name,
+ metadata,
+ level,
+ status_message,
+ version,
+ input,
+ output,
+ provided_model_name,
+ 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 observations o ${disableObservationsFinal ? "" : "FINAL"}
+ WHERE o.project_id = {projectId: String}
+ AND (id, trace_id, project_id, type, toDate(start_time)) in (select * from clickhouse_keys)
+ ORDER BY start_time DESC
+ `;
+
+ return measureAndReturn({
+ operationName: "generateObservationsForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "observation",
+ projectId: props.projectId,
+ operation_name: "generateObservationsForPublicApi",
+ },
+ },
+ fn: async (input) => {
+ const result = await queryClickhouse<ObservationRecordReadType>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+ return result.map((r) => convertObservation(r));
+ },
+ });
+};
+
+export const getObservationsCountForPublicApi = async (
+ props: PublicApiObservationQueryType,
+) => {
+ const chFilter = generatePublicApiObservationFilter(props);
+ const filter = chFilter.apply();
+ const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
+
+ const query = `
+ SELECT count() as count
+ FROM observations o
+ ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
+ WHERE o.project_id = {projectId: String}
+ ${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
+ AND ${filter.query}
+ `;
+
+ return measureAndReturn({
+ operationName: "getObservationsCountForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: { ...filter.params, projectId: props.projectId },
+ tags: {
+ feature: "tracing",
+ type: "observation",
+ projectId: props.projectId,
+ operation_name: "getObservationsCountForPublicApi",
+ },
+ },
+ fn: async (input) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
+ });
+};
+
+const publicApiObservationsFilterParams =
+ createPublicApiObservationsColumnMapping(
+ "observations",
+ "o",
+ "parent_observation_id",
+ );
+
+const generatePublicApiObservationFilter = (
+ query: PublicApiObservationQueryType,
+) => {
+ const { advancedFilters, ...simpleFilterProps } = query;
+ const chFilter = deriveFilters(
+ simpleFilterProps,
+ publicApiObservationsFilterParams,
+ advancedFilters,
+ observationsTableUiColumnDefinitions.filter(
+ (c) => c.clickhouseTableName !== "scores",
+ ),
+ observationsTableCols,
+ );
+
+ const filteredChFilter = chFilter.filter(
+ (f) => f.clickhouseTable !== "scores",
+ );
+
+ filteredChFilter.push(
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: query.projectId,
+ }),
+ );
+ return filteredChFilter;
+};
diff --git a/packages/shared/src/server/repositories/score-configs.ts b/packages/shared/src/server/repositories/score-configs.ts
new file mode 100644
index 0000000000..d9fc564df1
--- /dev/null
+++ b/packages/shared/src/server/repositories/score-configs.ts
@@ -0,0 +1,77 @@
+import { prisma } from "../../db";
+import {
+ filterAndValidateDbScoreConfigList,
+ validateDbScoreConfigSafe,
+} from "../../features/scoreConfigs/validation";
+import { LangfuseNotFoundError, InternalServerError } from "../../errors";
+import { traceException } from "../instrumentation";
+
+export const listScoreConfigs = async ({
+ projectId,
+ page,
+ limit,
+}: {
+ projectId: string;
+ page: number;
+ limit: number;
+}) => {
+ const [rawConfigs, totalItems] = await Promise.all([
+ prisma.scoreConfig.findMany({
+ where: {
+ projectId,
+ },
+ orderBy: [{ createdAt: "desc" }, { id: "asc" }],
+ take: limit,
+ skip: (page - 1) * limit,
+ }),
+ prisma.scoreConfig.count({
+ where: {
+ projectId,
+ },
+ }),
+ ]);
+
+ const configs = filterAndValidateDbScoreConfigList(
+ rawConfigs,
+ traceException,
+ );
+
+ return {
+ data: configs,
+ meta: {
+ page,
+ limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / limit),
+ },
+ };
+};
+
+export const getScoreConfig = async ({
+ projectId,
+ configId,
+}: {
+ projectId: string;
+ configId: string;
+}) => {
+ const config = await prisma.scoreConfig.findUnique({
+ where: {
+ id: configId,
+ projectId,
+ },
+ });
+
+ if (!config) {
+ throw new LangfuseNotFoundError(
+ "Score config not found within authorized project",
+ );
+ }
+
+ const parsedConfig = validateDbScoreConfigSafe(config);
+ if (!parsedConfig.success) {
+ traceException(parsedConfig.error);
+ throw new InternalServerError("Requested score config is corrupted");
+ }
+
+ return parsedConfig.data;
+};
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 3942aeefdb..4e81acabf7 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -1,3 +1,4 @@
+import { z } from "zod";
import {
ScoreDataTypeType,
ScoreDomain,
@@ -7,14 +8,30 @@ import {
ScoreByDataType,
LISTABLE_SCORE_TYPES,
ListableScoreDataType,
+ ScoreDataTypeEnum,
} from "../../domain/scores";
+import { InvalidRequestError, InternalServerError } from "../../errors";
+import type { APIScoreV3 } from "../../features/scores/interfaces/api/v3/schemas";
+import type { ScoreFieldGroupV3 } from "../../features/scores/interfaces/api/v3/endpoints";
+import { filterAndValidateV3GetScoreList } from "../../features/scores/interfaces/api/v3/validation";
import {
commandClickhouse,
queryClickhouse,
queryClickhouseStream,
upsertClickhouse,
+ parseClickhouseUTCDateTimeFormat,
+ clickhouseCompliantRandomCharacters,
} from "./clickhouse";
-import { FilterList, orderByToClickhouseSql } from "../queries";
+import {
+ FilterList,
+ orderByToClickhouseSql,
+ StringFilter,
+ StringOptionsFilter,
+ DateTimeFilter,
+ NumberFilter,
+ convertApiProvidedFilterToClickhouseFilter,
+ deriveFilters,
+} from "../queries";
import { FilterCondition, FilterState, TimeFilter } from "../../types";
import {
createFilterFromFilterState,
@@ -43,6 +60,7 @@ import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
import type { AnalyticsScoreEvent } from "../analytics-integrations/types";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
+import { logger } from "../logger";
import { prisma } from "../../db";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { scoresColumnsTableUiColumnDefinitions } from "../tableMappings/mapScoresColumnsTable";
@@ -2331,3 +2349,898 @@ export const getScoreCountsByProjectAndDay = async ({
date: row.date,
}));
};
+
+// ─── Cursor helpers (v3 pagination) ───────────────────────────────────────────
+
+export const ScoresCursorV3 = z.discriminatedUnion("v", [
+ z.object({
+ v: z.literal(1),
+ lastTimestamp: z.coerce.date(),
+ lastId: z.string(),
+ }),
+]);
+export type ScoresCursorV3Type = z.infer<typeof ScoresCursorV3>;
+
+export const EncodedScoresCursorV3 = z
+ .string()
+ .transform((val) => {
+ try {
+ const decoded = Buffer.from(val, "base64url").toString("utf-8");
+ return JSON.parse(decoded);
+ } catch (_e) {
+ throw new InvalidRequestError("Invalid cursor format");
+ }
+ })
+ .pipe(ScoresCursorV3);
+
+export const encodeCursorV3 = (cursor: ScoresCursorV3Type): string =>
+ Buffer.from(
+ JSON.stringify({
+ v: cursor.v,
+ lastTimestamp: cursor.lastTimestamp.toISOString(),
+ lastId: cursor.lastId,
+ }),
+ ).toString("base64url");
+
+// ─── v1/v2 public-API score query helpers ─────────────────────────────────────
+
+export type ScoreQueryType = {
+ page: number;
+ limit: number;
+ projectId: string;
+ traceId?: string;
+ userId?: string;
+ name?: string;
+ source?: string;
+ fromTimestamp?: string;
+ toTimestamp?: string;
+ value?: number;
+ scoreId?: string;
+ configId?: string;
+ sessionId?: string;
+ datasetRunId?: string;
+ queueId?: string;
+ traceTags?: string | string[];
+ operator?: string;
+ scoreIds?: string[];
+ observationId?: string[];
+ dataType?: string;
+ environment?: string | string[];
+ fields?: string[] | null;
+ advancedFilters?: FilterState;
+};
+
+const secureScoreFilterOptions = [
+ {
+ id: "traceId",
+ clickhouseSelect: "trace_id",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "observationId",
+ clickhouseSelect: "observation_id",
+ clickhouseTable: "scores",
+ filterType: "StringOptionsFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "name",
+ clickhouseSelect: "name",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "source",
+ clickhouseSelect: "source",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "fromTimestamp",
+ clickhouseSelect: "timestamp",
+ operator: ">=" as const,
+ clickhouseTable: "scores",
+ filterType: "DateTimeFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "toTimestamp",
+ clickhouseSelect: "timestamp",
+ operator: "<" as const,
+ clickhouseTable: "scores",
+ filterType: "DateTimeFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "value",
+ clickhouseSelect: "value",
+ clickhouseTable: "scores",
+ filterType: "NumberFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "scoreIds",
+ clickhouseSelect: "id",
+ clickhouseTable: "scores",
+ filterType: "StringOptionsFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "configId",
+ clickhouseSelect: "config_id",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "sessionId",
+ clickhouseSelect: "session_id",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "datasetRunId",
+ clickhouseSelect: "dataset_run_id",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "queueId",
+ clickhouseSelect: "queue_id",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "environment",
+ clickhouseSelect: "environment",
+ clickhouseTable: "scores",
+ filterType: "StringOptionsFilter",
+ clickhousePrefix: "s",
+ },
+ {
+ id: "dataType",
+ clickhouseSelect: "data_type",
+ clickhouseTable: "scores",
+ filterType: "StringFilter",
+ clickhousePrefix: "s",
+ },
+];
+
+const secureTraceFilterOptions = [
+ {
+ id: "traceTags",
+ clickhouseSelect: "tags",
+ clickhouseTable: "traces",
+ filterType: "ArrayOptionsFilter",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "userId",
+ clickhouseSelect: "user_id",
+ clickhouseTable: "traces",
+ filterType: "StringFilter",
+ clickhousePrefix: "t",
+ },
+];
+
+const determineTraceJoinRequirement = (
+ fields: string[] | null | undefined,
+ tracesFilterLength: number,
+) => {
+ const requestedFields = fields ?? ["score", "trace"];
+ const includeTrace = requestedFields.includes("trace");
+ const needsTraceJoin = includeTrace || tracesFilterLength > 0;
+ return { includeTrace, needsTraceJoin };
+};
+
+const generateScoreFilter = (
+ filter: ScoreQueryType,
+ scoreDataTypes?: readonly ScoreDataTypeType[],
+) => {
+ const scoresFilter = deriveFilters(
+ filter,
+ secureScoreFilterOptions,
+ filter.advancedFilters,
+ scoresTableUiColumnDefinitions,
+ scoresTableCols,
+ );
+ scoresFilter.push(
+ new StringFilter({
+ clickhouseTable: "scores",
+ field: "project_id",
+ operator: "=",
+ value: filter.projectId,
+ }),
+ );
+
+ if (scoreDataTypes) {
+ scoresFilter.push(
+ new StringOptionsFilter({
+ clickhouseTable: "scores",
+ field: "data_type",
+ operator: "any of",
+ values: [...scoreDataTypes],
+ tablePrefix: "s",
+ }),
+ );
+ }
+
+ const tracesFilter = convertApiProvidedFilterToClickhouseFilter(
+ filter,
+ secureTraceFilterOptions,
+ );
+
+ if (filter.environment && tracesFilter.length() > 0) {
+ const envValues = Array.isArray(filter.environment)
+ ? filter.environment
+ : [filter.environment];
+ tracesFilter.push(
+ new StringOptionsFilter({
+ clickhouseTable: "traces",
+ field: "environment",
+ operator: "any of",
+ values: envValues,
+ tablePrefix: "t",
+ }),
+ );
+ }
+
+ return { scoresFilter, tracesFilter };
+};
+
+export const _handleGenerateScoresForPublicApi = async ({
+ props,
+ scoreScope,
+ scoreDataTypes,
+}: {
+ props: ScoreQueryType;
+ scoreScope: "traces_only" | "all";
+ scoreDataTypes?: readonly ScoreDataTypeType[];
+}) => {
+ const { scoresFilter, tracesFilter } = generateScoreFilter(
+ props,
+ scoreDataTypes,
+ );
+ const appliedScoresFilter = scoresFilter.apply();
+ const appliedTracesFilter = tracesFilter.apply();
+
+ const { includeTrace, needsTraceJoin } = determineTraceJoinRequirement(
+ props.fields,
+ tracesFilter.length(),
+ );
+
+ const query = `
+ SELECT
+ ${needsTraceJoin ? "t.user_id as user_id, t.tags as tags, t.environment as trace_environment, t.session_id as trace_session_id," : ""}
+ s.id as id,
+ s.project_id as project_id,
+ s.timestamp as timestamp,
+ s.environment as environment,
+ s.name as name,
+ s.value as value,
+ s.string_value as string_value,
+ s.long_string_value as long_string_value,
+ s.author_user_id as author_user_id,
+ s.created_at as created_at,
+ s.updated_at as updated_at,
+ s.source as source,
+ s.comment as comment,
+ s.metadata as metadata,
+ s.data_type as data_type,
+ s.config_id as config_id,
+ s.queue_id as queue_id,
+ s.execution_trace_id as execution_trace_id,
+ s.trace_id as trace_id,
+ s.observation_id as observation_id,
+ s.session_id as session_id,
+ s.dataset_run_id as dataset_run_id
+ FROM
+ scores s
+ ${needsTraceJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}
+ WHERE
+ s.project_id = {projectId: String}
+ AND (
+ ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}
+ (s.trace_id IS NOT NULL AND (${needsTraceJoin ? "t.id, t.project_id" : "s.trace_id, s.project_id"}) IN (
+ SELECT
+ ${needsTraceJoin ? "trace_id, project_id" : "s.trace_id, s.project_id"}
+ FROM
+ scores s
+ WHERE
+ s.project_id = {projectId: String}
+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
+ ORDER BY
+ s.timestamp desc
+ LIMIT
+ 1 BY s.id, s.project_id
+ ))
+ )
+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
+ ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}
+ ORDER BY
+ s.timestamp desc, s.event_ts desc
+ LIMIT
+ 1 BY s.id, s.project_id
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
+
+ return measureAndReturn({
+ operationName: "_handleGenerateScoresForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedScoresFilter.params,
+ ...appliedTracesFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ },
+ tags: {
+ feature: "scoring",
+ type: "score",
+ projectId: props.projectId,
+ scoreScope,
+ operation_name: "_handleGenerateScoresForPublicApi",
+ includeTrace: includeTrace.toString(),
+ },
+ },
+ fn: async (input) => {
+ const records = await queryClickhouse<
+ ScoreRecordReadType & {
+ tags?: string[];
+ user_id?: string;
+ trace_environment?: string;
+ trace_session_id?: string | null;
+ }
+ >({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+
+ return records.map((record) => {
+ const domainScore = convertClickhouseScoreToDomain(record);
+ return {
+ ...domainScore,
+ trace:
+ includeTrace && record.trace_id !== null
+ ? {
+ userId: record.user_id,
+ tags: record.tags,
+ environment: record.trace_environment,
+ sessionId: record.trace_session_id,
+ }
+ : null,
+ };
+ });
+ },
+ });
+};
+
+export const _handleGetScoresCountForPublicApi = async ({
+ props,
+ scoreScope,
+ scoreDataTypes,
+}: {
+ props: ScoreQueryType;
+ scoreScope: "traces_only" | "all";
+ scoreDataTypes?: readonly ScoreDataTypeType[];
+}) => {
+ const { scoresFilter, tracesFilter } = generateScoreFilter(
+ props,
+ scoreDataTypes,
+ );
+ const appliedScoresFilter = scoresFilter.apply();
+ const appliedTracesFilter = tracesFilter.apply();
+
+ const { includeTrace, needsTraceJoin } = determineTraceJoinRequirement(
+ props.fields,
+ tracesFilter.length(),
+ );
+
+ const query = `
+ SELECT
+ count() as count
+ FROM
+ scores s
+ ${needsTraceJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}
+ WHERE
+ s.project_id = {projectId: String}
+ AND (
+ ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}
+ (s.trace_id IS NOT NULL AND (${needsTraceJoin ? "t.id, t.project_id" : "s.trace_id, s.project_id"}) IN (
+ SELECT
+ ${needsTraceJoin ? "trace_id, project_id" : "s.trace_id, s.project_id"}
+ FROM
+ scores s
+ WHERE
+ s.project_id = {projectId: String}
+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}
+ ORDER BY
+ s.timestamp desc
+ LIMIT
+ 1 BY s.id, s.project_id
+ ))
+ )
+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
+ ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}
+ `;
+
+ return measureAndReturn({
+ operationName: "_handleGetScoresCountForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedScoresFilter.params,
+ ...appliedTracesFilter.params,
+ projectId: props.projectId,
+ },
+ tags: {
+ feature: "scoring",
+ type: "score",
+ projectId: props.projectId,
+ scoreScope,
+ operation_name: "_handleGetScoresCountForPublicApi",
+ includeTrace: includeTrace.toString(),
+ },
+ },
+ fn: async (input) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
+ });
+};
+
+// ─── v3 public-API score query helpers ────────────────────────────────────────
+
+type ListFilterParams = {
+ id?: string[];
+ name?: string[];
+ source?: string[];
+ dataType?: string[];
+ environment?: string[];
+ configId?: string[];
+ queueId?: string[];
+ authorUserId?: string[];
+ value?: string[];
+ valueMin?: number;
+ valueMax?: number;
+ traceId?: string[];
+ sessionId?: string[];
+ observationId?: string[];
+ experimentId?: string[];
+ fromTimestamp?: Date;
+ toTimestamp?: Date;
+};
+
+const CORE_COLUMNS_V3 = [
+ "s.id as id",
+ "s.project_id as project_id",
+ "s.timestamp as timestamp",
+ "s.environment as environment",
+ "s.name as name",
+ "s.value as value",
+ "s.string_value as string_value",
+ "s.long_string_value as long_string_value",
+ "s.source as source",
+ "s.data_type as data_type",
+ "s.created_at as created_at",
+ "s.updated_at as updated_at",
+ "s.execution_trace_id as execution_trace_id",
+];
+const DETAILS_COLUMNS_V3 = [
+ "s.comment as comment",
+ "s.metadata as metadata",
+ "s.config_id as config_id",
+];
+const SUBJECT_COLUMNS_V3 = [
+ "s.trace_id as trace_id",
+ "s.observation_id as observation_id",
+ "s.session_id as session_id",
+ "s.dataset_run_id as dataset_run_id",
+];
+const ANNOTATION_COLUMNS_V3 = [
+ "s.author_user_id as author_user_id",
+ "s.queue_id as queue_id",
+];
+
+export const buildSelectColumns = (fields: ScoreFieldGroupV3[]): string => {
+ const selected = [...CORE_COLUMNS_V3];
+ if (fields.includes("details")) selected.push(...DETAILS_COLUMNS_V3);
+ if (fields.includes("subject")) selected.push(...SUBJECT_COLUMNS_V3);
+ if (fields.includes("annotation")) selected.push(...ANNOTATION_COLUMNS_V3);
+ return selected.join(",\n ");
+};
+
+export function transformBooleanValueForFilter(v: "true" | "false"): number {
+ if (v === "true") return 1;
+ if (v === "false") return 0;
+ throw new InternalServerError(
+ `transformBooleanValueForFilter received unexpected value: ${v}`,
+ );
+}
+
+function buildDynamicFilters(params: ListFilterParams): {
+ query: string;
+ params: Record<string, unknown>;
+} {
+ const filterList = new FilterList();
+
+ type StringOptionFilterKey = Extract<
+ keyof ListFilterParams,
+ | "id"
+ | "name"
+ | "source"
+ | "dataType"
+ | "environment"
+ | "configId"
+ | "queueId"
+ | "authorUserId"
+ | "traceId"
+ | "sessionId"
+ | "observationId"
+ | "experimentId"
+ >;
+
+ const STRING_OPTIONS_FILTERS: ReadonlyArray<{
+ key: StringOptionFilterKey;
+ field: string;
+ }> = [
+ { key: "id", field: "id" },
+ { key: "name", field: "name" },
+ { key: "source", field: "source" },
+ { key: "dataType", field: "data_type" },
+ { key: "environment", field: "environment" },
+ { key: "configId", field: "config_id" },
+ { key: "queueId", field: "queue_id" },
+ { key: "authorUserId", field: "author_user_id" },
+ { key: "traceId", field: "trace_id" },
+ { key: "sessionId", field: "session_id" },
+ { key: "observationId", field: "observation_id" },
+ { key: "experimentId", field: "dataset_run_id" },
+ ];
+
+ for (const { key, field } of STRING_OPTIONS_FILTERS) {
+ const values = params[key];
+ if (values?.length) {
+ filterList.push(
+ new StringOptionsFilter({
+ clickhouseTable: "scores",
+ field,
+ operator: "any of",
+ values,
+ tablePrefix: "s",
+ }),
+ );
+ }
+ }
+ if (params.fromTimestamp !== undefined)
+ filterList.push(
+ new DateTimeFilter({
+ clickhouseTable: "scores",
+ field: "timestamp",
+ operator: ">=",
+ value: params.fromTimestamp,
+ tablePrefix: "s",
+ }),
+ );
+ if (params.toTimestamp !== undefined)
+ filterList.push(
+ new DateTimeFilter({
+ clickhouseTable: "scores",
+ field: "timestamp",
+ operator: "<",
+ value: params.toTimestamp,
+ tablePrefix: "s",
+ }),
+ );
+ if (params.valueMin !== undefined)
+ filterList.push(
+ new NumberFilter({
+ clickhouseTable: "scores",
+ field: "value",
+ operator: ">=",
+ value: params.valueMin,
+ tablePrefix: "s",
+ clickhouseTypeOverwrite: "Float64",
+ }),
+ );
+ if (params.valueMax !== undefined)
+ filterList.push(
+ new NumberFilter({
+ clickhouseTable: "scores",
+ field: "value",
+ operator: "<=",
+ value: params.valueMax,
+ tablePrefix: "s",
+ clickhouseTypeOverwrite: "Float64",
+ }),
+ );
+
+ const compiled = filterList.apply();
+
+ const extraClauses: string[] = [];
+ const extraParams: Record<string, unknown> = {};
+
+ if (params.value?.length && params.dataType?.length === 1) {
+ const dt = params.dataType[0] as ScoreDataTypeType;
+ const uid = clickhouseCompliantRandomCharacters();
+ const varName = `valueFilter${uid}`;
+
+ switch (dt) {
+ case ScoreDataTypeEnum.NUMERIC: {
+ extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);
+ extraParams[varName] = params.value.map((v) => {
+ const n = Number(v);
+ if (!Number.isFinite(n)) {
+ throw new InternalServerError(
+ `NUMERIC value filter received non-finite value: ${v}`,
+ );
+ }
+ return n;
+ });
+ break;
+ }
+ case ScoreDataTypeEnum.BOOLEAN: {
+ extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);
+ extraParams[varName] = params.value.map((v) =>
+ transformBooleanValueForFilter(v as "true" | "false"),
+ );
+ break;
+ }
+ case ScoreDataTypeEnum.CATEGORICAL: {
+ extraClauses.push(`s.string_value IN ({${varName}: Array(String)})`);
+ extraParams[varName] = params.value;
+ break;
+ }
+ case ScoreDataTypeEnum.TEXT:
+ case ScoreDataTypeEnum.CORRECTION:
+ throw new InternalServerError(
+ `value filter with dataType=${dt} should have been rejected by handler validation`,
+ );
+ default: {
+ const _exhaustiveCheck: never = dt;
+ throw new InternalServerError(
+ `value filter received unknown dataType: ${_exhaustiveCheck as string}`,
+ );
+ }
+ }
+ }
+
+ const allClauses = [compiled.query, ...extraClauses]
+ .filter(Boolean)
+ .join(" AND ");
+
+ return { query: allClauses, params: { ...compiled.params, ...extraParams } };
+}
+
+const buildV3ListQuery = (
+ withCursor: boolean,
+ fields: ScoreFieldGroupV3[],
+ filterClause: string,
+) => `
+ SELECT
+ ${buildSelectColumns(fields)}
+ FROM scores s
+ WHERE s.project_id = {projectId: String}
+ ${
+ withCursor
+ ? "AND (s.timestamp, s.id) < ({lastTimestamp: DateTime64(3)}, {lastId: String})"
+ : ""
+ }
+ ${filterClause ? `AND ${filterClause}` : ""}
+ ORDER BY s.timestamp DESC, s.id DESC, s.event_ts DESC
+ LIMIT 1 BY s.id, s.project_id
+ LIMIT {limit: Int32}
+`;
+
+export function polymorphicValueForV3(score: {
+ dataType: ScoreDataTypeType;
+ value: number;
+ stringValue?: string | null;
+ longStringValue?: string | null;
+}): number | boolean | string {
+ switch (score.dataType) {
+ case ScoreDataTypeEnum.NUMERIC:
+ return score.value;
+ case ScoreDataTypeEnum.BOOLEAN:
+ return score.value === 1;
+ case ScoreDataTypeEnum.CATEGORICAL:
+ case ScoreDataTypeEnum.TEXT:
+ if (score.stringValue == null) {
+ throw new InternalServerError(
+ `Score with dataType ${score.dataType} is missing its stringValue`,
+ );
+ }
+ return score.stringValue;
+ case ScoreDataTypeEnum.CORRECTION:
+ if (score.longStringValue == null) {
+ throw new InternalServerError(
+ "Score with dataType CORRECTION is missing its longStringValue",
+ );
+ }
+ return score.longStringValue;
+ default: {
+ const _exhaustiveCheck: never = score.dataType;
+ throw new InternalServerError(
+ `Score has unknown dataType: ${_exhaustiveCheck as string}`,
+ );
+ }
+ }
+}
+
+function deriveSubjectForV3(
+ score: ScoreDomain,
+):
+ | { kind: "observation"; id: string; traceId?: string }
+ | { kind: "trace" | "session" | "experiment"; id: string } {
+ if (score.datasetRunId) {
+ return { kind: "experiment", id: score.datasetRunId };
+ }
+ if (score.observationId) {
+ return {
+ kind: "observation",
+ id: score.observationId,
+ ...(score.traceId ? { traceId: score.traceId } : {}),
+ };
+ }
+ if (score.sessionId) {
+ return { kind: "session", id: score.sessionId };
+ }
+ if (!score.traceId) {
+ throw new InternalServerError(
+ `Score ${score.id} has kind=trace but missing traceId`,
+ );
+ }
+ return { kind: "trace", id: score.traceId };
+}
+
+function domainToV3Shared(
+ score: ScoreDomain,
+ fields: ScoreFieldGroupV3[],
+): APIScoreV3 {
+ return {
+ id: score.id,
+ projectId: score.projectId,
+ name: score.name,
+ dataType: score.dataType,
+ value: polymorphicValueForV3({
+ dataType: score.dataType,
+ value: score.value,
+ stringValue: score.stringValue as string | null | undefined,
+ longStringValue: score.longStringValue as string | null | undefined,
+ }),
+ source: score.source,
+ timestamp: score.timestamp,
+ environment: score.environment,
+ createdAt: score.createdAt,
+ updatedAt: score.updatedAt,
+ ...(fields.includes("details")
+ ? {
+ comment: score.comment,
+ configId: score.configId,
+ metadata: score.metadata,
+ }
+ : {}),
+ ...(fields.includes("annotation")
+ ? {
+ authorUserId: score.authorUserId,
+ queueId: score.queueId,
+ }
+ : {}),
+ ...(fields.includes("subject")
+ ? { subject: deriveSubjectForV3(score) }
+ : {}),
+ } as APIScoreV3;
+}
+
+export async function listScoresV3ForPublicApi(
+ params: {
+ projectId: string;
+ limit: number;
+ cursor?: ScoresCursorV3Type;
+ fields: ScoreFieldGroupV3[];
+ } & ListFilterParams,
+): Promise<{ data: APIScoreV3[]; cursor?: string }> {
+ const { query: filterClause, params: filterParams } =
+ buildDynamicFilters(params);
+
+ return measureAndReturn({
+ operationName: "listScoresV3ForPublicApi",
+ projectId: params.projectId,
+ input: {
+ params: {
+ projectId: params.projectId,
+ limit: params.limit + 1,
+ ...(params.cursor && {
+ lastTimestamp: convertDateToClickhouseDateTime(
+ params.cursor.lastTimestamp,
+ ),
+ lastId: params.cursor.lastId,
+ }),
+ ...filterParams,
+ },
+ tags: {
+ feature: "scoring",
+ type: "score",
+ projectId: params.projectId,
+ operation_name: "listScoresV3ForPublicApi",
+ },
+ },
+ fn: async (input) => {
+ const records = await queryClickhouse<ScoreRecordReadType>({
+ query: buildV3ListQuery(
+ Boolean(params.cursor),
+ params.fields,
+ filterClause,
+ ),
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+
+ const hasMore = records.length > params.limit;
+ const pageRecords = hasMore ? records.slice(0, params.limit) : records;
+
+ let nextCursor: string | undefined;
+ if (hasMore && pageRecords.length > 0) {
+ const last = pageRecords[pageRecords.length - 1];
+ nextCursor = encodeCursorV3({
+ v: 1,
+ lastTimestamp: parseClickhouseUTCDateTimeFormat(
+ String(last.timestamp),
+ ),
+ lastId: last.id,
+ });
+ }
+
+ const items: APIScoreV3[] = [];
+ for (const row of pageRecords) {
+ try {
+ items.push(
+ domainToV3Shared(
+ convertClickhouseScoreToDomain(row),
+ params.fields,
+ ),
+ );
+ } catch (error) {
+ logger.error("v3 score row dropped from response: conversion error", {
+ error,
+ scoreId: row.id,
+ projectId: params.projectId,
+ });
+ }
+ }
+ return {
+ data: filterAndValidateV3GetScoreList(items, (error) => {
+ logger.error(
+ "v3 score row dropped from response: schema validation error",
+ {
+ issues: error.issues,
+ projectId: params.projectId,
+ },
+ );
+ }),
+ cursor: nextCursor,
+ };
+ },
+ });
+}
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 5719ef7b35..dd75dbcd20 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -9,6 +9,15 @@ import {
createFilterFromFilterState,
getProjectIdDefaultFilter,
} from "../queries/clickhouse-sql/factory";
+import {
+ orderByToClickhouseSql,
+ deriveFilters,
+ createPublicApiTracesColumnMapping,
+} from "../queries";
+import { shouldSkipObservationsFinal } from "../queries/clickhouse-sql/query-options";
+import { LISTABLE_SCORE_TYPES } from "../../domain/scores";
+import { OrderByState } from "../../interfaces/orderBy";
+import snakeCase from "lodash/snakeCase";
import { FilterState } from "../../types";
import {
DateTimeFilter,
@@ -23,7 +32,10 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
-import { convertClickhouseToDomain } from "./traces_converters";
+import {
+ convertClickhouseToDomain,
+ convertClickhouseTracesListToDomain,
+} from "./traces_converters";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
OBSERVATIONS_TO_TRACE_INTERVAL,
@@ -1689,3 +1701,529 @@ export const getTraceCountsByProjectAndDay = async ({
date: row.date,
}));
};
+
+// ─── TRACE_FIELD_GROUPS (public-API field selection) ─────────────────────────
+
+export const TRACE_FIELD_GROUPS = [
+ "core",
+ "io",
+ "scores",
+ "observations",
+ "metrics",
+] as const;
+
+export type TraceFieldGroup = (typeof TRACE_FIELD_GROUPS)[number];
+
+// ─── Public-API trace query helpers ──────────────────────────────────────────
+
+export type TraceQueryType = {
+ page: number;
+ limit: number;
+ projectId: string;
+ traceId?: string;
+ userId?: string;
+ name?: string;
+ type?: string;
+ sessionId?: string;
+ version?: string;
+ release?: string;
+ tags?: string | string[];
+ environment?: string | string[];
+ fromTimestamp?: string;
+ toTimestamp?: string;
+ fields?: TraceFieldGroup[];
+ useEventsTable?: boolean | null;
+};
+
+const traceOrderByColumns = [
+ "id",
+ "timestamp",
+ "name",
+ "userId",
+ "release",
+ "version",
+ "public",
+ "bookmarked",
+ "sessionId",
+].map((name) => ({
+ uiTableName: name,
+ uiTableId: name,
+ clickhouseTableName: "traces",
+ clickhouseSelect: snakeCase(name),
+ queryPrefix: "t",
+}));
+
+const publicApiTracesFilterParams = createPublicApiTracesColumnMapping(
+ "traces",
+ "t",
+);
+
+async function buildTracesBaseQuery(
+ props: TraceQueryType,
+ select:
+ | {
+ includeObservations: boolean;
+ includeIO: boolean;
+ includeMetrics: boolean;
+ includeScores: boolean;
+ count: false;
+ }
+ | {
+ includeObservations: false;
+ includeIO: false;
+ includeMetrics: false;
+ includeScores: false;
+ count: true;
+ },
+ advancedFilters?: FilterState,
+ orderBy?: OrderByState,
+): Promise<{
+ query: string;
+ params: Record<string, any>;
+ fromTimeFilter?: DateTimeFilter | undefined;
+}> {
+ const disableObservationsFinal = await shouldSkipObservationsFinal(
+ props.projectId,
+ );
+ const propagateObservationsTimeBounds =
+ env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS === "true";
+
+ let filter = deriveFilters(
+ props,
+ publicApiTracesFilterParams,
+ advancedFilters,
+ tracesTableUiColumnDefinitions,
+ tracesTableCols,
+ );
+ const appliedFilter = filter.apply();
+
+ const fromTimeFilter = filter.find(
+ (f) =>
+ f.clickhouseTable === "traces" &&
+ f.field.includes("timestamp") &&
+ (f.operator === ">=" || f.operator === ">"),
+ ) as DateTimeFilter | undefined;
+ const toTimeFilter = filter.find(
+ (f) =>
+ f.clickhouseTable === "traces" &&
+ f.field.includes("timestamp") &&
+ (f.operator === "<=" || f.operator === "<"),
+ ) as DateTimeFilter | undefined;
+
+ const environmentFilter = filter
+ .filter((f) => f.field === "environment")
+ .map((f) => {
+ f.tablePrefix = undefined;
+ return f;
+ });
+ const appliedEnvironmentFilter = environmentFilter.apply();
+
+ const shouldUseSkipIndexes = filter.some(
+ (f) =>
+ f.clickhouseTable === "traces" &&
+ ["user_id", "session_id", "metadata"].some((skipIndexCol) =>
+ f.field.includes(skipIndexCol),
+ ),
+ );
+
+ const filtersNeedObservations = filter.some(
+ (f) => f.clickhouseTable === "observations",
+ );
+ const filtersNeedScores = filter.some((f) => f.clickhouseTable === "scores");
+
+ const hasScoreAggregationFilters = filter.some(
+ (f) => f.field === "s.scores_avg" || f.field === "s.score_categories",
+ );
+
+ const ctes = [];
+
+ if (
+ select.includeObservations ||
+ select.includeMetrics ||
+ filtersNeedObservations
+ ) {
+ const shouldUseFinal =
+ (select.includeMetrics || filtersNeedObservations) &&
+ !disableObservationsFinal;
+
+ const includeMetricsInCTE =
+ select.includeMetrics || filtersNeedObservations;
+
+ ctes.push(`
+ observation_stats AS (
+ SELECT
+ trace_id,
+ project_id,
+ ${includeMetricsInCTE ? "sum(total_cost) as total_cost, date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds, " : ""}
+ sumMap(usage_details) as usage_details,
+ sumMap(cost_details) as cost_details,
+ multiIf(arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR', arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING', arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT', 'DEBUG') AS aggregated_level,
+ countIf(level = 'WARNING') as warning_count,
+ countIf(level = 'ERROR') as error_count,
+ countIf(level = 'DEFAULT') as default_count,
+ countIf(level = 'DEBUG') as debug_count,
+ groupUniqArray(id) as observation_ids
+ FROM observations ${shouldUseFinal ? "FINAL" : ""}
+ WHERE project_id = {projectId: String}
+ ${fromTimeFilter ? `AND start_time >= {cteFromTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ${toTimeFilter && propagateObservationsTimeBounds ? `AND start_time <= {cteToTimeFilter: DateTime64(3)} + ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ${toTimeFilter && propagateObservationsTimeBounds ? `AND end_time <= {cteToTimeFilter: DateTime64(3)} + ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
+ GROUP BY project_id, trace_id
+ )`);
+ }
+
+ if (select.includeScores || filtersNeedScores) {
+ if (hasScoreAggregationFilters) {
+ ctes.push(`
+ score_stats AS (
+ SELECT
+ trace_id,
+ project_id,
+ groupUniqArray(id) as score_ids,
+ groupArrayIf(tuple(name, avg_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
+ groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories
+ FROM (
+ SELECT
+ project_id,
+ trace_id,
+ id,
+ name,
+ data_type,
+ string_value,
+ avg(value) as avg_value
+ FROM scores FINAL
+ WHERE project_id = {projectId: String}
+ AND session_id IS NULL
+ AND dataset_run_id IS NULL
+ AND data_type IN ({dataTypes: Array(String)})
+ ${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
+ ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
+ GROUP BY
+ project_id,
+ trace_id,
+ id,
+ name,
+ data_type,
+ string_value
+ ) tmp
+ GROUP BY project_id, trace_id
+ )`);
+ } else {
+ ctes.push(`
+ score_stats AS (
+ SELECT
+ trace_id,
+ project_id,
+ groupUniqArray(id) as score_ids,
+ groupArrayIf(tuple(name, value), data_type IN ('NUMERIC', 'BOOLEAN')) as scores_avg,
+ groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL') as score_categories
+ FROM scores
+ WHERE project_id = {projectId: String}
+ AND session_id IS NULL
+ AND dataset_run_id IS NULL
+ AND data_type IN ({dataTypes: Array(String)})
+ ${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
+ ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
+ GROUP BY project_id, trace_id
+ )`);
+ }
+ }
+
+ const withClause = ctes.length > 0 ? `WITH ${ctes.join(", ")}` : "";
+
+ const chOrderBy =
+ (orderByToClickhouseSql(orderBy || [], traceOrderByColumns) ||
+ "ORDER BY t.timestamp desc") +
+ (shouldUseSkipIndexes ? ", t.event_ts desc" : "");
+
+ const queryMiddle = `
+ FROM traces t ${shouldUseSkipIndexes ? "" : "FINAL"}
+ ${select.includeObservations || select.includeMetrics || filtersNeedObservations ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
+ ${select.includeScores || filtersNeedScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
+ WHERE t.project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ `;
+
+ const paginationClause =
+ props.limit !== undefined && props.page !== undefined
+ ? `LIMIT {limit: Int32} OFFSET {offset: Int32}`
+ : "";
+ const limitByClause = shouldUseSkipIndexes
+ ? "LIMIT 1 by t.id, t.project_id"
+ : "";
+
+ const coreSelect = `
+ t.id as id,
+ t.project_id as project_id,
+ t.timestamp as timestamp,
+ t.name as name,
+ t.environment as environment,
+ t.session_id as session_id,
+ t.user_id as user_id,
+ t.release as release,
+ t.version as version,
+ t.bookmarked as bookmarked,
+ t.public as public,
+ t.tags as tags,
+ t.created_at as created_at,
+ t.updated_at as updated_at`;
+
+ const scoresSelect = select.includeScores ? ", s.score_ids as scores" : "";
+ const observationsSelect = select.includeObservations
+ ? ", o.observation_ids as observations"
+ : "";
+ const metricsSelect = select.includeMetrics
+ ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost"
+ : "";
+
+ const finalOrderBy =
+ orderByToClickhouseSql(
+ orderBy || [],
+ traceOrderByColumns.map((c) => ({ ...c, queryPrefix: "b" })),
+ ) || "ORDER BY b.timestamp desc";
+
+ let query: string;
+
+ if (select.count) {
+ query = `${withClause}
+ SELECT count() as count
+ ${queryMiddle}
+ `;
+ } else if (select.includeIO) {
+ ctes.push(`base AS (
+ SELECT ${coreSelect}
+ ${scoresSelect}
+ ${observationsSelect}
+ ${metricsSelect}
+ ${queryMiddle}
+ ${chOrderBy}
+ ${limitByClause}
+ ${paginationClause}
+ )`);
+
+ const ioFinal = shouldUseSkipIndexes ? "" : "FINAL";
+ const ioDedup = shouldUseSkipIndexes
+ ? "ORDER BY event_ts DESC LIMIT 1 BY id, project_id"
+ : "";
+ ctes.push(`io AS (
+ SELECT id as _io_id, project_id as _io_project_id, input, output, metadata
+ FROM traces ${ioFinal}
+ WHERE project_id = {projectId: String}
+ AND (id, project_id) IN (SELECT id, project_id FROM base)
+ ${fromTimeFilter ? "AND timestamp >= {cteFromTimeFilter: DateTime64(3)}" : ""}
+ ${toTimeFilter ? "AND timestamp <= {cteToTimeFilter: DateTime64(3)}" : ""}
+ ${ioDedup}
+ )`);
+
+ query = `WITH ${ctes.join(", ")}
+ SELECT
+ b.id as id,
+ CONCAT('/project/', b.project_id, '/traces/', b.id) as "htmlPath",
+ b.project_id as project_id,
+ b.timestamp as timestamp,
+ b.name as name,
+ b.environment as environment,
+ b.session_id as session_id,
+ b.user_id as user_id,
+ b.release as release,
+ b.version as version,
+ b.bookmarked as bookmarked,
+ b.public as public,
+ b.tags as tags,
+ b.created_at as created_at,
+ b.updated_at as updated_at,
+ i.input as input,
+ i.output as output,
+ i.metadata as metadata
+ ${select.includeScores ? ", b.scores as scores" : ""}
+ ${select.includeObservations ? ", b.observations as observations" : ""}
+ ${select.includeMetrics ? ", b.latency as latency, b.totalCost as totalCost" : ""}
+ FROM base b
+ LEFT JOIN io i ON b.id = i._io_id AND b.project_id = i._io_project_id
+ ${finalOrderBy}
+ `;
+ } else {
+ query = `
+ ${withClause}
+ SELECT
+ ${coreSelect},
+ CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath"
+ ${scoresSelect}
+ ${observationsSelect}
+ ${metricsSelect}
+ ${queryMiddle}
+ ${chOrderBy}
+ ${limitByClause}
+ ${paginationClause}
+ `;
+ }
+
+ const needsCteToTimeFilter =
+ toTimeFilter &&
+ (propagateObservationsTimeBounds || (!select.count && select.includeIO));
+
+ const params = {
+ ...appliedEnvironmentFilter.params,
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ dataTypes: LISTABLE_SCORE_TYPES,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ ...(fromTimeFilter
+ ? {
+ cteFromTimeFilter: convertDateToClickhouseDateTime(
+ fromTimeFilter.value,
+ ),
+ }
+ : {}),
+ ...(needsCteToTimeFilter
+ ? {
+ cteToTimeFilter: convertDateToClickhouseDateTime(toTimeFilter.value),
+ }
+ : {}),
+ };
+
+ return { query, params, fromTimeFilter };
+}
+
+export const generateTracesForPublicApi = async ({
+ props,
+ advancedFilters,
+ orderBy,
+}: {
+ props: TraceQueryType;
+ advancedFilters?: FilterState;
+ orderBy: OrderByState;
+}) => {
+ const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;
+ const includeIO = requestedFields.includes("io");
+ const includeScores = requestedFields.includes("scores");
+ const includeObservations = requestedFields.includes("observations");
+ const includeMetrics = requestedFields.includes("metrics");
+
+ const { query, params, fromTimeFilter } = await buildTracesBaseQuery(
+ props,
+ {
+ includeIO,
+ includeObservations,
+ includeMetrics,
+ includeScores,
+ count: false,
+ },
+ advancedFilters,
+ orderBy,
+ );
+ const result = await measureAndReturn({
+ operationName: "getTracesForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params,
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "public-api",
+ projectId: props.projectId,
+ operation_name: "getTracesForPublicApi",
+ },
+ fromTimestamp: fromTimeFilter?.value ?? undefined,
+ preferredClickhouseService: "ReadOnly",
+ },
+ fn: (input) => {
+ return queryClickhouse<
+ TraceRecordReadType & {
+ observations?: string[];
+ scores?: string[];
+ totalCost?: number;
+ latency?: number;
+ htmlPath: string;
+ }
+ >({
+ query,
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+ },
+ });
+
+ return convertClickhouseTracesListToDomain(result, {
+ metrics: includeMetrics,
+ scores: includeScores,
+ observations: includeObservations,
+ });
+};
+
+export const getTracesCountForPublicApi = async ({
+ props,
+ advancedFilters,
+}: {
+ props: TraceQueryType;
+ advancedFilters?: FilterState;
+}) => {
+ let filter = deriveFilters(
+ props,
+ publicApiTracesFilterParams,
+ advancedFilters,
+ tracesTableUiColumnDefinitions,
+ tracesTableCols,
+ );
+ const appliedFilter = filter.apply();
+
+ let query = `
+ SELECT count() as count
+ FROM __TRACE_TABLE__ t
+ WHERE project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ `;
+
+ let params: Record<string, any> = {
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ };
+
+ if (advancedFilters !== undefined && advancedFilters.length > 0) {
+ ({ query, params } = await buildTracesBaseQuery(
+ props,
+ {
+ includeObservations: false,
+ includeIO: false,
+ includeMetrics: false,
+ includeScores: false,
+ count: true,
+ },
+ advancedFilters,
+ ));
+ }
+
+ const timestamp = props.fromTimestamp
+ ? new Date(props.fromTimestamp)
+ : undefined;
+
+ return measureAndReturn({
+ operationName: "getTracesCountForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params,
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "count",
+ projectId: props.projectId,
+ operation_name: "getTracesCountForPublicApi",
+ },
+ timestamp,
+ },
+ fn: async (input) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
+ });
+};
diff --git a/web/src/__tests__/server/scores-api-v3.servertest.ts b/web/src/__tests__/server/scores-api-v3.servertest.ts
index 3acae29514..36991c42e1 100644
--- a/web/src/__tests__/server/scores-api-v3.servertest.ts
+++ b/web/src/__tests__/server/scores-api-v3.servertest.ts
@@ -5,7 +5,7 @@ import {
createScoresCh,
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
-import { transformBooleanValueForFilter } from "@/src/features/public-api/server/scores-api-v3";
+import { transformBooleanValueForFilter } from "@langfuse/shared/src/server";
import {
makeAPICall,
makeZodVerifiedAPICall,
diff --git a/web/src/__tests__/server/unit/scores-api-v3.servertest.ts b/web/src/__tests__/server/unit/scores-api-v3.servertest.ts
index c5655516e9..887869e77e 100644
--- a/web/src/__tests__/server/unit/scores-api-v3.servertest.ts
+++ b/web/src/__tests__/server/unit/scores-api-v3.servertest.ts
@@ -1,4 +1,4 @@
-import { buildSelectColumns } from "@/src/features/public-api/server/scores-api-v3";
+import { buildSelectColumns } from "@langfuse/shared/src/server";
import { GetScoresQueryV3 } from "@langfuse/shared";
describe("GetScoresQueryV3 enum case-insensitivity", () => {
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 15b4e1528b..390de1fb8c 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -401,13 +401,6 @@ export const env = createEnv({
LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS: z
.enum(["true", "false"])
.default("false"),
- // Whether to propagate the toTimestamp restriction (including a server-side offset)
- // onto the observations CTE in GET /api/public/traces. Can be used to improve performance
- // for self-hosters that have a trace known trace duration of less than multiple hours.
- LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS: z
- .enum(["true", "false"])
- .default("false"),
-
// API Traces endpoint controls (may induce breaking changes on API when changed!)
LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS: z.coerce
.number()
@@ -817,8 +810,6 @@ export const env = createEnv({
LANGFUSE_AI_FEATURES_HOST: process.env.LANGFUSE_AI_FEATURES_HOST,
// Api Performance Flags
- LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS:
- process.env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS,
LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS:
process.env.LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS,
diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.ts
index b54375f257..2f74c9ad3a 100644
--- a/web/src/features/public-api/server/dailyMetrics.ts
+++ b/web/src/features/public-api/server/dailyMetrics.ts
@@ -1,259 +1,4 @@
-import { convertApiProvidedFilterToClickhouseFilter } from "@langfuse/shared/src/server";
-import {
- convertDateToClickhouseDateTime,
- queryClickhouse,
- TRACE_TO_OBSERVATIONS_INTERVAL,
- type DateTimeFilter,
- measureAndReturn,
+export {
+ generateDailyMetrics,
+ getDailyMetricsCount,
} from "@langfuse/shared/src/server";
-
-type QueryType = {
- page: number;
- limit: number;
- projectId: string;
- userId?: string;
- tags?: string | string[];
- traceName?: string;
- fromTimestamp?: string;
- toTimestamp?: string;
-};
-
-export const generateDailyMetrics = async (props: QueryType) => {
- const filter = convertApiProvidedFilterToClickhouseFilter(
- props,
- filterParams,
- );
- const hasTracesFilter = filter.some((f) => f.clickhouseTable === "traces");
- const tracesFilter = filter.filter((f) => f.clickhouseTable === "traces");
- const appliedFilter = filter.apply();
- const appliedTracesFilter = tracesFilter.apply();
-
- const timeFilter = filter.find(
- (f) =>
- f.clickhouseTable === "traces" &&
- f.field.includes("timestamp") &&
- (f.operator === ">=" || f.operator === ">"),
- ) as DateTimeFilter | undefined;
-
- // If there is any other filter than fromTimestamp, we join the traces table to be on the safe side.
- const hasNonTimestampsFilter =
- (timeFilter && filter.length() > 1) || (!timeFilter && filter.length() > 0);
-
- const query = `
- WITH model_usage AS (
- SELECT
- toDate(o.start_time) as date,
- o.provided_model_name as model,
- count(o.id) as countObservations,
- count(distinct o.trace_id) as countTraces,
- sum(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, o.usage_details)))) as inputUsage,
- sum(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, o.usage_details)))) as outputUsage,
- sumMap(o.usage_details)['total'] as totalUsage,
- sum(coalesce(o.total_cost, 0)) as totalCost
- FROM observations o FINAL ${hasNonTimestampsFilter ? " LEFT JOIN __TRACE_TABLE__ t FINAL on o.trace_id = t.id AND o.project_id = t.project_id" : ""}
- WHERE o.project_id = {projectId: String}
- ${hasNonTimestampsFilter ? `AND t.project_id = {projectId: String} AND ${appliedFilter.query}` : ""}
- ${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
- GROUP BY date, model
- ), daily_model_usage AS (
- SELECT
- "date",
- sum(mu.countObservations) as countObservations,
- sum(mu.totalCost) as totalCost,
- groupArray(tuple(
- mu.model,
- mu.inputUsage,
- mu.outputUsage,
- mu.totalUsage,
- mu.totalCost,
- mu.countObservations,
- mu.countTraces
- )) as daily_usage_tuple
- FROM model_usage mu
- GROUP BY date
- ), trace_usage AS (
- SELECT
- toDate(t.timestamp) as date,
- count(t.id) as countTraces
- FROM __TRACE_TABLE__ t FINAL
- WHERE t.project_id = {projectId: String}
- ${hasTracesFilter ? `AND ${appliedTracesFilter.query}` : ""}
- GROUP BY date
- )
-
- SELECT
- COALESCE(dmu.date, tu.date) as date,
- COALESCE(tu.countTraces, 0) as countTraces,
- COALESCE(dmu.countObservations, 0) as countObservations,
- COALESCE(dmu.totalCost, 0) as totalCost,
- dmu.daily_usage_tuple as usage
- FROM daily_model_usage dmu
- FULL OUTER JOIN trace_usage tu ON dmu.date = tu.date
- ORDER BY date DESC
- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
-
- const timestamp = props.fromTimestamp
- ? new Date(props.fromTimestamp)
- : timeFilter?.value;
-
- return measureAndReturn({
- operationName: "generateDailyMetrics",
- projectId: props.projectId,
- input: {
- params: {
- ...appliedTracesFilter.params,
- ...appliedFilter.params,
- projectId: props.projectId,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
- ...(timeFilter
- ? {
- cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),
- }
- : {}),
- },
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "daily_metrics",
- projectId: props.projectId,
- operation_name: "generateDailyMetrics",
- },
- timestamp,
- },
- fn: async (input) => {
- const result = await queryClickhouse<{
- date: string;
- countTraces: number;
- countObservations: number;
- totalCost: number;
- usage: (string | null)[][];
- }>({
- query: query.replaceAll("__TRACE_TABLE__", "traces"),
- params: input.params,
- tags: input.tags,
- clickhouseConfigs: {
- request_timeout: 60_000, // Use 1 minute timeout for daily metrics
- },
- });
-
- return result.map((record) => ({
- date: record.date,
- countTraces: Number(record.countTraces),
- countObservations: Number(record.countObservations),
- totalCost: Number(record.totalCost),
- usage: record.usage.map((u) => ({
- model: u[0],
- inputUsage: Number(u[1]),
- outputUsage: Number(u[2]),
- totalUsage: Number(u[3]),
- totalCost: Number(u[4]),
- countObservations: Number(u[5]),
- countTraces: Number(u[6]),
- })),
- }));
- },
- });
-};
-
-export const getDailyMetricsCount = async (props: QueryType) => {
- const filter = convertApiProvidedFilterToClickhouseFilter(
- props,
- filterParams,
- );
- const appliedFilter = filter
- .filter((f) => f.clickhouseTable === "traces")
- .apply();
-
- const query = `
- SELECT count(distinct toDate(timestamp)) as count
- FROM __TRACE_TABLE__ t
- WHERE project_id = {projectId: String}
- ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
- `;
-
- const timestamp = props.fromTimestamp
- ? new Date(props.fromTimestamp)
- : undefined;
-
- return measureAndReturn({
- operationName: "getDailyMetricsCount",
- projectId: props.projectId,
- input: {
- params: { ...appliedFilter.params, projectId: props.projectId },
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "daily_metrics_count",
- projectId: props.projectId,
- operation_name: "getDailyMetricsCount",
- },
- timestamp,
- },
- fn: async (input) => {
- const records = await queryClickhouse<{ count: string }>({
- query: query.replace("__TRACE_TABLE__", "traces"),
- params: input.params,
- tags: input.tags,
- });
- return records.map((record) => Number(record.count)).shift();
- },
- });
-};
-
-const filterParams = [
- {
- id: "userId",
- clickhouseSelect: "user_id",
- filterType: "StringFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "traceName",
- clickhouseSelect: "name",
- filterType: "StringFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "tags",
- clickhouseSelect: "tags",
- filterType: "ArrayOptionsFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "traceEnvironment",
- clickhouseSelect: "environment",
- filterType: "StringOptionsFilter",
- clickhouseTable: "traces",
- clickhousePrefix: "t",
- },
- {
- id: "observationEnvironment",
- clickhouseSelect: "environment",
- filterType: "StringOptionsFilter",
- clickhouseTable: "observations",
- clickhousePrefix: "o",
- },
- {
- 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",
- },
-];
diff --git a/web/src/features/public-api/server/dataset-runs.ts b/web/src/features/public-api/server/dataset-runs.ts
index 1076413574..927ceaa3dd 100644
--- a/web/src/features/public-api/server/dataset-runs.ts
+++ b/web/src/features/public-api/server/dataset-runs.ts
@@ -1,97 +1 @@
-import { type jsonSchema } from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
-import { v4 } from "uuid";
-import type z from "zod";
-
-type Json = z.infer<typeof jsonSchema>;
-
-const isUniqueConstraintError = (error: any): boolean => {
- return (
- error.code === "P2002" || // Prisma unique constraint
- error.message?.includes("duplicate key") ||
- error.message?.toLowerCase().includes("unique constraint") ||
- error.message?.includes("violates unique constraint")
- );
-};
-
-/**
- * Create or fetch a dataset run with optimistic concurrency handling.
- *
- * Behavior:
- * - First tries to find an existing run by (projectId, datasetId, name).
- * - If not found, attempts to create it.
- * - If creation fails due to a unique constraint (likely created concurrently),
- * fetches and returns the existing run.
- * - If all steps fail, throws an error.
- *
- * Rationale: The public API can receive many POST requests almost simultaneously,
- * which is not concurrency-safe without this guard.
- */
-export const createOrFetchDatasetRun = async ({
- projectId,
- datasetId,
- name,
- description,
- metadata,
- createdAt,
-}: {
- projectId: string;
- datasetId: string;
- name: string;
- description?: string;
- metadata?: Json | null;
- createdAt?: Date;
-}) => {
- try {
- // Attempt to fetch existing run
- const existingRun = await prisma.datasetRuns.findUnique({
- where: {
- datasetId_projectId_name: {
- datasetId,
- projectId,
- name: name,
- },
- },
- });
- if (existingRun) {
- return existingRun;
- }
-
- // Attempt creation
- const datasetRun = await prisma.datasetRuns.create({
- data: {
- id: v4(),
- datasetId,
- projectId,
- name,
- description: description ?? null,
- metadata: metadata ?? {},
- createdAt: createdAt ?? new Date(),
- updatedAt: createdAt ?? new Date(),
- },
- });
- return datasetRun;
- } catch (error) {
- // Check if it's a unique constraint violation
- if (isUniqueConstraintError(error)) {
- // Fetch existing run
- const existingRun = await prisma.datasetRuns.findUnique({
- where: {
- datasetId_projectId_name: {
- datasetId,
- projectId,
- name: name,
- },
- },
- });
-
- if (existingRun) {
- return existingRun;
- }
- } else {
- throw error;
- }
- }
-
- throw new Error("Failed to create or fetch dataset run");
-};
+export { createOrFetchDatasetRun } from "@langfuse/shared/src/server";
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
index 0d77fd0d19..ea460a1e41 100644
--- a/web/src/features/public-api/server/observations.ts
+++ b/web/src/features/public-api/server/observations.ts
@@ -1,194 +1,4 @@
-import {
- createPublicApiObservationsColumnMapping,
- deriveFilters,
- StringFilter,
- type ObservationRecordReadType,
- queryClickhouse,
- measureAndReturn,
- observationsTableUiColumnDefinitions,
- convertObservation,
- shouldSkipObservationsFinal,
+export {
+ generateObservationsForPublicApi,
+ getObservationsCountForPublicApi,
} from "@langfuse/shared/src/server";
-import { type FilterState, observationsTableCols } from "@langfuse/shared";
-
-type QueryType = {
- page: number;
- limit: number;
- projectId: string;
- traceId?: string;
- userId?: string;
- name?: string;
- type?: string;
- parentObservationId?: string;
- fromStartTime?: string;
- toStartTime?: string;
- version?: string;
- advancedFilters?: FilterState;
-};
-
-export const generateObservationsForPublicApi = async (props: QueryType) => {
- const chFilter = generateFilter(props);
- const appliedFilter = chFilter.apply();
- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
-
- // ClickHouse query optimizations for List Observations API
- const disableObservationsFinal = await shouldSkipObservationsFinal(
- props.projectId,
- );
-
- const query = `
- with clickhouse_keys as (
- SELECT DISTINCT
- id,
- trace_id,
- project_id,
- type,
- toDate(start_time)
- FROM observations o
- ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
- WHERE o.project_id = {projectId: String}
- ${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
- AND ${appliedFilter.query}
- ORDER BY start_time DESC
- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- )
- SELECT
- id,
- trace_id,
- project_id,
- type,
- parent_observation_id,
- environment,
- start_time,
- end_time,
- name,
- metadata,
- level,
- status_message,
- version,
- input,
- output,
- provided_model_name,
- 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 observations o ${disableObservationsFinal ? "" : "FINAL"}
- WHERE o.project_id = {projectId: String}
- AND (id, trace_id, project_id, type, toDate(start_time)) in (select * from clickhouse_keys)
- ORDER BY start_time DESC
- `;
-
- return measureAndReturn({
- operationName: "generateObservationsForPublicApi",
- projectId: props.projectId,
- input: {
- params: {
- ...appliedFilter.params,
- projectId: props.projectId,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
- },
- tags: {
- feature: "tracing",
- type: "observation",
- projectId: props.projectId,
- operation_name: "generateObservationsForPublicApi",
- },
- },
- fn: async (input) => {
- const result = await queryClickhouse<ObservationRecordReadType>({
- query: query.replace("__TRACE_TABLE__", "traces"),
- params: input.params,
- tags: input.tags,
- preferredClickhouseService: "ReadOnly",
- });
- return result.map((r) => convertObservation(r));
- },
- });
-};
-
-export const getObservationsCountForPublicApi = async (props: QueryType) => {
- const chFilter = generateFilter(props);
- const filter = chFilter.apply();
- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
-
- const query = `
- SELECT count() as count
- FROM observations o
- ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
- WHERE o.project_id = {projectId: String}
- ${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
- AND ${filter.query}
- `;
-
- return measureAndReturn({
- operationName: "getObservationsCountForPublicApi",
- projectId: props.projectId,
- input: {
- params: { ...filter.params, projectId: props.projectId },
- tags: {
- feature: "tracing",
- type: "observation",
- projectId: props.projectId,
- operation_name: "getObservationsCountForPublicApi",
- },
- },
- fn: async (input) => {
- const records = await queryClickhouse<{ count: string }>({
- query: query.replace("__TRACE_TABLE__", "traces"),
- params: input.params,
- tags: input.tags,
- preferredClickhouseService: "ReadOnly",
- });
- return records.map((record) => Number(record.count)).shift();
- },
- });
-};
-
-const filterParams = createPublicApiObservationsColumnMapping(
- "observations",
- "o",
- "parent_observation_id",
-);
-
-const generateFilter = (query: QueryType) => {
- const { advancedFilters, ...simpleFilterProps } = query;
- const chFilter = deriveFilters(
- simpleFilterProps,
- filterParams,
- advancedFilters,
- observationsTableUiColumnDefinitions.filter(
- (c) => c.clickhouseTableName !== "scores",
- ),
- observationsTableCols,
- );
-
- // Remove score filters since observations don't support scores in response
- const filteredChFilter = chFilter.filter(
- (f) => f.clickhouseTable !== "scores",
- );
-
- // Add project filter
- filteredChFilter.push(
- new StringFilter({
- clickhouseTable: "observations",
- field: "project_id",
- operator: "=",
- value: query.projectId,
- }),
- );
- return filteredChFilter;
-};
diff --git a/web/src/features/public-api/server/score-configs-api-service.ts b/web/src/features/public-api/server/score-configs-api-service.ts
index 03ef380090..2cea6dbcbd 100644
--- a/web/src/features/public-api/server/score-configs-api-service.ts
+++ b/web/src/features/public-api/server/score-configs-api-service.ts
@@ -2,21 +2,20 @@ import { v4 } from "uuid";
import { type z } from "zod";
import { isBooleanDataType } from "@/src/features/scores/lib/helpers";
import {
- filterAndValidateDbScoreConfigList,
- InternalServerError,
InvalidRequestError,
LangfuseNotFoundError,
validateDbScoreConfig,
validateDbScoreConfigSafe,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { traceException } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import {
type PostScoreConfigBody,
type PutScoreConfigBody,
} from "@/src/features/public-api/types/score-configs";
+export { listScoreConfigs, getScoreConfig } from "@langfuse/shared/src/server";
+
type ApiKeyProjectContext = {
projectId: string;
orgId: string;
@@ -68,76 +67,6 @@ export const createScoreConfig = async ({
return validateDbScoreConfig(config);
};
-export const listScoreConfigs = async ({
- projectId,
- page,
- limit,
-}: {
- projectId: string;
- page: number;
- limit: number;
-}) => {
- const [rawConfigs, totalItems] = await Promise.all([
- prisma.scoreConfig.findMany({
- where: {
- projectId,
- },
- orderBy: [{ createdAt: "desc" }, { id: "asc" }],
- take: limit,
- skip: (page - 1) * limit,
- }),
- prisma.scoreConfig.count({
- where: {
- projectId,
- },
- }),
- ]);
-
- const configs = filterAndValidateDbScoreConfigList(
- rawConfigs,
- traceException,
- );
-
- return {
- data: configs,
- meta: {
- page,
- limit,
- totalItems,
- totalPages: Math.ceil(totalItems / limit),
- },
- };
-};
-
-export const getScoreConfig = async ({
- projectId,
- configId,
-}: {
- projectId: string;
- configId: string;
-}) => {
- const config = await prisma.scoreConfig.findUnique({
- where: {
- id: configId,
- projectId,
- },
- });
-
- if (!config) {
- throw new LangfuseNotFoundError(
- "Score config not found within authorized project",
- );
- }
-
- const parsedConfig = validateDbScoreConfigSafe(config);
- if (!parsedConfig.success) {
- traceException(parsedConfig.error);
- throw new InternalServerError("Requested score config is corrupted");
- }
-
- return parsedConfig.data;
-};
-
export const updateScoreConfig = async ({
context,
configId,
diff --git a/web/src/features/public-api/server/scores-api-service.ts b/web/src/features/public-api/server/scores-api-service.ts
index 571780e5a4..223e91327d 100644
--- a/web/src/features/public-api/server/scores-api-service.ts
+++ b/web/src/features/public-api/server/scores-api-service.ts
@@ -157,12 +157,20 @@ export class ScoresApiService {
* v2: Returns all score types including CORRECTION and TEXT
*/
async generateScoresForPublicApi(props: ScoreQueryType) {
- return _handleGenerateScoresForPublicApi({
+ const results = await _handleGenerateScoresForPublicApi({
props,
scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",
scoreDataTypes:
this.apiVersion === "v1" ? LISTABLE_SCORE_TYPES : undefined,
});
+ // Apply API-shape transformation (moves longStringValue→stringValue for
+ // CORRECTION, strips longStringValue for others). Must happen here because
+ // convertScoreToPublicApi is a web-layer concern that the shared repository
+ // function deliberately does not call.
+ return results.map(({ trace, ...rest }) => ({
+ ...convertScoreToPublicApi(rest),
+ trace,
+ }));
}
/**
diff --git a/web/src/features/public-api/server/scores-api-v3.ts b/web/src/features/public-api/server/scores-api-v3.ts
index 5a31ca6c1f..32acd87d9f 100644
--- a/web/src/features/public-api/server/scores-api-v3.ts
+++ b/web/src/features/public-api/server/scores-api-v3.ts
@@ -1,485 +1,4 @@
-import {
- convertClickhouseScoreToDomain,
- convertDateToClickhouseDateTime,
- DateTimeFilter,
- FilterList,
- logger,
- measureAndReturn,
- NumberFilter,
- parseClickhouseUTCDateTimeFormat,
- queryClickhouse,
- clickhouseCompliantRandomCharacters,
- StringOptionsFilter,
- type ScoreRecordReadType,
+export {
+ listScoresV3ForPublicApi,
+ polymorphicValueForV3 as polymorphicValue,
} from "@langfuse/shared/src/server";
-import type {
- APIScoreV3,
- ScoreDataTypeType,
- ScoreDomain,
- ScoreFieldGroupV3,
-} from "@langfuse/shared";
-import {
- filterAndValidateV3GetScoreList,
- InternalServerError,
- ScoreDataTypeEnum,
-} from "@langfuse/shared";
-import {
- encodeCursorV3,
- type ScoresCursorV3Type,
-} from "@/src/features/public-api/types/scores";
-
-export function polymorphicValue(score: {
- dataType: ScoreDataTypeType;
- value: number;
- stringValue?: string | null;
- longStringValue?: string | null;
-}): number | boolean | string {
- switch (score.dataType) {
- case ScoreDataTypeEnum.NUMERIC:
- return score.value;
- case ScoreDataTypeEnum.BOOLEAN:
- return score.value === 1;
- case ScoreDataTypeEnum.CATEGORICAL:
- case ScoreDataTypeEnum.TEXT:
- if (score.stringValue == null) {
- throw new InternalServerError(
- `Score with dataType ${score.dataType} is missing its stringValue`,
- );
- }
- return score.stringValue;
- case ScoreDataTypeEnum.CORRECTION:
- if (score.longStringValue == null) {
- throw new InternalServerError(
- "Score with dataType CORRECTION is missing its longStringValue",
- );
- }
- return score.longStringValue;
- default: {
- const _exhaustiveCheck: never = score.dataType;
- throw new InternalServerError(
- `Score has unknown dataType: ${_exhaustiveCheck as string}`,
- );
- }
- }
-}
-
-function deriveSubject(
- score: ScoreDomain,
-):
- | { kind: "observation"; id: string; traceId?: string }
- | { kind: "trace" | "session" | "experiment"; id: string } {
- if (score.datasetRunId) {
- return { kind: "experiment", id: score.datasetRunId };
- }
- if (score.observationId) {
- return {
- kind: "observation",
- id: score.observationId,
- ...(score.traceId ? { traceId: score.traceId } : {}),
- };
- }
- if (score.sessionId) {
- return { kind: "session", id: score.sessionId };
- }
- if (!score.traceId) {
- throw new InternalServerError(
- `Score ${score.id} has kind=trace but missing traceId`,
- );
- }
- return { kind: "trace", id: score.traceId };
-}
-
-function domainToV3(
- score: ScoreDomain,
- fields: ScoreFieldGroupV3[],
-): APIScoreV3 {
- // ScoreDomain is a flat type so TypeScript cannot verify that dataType and
- // value are a valid discriminated pair; polymorphicValue guarantees it at runtime.
- return {
- id: score.id,
- projectId: score.projectId,
- name: score.name,
- dataType: score.dataType,
- value: polymorphicValue({
- dataType: score.dataType,
- value: score.value,
- stringValue: score.stringValue as string | null | undefined,
- longStringValue: score.longStringValue as string | null | undefined,
- }),
- source: score.source,
- timestamp: score.timestamp,
- environment: score.environment,
- createdAt: score.createdAt,
- updatedAt: score.updatedAt,
- ...(fields.includes("details")
- ? {
- comment: score.comment,
- configId: score.configId,
- metadata: score.metadata,
- }
- : {}),
- ...(fields.includes("annotation")
- ? {
- authorUserId: score.authorUserId,
- queueId: score.queueId,
- }
- : {}),
- ...(fields.includes("subject") ? { subject: deriveSubject(score) } : {}),
- } as APIScoreV3;
-}
-
-// Always-selected columns map to the core APIScoreV3 fields plus the cursor
-// and bookkeeping columns. Optional groups (details/subject/annotation) are
-// only selected when their `fields` group is requested β€” ClickHouse is
-// columnar, so skipping unused columns avoids real I/O cost on large rows
-// (notably `metadata` and `long_string_value`).
-const CORE_COLUMNS = [
- "s.id as id",
- "s.project_id as project_id",
- "s.timestamp as timestamp",
- "s.environment as environment",
- "s.name as name",
- "s.value as value",
- "s.string_value as string_value",
- "s.long_string_value as long_string_value",
- "s.source as source",
- "s.data_type as data_type",
- "s.created_at as created_at",
- "s.updated_at as updated_at",
- "s.execution_trace_id as execution_trace_id",
-];
-const DETAILS_COLUMNS = [
- "s.comment as comment",
- "s.metadata as metadata",
- "s.config_id as config_id",
-];
-const SUBJECT_COLUMNS = [
- "s.trace_id as trace_id",
- "s.observation_id as observation_id",
- "s.session_id as session_id",
- "s.dataset_run_id as dataset_run_id",
-];
-const ANNOTATION_COLUMNS = [
- "s.author_user_id as author_user_id",
- "s.queue_id as queue_id",
-];
-
-export const buildSelectColumns = (fields: ScoreFieldGroupV3[]): string => {
- const selected = [...CORE_COLUMNS];
- if (fields.includes("details")) selected.push(...DETAILS_COLUMNS);
- if (fields.includes("subject")) selected.push(...SUBJECT_COLUMNS);
- if (fields.includes("annotation")) selected.push(...ANNOTATION_COLUMNS);
- return selected.join(",\n ");
-};
-
-export function transformBooleanValueForFilter(v: "true" | "false"): number {
- // Belt-and-braces: the route-handler superRefine narrows v to "true"|"false"
- // before this is called, but a regression in that validator would otherwise
- // silently return 0 for any non-"true" input. Throw loud instead.
- if (v === "true") return 1;
- if (v === "false") return 0;
- throw new InternalServerError(
- `transformBooleanValueForFilter received unexpected value: ${v}`,
- );
-}
-
-type ListFilterParams = {
- id?: string[];
- name?: string[];
- source?: string[];
- dataType?: string[];
- environment?: string[];
- configId?: string[];
- queueId?: string[];
- authorUserId?: string[];
- value?: string[];
- valueMin?: number;
- valueMax?: number;
- traceId?: string[];
- sessionId?: string[];
- observationId?: string[];
- experimentId?: string[];
- fromTimestamp?: Date;
- toTimestamp?: Date;
-};
-
-function buildDynamicFilters(params: ListFilterParams): {
- query: string;
- params: Record<string, unknown>;
-} {
- const filterList = new FilterList();
-
- // Positive union of the string-array filter keys. TypeScript errors if a
- // key is listed here that does not exist in ListFilterParams, catching drift
- // without a manual deny-list that has to grow alongside non-string filters.
- type StringOptionFilterKey = Extract<
- keyof ListFilterParams,
- | "id"
- | "name"
- | "source"
- | "dataType"
- | "environment"
- | "configId"
- | "queueId"
- | "authorUserId"
- | "traceId"
- | "sessionId"
- | "observationId"
- | "experimentId"
- >;
-
- // Each entry maps a ListFilterParams key to its ClickHouse column. Adding a
- // new identifier filter is a single row here β€” same operator/table shape.
- const STRING_OPTIONS_FILTERS: ReadonlyArray<{
- key: StringOptionFilterKey;
- field: string;
- }> = [
- { key: "id", field: "id" },
- { key: "name", field: "name" },
- { key: "source", field: "source" },
- { key: "dataType", field: "data_type" },
- { key: "environment", field: "environment" },
- { key: "configId", field: "config_id" },
- { key: "queueId", field: "queue_id" },
- { key: "authorUserId", field: "author_user_id" },
- { key: "traceId", field: "trace_id" },
- { key: "sessionId", field: "session_id" },
- { key: "observationId", field: "observation_id" },
- { key: "experimentId", field: "dataset_run_id" },
- ];
-
- for (const { key, field } of STRING_OPTIONS_FILTERS) {
- const values = params[key];
- if (values?.length) {
- filterList.push(
- new StringOptionsFilter({
- clickhouseTable: "scores",
- field,
- operator: "any of",
- values,
- tablePrefix: "s",
- }),
- );
- }
- }
- if (params.fromTimestamp !== undefined)
- filterList.push(
- new DateTimeFilter({
- clickhouseTable: "scores",
- field: "timestamp",
- operator: ">=",
- value: params.fromTimestamp,
- tablePrefix: "s",
- }),
- );
- if (params.toTimestamp !== undefined)
- filterList.push(
- new DateTimeFilter({
- clickhouseTable: "scores",
- field: "timestamp",
- operator: "<",
- value: params.toTimestamp,
- tablePrefix: "s",
- }),
- );
- if (params.valueMin !== undefined)
- filterList.push(
- new NumberFilter({
- clickhouseTable: "scores",
- field: "value",
- operator: ">=",
- value: params.valueMin,
- tablePrefix: "s",
- clickhouseTypeOverwrite: "Float64",
- }),
- );
- if (params.valueMax !== undefined)
- filterList.push(
- new NumberFilter({
- clickhouseTable: "scores",
- field: "value",
- operator: "<=",
- value: params.valueMax,
- tablePrefix: "s",
- clickhouseTypeOverwrite: "Float64",
- }),
- );
-
- const compiled = filterList.apply();
-
- // value= routes to different columns depending on dataType
- const extraClauses: string[] = [];
- const extraParams: Record<string, unknown> = {};
-
- if (params.value?.length && params.dataType?.length === 1) {
- // Cast: handler superRefine validates dt is a ScoreDataTypeType member.
- const dt = params.dataType[0] as ScoreDataTypeType;
- const uid = clickhouseCompliantRandomCharacters();
- const varName = `valueFilter${uid}`;
-
- switch (dt) {
- case ScoreDataTypeEnum.NUMERIC: {
- extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);
- // Belt-and-braces: the route-handler superRefine asserts each value is
- // a finite number before this is called. Re-validate so a regression
- // can't land NaN/Infinity directly in a CH IN-clause parameter.
- extraParams[varName] = params.value.map((v) => {
- const n = Number(v);
- if (!Number.isFinite(n)) {
- throw new InternalServerError(
- `NUMERIC value filter received non-finite value: ${v}`,
- );
- }
- return n;
- });
- break;
- }
- case ScoreDataTypeEnum.BOOLEAN: {
- extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);
- extraParams[varName] = params.value.map((v) =>
- transformBooleanValueForFilter(v as "true" | "false"),
- );
- break;
- }
- case ScoreDataTypeEnum.CATEGORICAL: {
- extraClauses.push(`s.string_value IN ({${varName}: Array(String)})`);
- extraParams[varName] = params.value;
- break;
- }
- case ScoreDataTypeEnum.TEXT:
- case ScoreDataTypeEnum.CORRECTION:
- // Handler superRefine rejects value= with TEXT/CORRECTION; reaching
- // this branch means the validator regressed.
- throw new InternalServerError(
- `value filter with dataType=${dt} should have been rejected by handler validation`,
- );
- default: {
- const _exhaustiveCheck: never = dt;
- throw new InternalServerError(
- `value filter received unknown dataType: ${_exhaustiveCheck as string}`,
- );
- }
- }
- }
-
- const allClauses = [compiled.query, ...extraClauses]
- .filter(Boolean)
- .join(" AND ");
-
- return { query: allClauses, params: { ...compiled.params, ...extraParams } };
-}
-
-const buildV3ListQuery = (
- withCursor: boolean,
- fields: ScoreFieldGroupV3[],
- filterClause: string,
-) => `
- SELECT
- ${buildSelectColumns(fields)}
- FROM scores s
- WHERE s.project_id = {projectId: String}
- ${
- withCursor
- ? "AND (s.timestamp, s.id) < ({lastTimestamp: DateTime64(3)}, {lastId: String})"
- : ""
- }
- ${filterClause ? `AND ${filterClause}` : ""}
- ORDER BY s.timestamp DESC, s.id DESC, s.event_ts DESC
- LIMIT 1 BY s.id, s.project_id
- LIMIT {limit: Int32}
-`;
-
-export async function listScoresV3ForPublicApi(
- params: {
- projectId: string;
- limit: number;
- cursor?: ScoresCursorV3Type;
- fields: ScoreFieldGroupV3[];
- } & ListFilterParams,
-): Promise<{ data: APIScoreV3[]; cursor?: string }> {
- const { query: filterClause, params: filterParams } =
- buildDynamicFilters(params);
-
- return measureAndReturn({
- operationName: "listScoresV3ForPublicApi",
- projectId: params.projectId,
- input: {
- params: {
- projectId: params.projectId,
- limit: params.limit + 1,
- ...(params.cursor && {
- lastTimestamp: convertDateToClickhouseDateTime(
- params.cursor.lastTimestamp,
- ),
- lastId: params.cursor.lastId,
- }),
- ...filterParams,
- },
- tags: {
- feature: "scoring",
- type: "score",
- projectId: params.projectId,
- operation_name: "listScoresV3ForPublicApi",
- },
- },
- fn: async (input) => {
- const records = await queryClickhouse<ScoreRecordReadType>({
- query: buildV3ListQuery(
- Boolean(params.cursor),
- params.fields,
- filterClause,
- ),
- params: input.params,
- tags: input.tags,
- preferredClickhouseService: "ReadOnly",
- });
-
- const hasMore = records.length > params.limit;
- const pageRecords = hasMore ? records.slice(0, params.limit) : records;
-
- let nextCursor: string | undefined;
- if (hasMore && pageRecords.length > 0) {
- const last = pageRecords[pageRecords.length - 1];
- nextCursor = encodeCursorV3({
- v: 1,
- lastTimestamp: parseClickhouseUTCDateTimeFormat(
- String(last.timestamp),
- ),
- lastId: last.id,
- });
- }
-
- // Log+drop bad rows rather than 500ing the whole page β€” domainToV3 can
- // throw (e.g. polymorphicValue's stringValue / longStringValue guards
- // for malformed CATEGORICAL / TEXT / CORRECTION rows, or deriveSubject
- // for a malformed subject record). Mirrors the row-level graceful-drop
- // semantics of filterAndValidateV3GetScoreList.
- const items: ReturnType<typeof domainToV3>[] = [];
- for (const row of pageRecords) {
- try {
- items.push(
- domainToV3(convertClickhouseScoreToDomain(row), params.fields),
- );
- } catch (error) {
- logger.error("v3 score row dropped from response: conversion error", {
- error,
- scoreId: row.id,
- projectId: params.projectId,
- });
- }
- }
- return {
- data: filterAndValidateV3GetScoreList(items, (error) => {
- logger.error(
- "v3 score row dropped from response: schema validation error",
- {
- issues: error.issues,
- projectId: params.projectId,
- },
- );
- }),
- cursor: nextCursor,
- };
- },
- });
-}
diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.ts
index dcdf191587..fda00b1007 100644
--- a/web/src/features/public-api/server/scores.ts
+++ b/web/src/features/public-api/server/scores.ts
@@ -1,23 +1,15 @@
-import {
- convertApiProvidedFilterToClickhouseFilter,
- deriveFilters,
- convertClickhouseScoreToDomain,
- StringFilter,
- StringOptionsFilter,
- type ScoreRecordReadType,
- queryClickhouse,
- measureAndReturn,
- scoresTableUiColumnDefinitions,
-} from "@langfuse/shared/src/server";
import {
removeObjectKeys,
ScoreDataTypeEnum,
- type ScoreDataTypeType,
- scoresTableCols,
type ScoreDomain,
- type FilterState,
} from "@langfuse/shared";
+export {
+ _handleGenerateScoresForPublicApi,
+ _handleGetScoresCountForPublicApi,
+ type ScoreQueryType,
+} from "@langfuse/shared/src/server";
+
type ScoreApiResult = Omit<ScoreDomain, "longStringValue"> & {
stringValue?: string | null;
};
@@ -52,452 +44,3 @@ export function convertScoreToPublicApi(
return removeObjectKeys(score, ["longStringValue"]);
}
-
-export type ScoreQueryType = {
- page: number;
- limit: number;
- projectId: string;
- traceId?: string;
- userId?: string;
- name?: string;
- source?: string;
- fromTimestamp?: string;
- toTimestamp?: string;
- value?: number;
- scoreId?: string;
- configId?: string;
- sessionId?: string;
- datasetRunId?: string;
- queueId?: string;
- traceTags?: string | string[];
- operator?: string;
- scoreIds?: string[];
- observationId?: string[];
- dataType?: string;
- environment?: string | string[];
- fields?: string[] | null;
- advancedFilters?: FilterState;
-};
-
-/**
- * @internal
- * Internal utility function for getting scores by ID.
- * Do not use directly - use ScoresApiService or repository functions instead.
- */
-export const _handleGenerateScoresForPublicApi = async ({
- props,
- scoreScope,
- scoreDataTypes,
-}: {
- props: ScoreQueryType;
- scoreScope: "traces_only" | "all";
- scoreDataTypes?: readonly ScoreDataTypeType[];
-}) => {
- const { scoresFilter, tracesFilter } = generateScoreFilter(
- props,
- scoreDataTypes,
- );
- const appliedScoresFilter = scoresFilter.apply();
- const appliedTracesFilter = tracesFilter.apply();
-
- // Determine if trace should be included based on fields parameter
- const { includeTrace, needsTraceJoin } = determineTraceJoinRequirement(
- props.fields,
- tracesFilter.length(),
- );
-
- const query = `
- SELECT
- ${needsTraceJoin ? "t.user_id as user_id, t.tags as tags, t.environment as trace_environment, t.session_id as trace_session_id," : ""}
- s.id as id,
- s.project_id as project_id,
- s.timestamp as timestamp,
- s.environment as environment,
- s.name as name,
- s.value as value,
- s.string_value as string_value,
- s.long_string_value as long_string_value,
- s.author_user_id as author_user_id,
- s.created_at as created_at,
- s.updated_at as updated_at,
- s.source as source,
- s.comment as comment,
- s.metadata as metadata,
- s.data_type as data_type,
- s.config_id as config_id,
- s.queue_id as queue_id,
- s.execution_trace_id as execution_trace_id,
- s.trace_id as trace_id,
- s.observation_id as observation_id,
- s.session_id as session_id,
- s.dataset_run_id as dataset_run_id
- FROM
- scores s
- ${needsTraceJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}
- WHERE
- s.project_id = {projectId: String}
- AND (
- ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}
- (s.trace_id IS NOT NULL AND (${needsTraceJoin ? "t.id, t.project_id" : "s.trace_id, s.project_id"}) IN (
- SELECT
- ${needsTraceJoin ? "trace_id, project_id" : "s.trace_id, s.project_id"}
- FROM
- scores s
- WHERE
- s.project_id = {projectId: String}
- ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
- ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
- ORDER BY
- s.timestamp desc
- LIMIT
- 1 BY s.id, s.project_id
- ))
- )
- ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
- ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
- ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}
- ORDER BY
- s.timestamp desc, s.event_ts desc
- LIMIT
- 1 BY s.id, s.project_id
- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
-
- return measureAndReturn({
- operationName: "_handleGenerateScoresForPublicApi",
- projectId: props.projectId,
- input: {
- params: {
- ...appliedScoresFilter.params,
- ...appliedTracesFilter.params,
- projectId: props.projectId,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
- },
- tags: {
- feature: "scoring",
- type: "score",
- projectId: props.projectId,
- scoreScope,
- operation_name: "_handleGenerateScoresForPublicApi",
- includeTrace: includeTrace.toString(),
- },
- },
- fn: async (input) => {
- const records = await queryClickhouse<
- ScoreRecordReadType & {
- tags?: string[];
- user_id?: string;
- trace_environment?: string;
- trace_session_id?: string | null;
- }
- >({
- query: query.replace("__TRACE_TABLE__", "traces"),
- params: input.params,
- tags: input.tags,
- preferredClickhouseService: "ReadOnly",
- });
-
- return records.map((record) => {
- const domainScore = convertClickhouseScoreToDomain(record);
- const apiScore = convertScoreToPublicApi(domainScore);
- return {
- ...apiScore,
- trace:
- includeTrace && record.trace_id !== null
- ? {
- userId: record.user_id,
- tags: record.tags,
- environment: record.trace_environment,
- sessionId: record.trace_session_id,
- }
- : null,
- };
- });
- },
- });
-};
-
-/**
- * @internal
- * Internal utility function for getting scores by ID.
- * Do not use directly - use ScoresApiService or repository functions instead.
- */
-export const _handleGetScoresCountForPublicApi = async ({
- props,
- scoreScope,
- scoreDataTypes,
-}: {
- props: ScoreQueryType;
- scoreScope: "traces_only" | "all";
- scoreDataTypes?: readonly ScoreDataTypeType[];
-}) => {
- const { scoresFilter, tracesFilter } = generateScoreFilter(
- props,
- scoreDataTypes,
- );
- const appliedScoresFilter = scoresFilter.apply();
- const appliedTracesFilter = tracesFilter.apply();
-
- // Determine if trace should be included based on fields parameter
- const { includeTrace, needsTraceJoin } = determineTraceJoinRequirement(
- props.fields,
- tracesFilter.length(),
- );
-
- const query = `
- SELECT
- count() as count
- FROM
- scores s
- ${needsTraceJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}
- WHERE
- s.project_id = {projectId: String}
- AND (
- ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}
- (s.trace_id IS NOT NULL AND (${needsTraceJoin ? "t.id, t.project_id" : "s.trace_id, s.project_id"}) IN (
- SELECT
- ${needsTraceJoin ? "trace_id, project_id" : "s.trace_id, s.project_id"}
- FROM
- scores s
- WHERE
- s.project_id = {projectId: String}
- ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
- ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}
- ORDER BY
- s.timestamp desc
- LIMIT
- 1 BY s.id, s.project_id
- ))
- )
- ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
- ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}
- `;
-
- return measureAndReturn({
- operationName: "_handleGetScoresCountForPublicApi",
- projectId: props.projectId,
- input: {
- params: {
- ...appliedScoresFilter.params,
- ...appliedTracesFilter.params,
- projectId: props.projectId,
- },
- tags: {
- feature: "scoring",
- type: "score",
- projectId: props.projectId,
- scoreScope,
- operation_name: "_handleGetScoresCountForPublicApi",
- includeTrace: includeTrace.toString(),
- },
- },
- fn: async (input) => {
- const records = await queryClickhouse<{ count: string }>({
- query: query.replace("__TRACE_TABLE__", "traces"),
- params: input.params,
- tags: input.tags,
- preferredClickhouseService: "ReadOnly",
- });
- return records.map((record) => Number(record.count)).shift();
- },
- });
-};
-
-const secureScoreFilterOptions = [
- {
- id: "traceId",
- clickhouseSelect: "trace_id",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
- {
- id: "observationId",
- clickhouseSelect: "observation_id",
- clickhouseTable: "scores",
- filterType: "StringOptionsFilter",
- clickhousePrefix: "s",
- },
- {
- id: "name",
- clickhouseSelect: "name",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
- {
- id: "source",
- clickhouseSelect: "source",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
- {
- id: "fromTimestamp",
- clickhouseSelect: "timestamp",
- operator: ">=" as const,
- clickhouseTable: "scores",
- filterType: "DateTimeFilter",
- clickhousePrefix: "s",
- },
- {
- id: "toTimestamp",
- clickhouseSelect: "timestamp",
- operator: "<" as const,
- clickhouseTable: "scores",
- filterType: "DateTimeFilter",
- clickhousePrefix: "s",
- },
- {
- id: "value",
- clickhouseSelect: "value",
- clickhouseTable: "scores",
- filterType: "NumberFilter",
- clickhousePrefix: "s",
- },
- {
- id: "scoreIds",
- clickhouseSelect: "id",
- clickhouseTable: "scores",
- filterType: "StringOptionsFilter",
- clickhousePrefix: "s",
- },
- {
- id: "configId",
- clickhouseSelect: "config_id",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
- {
- id: "sessionId",
- clickhouseSelect: "session_id",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
- {
- id: "datasetRunId",
- clickhouseSelect: "dataset_run_id",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
- {
- id: "queueId",
- clickhouseSelect: "queue_id",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
- {
- id: "environment",
- clickhouseSelect: "environment",
- clickhouseTable: "scores",
- filterType: "StringOptionsFilter",
- clickhousePrefix: "s",
- },
- {
- id: "dataType",
- clickhouseSelect: "data_type",
- clickhouseTable: "scores",
- filterType: "StringFilter",
- clickhousePrefix: "s",
- },
-];
-
-const secureTraceFilterOptions = [
- {
- id: "traceTags",
- clickhouseSelect: "tags",
- clickhouseTable: "traces",
- filterType: "ArrayOptionsFilter",
- clickhousePrefix: "t",
- },
- {
- id: "userId",
- clickhouseSelect: "user_id",
- clickhouseTable: "traces",
- filterType: "StringFilter",
- clickhousePrefix: "t",
- },
-];
-
-/**
- * Determines if trace join is needed based on fields parameter and trace filters
- */
-const determineTraceJoinRequirement = (
- fields: string[] | null | undefined,
- tracesFilterLength: number,
-) => {
- const requestedFields = fields ?? ["score", "trace"]; // Default includes both
- const includeTrace = requestedFields.includes("trace");
- const needsTraceJoin = includeTrace || tracesFilterLength > 0;
-
- return { includeTrace, needsTraceJoin };
-};
-
-const generateScoreFilter = (
- filter: ScoreQueryType,
- scoreDataTypes?: readonly ScoreDataTypeType[],
-) => {
- const scoresFilter = deriveFilters(
- filter,
- secureScoreFilterOptions,
- filter.advancedFilters,
- scoresTableUiColumnDefinitions,
- scoresTableCols,
- );
- scoresFilter.push(
- new StringFilter({
- clickhouseTable: "scores",
- field: "project_id",
- operator: "=",
- value: filter.projectId,
- }),
- );
-
- // Add version-based dataType restriction if provided
- // This will AND with any user-provided dataType filter for proper intersection
- if (scoreDataTypes) {
- scoresFilter.push(
- new StringOptionsFilter({
- clickhouseTable: "scores",
- field: "data_type",
- operator: "any of",
- values: [...scoreDataTypes],
- tablePrefix: "s",
- }),
- );
- }
-
- const tracesFilter = convertApiProvidedFilterToClickhouseFilter(
- filter,
- secureTraceFilterOptions,
- );
-
- // If environment is specified AND there are other trace filters (userId, traceTags),
- // also apply the environment filter to traces. This ensures that when filtering by
- // trace properties, the trace's environment matches the requested environment.
- // Without other trace filters, we only filter by the score's own environment,
- // which allows session scores (that have no trace) to be returned correctly.
- if (filter.environment && tracesFilter.length() > 0) {
- const envValues = Array.isArray(filter.environment)
- ? filter.environment
- : [filter.environment];
- tracesFilter.push(
- new StringOptionsFilter({
- clickhouseTable: "traces",
- field: "environment",
- operator: "any of",
- values: envValues,
- tablePrefix: "t",
- }),
- );
- }
-
- return { scoresFilter, tracesFilter };
-};
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 0ab02b9570..cef9e22318 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -1,559 +1,4 @@
-import {
- convertDateToClickhouseDateTime,
- queryClickhouse,
- TRACE_TO_OBSERVATIONS_INTERVAL,
- orderByToClickhouseSql,
- type DateTimeFilter,
- convertClickhouseTracesListToDomain,
- type TraceRecordReadType,
- measureAndReturn,
- deriveFilters,
- createPublicApiTracesColumnMapping,
- tracesTableUiColumnDefinitions,
- shouldSkipObservationsFinal,
+export {
+ generateTracesForPublicApi,
+ getTracesCountForPublicApi,
} from "@langfuse/shared/src/server";
-import {
- LISTABLE_SCORE_TYPES,
- type OrderByState,
- tracesTableCols,
-} from "@langfuse/shared";
-import {
- TRACE_FIELD_GROUPS,
- type TraceFieldGroup,
-} from "@/src/features/public-api/types/traces";
-import { env } from "@/src/env.mjs";
-
-import type { FilterState } from "@langfuse/shared";
-import snakeCase from "lodash/snakeCase";
-
-export type TraceQueryType = {
- page: number;
- limit: number;
- projectId: string;
- traceId?: string;
- userId?: string;
- name?: string;
- type?: string;
- sessionId?: string;
- version?: string;
- release?: string;
- tags?: string | string[];
- environment?: string | string[];
- fromTimestamp?: string;
- toTimestamp?: string;
- fields?: TraceFieldGroup[];
- useEventsTable?: boolean | null;
-};
-
-async function buildTracesBaseQuery(
- props: TraceQueryType,
- select:
- | {
- includeObservations: boolean;
- includeIO: boolean;
- includeMetrics: boolean;
- includeScores: boolean;
- count: false;
- }
- | {
- includeObservations: false;
- includeIO: false;
- includeMetrics: false;
- includeScores: false;
- count: true;
- },
- advancedFilters?: FilterState,
- orderBy?: OrderByState,
-): Promise<{
- query: string;
- params: Record<string, any>;
- fromTimeFilter?: DateTimeFilter | undefined;
-}> {
- // ClickHouse query optimizations for List Traces API
- const disableObservationsFinal = await shouldSkipObservationsFinal(
- props.projectId,
- );
- const propagateObservationsTimeBounds =
- env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS === "true";
-
- let filter = deriveFilters(
- props,
- filterParams,
- advancedFilters,
- tracesTableUiColumnDefinitions,
- tracesTableCols,
- );
- const appliedFilter = filter.apply();
-
- const fromTimeFilter = filter.find(
- (f) =>
- f.clickhouseTable === "traces" &&
- f.field.includes("timestamp") &&
- (f.operator === ">=" || f.operator === ">"),
- ) as DateTimeFilter | undefined;
- const toTimeFilter = filter.find(
- (f) =>
- f.clickhouseTable === "traces" &&
- f.field.includes("timestamp") &&
- (f.operator === "<=" || f.operator === "<"),
- ) as DateTimeFilter | undefined;
-
- // We need to drop the clickhousePrefix here to make the filter work for the observations and scores tables.
- const environmentFilter = filter
- .filter((f) => f.field === "environment")
- .map((f) => {
- f.tablePrefix = undefined;
- return f;
- });
- const appliedEnvironmentFilter = environmentFilter.apply();
-
- // This _must_ be updated if we add a new skip index column to the traces table.
- // Otherwise, we will ignore it in most cases due to `FINAL`.
- const shouldUseSkipIndexes = filter.some(
- (f) =>
- f.clickhouseTable === "traces" &&
- ["user_id", "session_id", "metadata"].some((skipIndexCol) =>
- f.field.includes(skipIndexCol),
- ),
- );
-
- // Check if any filters reference the observations or scores tables
- const filtersNeedObservations = filter.some(
- (f) => f.clickhouseTable === "observations",
- );
- const filtersNeedScores = filter.some((f) => f.clickhouseTable === "scores");
-
- // Check if filters specifically reference score aggregation columns
- const hasScoreAggregationFilters = filter.some(
- (f) => f.field === "s.scores_avg" || f.field === "s.score_categories",
- );
-
- // Build CTEs conditionally based on requested fields OR filters
- const ctes = [];
-
- if (
- select.includeObservations ||
- select.includeMetrics ||
- filtersNeedObservations
- ) {
- // Conditionally add FINAL based on env var and whether metrics are requested
- const shouldUseFinal =
- (select.includeMetrics || filtersNeedObservations) &&
- !disableObservationsFinal;
-
- // Include metrics in CTE if requested OR if filters need them
- const includeMetricsInCTE =
- select.includeMetrics || filtersNeedObservations;
-
- ctes.push(`
- observation_stats AS (
- SELECT
- trace_id,
- project_id,
- ${includeMetricsInCTE ? "sum(total_cost) as total_cost, date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds, " : ""}
- sumMap(usage_details) as usage_details,
- sumMap(cost_details) as cost_details,
- multiIf(arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR', arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING', arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT', 'DEBUG') AS aggregated_level,
- countIf(level = 'WARNING') as warning_count,
- countIf(level = 'ERROR') as error_count,
- countIf(level = 'DEFAULT') as default_count,
- countIf(level = 'DEBUG') as debug_count,
- groupUniqArray(id) as observation_ids
- FROM observations ${shouldUseFinal ? "FINAL" : ""}
- WHERE project_id = {projectId: String}
- ${fromTimeFilter ? `AND start_time >= {cteFromTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
- ${toTimeFilter && propagateObservationsTimeBounds ? `AND start_time <= {cteToTimeFilter: DateTime64(3)} + ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
- ${toTimeFilter && propagateObservationsTimeBounds ? `AND end_time <= {cteToTimeFilter: DateTime64(3)} + ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
- ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
- GROUP BY project_id, trace_id
- )`);
- }
-
- if (select.includeScores || filtersNeedScores) {
- // Use nested structure with pre-aggregation when score filters are present
- // This ensures proper avg() computation and enables array filtering
- if (hasScoreAggregationFilters) {
- ctes.push(`
- score_stats AS (
- SELECT
- trace_id,
- project_id,
- groupUniqArray(id) as score_ids,
- groupArrayIf(tuple(name, avg_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
- groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories
- FROM (
- SELECT
- project_id,
- trace_id,
- id,
- name,
- data_type,
- string_value,
- avg(value) as avg_value
- FROM scores FINAL
- WHERE project_id = {projectId: String}
- AND session_id IS NULL
- AND dataset_run_id IS NULL
- AND data_type IN ({dataTypes: Array(String)})
- ${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
- ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
- GROUP BY
- project_id,
- trace_id,
- id,
- name,
- data_type,
- string_value
- ) tmp
- GROUP BY project_id, trace_id
- )`);
- } else {
- // Use flat structure when no score filters present (backward compatible, better performance)
- ctes.push(`
- score_stats AS (
- SELECT
- trace_id,
- project_id,
- groupUniqArray(id) as score_ids,
- groupArrayIf(tuple(name, value), data_type IN ('NUMERIC', 'BOOLEAN')) as scores_avg,
- groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL') as score_categories
- FROM scores
- WHERE project_id = {projectId: String}
- AND session_id IS NULL
- AND dataset_run_id IS NULL
- AND data_type IN ({dataTypes: Array(String)})
- ${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
- ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
- GROUP BY project_id, trace_id
- )`);
- }
- }
-
- const withClause = ctes.length > 0 ? `WITH ${ctes.join(", ")}` : "";
-
- // If user provides an order we prefer it or fallback to timestamp as the default.
- // In both cases we append a t.event_ts desc order to pick the latest event in case of duplicates
- // if we want to use a skip index.
- // This may still return stale information if the orderBy key was updated between traces or if a filter
- // applies only to a stale value.
- const chOrderBy =
- (orderByToClickhouseSql(orderBy || [], orderByColumns) ||
- "ORDER BY t.timestamp desc") +
- (shouldUseSkipIndexes ? ", t.event_ts desc" : "");
-
- const queryMiddle = `
- FROM traces t ${shouldUseSkipIndexes ? "" : "FINAL"}
- ${select.includeObservations || select.includeMetrics || filtersNeedObservations ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
- ${select.includeScores || filtersNeedScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
- WHERE t.project_id = {projectId: String}
- ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
- `;
-
- const paginationClause =
- props.limit !== undefined && props.page !== undefined
- ? `LIMIT {limit: Int32} OFFSET {offset: Int32}`
- : "";
- const limitByClause = shouldUseSkipIndexes
- ? "LIMIT 1 by t.id, t.project_id"
- : "";
-
- const coreSelect = `
- t.id as id,
- t.project_id as project_id,
- t.timestamp as timestamp,
- t.name as name,
- t.environment as environment,
- t.session_id as session_id,
- t.user_id as user_id,
- t.release as release,
- t.version as version,
- t.bookmarked as bookmarked,
- t.public as public,
- t.tags as tags,
- t.created_at as created_at,
- t.updated_at as updated_at`;
-
- const scoresSelect = select.includeScores ? ", s.score_ids as scores" : "";
- const observationsSelect = select.includeObservations
- ? ", o.observation_ids as observations"
- : "";
- const metricsSelect = select.includeMetrics
- ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost"
- : "";
-
- // Re-apply the user's ORDER BY (or default timestamp desc) after the io LEFT JOIN.
- // Intentionally omits the event_ts tiebreaker used in the base CTE because it only
- // serves LIMIT 1 BY dedup; after dedup the base already has one row per (id, project_id).
- const finalOrderBy =
- orderByToClickhouseSql(
- orderBy || [],
- orderByColumns.map((c) => ({ ...c, queryPrefix: "b" })),
- ) || "ORDER BY b.timestamp desc";
-
- let query: string;
-
- if (select.count) {
- query = `${withClause}
- SELECT count() as count
- ${queryMiddle}
- `;
- } else if (select.includeIO) {
- // Split query: sort/paginate on lightweight columns in base CTE,
- // then fetch heavy IO columns only for the final result set.
- ctes.push(`base AS (
- SELECT ${coreSelect}
- ${scoresSelect}
- ${observationsSelect}
- ${metricsSelect}
- ${queryMiddle}
- ${chOrderBy}
- ${limitByClause}
- ${paginationClause}
- )`);
-
- const ioFinal = shouldUseSkipIndexes ? "" : "FINAL";
- const ioDedup = shouldUseSkipIndexes
- ? "ORDER BY event_ts DESC LIMIT 1 BY id, project_id"
- : "";
- ctes.push(`io AS (
- SELECT id as _io_id, project_id as _io_project_id, input, output, metadata
- FROM traces ${ioFinal}
- WHERE project_id = {projectId: String}
- AND (id, project_id) IN (SELECT id, project_id FROM base)
- ${fromTimeFilter ? "AND timestamp >= {cteFromTimeFilter: DateTime64(3)}" : ""}
- ${toTimeFilter ? "AND timestamp <= {cteToTimeFilter: DateTime64(3)}" : ""}
- ${ioDedup}
- )`);
-
- query = `WITH ${ctes.join(", ")}
- SELECT
- b.id as id,
- CONCAT('/project/', b.project_id, '/traces/', b.id) as "htmlPath",
- b.project_id as project_id,
- b.timestamp as timestamp,
- b.name as name,
- b.environment as environment,
- b.session_id as session_id,
- b.user_id as user_id,
- b.release as release,
- b.version as version,
- b.bookmarked as bookmarked,
- b.public as public,
- b.tags as tags,
- b.created_at as created_at,
- b.updated_at as updated_at,
- i.input as input,
- i.output as output,
- i.metadata as metadata
- ${select.includeScores ? ", b.scores as scores" : ""}
- ${select.includeObservations ? ", b.observations as observations" : ""}
- ${select.includeMetrics ? ", b.latency as latency, b.totalCost as totalCost" : ""}
- FROM base b
- LEFT JOIN io i ON b.id = i._io_id AND b.project_id = i._io_project_id
- ${finalOrderBy}
- `;
- } else {
- query = `
- ${withClause}
- SELECT
- ${coreSelect},
- CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath"
- ${scoresSelect}
- ${observationsSelect}
- ${metricsSelect}
- ${queryMiddle}
- ${chOrderBy}
- ${limitByClause}
- ${paginationClause}
- `;
- }
-
- const needsCteToTimeFilter =
- toTimeFilter &&
- (propagateObservationsTimeBounds || (!select.count && select.includeIO));
-
- const params = {
- ...appliedEnvironmentFilter.params,
- ...appliedFilter.params,
- projectId: props.projectId,
- dataTypes: LISTABLE_SCORE_TYPES,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
- ...(fromTimeFilter
- ? {
- cteFromTimeFilter: convertDateToClickhouseDateTime(
- fromTimeFilter.value,
- ),
- }
- : {}),
- ...(needsCteToTimeFilter
- ? {
- cteToTimeFilter: convertDateToClickhouseDateTime(toTimeFilter.value),
- }
- : {}),
- };
-
- return { query, params, fromTimeFilter };
-}
-
-export const generateTracesForPublicApi = async ({
- props,
- advancedFilters,
- orderBy,
-}: {
- props: TraceQueryType;
- advancedFilters?: FilterState;
- orderBy: OrderByState;
-}) => {
- const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;
- const includeIO = requestedFields.includes("io");
- const includeScores = requestedFields.includes("scores");
- const includeObservations = requestedFields.includes("observations");
- const includeMetrics = requestedFields.includes("metrics");
-
- const { query, params, fromTimeFilter } = await buildTracesBaseQuery(
- props,
- {
- includeIO,
- includeObservations,
- includeMetrics,
- includeScores,
- count: false,
- },
- advancedFilters,
- orderBy,
- );
- const result = await measureAndReturn({
- operationName: "getTracesForPublicApi",
- projectId: props.projectId,
- input: {
- params,
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "public-api",
- projectId: props.projectId,
- operation_name: "getTracesForPublicApi",
- },
- fromTimestamp: fromTimeFilter?.value ?? undefined,
- preferredClickhouseService: "ReadOnly",
- },
- fn: (input) => {
- return queryClickhouse<
- TraceRecordReadType & {
- observations?: string[];
- scores?: string[];
- totalCost?: number;
- latency?: number;
- htmlPath: string;
- }
- >({
- query,
- params: input.params,
- tags: input.tags,
- preferredClickhouseService: "ReadOnly",
- });
- },
- });
-
- return convertClickhouseTracesListToDomain(result, {
- metrics: includeMetrics,
- scores: includeScores,
- observations: includeObservations,
- });
-};
-
-export const getTracesCountForPublicApi = async ({
- props,
- advancedFilters,
-}: {
- props: TraceQueryType;
- advancedFilters?: FilterState;
-}) => {
- let filter = deriveFilters(
- props,
- filterParams,
- advancedFilters,
- tracesTableUiColumnDefinitions,
- tracesTableCols,
- );
- const appliedFilter = filter.apply();
-
- let query = `
- SELECT count() as count
- FROM __TRACE_TABLE__ t
- WHERE project_id = {projectId: String}
- ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
- `;
-
- let params: Record<string, any> = {
- ...appliedFilter.params,
- projectId: props.projectId,
- };
-
- if (advancedFilters !== undefined && advancedFilters.length > 0) {
- ({ query, params } = await buildTracesBaseQuery(
- props,
- {
- includeObservations: false,
- includeIO: false,
- includeMetrics: false,
- includeScores: false,
- count: true,
- },
- advancedFilters,
- ));
- }
-
- const timestamp = props.fromTimestamp
- ? new Date(props.fromTimestamp)
- : undefined;
-
- return measureAndReturn({
- operationName: "getTracesCountForPublicApi",
- projectId: props.projectId,
- input: {
- params,
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "count",
- projectId: props.projectId,
- operation_name: "getTracesCountForPublicApi",
- },
- timestamp,
- },
- fn: async (input) => {
- const records = await queryClickhouse<{ count: string }>({
- query: query.replace("__TRACE_TABLE__", "traces"),
- params: input.params,
- tags: input.tags,
- preferredClickhouseService: "ReadOnly",
- });
- return records.map((record) => Number(record.count)).shift();
- },
- });
-};
-
-const orderByColumns = [
- "id",
- "timestamp",
- "name",
- "userId",
- "release",
- "version",
- "public",
- "bookmarked",
- "sessionId",
-].map((name) => ({
- uiTableName: name,
- uiTableId: name,
- clickhouseTableName: "traces",
- clickhouseSelect: snakeCase(name),
- queryPrefix: "t",
-}));
-
-// Use factory functions to create column mappings (eliminates duplication with events table)
-const filterParams = createPublicApiTracesColumnMapping("traces", "t");
diff --git a/web/src/features/public-api/types/scores.ts b/web/src/features/public-api/types/scores.ts
index 9a478d84bd..3540c2034b 100644
--- a/web/src/features/public-api/types/scores.ts
+++ b/web/src/features/public-api/types/scores.ts
@@ -1,32 +1,6 @@
-import { z } from "zod";
-import { InvalidRequestError } from "@langfuse/shared";
-
-export const ScoresCursorV3 = z.discriminatedUnion("v", [
- z.object({
- v: z.literal(1),
- lastTimestamp: z.coerce.date(),
- lastId: z.string(),
- }),
-]);
-export type ScoresCursorV3Type = z.infer<typeof ScoresCursorV3>;
-
-export const EncodedScoresCursorV3 = z
- .string()
- .transform((val) => {
- try {
- const decoded = Buffer.from(val, "base64url").toString("utf-8");
- return JSON.parse(decoded);
- } catch (_e) {
- throw new InvalidRequestError("Invalid cursor format");
- }
- })
- .pipe(ScoresCursorV3);
-
-export const encodeCursorV3 = (cursor: ScoresCursorV3Type): string =>
- Buffer.from(
- JSON.stringify({
- v: cursor.v,
- lastTimestamp: cursor.lastTimestamp.toISOString(),
- lastId: cursor.lastId,
- }),
- ).toString("base64url");
+export {
+ ScoresCursorV3,
+ EncodedScoresCursorV3,
+ encodeCursorV3,
+} from "@langfuse/shared/src/server";
+export type { ScoresCursorV3Type } from "@langfuse/shared/src/server";
diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.ts
index 01864475f8..db747fd2b9 100644
--- a/web/src/features/public-api/types/traces.ts
+++ b/web/src/features/public-api/types/traces.ts
@@ -7,22 +7,18 @@ import {
singleFilter,
InvalidRequestError,
} from "@langfuse/shared";
-import { stringDateTime, TraceBody } from "@langfuse/shared/src/server";
+import {
+ stringDateTime,
+ TraceBody,
+ TRACE_FIELD_GROUPS,
+ type TraceFieldGroup,
+} from "@langfuse/shared/src/server";
import { z } from "zod";
import { useEventsTableSchema } from "@langfuse/shared/query";
-
-/**
- * Field groups for selective field fetching
- */
-export const TRACE_FIELD_GROUPS = [
- "core",
- "io",
- "scores",
- "observations",
- "metrics",
-] as const;
-
-export type TraceFieldGroup = (typeof TRACE_FIELD_GROUPS)[number];
+export {
+ TRACE_FIELD_GROUPS,
+ type TraceFieldGroup,
+} from "@langfuse/shared/src/server";
/**
* Objects