Skip to content

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

feat(widgets): distinguish between available and called tools in filter (#13281)

Nimare3c741d3b59f
diff --git a/packages/shared/src/server/queries/clickhouse-sql/factory.ts b/packages/shared/src/server/queries/clickhouse-sql/factory.ts
index 07962f8f5c..277625f39c 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/factory.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/factory.ts
@@ -5,6 +5,7 @@ import { InvalidRequestError } from "../../../errors";
import { isValidTableName } from "../../clickhouse/schemaUtils";
import { logger } from "../../logger";
import {
+ findUiColumnMapping,
type ColumnDefinition,
type UiColumnMappings,
} from "../../../tableDefinitions";
@@ -173,10 +174,7 @@ const matchAndVerifyTracesUiColumn = (
uiTableDefinitions: UiColumnMappings,
) => {
// tries to match the column name to the clickhouse table name
- const uiTable = uiTableDefinitions.find(
- (col) =>
- col.uiTableName === filter.column || col.uiTableId === filter.column, // matches on the NAME of the column in the UI.
- );
+ const uiTable = findUiColumnMapping(uiTableDefinitions, filter.column);
if (!uiTable) {
const errorMessage = `Column ${filter.column} does not match a UI / CH table mapping.`;
diff --git a/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts b/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts
index b50d79876b..74c32d931a 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts
@@ -1,6 +1,9 @@
import z from "zod";
import { OrderByState } from "../../../interfaces/orderBy";
-import { UiColumnMappings } from "../../../tableDefinitions";
+import {
+ findUiColumnMapping,
+ UiColumnMappings,
+} from "../../../tableDefinitions";
import { InvalidRequestError } from "../../../errors";
import { logger } from "../../logger";
import type { OrderByDirection, OrderByEntry } from "./event-query-builder";
@@ -30,9 +33,7 @@ export function orderByToClickhouseSql(
Boolean(o),
)) {
// Get column definition to map column to internal name, e.g. "t.id"
- const col = tableColumns.find(
- (c) => c.uiTableName === ob.column || c.uiTableId === ob.column,
- );
+ const col = findUiColumnMapping(tableColumns, ob.column);
if (!col) {
logger.warn(`Invalid order by column: ${ob.column}`);
@@ -83,9 +84,7 @@ export function orderByToEntries(
for (const ob of orderBy.filter((o): o is OrderByStateNotNull =>
Boolean(o),
)) {
- const col = tableColumns.find(
- (c) => c.uiTableName === ob.column || c.uiTableId === ob.column,
- );
+ const col = findUiColumnMapping(tableColumns, ob.column);
if (!col) {
logger.warn(`Invalid order by column: ${ob.column}`);
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 42d3b3752a..7f61f077f3 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -23,6 +23,7 @@ import {
observationsTableUiColumnDefinitions,
} from "../tableMappings";
import { OrderByState } from "../../interfaces/orderBy";
+import { matchesUiColumnMapping } from "../../tableDefinitions";
import { getTracesByIds } from "./traces";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import {
@@ -704,15 +705,14 @@ const getObservationsTableInternal = async <T>(
// query optimisation: joining traces onto observations is expensive. Hence, only join if the UI table contains filters on traces.
const traceTableFilter = filter.filter((f) =>
- observationsTableTraceUiColumnDefinitions.some(
- (c) => c.uiTableId === f.column || c.uiTableName === f.column,
+ observationsTableTraceUiColumnDefinitions.some((c) =>
+ matchesUiColumnMapping(c, f.column),
),
);
const orderByTraces = orderBy
- ? observationsTableTraceUiColumnDefinitions.some(
- (c) =>
- c.uiTableId === orderBy.column || c.uiTableName === orderBy.column,
+ ? observationsTableTraceUiColumnDefinitions.some((c) =>
+ matchesUiColumnMapping(c, orderBy.column),
)
: undefined;
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 6ad68bfda3..5d2e5a57ad 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -52,6 +52,10 @@ import {
eventsExperiments,
} from "../queries/clickhouse-sql/query-fragments";
import { scoresTableCols } from "../../tableDefinitions/scoresTable";
+import {
+ findUiColumnMapping,
+ matchesUiColumnMapping,
+} from "../../tableDefinitions";
export const searchExistingAnnotationScore = async (
projectId: string,
@@ -751,10 +755,8 @@ export const getScoresGroupedByNameSourceType = async ({
// Extract event-level filter entries from the frontend filter state
const eventFilterState = filter.filter((filterEntry) =>
- scoresEventsFilterMapping.some(
- (col) =>
- col.uiTableName === filterEntry.column ||
- col.uiTableId === filterEntry.column,
+ scoresEventsFilterMapping.some((col) =>
+ matchesUiColumnMapping(col, filterEntry.column),
),
);
@@ -1294,21 +1296,21 @@ const getScoresUiGenericFromEvents = async <T>(props: {
// Trace-level filter entries from the frontend filter state
const traceFilterState = filter.filter((filterEntry) =>
- scoresTraceFilterEventsMapping.some(
- (col) =>
- col.uiTableName === filterEntry.column ||
- col.uiTableId === filterEntry.column,
+ scoresTraceFilterEventsMapping.some((col) =>
+ matchesUiColumnMapping(col, filterEntry.column),
),
);
- const orderByColumn = orderBy
- ? scoresTableUiColumnDefinitionsFromEvents.find(
- (c) =>
- (c.uiTableName === orderBy.column ||
- c.uiTableId === orderBy.column) &&
- c.clickhouseTableName === "traces",
+ const matchedOrderByColumn = orderBy
+ ? findUiColumnMapping(
+ scoresTableUiColumnDefinitionsFromEvents,
+ orderBy.column,
)
: null;
+ const orderByColumn =
+ matchedOrderByColumn?.clickhouseTableName === "traces"
+ ? matchedOrderByColumn
+ : null;
const needsTracesCTE = traceFilterState.length > 0 || !!orderByColumn;
diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.ts
index b261aaa304..4227bbfa73 100644
--- a/packages/shared/src/server/services/sessions-ui-table-events-service.ts
+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.ts
@@ -19,6 +19,7 @@ import {
import { queryClickhouse } from "../repositories";
import { sessionCols } from "../tableMappings/mapSessionTable";
import { sessionsViewCols } from "../../tableDefinitions/sessionsView";
+import { findUiColumnMapping } from "../../tableDefinitions";
import { parseClickhouseUTCDateTimeFormat } from "../repositories/clickhouse";
type SessionEventsBaseReturnType = {
@@ -186,10 +187,8 @@ const getSessionsTableFromEventsGeneric = async <T>(
const requiresScoresJoin =
sessionFilters.some((f) => f.clickhouseTable === "scores") ||
- sessionCols.find(
- (c) =>
- c.uiTableName === orderBy?.column || c.uiTableId === orderBy?.column,
- )?.clickhouseTableName === "scores";
+ findUiColumnMapping(sessionCols, orderBy?.column)?.clickhouseTableName ===
+ "scores";
// Build session_data CTE
const sessionsBuilder = eventsSessionsAggregation({
diff --git a/packages/shared/src/server/services/sessions-ui-table-service.ts b/packages/shared/src/server/services/sessions-ui-table-service.ts
index dc79758cf0..0f931e7a91 100644
--- a/packages/shared/src/server/services/sessions-ui-table-service.ts
+++ b/packages/shared/src/server/services/sessions-ui-table-service.ts
@@ -3,6 +3,7 @@ import { OrderByState } from "../../interfaces/orderBy";
import { sessionCols } from "../tableMappings/mapSessionTable";
import { FilterState } from "../../types";
import { sessionsViewCols } from "../../tableDefinitions/sessionsView";
+import { findUiColumnMapping } from "../../tableDefinitions";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { DateTimeFilter, FilterList, orderByToClickhouseSql } from "../queries";
@@ -216,10 +217,8 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
const requiresScoresJoin =
tracesFilter.find((f) => f.clickhouseTable === "scores") !== undefined ||
- sessionCols.find(
- (c) =>
- c.uiTableName === orderBy?.column || c.uiTableId === orderBy?.column,
- )?.clickhouseTableName === "scores";
+ findUiColumnMapping(sessionCols, orderBy?.column)?.clickhouseTableName ===
+ "scores";
const hasMetricsFilter =
tracesFilter.find((f) =>
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.ts
index 987c664655..1ce7c80ec4 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -1,6 +1,7 @@
import { OrderByState } from "../../interfaces/orderBy";
import { tracesTableUiColumnDefinitions } from "../tableMappings";
import { tracesTableCols } from "../../tableDefinitions/tracesTable";
+import { findUiColumnMapping } from "../../tableDefinitions";
import { FilterState } from "../../types";
import {
StringFilter,
@@ -269,18 +270,14 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {
const requiresScoresJoin =
tracesFilter.find((f) => f.clickhouseTable === "scores") !== undefined ||
- tracesTableUiColumnDefinitions.find(
- (c) =>
- c.uiTableName === orderBy?.column || c.uiTableId === orderBy?.column,
- )?.clickhouseTableName === "scores";
+ findUiColumnMapping(tracesTableUiColumnDefinitions, orderBy?.column)
+ ?.clickhouseTableName === "scores";
const requiresObservationsJoin =
tracesFilter.find((f) => f.clickhouseTable === "observations") !==
undefined ||
- tracesTableUiColumnDefinitions.find(
- (c) =>
- c.uiTableName === orderBy?.column || c.uiTableId === orderBy?.column,
- )?.clickhouseTableName === "observations";
+ findUiColumnMapping(tracesTableUiColumnDefinitions, orderBy?.column)
+ ?.clickhouseTableName === "observations";
const tracesFilterRes = tracesFilter.apply();
const scoresFilterRes = scoresFilter.apply();
diff --git a/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts b/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts
index 76a90ef51a..ef2d4e5e63 100644
--- a/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts
@@ -1,4 +1,7 @@
-import { UiColumnMappings } from "../../tableDefinitions";
+import {
+ matchesUiColumnMapping,
+ UiColumnMappings,
+} from "../../tableDefinitions";
import { DatasetRunItemDomain } from "../../domain/dataset-run-items";
export const datasetRunItemsTableUiColumnDefinitions: UiColumnMappings = [
@@ -52,9 +55,7 @@ export const mapDatasetRunItemFilterColumn = (
): unknown => {
const columnDef = datasetRunItemsTableUiColumnDefinitions.find(
(col) =>
- col.uiTableId === column ||
- col.uiTableName === column ||
- col.clickhouseSelect === column,
+ matchesUiColumnMapping(col, column) || col.clickhouseSelect === column,
);
if (!columnDef) {
throw new Error(`Unhandled column for dataset run items filter: ${column}`);
diff --git a/packages/shared/src/tableDefinitions/mapDashboards.ts b/packages/shared/src/tableDefinitions/mapDashboards.ts
index c929f57abe..29351c8721 100644
--- a/packages/shared/src/tableDefinitions/mapDashboards.ts
+++ b/packages/shared/src/tableDefinitions/mapDashboards.ts
@@ -103,7 +103,14 @@ export const dashboardColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "observations",
clickhouseSelect: "mapKeys(tool_definitions)",
uiTableId: "toolNames",
- uiTableName: "Tool Names",
+ uiTableName: "Tool Names (Available)",
+ aliases: ["Tool Names"],
+ },
+ {
+ clickhouseTableName: "observations",
+ clickhouseSelect: "tool_call_names",
+ uiTableId: "calledToolNames",
+ uiTableName: "Tool Names (Called)",
},
{
clickhouseTableName: "traces",
diff --git a/packages/shared/src/tableDefinitions/types.ts b/packages/shared/src/tableDefinitions/types.ts
index 7116fe943e..557fb3816c 100644
--- a/packages/shared/src/tableDefinitions/types.ts
+++ b/packages/shared/src/tableDefinitions/types.ts
@@ -1,15 +1,44 @@
-export type UiColumnMappings = readonly UiColumnMapping[];
-
-export type UiColumnMapping = Readonly<{
+export type UiColumnMatchable = Readonly<{
uiTableName: string;
uiTableId: string;
- clickhouseTableName: string;
- clickhouseSelect: string;
- clickhouseTypeOverwrite?: string;
- queryPrefix?: string;
- emptyEqualsNull?: boolean;
+ aliases?: readonly string[];
}>;
+export type UiColumnMappings = readonly UiColumnMapping[];
+
+export type UiColumnMapping = UiColumnMatchable &
+ Readonly<{
+ clickhouseTableName: string;
+ clickhouseSelect: string;
+ clickhouseTypeOverwrite?: string;
+ queryPrefix?: string;
+ emptyEqualsNull?: boolean;
+ }>;
+
+export const matchesUiColumnMapping = (
+ columnDef: UiColumnMatchable,
+ column: string | undefined,
+): boolean => {
+ if (column === undefined) {
+ return false;
+ }
+
+ return (
+ columnDef.uiTableId === column ||
+ columnDef.uiTableName === column ||
+ columnDef.aliases?.includes(column) === true
+ );
+};
+
+export const findUiColumnMapping = <T extends UiColumnMatchable>(
+ columnDefs: readonly T[],
+ column: string | undefined,
+): T | undefined => {
+ return columnDefs.find((columnDef) =>
+ matchesUiColumnMapping(columnDef, column),
+ );
+};
+
export type SingleValueOption = {
value: string;
count?: number;
diff --git a/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts b/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts
index 06c6991f3c..a5ed9e9c62 100644
--- a/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts
+++ b/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts
@@ -148,6 +148,36 @@ describe("createFilterFromFilterState filter type validation", () => {
).toThrow(InvalidRequestError);
});
+ it("matches UiColumnMapping aliases during backend filter resolution", () => {
+ const [result] = createFilterFromFilterState(
+ [
+ {
+ column: "Tool Names",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["create_ticket"],
+ },
+ ],
+ [
+ {
+ uiTableName: "Tool Names (Available)",
+ uiTableId: "toolNames",
+ aliases: ["Tool Names"],
+ clickhouseTableName: "observations",
+ clickhouseSelect: "mapKeys(tool_definitions)",
+ },
+ ],
+ );
+
+ const { query, params } = result.apply();
+ expect(query).toContain("mapKeys(tool_definitions)");
+ expect(params).toEqual(
+ expect.objectContaining({
+ [Object.keys(params)[0]]: ["create_ticket"],
+ }),
+ );
+ });
+
it.each([
{
scenario: "matching filter type",
diff --git a/web/src/__tests__/server/dashboard-widget-version.servertest.ts b/web/src/__tests__/server/dashboard-widget-version.servertest.ts
index 88d510e002..b7261c10ce 100644
--- a/web/src/__tests__/server/dashboard-widget-version.servertest.ts
+++ b/web/src/__tests__/server/dashboard-widget-version.servertest.ts
@@ -7,6 +7,10 @@ import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import type { Session } from "next-auth";
import { requiresV2 } from "@/src/features/query/dataModel";
+import {
+ mapLegacyUiTableFilterToView,
+ mapWidgetUiTableFilterToView,
+} from "@/src/features/query";
describe("dashboard widget minVersion", () => {
let projectId: string;
@@ -95,27 +99,91 @@ describe("dashboard widget minVersion", () => {
describe("requiresV2", () => {
it.each([
// v2-only dimensions
- ["observations", [{ field: "costType" }], [], true],
- ["observations", [{ field: "usageType" }], [], true],
+ ["observations", [{ field: "costType" }], [], [], true],
+ ["observations", [{ field: "usageType" }], [], [], true],
// v2-only measures
- ["observations", [], [{ measure: "costByType" }], true],
- ["observations", [], [{ measure: "usageByType" }], true],
- ["observations", [], [{ measure: "traceId" }], true],
+ ["observations", [], [{ measure: "costByType" }], [], true],
+ ["observations", [], [{ measure: "usageByType" }], [], true],
+ ["observations", [], [{ measure: "traceId" }], [], true],
+ // v2-only filters
+ [
+ "observations",
+ [],
+ [{ measure: "count" }],
+ [{ column: "release" }],
+ true,
+ ],
// v1-compatible fields
- ["observations", [{ field: "name" }], [{ measure: "count" }], false],
+ [
+ "observations",
+ [{ field: "name" }],
+ [{ measure: "count" }],
+ [{ column: "traceRelease" }],
+ false,
+ ],
// views where v1 and v2 share all fields
- ["traces", [{ field: "name" }], [{ measure: "count" }], false],
- ["scores-numeric", [{ field: "name" }], [{ measure: "count" }], false],
+ ["traces", [{ field: "name" }], [{ measure: "count" }], [], false],
+ [
+ "scores-numeric",
+ [{ field: "name" }],
+ [{ measure: "count" }],
+ [],
+ false,
+ ],
// unknown view
- ["nonexistent", [{ field: "name" }], [{ measure: "count" }], false],
+ ["nonexistent", [{ field: "name" }], [{ measure: "count" }], [], false],
])(
- "requiresV2(%s, dims=%j, measures=%j) β†’ %s",
- (view, dimensions, measures, expected) => {
- expect(requiresV2({ view, dimensions, measures })).toBe(expected);
+ "requiresV2(%s, dims=%j, measures=%j, filters=%j) β†’ %s",
+ (view, dimensions, measures, filters, expected) => {
+ expect(requiresV2({ view, dimensions, measures, filters })).toBe(
+ expected,
+ );
},
);
});
+ describe("observations release filter mapping", () => {
+ it("keeps legacy observations Release filters on traceRelease for v1 compatibility", () => {
+ expect(
+ mapLegacyUiTableFilterToView("observations", [
+ {
+ column: "Release",
+ operator: "=",
+ value: "2026.04",
+ type: "string",
+ },
+ ]),
+ ).toEqual([
+ {
+ column: "traceRelease",
+ operator: "=",
+ value: "2026.04",
+ type: "string",
+ },
+ ]);
+ });
+
+ it("maps Observation Release to the v2-only release field", () => {
+ expect(
+ mapWidgetUiTableFilterToView("observations", [
+ {
+ column: "Observation Release",
+ operator: "=",
+ value: "2026.04",
+ type: "string",
+ },
+ ]),
+ ).toEqual([
+ {
+ column: "release",
+ operator: "=",
+ value: "2026.04",
+ type: "string",
+ },
+ ]);
+ });
+ });
+
// ── Service layer tests ─────────────────────────────────────────────
describe("DashboardService", () => {
diff --git a/web/src/__tests__/server/orderByToPrisma.servertest.ts b/web/src/__tests__/server/orderByToPrisma.servertest.ts
index c03eed9bb2..096c229041 100644
--- a/web/src/__tests__/server/orderByToPrisma.servertest.ts
+++ b/web/src/__tests__/server/orderByToPrisma.servertest.ts
@@ -1,4 +1,5 @@
import {
+ dashboardColumnDefinitions,
orderByToClickhouseSql,
orderByToPrismaSql,
tracesTableUiColumnDefinitions,
@@ -59,4 +60,13 @@ describe("orderByToPrisma (Convert orderBy to Prisma.sql)", () => {
),
).toThrow(InvalidRequestError);
});
+
+ test("orderByToClickhouseSql matches UiColumnMapping aliases", () => {
+ expect(
+ orderByToClickhouseSql(
+ { column: "Tool Names", order: "ASC" },
+ dashboardColumnDefinitions,
+ ),
+ ).toBe("ORDER BY mapKeys(tool_definitions) ASC");
+ });
});
diff --git a/web/src/__tests__/server/queryBuilderDashboards.servertest.ts b/web/src/__tests__/server/queryBuilderDashboards.servertest.ts
index 4670448e9e..a253959180 100644
--- a/web/src/__tests__/server/queryBuilderDashboards.servertest.ts
+++ b/web/src/__tests__/server/queryBuilderDashboards.servertest.ts
@@ -33,6 +33,7 @@ describe("selfServeDashboards", () => {
traceCounts: {} as Record<string, number>, // counts by trace name
environmentCounts: {} as Record<string, number>, // counts by environment
observationLevelCounts: {} as Record<string, number>, // counts by level
+ availableToolCounts: {} as Record<string, number>, // counts by available tool name
};
beforeAll(async () => {
@@ -134,6 +135,13 @@ describe("selfServeDashboards", () => {
completion_start_time: now.getTime() - i * 10000 + 800, // 800ms time to first token
end_time: now.getTime() - i * 10000 + 3000, // 3000ms total duration
provided_model_name: "gpt-4-turbo",
+ tool_definitions:
+ i === 0
+ ? {
+ create_ticket: '{"name":"create_ticket"}',
+ }
+ : {},
+ tool_call_names: i === 0 ? ["create_ticket"] : [],
}),
);
}
@@ -202,6 +210,11 @@ describe("selfServeDashboards", () => {
const level = observation.level || "DEFAULT";
stats.observationLevelCounts[level] =
(stats.observationLevelCounts[level] || 0) + 1;
+
+ Object.keys(observation.tool_definitions ?? {}).forEach((toolName) => {
+ stats.availableToolCounts[toolName] =
+ (stats.availableToolCounts[toolName] || 0) + 1;
+ });
});
// Count recent production traces (within the last hour)
@@ -595,6 +608,40 @@ describe("selfServeDashboards", () => {
stats.observationLevelCounts["ERROR"],
);
});
+
+ it("should support Tool Names (without available/called specified) filters after remapping", async () => {
+ // initially, we forgot to add the distinction and assumed available only
+ const legacyFilters: Parameters<typeof mapLegacyUiTableFilterToView>[1] =
+ [
+ {
+ column: "Tool Names",
+ operator: "any of",
+ value: ["create_ticket"],
+ type: "arrayOptions",
+ },
+ ];
+
+ const queryBuilderQuery: QueryType = {
+ view: "observations",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: mapLegacyUiTableFilterToView("observations", legacyFilters),
+ timeDimension: null,
+ fromTimestamp: defaultFromTime,
+ toTimestamp: defaultToTime,
+ orderBy: null,
+ };
+
+ const queryBuilderResult = await executeQuery(
+ projectId,
+ queryBuilderQuery,
+ );
+
+ expect(queryBuilderResult).toHaveLength(1);
+ expect(Number(queryBuilderResult[0].count_count)).toBe(
+ stats.availableToolCounts["create_ticket"],
+ );
+ });
});
describe("traces-timeseries query", () => {
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index 0a714c9aa1..c41c44ec7c 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -265,32 +265,13 @@ async function getObservationsByTypeV2(params: {
// Filter normalisation for the executeQuery (v2) path:
//
- // Filters arriving here originate from two different column-naming conventions:
- // A) uiTableName format ("Model", "Environment", …) β€” used by globalFilterState
- // filters that come from the standard dashboard filter bar. These are handled
- // canonically by mapLegacyUiTableFilterToView (see dashboardUiTableToViewMapping.ts).
- // B) uiTableId format ("model") β€” used by ModelSelectorPopover, which constructs
- // its filter using the lower-camel uiTableId rather than the display uiTableName.
- // mapLegacyUiTableFilterToView matches on uiTableName so it cannot cover this case.
- //
- // If additional uiTableId-format filters are introduced here in the future, add them
- // to the CHART_FILTER_ID_TO_VIEW_FIELD map below (the canonical view field names live
- // in dashboardUiTableToViewMapping.ts :: viewMappings["observations"]).
- const CHART_FILTER_ID_TO_VIEW_FIELD: Record<string, string> = {
- model: "providedModelName",
- };
-
const nonDatetimeFilters = filter.filter((f) => f.type !== "datetime");
- // Apply standard uiTableName β†’ view field mapping first.
- const standardMapped = mapLegacyUiTableFilterToView(
+ // mapLegacyUiTableFilterToView normalizes legacy dashboard filters whether
+ // they arrive as display labels, uiTableIds, or explicit aliases.
+ const viewFilters = mapLegacyUiTableFilterToView(
"observations",
nonDatetimeFilters,
);
- // Then patch any remaining uiTableId-format columns.
- const viewFilters = standardMapped.map((f) => {
- const viewField = CHART_FILTER_ID_TO_VIEW_FIELD[f.column];
- return viewField ? { ...f, column: viewField } : f;
- });
const q: QueryType = {
view: "observations",
diff --git a/web/src/features/filters/lib/filter-transform.ts b/web/src/features/filters/lib/filter-transform.ts
index 476b9499a1..b9ad1cbb0c 100644
--- a/web/src/features/filters/lib/filter-transform.ts
+++ b/web/src/features/filters/lib/filter-transform.ts
@@ -1,4 +1,8 @@
-import { type FilterState, type ColumnDefinition } from "@langfuse/shared";
+import {
+ type FilterState,
+ type ColumnDefinition,
+ type SingleValueOption,
+} from "@langfuse/shared";
/**
* Maps frontend column IDs to backend-expected column IDs
@@ -34,6 +38,23 @@ export function normalizeFilterColumnNames(
});
}
+type SingleValueOptionLike = Readonly<{
+ value: string;
+ count?: string | number;
+ displayValue?: string;
+}>;
+
+export const normalizeSingleValueOptions = (
+ options: readonly SingleValueOptionLike[] | undefined,
+): SingleValueOption[] =>
+ options?.map((option) => ({
+ value: option.value,
+ ...(option.count !== undefined ? { count: Number(option.count) } : {}),
+ ...(option.displayValue !== undefined
+ ? { displayValue: option.displayValue }
+ : {}),
+ })) ?? [];
+
/**
* Transforms frontend filter column IDs to backend-expected column IDs
*
diff --git a/web/src/features/query/dashboardUiTableToViewMapping.ts b/web/src/features/query/dashboardUiTableToViewMapping.ts
index 7c8d6d2de6..5390ad65f8 100644
--- a/web/src/features/query/dashboardUiTableToViewMapping.ts
+++ b/web/src/features/query/dashboardUiTableToViewMapping.ts
@@ -1,284 +1,420 @@
import { z } from "zod";
-import { dashboardColumnDefinitions, singleFilter } from "@langfuse/shared";
+import { singleFilter } from "@langfuse/shared";
import { type views } from "@/src/features/query/types";
// Exported to silence @typescript-eslint/no-unused-vars v8 warning
// (used for type extraction via typeof, which is a legitimate pattern)
export const FilterArray = z.array(singleFilter);
-const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {
+/**
+ * Central compatibility layer for dashboard/widget filter columns.
+ *
+ * Legacy dashboard filters can arrive in three shapes:
+ * - uiTableName display labels from the old dashboard filter bar, e.g. "Model"
+ * - uiTableId values from ad hoc callers, e.g. "model"
+ * - explicit legacy aliases, e.g. "Tool Names"
+ *
+ * The query engine expects canonical view field names instead, e.g.
+ * "providedModelName" or "toolNames". Widgets also need the inverse mapping
+ * when reopening saved filters in the editor so persisted query fields render
+ * with the current user-facing labels again.
+ *
+ * Keep all dashboard/widget filter migration and fallback logic in this module.
+ * If a new legacy dashboard column shape needs to remain supported, add it to
+ * this mapping rather than patching individual router or widget code paths.
+ */
+type DashboardViewFilterMapping = {
+ uiTableName: string;
+ uiTableId?: string;
+ aliases?: readonly string[];
+ viewName: string;
+};
+
+type ViewName = z.infer<typeof views>;
+
+type DashboardFilterSourceSpec = Omit<DashboardViewFilterMapping, "viewName">;
+
+type DashboardViewFieldDefinition = {
+ viewName: string;
+ current: DashboardFilterSourceSpec;
+ legacy?: DashboardFilterSourceSpec;
+};
+
+const sourceSpec = (
+ uiTableName: string,
+ options: Omit<DashboardFilterSourceSpec, "uiTableName"> = {},
+): DashboardFilterSourceSpec => ({
+ uiTableName,
+ ...options,
+});
+
+const defineField = (
+ viewName: string,
+ current: DashboardFilterSourceSpec,
+ legacy?: DashboardFilterSourceSpec,
+): DashboardViewFieldDefinition => ({
+ viewName,
+ current,
+ legacy,
+});
+
+const viewFilterDefinitions: Record<
+ ViewName,
+ readonly DashboardViewFieldDefinition[]
+> = {
traces: [
- {
- uiTableName: "Trace Name",
- viewName: "name",
- },
- {
- uiTableName: "Observation Name",
- viewName: "observationName",
- },
- {
- uiTableName: "Score Name",
- viewName: "scoreName",
- },
- {
- uiTableName: "Tags",
- viewName: "tags",
- },
- {
- uiTableName: "User",
- viewName: "userId",
- },
- {
- uiTableName: "Session",
- viewName: "sessionId",
- },
- {
- uiTableName: "Metadata",
- viewName: "metadata",
- },
- {
- uiTableName: "Release",
- viewName: "release",
- },
- {
- uiTableName: "Version",
- viewName: "version",
- },
- {
- uiTableName: "Environment",
- viewName: "environment",
- },
+ defineField("name", sourceSpec("Trace Name", { uiTableId: "traceName" })),
+ defineField(
+ "observationName",
+ sourceSpec("Observation Name", { uiTableId: "observationName" }),
+ ),
+ defineField(
+ "scoreName",
+ sourceSpec("Score Name", { uiTableId: "scoreName" }),
+ ),
+ defineField("tags", sourceSpec("Tags", { uiTableId: "traceTags" })),
+ defineField(
+ "userId",
+ sourceSpec("User", { uiTableId: "user" }),
+ sourceSpec("User", { uiTableId: "userId" }),
+ ),
+ defineField(
+ "sessionId",
+ sourceSpec("Session", { uiTableId: "session" }),
+ sourceSpec("Session", { uiTableId: "sessionId" }),
+ ),
+ defineField("metadata", sourceSpec("Metadata", { uiTableId: "metadata" })),
+ defineField("release", sourceSpec("Release", { uiTableId: "release" })),
+ defineField("version", sourceSpec("Version", { uiTableId: "version" })),
+ defineField(
+ "environment",
+ sourceSpec("Environment", { uiTableId: "environment" }),
+ ),
],
observations: [
- {
- uiTableName: "Trace Name",
- viewName: "traceName",
- },
- {
- uiTableName: "Observation Name",
- viewName: "name",
- },
- {
- uiTableName: "Score Name",
- viewName: "scoreName",
- },
- {
- uiTableName: "User",
- viewName: "userId",
- },
- {
- uiTableName: "Session",
- viewName: "sessionId",
- },
- {
- uiTableName: "Metadata",
- viewName: "metadata",
- },
- {
- uiTableName: "Type",
- viewName: "type",
- },
- {
- uiTableName: "Tags",
- viewName: "tags",
- },
- {
- uiTableName: "Model",
- viewName: "providedModelName",
- },
- {
- uiTableName: "Level",
- viewName: "level",
- },
- {
- uiTableName: "Tool Names",
- viewName: "toolNames",
- },
- {
- uiTableName: "Environment",
- viewName: "environment",
- },
- {
- uiTableName: "Release",
- viewName: "traceRelease",
- },
- {
- uiTableName: "Version",
- viewName: "traceVersion",
- },
+ defineField(
+ "traceName",
+ sourceSpec("Trace Name", { uiTableId: "traceName" }),
+ ),
+ defineField(
+ "name",
+ sourceSpec("Observation Name", { uiTableId: "observationName" }),
+ ),
+ defineField(
+ "scoreName",
+ sourceSpec("Score Name", { uiTableId: "scoreName" }),
+ ),
+ defineField(
+ "userId",
+ sourceSpec("User", { uiTableId: "user" }),
+ sourceSpec("User", { uiTableId: "userId" }),
+ ),
+ defineField(
+ "sessionId",
+ sourceSpec("Session", { uiTableId: "session" }),
+ sourceSpec("Session", { uiTableId: "sessionId" }),
+ ),
+ defineField("metadata", sourceSpec("Metadata", { uiTableId: "metadata" })),
+ defineField("type", sourceSpec("Type", { uiTableId: "type" })),
+ defineField("tags", sourceSpec("Tags", { uiTableId: "traceTags" })),
+ defineField(
+ "providedModelName",
+ sourceSpec("Model", { uiTableId: "model" }),
+ ),
+ defineField("level", sourceSpec("Level", { uiTableId: "level" })),
+ defineField(
+ "toolNames",
+ sourceSpec("Tool Names (Available)", { uiTableId: "toolNames" }),
+ sourceSpec("Tool Names (Available)", {
+ uiTableId: "toolNames",
+ aliases: ["Tool Names"],
+ }),
+ ),
+ defineField(
+ "calledToolNames",
+ sourceSpec("Tool Names (Called)", { uiTableId: "calledToolNames" }),
+ ),
+ defineField(
+ "traceRelease",
+ sourceSpec("Trace Release", { uiTableId: "traceRelease" }),
+ sourceSpec("Release"),
+ ),
+ defineField(
+ "traceVersion",
+ sourceSpec("Trace Version", { uiTableId: "traceVersion" }),
+ sourceSpec("Version"),
+ ),
+ defineField(
+ "environment",
+ sourceSpec("Environment", { uiTableId: "environment" }),
+ ),
+ defineField(
+ "release",
+ sourceSpec("Observation Release", { uiTableId: "release" }),
+ ),
+ defineField("version", sourceSpec("Version", { uiTableId: "version" })),
],
"scores-numeric": [
- {
- uiTableName: "Score Name",
- viewName: "name",
- },
- {
- uiTableName: "Score Source",
- viewName: "source",
- },
- {
- uiTableName: "Score Value",
- viewName: "value",
- },
- {
- // Legacy column name from dashboardColumnDefinitions (uiTableName: "value")
- uiTableName: "value",
- viewName: "value",
- },
- {
- uiTableName: "Scores Data Type",
- viewName: "dataType",
- },
- {
- uiTableName: "Tags",
- viewName: "tags",
- },
- {
- uiTableName: "Environment",
- viewName: "environment",
- },
- {
- uiTableName: "User",
- viewName: "userId",
- },
- {
- uiTableName: "Session",
- viewName: "sessionId",
- },
- {
- uiTableName: "Metadata",
- viewName: "metadata",
- },
- {
- uiTableName: "Trace Name",
- viewName: "traceName",
- },
- {
- uiTableName: "Observation Name",
- viewName: "observationName",
- },
- {
- uiTableName: "Release",
- viewName: "traceRelease",
- },
- {
- uiTableName: "Version",
- viewName: "traceVersion",
- },
+ defineField("name", sourceSpec("Score Name", { uiTableId: "scoreName" })),
+ defineField(
+ "source",
+ sourceSpec("Score Source", { uiTableId: "scoreSource" }),
+ ),
+ defineField(
+ "value",
+ sourceSpec("Score Value", {
+ uiTableId: "value",
+ aliases: ["value"],
+ }),
+ ),
+ defineField(
+ "dataType",
+ sourceSpec("Scores Data Type", { uiTableId: "scoreDataType" }),
+ ),
+ defineField("tags", sourceSpec("Tags", { uiTableId: "traceTags" })),
+ defineField(
+ "environment",
+ sourceSpec("Environment", { uiTableId: "environment" }),
+ ),
+ defineField(
+ "userId",
+ sourceSpec("User", { uiTableId: "user" }),
+ sourceSpec("User", { uiTableId: "userId" }),
+ ),
+ defineField(
+ "sessionId",
+ sourceSpec("Session", { uiTableId: "session" }),
+ sourceSpec("Session", { uiTableId: "sessionId" }),
+ ),
+ defineField("metadata", sourceSpec("Metadata", { uiTableId: "metadata" })),
+ defineField(
+ "traceName",
+ sourceSpec("Trace Name", { uiTableId: "traceName" }),
+ ),
+ defineField(
+ "observationName",
+ sourceSpec("Observation Name", { uiTableId: "observationName" }),
+ ),
+ defineField(
+ "traceRelease",
+ sourceSpec("Release", { uiTableId: "release" }),
+ ),
+ defineField(
+ "traceVersion",
+ sourceSpec("Version", { uiTableId: "version" }),
+ ),
],
"scores-categorical": [
- {
- uiTableName: "Score Name",
- viewName: "name",
- },
- {
- uiTableName: "Score Source",
- viewName: "source",
- },
- {
- uiTableName: "Score String Value",
- viewName: "stringValue",
- },
- {
- uiTableName: "Scores Data Type",
- viewName: "dataType",
- },
- {
- uiTableName: "Tags",
- viewName: "tags",
- },
- {
- uiTableName: "Environment",
- viewName: "environment",
- },
- {
- uiTableName: "User",
- viewName: "userId",
- },
- {
- uiTableName: "Session",
- viewName: "sessionId",
- },
- {
- uiTableName: "Metadata",
- viewName: "metadata",
- },
- {
- uiTableName: "Trace Name",
- viewName: "traceName",
- },
- {
- uiTableName: "Observation Name",
- viewName: "observationName",
- },
- {
- uiTableName: "Release",
- viewName: "traceRelease",
- },
- {
- uiTableName: "Version",
- viewName: "traceVersion",
- },
+ defineField("name", sourceSpec("Score Name", { uiTableId: "scoreName" })),
+ defineField(
+ "source",
+ sourceSpec("Score Source", { uiTableId: "scoreSource" }),
+ ),
+ defineField(
+ "stringValue",
+ sourceSpec("Score String Value", { uiTableId: "stringValue" }),
+ ),
+ defineField(
+ "dataType",
+ sourceSpec("Scores Data Type", { uiTableId: "scoreDataType" }),
+ ),
+ defineField("tags", sourceSpec("Tags", { uiTableId: "traceTags" })),
+ defineField(
+ "environment",
+ sourceSpec("Environment", { uiTableId: "environment" }),
+ ),
+ defineField(
+ "userId",
+ sourceSpec("User", { uiTableId: "user" }),
+ sourceSpec("User", { uiTableId: "userId" }),
+ ),
+ defineField(
+ "sessionId",
+ sourceSpec("Session", { uiTableId: "session" }),
+ sourceSpec("Session", { uiTableId: "sessionId" }),
+ ),
+ defineField("metadata", sourceSpec("Metadata", { uiTableId: "metadata" })),
+ defineField(
+ "traceName",
+ sourceSpec("Trace Name", { uiTableId: "traceName" }),
+ ),
+ defineField(
+ "observationName",
+ sourceSpec("Observation Name", { uiTableId: "observationName" }),
+ ),
+ defineField(
+ "traceRelease",
+ sourceSpec("Release", { uiTableId: "release" }),
+ ),
+ defineField(
+ "traceVersion",
+ sourceSpec("Version", { uiTableId: "version" }),
+ ),
],
};
-const isLegacyUiTableFilter = (
- filter: z.infer<typeof singleFilter>,
+const buildFilterMappings = (
+ source: "current" | "legacy",
+): Record<ViewName, readonly DashboardViewFilterMapping[]> =>
+ (Object.keys(viewFilterDefinitions) as ViewName[]).reduce<
+ Record<ViewName, readonly DashboardViewFilterMapping[]>
+ >(
+ (acc, view) => {
+ acc[view] = viewFilterDefinitions[view].map((field) => ({
+ ...(source === "legacy"
+ ? (field.legacy ?? field.current)
+ : field.current),
+ viewName: field.viewName,
+ }));
+
+ return acc;
+ },
+ {} as Record<ViewName, readonly DashboardViewFilterMapping[]>,
+ );
+
+const currentWidgetFilterMappings = buildFilterMappings("current");
+const legacyDashboardFilterMappings = buildFilterMappings("legacy");
+
+const allWidgetFilterMappings = [
+ ...Object.values(currentWidgetFilterMappings).flat(),
+ ...Object.values(legacyDashboardFilterMappings).flat(),
+];
+
+const matchesFilterMapping = (
+ mapping: DashboardViewFilterMapping,
+ column: string | undefined,
): boolean => {
- return dashboardColumnDefinitions
- .concat([
- {
- uiTableName: "Session",
- uiTableId: "sessionId",
- clickhouseTableName: "traces",
- clickhouseSelect: 't."sessionId"',
- },
- {
- uiTableName: "Observation Name",
- uiTableId: "observationName",
- clickhouseTableName: "observations",
- clickhouseSelect: 'o."name"',
- },
- {
- uiTableName: "Metadata",
- uiTableId: "metadata",
- clickhouseTableName: "traces",
- clickhouseSelect: 't."metadata"',
- },
- {
- uiTableName: "Score Value",
- uiTableId: "value",
- clickhouseTableName: "scores",
- clickhouseSelect: 's."value"',
- },
- {
- uiTableName: "Score String Value",
- uiTableId: "stringValue",
- clickhouseTableName: "scores",
- clickhouseSelect: 's."string_value"',
- },
- ])
- .some((columnDef) => columnDef.uiTableName === filter.column);
+ if (column === undefined) {
+ return false;
+ }
+
+ return (
+ mapping.uiTableName === column ||
+ mapping.uiTableId === column ||
+ mapping.aliases?.includes(column) === true
+ );
+};
+
+const findViewFilterMapping = (
+ mappings: readonly DashboardViewFilterMapping[],
+ column: string | undefined,
+): DashboardViewFilterMapping | undefined =>
+ mappings.find((mapping) => matchesFilterMapping(mapping, column));
+
+const isCanonicalViewFilterColumn = (
+ view: z.infer<typeof views>,
+ column: string | undefined,
+): boolean =>
+ column !== undefined &&
+ currentWidgetFilterMappings[view].some(
+ (mapping) => mapping.viewName === column,
+ );
+
+const isKnownWidgetFilterColumn = (column: string | undefined): boolean =>
+ allWidgetFilterMappings.some((mapping) =>
+ matchesFilterMapping(mapping, column),
+ );
+
+type PartitionedWidgetFilters = {
+ mappedFilters: z.infer<typeof FilterArray>;
+ unsupportedFilters: z.infer<typeof FilterArray>;
+};
+
+const partitionUiTableFiltersToView = (
+ view: z.infer<typeof views>,
+ filters: z.infer<typeof FilterArray>,
+ source: "stored" | "editor",
+): PartitionedWidgetFilters => {
+ return filters.reduce<PartitionedWidgetFilters>(
+ (acc, filter) => {
+ if (isCanonicalViewFilterColumn(view, filter.column)) {
+ acc.mappedFilters.push(filter);
+ return acc;
+ }
+
+ const primaryMappings =
+ source === "stored"
+ ? legacyDashboardFilterMappings[view]
+ : currentWidgetFilterMappings[view];
+ const fallbackMappings =
+ source === "stored"
+ ? currentWidgetFilterMappings[view]
+ : legacyDashboardFilterMappings[view];
+
+ const definition =
+ findViewFilterMapping(primaryMappings, filter.column) ??
+ findViewFilterMapping(fallbackMappings, filter.column);
+
+ if (definition) {
+ acc.mappedFilters.push({ ...filter, column: definition.viewName });
+ return acc;
+ }
+
+ if (isKnownWidgetFilterColumn(filter.column)) {
+ acc.unsupportedFilters.push(filter);
+ return acc;
+ }
+
+ acc.mappedFilters.push(filter);
+ return acc;
+ },
+ { mappedFilters: [], unsupportedFilters: [] },
+ );
};
+export const partitionStoredUiTableFiltersToView = (
+ view: z.infer<typeof views>,
+ filters: z.infer<typeof FilterArray>,
+): PartitionedWidgetFilters =>
+ partitionUiTableFiltersToView(view, filters, "stored");
+
+export const partitionWidgetUiTableFiltersToView = (
+ view: z.infer<typeof views>,
+ filters: z.infer<typeof FilterArray>,
+): PartitionedWidgetFilters =>
+ partitionUiTableFiltersToView(view, filters, "editor");
+
export const mapLegacyUiTableFilterToView = (
view: z.infer<typeof views>,
filters: z.infer<typeof FilterArray>,
): z.infer<typeof FilterArray> => {
- return filters.flatMap((filter) => {
- // If it's not a legacy filter, return it as is
- if (!isLegacyUiTableFilter(filter)) {
- return [filter];
- }
- // Check if we have a match in our mapping
- const definition = viewMappings[view].find(
- (def) => def.uiTableName === filter.column,
+ return partitionStoredUiTableFiltersToView(view, filters).mappedFilters;
+};
+
+export const mapWidgetUiTableFilterToView = (
+ view: z.infer<typeof views>,
+ filters: z.infer<typeof FilterArray>,
+): z.infer<typeof FilterArray> => {
+ return partitionWidgetUiTableFiltersToView(view, filters).mappedFilters;
+};
+
+export const normalizeStoredWidgetFiltersForEditor = (
+ view: z.infer<typeof views>,
+ filters: z.infer<typeof FilterArray>,
+): {
+ editorFilters: z.infer<typeof FilterArray>;
+ unsupportedFilters: z.infer<typeof FilterArray>;
+} => {
+ const partitionedFilters = partitionStoredUiTableFiltersToView(view, filters);
+
+ return {
+ editorFilters: [
+ ...mapViewFilterToUiTableFilter(view, partitionedFilters.mappedFilters),
+ ...partitionedFilters.unsupportedFilters,
+ ],
+ unsupportedFilters: partitionedFilters.unsupportedFilters,
+ };
+};
+
+export const mapViewFilterToUiTableFilter = (
+ view: z.infer<typeof views>,
+ filters: z.infer<typeof FilterArray>,
+): z.infer<typeof FilterArray> => {
+ return filters.map((filter) => {
+ const definition = currentWidgetFilterMappings[view].find(
+ (mapping) => mapping.viewName === filter.column,
);
- // Ignore if there is no match
- if (!definition) {
- return [];
- }
- // Overwrite column name if a match is found
- return [{ ...filter, column: definition.viewName }];
+
+ return definition ? { ...filter, column: definition.uiTableName } : filter;
});
};
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index 97cecda968..3a91a27741 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -1385,6 +1385,7 @@ export function requiresV2(params: {
view: string;
dimensions: { field: string }[];
measures: { measure: string }[];
+ filters?: { column: string }[];
}): boolean {
const v1View =
viewDeclarations.v1[params.view as keyof (typeof viewDeclarations)["v1"]];
@@ -1401,6 +1402,7 @@ export function requiresV2(params: {
return (
params.dimensions.some((d) => v2OnlyDims.includes(d.field)) ||
- params.measures.some((m) => v2OnlyMeasures.includes(m.measure))
+ params.measures.some((m) => v2OnlyMeasures.includes(m.measure)) ||
+ (params.filters ?? []).some((f) => v2OnlyDims.includes(f.column))
);
}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index 06bae0cb71..ff85e9be4d 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -38,6 +38,7 @@ import {
isV2BreakdownChart,
buildWidgetOrderBy,
} from "@/src/features/query/validateQuery";
+import { requiresV2 } from "@/src/features/query/dataModel";
export interface WidgetPlacement {
id: string;
@@ -80,10 +81,19 @@ export function DashboardWidget({
enabled: Boolean(projectId),
},
);
+ const widgetRequiresV2 = requiresV2({
+ view: widget.data?.view ?? "traces",
+ dimensions: widget.data?.dimensions ?? [],
+ measures:
+ widget.data?.metrics.map((metric) => ({ measure: metric.measure })) ?? [],
+ filters: widget.data?.filters ?? [],
+ });
// If widget requires v2 features (minVersion >= 2), must use v2.
// Otherwise follow the beta toggle.
const metricsVersion: ViewVersion =
- (widget.data?.minVersion ?? 1) >= 2 || isBetaEnabled ? "v2" : "v1";
+ widgetRequiresV2 || (widget.data?.minVersion ?? 1) >= 2 || isBetaEnabled
+ ? "v2"
+ : "v1";
const hasCUDAccess =
useHasProjectAccess({ projectId, scope: "dashboards:CUD" }) &&
dashboardOwner !== "LANGFUSE";
@@ -156,7 +166,10 @@ export function DashboardWidget({
aggregation: metric.agg as z.infer<typeof metricAggregations>,
})) ?? [],
filters: [
- ...(widget.data?.filters ?? []),
+ ...mapLegacyUiTableFilterToView(
+ (widget.data?.view as z.infer<typeof views>) ?? "traces",
+ widget.data?.filters ?? [],
+ ),
...mapLegacyUiTableFilterToView(
(widget.data?.view as z.infer<typeof views>) ?? "traces",
filterState,
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index fc37bab312..5519ab1127 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -11,7 +11,9 @@ import {
type metricAggregations,
getValidAggregationsForMeasureType,
type QueryType,
- mapLegacyUiTableFilterToView,
+ mapWidgetUiTableFilterToView,
+ normalizeStoredWidgetFiltersForEditor,
+ partitionWidgetUiTableFiltersToView,
} from "@/src/features/query";
import React, { useState, useMemo, useEffect, useRef } from "react";
import {
@@ -40,7 +42,7 @@ import {
toAbsoluteTimeRange,
type DashboardDateRangeOptions,
} from "@/src/utils/date-range-utils";
-import { type ColumnDefinition } from "@langfuse/shared";
+import { normalizeSingleValueOptions } from "@/src/features/filters/lib/filter-transform";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
import { Button } from "@/src/components/ui/button";
@@ -79,6 +81,10 @@ import {
getChartLoadingProgress,
getChartLoadingStateProps,
} from "@/src/features/widgets/chart-library/chartLoadingStateUtils";
+import {
+ getWidgetColumnsWithCustomSelect,
+ getWidgetFilterColumns,
+} from "./widgetFilterColumns";
type ChartType = {
group: "time-series" | "total-value";
@@ -289,9 +295,22 @@ export function WidgetForm({
// Form definitions follow beta toggle, or v2 if widget already requires it.
// Traces view is excluded from beta-v2 because it has no v2-only fields.
+ const initialWidgetRequiresV2 = requiresV2({
+ view: initialValues.view,
+ dimensions:
+ initialValues.dimensions ??
+ (initialValues.dimension && initialValues.dimension !== "none"
+ ? [{ field: initialValues.dimension }]
+ : []),
+ measures: initialValues.metrics?.map((metric) => ({
+ measure: metric.measure,
+ })) ?? [{ measure: initialValues.measure }],
+ filters: initialValues.filters ?? [],
+ });
const viewVersion: ViewVersion =
(isBetaEnabled && selectedView !== "traces") ||
- (initialValues.minVersion ?? 1) >= 2
+ (initialValues.minVersion ?? 1) >= 2 ||
+ initialWidgetRequiresV2
? "v2"
: "v1";
const availableViewOptions = viewVersion === "v2" ? viewsV2 : views;
@@ -394,21 +413,28 @@ export function WidgetForm({
}
};
const [userFilterState, setUserFilterState] = useState<FilterState>(
- initialValues.filters?.map((filter) => {
- if (filter.column === "name") {
- // We need to map the generic `name` property to the correct column name for the selected view
- return {
- ...filter,
- column:
- initialValues.view === "traces"
- ? "traceName"
- : initialValues.view === "observations"
- ? "observationName"
- : "scoreName",
- };
- }
- return filter;
- }) ?? [],
+ () =>
+ normalizeStoredWidgetFiltersForEditor(
+ initialValues.view,
+ initialValues.filters ?? [],
+ ).editorFilters,
+ );
+ const unsupportedFilters = useMemo(
+ () =>
+ partitionWidgetUiTableFiltersToView(selectedView, userFilterState)
+ .unsupportedFilters,
+ [selectedView, userFilterState],
+ );
+ const unsupportedFilterColumns = useMemo(
+ () =>
+ Array.from(
+ new Set(unsupportedFilters.map((filter) => filter.column)),
+ ).join(", "),
+ [unsupportedFilters],
+ );
+ const normalizedUserFilters = useMemo(
+ () => mapWidgetUiTableFilterToView(selectedView, userFilterState),
+ [selectedView, userFilterState],
);
// When beta is toggled on while "traces" is selected (and not editing an
@@ -587,10 +613,14 @@ export function WidgetForm({
environmentFilterOptions.data?.map((value) => ({
value: value.environment,
})) || [];
- const nameOptions = traceFilterOptions.data?.name || [];
+ const nameOptions = normalizeSingleValueOptions(
+ traceFilterOptions.data?.name,
+ );
const tagsOptions = traceFilterOptions.data?.tags || [];
const modelOptions = generationsFilterOptions.data?.model || [];
const toolNamesOptions = generationsFilterOptions.data?.toolNames || [];
+ const calledToolNamesOptions =
+ generationsFilterOptions.data?.calledToolNames || [];
const observationLevelOptions = [
{ value: "DEBUG" },
{ value: "DEFAULT" },
@@ -598,111 +628,28 @@ export function WidgetForm({
{ value: "ERROR" },
];
- // Filter columns for PopoverFilterBuilder
- const filterColumns: ColumnDefinition[] = [
- {
- name: "Environment",
- id: "environment",
- type: "stringOptions",
- options: environmentOptions,
- internal: "internalValue",
- },
- {
- name: "Trace Name",
- id: "traceName",
- type: "stringOptions",
- options: nameOptions,
- internal: "internalValue",
- },
- {
- name: "Observation Name",
- id: "observationName",
- type: "string",
- internal: "internalValue",
- },
- {
- name: "Score Name",
- id: "scoreName",
- type: "string",
- internal: "internalValue",
- },
- {
- name: "Tags",
- id: "tags",
- type: "arrayOptions",
- options: tagsOptions,
- internal: "internalValue",
- },
- {
- name: "Tool Names",
- id: "toolNames",
- type: "arrayOptions",
- options: toolNamesOptions,
- internal: "internalValue",
- },
- {
- name: "User",
- id: "user",
- type: "string",
- internal: "internalValue",
- },
- {
- name: "Session",
- id: "session",
- type: "string",
- internal: "internalValue",
- },
- {
- name: "Metadata",
- id: "metadata",
- type: "stringObject",
- internal: "internalValue",
- },
- {
- name: "Release",
- id: "release",
- type: "string",
- internal: "internalValue",
- },
- {
- name: "Version",
- id: "version",
- type: "string",
- internal: "internalValue",
- },
- ];
- if (selectedView === "observations") {
- filterColumns.push({
- name: "Model",
- id: "providedModelName",
- type: "stringOptions",
- options: modelOptions,
- internal: "internalValue",
- });
- filterColumns.push({
- name: "Level",
- id: "level",
- type: "stringOptions",
- options: observationLevelOptions,
- internal: "internalValue",
- });
- }
- if (selectedView === "scores-categorical") {
- filterColumns.push({
- name: "Score String Value",
- id: "stringValue",
- type: "string",
- internal: "internalValue",
- });
- }
- if (selectedView === "scores-numeric") {
- filterColumns.push({
- name: "Score Value",
- id: "value",
- type: "number",
- internal: "internalValue",
- });
- }
+ const filterColumns = getWidgetFilterColumns({
+ selectedView,
+ viewVersion,
+ environmentOptions,
+ nameOptions,
+ tagsOptions,
+ modelOptions,
+ toolNamesOptions,
+ calledToolNamesOptions,
+ observationLevelOptions,
+ });
+ const columnsWithCustomSelect = getWidgetColumnsWithCustomSelect({
+ selectedView,
+ viewVersion,
+ environmentOptions,
+ nameOptions,
+ tagsOptions,
+ modelOptions,
+ toolNamesOptions,
+ calledToolNamesOptions,
+ observationLevelOptions,
+ });
// When chart type does not support breakdown, wipe the breakdown dimension
useEffect(() => {
@@ -952,7 +899,7 @@ export function WidgetForm({
view: selectedView,
dimensions: queryDimensions,
metrics: queryMetrics,
- filters: [...mapLegacyUiTableFilterToView(selectedView, userFilterState)],
+ filters: [...normalizedUserFilters],
timeDimension: isTimeSeriesChart(
selectedChartType as DashboardWidgetChartType,
)
@@ -969,7 +916,6 @@ export function WidgetForm({
selectedAggregation,
selectedMeasure,
selectedMetrics,
- userFilterState,
dateRange,
selectedChartType,
histogramBins,
@@ -977,12 +923,21 @@ export function WidgetForm({
rowLimit,
previewSortState,
viewVersion,
+ normalizedUserFilters,
]);
- const queryValidation = useMemo(
- () => validateQuery(query, viewVersion),
- [query, viewVersion],
- );
+ const queryValidation = useMemo(() => {
+ if (unsupportedFilters.length > 0) {
+ return {
+ valid: false as const,
+ reason:
+ `Unsupported legacy filter column(s): ${unsupportedFilterColumns}. ` +
+ "Remove them or switch to a compatible view before saving this widget.",
+ };
+ }
+
+ return validateQuery(query, viewVersion);
+ }, [query, unsupportedFilterColumns, unsupportedFilters.length, viewVersion]);
const queryResult = api.dashboard.executeQuery.useQuery(
{
@@ -1108,7 +1063,7 @@ export function WidgetForm({
view: selectedView,
dimensions: saveDimensions,
metrics: saveMetrics,
- filters: mapLegacyUiTableFilterToView(selectedView, userFilterState),
+ filters: normalizedUserFilters,
chartType: selectedChartType as DashboardWidgetChartType,
chartConfig: isTimeSeriesChart(
selectedChartType as DashboardWidgetChartType,
@@ -1139,6 +1094,7 @@ export function WidgetForm({
view: selectedView,
dimensions: saveDimensions,
measures: saveMetrics.map((m) => ({ measure: m.measure })),
+ filters: normalizedUserFilters,
})
? 2
: 1,
@@ -1307,19 +1263,33 @@ export function WidgetForm({
setPivotDimensions(validDimensions);
}
- // Remove invalid filters based on the new view
- if (newView !== "scores-categorical") {
- setUserFilterState((prev) =>
- prev.filter(
- (filter) => filter.column !== "stringValue",
- ),
- );
- }
- if (newView === "scores-numeric") {
- setUserFilterState((prev) =>
- prev.filter((filter) => filter.column !== "value"),
- );
- }
+ // Remove score-only filters when switching away from
+ // scores-categorical or scores-numeric. The widget editor
+ // state stores current UI labels such as "Score Value",
+ // but older/canonical filters can still surface as ids
+ // during transitions, so we need to clean up both
+ // representations here.
+ setUserFilterState((prev) =>
+ prev.filter((filter) => {
+ if (
+ newView !== "scores-categorical" &&
+ (filter.column === "stringValue" ||
+ filter.column === "Score String Value")
+ ) {
+ return false;
+ }
+
+ if (
+ newView !== "scores-numeric" &&
+ (filter.column === "value" ||
+ filter.column === "Score Value")
+ ) {
+ return false;
+ }
+
+ return true;
+ }),
+ );
}
setSelectedView(value as z.infer<typeof views>);
}}
@@ -1558,16 +1528,25 @@ export function WidgetForm({
<div className="space-y-2">
<Label>Filters</Label>
<div className="space-y-2">
+ {unsupportedFilters.length > 0 && (
+ <Alert
+ variant="default"
+ className="border-yellow-500/50 bg-yellow-50 dark:bg-yellow-950/20"
+ >
+ <AlertCircle className="h-4 w-4 text-yellow-600 dark:text-yellow-500" />
+ <AlertTitle className="text-yellow-800 dark:text-yellow-400">
+ Unsupported legacy filters
+ </AlertTitle>
+ <AlertDescription className="text-yellow-700 dark:text-yellow-500">
+ {`This widget still contains filter columns that are not supported for ${startCase(selectedView)}: ${unsupportedFilterColumns}. Remove them or switch to a compatible view before saving.`}
+ </AlertDescription>
+ </Alert>
+ )}
<InlineFilterBuilder
columns={filterColumns}
filterState={userFilterState}
onChange={setUserFilterState}
- columnsWithCustomSelect={[
- "environment",
- "traceName",
- "tags",
- "providedModelName",
- ]}
+ columnsWithCustomSelect={columnsWithCustomSelect}
/>
</div>
</div>
diff --git a/web/src/features/widgets/components/widgetFilterColumns.ts b/web/src/features/widgets/components/widgetFilterColumns.ts
new file mode 100644
index 0000000000..d3ba835a93
--- /dev/null
+++ b/web/src/features/widgets/components/widgetFilterColumns.ts
@@ -0,0 +1,236 @@
+import {
+ type ColumnDefinition,
+ type SingleValueOption,
+} from "@langfuse/shared";
+import { type views } from "@/src/features/query/types";
+import { type ViewVersion } from "@/src/features/query";
+import { type z } from "zod";
+
+type GetWidgetFilterColumnsParams = {
+ selectedView: z.infer<typeof views>;
+ viewVersion: ViewVersion;
+ environmentOptions: SingleValueOption[];
+ nameOptions: SingleValueOption[];
+ tagsOptions: SingleValueOption[];
+ modelOptions: SingleValueOption[];
+ toolNamesOptions: SingleValueOption[];
+ calledToolNamesOptions: SingleValueOption[];
+ observationLevelOptions: SingleValueOption[];
+};
+
+type WidgetFilterColumnSpec = {
+ column: ColumnDefinition;
+ customSelect?: boolean;
+};
+
+const getWidgetFilterColumnSpecs = ({
+ selectedView,
+ viewVersion,
+ environmentOptions,
+ nameOptions,
+ tagsOptions,
+ modelOptions,
+ toolNamesOptions,
+ calledToolNamesOptions,
+ observationLevelOptions,
+}: GetWidgetFilterColumnsParams): WidgetFilterColumnSpec[] => {
+ const filterColumns: WidgetFilterColumnSpec[] = [
+ {
+ column: {
+ name: "Environment",
+ id: "environment",
+ type: "stringOptions",
+ options: environmentOptions,
+ internal: "internalValue",
+ },
+ customSelect: true,
+ },
+ {
+ column: {
+ name: "Trace Name",
+ id: "traceName",
+ type: "stringOptions",
+ options: nameOptions,
+ internal: "internalValue",
+ },
+ customSelect: true,
+ },
+ {
+ column: {
+ name: "Observation Name",
+ id: "observationName",
+ type: "string",
+ internal: "internalValue",
+ },
+ },
+ {
+ column: {
+ name: "Score Name",
+ id: "scoreName",
+ type: "string",
+ internal: "internalValue",
+ },
+ },
+ {
+ column: {
+ name: "Tags",
+ id: "tags",
+ type: "arrayOptions",
+ options: tagsOptions,
+ internal: "internalValue",
+ },
+ customSelect: true,
+ },
+ {
+ column: {
+ name: "User",
+ id: "user",
+ type: "string",
+ internal: "internalValue",
+ },
+ },
+ {
+ column: {
+ name: "Session",
+ id: "session",
+ type: "string",
+ internal: "internalValue",
+ },
+ },
+ {
+ column: {
+ name: "Metadata",
+ id: "metadata",
+ type: "stringObject",
+ internal: "internalValue",
+ },
+ },
+ {
+ column: {
+ name: "Version",
+ id: "version",
+ type: "string",
+ internal: "internalValue",
+ },
+ },
+ ];
+
+ if (selectedView !== "observations") {
+ filterColumns.push({
+ column: {
+ name: "Release",
+ id: "release",
+ type: "string",
+ internal: "internalValue",
+ },
+ });
+ }
+
+ if (selectedView === "observations") {
+ filterColumns.push(
+ ...(viewVersion === "v2"
+ ? [
+ {
+ column: {
+ name: "Observation Release",
+ id: "release",
+ type: "string",
+ internal: "internalValue",
+ },
+ } satisfies WidgetFilterColumnSpec,
+ ]
+ : []),
+ {
+ column: {
+ name: "Tool Names (Available)",
+ id: "toolNames",
+ type: "arrayOptions",
+ options: toolNamesOptions,
+ internal: "internalValue",
+ },
+ customSelect: true,
+ },
+ {
+ column: {
+ name: "Tool Names (Called)",
+ id: "calledToolNames",
+ type: "arrayOptions",
+ options: calledToolNamesOptions,
+ internal: "internalValue",
+ },
+ customSelect: true,
+ },
+ {
+ column: {
+ name: "Trace Release",
+ id: "traceRelease",
+ type: "string",
+ internal: "internalValue",
+ },
+ },
+ {
+ column: {
+ name: "Trace Version",
+ id: "traceVersion",
+ type: "string",
+ internal: "internalValue",
+ },
+ },
+ {
+ column: {
+ name: "Model",
+ id: "providedModelName",
+ type: "stringOptions",
+ options: modelOptions,
+ internal: "internalValue",
+ },
+ customSelect: true,
+ },
+ {
+ column: {
+ name: "Level",
+ id: "level",
+ type: "stringOptions",
+ options: observationLevelOptions,
+ internal: "internalValue",
+ },
+ },
+ );
+ }
+
+ if (selectedView === "scores-categorical") {
+ filterColumns.push({
+ column: {
+ name: "Score String Value",
+ id: "stringValue",
+ type: "string",
+ internal: "internalValue",
+ },
+ });
+ }
+
+ if (selectedView === "scores-numeric") {
+ filterColumns.push({
+ column: {
+ name: "Score Value",
+ id: "value",
+ type: "number",
+ internal: "internalValue",
+ },
+ });
+ }
+
+ return filterColumns;
+};
+
+export const getWidgetFilterColumns = (
+ params: GetWidgetFilterColumnsParams,
+): ColumnDefinition[] =>
+ getWidgetFilterColumnSpecs(params).map((spec) => spec.column);
+
+export const getWidgetColumnsWithCustomSelect = (
+ params: GetWidgetFilterColumnsParams,
+): string[] =>
+ getWidgetFilterColumnSpecs(params)
+ .filter((spec) => spec.customSelect)
+ .map((spec) => spec.column.id);
diff --git a/web/src/hooks/useDashboardFilterOptions.ts b/web/src/hooks/useDashboardFilterOptions.ts
index bd5ccc1f47..ce2c4e60b3 100644
--- a/web/src/hooks/useDashboardFilterOptions.ts
+++ b/web/src/hooks/useDashboardFilterOptions.ts
@@ -1,5 +1,6 @@
import { useMemo } from "react";
import { api } from "@/src/utils/api";
+import { normalizeSingleValueOptions } from "@/src/features/filters/lib/filter-transform";
import {
toAbsoluteTimeRange,
type TimeRange,
@@ -11,11 +12,6 @@ type UseDashboardFilterOptionsParams = {
timeRange: TimeRange;
};
-const toNameOption = (n: { value: string; count: string | number }) => ({
- value: n.value,
- count: Number(n.count),
-});
-
export function useDashboardFilterOptions({
projectId,
isBetaEnabled,
@@ -72,8 +68,8 @@ export function useDashboardFilterOptions({
const nameOptions = useMemo(
() =>
isBetaEnabled
- ? (eventsFilterOptions.data?.traceName?.map(toNameOption) ?? [])
- : (traceFilterOptions.data?.name?.map(toNameOption) ?? []),
+ ? normalizeSingleValueOptions(eventsFilterOptions.data?.traceName)
+ : normalizeSingleValueOptions(traceFilterOptions.data?.name),
[
isBetaEnabled,
eventsFilterOptions.data?.traceName,