Skip to content

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

chore: batch events_* table scans when computing filterOptions (#14516)

Valery Meleshkind982adfc8491
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-filter-options.ts b/packages/shared/src/server/queries/clickhouse-sql/event-filter-options.ts
new file mode 100644
index 0000000000..595b727f40
--- /dev/null
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-filter-options.ts
@@ -0,0 +1,413 @@
+import { InvalidRequestError } from "../../../errors";
+import {
+ eventsTableCols,
+ eventsTableHasParentObservationSql,
+ eventsTableIsRootObservationSql,
+} from "../../../eventsTable";
+import type { FilterState } from "../../../types";
+import { eventsTableUiColumnDefinitions } from "../../tableMappings/mapEventsTable";
+import { FilterList } from "./clickhouse-filter";
+import {
+ EventsAggQueryBuilder,
+ EventsQueryBuilder,
+} from "./event-query-builder";
+import { createFilterFromFilterState } from "./factory";
+
+export const EVENTS_FILTER_OPTION_TOP_N = 1000;
+const EVENTS_FILTER_OPTION_TOP_K_MAX_N = 65_536;
+
+type EventFilterOptionSort = "countDesc" | "alpha" | "booleanAsc";
+
+type EventFilterOptionDefinition =
+ | {
+ kind: "scalar";
+ expression: string;
+ includeWhen: string;
+ sort: EventFilterOptionSort;
+ }
+ | {
+ kind: "array";
+ expression: string;
+ sort: EventFilterOptionSort;
+ distinct?: boolean;
+ }
+ | {
+ kind: "boolean";
+ expression: string;
+ sort: "booleanAsc";
+ };
+
+const EVENTS_FILTER_OPTION_DEFINITIONS = {
+ providedModelName: {
+ kind: "scalar",
+ expression: "e.provided_model_name",
+ includeWhen:
+ "e.provided_model_name IS NOT NULL AND length(e.provided_model_name) > 0",
+ sort: "countDesc",
+ },
+ modelId: {
+ kind: "scalar",
+ expression: "e.model_id",
+ includeWhen: "e.model_id IS NOT NULL AND length(e.model_id) > 0",
+ sort: "countDesc",
+ },
+ name: {
+ kind: "scalar",
+ expression: "e.name",
+ includeWhen: "e.name IS NOT NULL AND length(e.name) > 0",
+ sort: "countDesc",
+ },
+ traceName: {
+ kind: "scalar",
+ expression: "e.trace_name",
+ includeWhen: "e.trace_name IS NOT NULL AND length(e.trace_name) > 0",
+ sort: "countDesc",
+ },
+ type: {
+ kind: "scalar",
+ expression: "e.type",
+ includeWhen: "e.type IS NOT NULL AND length(e.type) > 0",
+ sort: "countDesc",
+ },
+ userId: {
+ kind: "scalar",
+ expression: "e.user_id",
+ includeWhen: "e.user_id IS NOT NULL AND length(e.user_id) > 0",
+ sort: "countDesc",
+ },
+ version: {
+ kind: "scalar",
+ expression: "e.version",
+ includeWhen: "e.version IS NOT NULL AND length(e.version) > 0",
+ sort: "countDesc",
+ },
+ sessionId: {
+ kind: "scalar",
+ expression: "e.session_id",
+ includeWhen: "e.session_id IS NOT NULL AND length(e.session_id) > 0",
+ sort: "countDesc",
+ },
+ level: {
+ kind: "scalar",
+ expression: "e.level",
+ includeWhen: "e.level IS NOT NULL AND length(e.level) > 0",
+ sort: "countDesc",
+ },
+ environment: {
+ kind: "scalar",
+ expression: "e.environment",
+ includeWhen: "e.environment IS NOT NULL AND length(e.environment) > 0",
+ sort: "countDesc",
+ },
+ promptName: {
+ kind: "scalar",
+ expression: "e.prompt_name",
+ includeWhen:
+ "e.type = 'GENERATION' AND e.prompt_name IS NOT NULL AND e.prompt_name != ''",
+ sort: "countDesc",
+ },
+ traceTags: {
+ kind: "array",
+ expression: "e.tags",
+ sort: "alpha",
+ distinct: true,
+ },
+ experimentDatasetId: {
+ kind: "scalar",
+ expression: "e.experiment_dataset_id",
+ includeWhen:
+ "e.experiment_dataset_id IS NOT NULL AND length(e.experiment_dataset_id) > 0",
+ sort: "countDesc",
+ },
+ experimentId: {
+ kind: "scalar",
+ expression: "e.experiment_id",
+ includeWhen: "e.experiment_id IS NOT NULL AND length(e.experiment_id) > 0",
+ sort: "countDesc",
+ },
+ experimentName: {
+ kind: "scalar",
+ expression: "e.experiment_name",
+ includeWhen:
+ "e.experiment_name IS NOT NULL AND length(e.experiment_name) > 0",
+ sort: "countDesc",
+ },
+ isRootObservation: {
+ kind: "boolean",
+ expression: eventsTableIsRootObservationSql,
+ sort: "booleanAsc",
+ },
+ hasParentObservation: {
+ kind: "boolean",
+ expression: eventsTableHasParentObservationSql,
+ sort: "booleanAsc",
+ },
+ toolNames: {
+ kind: "array",
+ expression: "mapKeys(e.tool_definitions)",
+ sort: "countDesc",
+ },
+ calledToolNames: {
+ kind: "array",
+ expression: "e.tool_call_names",
+ sort: "countDesc",
+ },
+} satisfies Record<string, EventFilterOptionDefinition>;
+
+export type EventFilterOptionColumn =
+ keyof typeof EVENTS_FILTER_OPTION_DEFINITIONS;
+
+export type EventFilterOptionRow = {
+ column: EventFilterOptionColumn;
+ value: string;
+ count: number;
+};
+
+export type EventFilterOptionScope = "scoredTraces";
+
+const EVENTS_FILTER_OPTION_COLUMN_IDENTIFIER_PATTERN = /^[A-Za-z]+$/;
+
+const assertEventFilterOptionColumnSet = <T extends Record<string, unknown>>(
+ definitions: T,
+): ReadonlySet<Extract<keyof T, string>> => {
+ const columns = Object.keys(definitions) as Array<Extract<keyof T, string>>;
+ const invalidColumn = columns.find(
+ (column) => !EVENTS_FILTER_OPTION_COLUMN_IDENTIFIER_PATTERN.test(column),
+ );
+
+ if (invalidColumn) {
+ throw new Error(
+ `Invalid events filter option column identifier: ${invalidColumn}`,
+ );
+ }
+
+ return new Set(columns);
+};
+
+const EVENTS_FILTER_OPTION_COLUMN_SET = assertEventFilterOptionColumnSet(
+ EVENTS_FILTER_OPTION_DEFINITIONS,
+);
+
+const isEventFilterOptionColumn = (
+ column: unknown,
+): column is EventFilterOptionColumn =>
+ typeof column === "string" &&
+ EVENTS_FILTER_OPTION_COLUMN_SET.has(column as EventFilterOptionColumn);
+
+export const normalizeEventFilterOptionColumn = (
+ column: unknown,
+): EventFilterOptionColumn => {
+ if (!isEventFilterOptionColumn(column)) {
+ throw new InvalidRequestError(
+ `Unsupported events filter option column: ${String(column)}`,
+ );
+ }
+
+ return column;
+};
+
+const uniqueEventFilterOptionColumns = (
+ columns: readonly EventFilterOptionColumn[],
+) => Array.from(new Set(columns.map(normalizeEventFilterOptionColumn)));
+
+const eventFilterOptionColumnSqlLiteral = (column: EventFilterOptionColumn) =>
+ `'${column}'`;
+
+const stringValueExpression = (expression: string) =>
+ `toString(ifNull(${expression}, ''))`;
+
+const optionValuesArrayExpression = (
+ column: EventFilterOptionColumn,
+): string => {
+ const definition = EVENTS_FILTER_OPTION_DEFINITIONS[column];
+
+ if (definition.kind === "scalar") {
+ return `if(${definition.includeWhen}, [${stringValueExpression(definition.expression)}], CAST([], 'Array(String)'))`;
+ }
+
+ if (definition.kind === "boolean") {
+ return `[if(${definition.expression}, 'true', 'false')]`;
+ }
+
+ const valuesExpression =
+ "distinct" in definition && definition.distinct
+ ? `arrayDistinct(${definition.expression})`
+ : definition.expression;
+
+ return `arrayMap(value -> toString(value), arrayFilter(value -> length(toString(value)) > 0, ${valuesExpression}))`;
+};
+
+const optionPresenceCondition = (column: EventFilterOptionColumn): string => {
+ const definition = EVENTS_FILTER_OPTION_DEFINITIONS[column];
+
+ if (definition.kind === "scalar") {
+ return definition.includeWhen;
+ }
+
+ if (definition.kind === "boolean") {
+ return "1";
+ }
+
+ return `length(${definition.expression}) > 0`;
+};
+
+const singleColumnOrderBy = (column: EventFilterOptionColumn): string => {
+ const definition = EVENTS_FILTER_OPTION_DEFINITIONS[column];
+
+ if (definition.sort === "countDesc") {
+ return "ORDER BY count() DESC, value ASC";
+ }
+
+ return "ORDER BY value ASC";
+};
+
+const optionTopAlias = (column: EventFilterOptionColumn) =>
+ `${column}TopOptions`;
+
+const optionTopKSelectExpression = (column: EventFilterOptionColumn) => {
+ const definition = EVENTS_FILTER_OPTION_DEFINITIONS[column];
+
+ if (definition.kind === "scalar") {
+ return `approx_top_kIf({optionLimit: UInt64})(${stringValueExpression(definition.expression)}, ${definition.includeWhen}) AS ${optionTopAlias(column)}`;
+ }
+
+ if (definition.kind === "boolean") {
+ return `arrayFilter(option -> tupleElement(option, 2) > 0, [tuple('false', countIf(NOT (${definition.expression})), toUInt64(0)), tuple('true', countIf(${definition.expression}), toUInt64(0))]) AS ${optionTopAlias(column)}`;
+ }
+
+ return `approx_top_kArray({optionLimit: UInt64})(${optionValuesArrayExpression(column)}) AS ${optionTopAlias(column)}`;
+};
+
+const optionRowsArrayExpression = (column: EventFilterOptionColumn) => {
+ const definition = EVENTS_FILTER_OPTION_DEFINITIONS[column];
+ const topAlias = optionTopAlias(column);
+ // Alpha facets use a constant sort key; the final ORDER BY value tie-breaker
+ // below provides alphabetical ordering within the top-k candidate set.
+ const sortKeyExpression =
+ definition.sort === "countDesc"
+ ? "-toInt64(tupleElement(option, 2))"
+ : definition.sort === "booleanAsc"
+ ? "if(tupleElement(option, 1) = 'true', toInt64(1), toInt64(0))"
+ : "toInt64(0)";
+
+ return `arrayMap(option -> tuple(${eventFilterOptionColumnSqlLiteral(column)}, tupleElement(option, 1), tupleElement(option, 2), ${sortKeyExpression}), ${topAlias})`;
+};
+
+const eventFilterOptionScopeCondition = (
+ scope: EventFilterOptionScope,
+): string => {
+ switch (scope) {
+ case "scoredTraces":
+ return "e.trace_id IN (SELECT DISTINCT trace_id FROM scores WHERE project_id = {projectId: String})";
+ }
+};
+
+export const buildEventsFilterOptionColumnQuery = (params: {
+ projectId: string;
+ filter: FilterState;
+ column: EventFilterOptionColumn;
+ limit: number;
+ offset?: number;
+ scope?: EventFilterOptionScope;
+}): { query: string; params: Record<string, unknown> } | null => {
+ if (params.limit <= 0) {
+ return null;
+ }
+
+ const column = normalizeEventFilterOptionColumn(params.column);
+ const definition = EVENTS_FILTER_OPTION_DEFINITIONS[column];
+ const eventsFilter = new FilterList(
+ createFilterFromFilterState(
+ params.filter,
+ eventsTableUiColumnDefinitions,
+ eventsTableCols,
+ ),
+ );
+
+ const valueExpression =
+ definition.kind === "scalar"
+ ? `toString(${definition.expression})`
+ : definition.kind === "boolean"
+ ? `if(${definition.expression}, 'true', 'false')`
+ : `arrayJoin(${optionValuesArrayExpression(column)})`;
+
+ const queryBuilder = new EventsAggQueryBuilder({
+ projectId: params.projectId,
+ groupByColumn: "value",
+ selectExpression: `${eventFilterOptionColumnSqlLiteral(column)} AS column, ${valueExpression} AS value, count() AS count`,
+ })
+ .where(eventsFilter.apply())
+ .whereRaw(optionPresenceCondition(column))
+ .orderBy(singleColumnOrderBy(column))
+ .limit(params.limit, params.offset ?? 0);
+
+ if (params.scope) {
+ queryBuilder.whereRaw(eventFilterOptionScopeCondition(params.scope));
+ }
+
+ return queryBuilder.buildWithParams();
+};
+
+export const buildEventsFilterOptionsForColumnsQuery = (params: {
+ projectId: string;
+ filter: FilterState;
+ columns: readonly EventFilterOptionColumn[];
+ limit: number;
+ scope?: EventFilterOptionScope;
+}): { query: string; params: Record<string, unknown> } | null => {
+ const columns = uniqueEventFilterOptionColumns(params.columns);
+ if (columns.length === 0 || params.limit <= 0) {
+ return null;
+ }
+
+ const eventsFilter = new FilterList(
+ createFilterFromFilterState(
+ params.filter,
+ eventsTableUiColumnDefinitions,
+ eventsTableCols,
+ ),
+ );
+
+ const optionLimit = Math.min(params.limit, EVENTS_FILTER_OPTION_TOP_K_MAX_N);
+ const aggregatedOptionsBuilder = new EventsQueryBuilder({
+ projectId: params.projectId,
+ })
+ .selectRaw(...columns.map(optionTopKSelectExpression))
+ .where(eventsFilter.apply());
+
+ if (params.scope) {
+ aggregatedOptionsBuilder.whereRaw(
+ eventFilterOptionScopeCondition(params.scope),
+ );
+ }
+
+ const { query: aggregatedOptionsQuery, params: aggregatedOptionsParams } =
+ aggregatedOptionsBuilder.buildWithParams();
+
+ const query = `
+WITH aggregated_options AS (
+${aggregatedOptionsQuery}
+),
+option_rows AS (
+ SELECT
+ arrayJoin(arrayConcat(
+ ${columns.map(optionRowsArrayExpression).join(",\n ")}
+ )) AS option
+ FROM aggregated_options
+)
+SELECT
+ tupleElement(option, 1) AS column,
+ tupleElement(option, 2) AS value,
+ tupleElement(option, 3) AS count
+FROM option_rows
+ORDER BY column ASC, tupleElement(option, 4) ASC, tupleElement(option, 2) ASC
+`.trim();
+
+ return {
+ query,
+ params: {
+ ...aggregatedOptionsParams,
+ optionLimit,
+ },
+ };
+};
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index f6820dac71..36e46166df 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -67,6 +67,15 @@ export {
type SessionEventsMetricsRow,
type SplitQueryBuilder,
} from "./clickhouse-sql/event-query-builder";
+export {
+ buildEventsFilterOptionColumnQuery,
+ buildEventsFilterOptionsForColumnsQuery,
+ EVENTS_FILTER_OPTION_TOP_N,
+ normalizeEventFilterOptionColumn,
+ type EventFilterOptionRow,
+ type EventFilterOptionColumn,
+ type EventFilterOptionScope,
+} from "./clickhouse-sql/event-filter-options";
export {
eventsScoresAggregation,
eventsSessionsAggregation,
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index af9d618c25..3598ae53c8 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -104,11 +104,17 @@ import {
type SessionEventsMetricsRow,
OrderByEntry,
} from "../queries/clickhouse-sql/event-query-builder";
+import {
+ buildEventsFilterOptionColumnQuery,
+ buildEventsFilterOptionsForColumnsQuery,
+ EVENTS_FILTER_OPTION_TOP_N,
+ type EventFilterOptionRow,
+ type EventFilterOptionColumn,
+ type EventFilterOptionScope,
+} from "../queries/clickhouse-sql/event-filter-options";
import { type EventsObservationPublic } from "../queries/createGenerationsQuery";
import {
eventsTableCols,
- eventsTableHasParentObservationSql,
- eventsTableIsRootObservationSql,
type NumericEventsTableColumnId,
} from "../../eventsTable";
import {
@@ -1875,51 +1881,27 @@ export const updateEvents = async (
]);
};
-/**
- * Get grouped provided model names from events table
- * Used for filter options
- */
type GroupedEventsFilterOptions = {
- extraWhereRaw?: string;
limit?: number;
- offset?: number;
- orderBy?: string;
+ scope?: EventFilterOptionScope;
};
-export const getEventsGroupedByModel = async (
+type BuiltEventsFilterOptionColumnQuery = NonNullable<
+ ReturnType<typeof buildEventsFilterOptionColumnQuery>
+>;
+type BuiltEventsFilterOptionsForColumnsQuery = NonNullable<
+ ReturnType<typeof buildEventsFilterOptionsForColumnsQuery>
+>;
+
+const queryEventsFilterOptionRows = async (
projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
+ queryWithParams:
+ | BuiltEventsFilterOptionColumnQuery
+ | BuiltEventsFilterOptionsForColumnsQuery,
) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.provided_model_name",
- selectExpression: "e.provided_model_name as name, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw(
- "e.provided_model_name IS NOT NULL AND length(e.provided_model_name) > 0",
- )
- .orderBy(
- opts?.orderBy ?? "ORDER BY count() DESC, e.provided_model_name ASC",
- )
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ name: string; count: number }>({
- query,
- params,
+ return queryClickhouse<EventFilterOptionRow>({
+ query: queryWithParams.query,
+ params: queryWithParams.params,
tags: {
feature: "tracing",
type: "events",
@@ -1928,273 +1910,151 @@ export const getEventsGroupedByModel = async (
},
preferredClickhouseService: "EventsReadOnly",
});
- return res.map((r) => ({ model: r.name, count: r.count }));
};
-/**
- * Get grouped model IDs from events table
- * Used for filter options
- */
-export const getEventsGroupedByModelId = async (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
+const queryEventsFilterOptionsForColumns = async (params: {
+ projectId: string;
+ filter: FilterState;
+ columns: readonly EventFilterOptionColumn[];
+ limit: number;
+ scope?: EventFilterOptionScope;
+}) => {
+ const queryWithParams = buildEventsFilterOptionsForColumnsQuery({
+ projectId: params.projectId,
+ filter: params.filter,
+ columns: params.columns,
+ limit: params.limit,
+ scope: params.scope,
+ });
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.model_id",
- selectExpression: "e.model_id as modelId, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.model_id IS NOT NULL AND length(e.model_id) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.model_id ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
+ if (!queryWithParams) {
+ return [];
+ }
- const { query, params } = queryBuilder.buildWithParams();
+ return queryEventsFilterOptionRows(params.projectId, queryWithParams);
+};
- const res = await queryClickhouse<{ modelId: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
+const queryEventsFilterOptionColumn = async (params: {
+ projectId: string;
+ filter: FilterState;
+ column: EventFilterOptionColumn;
+ limit: number;
+ offset?: number;
+ scope?: EventFilterOptionScope;
+}) => {
+ const queryWithParams = buildEventsFilterOptionColumnQuery({
+ projectId: params.projectId,
+ filter: params.filter,
+ column: params.column,
+ limit: params.limit,
+ offset: params.offset,
+ scope: params.scope,
});
- return res.map((r) => ({ modelId: r.modelId, count: r.count }));
+
+ if (!queryWithParams) {
+ return [];
+ }
+
+ return queryEventsFilterOptionRows(params.projectId, queryWithParams);
};
-/**
- * Get grouped observation names from events table
- * Used for filter options
- */
-export const getEventsGroupedByName = async (
+export const getEventsFilterOptionsForColumns = async (params: {
+ projectId: string;
+ filter: FilterState;
+ columns: readonly EventFilterOptionColumn[];
+ topN?: number;
+ scope?: EventFilterOptionScope;
+}) =>
+ queryEventsFilterOptionsForColumns({
+ ...params,
+ limit: params.topN ?? EVENTS_FILTER_OPTION_TOP_N,
+ });
+
+export const getEventsFilterOptionValuesPage = async (params: {
+ projectId: string;
+ filter: FilterState;
+ column: EventFilterOptionColumn;
+ limit: number;
+ offset: number;
+}) =>
+ queryEventsFilterOptionColumn({
+ projectId: params.projectId,
+ filter: params.filter,
+ column: params.column,
+ limit: params.limit,
+ offset: params.offset,
+ });
+
+const getSingleEventsFilterOptionColumn = async (
projectId: string,
filter: FilterState,
+ column: EventFilterOptionColumn,
opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
+) =>
+ queryEventsFilterOptionColumn({
projectId,
- groupByColumn: "e.name",
- selectExpression: "e.name as name, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.name IS NOT NULL AND length(e.name) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.name ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ name: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
+ filter,
+ column,
+ limit: opts?.limit ?? EVENTS_FILTER_OPTION_TOP_N,
+ scope: opts?.scope,
});
- return res;
-};
-/**
- * Get grouped trace names from events table
- * Used for filter options
- */
export const getEventsGroupedByTraceName = async (
projectId: string,
filter: FilterState,
opts?: GroupedEventsFilterOptions,
) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
+ const rows = await getSingleEventsFilterOptionColumn(
projectId,
- groupByColumn: "e.trace_name",
- selectExpression: "e.trace_name as traceName, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.trace_name IS NOT NULL AND length(e.trace_name) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.trace_name ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- if (opts?.extraWhereRaw) queryBuilder.whereRaw(opts.extraWhereRaw);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ traceName: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
+ filter,
+ "traceName",
+ opts,
+ );
+ return rows.map((row) => ({ traceName: row.value, count: row.count }));
};
-/**
- * Get grouped trace tags from events table
- * Used for filter options
- *
- * NOTE:
- * - arrayJoin() explodes arrays into rows, requiring DISTINCT (not GROUP BY)
- * - EventsAggQueryBuilder always emits GROUP BY, which changes semantics
- * - We want unique tag values, not tag occurrence counts
- * We therefore compose a row-level events query via EventsQueryBuilder and
- * run arrayJoin() in an outer CTE query.
- */
export const getEventsGroupedByTraceTags = async (
projectId: string,
filter: FilterState,
- // We do not support counts for tags so changing the orderBy does not make sense. Therefore, we omit orderBy from options.
- opts?: Pick<GroupedEventsFilterOptions, "extraWhereRaw" | "limit" | "offset">,
+ opts?: GroupedEventsFilterOptions,
) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const filteredEventsBuilder = new EventsQueryBuilder({ projectId })
- .selectRaw("e.tags AS tags")
- .where(appliedEventsFilter)
- .whereRaw("e.is_deleted = 0")
- .whereRaw("notEmpty(e.tags)");
-
- if (opts?.extraWhereRaw) filteredEventsBuilder.whereRaw(opts.extraWhereRaw);
-
- const { query: filteredEventsQuery, params: filteredEventsParams } =
- filteredEventsBuilder.buildWithParams();
-
- const tagsQueryBuilder = new CTEQueryBuilder()
- .withCTE("filtered_events", {
- query: filteredEventsQuery,
- params: filteredEventsParams,
- schema: ["tags"],
- })
- .from("filtered_events", "fe")
- .select("DISTINCT arrayJoin(fe.tags) AS tag")
- .orderBy("ORDER BY tag ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = tagsQueryBuilder.buildWithParams();
-
- return measureAndReturn({
- operationName: "getEventsGroupedByTraceTags",
+ const rows = await getSingleEventsFilterOptionColumn(
projectId,
- input: { params },
- fn: async (input) => {
- return queryClickhouse<{ tag: string }>({
- query,
- params: input.params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- },
- });
+ filter,
+ "traceTags",
+ opts,
+ );
+ return rows.map((row) => ({ tag: row.value }));
};
-/**
- * Get grouped prompt names from events table
- * Used for filter options
- */
-export const getEventsGroupedByPromptName = async (
+export const getEventsGroupedByUserId = async (
projectId: string,
filter: FilterState,
opts?: GroupedEventsFilterOptions,
) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
+ const rows = await getSingleEventsFilterOptionColumn(
projectId,
- groupByColumn: "e.prompt_name",
- selectExpression: "e.prompt_name as promptName, count() as count",
- })
- .whereRaw("e.type = 'GENERATION'")
- .whereRaw("e.prompt_name IS NOT NULL AND e.prompt_name != ''")
- .where(appliedEventsFilter)
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.prompt_name ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ promptName: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
-
- return res.filter((r) => Boolean(r.promptName));
+ filter,
+ "userId",
+ opts,
+ );
+ return rows.map((row) => ({ userId: row.value, count: row.count }));
};
-/**
- * Get grouped observation types from events table
- * Used for filter options
- */
-export const getEventsGroupedByType = async (
+export const getEventsNumericStatsByFilterColumn = async (
projectId: string,
filter: FilterState,
- opts?: GroupedEventsFilterOptions,
+ columnId: Exclude<
+ NumericEventsTableColumnId,
+ "inputTokens" | "outputTokens" | "inputCost" | "outputCost"
+ >,
) => {
+ const column = eventsTableCols.find((col) => col.id === columnId);
+
+ if (!column || column.type !== "number") {
+ throw new Error(`Column ${columnId} is not supported for numeric stats`);
+ }
+
const eventsFilter = new FilterList(
createFilterFromFilterState(
filter,
@@ -2203,21 +2063,25 @@ export const getEventsGroupedByType = async (
),
);
+ const valueExpression = column.internal;
const appliedEventsFilter = eventsFilter.apply();
const queryBuilder = new EventsAggQueryBuilder({
projectId,
- groupByColumn: "e.type",
- selectExpression: "e.type as type, count() as count",
+ groupByColumn: "tuple()",
+ selectExpression: `min(${valueExpression}) as min, max(${valueExpression}) as max, avg(${valueExpression}) as avg, count(${valueExpression}) as count`,
})
.where(appliedEventsFilter)
- .whereRaw("e.type IS NOT NULL AND length(e.type) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.type ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
+ .whereRaw(`isNotNull(${valueExpression})`);
const { query, params } = queryBuilder.buildWithParams();
- const res = await queryClickhouse<{ type: string; count: number }>({
+ const res = await queryClickhouse<{
+ min: number | null;
+ max: number | null;
+ avg: number | null;
+ count: number;
+ }>({
query,
params,
tags: {
@@ -2228,624 +2092,33 @@ export const getEventsGroupedByType = async (
},
preferredClickhouseService: "EventsReadOnly",
});
- return res;
+ const range = res[0];
+
+ if (
+ !range ||
+ range.min === null ||
+ range.max === null ||
+ range.avg === null
+ ) {
+ return null;
+ }
+
+ return range;
};
-/**
- * Get grouped user IDs from events table (joined with traces)
- * Used for filter options
- */
-export const getEventsGroupedByUserId = async (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- // We mainly use queries like this to retrieve filter options.
- // Therefore, we can skip final as some inaccuracy in count is acceptable.
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.user_id",
- selectExpression: "e.user_id as userId, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.user_id IS NOT NULL AND length(e.user_id) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.user_id ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- if (opts?.extraWhereRaw) queryBuilder.whereRaw(opts.extraWhereRaw);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ userId: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped versions from events table
- * Used for filter options
- */
-export const getEventsGroupedByVersion = async (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- // We mainly use queries like this to retrieve filter options.
- // Therefore, we can skip final as some inaccuracy in count is acceptable.
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.version",
- selectExpression: "e.version as version, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.version IS NOT NULL AND length(e.version) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.version ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ version: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-export const getEventsNumericStatsByFilterColumn = async (
- projectId: string,
- filter: FilterState,
- columnId: Exclude<
- NumericEventsTableColumnId,
- "inputTokens" | "outputTokens" | "inputCost" | "outputCost"
- >,
-) => {
- const column = eventsTableCols.find((col) => col.id === columnId);
-
- if (!column || column.type !== "number") {
- throw new Error(`Column ${columnId} is not supported for numeric stats`);
- }
-
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const valueExpression = column.internal;
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "tuple()",
- selectExpression: `min(${valueExpression}) as min, max(${valueExpression}) as max, avg(${valueExpression}) as avg, count(${valueExpression}) as count`,
- })
- .where(appliedEventsFilter)
- .whereRaw(`isNotNull(${valueExpression})`);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{
- min: number | null;
- max: number | null;
- avg: number | null;
- count: number;
- }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- const range = res[0];
-
- if (
- !range ||
- range.min === null ||
- range.max === null ||
- range.avg === null
- ) {
- return null;
- }
-
- return range;
-};
-
-/**
- * Get grouped session IDs from events table (joined with traces)
- * Used for filter options
- */
-export const getEventsGroupedBySessionId = async (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- // We mainly use queries like this to retrieve filter options.
- // Therefore, we can skip final as some inaccuracy in count is acceptable.
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.session_id",
- selectExpression: "e.session_id as sessionId, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.session_id IS NOT NULL AND length(e.session_id) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.session_id ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ sessionId: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped levels from events table
- * Used for filter options
- */
-export const getEventsGroupedByLevel = async (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- // We mainly use queries like this to retrieve filter options.
- // Therefore, we can skip final as some inaccuracy in count is acceptable.
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.level",
- selectExpression: "e.level as level, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.level IS NOT NULL AND length(e.level) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.level ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ level: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped environments from events table
- * Used for filter options
- */
-export const getEventsGroupedByEnvironment = async (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- // We mainly use queries like this to retrieve filter options.
- // Therefore, we can skip final as some inaccuracy in count is acceptable.
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.environment",
- selectExpression: "e.environment as environment, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.environment IS NOT NULL AND length(e.environment) > 0")
- .orderBy(opts?.orderBy ?? "ORDER BY count() DESC, e.environment ASC")
- .limit(opts?.limit ?? 1000, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ environment: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped experiment dataset IDs from events table
- * Used for filter options
- */
export const getEventsGroupedByExperimentDatasetId = async (
projectId: string,
filter: FilterState,
) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.experiment_dataset_id",
- selectExpression:
- "e.experiment_dataset_id as experimentDatasetId, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw(
- "e.experiment_dataset_id IS NOT NULL AND length(e.experiment_dataset_id) > 0",
- )
- .orderBy("ORDER BY count() DESC, e.experiment_dataset_id ASC")
- .limit(1000, 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{
- experimentDatasetId: string;
- count: number;
- }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped experiment IDs from events table
- * Used for filter options
- */
-export const getEventsGroupedByExperimentId = async (
- projectId: string,
- filter: FilterState,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.experiment_id",
- selectExpression: "e.experiment_id as experimentId, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.experiment_id IS NOT NULL AND length(e.experiment_id) > 0")
- .orderBy("ORDER BY count() DESC, e.experiment_id ASC")
- .limit(1000, 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ experimentId: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped experiment names from events table
- * Used for filter options
- */
-export const getEventsGroupedByExperimentName = async (
- projectId: string,
- filter: FilterState,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "e.experiment_name",
- selectExpression: "e.experiment_name as experimentName, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("e.experiment_name IS NOT NULL AND length(e.experiment_name) > 0")
- .orderBy("ORDER BY count() DESC, e.experiment_name ASC")
- .limit(1000, 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ experimentName: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped literal parent-pointer boolean from events table.
- */
-export const getEventsGroupedByHasParentObservation = async (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: eventsTableHasParentObservationSql,
- selectExpression: `${eventsTableHasParentObservationSql} as hasParentObservation, count() as count`,
- })
- .where(appliedEventsFilter)
- .orderBy(opts?.orderBy ?? "ORDER BY hasParentObservation ASC")
- .limit(opts?.limit ?? 2, opts?.offset ?? 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- return queryClickhouse<{ hasParentObservation: boolean; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
-};
-
-/**
- * Get grouped root observation boolean from events table.
- * Used for filter options for the "Is Root Observation" facet.
- */
-export const getEventsGroupedByIsRootObservation = async (
- projectId: string,
- filter: FilterState,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
+ const rows = await getSingleEventsFilterOptionColumn(
projectId,
- groupByColumn: eventsTableIsRootObservationSql,
- selectExpression: `${eventsTableIsRootObservationSql} as isRootObservation, count() as count`,
- })
- .where(appliedEventsFilter)
- .orderBy("ORDER BY isRootObservation ASC")
- .limit(2, 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- return queryClickhouse<{ isRootObservation: boolean; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
-};
-
-/**
- * Get grouped available tool names from events table
- * Used for filter options
- */
-export const getEventsGroupedByToolName = async (
- projectId: string,
- filter: FilterState,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "arrayJoin(mapKeys(e.tool_definitions))",
- selectExpression:
- "arrayJoin(mapKeys(e.tool_definitions)) as toolName, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("length(mapKeys(e.tool_definitions)) > 0")
- .orderBy("ORDER BY count() DESC, toolName ASC")
- .limit(1000, 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{ toolName: string; count: number }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
-};
-
-/**
- * Get grouped called tool names from events table
- * Used for filter options
- */
-export const getEventsGroupedByCalledToolName = async (
- projectId: string,
- filter: FilterState,
-) => {
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filter,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
+ filter,
+ "experimentDatasetId",
);
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const queryBuilder = new EventsAggQueryBuilder({
- projectId,
- groupByColumn: "arrayJoin(e.tool_call_names)",
- selectExpression:
- "arrayJoin(e.tool_call_names) as calledToolName, count() as count",
- })
- .where(appliedEventsFilter)
- .whereRaw("length(e.tool_call_names) > 0")
- .orderBy("ORDER BY count() DESC, calledToolName ASC")
- .limit(1000, 0);
-
- const { query, params } = queryBuilder.buildWithParams();
-
- const res = await queryClickhouse<{
- calledToolName: string;
- count: number;
- }>({
- query,
- params,
- tags: {
- feature: "tracing",
- type: "events",
- kind: "analytic",
- projectId,
- },
- preferredClickhouseService: "EventsReadOnly",
- });
- return res;
+ return rows.map((row) => ({
+ experimentDatasetId: row.value,
+ count: row.count,
+ }));
};
/**
@@ -3135,7 +2408,7 @@ export const getObservationsBatchIOFromEventsTable = async <
: `e.output as output`;
const experimentFieldsSelect = opts.includeExperimentFields
? `
- experiment_item_expected_output,
+ experiment_item_expected_output,
mapFromArrays(arrayReverse(e.experiment_item_metadata_names), arrayReverse(e.experiment_item_metadata_values)) as experiment_item_metadata,
`
: "";
diff --git a/web/src/__tests__/server/event-query-builder.servertest.ts b/web/src/__tests__/server/event-query-builder.servertest.ts
index aa4d5fb9ae..06dd70c5ee 100644
--- a/web/src/__tests__/server/event-query-builder.servertest.ts
+++ b/web/src/__tests__/server/event-query-builder.servertest.ts
@@ -1,9 +1,228 @@
import {
+ buildEventsFilterOptionColumnQuery,
+ buildEventsFilterOptionsForColumnsQuery,
CTEQueryBuilder,
EventsAggregationQueryBuilder,
EventsQueryBuilder,
} from "@langfuse/shared/src/server";
+describe("buildEventsFilterOptionsForColumnsQuery", () => {
+ it("builds one events_core scan for multiple filter option columns", () => {
+ const built = buildEventsFilterOptionsForColumnsQuery({
+ projectId: "test-project",
+ filter: [],
+ columns: ["name", "traceTags", "isRootObservation"],
+ limit: 1000,
+ });
+
+ expect(built).not.toBeNull();
+ if (!built) throw new Error("expected query");
+
+ expect(built.query.match(/FROM events_core e/g)).toHaveLength(1);
+ expect(built.query).toContain("e.project_id = {projectId: String}");
+ expect(built.query).toContain("approx_top_kIf");
+ expect(built.query).toContain("approx_top_kArray");
+ expect(built.query).toContain("countIf");
+ expect(built.query).toContain("arrayJoin(arrayConcat");
+ expect(built.query).toContain("tuple('name'");
+ expect(built.query).toContain("tuple('traceTags'");
+ expect(built.query).toContain("tuple('isRootObservation'");
+ expect(built.query).not.toContain("FINAL");
+ expect(built.query).not.toMatch(/\bJOIN\b/i);
+ expect(built.query).not.toContain("row_number()");
+ expect(built.query).not.toContain("LIMIT {optionLimit: Int32} BY");
+ expect(built.query).not.toContain("GROUP BY column");
+ expect(built.query).not.toContain("top_options");
+ expect(built.query).not.toContain("arrayEnumerate");
+ expect(built.params).toMatchObject({
+ projectId: "test-project",
+ optionLimit: 1000,
+ });
+ expect(built.params).not.toHaveProperty("optionReserved");
+ });
+
+ it("orders bulk filter option rows by per-column sort key and value", () => {
+ const built = buildEventsFilterOptionsForColumnsQuery({
+ projectId: "test-project",
+ filter: [],
+ columns: ["name", "traceTags", "isRootObservation"],
+ limit: 1000,
+ });
+
+ expect(built).not.toBeNull();
+ if (!built) throw new Error("expected query");
+
+ expect(built.query).toContain(
+ "tuple('name', tupleElement(option, 1), tupleElement(option, 2), -toInt64(tupleElement(option, 2)))",
+ );
+ expect(built.query).toContain(
+ "tuple('traceTags', tupleElement(option, 1), tupleElement(option, 2), toInt64(0))",
+ );
+ expect(built.query).toContain(
+ "tuple('isRootObservation', tupleElement(option, 1), tupleElement(option, 2), if(tupleElement(option, 1) = 'true', toInt64(1), toInt64(0)))",
+ );
+ expect(built.query).toContain(
+ "ORDER BY column ASC, tupleElement(option, 4) ASC, tupleElement(option, 2) ASC",
+ );
+ });
+
+ it("applies events filters to the single base scan", () => {
+ const built = buildEventsFilterOptionsForColumnsQuery({
+ projectId: "test-project",
+ filter: [
+ {
+ column: "startTime",
+ operator: ">=",
+ value: new Date("2026-01-01T00:00:00.000Z"),
+ type: "datetime",
+ },
+ ],
+ columns: ["name"],
+ limit: 10,
+ });
+
+ expect(built).not.toBeNull();
+ if (!built) throw new Error("expected query");
+
+ expect(built.query.match(/FROM events_core e/g)).toHaveLength(1);
+ expect(built.query).toContain("start_time");
+ expect(built.query).toContain("approx_top_kIf");
+ expect(built.query).not.toContain("LIMIT {optionLimit: Int32} BY");
+ expect(built.params).toMatchObject({
+ projectId: "test-project",
+ optionLimit: 10,
+ });
+ expect(built.params).not.toHaveProperty("optionReserved");
+ });
+
+ it("applies the scored traces scope without caller-provided raw SQL", () => {
+ const built = buildEventsFilterOptionColumnQuery({
+ projectId: "test-project",
+ filter: [],
+ column: "traceName",
+ limit: 100,
+ scope: "scoredTraces",
+ });
+
+ expect(built).not.toBeNull();
+ if (!built) throw new Error("expected query");
+
+ expect(built.query).toContain(
+ "e.trace_id IN (SELECT DISTINCT trace_id FROM scores WHERE project_id = {projectId: String})",
+ );
+ expect(built.query).toContain("GROUP BY value");
+ expect(built.params).toMatchObject({
+ projectId: "test-project",
+ limit: 100,
+ });
+ });
+
+ it("builds a direct grouped query for one scalar filter option column", () => {
+ const built = buildEventsFilterOptionColumnQuery({
+ projectId: "test-project",
+ filter: [
+ {
+ column: "startTime",
+ operator: ">=",
+ value: new Date("2026-01-01T00:00:00.000Z"),
+ type: "datetime",
+ },
+ ],
+ column: "level",
+ limit: 10,
+ offset: 20,
+ });
+
+ expect(built).not.toBeNull();
+ if (!built) throw new Error("expected query");
+
+ expect(built.query.match(/FROM events_core e/g)).toHaveLength(1);
+ expect(built.query).toContain("'level' AS column");
+ expect(built.query).toContain("toString(e.level) AS value");
+ expect(built.query).toContain("e.level IS NOT NULL");
+ expect(built.query).toContain("GROUP BY value");
+ expect(built.query).not.toContain("GROUP BY e.level");
+ expect(built.query).toContain("ORDER BY count() DESC, value ASC");
+ expect(built.query).toContain(
+ "LIMIT {limit: Int32} OFFSET {offset: Int32}",
+ );
+ expect(built.query).not.toContain("arrayJoin(arrayConcat");
+ expect(built.query).not.toContain("row_number()");
+ expect(built.params).toMatchObject({
+ projectId: "test-project",
+ limit: 10,
+ offset: 20,
+ });
+ });
+
+ it("builds a direct grouped query for one boolean filter option column", () => {
+ const built = buildEventsFilterOptionColumnQuery({
+ projectId: "test-project",
+ filter: [],
+ column: "isRootObservation",
+ limit: 2,
+ });
+
+ expect(built).not.toBeNull();
+ if (!built) throw new Error("expected query");
+
+ expect(built.query.match(/FROM events_core e/g)).toHaveLength(1);
+ expect(built.query).toContain("'isRootObservation' AS column");
+ expect(built.query).toContain("AS value");
+ expect(built.query).toContain("GROUP BY value");
+ expect(built.query).not.toContain("GROUP BY if(");
+ expect(built.query).toContain("ORDER BY value ASC");
+ expect(built.params).toMatchObject({
+ projectId: "test-project",
+ limit: 2,
+ });
+ });
+
+ it("builds a direct grouped query for one array filter option column", () => {
+ const built = buildEventsFilterOptionColumnQuery({
+ projectId: "test-project",
+ filter: [],
+ column: "traceTags",
+ limit: 10,
+ });
+
+ expect(built).not.toBeNull();
+ if (!built) throw new Error("expected query");
+
+ expect(built.query.match(/FROM events_core e/g)).toHaveLength(1);
+ expect(built.query).toContain("'traceTags' AS column");
+ expect(built.query).toContain("arrayJoin(arrayMap(");
+ expect(built.query).toContain("length(e.tags) > 0");
+ expect(built.query).toContain("GROUP BY value");
+ expect(built.query).not.toContain("GROUP BY arrayJoin");
+ expect(built.query).toContain("ORDER BY value ASC");
+ expect(built.params).toMatchObject({
+ projectId: "test-project",
+ limit: 10,
+ });
+ });
+
+ it("rejects runtime values outside the filter option column registry", () => {
+ expect(() =>
+ buildEventsFilterOptionsForColumnsQuery({
+ projectId: "test-project",
+ filter: [],
+ columns: ["name'; SELECT 1; --"] as any,
+ limit: 1000,
+ }),
+ ).toThrow("Unsupported events filter option column");
+
+ expect(() =>
+ buildEventsFilterOptionColumnQuery({
+ projectId: "test-project",
+ filter: [],
+ column: "name'; SELECT 1; --" as any,
+ limit: 1000,
+ }),
+ ).toThrow("Unsupported events filter option column");
+ });
+});
+
describe("CTEQueryBuilder", () => {
it("should compose multiple CTEs with type-safe references", () => {
const tracesBuilder = new EventsAggregationQueryBuilder({
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index a1cd7a2411..730405a51b 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -12,6 +12,9 @@ import {
getObservationsBatchIOFromEventsTable,
getLatestSdkVersionInfoFromEvents,
getTracesIdentifierForSessionFromEvents,
+ getEventsFilterOptionsForColumns,
+ getEventsFilterOptionValuesPage,
+ type EventFilterOptionColumn,
} from "@langfuse/shared/src/server";
import {
getEventFilterNumericRange,
@@ -40,6 +43,12 @@ function idFilter(id: string): FilterCondition {
};
}
+const findFilterOption = (
+ rows: Awaited<ReturnType<typeof getEventsFilterOptionsForColumns>>,
+ column: EventFilterOptionColumn,
+ value: string,
+) => rows.find((row) => row.column === column && row.value === value);
+
describe("Clickhouse Events Repository Test", () => {
it("should kill redis connection", () => {
// we need at least one test case to avoid hanging
@@ -718,6 +727,193 @@ describe("Clickhouse Events Repository Test", () => {
});
});
+ maybe("events filter option repository helpers", () => {
+ it("executes the bulk filter option query for scalar, array, and boolean facets", async () => {
+ const uniqueProjectId = randomUUID();
+ const traceId = randomUUID();
+ const rootSpanId = randomUUID();
+ const childSpanId = randomUUID();
+ const otherRootSpanId = randomUUID();
+ const nowMicro = Date.now() * 1000;
+
+ await createEventsCh([
+ createEvent({
+ id: rootSpanId,
+ span_id: rootSpanId,
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ parent_span_id: "",
+ is_app_root: true,
+ type: "GENERATION",
+ name: "runtime-filter-alpha",
+ level: "WARNING",
+ tags: ["zeta", "alpha", "alpha"],
+ tool_definitions: { search: "{}", calculator: "{}" },
+ tool_call_names: ["search"],
+ start_time: nowMicro,
+ event_ts: nowMicro,
+ }),
+ createEvent({
+ id: childSpanId,
+ span_id: childSpanId,
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ parent_span_id: rootSpanId,
+ type: "SPAN",
+ name: "runtime-filter-beta",
+ level: "WARNING",
+ tags: ["beta"],
+ tool_definitions: { search: "{}" },
+ tool_call_names: ["lookup", "search"],
+ start_time: nowMicro + 1_000,
+ event_ts: nowMicro + 1_000,
+ }),
+ createEvent({
+ id: otherRootSpanId,
+ span_id: otherRootSpanId,
+ project_id: uniqueProjectId,
+ trace_id: randomUUID(),
+ parent_span_id: "",
+ is_app_root: true,
+ type: "GENERATION",
+ name: "runtime-filter-alpha",
+ level: "ERROR",
+ tags: ["alpha"],
+ tool_definitions: { lookup: "{}" },
+ tool_call_names: ["lookup"],
+ start_time: nowMicro + 2_000,
+ event_ts: nowMicro + 2_000,
+ }),
+ ]);
+
+ await waitForExpect(async () => {
+ const rows = await getEventsFilterOptionsForColumns({
+ projectId: uniqueProjectId,
+ filter: [],
+ columns: [
+ "name",
+ "level",
+ "traceTags",
+ "isRootObservation",
+ "hasParentObservation",
+ "toolNames",
+ "calledToolNames",
+ ],
+ topN: 20,
+ });
+
+ expect(Number(findFilterOption(rows, "level", "WARNING")?.count)).toBe(
+ 2,
+ );
+ expect(Number(findFilterOption(rows, "level", "ERROR")?.count)).toBe(1);
+ expect(
+ Number(findFilterOption(rows, "name", "runtime-filter-alpha")?.count),
+ ).toBe(2);
+ expect(
+ Number(findFilterOption(rows, "name", "runtime-filter-beta")?.count),
+ ).toBe(1);
+ expect(
+ Number(findFilterOption(rows, "traceTags", "alpha")?.count),
+ ).toBe(2);
+ expect(Number(findFilterOption(rows, "traceTags", "beta")?.count)).toBe(
+ 1,
+ );
+ expect(Number(findFilterOption(rows, "traceTags", "zeta")?.count)).toBe(
+ 1,
+ );
+ expect(
+ rows
+ .filter((row) => row.column === "traceTags")
+ .map((row) => row.value),
+ ).toEqual(["alpha", "beta", "zeta"]);
+ expect(
+ rows
+ .filter((row) => row.column === "isRootObservation")
+ .map((row) => row.value),
+ ).toEqual(["false", "true"]);
+ expect(
+ Number(findFilterOption(rows, "isRootObservation", "false")?.count),
+ ).toBe(1);
+ expect(
+ Number(findFilterOption(rows, "isRootObservation", "true")?.count),
+ ).toBe(2);
+ expect(
+ Number(
+ findFilterOption(rows, "hasParentObservation", "false")?.count,
+ ),
+ ).toBe(2);
+ expect(
+ Number(findFilterOption(rows, "hasParentObservation", "true")?.count),
+ ).toBe(1);
+ expect(
+ Number(findFilterOption(rows, "toolNames", "search")?.count),
+ ).toBe(2);
+ expect(
+ Number(findFilterOption(rows, "toolNames", "calculator")?.count),
+ ).toBe(1);
+ expect(
+ Number(findFilterOption(rows, "calledToolNames", "lookup")?.count),
+ ).toBe(2);
+ expect(
+ Number(findFilterOption(rows, "calledToolNames", "search")?.count),
+ ).toBe(2);
+ });
+ });
+
+ it("executes the exact single-column array filter option query with paging", async () => {
+ const uniqueProjectId = randomUUID();
+ const nowMicro = Date.now() * 1000;
+
+ await createEventsCh([
+ createEvent({
+ id: randomUUID(),
+ span_id: randomUUID(),
+ project_id: uniqueProjectId,
+ trace_id: randomUUID(),
+ type: "SPAN",
+ tags: ["gamma", "alpha", "alpha"],
+ start_time: nowMicro,
+ event_ts: nowMicro,
+ }),
+ createEvent({
+ id: randomUUID(),
+ span_id: randomUUID(),
+ project_id: uniqueProjectId,
+ trace_id: randomUUID(),
+ type: "SPAN",
+ tags: ["beta", "alpha"],
+ start_time: nowMicro + 1_000,
+ event_ts: nowMicro + 1_000,
+ }),
+ ]);
+
+ await waitForExpect(async () => {
+ const firstPage = await getEventsFilterOptionValuesPage({
+ projectId: uniqueProjectId,
+ filter: [],
+ column: "traceTags",
+ limit: 2,
+ offset: 0,
+ });
+
+ expect(firstPage.map((row) => row.value)).toEqual(["alpha", "beta"]);
+ expect(Number(firstPage[0]?.count)).toBe(2);
+ expect(Number(firstPage[1]?.count)).toBe(1);
+ });
+
+ const secondPage = await getEventsFilterOptionValuesPage({
+ projectId: uniqueProjectId,
+ filter: [],
+ column: "traceTags",
+ limit: 2,
+ offset: 2,
+ });
+
+ expect(secondPage.map((row) => row.value)).toEqual(["gamma"]);
+ expect(Number(secondPage[0]?.count)).toBe(1);
+ });
+ });
+
maybe("Filter Tests", () => {
describe("Timestamp Filters", () => {
it("should filter observations by start time with >= operator", async () => {
diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.ts
index 2bb3b0b6d3..3acfa670a3 100644
--- a/web/src/features/events/server/eventsService.ts
+++ b/web/src/features/events/server/eventsService.ts
@@ -9,26 +9,9 @@ import {
getObservationsCountFromEventsTable,
getObservationsWithModelDataFromEventsTable,
getCategoricalScoresGroupedByName,
- getEventsGroupedByModel,
- getEventsGroupedByModelId,
- getEventsGroupedByName,
- getEventsGroupedByTraceName,
- getEventsGroupedByTraceTags,
- getEventsGroupedByPromptName,
- getEventsGroupedByType,
- getEventsGroupedByUserId,
- getEventsGroupedByVersion,
+ getEventsFilterOptionsForColumns,
+ getEventsFilterOptionValuesPage,
getEventsNumericStatsByFilterColumn,
- getEventsGroupedBySessionId,
- getEventsGroupedByLevel,
- getEventsGroupedByEnvironment,
- getEventsGroupedByExperimentDatasetId,
- getEventsGroupedByExperimentId,
- getEventsGroupedByExperimentName,
- getEventsGroupedByHasParentObservation,
- getEventsGroupedByIsRootObservation,
- getEventsGroupedByToolName,
- getEventsGroupedByCalledToolName,
getNumericScoresGroupedByName,
getScoresGroupedByNameSourceType,
getObservationsBatchIOFromEventsTable,
@@ -36,6 +19,7 @@ import {
getScoresForTraces,
logger,
traceException,
+ type EventFilterOptionColumn,
} from "@langfuse/shared/src/server";
import { type timeFilter, type FilterState } from "@langfuse/shared";
import {
@@ -44,7 +28,6 @@ import {
windowToMs,
} from "@langfuse/shared/monitors";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
-import { assertUnreachable } from "@/src/utils/types";
type TimeFilter = z.infer<typeof timeFilter>;
@@ -95,12 +78,27 @@ type EventFilterValueOption = {
count?: number;
};
-type GroupedEventsFilterOptions = {
- extraWhereRaw?: string;
- limit?: number;
- offset?: number;
- orderBy?: string;
-};
+// Subset of event filter option columns returned by the bulk filter-options response.
+const EVENT_FILTER_OPTION_COLUMNS = [
+ "providedModelName",
+ "modelId",
+ "name",
+ "promptName",
+ "traceTags",
+ "traceName",
+ "type",
+ "userId",
+ "version",
+ "sessionId",
+ "level",
+ "environment",
+ "experimentDatasetId",
+ "experimentId",
+ "experimentName",
+ "isRootObservation",
+ "toolNames",
+ "calledToolNames",
+] as const satisfies readonly EventFilterOptionColumn[];
const OBSERVATIONS_TO_TRACE_INTERVAL_MS = 2 * 24 * 60 * 60 * 1000;
const SCORE_TO_TRACE_OBSERVATIONS_INTERVAL_MS = 60 * 60 * 1000;
@@ -353,17 +351,47 @@ export async function getEventCount(params: GetObservationsCountParams) {
return { totalCount };
}
-const toFilterValueOptions = <
- TKey extends string,
- TItem extends Record<TKey, string | null> & { count: number },
->(
- items: TItem[],
- key: TKey,
-) =>
- items.flatMap((item) => {
- const value = item[key];
- return value === null ? [] : [{ value, count: item.count }];
- });
+type EventFilterOptionRow = Awaited<
+ ReturnType<typeof getEventsFilterOptionsForColumns>
+>[number];
+
+const toFilterValueOptions = (
+ items: EventFilterOptionRow[],
+ column: EventFilterOptionColumn,
+): EventFilterValueOption[] =>
+ items
+ .filter((item) => item.column === column)
+ .map((item) => ({ value: item.value, count: item.count }));
+
+const EVENT_FILTER_VALUE_ONLY_COLUMNS = new Set<EventFilterOptionColumn>([
+ "traceTags",
+ "toolNames",
+ "calledToolNames",
+]);
+
+type EventFilterOptionsByColumn = Record<
+ (typeof EVENT_FILTER_OPTION_COLUMNS)[number],
+ EventFilterValueOption[]
+>;
+
+const toEventFilterValueOptions = (
+ items: EventFilterOptionRow[],
+ column: EventFilterOptionColumn,
+): EventFilterValueOption[] => {
+ const options = toFilterValueOptions(items, column);
+
+ return EVENT_FILTER_VALUE_ONLY_COLUMNS.has(column)
+ ? options.map(({ value }) => ({ value }))
+ : options;
+};
+
+const toEventFilterOptionsByColumn = (
+ items: EventFilterOptionRow[],
+): EventFilterOptionsByColumn =>
+ EVENT_FILTER_OPTION_COLUMNS.reduce((acc, column) => {
+ acc[column] = toEventFilterValueOptions(items, column);
+ return acc;
+ }, {} as EventFilterOptionsByColumn);
const getEventFilterOptionsScope = (
params: GetObservationsFilterOptionsParams,
@@ -454,126 +482,27 @@ export async function getEventFilterValuePage(
const { eventsFilter } = getEventFilterOptionsScope(scopedParams);
const queryLimit = limit + 1;
- const createResultFromGroupedQuery = async <T>(
- query: (
- projectId: string,
- filter: FilterState,
- opts?: GroupedEventsFilterOptions,
- ) => Promise<Array<T & { count?: number }>>,
- valueGetter: (item: T) => string,
- ) => {
- const values = await query(projectId, eventsFilter, {
- limit: queryLimit,
- offset,
- }).then((items) =>
- items.map(
- (item) =>
- ({
- value: valueGetter(item),
- count: item.count,
- }) satisfies EventFilterValueOption,
- ),
- );
-
- return {
- values: values.slice(0, limit),
- nextOffset: values.length > limit ? offset + limit : undefined,
- };
- };
-
- if (column === "hasParentObservation") {
- return createResultFromGroupedQuery(
- getEventsGroupedByHasParentObservation,
- (item) => (item.hasParentObservation ? "true" : "false"),
- );
- }
-
- if (column === "traceTags") {
- // Trace tags do not support counting right now
- return createResultFromGroupedQuery(
- getEventsGroupedByTraceTags,
- (item) => item.tag,
- );
- }
-
- if (column === "providedModelName") {
- return createResultFromGroupedQuery(
- getEventsGroupedByModel,
- (item) => item.model,
- );
- }
-
- if (column === "modelId") {
- return createResultFromGroupedQuery(
- getEventsGroupedByModelId,
- (item) => item.modelId,
- );
- }
-
- if (column === "name") {
- return createResultFromGroupedQuery(
- getEventsGroupedByName,
- (item) => item.name,
- );
- }
-
- if (column === "traceName") {
- return createResultFromGroupedQuery(
- getEventsGroupedByTraceName,
- (item) => item.traceName,
- );
- }
-
- if (column === "type") {
- return createResultFromGroupedQuery(
- getEventsGroupedByType,
- (item) => item.type,
- );
- }
-
- if (column === "userId") {
- return createResultFromGroupedQuery(
- getEventsGroupedByUserId,
- (item) => item.userId,
- );
- }
-
- if (column === "version") {
- return createResultFromGroupedQuery(
- getEventsGroupedByVersion,
- (item) => item.version,
- );
- }
-
- if (column === "sessionId") {
- return createResultFromGroupedQuery(
- getEventsGroupedBySessionId,
- (item) => item.sessionId,
- );
- }
-
- if (column === "level") {
- return createResultFromGroupedQuery(
- getEventsGroupedByLevel,
- (item) => item.level,
- );
- }
-
- if (column === "environment") {
- return createResultFromGroupedQuery(
- getEventsGroupedByEnvironment,
- (item) => item.environment,
- );
- }
+ const rows = await getEventsFilterOptionValuesPage({
+ projectId,
+ filter: eventsFilter,
+ column,
+ limit: queryLimit,
+ offset,
+ });
- if (column === "promptName") {
- return createResultFromGroupedQuery(
- getEventsGroupedByPromptName,
- (item) => item.promptName,
- );
- }
+ const values = rows.map((row) =>
+ column === "traceTags"
+ ? ({ value: row.value } satisfies EventFilterValueOption)
+ : ({
+ value: row.value,
+ count: row.count,
+ } satisfies EventFilterValueOption),
+ );
- return assertUnreachable(column);
+ return {
+ values: values.slice(0, limit),
+ nextOffset: values.length > limit ? offset + limit : undefined,
+ };
}
export async function getEventFilterNumericRange(
@@ -606,24 +535,7 @@ export async function getEventFilterOptions(
numericScoreNames,
categoricalScoreNames,
traceScoreColumns,
- providedModelName,
- name,
- promptNames,
- traceTags,
- traceNames,
- modelId,
- types,
- userIds,
- versions,
- sessionIds,
- levels,
- environments,
- experimentDatasetIds,
- experimentIds,
- experimentNames,
- isRootObservationResults,
- toolNames,
- calledToolNames,
+ eventFilterOptions,
] = await Promise.all([
getNumericScoresGroupedByName(projectId, traceTimestampFilters),
getCategoricalScoresGroupedByName(projectId, traceTimestampFilters),
@@ -631,24 +543,11 @@ export async function getEventFilterOptions(
projectId,
filter: [...TRACE_SCORE_SCOPE_FILTER, ...traceScoreTimestampFilters],
}),
- getEventsGroupedByModel(projectId, eventsFilter),
- getEventsGroupedByName(projectId, eventsFilter),
- getEventsGroupedByPromptName(projectId, eventsFilter),
- getEventsGroupedByTraceTags(projectId, eventsFilter),
- getEventsGroupedByTraceName(projectId, eventsFilter),
- getEventsGroupedByModelId(projectId, eventsFilter),
- getEventsGroupedByType(projectId, eventsFilter),
- getEventsGroupedByUserId(projectId, eventsFilter),
- getEventsGroupedByVersion(projectId, eventsFilter),
- getEventsGroupedBySessionId(projectId, eventsFilter),
- getEventsGroupedByLevel(projectId, eventsFilter),
- getEventsGroupedByEnvironment(projectId, eventsFilter),
- getEventsGroupedByExperimentDatasetId(projectId, eventsFilter),
- getEventsGroupedByExperimentId(projectId, eventsFilter),
- getEventsGroupedByExperimentName(projectId, eventsFilter),
- getEventsGroupedByIsRootObservation(projectId, eventsFilter),
- getEventsGroupedByToolName(projectId, eventsFilter),
- getEventsGroupedByCalledToolName(projectId, eventsFilter),
+ getEventsFilterOptionsForColumns({
+ projectId,
+ filter: eventsFilter,
+ columns: EVENT_FILTER_OPTION_COLUMNS,
+ }),
]);
const traceNumericScoreNames = Array.from(
new Set(
@@ -665,47 +564,17 @@ export async function getEventFilterOptions(
.filter((score) => score.dataType === "CATEGORICAL")
.map((score) => score.name),
);
+ const eventFilterOptionsByColumn =
+ toEventFilterOptionsByColumn(eventFilterOptions);
return {
- providedModelName: toFilterValueOptions(providedModelName, "model"),
- modelId: toFilterValueOptions(modelId, "modelId"),
- name: toFilterValueOptions(name, "name"),
+ ...eventFilterOptionsByColumn,
scores_avg: numericScoreNames.map((score) => score.name),
score_categories: categoricalScoreNames,
trace_scores_avg: traceNumericScoreNames,
trace_score_categories: categoricalScoreNames.filter((score) =>
traceCategoricalScoreNames.has(score.label),
),
- promptName: toFilterValueOptions(promptNames, "promptName"),
- traceTags: traceTags
- .filter((i) => i.tag !== null)
- .map((i) => ({
- value: i.tag,
- })),
- traceName: toFilterValueOptions(traceNames, "traceName"),
- type: toFilterValueOptions(types, "type"),
- userId: toFilterValueOptions(userIds, "userId"),
- version: toFilterValueOptions(versions, "version"),
- sessionId: toFilterValueOptions(sessionIds, "sessionId"),
- level: toFilterValueOptions(levels, "level"),
- environment: toFilterValueOptions(environments, "environment"),
- experimentDatasetId: toFilterValueOptions(
- experimentDatasetIds,
- "experimentDatasetId",
- ),
- experimentId: toFilterValueOptions(experimentIds, "experimentId"),
- experimentName: toFilterValueOptions(experimentNames, "experimentName"),
- isRootObservation: isRootObservationResults.map((i) => ({
- // ClickHouse returns UInt8 (0/1) for computed boolean; normalize to "true"/"false"
- value: i.isRootObservation ? "true" : "false",
- count: i.count,
- })),
- toolNames: toolNames
- .filter((i) => i.toolName !== null)
- .map((i) => ({ value: i.toolName })),
- calledToolNames: calledToolNames
- .filter((i) => i.calledToolName !== null)
- .map((i) => ({ value: i.calledToolName })),
};
}
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index c12e95de66..b6da94361a 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -339,20 +339,17 @@ export const scoresRouter = createTRPCRouter({
);
}
- const scoredTracesScope =
- "e.trace_id IN (SELECT DISTINCT trace_id FROM scores WHERE project_id = {projectId: String})";
-
const [names, tags, traceNames, userIds, stringValues] =
await Promise.all([
getScoreNames(input.projectId, timestampFilter ?? []),
getEventsGroupedByTraceTags(input.projectId, eventsFilter, {
- extraWhereRaw: scoredTracesScope,
+ scope: "scoredTraces",
}),
getEventsGroupedByTraceName(input.projectId, eventsFilter, {
- extraWhereRaw: scoredTracesScope,
+ scope: "scoredTraces",
}),
getEventsGroupedByUserId(input.projectId, eventsFilter, {
- extraWhereRaw: scoredTracesScope,
+ scope: "scoredTraces",
}),
getScoreStringValues(input.projectId, timestampFilter ?? []),
]);