Skip to content

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

feat(api): allow hight cardinality measures in v2/metrics when its topN (#11243)

Valery Meleshkin1ebc413df458
diff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/async/metrics-v2-api.servertest.ts
index c000679335..304600d6e7 100644
--- a/web/src/__tests__/async/metrics-v2-api.servertest.ts
+++ b/web/src/__tests__/async/metrics-v2-api.servertest.ts
@@ -411,7 +411,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
["sessionId", "scores-numeric"],
["observationId", "scores-numeric"],
])(
- "should reject high cardinality dimension %s in %s view",
+ "should reject high cardinality dimension %s in %s view without LIMIT and ORDER DESC",
async (dimensionField, viewName) => {
const query = {
view: viewName,
@@ -430,12 +430,37 @@ describe("/api/public/v2/metrics API Endpoint", () => {
expect(response.body).toMatchObject({
error: "InvalidRequestError",
message: expect.stringContaining(
- `Dimension '${dimensionField}' has high cardinality`,
+ `require both 'config.row_limit' and 'orderBy' with direction 'desc'`,
),
});
},
);
+ it("should reject high cardinality dimension without LIMIT", async () => {
+ const query = {
+ view: "observations",
+ dimensions: [{ field: "traceId" }],
+ metrics: [{ measure: "latency", aggregation: "sum" }],
+ orderBy: [{ field: "sum_latency", direction: "desc" }],
+ // Missing config.row_limit
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeAPICall(
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(400);
+ expect(response.body).toMatchObject({
+ error: "InvalidRequestError",
+ message: expect.stringContaining(
+ `require both 'config.row_limit' and 'orderBy' with direction 'desc'`,
+ ),
+ });
+ });
+
it("should allow high cardinality fields in filters", async () => {
const query = {
view: "observations",
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.ts
index cae9715181..8b870870a2 100644
--- a/web/src/__tests__/queryBuilder.servertest.ts
+++ b/web/src/__tests__/queryBuilder.servertest.ts
@@ -1,6 +1,9 @@
import { QueryBuilder } from "@/src/features/query/server/queryBuilder";
import { type QueryType } from "@/src/features/query/types";
-import { executeQuery } from "@/src/features/query/server/queryExecutor";
+import {
+ executeQuery,
+ validateQuery,
+} from "@/src/features/query/server/queryExecutor";
import {
createTrace,
createObservation,
@@ -3727,3 +3730,160 @@ describe("queryBuilder", () => {
});
});
});
+
+describe("validateQuery", () => {
+ const baseQuery = {
+ view: "observations",
+ dimensions: [],
+ metrics: [{ measure: "totalCost", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: "2025-01-01T00:00:00.000Z",
+ toTimestamp: "2025-03-01T00:00:00.000Z",
+ orderBy: null,
+ } as QueryType;
+
+ it("should return valid for queries without high cardinality dimensions", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "name" }], // name is not high cardinality
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result).toEqual({ valid: true });
+ });
+
+ it("should return invalid when high cardinality dimension is used without row_limit", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "traceId" }], // high cardinality
+ orderBy: [{ field: "sum_totalCost", direction: "desc" }],
+ // no chartConfig.row_limit
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result.valid).toBe(false);
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "High cardinality dimension(s) 'traceId'",
+ );
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "require both 'config.row_limit' and 'orderBy' with direction 'desc'",
+ );
+ });
+
+ it("should return invalid when high cardinality dimension is used without ORDER DESC", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "userId" }], // high cardinality
+ chartConfig: { type: "table", row_limit: 10 },
+ orderBy: [{ field: "sum_totalCost", direction: "asc" }], // asc, not desc
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result.valid).toBe(false);
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "High cardinality dimension(s) 'userId'",
+ );
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "require both 'config.row_limit' and 'orderBy' with direction 'desc'",
+ );
+ });
+
+ it("should return invalid when ORDER BY desc field is not a measure in the query", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "traceId" }], // high cardinality
+ chartConfig: { type: "table", row_limit: 10 },
+ orderBy: [{ field: "sum_latency", direction: "desc" }], // latency is not in metrics
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result.valid).toBe(false);
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "High cardinality dimension(s) 'traceId'",
+ );
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "'sum_latency'",
+ );
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "not a measure in this query",
+ );
+ });
+
+ it("should return invalid when ORDER BY desc field is a dimension (not a measure)", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "traceId" }, { field: "name" }], // traceId is high cardinality
+ chartConfig: { type: "table", row_limit: 10 },
+ orderBy: [{ field: "name", direction: "desc" }], // name is a dimension, not a measure
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result.valid).toBe(false);
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "High cardinality dimension(s) 'traceId'",
+ );
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "'name'",
+ );
+ expect((result as { valid: false; reason: string }).reason).toContain(
+ "not a measure in this query",
+ );
+ });
+
+ it("should return invalid for multiple high cardinality dimensions without required config", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "traceId" }, { field: "sessionId" }], // both high cardinality
+ // missing row_limit and orderBy desc
+ };
+
+ 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(
+ "sessionId",
+ );
+ });
+
+ it("should support public API 'config' field name for row_limit", () => {
+ // Test that "config" field works (used by public API) vs "chartConfig" (used internally)
+ const query = {
+ view: "observations",
+ dimensions: [{ field: "traceId" }], // high cardinality
+ metrics: [{ measure: "totalCost", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: [{ field: "totalCost", direction: "desc" }],
+ config: { type: "table", row_limit: 10 }, // Public API uses "config"
+ } as unknown as QueryType;
+
+ const result = validateQuery(query, "v2");
+
+ expect(result).toEqual({ valid: true });
+ });
+
+ it("should return valid for count-only metrics with high cardinality", () => {
+ const query: QueryType = {
+ ...baseQuery,
+ dimensions: [{ field: "traceId" }],
+ metrics: [{ measure: "count", aggregation: "count" }], // count-only
+ orderBy: [{ field: "count", direction: "desc" }],
+ chartConfig: { type: "table", row_limit: 10 },
+ };
+
+ const result = validateQuery(query, "v2");
+
+ expect(result).toEqual({ valid: true });
+ });
+});
diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.ts
index c7a75e66ae..9d02bcee3a 100644
--- a/web/src/features/query/server/queryBuilder.ts
+++ b/web/src/features/query/server/queryBuilder.ts
@@ -33,6 +33,7 @@ type AppliedMetricType = {
alias?: string;
relationTable?: string;
aggs?: Record<string, string>;
+ measureName: string; // Original measure name for lookups
};
export class QueryBuilder {
@@ -120,6 +121,7 @@ export class QueryBuilder {
...view.measures[metric.measure],
aggregation: metric.aggregation,
aggs: view.measures[metric.measure].aggs,
+ measureName: metric.measure,
};
});
}
@@ -401,10 +403,10 @@ export class QueryBuilder {
aggs: Record<string, string>,
): string {
let result = sql;
- // Replace each @@AGGN@@ placeholder with its corresponding aggregation function
- for (const [placeholder, aggFunc] of Object.entries(aggs)) {
+ // Replace each @@AGGN@@ placeholder with its corresponding value
+ for (const [placeholder, replacement] of Object.entries(aggs)) {
const marker = `@@${placeholder.toUpperCase()}@@`;
- result = result.replaceAll(marker, aggFunc);
+ result = result.replaceAll(marker, replacement);
}
return result;
}
diff --git a/web/src/features/query/server/queryExecutor.ts b/web/src/features/query/server/queryExecutor.ts
index 54ba5898c4..3a2708caab 100644
--- a/web/src/features/query/server/queryExecutor.ts
+++ b/web/src/features/query/server/queryExecutor.ts
@@ -5,8 +5,133 @@ import {
} from "@langfuse/shared/src/server";
import { QueryBuilder } from "@/src/features/query/server/queryBuilder";
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 };
+}
+
/**
* Compares two query results for equivalence.
* Returns true if results match, false otherwise.
diff --git a/web/src/pages/api/public/v2/metrics.ts b/web/src/pages/api/public/v2/metrics.ts
index 7dc5aeb616..8e5b6f8d3b 100644
--- a/web/src/pages/api/public/v2/metrics.ts
+++ b/web/src/pages/api/public/v2/metrics.ts
@@ -6,37 +6,14 @@ import {
GetMetricsV2Query,
GetMetricsV2Response,
} from "@/src/features/public-api/types/metrics";
-import { executeQuery } from "@/src/features/query/server/queryExecutor";
-import { getViewDeclaration } from "@/src/features/query/dataModel";
import { InvalidRequestError, NotImplementedError } from "@langfuse/shared";
+import {
+ executeQuery,
+ validateQuery,
+} from "@/src/features/query/server/queryExecutor";
const DEFAULT_ROW_LIMIT = 100;
-/**
- * Validates that no high cardinality dimensions are used in the query.
- * High cardinality dimensions (id, traceId, userId, sessionId, etc.) are not
- * supported in the v2 metrics API as they can cause performance issues.
- */
-function validateNoHighCardinalityDimensions(queryParams: {
- view: string;
- dimensions?: Array<{ field: string }>;
-}): void {
- if (!queryParams.dimensions || queryParams.dimensions.length === 0) {
- return;
- }
-
- const view = getViewDeclaration(queryParams.view as any, "v2");
-
- for (const dimension of queryParams.dimensions) {
- const dim = view.dimensions[dimension.field];
- if (dim?.highCardinality) {
- throw new InvalidRequestError(
- `Dimension '${dimension.field}' has high cardinality and is not supported in v2 metrics API. Use filters instead.`,
- );
- }
- }
-}
-
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
name: "Get Metrics V2",
@@ -51,18 +28,23 @@ export default withMiddlewares({
}
try {
+ // Validate query (high cardinality checks) BEFORE applying defaults
+ // This ensures users must explicitly opt-in with row_limit for high cardinality queries
+ const validation = validateQuery(query.query as any, "v2");
+
+ if (!validation.valid) {
+ throw new InvalidRequestError(validation.reason);
+ }
+
+ // Apply default row_limit AFTER validation
const queryParams = {
...query.query,
- // Apply default row_limit if not specified
config: {
...query.query.config,
row_limit: query.query.config?.row_limit ?? DEFAULT_ROW_LIMIT,
},
};
- // Validate no high cardinality dimensions are used
- validateNoHighCardinalityDimensions(queryParams);
-
logger.info("Received v2 metrics query", {
query: queryParams,
version: "v2",