Skip to content

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

feat(dataset-runs): support score filters in ui tables (#8755)

marliessophiee6b4af40049d
diff --git a/packages/shared/src/server/repositories/dataset-run-items.ts b/packages/shared/src/server/repositories/dataset-run-items.ts
index 0238b516b0..dda658f742 100644
--- a/packages/shared/src/server/repositories/dataset-run-items.ts
+++ b/packages/shared/src/server/repositories/dataset-run-items.ts
@@ -1,12 +1,14 @@
import { DatasetRunItemDomain } from "../../domain/dataset-run-items";
import { type OrderByState } from "../../interfaces/orderBy";
import { datasetRunItemsTableUiColumnDefinitions } from "../tableMappings";
+import { datasetRunsTableUiColumnDefinitions } from "../../tableDefinitions/mapDatasetRunsTable";
import { FilterState } from "../../types";
import {
createFilterFromFilterState,
FilterList,
orderByToClickhouseSql,
StringFilter,
+ StringOptionsFilter,
} from "../queries";
import {
parseClickhouseUTCDateTimeFormat,
@@ -45,8 +47,11 @@ type DatasetRunItemsByDatasetIdQuery = Omit<
};
type DatasetRunsMetricsTableQuery = {
+ select: "rows" | "metrics" | "count";
projectId: string;
datasetId: string;
+ filter: FilterState;
+ runIds?: string[];
orderBy?: OrderByState;
limit?: number;
offset?: number;
@@ -54,22 +59,46 @@ type DatasetRunsMetricsTableQuery = {
export type DatasetRunsMetrics = {
id: string;
+ name: string;
projectId: string;
- createdAt: Date;
datasetId: string;
countRunItems: number;
avgTotalCost: Decimal;
avgLatency: number;
+ aggScoresAvg: Array<[string, number]>;
+ aggScoreCategories: string[];
+};
+
+type DatasetRunsRows = {
+ id: string;
+ name: string;
+ projectId: string;
+ createdAt: Date;
+ datasetId: string;
+ description: string;
+ metadata: string;
};
type DatasetRunsMetricsRecordType = {
dataset_run_id: string;
+ dataset_run_name: string;
project_id: string;
- dataset_run_created_at: string;
dataset_id: string;
count_run_items: number;
avg_latency_seconds: number;
avg_total_cost: number;
+ agg_scores_avg: Array<[string, number]>;
+ agg_score_categories: string[];
+};
+
+type DatasetRunsRowsRecordType = {
+ dataset_run_id: string;
+ dataset_run_name: string;
+ project_id: string;
+ dataset_id: string;
+ dataset_run_created_at: string;
+ dataset_run_description: string;
+ dataset_run_metadata: string;
};
const convertDatasetRunsMetricsRecord = (
@@ -77,20 +106,37 @@ const convertDatasetRunsMetricsRecord = (
): DatasetRunsMetrics => {
return {
id: record.dataset_run_id,
+ name: record.dataset_run_name,
projectId: record.project_id,
- createdAt: parseClickhouseUTCDateTimeFormat(record.dataset_run_created_at),
datasetId: record.dataset_id,
countRunItems: record.count_run_items,
avgTotalCost: record.avg_total_cost
? new Decimal(record.avg_total_cost)
: new Decimal(0),
avgLatency: record.avg_latency_seconds ?? 0,
+ aggScoresAvg: record.agg_scores_avg ?? [],
+ aggScoreCategories: record.agg_score_categories ?? [],
+ };
+};
+
+const convertDatasetRunsRowsRecord = (
+ record: DatasetRunsRowsRecordType,
+): DatasetRunsRows => {
+ return {
+ id: record.dataset_run_id,
+ name: record.dataset_run_name,
+ projectId: record.project_id,
+ createdAt: parseClickhouseUTCDateTimeFormat(record.dataset_run_created_at),
+ datasetId: record.dataset_id,
+ description: record.dataset_run_description,
+ metadata: record.dataset_run_metadata,
};
};
const getProjectDatasetIdDefaultFilter = (
projectId: string,
datasetId?: string,
+ runIds?: string[],
) => {
return {
datasetRunItemsFilter: new FilterList([
@@ -110,6 +156,16 @@ const getProjectDatasetIdDefaultFilter = (
}),
]
: []),
+ ...(runIds && runIds.length > 0
+ ? [
+ new StringOptionsFilter({
+ clickhouseTable: "dataset_run_items_rmt",
+ field: "dataset_run_id",
+ operator: "any of",
+ values: runIds,
+ }),
+ ]
+ : []),
]),
};
};
@@ -119,17 +175,85 @@ const getDatasetRunsTableInternal = async <T>(
tags: Record<string, string>;
},
): Promise<Array<T>> => {
- const { projectId, datasetId, orderBy, limit, offset } = opts;
+ const { projectId, datasetId, runIds, filter, orderBy, limit, offset } = opts;
+ let select = "";
+
+ switch (opts.select) {
+ case "rows":
+ select = `
+ drm.project_id as project_id,
+ drm.dataset_id as dataset_id,
+ drm.dataset_run_id as dataset_run_id,
+ drm.dataset_run_name as dataset_run_name,
+ drm.dataset_run_created_at as dataset_run_created_at,
+ drm.dataset_run_description as dataset_run_description,
+ drm.dataset_run_metadata as dataset_run_metadata
+ `;
+ break;
+ case "metrics":
+ select = `
+ drm.project_id as project_id,
+ drm.dataset_id as dataset_id,
+ drm.dataset_run_id as dataset_run_id,
+ drm.dataset_run_name as dataset_run_name,
+ drm.count_run_items as count_run_items,
+
+ -- Latency metrics (priority: trace > observation - matching old PostgreSQL behavior)
+ CASE
+ WHEN drm.trace_avg_latency IS NOT NULL THEN drm.trace_avg_latency
+ ELSE drm.obs_avg_latency
+ END as avg_latency_seconds,
+
+ -- Cost metrics (priority: trace > observation - matching old PostgreSQL behavior)
+ CASE
+ WHEN drm.trace_avg_cost IS NOT NULL THEN drm.trace_avg_cost
+ ELSE COALESCE(drm.obs_avg_cost, 0)
+ END as avg_total_cost,
+
+ -- Score aggregations
+ sa.scores_avg as agg_scores_avg,
+ sa.score_categories as agg_score_categories`;
+ break;
+ case "count":
+ select = "count(DISTINCT drm.dataset_run_id) as count";
+ break;
+ }
const { datasetRunItemsFilter } = getProjectDatasetIdDefaultFilter(
projectId,
datasetId,
+ runIds,
+ );
+
+ const baseFilter = datasetRunItemsFilter.apply();
+
+ const scoresFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "scores",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ }),
+ ]);
+
+ const appliedScoresFilter = scoresFilter.apply();
+
+ const userFilters = createFilterFromFilterState(
+ filter,
+ datasetRunsTableUiColumnDefinitions,
);
+ datasetRunItemsFilter.push(...userFilters);
+
const appliedFilter = datasetRunItemsFilter.apply();
- // Build ORDER BY array - conditionally add event_ts DESC for rows
const orderByArray: OrderByState[] = [];
-
+ // Build ORDER BY array - conditionally add dataset_run_created_at ASC for rows
+ if (opts.select === "metrics" && orderBy?.column !== "createdAt") {
+ orderByArray.push({
+ column: "createdAt",
+ order: "DESC",
+ });
+ }
// Add user ordering if provided
if (orderBy) {
orderByArray.push(orderBy);
@@ -137,11 +261,50 @@ const getDatasetRunsTableInternal = async <T>(
const orderByClause = orderByToClickhouseSql(
orderByArray,
- datasetRunItemsTableUiColumnDefinitions,
+ datasetRunsTableUiColumnDefinitions,
);
- const query = `
- WITH observations_filtered AS (
+ const scoresCte = `
+ WITH scores_aggregated AS (
+ SELECT
+ dri.dataset_run_id,
+ dri.project_id,
+ -- For numeric scores, use tuples of (name, avg_value)
+ groupArrayIf(
+ tuple(s.name, s.avg_value),
+ s.data_type IN ('NUMERIC', 'BOOLEAN')
+ ) AS scores_avg,
+ -- For categorical scores, use name:value format for improved query performance
+ groupArrayIf(
+ concat(s.name, ':', s.string_value),
+ s.data_type = 'CATEGORICAL' AND notEmpty(s.string_value)
+ ) AS score_categories
+ FROM dataset_run_items_rmt dri
+ LEFT JOIN (
+ SELECT
+ project_id,
+ trace_id,
+ name,
+ data_type,
+ string_value,
+ avg(value) as avg_value
+ FROM scores s FINAL
+ WHERE ${appliedScoresFilter.query}
+ GROUP BY
+ project_id,
+ trace_id,
+ name,
+ data_type,
+ string_value
+ ) s ON s.project_id = dri.project_id AND s.trace_id = dri.trace_id
+ WHERE dri.project_id = {projectId: String}
+ AND dri.dataset_id = {datasetId: String}
+ GROUP BY dri.dataset_run_id, dri.project_id
+ ),
+ `;
+
+ const filteredObservationsCte = `
+ observations_filtered AS (
SELECT
o.id,
o.trace_id,
@@ -164,7 +327,10 @@ const getDatasetRunsTableInternal = async <T>(
AND dri.dataset_id = {datasetId: String}
)
),
- traces_aggregated AS (
+ `;
+
+ const traceMetricsCte = `
+ trace_metrics AS (
SELECT
of.trace_id,
of.project_id,
@@ -174,54 +340,56 @@ const getDatasetRunsTableInternal = async <T>(
JOIN dataset_run_items_rmt dri ON dri.trace_id = of.trace_id
AND dri.project_id = of.project_id
AND dri.observation_id IS NULL -- Only for trace-level dataset run items
- WHERE dri.dataset_id = {datasetId: String}
+ WHERE ${baseFilter.query}
GROUP BY of.trace_id, of.project_id
),
- observations_direct AS (
+ `;
+
+ const datasetRunMetricsCte = `
+ dataset_run_metrics AS (
SELECT
- dri.observation_id,
- dri.project_id,
- dri.trace_id,
- of.total_cost,
- dateDiff('millisecond', of.start_time, of.end_time) as latency_ms
+ dri.dataset_run_id as dataset_run_id,
+ dri.project_id as project_id,
+ dri.dataset_id as dataset_id,
+ dri.dataset_run_created_at as dataset_run_created_at,
+ dri.dataset_run_name as dataset_run_name,
+ dri.dataset_run_description as dataset_run_description,
+ dri.dataset_run_metadata as dataset_run_metadata,
+ count(DISTINCT dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.dataset_item_id) as count_run_items,
+
+ -- Trace-level metrics (average across traces in this dataset run)
+ AVG(CASE WHEN dri.observation_id IS NULL THEN tm.latency_ms ELSE NULL END) / 1000.0 as trace_avg_latency,
+ AVG(CASE WHEN dri.observation_id IS NULL THEN tm.total_cost ELSE NULL END) as trace_avg_cost,
+
+ -- Observation-level metrics
+ AVG(CASE WHEN dri.observation_id IS NOT NULL THEN
+ dateDiff('millisecond', of.start_time, of.end_time) / 1000.0
+ ELSE NULL END) as obs_avg_latency,
+ AVG(CASE WHEN dri.observation_id IS NOT NULL THEN of.total_cost ELSE NULL END) as obs_avg_cost
+
FROM dataset_run_items_rmt dri
- JOIN observations_filtered of ON dri.observation_id = of.id
+ LEFT JOIN observations_filtered of ON dri.observation_id = of.id
AND dri.project_id = of.project_id
AND dri.trace_id = of.trace_id
- WHERE dri.dataset_id = {datasetId: String}
- AND dri.observation_id IS NOT NULL -- Only for observation-level dataset run items
+ LEFT JOIN trace_metrics tm ON dri.trace_id = tm.trace_id
+ AND dri.project_id = tm.project_id
+ AND dri.observation_id IS NULL
+ WHERE ${baseFilter.query}
+ GROUP BY dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.dataset_run_name, dri.dataset_run_description, dri.dataset_run_metadata, dri.dataset_run_created_at
)
- SELECT DISTINCT
- dri.dataset_run_id as dataset_run_id,
- dri.project_id as project_id,
- dri.dataset_id as dataset_id,
- dri.dataset_run_created_at as dataset_run_created_at,
- count(DISTINCT dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.dataset_item_id) as count_run_items,
-
- -- Latency metrics (priority: trace > observation - matching old PostgreSQL behavior)
- CASE
- WHEN AVG(CASE WHEN dri.observation_id IS NULL THEN ta.latency_ms / 1000.0 ELSE NULL END) IS NOT NULL
- THEN AVG(CASE WHEN dri.observation_id IS NULL THEN ta.latency_ms / 1000.0 ELSE NULL END)
- ELSE AVG(CASE WHEN dri.observation_id IS NOT NULL THEN od.latency_ms / 1000.0 ELSE NULL END)
- END as avg_latency_seconds,
-
- -- Cost metrics (priority: trace > observation - matching old PostgreSQL behavior)
- CASE
- WHEN AVG(CASE WHEN dri.observation_id IS NULL THEN ta.total_cost ELSE NULL END) IS NOT NULL
- THEN AVG(CASE WHEN dri.observation_id IS NULL THEN ta.total_cost ELSE NULL END)
- ELSE COALESCE(AVG(CASE WHEN dri.observation_id IS NOT NULL THEN od.total_cost ELSE NULL END), 0)
- END as avg_total_cost
- FROM dataset_run_items_rmt dri
- LEFT JOIN traces_aggregated ta
- ON dri.trace_id = ta.trace_id
- AND dri.project_id = ta.project_id
- LEFT JOIN observations_direct od
- ON dri.observation_id = od.observation_id
- AND dri.project_id = od.project_id
- AND dri.trace_id = od.trace_id
- WHERE ${appliedFilter.query}
- GROUP BY dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.dataset_run_created_at
- ORDER BY dri.dataset_run_created_at DESC
+ `;
+
+ const query = `
+ ${scoresCte}
+ ${filteredObservationsCte}
+ ${traceMetricsCte}
+ ${datasetRunMetricsCte}
+ SELECT ${opts.select === "count" ? "" : "DISTINCT"}
+ ${select}
+ FROM dataset_run_metrics drm
+ LEFT JOIN scores_aggregated sa ON drm.dataset_run_id = sa.dataset_run_id AND drm.project_id = sa.project_id
+ WHERE drm.project_id = {projectId: String} AND drm.dataset_id = {datasetId: String}
+ ${appliedFilter.query ? `AND ${appliedFilter.query}` : ""}
${orderByClause}
${limit !== undefined && offset !== undefined ? `LIMIT ${limit} OFFSET ${offset}` : ""};`;
@@ -230,6 +398,9 @@ const getDatasetRunsTableInternal = async <T>(
params: {
projectId,
datasetId,
+ ...(runIds && runIds.length > 0 ? { runIds } : {}),
+ ...appliedScoresFilter.params,
+ ...baseFilter.params,
...appliedFilter.params,
},
tags: {
@@ -245,17 +416,42 @@ const getDatasetRunsTableInternal = async <T>(
};
export const getDatasetRunsTableMetricsCh = async (
- opts: DatasetRunsMetricsTableQuery,
+ opts: Omit<DatasetRunsMetricsTableQuery, "select">,
): Promise<DatasetRunsMetrics[]> => {
// First get the metrics (latency, cost, counts)
const rows = await getDatasetRunsTableInternal<DatasetRunsMetricsRecordType>({
...opts,
+ select: "metrics",
tags: { kind: "list" },
});
return rows.map(convertDatasetRunsMetricsRecord);
};
+export const getDatasetRunsTableRowsCh = async (
+ opts: Omit<DatasetRunsMetricsTableQuery, "select">,
+): Promise<DatasetRunsRows[]> => {
+ const rows = await getDatasetRunsTableInternal<DatasetRunsRowsRecordType>({
+ ...opts,
+ select: "rows",
+ tags: { kind: "list" },
+ });
+
+ return rows.map(convertDatasetRunsRowsRecord);
+};
+
+export const getDatasetRunsTableCountCh = async (
+ opts: Omit<DatasetRunsMetricsTableQuery, "select">,
+): Promise<number> => {
+ const rows = await getDatasetRunsTableInternal<{ count: string }>({
+ ...opts,
+ select: "count",
+ tags: { kind: "list" },
+ });
+
+ return Number(rows[0]?.count);
+};
+
const getDatasetRunItemsTableInternal = async <T>(
opts: DatasetRunItemsTableQuery & {
select: "count" | "rows";
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 070685e73e..8a6e9a25ed 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -529,12 +529,27 @@ export const getScoresForObservations = async <
export const getRunScoresGroupedByNameSourceType = async (
projectId: string,
datasetRunIds: string[],
- timestamp: Date | undefined,
+ timestampFilter?: FilterState,
) => {
if (datasetRunIds.length === 0) {
return [];
}
+ const chFilter = timestampFilter
+ ? createFilterFromFilterState(timestampFilter, [
+ {
+ uiTableName: "Timestamp",
+ uiTableId: "timestamp",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "timestamp",
+ },
+ ])
+ : undefined;
+
+ const timestampFilterRes = chFilter
+ ? new FilterList(chFilter).apply()
+ : undefined;
+
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
@@ -544,7 +559,7 @@ export const getRunScoresGroupedByNameSourceType = async (
data_type
from scores s
WHERE s.project_id = {projectId: String}
- ${timestamp ? `AND s.timestamp >= {timestamp: DateTime64(3)}` : ""}
+ ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
AND s.dataset_run_id IN ({datasetRunIds: Array(String)})
GROUP BY name, source, data_type
ORDER BY count() desc
@@ -559,9 +574,7 @@ export const getRunScoresGroupedByNameSourceType = async (
query: query,
params: {
projectId: projectId,
- ...(timestamp
- ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
- : {}),
+ ...(timestampFilterRes ? timestampFilterRes.params : {}),
datasetRunIds: datasetRunIds,
},
tags: {
diff --git a/packages/shared/src/tableDefinitions/datasetRunsTable.ts b/packages/shared/src/tableDefinitions/datasetRunsTable.ts
new file mode 100644
index 0000000000..924f7f08a9
--- /dev/null
+++ b/packages/shared/src/tableDefinitions/datasetRunsTable.ts
@@ -0,0 +1,75 @@
+import { type ColumnDefinition, type MultiValueOption } from "..";
+import { formatColumnOptions } from "./typeHelpers";
+import { datasetRunsTableUiColumnDefinitions } from "./mapDatasetRunsTable";
+
+/**
+ * Type representing all possible dataset run filter column IDs
+ */
+type ExtractLiterals<T> = T extends readonly { uiTableName: infer U }[]
+ ? U
+ : never;
+
+type DatasetRunFilterColumnLiterals = ExtractLiterals<
+ typeof datasetRunsTableUiColumnDefinitions
+>;
+
+/**
+ * Columns that can be filtered using basic PostgreSQL dataset run data
+ * (don't require aggregated metrics from ClickHouse)
+ */
+const CLICKHOUSE_FILTER_COLUMNS: DatasetRunFilterColumnLiterals[] = [
+ "Scores (categorical)",
+ "Scores (numeric)",
+];
+const CLICKHOUSE_FILTER_COLUMNS_SET = new Set(CLICKHOUSE_FILTER_COLUMNS);
+
+/**
+ * Returns true if the dataset run filter column requires DRI metrics from ClickHouse.
+ *
+ * This function determines data source requirements by checking if the column
+ * needs aggregated metrics that are only available in ClickHouse dataset_run_items_rmt.
+ *
+ * @param column - The dataset run filter column ID to check
+ * @returns true if requires ClickHouse DRI metrics, false if PostgreSQL data is sufficient
+ */
+export function isClickhouseFilterColumn(column: string): boolean {
+ return CLICKHOUSE_FILTER_COLUMNS_SET.has(column);
+}
+
+export const datasetRunsTableCols: ColumnDefinition[] = [
+ {
+ name: "Scores (numeric)",
+ id: "agg_scores_avg",
+ type: "numberObject",
+ internal: "agg_scores_avg",
+ nullable: true,
+ },
+ {
+ name: "Scores (categorical)",
+ id: "agg_score_categories",
+ type: "categoryOptions",
+ internal: "agg_score_categories",
+ options: [], // to be filled in at runtime
+ nullable: true,
+ },
+];
+
+export type DatasetRunsOptions = {
+ agg_scores_avg?: Array<string>;
+ agg_score_categories?: Array<MultiValueOption>;
+};
+
+export function datasetRunsTableColsWithOptions(
+ options?: DatasetRunsOptions,
+ cols: ColumnDefinition[] = datasetRunsTableCols,
+): ColumnDefinition[] {
+ return cols.map((col) => {
+ if (col.id === "agg_scores_avg") {
+ return formatColumnOptions(col, options?.agg_scores_avg ?? []);
+ }
+ if (col.id === "agg_score_categories") {
+ return formatColumnOptions(col, options?.agg_score_categories ?? []);
+ }
+ return col;
+ });
+}
diff --git a/packages/shared/src/tableDefinitions/index.ts b/packages/shared/src/tableDefinitions/index.ts
index a32ace1747..4c7ab8cc3c 100644
--- a/packages/shared/src/tableDefinitions/index.ts
+++ b/packages/shared/src/tableDefinitions/index.ts
@@ -3,3 +3,5 @@ export * from "./types";
export * from "./mapDashboards";
export * from "./promptsTable";
export * from "./datasetItemsTable";
+export * from "./mapDatasetRunsTable";
+export * from "./datasetRunsTable";
diff --git a/packages/shared/src/tableDefinitions/mapDatasetRunsTable.ts b/packages/shared/src/tableDefinitions/mapDatasetRunsTable.ts
new file mode 100644
index 0000000000..c043083394
--- /dev/null
+++ b/packages/shared/src/tableDefinitions/mapDatasetRunsTable.ts
@@ -0,0 +1,28 @@
+import { UiColumnMappings } from "./types";
+
+export const datasetRunsTableUiColumnDefinitions: UiColumnMappings = [
+ {
+ uiTableName: "Dataset Run ID",
+ uiTableId: "id",
+ clickhouseTableName: "dataset_run_items_rmt",
+ clickhouseSelect: "drm.dataset_run_id",
+ },
+ {
+ uiTableName: "Created At",
+ uiTableId: "createdAt",
+ clickhouseTableName: "dataset_run_items_rmt",
+ clickhouseSelect: "drm.dataset_run_created_at",
+ },
+ {
+ uiTableName: "Scores (numeric)",
+ uiTableId: "agg_scores_avg",
+ clickhouseTableName: "dataset_run_items_rmt",
+ clickhouseSelect: "sa.scores_avg",
+ },
+ {
+ uiTableName: "Scores (categorical)",
+ uiTableId: "agg_score_categories",
+ clickhouseTableName: "dataset_run_items_rmt",
+ clickhouseSelect: "sa.score_categories",
+ },
+];
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 6c49036d02..a858b547ea 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -38,4 +38,5 @@ export type TableName =
| "users"
| "eval_configs"
| "dataset_items"
- | "job_executions";
+ | "job_executions"
+ | "dataset_runs";
diff --git a/web/src/__tests__/async/dataset-service.servertest.ts b/web/src/__tests__/async/dataset-service.servertest.ts
index b8272ccf42..440d073432 100644
--- a/web/src/__tests__/async/dataset-service.servertest.ts
+++ b/web/src/__tests__/async/dataset-service.servertest.ts
@@ -4,7 +4,6 @@ import {
createObservationsCh,
createScoresCh,
createTracesCh,
- type DatasetRunsMetrics,
getDatasetRunItemsByDatasetIdCh,
getDatasetRunsTableMetricsCh,
getScoresForDatasetRuns,
@@ -22,14 +21,11 @@ import {
getRunItemsByRunIdOrItemId,
} from "@/src/features/datasets/server/service";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
-import { isPresent } from "@langfuse/shared";
-import waitForExpect from "wait-for-expect";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
describe("Fetch datasets for UI presentation", () => {
- // test is flaky in CI, skipping for now
- it.skip("should fetch dataset runs for UI", async () => {
+ it("should fetch dataset runs for UI", async () => {
const datasetId = v4();
await prisma.dataset.create({
@@ -41,23 +37,27 @@ describe("Fetch datasets for UI presentation", () => {
});
const datasetRunId = v4();
const datasetRun2Id = v4();
+ const now = new Date();
+ const oneMinuteAgo = new Date(now.getTime() - 60 * 1000);
await prisma.datasetRuns.create({
data: {
id: datasetRunId,
- name: v4(),
+ name: "run1",
datasetId,
metadata: {},
projectId,
+ createdAt: now,
},
});
await prisma.datasetRuns.create({
data: {
id: datasetRun2Id,
- name: v4(),
+ name: "run2",
datasetId,
metadata: {},
projectId,
+ createdAt: oneMinuteAgo,
},
});
@@ -124,6 +124,8 @@ describe("Fetch datasets for UI presentation", () => {
project_id: projectId,
dataset_item_id: datasetItemId,
dataset_id: datasetId,
+ dataset_run_name: "run1",
+ dataset_run_created_at: now.getTime(),
});
const datasetRunItem2 = createDatasetRunItem({
@@ -134,6 +136,8 @@ describe("Fetch datasets for UI presentation", () => {
project_id: projectId,
dataset_item_id: datasetItemId2,
dataset_id: datasetId,
+ dataset_run_name: "run1",
+ dataset_run_created_at: now.getTime(),
});
const datasetRunItem3 = createDatasetRunItem({
@@ -144,6 +148,8 @@ describe("Fetch datasets for UI presentation", () => {
project_id: projectId,
dataset_item_id: datasetItemId3,
dataset_id: datasetId,
+ dataset_run_name: "run1",
+ dataset_run_created_at: now.getTime(),
});
const datasetRunItem4 = createDatasetRunItem({
@@ -154,6 +160,8 @@ describe("Fetch datasets for UI presentation", () => {
project_id: projectId,
dataset_item_id: datasetItemId4,
dataset_id: datasetId,
+ dataset_run_name: "run2",
+ dataset_run_created_at: oneMinuteAgo.getTime(),
});
await createDatasetRunItemsCh([
@@ -240,99 +248,63 @@ describe("Fetch datasets for UI presentation", () => {
});
await createScoresCh([score, score2, score3]);
- const limit = 10;
- const page = 0;
-
- let allRuns: any[] = [];
- let firstRun: any | undefined;
-
- await waitForExpect(async () => {
- // Get all runs from PostgreSQL and merge with ClickHouse metrics to maintain consistent count
- const [runsWithMetrics, allRunsBasicInfo] = await Promise.all([
- // Get runs that have metrics (only runs with dataset_run_items_rmt)
- getDatasetRunsTableMetricsCh({
- projectId: projectId,
- datasetId: datasetId,
- limit: limit,
- offset: page * limit,
- }),
- // Get basic info for all runs to ensure we return all runs, even those without dataset_run_items_rmt
- prisma.datasetRuns.findMany({
- where: {
- datasetId: datasetId,
- projectId: projectId,
- },
- select: {
- id: true,
- name: true,
- description: true,
- metadata: true,
- createdAt: true,
- datasetId: true,
- projectId: true,
- },
- take: limit,
- skip: page * limit,
- orderBy: {
- createdAt: "desc",
- },
- }),
- ]);
-
- // Create lookup map for runs that have metrics
- const metricsLookup = new Map<string, DatasetRunsMetrics>(
- runsWithMetrics.map((run) => [run.id, run]),
- );
+ // Get runs that have metrics (only runs with dataset_run_items_rmt)
+ const runsWithMetrics = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [datasetRunId, datasetRun2Id],
+ filter: [],
+ });
- // Only fetch scores for runs that have metrics (runs without dataset_run_items_rmt won't have trace scores)
- const runsWithMetricsIds = runsWithMetrics.map((run) => run.id);
- const [traceScores, runScores] = await Promise.all([
- runsWithMetricsIds.length > 0
- ? getTraceScoresForDatasetRuns(projectId, runsWithMetricsIds)
- : [],
- getScoresForDatasetRuns({
- projectId: projectId,
- runIds: allRunsBasicInfo.map((run) => run.id),
- includeHasMetadata: true,
- excludeMetadata: false,
- }),
- ]);
+ // Only fetch scores for runs that have metrics (runs without dataset_run_items_rmt won't have trace scores)
+ const runsWithMetricsIds = runsWithMetrics.map((run) => run.id);
+ const [traceScores, runScores] = await Promise.all([
+ runsWithMetricsIds.length > 0
+ ? getTraceScoresForDatasetRuns(projectId, runsWithMetricsIds)
+ : [],
+ getScoresForDatasetRuns({
+ projectId: projectId,
+ runIds: runsWithMetrics.map((run) => run.id),
+ includeHasMetadata: true,
+ excludeMetadata: false,
+ }),
+ ]);
- // Merge all runs: use metrics where available, defaults otherwise
- const runs = allRunsBasicInfo.map((run) => {
- const metrics = metricsLookup.get(run.id);
-
- return {
- ...run,
- // Use ClickHouse metrics if available, otherwise use defaults for runs without dataset_run_items_rmt
- countRunItems: metrics?.countRunItems ?? 0,
- avgTotalCost: metrics?.avgTotalCost ?? null,
- avgLatency: metrics?.avgLatency ?? null,
- scores: aggregateScores(
- traceScores.filter((s) => s.datasetRunId === run.id),
- ),
- runScores: aggregateScores(
- runScores.filter((s) => s.datasetRunId === run.id),
- ),
- };
- });
+ // Merge all runs: use metrics where available, defaults otherwise
+ const allRuns = runsWithMetrics.map((run) => {
+ return {
+ id: run.id,
+ name: run.name,
+ // Use ClickHouse metrics if available, otherwise use defaults for runs without dataset_run_items_rmt
+ countRunItems: run.countRunItems ?? 0,
+ avgTotalCost: run.avgTotalCost ?? null,
+ avgLatency: run.avgLatency ?? null,
+ scores: aggregateScores(
+ traceScores.filter((s) => s.datasetRunId === run.id),
+ ),
+ runScores: aggregateScores(
+ runScores.filter((s) => s.datasetRunId === run.id),
+ ),
+ };
+ });
- allRuns = runs;
- expect(allRuns).toHaveLength(2);
+ expect(allRuns).toHaveLength(2);
- firstRun = allRuns.find((run) => run.id === datasetRunId);
- expect(firstRun).toBeDefined();
- if (!firstRun) {
- throw new Error("first run is not defined");
- }
- expect(firstRun.id).toEqual(datasetRunId);
+ // Verify runs are returned in chronological order (oldest first, most recent last)
+ expect(allRuns[0].id).toEqual(datasetRunId); // First run (older)
+ expect(allRuns[1].id).toEqual(datasetRun2Id); // Second run (more recent)
+ expect(allRuns[0].name).toEqual("run1");
+ expect(allRuns[1].name).toEqual("run2");
- expect(firstRun.description).toBeNull();
- expect(firstRun.metadata).toEqual({});
+ const firstRun = allRuns.find((run) => run.id === datasetRunId);
+ expect(firstRun).toBeDefined();
+ if (!firstRun) {
+ throw new Error("first run is not defined");
+ }
+ expect(firstRun.id).toEqual(datasetRunId);
- expect(firstRun.avgLatency).toBeGreaterThanOrEqual(10800);
- expect(firstRun.avgTotalCost?.toString()).toStrictEqual("275");
- }, 10_000);
+ expect(firstRun.avgLatency).toBeGreaterThanOrEqual(10800);
+ expect(firstRun.avgTotalCost?.toString()).toStrictEqual("275");
const expectedObject = {
[`${scoreName.replaceAll("-", "_")}-API-NUMERIC`]: {
@@ -363,14 +335,12 @@ describe("Fetch datasets for UI presentation", () => {
}
expect(secondRun.id).toEqual(datasetRun2Id);
- expect(secondRun.description).toBeNull();
- expect(secondRun.metadata).toEqual({});
expect(secondRun.avgLatency).toBeGreaterThanOrEqual(1);
expect(secondRun.avgLatency).toBeLessThanOrEqual(1.002);
expect(secondRun.avgTotalCost?.toString()).toStrictEqual("300");
expect(JSON.stringify(secondRun.scores)).toEqual(JSON.stringify({}));
- }, 10_000);
+ });
it("should test that dataset runs can link to the same traces", async () => {
const datasetId = v4();
@@ -453,50 +423,13 @@ describe("Fetch datasets for UI presentation", () => {
await createScoresCh([score]);
- const limit = 10;
- const page = 0;
-
- // Get all runs from PostgreSQL and merge with ClickHouse metrics to maintain consistent count
- const [runsWithMetrics, allRunsBasicInfo] = await Promise.all([
- // Get runs that have metrics (only runs with dataset_run_items_rmt)
- getDatasetRunsTableMetricsCh({
- projectId: projectId,
- datasetId: datasetId,
- limit: limit,
- offset: isPresent(page) && isPresent(limit) ? page * limit : undefined,
- }),
- // Get basic info for all runs to ensure we return all runs, even those without dataset_run_items_rmt
- prisma.datasetRuns.findMany({
- where: {
- datasetId: datasetId,
- projectId: projectId,
- },
- select: {
- id: true,
- name: true,
- description: true,
- metadata: true,
- createdAt: true,
- datasetId: true,
- projectId: true,
- },
- ...(isPresent(limit) && {
- take: limit,
- }),
- ...(isPresent(page) &&
- isPresent(limit) && {
- skip: page * limit,
- }),
- orderBy: {
- createdAt: "desc",
- },
- }),
- ]);
-
- // Create lookup map for runs that have metrics
- const metricsLookup = new Map<string, DatasetRunsMetrics>(
- runsWithMetrics.map((run) => [run.id, run]),
- );
+ // Get runs that have metrics (only runs with dataset_run_items_rmt)
+ const runsWithMetrics = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [datasetRunId, datasetRun2Id],
+ filter: [],
+ });
// Only fetch scores for runs that have metrics (runs without dataset_run_items_rmt won't have trace scores)
const runsWithMetricsIds = runsWithMetrics.map((run) => run.id);
@@ -506,22 +439,21 @@ describe("Fetch datasets for UI presentation", () => {
: [],
getScoresForDatasetRuns({
projectId: projectId,
- runIds: allRunsBasicInfo.map((run) => run.id),
+ runIds: runsWithMetrics.map((run) => run.id),
includeHasMetadata: true,
excludeMetadata: false,
}),
]);
// Merge all runs: use metrics where available, defaults otherwise
- const allRuns = allRunsBasicInfo.map((run) => {
- const metrics = metricsLookup.get(run.id);
-
+ const allRuns = runsWithMetrics.map((run) => {
return {
- ...run,
+ id: run.id,
+ name: run.name,
// Use ClickHouse metrics if available, otherwise use defaults for runs without dataset_run_items_rmt
- countRunItems: metrics?.countRunItems ?? 0,
- avgTotalCost: metrics?.avgTotalCost ?? null,
- avgLatency: metrics?.avgLatency ?? null,
+ countRunItems: run.countRunItems ?? 0,
+ avgTotalCost: run.avgTotalCost ?? null,
+ avgLatency: run.avgLatency ?? null,
scores: aggregateScores(
traceScores.filter((s) => s.datasetRunId === run.id),
),
@@ -540,9 +472,6 @@ describe("Fetch datasets for UI presentation", () => {
}
expect(firstRun.id).toEqual(datasetRunId);
- expect(firstRun.description).toBeNull();
- expect(firstRun.metadata).toEqual({});
-
expect(firstRun.avgLatency).toBeGreaterThanOrEqual(0);
expect(firstRun.avgTotalCost?.toString()).toStrictEqual("0");
@@ -568,14 +497,615 @@ describe("Fetch datasets for UI presentation", () => {
}
expect(secondRun.id).toEqual(datasetRun2Id);
- expect(secondRun.description).toBeNull();
- expect(secondRun.metadata).toEqual({});
expect(secondRun.avgLatency).toEqual(0);
expect(secondRun.avgTotalCost?.toString()).toStrictEqual("0");
expect(firstRun.scores).toEqual(expectedObject);
});
+ describe("Dataset Run Score Filtering", () => {
+ it("should filter dataset runs by numeric scores", async () => {
+ const datasetId = v4();
+
+ await prisma.dataset.create({
+ data: {
+ id: datasetId,
+ name: v4(),
+ projectId: projectId,
+ },
+ });
+
+ // Create dataset runs
+ const highScoreRunId = v4();
+ const lowScoreRunId = v4();
+ const noScoreRunId = v4();
+
+ await prisma.datasetRuns.create({
+ data: {
+ id: highScoreRunId,
+ name: "high-accuracy-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ });
+
+ await prisma.datasetRuns.create({
+ data: {
+ id: lowScoreRunId,
+ name: "low-accuracy-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ });
+
+ await prisma.datasetRuns.create({
+ data: {
+ id: noScoreRunId,
+ name: "no-score-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ });
+
+ // Create dataset items
+ const itemId1 = v4();
+ const itemId2 = v4();
+ const itemId3 = v4();
+
+ await prisma.datasetItem.createMany({
+ data: [
+ { id: itemId1, datasetId, metadata: {}, projectId },
+ { id: itemId2, datasetId, metadata: {}, projectId },
+ { id: itemId3, datasetId, metadata: {}, projectId },
+ ],
+ });
+
+ // Create traces and observations
+ const traceId1 = v4();
+ const traceId2 = v4();
+ const traceId3 = v4();
+
+ // Create dataset run items
+ const runItem1 = createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: highScoreRunId,
+ trace_id: traceId1,
+ project_id: projectId,
+ dataset_item_id: itemId1,
+ dataset_id: datasetId,
+ dataset_run_name: "high-accuracy-run",
+ });
+
+ const runItem2 = createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: lowScoreRunId,
+ trace_id: traceId2,
+ project_id: projectId,
+ dataset_item_id: itemId2,
+ dataset_id: datasetId,
+ dataset_run_name: "low-accuracy-run",
+ });
+
+ const runItem3 = createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: noScoreRunId,
+ trace_id: traceId3,
+ project_id: projectId,
+ dataset_item_id: itemId3,
+ dataset_id: datasetId,
+ dataset_run_name: "no-score-run",
+ });
+
+ await createDatasetRunItemsCh([runItem1, runItem2, runItem3]);
+
+ // Create observations for latency calculation
+ const observation1 = createObservation({
+ trace_id: traceId1,
+ project_id: projectId,
+ start_time: new Date().getTime() - 2000,
+ end_time: new Date().getTime() - 1000,
+ });
+
+ const observation2 = createObservation({
+ trace_id: traceId2,
+ project_id: projectId,
+ start_time: new Date().getTime() - 3000,
+ end_time: new Date().getTime() - 1000,
+ });
+
+ const observation3 = createObservation({
+ trace_id: traceId3,
+ project_id: projectId,
+ start_time: new Date().getTime() - 1000,
+ end_time: new Date().getTime(),
+ });
+
+ await createObservationsCh([observation1, observation2, observation3]);
+
+ // Create scores with different values for the same score name
+ const highAccuracyScore = createTraceScore({
+ id: v4(),
+ trace_id: traceId1,
+ project_id: projectId,
+ name: "accuracy",
+ value: 0.95, // High accuracy
+ });
+
+ const lowAccuracyScore = createTraceScore({
+ id: v4(),
+ trace_id: traceId2,
+ project_id: projectId,
+ name: "accuracy",
+ value: 0.65, // Low accuracy
+ });
+
+ const highPrecisionScore = createTraceScore({
+ id: v4(),
+ trace_id: traceId1,
+ project_id: projectId,
+ name: "precision",
+ value: 0.88,
+ });
+
+ // No scores for traceId3 to test filtering behavior
+
+ await createScoresCh([
+ highAccuracyScore,
+ lowAccuracyScore,
+ highPrecisionScore,
+ ]);
+
+ // Test 1: Filter for runs with accuracy > 0.8
+ const highAccuracyRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [highScoreRunId, lowScoreRunId, noScoreRunId],
+ filter: [
+ {
+ type: "numberObject" as const,
+ column: "agg_scores_avg",
+ key: "accuracy",
+ operator: ">" as const,
+ value: 0.8,
+ },
+ ],
+ });
+
+ expect(highAccuracyRuns).toHaveLength(1);
+ expect(highAccuracyRuns[0].id).toEqual(highScoreRunId);
+ expect(highAccuracyRuns[0].name).toEqual("high-accuracy-run");
+
+ // Test 2: Filter for runs with accuracy >= 0.65 (should include both)
+ const mediumAccuracyRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [highScoreRunId, lowScoreRunId, noScoreRunId],
+ filter: [
+ {
+ type: "numberObject" as const,
+ column: "agg_scores_avg",
+ key: "accuracy",
+ operator: ">=" as const,
+ value: 0.65,
+ },
+ ],
+ });
+
+ expect(mediumAccuracyRuns).toHaveLength(2);
+ const runIds = mediumAccuracyRuns.map((run) => run.id);
+ expect(runIds).toContain(highScoreRunId);
+ expect(runIds).toContain(lowScoreRunId);
+
+ // Test 3: Filter for runs with precision = 0.88
+ const precisionRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [highScoreRunId, lowScoreRunId, noScoreRunId],
+ filter: [
+ {
+ type: "numberObject" as const,
+ column: "agg_scores_avg",
+ key: "precision",
+ operator: "=" as const,
+ value: 0.88,
+ },
+ ],
+ });
+
+ expect(precisionRuns).toHaveLength(1);
+ expect(precisionRuns[0].id).toEqual(highScoreRunId);
+ });
+
+ it("should filter dataset runs by categorical scores", async () => {
+ const datasetId = v4();
+
+ await prisma.dataset.create({
+ data: {
+ id: datasetId,
+ name: v4(),
+ projectId: projectId,
+ },
+ });
+
+ // Create dataset runs
+ const excellentRunId = v4();
+ const goodRunId = v4();
+ const poorRunId = v4();
+
+ await prisma.datasetRuns.createMany({
+ data: [
+ {
+ id: excellentRunId,
+ name: "excellent-quality-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ {
+ id: goodRunId,
+ name: "good-quality-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ {
+ id: poorRunId,
+ name: "poor-quality-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ ],
+ });
+
+ // Create dataset items and traces
+ const itemIds = [v4(), v4(), v4()];
+ const traceIds = [v4(), v4(), v4()];
+
+ await prisma.datasetItem.createMany({
+ data: itemIds.map((id) => ({ id, datasetId, metadata: {}, projectId })),
+ });
+
+ // Create dataset run items
+ const runItems = [
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: excellentRunId,
+ trace_id: traceIds[0],
+ project_id: projectId,
+ dataset_item_id: itemIds[0],
+ dataset_id: datasetId,
+ dataset_run_name: "excellent-quality-run",
+ }),
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: goodRunId,
+ trace_id: traceIds[1],
+ project_id: projectId,
+ dataset_item_id: itemIds[1],
+ dataset_id: datasetId,
+ dataset_run_name: "good-quality-run",
+ }),
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: poorRunId,
+ trace_id: traceIds[2],
+ project_id: projectId,
+ dataset_item_id: itemIds[2],
+ dataset_id: datasetId,
+ dataset_run_name: "poor-quality-run",
+ }),
+ ];
+
+ await createDatasetRunItemsCh(runItems);
+
+ // Create observations for each trace
+ const observations = traceIds.map((traceId) =>
+ createObservation({
+ trace_id: traceId,
+ project_id: projectId,
+ start_time: new Date().getTime() - 1000,
+ end_time: new Date().getTime(),
+ }),
+ );
+
+ await createObservationsCh(observations);
+
+ // Create categorical scores
+ const qualityScores = [
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[0],
+ project_id: projectId,
+ name: "quality",
+ data_type: "CATEGORICAL",
+ string_value: "excellent",
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[1],
+ project_id: projectId,
+ name: "quality",
+ data_type: "CATEGORICAL",
+ string_value: "good",
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[2],
+ project_id: projectId,
+ name: "quality",
+ data_type: "CATEGORICAL",
+ string_value: "poor",
+ }),
+ ];
+
+ // Add sentiment scores for more complex filtering
+ const sentimentScores = [
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[0],
+ project_id: projectId,
+ name: "sentiment",
+ data_type: "CATEGORICAL",
+ string_value: "positive",
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[1],
+ project_id: projectId,
+ name: "sentiment",
+ data_type: "CATEGORICAL",
+ string_value: "neutral",
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[2],
+ project_id: projectId,
+ name: "sentiment",
+ data_type: "CATEGORICAL",
+ string_value: "negative",
+ }),
+ ];
+
+ await createScoresCh([...qualityScores, ...sentimentScores]);
+
+ // Test: Filter for high quality runs (excellent or good)
+ const highQualityRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [excellentRunId, goodRunId, poorRunId],
+ filter: [
+ {
+ type: "categoryOptions" as const,
+ column: "agg_score_categories",
+ key: "quality",
+ operator: "any of" as const,
+ value: ["excellent", "good"],
+ },
+ ],
+ });
+
+ expect(highQualityRuns).toHaveLength(2);
+ const highQualityIds = highQualityRuns.map((run) => run.id);
+ expect(highQualityIds).toContain(excellentRunId);
+ expect(highQualityIds).toContain(goodRunId);
+
+ // Test: Filter for runs that are NOT poor quality
+ const notPoorRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [excellentRunId, goodRunId, poorRunId],
+ filter: [
+ {
+ type: "categoryOptions" as const,
+ column: "agg_score_categories",
+ key: "quality",
+ operator: "none of" as const,
+ value: ["poor"],
+ },
+ ],
+ });
+
+ expect(notPoorRuns).toHaveLength(2);
+ const notPoorIds = notPoorRuns.map((run) => run.id);
+ expect(notPoorIds).toContain(excellentRunId);
+ expect(notPoorIds).toContain(goodRunId);
+
+ // Test: Filter for positive sentiment
+ const positiveSentimentRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [excellentRunId, goodRunId, poorRunId],
+ filter: [
+ {
+ type: "categoryOptions" as const,
+ column: "agg_score_categories",
+ key: "sentiment",
+ operator: "any of" as const,
+ value: ["positive"],
+ },
+ ],
+ });
+
+ expect(positiveSentimentRuns).toHaveLength(1);
+ expect(positiveSentimentRuns[0].id).toEqual(excellentRunId);
+ });
+
+ it("should combine score filters with other filters", async () => {
+ const datasetId = v4();
+
+ await prisma.dataset.create({
+ data: {
+ id: datasetId,
+ name: v4(),
+ projectId: projectId,
+ },
+ });
+
+ // Create dataset runs with specific names and times
+ const recentRunId = v4();
+ const oldRunId = v4();
+
+ const recentDate = new Date();
+ const oldDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); // 7 days ago
+
+ await prisma.datasetRuns.create({
+ data: {
+ id: recentRunId,
+ name: "recent-high-accuracy",
+ datasetId,
+ metadata: { version: "2.0" },
+ projectId,
+ createdAt: recentDate,
+ },
+ });
+
+ await prisma.datasetRuns.create({
+ data: {
+ id: oldRunId,
+ name: "old-high-accuracy",
+ datasetId,
+ metadata: { version: "1.0" },
+ projectId,
+ createdAt: oldDate,
+ },
+ });
+
+ // Create dataset items and traces
+ const itemIds = [v4(), v4()];
+ const traceIds = [v4(), v4()];
+
+ await prisma.datasetItem.createMany({
+ data: itemIds.map((id) => ({ id, datasetId, metadata: {}, projectId })),
+ });
+
+ // Create dataset run items
+ const runItems = [
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: recentRunId,
+ trace_id: traceIds[0],
+ project_id: projectId,
+ dataset_item_id: itemIds[0],
+ dataset_id: datasetId,
+ dataset_run_name: "recent-high-accuracy",
+ created_at: recentDate.getTime(),
+ }),
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: oldRunId,
+ trace_id: traceIds[1],
+ project_id: projectId,
+ dataset_item_id: itemIds[1],
+ dataset_id: datasetId,
+ dataset_run_name: "old-high-accuracy",
+ created_at: oldDate.getTime(),
+ }),
+ ];
+
+ await createDatasetRunItemsCh(runItems);
+
+ // Create observations with different costs
+ const observations = [
+ createObservation({
+ trace_id: traceIds[0],
+ project_id: projectId,
+ start_time: new Date().getTime() - 1000,
+ end_time: new Date().getTime(),
+ total_cost: 100, // Higher cost
+ }),
+ createObservation({
+ trace_id: traceIds[1],
+ project_id: projectId,
+ start_time: new Date().getTime() - 1000,
+ end_time: new Date().getTime(),
+ total_cost: 50, // Lower cost
+ }),
+ ];
+
+ await createObservationsCh(observations);
+
+ // Create high accuracy scores for both runs
+ const scores = [
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[0],
+ project_id: projectId,
+ name: "accuracy",
+ value: 0.92,
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[1],
+ project_id: projectId,
+ name: "accuracy",
+ value: 0.94,
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[0],
+ project_id: projectId,
+ name: "sentiment",
+ data_type: "CATEGORICAL",
+ string_value: "positive",
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ // Test: Combine numeric score filter with category filter
+ const recentHighAccuracyRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [recentRunId, oldRunId],
+ filter: [
+ {
+ type: "numberObject" as const,
+ column: "agg_scores_avg",
+ key: "accuracy",
+ operator: ">=" as const,
+ value: 0.9,
+ },
+ {
+ type: "categoryOptions" as const,
+ column: "agg_score_categories",
+ key: "sentiment",
+ operator: "any of" as const,
+ value: ["positive"],
+ },
+ ],
+ });
+
+ expect(recentHighAccuracyRuns).toHaveLength(1);
+ expect(recentHighAccuracyRuns[0].id).toEqual(recentRunId);
+ expect(recentHighAccuracyRuns[0].name).toEqual("recent-high-accuracy");
+
+ // Test: All high accuracy runs (should return both)
+ const allHighAccuracyRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [recentRunId, oldRunId],
+ filter: [
+ {
+ type: "numberObject" as const,
+ column: "agg_scores_avg",
+ key: "accuracy",
+ operator: ">=" as const,
+ value: 0.9,
+ },
+ ],
+ });
+
+ expect(allHighAccuracyRuns).toHaveLength(2);
+ const allIds = allHighAccuracyRuns.map((run) => run.id);
+ expect(allIds).toContain(recentRunId);
+ expect(allIds).toContain(oldRunId);
+ });
+ });
+
it("should fetch dataset run items for UI", async () => {
const datasetId = v4();
diff --git a/web/src/features/datasets/components/DatasetRunsTable.tsx b/web/src/features/datasets/components/DatasetRunsTable.tsx
index 2a64cc0a6a..cf7a6f59c0 100644
--- a/web/src/features/datasets/components/DatasetRunsTable.tsx
+++ b/web/src/features/datasets/components/DatasetRunsTable.tsx
@@ -10,7 +10,9 @@ import { useEffect, useMemo, useState } from "react";
import { usdFormatter } from "../../../utils/numbers";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
-import { type Prisma } from "@langfuse/shared";
+import { type Prisma, datasetRunsTableColsWithOptions } from "@langfuse/shared";
+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
+import { useDebounce } from "@/src/hooks/useDebounce";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { IOTableCell } from "@/src/components/ui/IOTableCell";
import {
@@ -189,6 +191,12 @@ export function DatasetRunsTable(props: {
});
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
+ const [userFilterState, setUserFilterState] = useQueryFilterState(
+ [],
+ "dataset_runs",
+ props.projectId,
+ );
+
const [rowHeight, setRowHeight] = useRowHeightLocalStorage(
"datasetRuns",
"s",
@@ -202,19 +210,45 @@ export function DatasetRunsTable(props: {
const { setScoreOptions } = props;
+ // Filter options for the table
+ const datasetRunsFilterOptionsResponse =
+ api.datasets.runFilterOptions.useQuery(
+ { projectId: props.projectId, datasetId: props.datasetId },
+ {
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ const datasetRunsFilterOptions = datasetRunsFilterOptionsResponse.data;
+
+ const transformedFilterOptions = useMemo(() => {
+ return datasetRunsTableColsWithOptions(datasetRunsFilterOptions);
+ }, [datasetRunsFilterOptions]);
+
+ const setFilterState = useDebounce(setUserFilterState);
+
const runs = api.datasets.runsByDatasetId.useQuery({
projectId: props.projectId,
datasetId: props.datasetId,
page: paginationState.pageIndex,
limit: paginationState.pageSize,
+ filter: userFilterState,
});
- const runsMetrics = api.datasets.runsByDatasetIdMetrics.useQuery({
- projectId: props.projectId,
- datasetId: props.datasetId,
- page: paginationState.pageIndex,
- limit: paginationState.pageSize,
- });
+ const runsMetrics = api.datasets.runsByDatasetIdMetrics.useQuery(
+ {
+ projectId: props.projectId,
+ datasetId: props.datasetId,
+ runIds: runs.data?.runs.map((r) => r.id) ?? [],
+ filter: userFilterState,
+ },
+ {
+ enabled: runs.isSuccess,
+ },
+ );
type DatasetsCoreOutput =
RouterOutput["datasets"]["runsByDatasetId"]["runs"][number];
@@ -248,7 +282,6 @@ export function DatasetRunsTable(props: {
projectId: props.projectId,
scoreColumnKey: "runItemScores",
showAggregateViewOnly: false,
- scoreColumnPrefix: "Aggregated",
});
const {
@@ -437,7 +470,7 @@ export function DatasetRunsTable(props: {
{
...getScoreGroupColumnProps(isColumnLoading, {
accessorKey: "runItemScores",
- header: "Aggregated Run Items Scores",
+ header: "Run Item Scores",
id: "runItemScores",
}),
columns: scoreColumns,
@@ -510,11 +543,7 @@ export function DatasetRunsTable(props: {
? usdFormatter(item.avgTotalCost.toNumber())
: usdFormatter(0),
runItemScores: item.scores
- ? verifyAndPrefixScoreDataAgainstKeys(
- scoreKeysAndProps,
- item.scores,
- "Aggregated",
- )
+ ? verifyAndPrefixScoreDataAgainstKeys(scoreKeysAndProps, item.scores)
: undefined,
runScores: item.runScores
? verifyAndPrefixScoreDataAgainstKeys(
@@ -615,6 +644,9 @@ export function DatasetRunsTable(props: {
>
<DataTableToolbar
columns={columns}
+ filterColumnDefinition={transformedFilterOptions}
+ filterState={userFilterState}
+ setFilterState={setFilterState}
columnVisibility={columnVisibility}
setColumnVisibility={setColumnVisibility}
columnOrder={columnOrder}
@@ -676,6 +708,9 @@ export function DatasetRunsTable(props: {
<>
<DataTableToolbar
columns={columns}
+ filterColumnDefinition={transformedFilterOptions}
+ filterState={userFilterState}
+ setFilterState={setFilterState}
columnVisibility={columnVisibility}
setColumnVisibility={setColumnVisibility}
columnOrder={columnOrder}
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index 82ed785600..9c1da20266 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -16,10 +16,13 @@ import {
type FilterState,
isPresent,
TracingSearchType,
+ timeFilter,
+ isClickhouseFilterColumn,
} from "@langfuse/shared";
import { TRPCError } from "@trpc/server";
import {
datasetRunsTableSchema,
+ datasetRunTableMetricsSchema,
fetchDatasetItems,
getRunItemsByRunIdOrItemId,
} from "@/src/features/datasets/server/service";
@@ -32,8 +35,11 @@ import {
getDatasetRunsTableMetricsCh,
getScoresForDatasetRuns,
getTraceScoresForDatasetRuns,
- type DatasetRunsMetrics,
getDatasetRunItemsCountCh,
+ getNumericScoresGroupedByName,
+ getCategoricalScoresGroupedByName,
+ getDatasetRunsTableRowsCh,
+ getDatasetRunsTableCountCh,
} from "@langfuse/shared/src/server";
import { createId as createCuid } from "@paralleldrive/cuid2";
import {
@@ -54,6 +60,22 @@ const formatDatasetItemData = (data: string | null | undefined) => {
}
};
+/**
+ * Determines whether the given filters require Dataset Run Items (DRI) metrics from ClickHouse.
+ *
+ * @param filters - Array of filter conditions to evaluate
+ * @returns true if any filter requires DRI metrics, false if using basic dataset run data is sufficient
+ */
+export const requiresClickhouseLookups = (filters: FilterState): boolean => {
+ if (filters.length === 0) {
+ return false;
+ }
+
+ return filters.some((filter) => {
+ return isClickhouseFilterColumn(filter.column);
+ });
+};
+
/**
* Adds a case-insensitive search condition to a Kysely query
* @param query The Kysely query to modify
@@ -273,90 +295,72 @@ export const datasetRouter = createTRPCRouter({
runsByDatasetId: protectedProjectProcedure
.input(datasetRunsTableSchema)
.query(async ({ input, ctx }) => {
- const [runs, totalRuns] = await Promise.all([
- await ctx.prisma.datasetRuns.findMany({
- where: {
- datasetId: input.datasetId,
+ // Use helper function to determine if we need DRI metrics
+ if (!requiresClickhouseLookups(input.filter ?? [])) {
+ const [runs, totalRuns] = await Promise.all([
+ await ctx.prisma.datasetRuns.findMany({
+ where: {
+ datasetId: input.datasetId,
+ projectId: input.projectId,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ take: input.limit,
+ skip:
+ isPresent(input.page) && isPresent(input.limit)
+ ? input.page * input.limit
+ : undefined,
+ }),
+ // dataset run items will continue to be stored in postgres
+ await ctx.prisma.datasetRuns.count({
+ where: {
+ datasetId: input.datasetId,
+ projectId: input.projectId,
+ },
+ }),
+ ]);
+
+ return {
+ totalRuns,
+ runs,
+ };
+ } else {
+ const [runs, totalRuns] = await Promise.all([
+ getDatasetRunsTableRowsCh({
projectId: input.projectId,
- },
- orderBy: {
- createdAt: "desc",
- },
- take: input.limit,
- skip:
- isPresent(input.page) && isPresent(input.limit)
- ? input.page * input.limit
- : undefined,
- }),
- // dataset run items will continue to be stored in postgres
- await ctx.prisma.datasetRuns.count({
- where: {
datasetId: input.datasetId,
+ filter: input.filter ?? [],
+ limit: isPresent(input.limit) ? input.limit : undefined,
+ offset:
+ isPresent(input.page) && isPresent(input.limit)
+ ? input.page * input.limit
+ : undefined,
+ }),
+ getDatasetRunsTableCountCh({
projectId: input.projectId,
- },
- }),
- ]);
+ datasetId: input.datasetId,
+ filter: input.filter ?? [],
+ }),
+ ]);
- return {
- totalRuns,
- runs,
- };
+ return {
+ totalRuns,
+ runs,
+ };
+ }
}),
runsByDatasetIdMetrics: protectedProjectProcedure
- .input(datasetRunsTableSchema)
- .query(async ({ input, ctx }) => {
- // Get all runs from PostgreSQL and merge with ClickHouse metrics to maintain consistent count
- const [runsWithMetrics, totalRuns, allRunsBasicInfo] = await Promise.all([
- // Get runs that have metrics (only runs with dataset_run_items_rmt)
- getDatasetRunsTableMetricsCh({
- projectId: input.projectId,
- datasetId: input.datasetId,
- limit: input.limit,
- offset:
- isPresent(input.page) && isPresent(input.limit)
- ? input.page * input.limit
- : undefined,
- }),
- // Count all runs (including those without dataset_run_items_rmt)
- ctx.prisma.datasetRuns.count({
- where: {
- datasetId: input.datasetId,
- projectId: input.projectId,
- },
- }),
- // Get basic info for all runs to ensure we return all runs, even those without dataset_run_items_rmt
- ctx.prisma.datasetRuns.findMany({
- where: {
- datasetId: input.datasetId,
- projectId: input.projectId,
- },
- select: {
- id: true,
- name: true,
- description: true,
- metadata: true,
- createdAt: true,
- datasetId: true,
- projectId: true,
- },
- ...(isPresent(input.limit) && {
- take: input.limit,
- }),
- ...(isPresent(input.page) &&
- isPresent(input.limit) && {
- skip: input.page * input.limit,
- }),
- orderBy: {
- createdAt: "desc",
- },
- }),
- ]);
-
- // Create lookup map for runs that have metrics
- const metricsLookup = new Map<string, DatasetRunsMetrics>(
- runsWithMetrics.map((run) => [run.id, run]),
- );
+ .input(datasetRunTableMetricsSchema)
+ .query(async ({ input }) => {
+ // Get runs that have metrics (only runs with dataset_run_items_rmt)
+ const runsWithMetrics = await getDatasetRunsTableMetricsCh({
+ projectId: input.projectId,
+ datasetId: input.datasetId,
+ runIds: input.runIds ?? [],
+ filter: input.filter ?? [],
+ });
// Only fetch scores for runs that have metrics (runs without dataset_run_items_rmt won't have trace scores)
const runsWithMetricsIds = runsWithMetrics.map((run) => run.id);
@@ -366,22 +370,21 @@ export const datasetRouter = createTRPCRouter({
: [],
getScoresForDatasetRuns({
projectId: input.projectId,
- runIds: allRunsBasicInfo.map((run) => run.id),
+ runIds: runsWithMetrics.map((run) => run.id),
includeHasMetadata: true,
excludeMetadata: false,
}),
]);
// Merge all runs: use metrics where available, defaults otherwise
- const allRuns = allRunsBasicInfo.map((run) => {
- const metrics = metricsLookup.get(run.id);
-
+ const allRuns = runsWithMetrics.map((run) => {
return {
- ...run,
+ id: run.id,
+ name: run.name,
// Use ClickHouse metrics if available, otherwise use defaults for runs without dataset_run_items_rmt
- countRunItems: metrics?.countRunItems ?? 0,
- avgTotalCost: metrics?.avgTotalCost ?? null,
- avgLatency: metrics?.avgLatency ?? null,
+ countRunItems: run.countRunItems ?? 0,
+ avgTotalCost: run.avgTotalCost ?? null,
+ avgLatency: run.avgLatency ?? null,
scores: aggregateScores(
traceScores.filter((s) => s.datasetRunId === run.id),
),
@@ -392,10 +395,38 @@ export const datasetRouter = createTRPCRouter({
});
return {
- totalRuns,
runs: allRuns,
};
}),
+
+ runFilterOptions: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ datasetId: z.string(),
+ timestampFilter: timeFilter.optional(),
+ }),
+ )
+ .query(async ({ input }) => {
+ const { timestampFilter } = input;
+
+ const [numericScoreNames, categoricalScoreNames] = await Promise.all([
+ getNumericScoresGroupedByName(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getCategoricalScoresGroupedByName(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ ]);
+
+ return {
+ agg_scores_avg: numericScoreNames.map((s) => s.name),
+ agg_score_categories: categoricalScoreNames,
+ };
+ }),
+
itemById: protectedProjectProcedure
.input(
z.object({
@@ -1210,7 +1241,14 @@ export const datasetRouter = createTRPCRouter({
const res = await getRunScoresGroupedByNameSourceType(
input.projectId,
datasetRuns.map((dr) => dr.id),
- dataset.createdAt,
+ [
+ {
+ column: "timestamp",
+ operator: ">=",
+ value: dataset.createdAt,
+ type: "datetime",
+ },
+ ],
);
return res.map(({ name, source, dataType }) => ({
key: composeAggregateScoreKey({ name, source, dataType }),
@@ -1363,7 +1401,6 @@ export const datasetRouter = createTRPCRouter({
success: true,
};
} catch (error) {
- console.log({ error });
if (error instanceof Error) {
return {
success: false,
diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.ts
index bf2ddc9677..58a5877717 100644
--- a/web/src/features/datasets/server/service.ts
+++ b/web/src/features/datasets/server/service.ts
@@ -8,6 +8,7 @@ import {
datasetItemFilterColumns,
type DatasetItem,
type TracingSearchType,
+ singleFilter,
} from "@langfuse/shared";
import { z } from "zod/v4";
import {
@@ -23,11 +24,27 @@ import Decimal from "decimal.js";
export const datasetRunsTableSchema = z.object({
projectId: z.string(),
datasetId: z.string(),
+ // LFE-6397: deprecated, remove runIds
runIds: z.array(z.string()).optional(),
+ // LFE-6397: remove optional
+ filter: z.array(singleFilter).optional(),
+ ...optionalPaginationZod,
+});
+
+export const datasetRunTableMetricsSchema = z.object({
+ projectId: z.string(),
+ datasetId: z.string(),
+ // LFE-6397: remove optional
+ runIds: z.array(z.string()).optional(),
+ filter: z.array(singleFilter),
+ // LFE-6397: deprecated, remove optional pagination
...optionalPaginationZod,
});
export type DatasetRunsTableInput = z.infer<typeof datasetRunsTableSchema>;
+export type DatasetRunTableMetricsInput = z.infer<
+ typeof datasetRunTableMetricsSchema
+>;
export type DatasetRunItemsTableInput = {
projectId: string;
diff --git a/web/src/features/filters/hooks/useFilterState.ts b/web/src/features/filters/hooks/useFilterState.ts
index f4b65522d5..64041c251b 100644
--- a/web/src/features/filters/hooks/useFilterState.ts
+++ b/web/src/features/filters/hooks/useFilterState.ts
@@ -6,6 +6,7 @@ import {
singleFilter,
sessionsViewCols,
promptsTableCols,
+ datasetRunsTableCols,
datasetItemFilterColumns,
} from "@langfuse/shared";
import { scoresTableCols } from "@/src/server/api/definitions/scoresTable";
@@ -143,6 +144,7 @@ const tableCols = {
eval_configs: evalConfigFilterColumns,
job_executions: evalExecutionsFilterCols,
dataset_items: datasetItemFilterColumns,
+ dataset_runs: datasetRunsTableCols,
widgets: [
{ id: "environment", name: "Environment" },
{ id: "traceName", name: "Trace Name" },
diff --git a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx
index 859f36a9fa..e4f87dedea 100644
--- a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx
+++ b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx
@@ -22,7 +22,7 @@ import { type SessionTableRow } from "@/src/components/table/use-cases/sessions"
const prefixScoreColKey = (
key: string,
- prefix: "Trace" | "Generation" | "Run-level" | "Aggregated",
+ prefix: "Trace" | "Generation" | "Run-level",
): string => `${prefix}-${key}`;
export const getScoreDataTypeIcon = (dataType: ScoreDataType): string => {
@@ -47,7 +47,7 @@ const parseScoreColumn = <
| SessionTableRow,
>(
col: ScoreData,
- prefix?: "Trace" | "Generation" | "Run-level" | "Aggregated",
+ prefix?: "Trace" | "Generation" | "Run-level",
): LangfuseColumnDef<T> => {
const { key, name, source, dataType } = col;
@@ -73,7 +73,7 @@ const parseScoreColumn = <
export function verifyAndPrefixScoreDataAgainstKeys(
scoreKeys: ScoreData[],
scoreData: ScoreAggregate,
- prefix?: "Trace" | "Generation" | "Run-level" | "Aggregated",
+ prefix?: "Trace" | "Generation" | "Run-level",
): ScoreAggregate {
if (!Boolean(scoreKeys.length)) return {};
let filteredScores: ScoreAggregate = {};
@@ -102,7 +102,7 @@ export const constructIndividualScoreColumns = <
scoreColumnProps: ScoreData[];
scoreColumnKey: keyof T & string;
showAggregateViewOnly?: boolean;
- scoreColumnPrefix?: "Trace" | "Generation" | "Run-level" | "Aggregated";
+ scoreColumnPrefix?: "Trace" | "Generation" | "Run-level";
cellsLoading?: boolean;
}): LangfuseColumnDef<T>[] => {
return scoreColumnProps.map((col) => {
diff --git a/web/src/features/scores/hooks/useIndividualScoreColumns.ts b/web/src/features/scores/hooks/useIndividualScoreColumns.ts
index 1a7cfa609f..ae9e956a2f 100644
--- a/web/src/features/scores/hooks/useIndividualScoreColumns.ts
+++ b/web/src/features/scores/hooks/useIndividualScoreColumns.ts
@@ -21,7 +21,7 @@ export function useIndividualScoreColumns<
scoreColumnKey: keyof T & string;
selectedFilterOption?: TableDateRangeOptions;
showAggregateViewOnly?: boolean;
- scoreColumnPrefix?: "Trace" | "Generation" | "Run-level" | "Aggregated";
+ scoreColumnPrefix?: "Trace" | "Generation" | "Run-level";
cellsLoading?: boolean;
scoreKeysAndPropsData?: RouterOutputs["scores"]["getScoreKeysAndProps"];
}) {
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx
index 3ce10b8e69..fc3c8944ba 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare.tsx
@@ -84,7 +84,8 @@ export default function DatasetCompare() {
{
projectId,
datasetId,
- runIds: runIds,
+ runIds: runIds ?? [],
+ filter: [],
},
{
enabled: runIds && runIds.length > 1,