Skip to content

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

feat(dashboard): validate high-cardinality dimensions require top-N shape on v2 path (#12345)

Valery Meleshkin70122f242ad3
diff --git a/web/src/__tests__/server/queryBuilder.servertest.ts b/web/src/__tests__/server/queryBuilder.servertest.ts
index 9f1ac6d1c1..d26e05f923 100644
--- a/web/src/__tests__/server/queryBuilder.servertest.ts
+++ b/web/src/__tests__/server/queryBuilder.servertest.ts
@@ -4312,6 +4312,38 @@ describe("validateQuery", () => {
expect(result).toEqual({ valid: true });
});
+
+ it("should return invalid when high cardinality dimension is used with timeDimension", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "traceId" }], // high cardinality
+ orderBy: [{ field: "sum_totalCost", direction: "desc" }],
+ chartConfig: { type: "table", row_limit: 10 },
+ timeDimension: { granularity: "day" }, // timeseries
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result.valid).toBe(false);
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "traceId",
+ );
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "timeDimension",
+ );
+ });
+
+ it("should return valid for low cardinality dimension with timeDimension", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "name" }], // low cardinality
+ timeDimension: { granularity: "day" },
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result).toEqual({ valid: true });
+ });
});
describe("getValidAggregationsForMeasureType", () => {
diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsx
index e24b43bfd3..c6d9f68d2e 100644
--- a/web/src/features/dashboard/components/UserChart.tsx
+++ b/web/src/features/dashboard/components/UserChart.tsx
@@ -42,6 +42,8 @@ export const UserChart = ({
schedulerId?: string;
}) => {
const [isExpanded, setIsExpanded] = useState(false);
+ const maxNumberOfEntries = { collapsed: 5, expanded: 20 } as const;
+
const userCostQuery: QueryType = {
view: "observations",
dimensions: [{ field: "userId" }],
@@ -61,7 +63,11 @@ export const UserChart = ({
timeDimension: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
- orderBy: null,
+ orderBy: [{ field: "sum_totalCost", direction: "desc" }],
+ chartConfig: {
+ type: "HORIZONTAL_BAR",
+ row_limit: maxNumberOfEntries.expanded,
+ },
};
const user = useScheduledDashboardExecuteQuery(
@@ -84,13 +90,27 @@ export const UserChart = ({
const isV2 = metricsVersion === "v2";
const countField = isV2 ? "uniq_traceId" : "count_count";
+ const traceViewBase = traceViewQuery({ metricsVersion, globalFilterState });
+ const traceMetric = traceViewBase.metrics[0] ?? {
+ aggregation: "count",
+ measure: "count",
+ };
const traceCountQuery: QueryType = {
- ...traceViewQuery({ metricsVersion, globalFilterState }),
+ ...traceViewBase,
dimensions: [{ field: "userId" }],
timeDimension: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
- orderBy: null,
+ orderBy: [
+ {
+ field: `${traceMetric.aggregation}_${traceMetric.measure}`,
+ direction: "desc",
+ },
+ ],
+ chartConfig: {
+ type: "HORIZONTAL_BAR",
+ row_limit: maxNumberOfEntries.expanded,
+ },
};
const traces = useScheduledDashboardExecuteQuery(
@@ -142,8 +162,6 @@ export const UserChart = ({
0,
);
- const maxNumberOfEntries = { collapsed: 5, expanded: 20 } as const;
-
const BAR_ROW_HEIGHT = 36;
const CHART_AXIS_PADDING = 32;
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index f34c4bd9ec..49c2ea5515 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -35,7 +35,10 @@ import {
type FilterState,
} from "@langfuse/shared";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { executeQuery } from "@/src/features/query/server/queryExecutor";
+import {
+ executeQuery,
+ validateQuery,
+} from "@/src/features/query/server/queryExecutor";
// Define the dashboard list input schema
const ListDashboardsInput = z.object({
@@ -443,9 +446,14 @@ export const dashboardRouter = createTRPCRouter({
)
.query(async ({ input }) => {
try {
+ const validation = validateQuery(input.query, input.version);
+ if (!validation.valid) {
+ throw new InvalidRequestError(validation.reason);
+ }
+
return executeQuery(
input.projectId,
- input.query as QueryType,
+ input.query,
input.version,
input.version === "v2",
);
diff --git a/web/src/features/query/server/queryExecutor.ts b/web/src/features/query/server/queryExecutor.ts
index 00d68b01ee..568b1427bc 100644
--- a/web/src/features/query/server/queryExecutor.ts
+++ b/web/src/features/query/server/queryExecutor.ts
@@ -4,129 +4,11 @@ import { type QueryType, type ViewVersion } from "@/src/features/query/types";
import { getViewDeclaration } from "@/src/features/query/dataModel";
import { env } from "@/src/env.mjs";
-/**
- * Result of query validation.
- * Either valid (query is safe to run) or invalid with a reason.
- */
-export type QueryValidationResult =
- | { valid: true }
- | { valid: false; reason: string };
-
-/**
- * Gets the list of high cardinality dimension fields used in the query.
- *
- * @param query - The query configuration
- * @param version - The view version (v1 or v2)
- * @returns Array of high cardinality field names
- */
-function getHighCardinalityDimensions(
- query: QueryType,
- version: ViewVersion,
-): string[] {
- if (!query.dimensions || query.dimensions.length === 0) {
- return [];
- }
-
- const view = getViewDeclaration(query.view, version);
- return query.dimensions
- .filter((dim) => view.dimensions[dim.field]?.highCardinality)
- .map((dim) => dim.field);
-}
-
-/**
- * Finds the measure name that matches an orderBy field.
- * OrderBy fields can be:
- * - "{aggregation}_{measureName}" like "sum_totalCost" or "count_count"
- * - Just the measure name like "totalCost"
- * We search for known measure names as suffixes of the orderBy field.
- *
- * @param orderByField - The orderBy field string
- * @param knownMeasures - List of known measure names from the query
- * @returns The matching measure name, or null if no match found
- */
-function findMeasureInOrderByField(
- orderByField: string,
- knownMeasures: string[],
-): string | null {
- for (const measure of knownMeasures) {
- // Check exact match (e.g., orderBy: "totalCost" matches measure "totalCost")
- if (orderByField === measure) {
- return measure;
- }
- // Check suffix match (e.g., orderBy: "sum_totalCost" matches measure "totalCost")
- if (orderByField.endsWith(`_${measure}`)) {
- return measure;
- }
- }
- return null;
-}
-
-/**
- * Validates a query for safety before execution.
- * Performs sanity checks for high cardinality dimension validation.
- *
- * High cardinality dimensions (id, traceId, userId, sessionId, etc.) are only allowed when:
- * 1. config.row_limit (or chartConfig.row_limit) is explicitly specified (LIMIT)
- * 2. orderBy with direction 'desc' on a measure field is specified (for top-N queries)
- *
- * @param query - The query configuration (with original config, before defaults applied)
- * @param version - The view version (v1 or v2)
- * @returns Validation result: { valid: true } or { valid: false, reason: string }
- */
-export function validateQuery(
- query: QueryType,
- version: ViewVersion,
-): QueryValidationResult {
- // 1. Check for high cardinality dimensions
- const highCardDims = getHighCardinalityDimensions(query, version);
-
- if (highCardDims.length === 0) {
- return { valid: true };
- }
-
- // 2. Validate required conditions for high cardinality
- // Support both public API "config" and internal "chartConfig" field names
- const chartConfig =
- (query as unknown as { config?: QueryType["chartConfig"] }).config ??
- query.chartConfig;
- const hasExplicitLimit = chartConfig?.row_limit !== undefined;
-
- // 3. Validate ORDER BY - must have at least one desc on a measure field
- const orderByDescFields =
- query.orderBy?.filter((o) => o.direction === "desc") ?? [];
-
- if (!hasExplicitLimit || orderByDescFields.length === 0) {
- return {
- valid: false,
- reason: `High cardinality dimension(s) '${highCardDims.join(", ")}' require both 'config.row_limit' and 'orderBy' with direction 'desc' on a measure field.`,
- };
- }
-
- // Extract measure names from orderBy fields and validate they are measures in the query
- const queryMeasureNames = query.metrics.map((m) => m.measure);
- const invalidOrderByFields: string[] = [];
-
- for (const orderBy of orderByDescFields) {
- const matchedMeasure = findMeasureInOrderByField(
- orderBy.field,
- queryMeasureNames,
- );
- if (!matchedMeasure) {
- invalidOrderByFields.push(orderBy.field);
- }
- }
-
- if (invalidOrderByFields.length > 0) {
- return {
- valid: false,
- reason:
- `High cardinality dimension(s) '${highCardDims.join(", ")}' require 'orderBy' with direction 'desc' on a measure field. ` +
- `'${invalidOrderByFields.join(", ")}' ${invalidOrderByFields.length === 1 ? "is" : "are"} not a measure in this query.`,
- };
- }
-
- return { valid: true };
-}
+// Re-export validation logic (shared between server and client)
+export {
+ validateQuery,
+ type QueryValidationResult,
+} from "@/src/features/query/validateQuery";
/**
* Execute a query using the QueryBuilder.
diff --git a/web/src/features/query/validateQuery.ts b/web/src/features/query/validateQuery.ts
new file mode 100644
index 0000000000..be3630f5e8
--- /dev/null
+++ b/web/src/features/query/validateQuery.ts
@@ -0,0 +1,216 @@
+import { type QueryType, type ViewVersion } from "@/src/features/query/types";
+import { getViewDeclaration } from "@/src/features/query/dataModel";
+
+/**
+ * Result of query validation.
+ * Either valid (query is safe to run) or invalid with a reason.
+ */
+export type QueryValidationResult =
+ | { valid: true }
+ | { valid: false; reason: string };
+
+/**
+ * Gets the list of high cardinality dimension fields used in the query.
+ *
+ * @param query - The query configuration
+ * @param version - The view version (v1 or v2)
+ * @returns Array of high cardinality field names
+ */
+function getHighCardinalityDimensions(
+ query: QueryType,
+ version: ViewVersion,
+): string[] {
+ if (!query.dimensions || query.dimensions.length === 0) {
+ return [];
+ }
+
+ const view = getViewDeclaration(query.view, version);
+ return query.dimensions
+ .filter((dim) => view.dimensions[dim.field]?.highCardinality)
+ .map((dim) => dim.field);
+}
+
+/**
+ * Finds the measure name that matches an orderBy field.
+ * OrderBy fields can be:
+ * - "{aggregation}_{measureName}" like "sum_totalCost" or "count_count"
+ * - Just the measure name like "totalCost"
+ * We search for known measure names as suffixes of the orderBy field.
+ *
+ * @param orderByField - The orderBy field string
+ * @param knownMeasures - List of known measure names from the query
+ * @returns The matching measure name, or null if no match found
+ */
+function findMeasureInOrderByField(
+ orderByField: string,
+ knownMeasures: string[],
+): string | null {
+ for (const measure of knownMeasures) {
+ // Check exact match (e.g., orderBy: "totalCost" matches measure "totalCost")
+ if (orderByField === measure) {
+ return measure;
+ }
+ // Check suffix match (e.g., orderBy: "sum_totalCost" matches measure "totalCost")
+ if (orderByField.endsWith(`_${measure}`)) {
+ return measure;
+ }
+ }
+ return null;
+}
+
+/**
+ * Validates a query for safety before execution.
+ * Performs sanity checks for high cardinality dimension validation.
+ *
+ * High cardinality dimensions (id, traceId, userId, sessionId, etc.) are only allowed when:
+ * 1. timeDimension is NOT set (timeseries with high cardinality produces unbounded results)
+ * 2. config.row_limit (or chartConfig.row_limit) is explicitly specified (LIMIT)
+ * 3. orderBy with direction 'desc' on a measure field is specified (for top-N queries)
+ *
+ * @param query - The query configuration (with original config, before defaults applied)
+ * @param version - The view version (v1 or v2)
+ * @returns Validation result: { valid: true } or { valid: false, reason: string }
+ */
+export function validateQuery(
+ query: QueryType,
+ version: ViewVersion,
+): QueryValidationResult {
+ // Only enforce validation for v2 queries
+ if (version !== "v2") {
+ return { valid: true };
+ }
+
+ // 1. Check for high cardinality dimensions
+ const highCardDims = getHighCardinalityDimensions(query, version);
+
+ if (highCardDims.length === 0) {
+ return { valid: true };
+ }
+
+ // 2. Reject high cardinality dimensions in timeseries queries
+ // A timeseries grouped by e.g. traceId produces unbounded rows (one per ID per time bucket)
+ // and cannot be meaningfully limited with row_limit.
+ if (query.timeDimension) {
+ return {
+ valid: false,
+ reason: `High cardinality dimension(s) '${highCardDims.join(", ")}' cannot be used with timeDimension. Time series queries with high cardinality dimensions produce unbounded result sets.`,
+ };
+ }
+
+ // 3. Validate required conditions for high cardinality
+ // Support both public API "config" and internal "chartConfig" field names
+ const chartConfig =
+ (query as unknown as { config?: QueryType["chartConfig"] }).config ??
+ query.chartConfig;
+ const hasExplicitLimit = chartConfig?.row_limit !== undefined;
+
+ // 4. Validate ORDER BY - must have at least one desc on a measure field
+ const orderByDescFields =
+ query.orderBy?.filter((o) => o.direction === "desc") ?? [];
+
+ if (!hasExplicitLimit || orderByDescFields.length === 0) {
+ return {
+ valid: false,
+ reason: `High cardinality dimension(s) '${highCardDims.join(", ")}' require both 'config.row_limit' and 'orderBy' with direction 'desc' on a measure field.`,
+ };
+ }
+
+ // Extract measure names from orderBy fields and validate they are measures in the query
+ const queryMeasureNames = query.metrics.map((m) => m.measure);
+ const invalidOrderByFields: string[] = [];
+
+ for (const orderBy of orderByDescFields) {
+ const matchedMeasure = findMeasureInOrderByField(
+ orderBy.field,
+ queryMeasureNames,
+ );
+ if (!matchedMeasure) {
+ invalidOrderByFields.push(orderBy.field);
+ }
+ }
+
+ if (invalidOrderByFields.length > 0) {
+ return {
+ valid: false,
+ reason:
+ `High cardinality dimension(s) '${highCardDims.join(", ")}' require 'orderBy' with direction 'desc' on a measure field. ` +
+ `'${invalidOrderByFields.join(", ")}' ${invalidOrderByFields.length === 1 ? "is" : "are"} not a measure in this query.`,
+ };
+ }
+
+ return { valid: true };
+}
+
+/**
+ * Extracts only query-engine fields from a widget's persisted chartConfig.
+ * Strips rendering-only fields (defaultSort, show_value_labels, etc.)
+ * that are only used by Chart components.
+ *
+ * Accepts any object with at least `type: string` — the discriminated union
+ * from ChartConfigSchema satisfies this via tRPC inference.
+ */
+export function toQueryChartConfig<
+ T extends { type: string; bins?: number; row_limit?: number },
+>(
+ widgetChartConfig: T,
+ options?: { defaultRowLimit?: number },
+): NonNullable<QueryType["chartConfig"]> {
+ const rowLimit = widgetChartConfig.row_limit ?? options?.defaultRowLimit;
+ return {
+ type: widgetChartConfig.type,
+ ...(widgetChartConfig.bins !== undefined && {
+ bins: widgetChartConfig.bins,
+ }),
+ ...(rowLimit !== undefined && { row_limit: rowLimit }),
+ };
+}
+
+/**
+ * Checks if a non-timeseries chart with a dimension on v2 needs top-N
+ * enforcement (orderBy desc + row_limit).
+ */
+export function isV2BreakdownChart(params: {
+ version: ViewVersion;
+ hasDimension: boolean;
+ isTimeSeries: boolean;
+ chartType: string;
+}): boolean {
+ return (
+ params.version === "v2" &&
+ params.hasDimension &&
+ !params.isTimeSeries &&
+ params.chartType !== "HISTOGRAM" &&
+ params.chartType !== "PIVOT_TABLE"
+ );
+}
+
+/**
+ * Builds the orderBy clause for a widget query.
+ * - PIVOT_TABLE: uses the provided sort state
+ * - v2 breakdown charts: auto-sorts desc on the first metric for top-N
+ * - Otherwise: null
+ */
+export function buildWidgetOrderBy(params: {
+ chartType: string;
+ sortState: { column: string; order: string } | null;
+ needsTopN: boolean;
+ firstMetric: { aggregation: string; measure: string } | undefined;
+}): QueryType["orderBy"] {
+ if (params.chartType === "PIVOT_TABLE" && params.sortState) {
+ return [
+ {
+ field: params.sortState.column,
+ direction: params.sortState.order.toLowerCase() as "asc" | "desc",
+ },
+ ];
+ }
+ if (params.needsTopN && params.firstMetric) {
+ return [
+ {
+ field: `${params.firstMetric.aggregation}_${params.firstMetric.measure}`,
+ direction: "desc",
+ },
+ ];
+ }
+ return null;
+}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index c15488ebc2..ed2b839eea 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -3,6 +3,7 @@ import { api } from "@/src/utils/api";
import {
type views,
type metricAggregations,
+ type QueryType,
mapLegacyUiTableFilterToView,
} from "@/src/features/query";
import { type z } from "zod/v4";
@@ -25,6 +26,12 @@ import { getChartLoadingStateProps } from "@/src/features/widgets/chart-library/
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import { type ViewVersion } from "@/src/features/query";
import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";
+import {
+ validateQuery,
+ toQueryChartConfig,
+ isV2BreakdownChart,
+ buildWidgetOrderBy,
+} from "@/src/features/query/validateQuery";
export interface WidgetPlacement {
id: string;
@@ -75,11 +82,6 @@ export function DashboardWidget({
useHasProjectAccess({ projectId, scope: "dashboards:CUD" }) &&
dashboardOwner !== "LANGFUSE";
- const fromTimestamp = dateRange
- ? dateRange.from
- : new Date(new Date().getTime() - 1000);
- const toTimestamp = dateRange ? dateRange.to : new Date();
-
// Initialize sort state for pivot tables
const defaultSort =
widget.data?.chartConfig.type === "PIVOT_TABLE"
@@ -102,43 +104,78 @@ export function DashboardWidget({
setSortState(newSort);
}, []);
+ const widgetQuery: QueryType = useMemo(() => {
+ const fromTimestamp = dateRange
+ ? dateRange.from
+ : new Date(new Date().getTime() - 1000);
+ const toTimestamp = dateRange ? dateRange.to : new Date();
+
+ const isTimeSeries = isTimeSeriesChart(
+ widget.data?.chartType ?? "LINE_TIME_SERIES",
+ );
+ const hasDimension = (widget.data?.dimensions ?? []).length > 0;
+ const chartType = widget.data?.chartConfig.type ?? "LINE_TIME_SERIES";
+ const needsTopN = isV2BreakdownChart({
+ version: metricsVersion,
+ hasDimension,
+ isTimeSeries,
+ chartType,
+ });
+
+ const firstMetric = widget.data?.metrics[0];
+ const orderBy = buildWidgetOrderBy({
+ chartType,
+ sortState,
+ needsTopN,
+ firstMetric: firstMetric
+ ? { aggregation: firstMetric.agg, measure: firstMetric.measure }
+ : undefined,
+ });
+
+ // Only query-engine fields — rendering fields (defaultSort, show_value_labels)
+ // stay on widget.data.chartConfig for the Chart component
+ const chartConfig = widget.data?.chartConfig
+ ? toQueryChartConfig(widget.data.chartConfig, {
+ defaultRowLimit: needsTopN ? 100 : undefined,
+ })
+ : { type: chartType };
+
+ return {
+ view: (widget.data?.view as z.infer<typeof views>) ?? "traces",
+ dimensions: widget.data?.dimensions ?? [],
+ metrics:
+ widget.data?.metrics.map((metric) => ({
+ measure: metric.measure,
+ aggregation: metric.agg as z.infer<typeof metricAggregations>,
+ })) ?? [],
+ filters: [
+ ...(widget.data?.filters ?? []),
+ ...mapLegacyUiTableFilterToView(
+ (widget.data?.view as z.infer<typeof views>) ?? "traces",
+ filterState,
+ ),
+ ],
+ timeDimension: isTimeSeries ? { granularity: "auto" as const } : null,
+ fromTimestamp: fromTimestamp.toISOString(),
+ toTimestamp: toTimestamp.toISOString(),
+ orderBy,
+ chartConfig,
+ };
+ }, [widget.data, filterState, dateRange, sortState, metricsVersion]);
+
+ const queryValidation = useMemo(
+ () =>
+ widget.data
+ ? validateQuery(widgetQuery, metricsVersion)
+ : ({ valid: true } as const),
+ [widgetQuery, metricsVersion, widget.data],
+ );
+
const queryResult = useScheduledDashboardExecuteQuery(
{
projectId,
version: metricsVersion,
- query: {
- view: (widget.data?.view as z.infer<typeof views>) ?? "traces",
- dimensions: widget.data?.dimensions ?? [],
- metrics:
- widget.data?.metrics.map((metric) => ({
- measure: metric.measure,
- aggregation: metric.agg as z.infer<typeof metricAggregations>,
- })) ?? [],
- filters: [
- ...(widget.data?.filters ?? []),
- ...mapLegacyUiTableFilterToView(
- (widget.data?.view as z.infer<typeof views>) ?? "traces",
- filterState,
- ),
- ],
- timeDimension: isTimeSeriesChart(
- widget.data?.chartType ?? "LINE_TIME_SERIES",
- )
- ? { granularity: "auto" }
- : null,
- fromTimestamp: fromTimestamp.toISOString(),
- toTimestamp: toTimestamp.toISOString(),
- orderBy:
- widget.data?.chartConfig.type === "PIVOT_TABLE" && sortState
- ? [
- {
- field: sortState.column,
- direction: sortState.order.toLowerCase() as "asc" | "desc",
- },
- ]
- : null,
- chartConfig: widget.data?.chartConfig,
- },
+ query: widgetQuery,
},
{
trpc: {
@@ -150,7 +187,8 @@ export function DashboardWidget({
meta: {
silentHttpCodes: [422],
},
- enabled: !widget.isPending && Boolean(widget.data),
+ enabled:
+ !widget.isPending && Boolean(widget.data) && queryValidation.valid,
},
);
@@ -325,42 +363,55 @@ export function DashboardWidget({
{widget.data.description}
</div>
<div className="relative min-h-0 flex-1">
- <Chart
- chartType={widget.data.chartType}
- data={transformedData}
- rowLimit={
- widget.data.chartConfig.type === "LINE_TIME_SERIES" ||
- widget.data.chartConfig.type === "BAR_TIME_SERIES" ||
- widget.data.chartConfig.type === "AREA_TIME_SERIES"
- ? 100
- : (widget.data.chartConfig.row_limit ?? 100)
- }
- chartConfig={{
- ...widget.data.chartConfig,
- // For PIVOT_TABLE, enhance chartConfig with dimensions and metric field names
- ...(widget.data.chartType === "PIVOT_TABLE" && {
- dimensions: widget.data.dimensions.map((dim) => dim.field),
- metrics: widget.data.metrics.map(
- (metric) => `${metric.agg}_${metric.measure}`,
- ),
- }),
- }}
- sortState={
- widget.data.chartType === "PIVOT_TABLE" ? sortState : undefined
- }
- onSortChange={
- widget.data.chartType === "PIVOT_TABLE" ? updateSort : undefined
- }
- isLoading={queryResult.isPending}
- />
- <ChartLoadingState
- isLoading={chartLoadingState.isLoading}
- showSpinner={chartLoadingState.showSpinner}
- showHintImmediately={chartLoadingState.showHintImmediately}
- hintText={chartLoadingState.hintText}
- className="absolute inset-0 z-20 bg-background/80 backdrop-blur-sm"
- hintClassName="max-w-sm px-4"
- />
+ {!queryValidation.valid ? (
+ <ChartLoadingState
+ isLoading={true}
+ showSpinner={false}
+ showHintImmediately={true}
+ hintText={queryValidation.reason}
+ className="absolute inset-0 z-20 bg-background/80 backdrop-blur-sm"
+ hintClassName="max-w-sm px-4"
+ />
+ ) : (
+ <>
+ <Chart
+ chartType={widget.data.chartType}
+ data={transformedData}
+ rowLimit={
+ widget.data.chartConfig.type === "LINE_TIME_SERIES" ||
+ widget.data.chartConfig.type === "BAR_TIME_SERIES" ||
+ widget.data.chartConfig.type === "AREA_TIME_SERIES"
+ ? 100
+ : (widget.data.chartConfig.row_limit ?? 100)
+ }
+ chartConfig={{
+ ...widget.data.chartConfig,
+ // For PIVOT_TABLE, enhance chartConfig with dimensions and metric field names
+ ...(widget.data.chartType === "PIVOT_TABLE" && {
+ dimensions: widget.data.dimensions.map((dim) => dim.field),
+ metrics: widget.data.metrics.map(
+ (metric) => `${metric.agg}_${metric.measure}`,
+ ),
+ }),
+ }}
+ sortState={
+ widget.data.chartType === "PIVOT_TABLE" ? sortState : undefined
+ }
+ onSortChange={
+ widget.data.chartType === "PIVOT_TABLE" ? updateSort : undefined
+ }
+ isLoading={queryResult.isPending}
+ />
+ <ChartLoadingState
+ isLoading={chartLoadingState.isLoading}
+ showSpinner={chartLoadingState.showSpinner}
+ showHintImmediately={chartLoadingState.showHintImmediately}
+ hintText={chartLoadingState.hintText}
+ className="absolute inset-0 z-20 bg-background/80 backdrop-blur-sm"
+ hintClassName="max-w-sm px-4"
+ />
+ </>
+ )}
</div>
</div>
);
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 4eb45dc691..78547daf88 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -48,6 +48,11 @@ import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { type FilterState } from "@langfuse/shared";
import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";
+import {
+ validateQuery,
+ isV2BreakdownChart,
+ buildWidgetOrderBy,
+} from "@/src/features/query/validateQuery";
import {
BarChart,
PieChart,
@@ -873,6 +878,37 @@ export function WidgetForm({
},
];
+ // For v2 non-timeseries breakdown charts, auto-sort desc by metric for top-N
+ const needsTopN = isV2BreakdownChart({
+ version: viewVersion,
+ hasDimension: selectedDimension !== "none",
+ isTimeSeries: isTimeSeriesChart(
+ selectedChartType as DashboardWidgetChartType,
+ ),
+ chartType: selectedChartType,
+ });
+
+ const orderBy = buildWidgetOrderBy({
+ chartType: selectedChartType,
+ sortState: previewSortState,
+ needsTopN,
+ firstMetric: {
+ aggregation: selectedAggregation,
+ measure: selectedMeasure,
+ },
+ });
+
+ // Only query-engine fields (type, bins, row_limit) — rendering fields
+ // (dimensions, defaultSort) go via handleSaveWidget / Chart component
+ let chartConfig: QueryType["chartConfig"];
+ if (selectedChartType === "HISTOGRAM") {
+ chartConfig = { type: selectedChartType, bins: histogramBins };
+ } else if (selectedChartType === "PIVOT_TABLE" || needsTopN) {
+ chartConfig = { type: selectedChartType, row_limit: rowLimit };
+ } else {
+ chartConfig = { type: selectedChartType };
+ }
+
return {
view: selectedView,
dimensions: queryDimensions,
@@ -885,34 +921,8 @@ export function WidgetForm({
: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
- orderBy:
- selectedChartType === "PIVOT_TABLE" && previewSortState
- ? [
- {
- field: previewSortState.column,
- direction: previewSortState.order.toLowerCase() as
- | "asc"
- | "desc",
- },
- ]
- : null,
- chartConfig:
- selectedChartType === "HISTOGRAM"
- ? { type: selectedChartType, bins: histogramBins }
- : selectedChartType === "PIVOT_TABLE"
- ? {
- type: selectedChartType,
- dimensions: pivotDimensions,
- row_limit: rowLimit,
- defaultSort:
- defaultSortColumn && defaultSortColumn !== "none"
- ? {
- column: defaultSortColumn,
- order: defaultSortOrder,
- }
- : undefined,
- }
- : { type: selectedChartType },
+ orderBy,
+ chartConfig,
};
}, [
selectedView,
@@ -926,11 +936,15 @@ export function WidgetForm({
histogramBins,
pivotDimensions,
rowLimit,
- defaultSortColumn,
- defaultSortOrder,
previewSortState,
+ viewVersion,
]);
+ const queryValidation = useMemo(
+ () => validateQuery(query, viewVersion),
+ [query, viewVersion],
+ );
+
const queryResult = api.dashboard.executeQuery.useQuery(
{
projectId,
@@ -946,6 +960,7 @@ export function WidgetForm({
meta: {
silentHttpCodes: [422],
},
+ enabled: queryValidation.valid,
},
);
@@ -1002,6 +1017,11 @@ export function WidgetForm({
);
const handleSaveWidget = () => {
+ if (!queryValidation.valid) {
+ showErrorToast("Invalid query", queryValidation.reason);
+ return;
+ }
+
if (!widgetName.trim()) {
showErrorToast("Error", "Widget name is required");
return;
@@ -1857,7 +1877,17 @@ export function WidgetForm({
{widgetDescription}
</CardDescription>
</CardHeader>
- {queryResult.data ? (
+ {!queryValidation.valid ? (
+ <CardContent>
+ <div className="flex h-[300px] items-center justify-center">
+ <Alert variant="destructive" className="max-w-sm">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Invalid query</AlertTitle>
+ <AlertDescription>{queryValidation.reason}</AlertDescription>
+ </Alert>
+ </div>
+ </CardContent>
+ ) : queryResult.data ? (
<div className="relative min-h-0 flex-1">
<Chart
chartType={selectedChartType as DashboardWidgetChartType}