πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(public-api): redesign repository interfaces to accept pre-built FilterList (#14182)
Niklas Semmlerd1921ae5a9bd
diff --git a/packages/shared/src/server/repositories/daily-metrics.ts b/packages/shared/src/server/repositories/daily-metrics.tsindex 9c474a17b4..f7405f128f 100644--- a/packages/shared/src/server/repositories/daily-metrics.ts+++ b/packages/shared/src/server/repositories/daily-metrics.ts@@ -1,28 +1,18 @@-import {- convertApiProvidedFilterToClickhouseFilter,- type DateTimeFilter,-} from "../queries";+import { type DateTimeFilter, FilterList } 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;+export const generateDailyMetrics = async ({+ projectId,+ filter,+ pagination,+}: {projectId: string;- userId?: string;- tags?: string | string[];- traceName?: string;- fromTimestamp?: string;- toTimestamp?: string;-};--export const generateDailyMetrics = async (props: QueryType) => {- const filter = convertApiProvidedFilterToClickhouseFilter(- props,- filterParams,- );+ filter: FilterList;+ pagination?: { limit: number; page: number };+}) => {const hasTracesFilter = filter.some((f) => f.clickhouseTable === "traces");const tracesFilter = filter.filter((f) => f.clickhouseTable === "traces");const appliedFilter = filter.apply();@@ -89,24 +79,24 @@ export const generateDailyMetrics = async (props: QueryType) => {FROM daily_model_usage dmuFULL OUTER JOIN trace_usage tu ON dmu.date = tu.dateORDER BY date DESC- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ ${pagination !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;- const timestamp = props.fromTimestamp- ? new Date(props.fromTimestamp)- : timeFilter?.value;+ const timestamp = timeFilter?.value;return measureAndReturn({operationName: "generateDailyMetrics",- projectId: props.projectId,+ 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 }+ projectId,+ ...(pagination !== undefined+ ? {+ limit: pagination.limit,+ offset: (pagination.page - 1) * pagination.limit,+ }: {}),...(timeFilter? {@@ -118,7 +108,7 @@ export const generateDailyMetrics = async (props: QueryType) => {feature: "tracing",type: "trace",kind: "daily_metrics",- projectId: props.projectId,+ projectId,operation_name: "generateDailyMetrics",},timestamp,@@ -162,14 +152,23 @@ export const generateDailyMetrics = async (props: QueryType) => {});};-export const getDailyMetricsCount = async (props: QueryType) => {- const filter = convertApiProvidedFilterToClickhouseFilter(- props,- filterParams,- );- const appliedFilter = filter- .filter((f) => f.clickhouseTable === "traces")- .apply();+export const getDailyMetricsCount = async ({+ projectId,+ filter,+}: {+ projectId: string;+ filter: FilterList;+}) => {+ const tracesFilter = filter.filter((f) => f.clickhouseTable === "traces");+ const appliedFilter = tracesFilter.apply();++ const timeFilter = filter.find(+ (f) =>+ f.clickhouseTable === "traces" &&+ f.field.includes("timestamp") &&+ (f.operator === ">=" || f.operator === ">"),+ ) as DateTimeFilter | undefined;+ const timestamp = timeFilter?.value;const query = `SELECT count(distinct toDate(timestamp)) as count@@ -178,20 +177,16 @@ export const getDailyMetricsCount = async (props: QueryType) => {${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}`;- const timestamp = props.fromTimestamp- ? new Date(props.fromTimestamp)- : undefined;-return measureAndReturn({operationName: "getDailyMetricsCount",- projectId: props.projectId,+ projectId,input: {- params: { ...appliedFilter.params, projectId: props.projectId },+ params: { ...appliedFilter.params, projectId },tags: {feature: "tracing",type: "trace",kind: "daily_metrics_count",- projectId: props.projectId,+ projectId,operation_name: "getDailyMetricsCount",},timestamp,@@ -210,57 +205,3 @@ export const getDailyMetricsCount = async (props: QueryType) => {},});};--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/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 1ae0388536..b5d12e2b8f 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -16,8 +16,6 @@ import {StringFilter,FullObservations,orderByToClickhouseSql,- createPublicApiObservationsColumnMapping,- deriveFilters,} from "../queries";import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";import {@@ -2117,31 +2115,19 @@ export const getCostByEvaluatorIds = async (// βββ Public-API observation query helpers βββββββββββββββββββββββββββββββββββββ-type PublicApiObservationQueryType = {- page: number;- limit: number;+export const generateObservationsForPublicApi = async ({+ projectId,+ filter,+ pagination,+}: {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");+ filter: FilterList;+ pagination: { limit: number; page: number };+}) => {+ const appliedFilter = filter.apply();+ const traceFilter = filter.find((f) => f.clickhouseTable === "traces");- const disableObservationsFinal = await shouldSkipObservationsFinal(- props.projectId,- );+ const disableObservationsFinal = await shouldSkipObservationsFinal(projectId);const query = `with clickhouse_keys as (@@ -2157,7 +2143,7 @@ export const generateObservationsForPublicApi = async (${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}` : ""}+ LIMIT {limit: Int32} OFFSET {offset: Int32})SELECTid,@@ -2198,20 +2184,18 @@ export const generateObservationsForPublicApi = async (return measureAndReturn({operationName: "generateObservationsForPublicApi",- projectId: props.projectId,+ projectId,input: {params: {...appliedFilter.params,- projectId: props.projectId,- ...(props.limit !== undefined ? { limit: props.limit } : {}),- ...(props.page !== undefined- ? { offset: (props.page - 1) * props.limit }- : {}),+ projectId,+ limit: pagination.limit,+ offset: (pagination.page - 1) * pagination.limit,},tags: {feature: "tracing",type: "observation",- projectId: props.projectId,+ projectId,operation_name: "generateObservationsForPublicApi",},},@@ -2227,12 +2211,15 @@ export const generateObservationsForPublicApi = async (});};-export const getObservationsCountForPublicApi = async (- props: PublicApiObservationQueryType,-) => {- const chFilter = generatePublicApiObservationFilter(props);- const filter = chFilter.apply();- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");+export const getObservationsCountForPublicApi = async ({+ projectId,+ filter,+}: {+ projectId: string;+ filter: FilterList;+}) => {+ const appliedFilter = filter.apply();+ const traceFilter = filter.find((f) => f.clickhouseTable === "traces");const query = `SELECT count() as count@@ -2240,18 +2227,18 @@ export const getObservationsCountForPublicApi = async (${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}+ AND ${appliedFilter.query}`;return measureAndReturn({operationName: "getObservationsCountForPublicApi",- projectId: props.projectId,+ projectId,input: {- params: { ...filter.params, projectId: props.projectId },+ params: { ...appliedFilter.params, projectId },tags: {feature: "tracing",type: "observation",- projectId: props.projectId,+ projectId,operation_name: "getObservationsCountForPublicApi",},},@@ -2266,39 +2253,3 @@ export const getObservationsCountForPublicApi = async (},});};--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/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 4e81acabf7..495bfd9dbb 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -25,12 +25,9 @@ import {import {FilterList,orderByToClickhouseSql,- StringFilter,StringOptionsFilter,DateTimeFilter,NumberFilter,- convertApiProvidedFilterToClickhouseFilter,- deriveFilters,} from "../queries";import { FilterCondition, FilterState, TimeFilter } from "../../types";import {@@ -2410,212 +2407,26 @@ export type ScoreQueryType = {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,+ projectId,+ scoresFilter,+ tracesFilter,scoreScope,- scoreDataTypes,+ includeTrace,+ needsTraceJoin,+ pagination,}: {- props: ScoreQueryType;+ projectId: string;+ scoresFilter: FilterList;+ tracesFilter: FilterList;scoreScope: "traces_only" | "all";- scoreDataTypes?: readonly ScoreDataTypeType[];+ includeTrace: boolean;+ needsTraceJoin: boolean;+ pagination?: { limit: number; page: number };}) => {- 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," : ""}@@ -2670,26 +2481,28 @@ export const _handleGenerateScoresForPublicApi = async ({s.timestamp desc, s.event_ts descLIMIT1 BY s.id, s.project_id- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ ${pagination !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;return measureAndReturn({operationName: "_handleGenerateScoresForPublicApi",- projectId: props.projectId,+ 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 }+ projectId,+ ...(pagination !== undefined+ ? {+ limit: pagination.limit,+ offset: (pagination.page - 1) * pagination.limit,+ }: {}),},tags: {feature: "scoring",type: "score",- projectId: props.projectId,+ projectId,scoreScope,operation_name: "_handleGenerateScoresForPublicApi",includeTrace: includeTrace.toString(),@@ -2730,26 +2543,23 @@ export const _handleGenerateScoresForPublicApi = async ({};export const _handleGetScoresCountForPublicApi = async ({- props,+ projectId,+ scoresFilter,+ tracesFilter,scoreScope,- scoreDataTypes,+ includeTrace,+ needsTraceJoin,}: {- props: ScoreQueryType;+ projectId: string;+ scoresFilter: FilterList;+ tracesFilter: FilterList;scoreScope: "traces_only" | "all";- scoreDataTypes?: readonly ScoreDataTypeType[];+ includeTrace: boolean;+ needsTraceJoin: boolean;}) => {- const { scoresFilter, tracesFilter } = generateScoreFilter(- props,- scoreDataTypes,- );const appliedScoresFilter = scoresFilter.apply();const appliedTracesFilter = tracesFilter.apply();- const { includeTrace, needsTraceJoin } = determineTraceJoinRequirement(- props.fields,- tracesFilter.length(),- );-const query = `SELECTcount() as count@@ -2781,17 +2591,17 @@ export const _handleGetScoresCountForPublicApi = async ({return measureAndReturn({operationName: "_handleGetScoresCountForPublicApi",- projectId: props.projectId,+ projectId,input: {params: {...appliedScoresFilter.params,...appliedTracesFilter.params,- projectId: props.projectId,+ projectId,},tags: {feature: "scoring",type: "score",- projectId: props.projectId,+ projectId,scoreScope,operation_name: "_handleGetScoresCountForPublicApi",includeTrace: includeTrace.toString(),diff --git a/packages/shared/src/server/repositories/traces.test.ts b/packages/shared/src/server/repositories/traces.test.tsnew file mode 100644index 0000000000..fbbc4133f9--- /dev/null+++ b/packages/shared/src/server/repositories/traces.test.ts@@ -0,0 +1,85 @@+import { describe, it, expect, beforeEach, vi } from "vitest";++const mockQueryClickhouse = vi.hoisted(() => vi.fn());+const mockShouldSkipObservationsFinal = vi.hoisted(() => vi.fn());+let charCounter = 0;++vi.mock("./clickhouse", () => ({+ queryClickhouse: mockQueryClickhouse,+ commandClickhouse: vi.fn(),+ queryClickhouseStream: vi.fn(),+ upsertClickhouse: vi.fn(),+ parseClickhouseUTCDateTimeFormat: vi.fn(),+ // Return unique names per call so filter parameter variables don't collide+ clickhouseCompliantRandomCharacters: vi.fn(() => `x${++charCounter}`),+}));++vi.mock("../queries/clickhouse-sql/query-options", () => ({+ shouldSkipObservationsFinal: mockShouldSkipObservationsFinal,+}));++import { getTracesCountForPublicApi } from "./traces";+import {+ FilterList,+ StringFilter,+} from "../queries/clickhouse-sql/clickhouse-filter";++describe("getTracesCountForPublicApi β FINAL modifier", () => {+ beforeEach(() => {+ charCounter = 0;+ vi.clearAllMocks();+ mockQueryClickhouse.mockResolvedValue([{ count: "0" }]);+ mockShouldSkipObservationsFinal.mockResolvedValue(false);+ });++ it("uses FINAL for a non-skip-index trace filter", async () => {+ const filter = new FilterList([+ new StringFilter({+ clickhouseTable: "traces",+ field: "name",+ operator: "=",+ value: "my-trace",+ }),+ ]);++ await getTracesCountForPublicApi({ projectId: "proj-1", filter });++ expect(mockQueryClickhouse).toHaveBeenCalledOnce();+ const { query } = mockQueryClickhouse.mock.calls[0][0];+ expect(query).toMatch(/FROM\s+traces\s+t\s+FINAL/);+ });++ it("does not use FINAL for skip-index trace filters (user_id / session_id / metadata)", async () => {+ const filter = new FilterList([+ new StringFilter({+ clickhouseTable: "traces",+ field: "user_id",+ operator: "=",+ value: "user-abc",+ }),+ ]);++ await getTracesCountForPublicApi({ projectId: "proj-1", filter });++ expect(mockQueryClickhouse).toHaveBeenCalledOnce();+ const { query } = mockQueryClickhouse.mock.calls[0][0];+ expect(query).not.toContain("FINAL");+ });++ it("uses FINAL when an observations-table filter is present", async () => {+ const filter = new FilterList([+ new StringFilter({+ clickhouseTable: "observations",+ field: "name",+ operator: "=",+ value: "obs-span",+ }),+ ]);++ await getTracesCountForPublicApi({ projectId: "proj-1", filter });++ expect(mockQueryClickhouse).toHaveBeenCalledOnce();+ const { query } = mockQueryClickhouse.mock.calls[0][0];+ expect(query).toMatch(/FROM\s+traces\s+t\s+FINAL/);+ });+});diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex dd75dbcd20..67b225e43f 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -9,11 +9,7 @@ import {createFilterFromFilterState,getProjectIdDefaultFilter,} from "../queries/clickhouse-sql/factory";-import {- orderByToClickhouseSql,- deriveFilters,- createPublicApiTracesColumnMapping,-} from "../queries";+import { orderByToClickhouseSql } from "../queries";import { shouldSkipObservationsFinal } from "../queries/clickhouse-sql/query-options";import { LISTABLE_SCORE_TYPES } from "../../domain/scores";import { OrderByState } from "../../interfaces/orderBy";@@ -1753,13 +1749,16 @@ const traceOrderByColumns = [queryPrefix: "t",}));-const publicApiTracesFilterParams = createPublicApiTracesColumnMapping(- "traces",- "t",-);-async function buildTracesBaseQuery(- props: TraceQueryType,+ {+ projectId,+ filter,+ pagination,+ }: {+ projectId: string;+ filter: FilterList;+ pagination?: { limit: number; page: number };+ },select:| {includeObservations: boolean;@@ -1775,26 +1774,16 @@ async function buildTracesBaseQuery(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 disableObservationsFinal = await shouldSkipObservationsFinal(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(@@ -1946,7 +1935,7 @@ async function buildTracesBaseQuery(`;const paginationClause =- props.limit !== undefined && props.page !== undefined+ pagination !== undefined? `LIMIT {limit: Int32} OFFSET {offset: Int32}`: "";const limitByClause = shouldUseSkipIndexes@@ -2066,11 +2055,13 @@ async function buildTracesBaseQuery(const params = {...appliedEnvironmentFilter.params,...appliedFilter.params,- projectId: props.projectId,+ projectId,dataTypes: LISTABLE_SCORE_TYPES,- ...(props.limit !== undefined ? { limit: props.limit } : {}),- ...(props.page !== undefined- ? { offset: (props.page - 1) * props.limit }+ ...(pagination !== undefined+ ? {+ limit: pagination.limit,+ offset: (pagination.page - 1) * pagination.limit,+ }: {}),...(fromTimeFilter? {@@ -2090,22 +2081,26 @@ async function buildTracesBaseQuery(}export const generateTracesForPublicApi = async ({- props,- advancedFilters,+ projectId,+ filter,orderBy,+ pagination,+ fields,}: {- props: TraceQueryType;- advancedFilters?: FilterState;+ projectId: string;+ filter: FilterList;orderBy: OrderByState;+ pagination?: { limit: number; page: number };+ fields?: TraceFieldGroup[];}) => {- const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;+ const requestedFields = 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,+ { projectId, filter, pagination },{includeIO,includeObservations,@@ -2113,19 +2108,18 @@ export const generateTracesForPublicApi = async ({includeScores,count: false,},- advancedFilters,orderBy,);const result = await measureAndReturn({operationName: "getTracesForPublicApi",- projectId: props.projectId,+ projectId,input: {params,tags: {feature: "tracing",type: "trace",kind: "public-api",- projectId: props.projectId,+ projectId,operation_name: "getTracesForPublicApi",},fromTimestamp: fromTimeFilter?.value ?? undefined,@@ -2157,21 +2151,33 @@ export const generateTracesForPublicApi = async ({};export const getTracesCountForPublicApi = async ({- props,- advancedFilters,+ projectId,+ filter,+ pagination,}: {- props: TraceQueryType;- advancedFilters?: FilterState;+ projectId: string;+ filter: FilterList;+ pagination?: { limit: number; page: number };}) => {- 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 needsComplexQuery = filter.some(+ (f) =>+ f.clickhouseTable === "observations" ||+ f.clickhouseTable === "scores" ||+ (f.clickhouseTable === "traces" &&+ !["user_id", "session_id", "metadata"].some((c) =>+ f.field.includes(c),+ )),+ );+let query = `SELECT count() as countFROM __TRACE_TABLE__ t@@ -2181,12 +2187,12 @@ export const getTracesCountForPublicApi = async ({let params: Record<string, any> = {...appliedFilter.params,- projectId: props.projectId,+ projectId,};- if (advancedFilters !== undefined && advancedFilters.length > 0) {+ if (needsComplexQuery) {({ query, params } = await buildTracesBaseQuery(- props,+ { projectId, filter, pagination },{includeObservations: false,includeIO: false,@@ -2194,24 +2200,21 @@ export const getTracesCountForPublicApi = async ({includeScores: false,count: true,},- advancedFilters,));}- const timestamp = props.fromTimestamp- ? new Date(props.fromTimestamp)- : undefined;+ const timestamp = fromTimeFilter?.value;return measureAndReturn({operationName: "getTracesCountForPublicApi",- projectId: props.projectId,+ projectId,input: {params,tags: {feature: "tracing",type: "trace",kind: "count",- projectId: props.projectId,+ projectId,operation_name: "getTracesCountForPublicApi",},timestamp,diff --git a/web/src/__tests__/server/unit/buildObservationsFilter.servertest.ts b/web/src/__tests__/server/unit/buildObservationsFilter.servertest.tsnew file mode 100644index 0000000000..ee46ec4653--- /dev/null+++ b/web/src/__tests__/server/unit/buildObservationsFilter.servertest.ts@@ -0,0 +1,156 @@+const {+ mockGenerateObservations,+ mockGetObservationsCount,+ mockDeriveFilters,+ // A mutable holder so the mock factory (hoisted) can store the real+ // deriveFilters implementation for use as the default pass-through.+ realFns,+} = vi.hoisted(() => ({+ mockGenerateObservations: vi.fn(),+ mockGetObservationsCount: vi.fn(),+ mockDeriveFilters: vi.fn(),+ realFns: { deriveFilters: null as unknown },+}));++vi.mock("@langfuse/shared/src/server", async () => {+ const actual = await vi.importActual("@langfuse/shared/src/server");+ realFns.deriveFilters = (actual as Record<string, unknown>).deriveFilters;+ return {+ ...(actual as object),+ generateObservationsForPublicApi: mockGenerateObservations,+ getObservationsCountForPublicApi: mockGetObservationsCount,+ deriveFilters: mockDeriveFilters,+ };+});++import {+ generateObservationsForPublicApi,+ getObservationsCountForPublicApi,+} from "@/src/features/public-api/server/observations";+import { FilterList, StringFilter } from "@langfuse/shared/src/server";++const BASE = {+ projectId: "project-1",+ page: 1,+ limit: 10,+};++describe("buildObservationsFilter", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGenerateObservations.mockResolvedValue([]);+ mockGetObservationsCount.mockResolvedValue(0);+ // Pass through to the real deriveFilters by default.+ mockDeriveFilters.mockImplementation((...args: unknown[]) =>+ (realFns.deriveFilters as (...a: unknown[]) => unknown)(...args),+ );+ });++ it("always injects project_id on the observations table", async () => {+ await generateObservationsForPublicApi(BASE);++ const { filter } = mockGenerateObservations.mock.calls[0][0];+ expect(+ filter.some(+ (f: any) =>+ f.field === "project_id" &&+ f.clickhouseTable === "observations" &&+ f.value === "project-1",+ ),+ ).toBe(true);+ });++ it("traceId maps to trace_id on the observations table", async () => {+ await generateObservationsForPublicApi({ ...BASE, traceId: "trace-abc" });++ const { filter } = mockGenerateObservations.mock.calls[0][0];+ expect(+ filter.some(+ (f: any) =>+ f.field === "trace_id" && f.clickhouseTable === "observations",+ ),+ ).toBe(true);+ });++ it("level maps to a filter on the observations table", async () => {+ await generateObservationsForPublicApi({ ...BASE, level: "ERROR" });++ const { filter } = mockGenerateObservations.mock.calls[0][0];+ expect(+ filter.some(+ (f: any) => f.field === "level" && f.clickhouseTable === "observations",+ ),+ ).toBe(true);+ });++ it("strips scores-table filters even when deriveFilters produces them", async () => {+ // Simulate a future regression where deriveFilters somehow emits a+ // scores-table filter. The post-process strip in buildObservationsFilter+ // must remove it before the filter reaches the repository.+ mockDeriveFilters.mockReturnValueOnce(+ new FilterList([+ new StringFilter({+ clickhouseTable: "scores",+ field: "name",+ operator: "=",+ value: "accuracy",+ }),+ new StringFilter({+ clickhouseTable: "observations",+ field: "trace_id",+ operator: "=",+ value: "trace-abc",+ }),+ ]),+ );++ await generateObservationsForPublicApi(BASE);++ const { filter } = mockGenerateObservations.mock.calls[0][0];+ expect(filter.some((f: any) => f.clickhouseTable === "scores")).toBe(false);+ expect(filter.some((f: any) => f.clickhouseTable === "observations")).toBe(+ true,+ );+ });++ it("passes the correct projectId and pagination through to the repository", async () => {+ await generateObservationsForPublicApi({+ ...BASE,+ projectId: "proj-99",+ page: 3,+ limit: 50,+ });++ const callArg = mockGenerateObservations.mock.calls[0][0];+ expect(callArg.projectId).toBe("proj-99");+ expect(callArg.pagination).toEqual({ page: 3, limit: 50 });+ });++ it("count variant strips scores-table filters and injects project_id", async () => {+ // Same injection approach as the list variant to verify the strip runs+ // on the count path too.+ mockDeriveFilters.mockReturnValueOnce(+ new FilterList([+ new StringFilter({+ clickhouseTable: "scores",+ field: "value",+ operator: "=",+ value: "0.9",+ }),+ ]),+ );++ await getObservationsCountForPublicApi({ ...BASE, traceId: "trace-abc" });++ const { filter } = mockGetObservationsCount.mock.calls[0][0];+ expect(+ filter.some(+ (f: any) =>+ f.field === "project_id" &&+ f.clickhouseTable === "observations" &&+ f.value === "project-1",+ ),+ ).toBe(true);+ expect(filter.some((f: any) => f.clickhouseTable === "scores")).toBe(false);+ });+});diff --git a/web/src/__tests__/server/unit/buildScoreFilters.servertest.ts b/web/src/__tests__/server/unit/buildScoreFilters.servertest.tsnew file mode 100644index 0000000000..22374853e9--- /dev/null+++ b/web/src/__tests__/server/unit/buildScoreFilters.servertest.ts@@ -0,0 +1,191 @@+const { mockHandleGenerateScores, mockHandleGetScoresCount } = vi.hoisted(+ () => ({+ mockHandleGenerateScores: vi.fn(),+ mockHandleGetScoresCount: vi.fn(),+ }),+);++vi.mock("@/src/features/public-api/server/scores", () => ({+ _handleGenerateScoresForPublicApi: mockHandleGenerateScores,+ _handleGetScoresCountForPublicApi: mockHandleGetScoresCount,+ convertScoreToPublicApi: vi.fn((score) => score),+}));++vi.mock("@/src/features/audit-logs/auditLog", () => ({+ auditLog: vi.fn(),+}));++import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";+import { LISTABLE_SCORE_TYPES } from "@langfuse/shared";+import type { ScoreQueryType } from "@langfuse/shared/src/server";++const BASE: ScoreQueryType = {+ projectId: "project-1",+ page: 1,+ limit: 10,+};++describe("buildScoreFilters", () => {+ beforeEach(() => {+ mockHandleGenerateScores.mockResolvedValue([]);+ mockHandleGetScoresCount.mockResolvedValue(0);+ vi.clearAllMocks();+ mockHandleGenerateScores.mockResolvedValue([]);+ });++ it("always injects project_id into scoresFilter", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi(BASE);++ const { scoresFilter } = mockHandleGenerateScores.mock.calls[0][0];+ expect(+ scoresFilter.some(+ (f: any) => f.field === "project_id" && f.value === "project-1",+ ),+ ).toBe(true);+ });++ it("v1 adds data_type restriction to scoresFilter for listable score types", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi(BASE);++ const { scoresFilter } = mockHandleGenerateScores.mock.calls[0][0];+ const dataTypeFilter = scoresFilter.find(+ (f: any) => f.field === "data_type",+ );+ expect(dataTypeFilter).toBeDefined();+ expect(dataTypeFilter.values).toEqual(+ expect.arrayContaining([...LISTABLE_SCORE_TYPES]),+ );+ expect(dataTypeFilter.values).toHaveLength(LISTABLE_SCORE_TYPES.length);+ });++ it("v2 does not add a data_type restriction from scoreDataTypes", async () => {+ await new ScoresApiService("v2").generateScoresForPublicApi(BASE);++ const { scoresFilter } = mockHandleGenerateScores.mock.calls[0][0];+ // With BASE props only project_id should be present (1 filter total)+ expect(scoresFilter.length()).toBe(1);+ });++ it("name filter lands in scoresFilter, not tracesFilter", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ name: "accuracy",+ });++ const { scoresFilter, tracesFilter } =+ mockHandleGenerateScores.mock.calls[0][0];+ expect(scoresFilter.some((f: any) => f.field === "name")).toBe(true);+ expect(tracesFilter.some((f: any) => f.field === "name")).toBe(false);+ });++ it("traceId filter lands in scoresFilter, not tracesFilter", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ traceId: "trace-abc",+ });++ const { scoresFilter, tracesFilter } =+ mockHandleGenerateScores.mock.calls[0][0];+ expect(scoresFilter.some((f: any) => f.field === "trace_id")).toBe(true);+ expect(tracesFilter.some((f: any) => f.field === "trace_id")).toBe(false);+ });++ it("userId filter lands in tracesFilter, not scoresFilter", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ userId: "user-xyz",+ });++ const { scoresFilter, tracesFilter } =+ mockHandleGenerateScores.mock.calls[0][0];+ expect(tracesFilter.some((f: any) => f.field === "user_id")).toBe(true);+ expect(scoresFilter.some((f: any) => f.field === "user_id")).toBe(false);+ });++ it("environment alone does not add to tracesFilter when no other trace filters are set", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ environment: "production",+ });++ const { tracesFilter } = mockHandleGenerateScores.mock.calls[0][0];+ expect(tracesFilter.length()).toBe(0);+ });++ it("environment is added to tracesFilter when userId is also provided", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ userId: "user-xyz",+ environment: "production",+ });++ const { tracesFilter } = mockHandleGenerateScores.mock.calls[0][0];+ expect(tracesFilter.some((f: any) => f.field === "user_id")).toBe(true);+ expect(tracesFilter.some((f: any) => f.field === "environment")).toBe(true);+ });++ it("environment is added to tracesFilter when traceTags is also provided", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ traceTags: ["llm"],+ environment: "staging",+ });++ const { tracesFilter } = mockHandleGenerateScores.mock.calls[0][0];+ expect(tracesFilter.some((f: any) => f.field === "tags")).toBe(true);+ expect(tracesFilter.some((f: any) => f.field === "environment")).toBe(true);+ });+});++describe("determineTraceJoinRequirement", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockHandleGenerateScores.mockResolvedValue([]);+ });++ it("no fields param β includeTrace true, needsTraceJoin true", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi(BASE);++ const { includeTrace, needsTraceJoin } =+ mockHandleGenerateScores.mock.calls[0][0];+ expect(includeTrace).toBe(true);+ expect(needsTraceJoin).toBe(true);+ });++ it("fields=[score] and no trace filters β includeTrace false, needsTraceJoin false", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ fields: ["score"],+ });++ const { includeTrace, needsTraceJoin } =+ mockHandleGenerateScores.mock.calls[0][0];+ expect(includeTrace).toBe(false);+ expect(needsTraceJoin).toBe(false);+ });++ it("fields=[score] with userId β includeTrace false but needsTraceJoin true", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ fields: ["score"],+ userId: "user-xyz",+ });++ const { includeTrace, needsTraceJoin } =+ mockHandleGenerateScores.mock.calls[0][0];+ expect(includeTrace).toBe(false);+ expect(needsTraceJoin).toBe(true);+ });++ it("fields=[score, trace] β includeTrace true, needsTraceJoin true", async () => {+ await new ScoresApiService("v1").generateScoresForPublicApi({+ ...BASE,+ fields: ["score", "trace"],+ });++ const { includeTrace, needsTraceJoin } =+ mockHandleGenerateScores.mock.calls[0][0];+ expect(includeTrace).toBe(true);+ expect(needsTraceJoin).toBe(true);+ });+});diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.tsindex 2f74c9ad3a..dff5124a85 100644--- a/web/src/features/public-api/server/dailyMetrics.ts+++ b/web/src/features/public-api/server/dailyMetrics.ts@@ -1,4 +1,92 @@-export {- generateDailyMetrics,- getDailyMetricsCount,+import {+ generateDailyMetrics as _generateDailyMetrics,+ getDailyMetricsCount as _getDailyMetricsCount,+ convertApiProvidedFilterToClickhouseFilter,} from "@langfuse/shared/src/server";++type DailyMetricsQueryProps = {+ page: number;+ limit: number;+ projectId: string;+ userId?: string;+ tags?: string | string[];+ traceName?: string;+ fromTimestamp?: string;+ toTimestamp?: string;+ traceEnvironment?: string | string[];+ observationEnvironment?: string | string[];+};++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",+ },+];++export const generateDailyMetrics = (props: DailyMetricsQueryProps) => {+ const filter = convertApiProvidedFilterToClickhouseFilter(+ props,+ filterParams,+ );+ return _generateDailyMetrics({+ projectId: props.projectId,+ filter,+ pagination: { limit: props.limit, page: props.page },+ });+};++export const getDailyMetricsCount = (props: DailyMetricsQueryProps) => {+ const filter = convertApiProvidedFilterToClickhouseFilter(+ props,+ filterParams,+ );+ return _getDailyMetricsCount({ projectId: props.projectId, filter });+};diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.tsindex ea460a1e41..b4906b7a72 100644--- a/web/src/features/public-api/server/observations.ts+++ b/web/src/features/public-api/server/observations.ts@@ -1,4 +1,82 @@-export {- generateObservationsForPublicApi,- getObservationsCountForPublicApi,+import {+ generateObservationsForPublicApi as _generateObservationsForPublicApi,+ getObservationsCountForPublicApi as _getObservationsCountForPublicApi,+ createPublicApiObservationsColumnMapping,+ deriveFilters,+ StringFilter,+ observationsTableUiColumnDefinitions,} from "@langfuse/shared/src/server";+import { observationsTableCols } from "@langfuse/shared";+import type { FilterState } from "@langfuse/shared";++type ObservationsApiQueryProps = {+ page: number;+ limit: number;+ projectId: string;+ traceId?: string;+ userId?: string;+ level?: string;+ name?: string;+ type?: string;+ environment?: string | string[];+ parentObservationId?: string;+ fromStartTime?: string;+ toStartTime?: string;+ version?: string;+ advancedFilters?: FilterState;+};++const publicApiObservationsFilterParams =+ createPublicApiObservationsColumnMapping(+ "observations",+ "o",+ "parent_observation_id",+ );++function buildObservationsFilter(props: ObservationsApiQueryProps) {+ const { advancedFilters, ...simpleFilterProps } = props;+ 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: props.projectId,+ }),+ );+ return filteredChFilter;+}++export const generateObservationsForPublicApi = (+ props: ObservationsApiQueryProps,+) => {+ const filter = buildObservationsFilter(props);+ return _generateObservationsForPublicApi({+ projectId: props.projectId,+ filter,+ pagination: { limit: props.limit, page: props.page },+ });+};++export const getObservationsCountForPublicApi = (+ props: ObservationsApiQueryProps,+) => {+ const filter = buildObservationsFilter(props);+ return _getObservationsCountForPublicApi({+ projectId: props.projectId,+ filter,+ });+};diff --git a/web/src/features/public-api/server/scores-api-service.ts b/web/src/features/public-api/server/scores-api-service.tsindex 223e91327d..9232e6c5b2 100644--- a/web/src/features/public-api/server/scores-api-service.ts+++ b/web/src/features/public-api/server/scores-api-service.ts@@ -12,6 +12,8 @@ import {LISTABLE_SCORE_TYPES,type ScoreSourceType,type PostScoresBodyV1,+ scoresTableCols,+ type ScoreDataTypeType,} from "@langfuse/shared";import {_handleGetScoreById,@@ -20,9 +22,200 @@ import {QueueJobs,ScoreDeleteQueue,type AuthHeaderValidVerificationResultIngestion,+ StringFilter,+ StringOptionsFilter,+ type FilterList,+ deriveFilters,+ convertApiProvidedFilterToClickhouseFilter,+ scoresTableUiColumnDefinitions,} from "@langfuse/shared/src/server";import type { z } from "zod";+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",+ },+];++function buildScoreFilters(+ props: ScoreQueryType,+ scoreDataTypes?: readonly ScoreDataTypeType[],+): { scoresFilter: FilterList; tracesFilter: FilterList } {+ const scoresFilter = deriveFilters(+ props,+ secureScoreFilterOptions,+ props.advancedFilters,+ scoresTableUiColumnDefinitions,+ scoresTableCols,+ );+ scoresFilter.push(+ new StringFilter({+ clickhouseTable: "scores",+ field: "project_id",+ operator: "=",+ value: props.projectId,+ }),+ );++ if (scoreDataTypes) {+ scoresFilter.push(+ new StringOptionsFilter({+ clickhouseTable: "scores",+ field: "data_type",+ operator: "any of",+ values: [...scoreDataTypes],+ tablePrefix: "s",+ }),+ );+ }++ const tracesFilter = convertApiProvidedFilterToClickhouseFilter(+ props,+ secureTraceFilterOptions,+ );++ if (props.environment && tracesFilter.length() > 0) {+ const envValues = Array.isArray(props.environment)+ ? props.environment+ : [props.environment];+ tracesFilter.push(+ new StringOptionsFilter({+ clickhouseTable: "traces",+ field: "environment",+ operator: "any of",+ values: envValues,+ tablePrefix: "t",+ }),+ );+ }++ return { scoresFilter, tracesFilter };+}++function 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 };+}+export class ScoresApiService {constructor(private readonly apiVersion: "v1" | "v2") {}@@ -157,11 +350,24 @@ export class ScoresApiService {* v2: Returns all score types including CORRECTION and TEXT*/async generateScoresForPublicApi(props: ScoreQueryType) {- const results = await _handleGenerateScoresForPublicApi({+ const scoreDataTypes =+ this.apiVersion === "v1" ? LISTABLE_SCORE_TYPES : undefined;+ const { scoresFilter, tracesFilter } = buildScoreFilters(props,+ scoreDataTypes,+ );+ const { includeTrace, needsTraceJoin } = determineTraceJoinRequirement(+ props.fields,+ tracesFilter.length(),+ );+ const results = await _handleGenerateScoresForPublicApi({+ projectId: props.projectId,+ scoresFilter,+ tracesFilter,scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",- scoreDataTypes:- this.apiVersion === "v1" ? LISTABLE_SCORE_TYPES : undefined,+ includeTrace,+ needsTraceJoin,+ pagination: { limit: props.limit, page: props.page },});// Apply API-shape transformation (moves longStringValueβstringValue for// CORRECTION, strips longStringValue for others). Must happen here because@@ -179,11 +385,23 @@ export class ScoresApiService {* v2: Counts all score types including CORRECTION and TEXT*/async getScoresCountForPublicApi(props: ScoreQueryType) {- return _handleGetScoresCountForPublicApi({+ const scoreDataTypes =+ this.apiVersion === "v1" ? LISTABLE_SCORE_TYPES : undefined;+ const { scoresFilter, tracesFilter } = buildScoreFilters(props,+ scoreDataTypes,+ );+ const { includeTrace, needsTraceJoin } = determineTraceJoinRequirement(+ props.fields,+ tracesFilter.length(),+ );+ return _handleGetScoresCountForPublicApi({+ projectId: props.projectId,+ scoresFilter,+ tracesFilter,scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",- scoreDataTypes:- this.apiVersion === "v1" ? LISTABLE_SCORE_TYPES : undefined,+ includeTrace,+ needsTraceJoin,});}}diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsindex cef9e22318..2fafbe02ab 100644--- a/web/src/features/public-api/server/traces.ts+++ b/web/src/features/public-api/server/traces.ts@@ -1,4 +1,61 @@-export {- generateTracesForPublicApi,- getTracesCountForPublicApi,+import {+ generateTracesForPublicApi as _generateTracesForPublicApi,+ getTracesCountForPublicApi as _getTracesCountForPublicApi,+ createPublicApiTracesColumnMapping,+ deriveFilters,+ tracesTableUiColumnDefinitions,+ type TraceQueryType,} from "@langfuse/shared/src/server";+import { tracesTableCols } from "@langfuse/shared";+import type { FilterState, OrderByState } from "@langfuse/shared";++const publicApiTracesFilterParams = createPublicApiTracesColumnMapping(+ "traces",+ "t",+);++export const generateTracesForPublicApi = ({+ props,+ advancedFilters,+ orderBy,+}: {+ props: TraceQueryType;+ advancedFilters?: FilterState;+ orderBy: OrderByState;+}) => {+ const filter = deriveFilters(+ props,+ publicApiTracesFilterParams,+ advancedFilters,+ tracesTableUiColumnDefinitions,+ tracesTableCols,+ );+ return _generateTracesForPublicApi({+ projectId: props.projectId,+ filter,+ orderBy,+ pagination: { limit: props.limit, page: props.page },+ fields: props.fields,+ });+};++export const getTracesCountForPublicApi = ({+ props,+ advancedFilters,+}: {+ props: TraceQueryType;+ advancedFilters?: FilterState;+}) => {+ const filter = deriveFilters(+ props,+ publicApiTracesFilterParams,+ advancedFilters,+ tracesTableUiColumnDefinitions,+ tracesTableCols,+ );+ return _getTracesCountForPublicApi({+ projectId: props.projectId,+ filter,+ pagination: { limit: props.limit, page: props.page },+ });+};