Skip to content

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

chore(events-table): add v4 view of scores via metrics query (#12124)

Nimar0251b9257264
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 94ccd14647..e30499c089 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -21,6 +21,7 @@ import { OrderByState } from "../../interfaces/orderBy";
import {
dashboardColumnDefinitions,
scoresTableUiColumnDefinitions,
+ scoresTableUiColumnDefinitionsFromEvents,
} from "../tableMappings";
import {
convertScoreAggregation,
@@ -1051,6 +1052,253 @@ const getScoresUiGeneric = async <T>(props: {
});
};
+/**
+ * v4 variant: scores query using events_core instead of traces table.
+ * Trace-level filters use IN subqueries against events_core.
+ * When sorting by trace columns, adds LEFT ANY JOIN with events_core subquery.
+ * Does NOT select trace metadata (that comes via metricsFromEvents).
+ */
+const getScoresUiGenericFromEvents = async <T>(props: {
+ select: "count" | "rows";
+ projectId: string;
+ filter: FilterState;
+ orderBy: OrderByState;
+ limit?: number;
+ offset?: number;
+ tags?: Record<string, string>;
+ clickhouseConfigs?: ClickHouseClientConfigOptions;
+ excludeMetadata?: boolean;
+ includeHasMetadataFlag?: boolean;
+}): Promise<T[]> => {
+ const {
+ projectId,
+ filter,
+ orderBy,
+ limit,
+ offset,
+ clickhouseConfigs,
+ excludeMetadata = false,
+ includeHasMetadataFlag = false,
+ } = props;
+
+ const { scoresFilter } = getProjectIdDefaultFilter(projectId, {
+ tracesPrefix: "e",
+ });
+ scoresFilter.push(
+ ...createFilterFromFilterState(
+ filter,
+ scoresTableUiColumnDefinitionsFromEvents,
+ ),
+ );
+
+ // Separate trace filters (events_core) from score filters
+ const traceFilters = scoresFilter.filter(
+ (f) => f.clickhouseTable === "events_core",
+ );
+ const scoreOnlyFilters = scoresFilter.filter(
+ (f) => f.clickhouseTable !== "events_core",
+ );
+
+ const scoreOnlyFilterRes = scoreOnlyFilters.apply();
+
+ // Build IN subqueries for trace-level filters
+ const traceFilterSubqueries: string[] = [];
+ const traceFilterParams: Record<string, unknown> = {};
+
+ if (traceFilters.find(() => true)) {
+ const traceFilterRes = traceFilters.apply();
+ if (traceFilterRes.query) {
+ traceFilterSubqueries.push(
+ `s.trace_id IN (
+ SELECT DISTINCT trace_id FROM events_core
+ WHERE project_id = {projectId: String}
+ AND is_deleted = 0
+ AND ${traceFilterRes.query}
+ )`,
+ );
+ Object.assign(traceFilterParams, traceFilterRes.params);
+ }
+ }
+
+ const orderByColumn = orderBy
+ ? scoresTableUiColumnDefinitionsFromEvents.find(
+ (c) =>
+ (c.uiTableName === orderBy.column ||
+ c.uiTableId === orderBy.column) &&
+ c.clickhouseTableName === "events_core",
+ )
+ : null;
+
+ const needsEventsJoinForSort = !!orderByColumn;
+
+ const eventsSubqueryJoin = needsEventsJoinForSort
+ ? `LEFT ANY JOIN (
+ SELECT
+ trace_id,
+ anyIf(trace_name, trace_name <> '') as trace_name,
+ anyIf(user_id, user_id <> '') as user_id,
+ anyIf(tags, notEmpty(tags)) as tags
+ FROM events_core
+ WHERE project_id = {projectId: String}
+ AND is_deleted = 0
+ GROUP BY trace_id
+ ) e ON s.trace_id = e.trace_id`
+ : "";
+
+ const select =
+ props.select === "count"
+ ? "count(*) as count"
+ : `
+ s.id,
+ s.project_id,
+ s.environment,
+ s.name,
+ s.value,
+ s.string_value,
+ s.timestamp,
+ s.source,
+ s.data_type,
+ s.comment,
+ ${excludeMetadata ? "" : "s.metadata,"}
+ s.trace_id,
+ s.session_id,
+ s.observation_id,
+ s.author_user_id,
+ s.created_at,
+ s.updated_at,
+ s.config_id,
+ s.queue_id,
+ s.execution_trace_id,
+ s.is_deleted,
+ s.event_ts
+ ${includeHasMetadataFlag ? ",length(mapKeys(s.metadata)) > 0 AS has_metadata" : ""}
+ `;
+
+ const query = `
+ SELECT
+ ${select}
+ FROM scores s final
+ ${eventsSubqueryJoin}
+ WHERE s.project_id = {projectId: String}
+ AND s.data_type IN ({dataTypes: Array(String)})
+ ${scoreOnlyFilterRes?.query ? `AND ${scoreOnlyFilterRes.query}` : ""}
+ ${traceFilterSubqueries.map((sq) => `AND ${sq}`).join("\n")}
+ ${orderByToClickhouseSql(orderBy ?? null, scoresTableUiColumnDefinitionsFromEvents)}
+ ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
+ `;
+
+ return measureAndReturn({
+ operationName: "getScoresUiGenericFromEvents",
+ projectId,
+ input: {
+ params: {
+ projectId,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
+ ...(scoreOnlyFilterRes ? scoreOnlyFilterRes.params : {}),
+ ...traceFilterParams,
+ limit,
+ offset,
+ },
+ tags: {
+ ...(props.tags ?? {}),
+ feature: "tracing",
+ type: "score",
+ projectId,
+ select: props.select,
+ operation_name: "getScoresUiGenericFromEvents",
+ },
+ },
+ fn: async (input) => {
+ return queryClickhouse<T>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs,
+ });
+ },
+ });
+};
+
+export const getScoresUiCountFromEvents = async (props: {
+ projectId: string;
+ filter: FilterState;
+ orderBy: OrderByState;
+ limit?: number;
+ offset?: number;
+}) => {
+ const rows = await getScoresUiGenericFromEvents<{ count: string }>({
+ select: "count",
+ excludeMetadata: true,
+ tags: { kind: "count" },
+ ...props,
+ });
+
+ return Number(rows[0].count);
+};
+
+export type ScoreUiTableRowFromEvents = Omit<ScoreDomain, "metadata"> & {
+ hasMetadata: boolean;
+};
+
+export async function getScoresUiTableFromEvents(props: {
+ projectId: string;
+ filter: FilterState;
+ orderBy: OrderByState;
+ limit?: number;
+ offset?: number;
+ clickhouseConfigs?: ClickHouseClientConfigOptions;
+}) {
+ const { clickhouseConfigs, ...rest } = props;
+
+ const rows = await getScoresUiGenericFromEvents<{
+ id: string;
+ project_id: string;
+ environment: string;
+ name: string;
+ value: number;
+ string_value: string | null;
+ timestamp: string;
+ source: string;
+ data_type: string;
+ comment: string | null;
+ trace_id: string | null;
+ session_id: string | null;
+ dataset_run_id: string | null;
+ observation_id: string | null;
+ author_user_id: string | null;
+ config_id: string | null;
+ queue_id: string | null;
+ execution_trace_id: string | null;
+ is_deleted: number;
+ event_ts: string;
+ created_at: string;
+ updated_at: string;
+ has_metadata: 0 | 1;
+ }>({
+ select: "rows",
+ tags: { kind: "analytic" },
+ excludeMetadata: true,
+ includeHasMetadataFlag: true,
+ clickhouseConfigs,
+ ...rest,
+ });
+
+ return rows.map((row) => {
+ const score = convertClickhouseScoreToDomain(
+ {
+ ...row,
+ metadata: {},
+ long_string_value: "",
+ },
+ false,
+ );
+ return {
+ ...score,
+ hasMetadata: !!row.has_metadata,
+ };
+ });
+}
+
export const getScoreNames = async (
projectId: string,
timestampFilter: FilterState,
@@ -1818,3 +2066,47 @@ export const getScoreCountsByProjectAndDay = async ({
date: row.date,
}));
};
+
+export async function getScoresTraceMetricsFromEvents(params: {
+ projectId: string;
+ traceIds: string[];
+}) {
+ const { projectId, traceIds } = params;
+ if (traceIds.length === 0) return [];
+
+ const query = `
+ SELECT
+ trace_id,
+ anyIf(trace_name, trace_name <> '') as trace_name,
+ anyIf(user_id, user_id <> '') as user_id,
+ anyIf(tags, notEmpty(tags)) as tags
+ FROM events_core
+ WHERE project_id = {projectId: String}
+ AND trace_id IN ({traceIds: Array(String)})
+ AND is_deleted = 0
+ GROUP BY trace_id
+ `;
+
+ const rows = await queryClickhouse<{
+ trace_id: string;
+ trace_name: string | null;
+ user_id: string | null;
+ tags: string[] | null;
+ }>({
+ query,
+ params: { projectId, traceIds },
+ tags: {
+ feature: "tracing",
+ type: "score",
+ kind: "metrics",
+ projectId,
+ },
+ });
+
+ return rows.map((row) => ({
+ traceId: row.trace_id,
+ traceName: row.trace_name || null,
+ userId: row.user_id || null,
+ tags: row.tags && row.tags.length > 0 ? row.tags : null,
+ }));
+}
diff --git a/packages/shared/src/server/tableMappings/mapScoresTable.ts b/packages/shared/src/server/tableMappings/mapScoresTable.ts
index b22d579edc..8e187a2f90 100644
--- a/packages/shared/src/server/tableMappings/mapScoresTable.ts
+++ b/packages/shared/src/server/tableMappings/mapScoresTable.ts
@@ -104,3 +104,32 @@ export const scoresTableUiColumnDefinitions: UiColumnMappings = [
clickhouseSelect: "t.tags",
},
];
+
+/**
+ * v4 column definitions for scores table — trace columns reference events_core
+ * instead of traces table. Used with the events_core subquery JOIN (alias e).
+ */
+export const scoresTableUiColumnDefinitionsFromEvents: UiColumnMappings = [
+ // All scores-native columns are identical to v3
+ ...scoresTableUiColumnDefinitions.filter(
+ (c) => c.clickhouseTableName === "scores",
+ ),
+ {
+ uiTableName: "Trace Name",
+ uiTableId: "traceName",
+ clickhouseTableName: "events_core",
+ clickhouseSelect: "trace_name",
+ },
+ {
+ uiTableName: "User ID",
+ uiTableId: "userId",
+ clickhouseTableName: "events_core",
+ clickhouseSelect: "user_id",
+ },
+ {
+ uiTableName: "Trace Tags",
+ uiTableId: "trace_tags",
+ clickhouseTableName: "events_core",
+ clickhouseSelect: "tags",
+ },
+];
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 28591b9e22..8657e93fdb 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -41,7 +41,7 @@ import { Badge } from "@/src/components/ui/badge";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
-import React, { useState, useRef, useCallback } from "react";
+import React, { useState, useRef, useCallback, useMemo } from "react";
import type { TableAction } from "@/src/features/table/types";
import type { RowSelectionState } from "@tanstack/react-table";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
@@ -50,6 +50,8 @@ import { TableSelectionManager } from "@/src/features/table/components/TableSele
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import TableIdOrName from "@/src/components/table/table-id";
import { usePaginationState } from "@/src/hooks/usePaginationState";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { Skeleton } from "@/src/components/ui/skeleton";
export type ScoresTableRow = {
id: string;
@@ -110,6 +112,7 @@ export default function ScoresTable({
localStorageSuffix?: string;
disableUrlPersistence?: boolean;
}) {
+ const { isBetaEnabled } = useV4Beta();
const utils = api.useUtils();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const [paginationState, setPaginationState] = usePaginationState(0, 50, {
@@ -184,6 +187,8 @@ export default function ScoresTable({
},
onSettled: () => {
void utils.scores.all.invalidate();
+ void utils.scores.allFromEvents.invalidate();
+ void utils.scores.countAllFromEvents.invalidate();
},
});
@@ -206,27 +211,45 @@ export default function ScoresTable({
setSelectedRows({});
};
- const filterOptions = api.scores.filterOptions.useQuery(
+ // Filter options — v3 vs v4
+ const filterOptionsTimestampInput = {
+ projectId,
+ timestampFilter:
+ dateRangeFilter.length > 0
+ ? (dateRangeFilter as TimeFilter[])
+ : undefined,
+ };
+
+ const filterOptionsQueryConfig = {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ } as const;
+
+ const filterOptionsV3 = api.scores.filterOptions.useQuery(
+ filterOptionsTimestampInput,
{
- projectId,
- timestampFilter:
- dateRangeFilter.length > 0
- ? (dateRangeFilter as TimeFilter[])
- : undefined,
+ ...filterOptionsQueryConfig,
+ enabled: !isBetaEnabled,
},
+ );
+
+ const filterOptionsV4 = api.scores.filterOptionsFromEvents.useQuery(
+ filterOptionsTimestampInput,
{
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
+ ...filterOptionsQueryConfig,
+ enabled: isBetaEnabled,
},
);
+ const filterOptions = isBetaEnabled ? filterOptionsV4 : filterOptionsV3;
+
const newFilterOptions = React.useMemo(
() => ({
name:
@@ -307,15 +330,46 @@ export default function ScoresTable({
orderBy: orderByState,
};
- const scores = api.scores.all.useQuery(getAllPayload, {
- enabled: !environmentFilterOptions.isLoading,
+ // Base data — v3 (existing, unchanged)
+ const scoresV3 = api.scores.all.useQuery(getAllPayload, {
+ enabled: !environmentFilterOptions.isLoading && !isBetaEnabled,
});
- const totalScoreCountQuery = api.scores.countAll.useQuery(getCountPayload, {
- enabled: !environmentFilterOptions.isLoading,
+
+ // Base data — v4 (no traces JOIN)
+ const scoresV4 = api.scores.allFromEvents.useQuery(getAllPayload, {
+ enabled: !environmentFilterOptions.isLoading && isBetaEnabled,
});
+ const scores = isBetaEnabled ? scoresV4 : scoresV3;
+
+ // Count — v3 vs v4
+ const countV3 = api.scores.countAll.useQuery(getCountPayload, {
+ enabled: !environmentFilterOptions.isLoading && !isBetaEnabled,
+ });
+ const countV4 = api.scores.countAllFromEvents.useQuery(getCountPayload, {
+ enabled: !environmentFilterOptions.isLoading && isBetaEnabled,
+ });
+ const totalScoreCountQuery = isBetaEnabled ? countV4 : countV3;
+
const totalCount = totalScoreCountQuery.data?.totalCount ?? null;
+ // Metrics — v4 only (loads trace metadata from events_core)
+ const scoreMetrics = api.scores.metricsFromEvents.useQuery(
+ {
+ projectId,
+ traceIds: [
+ ...new Set(
+ scoresV4.data?.scores
+ .map((s) => s.traceId)
+ .filter((id): id is string => Boolean(id)) ?? [],
+ ),
+ ],
+ },
+ {
+ enabled: scoresV4.data !== undefined && isBetaEnabled,
+ },
+ );
+
const { selectActionColumn } = TableSelectionManager<ScoresTableRow>({
projectId,
tableName: "scores",
@@ -348,6 +402,8 @@ export default function ScoresTable({
enableSorting: true,
size: 150,
cell: ({ row }) => {
+ if (isBetaEnabled && !scoreMetrics.data)
+ return <Skeleton className="h-3 w-1/2" />;
const value = row.getValue("traceName") as ScoresTableRow["traceName"];
const filter = encodeURIComponent(
`name;stringOptions;;any of;${value}`,
@@ -463,6 +519,8 @@ export default function ScoresTable({
enableSorting: true,
size: 100,
cell: ({ row }) => {
+ if (isBetaEnabled && !scoreMetrics.data)
+ return <Skeleton className="h-3 w-1/2" />;
const value = row.getValue("userId");
return typeof value === "string" ? (
<>
@@ -607,6 +665,8 @@ export default function ScoresTable({
enableHiding: true,
defaultHidden: true,
cell: ({ row }) => {
+ if (isBetaEnabled && !scoreMetrics.data)
+ return <Skeleton className="h-3 w-1/2" />;
const traceTags: string[] | undefined = row.getValue("traceTags");
return (
traceTags && (
@@ -691,6 +751,53 @@ export default function ScoresTable({
};
};
+ // Merge v4 metrics into table rows
+ const enrichedScores = useMemo(() => {
+ if (!isBetaEnabled) {
+ return scoresV3.data?.scores.map(convertToTableRow);
+ }
+
+ const v4Data = scoresV4.data?.scores;
+ if (!v4Data) return undefined;
+
+ const metaByTraceId = new Map(
+ scoreMetrics.data?.map((m) => [m.traceId, m]) ?? [],
+ );
+
+ return v4Data.map((score) => {
+ const meta = metaByTraceId.get(score.traceId ?? "");
+ return {
+ id: score.id,
+ timestamp: score.timestamp,
+ source: score.source,
+ name: score.name,
+ dataType: score.dataType,
+ value:
+ isNumericDataType(score.dataType) && isPresent(score.value)
+ ? score.value % 1 === 0
+ ? String(score.value)
+ : score.value.toFixed(4)
+ : (score.stringValue ?? ""),
+ author: {
+ userId: score.authorUserId ?? undefined,
+ image: score.authorUserImage ?? undefined,
+ name: score.authorUserName ?? undefined,
+ },
+ comment: score.comment ?? undefined,
+ observationId: score.observationId ?? undefined,
+ sessionId: score.sessionId ?? undefined,
+ traceId: score.traceId ?? undefined,
+ traceName: meta?.traceName ?? undefined,
+ userId: meta?.userId ?? undefined,
+ jobConfigurationId: score.jobConfigurationId ?? undefined,
+ traceTags: meta?.tags ?? undefined,
+ environment: score.environment ?? undefined,
+ executionTraceId: score.executionTraceId ?? undefined,
+ } satisfies ScoresTableRow;
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [scores.data, scoreMetrics.data, isBetaEnabled]);
+
const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({
tableName: TableViewPresetTableName.Scores,
projectId,
@@ -792,7 +899,7 @@ export default function ScoresTable({
: {
isLoading: false,
isError: false,
- data: scores.data?.scores.map(convertToTableRow) ?? [],
+ data: enrichedScores ?? [],
}
}
pagination={{
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index fcc49f42eb..22e70bb196 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -25,6 +25,7 @@ import {
ActionId,
BatchExportTableName,
type ScoreDomain,
+ type FilterState,
CreateAnnotationScoreData,
type ScoreConfigDomain,
ScoreSourceEnum,
@@ -35,11 +36,17 @@ import {
getScoresGroupedByNameSourceType,
getScoresUiCount,
getScoresUiTable,
+ getScoresUiCountFromEvents,
+ getScoresUiTableFromEvents,
+ getScoresTraceMetricsFromEvents,
getScoreNames,
getScoreStringValues,
getTracesGroupedByTags,
getTracesGroupedByName,
getTracesGroupedByUsers,
+ getEventsGroupedByTraceName,
+ getEventsGroupedByTraceTags,
+ getEventsGroupedByUserId,
tracesTableUiColumnDefinitions,
upsertScore,
logger,
@@ -85,6 +92,13 @@ type AllScoresReturnType = Omit<ScoreDomain, "metadata"> & {
hasMetadata: boolean;
};
+type AllScoresFromEventsReturnType = Omit<ScoreDomain, "metadata"> & {
+ jobConfigurationId: string | null;
+ authorUserImage: string | null;
+ authorUserName: string | null;
+ hasMetadata: boolean;
+};
+
export const scoresRouter = createTRPCRouter({
/**
* Get all scores for a project, meant for internal use and *excludes metadata of scores*
@@ -182,6 +196,148 @@ export const scoresRouter = createTRPCRouter({
totalCount: clickhouseScoreData,
};
}),
+ /**
+ * v4: Get all scores without traces JOIN. Trace metadata loaded via metricsFromEvents.
+ */
+ allFromEvents: protectedProjectProcedure
+ .input(ScoreAllOptions)
+ .query(async ({ input, ctx }) => {
+ const clickhouseScoreData = await getScoresUiTableFromEvents({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ limit: input.limit,
+ offset: input.page * input.limit,
+ });
+
+ const [jobExecutions, users] = await Promise.all([
+ ctx.prisma.jobExecution.findMany({
+ where: {
+ projectId: input.projectId,
+ jobOutputScoreId: {
+ in: clickhouseScoreData.map((score) => score.id),
+ },
+ },
+ select: {
+ id: true,
+ jobConfigurationId: true,
+ jobOutputScoreId: true,
+ },
+ }),
+ ctx.prisma.user.findMany({
+ where: {
+ id: {
+ in: clickhouseScoreData
+ .map((score) => score.authorUserId)
+ .filter((s): s is string => Boolean(s)),
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ },
+ }),
+ ]);
+
+ return {
+ scores: clickhouseScoreData.map<AllScoresFromEventsReturnType>(
+ (score) => {
+ const jobExecution = jobExecutions.find(
+ (je) => je.jobOutputScoreId === score.id,
+ );
+ const user = users.find((u) => u.id === score.authorUserId);
+ return {
+ ...score,
+ jobConfigurationId: jobExecution?.jobConfigurationId ?? null,
+ authorUserImage: user?.image ?? null,
+ authorUserName: user?.name ?? null,
+ };
+ },
+ ),
+ };
+ }),
+ /**
+ * v4: Count scores without traces JOIN.
+ */
+ countAllFromEvents: protectedProjectProcedure
+ .input(ScoreAllOptions)
+ .query(async ({ input }) => {
+ const count = await getScoresUiCountFromEvents({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ limit: 1,
+ offset: 0,
+ });
+
+ return {
+ totalCount: count,
+ };
+ }),
+ /**
+ * v4: Load trace metadata (name, userId, tags) from events_core for a page of scores.
+ */
+ metricsFromEvents: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ traceIds: z.array(z.string()),
+ }),
+ )
+ .query(async ({ input }) => {
+ if (input.traceIds.length === 0) return [];
+ return getScoresTraceMetricsFromEvents({
+ projectId: input.projectId,
+ traceIds: input.traceIds,
+ });
+ }),
+ /**
+ * v4: Filter options using events_core instead of traces table.
+ */
+ filterOptionsFromEvents: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ timestampFilter: z.array(timeFilter).optional(),
+ }),
+ )
+ .query(async ({ input }) => {
+ const { timestampFilter } = input;
+
+ const eventsFilter: FilterState = [];
+ if (timestampFilter && timestampFilter.length > 0) {
+ eventsFilter.push(
+ ...timestampFilter.map((tf) => ({
+ ...tf,
+ column: "startTime" as const,
+ })),
+ );
+ }
+
+ const [names, tags, traceNames, userIds, stringValues] =
+ await Promise.all([
+ getScoreNames(input.projectId, timestampFilter ?? []),
+ getEventsGroupedByTraceTags(input.projectId, eventsFilter),
+ getEventsGroupedByTraceName(input.projectId, eventsFilter),
+ getEventsGroupedByUserId(input.projectId, eventsFilter),
+ getScoreStringValues(input.projectId, timestampFilter ?? []),
+ ]);
+
+ return {
+ name: names.map((i) => ({ value: i.name, count: i.count })),
+ tags: tags.map((t) => ({ value: t.tag })),
+ traceName: traceNames.map((tn) => ({
+ value: tn.traceName,
+ count: Number(tn.count),
+ })),
+ userId: userIds.map((u) => ({
+ value: u.userId,
+ count: Number(u.count),
+ })),
+ stringValue: stringValues,
+ };
+ }),
filterOptions: protectedProjectProcedure
.input(
z.object({