Skip to content

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

fix(api): prevent v2/metrics from accepting hight cardinality dimensions (#11203)

Valery Meleshkin95d3fdc5a19b
diff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/async/metrics-v2-api.servertest.ts
index a5c3b9c049..8d41970e60 100644
--- a/web/src/__tests__/async/metrics-v2-api.servertest.ts
+++ b/web/src/__tests__/async/metrics-v2-api.servertest.ts
@@ -350,7 +350,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
});
maybe("Denormalized Trace Fields", () => {
- it.each([["traceId"], ["userId"], ["sessionId"], ["tags"], ["release"]])(
+ it.each([["tags"], ["release"]])(
"Denormalized field: %s",
async (field) => {
const query = {
@@ -381,12 +381,74 @@ describe("/api/public/v2/metrics API Endpoint", () => {
it("should support multiple denormalized dimensions together", async () => {
const query = {
view: "observations",
- dimensions: [
- { field: "userId" },
- { field: "sessionId" },
- { field: "tags" },
- ],
+ dimensions: [{ field: "tags" }, { field: "release" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV1Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ });
+ });
+
+ maybe("High Cardinality Dimension Validation", () => {
+ it.each([
+ ["id", "observations"],
+ ["traceId", "observations"],
+ ["userId", "observations"],
+ ["sessionId", "observations"],
+ ["parentObservationId", "observations"],
+ ["id", "scores-numeric"],
+ ["traceId", "scores-numeric"],
+ ["userId", "scores-numeric"],
+ ["sessionId", "scores-numeric"],
+ ["observationId", "scores-numeric"],
+ ])(
+ "should reject high cardinality dimension %s in %s view",
+ async (dimensionField, viewName) => {
+ const query = {
+ view: viewName,
+ dimensions: [{ field: dimensionField }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ 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(
+ `Dimension '${dimensionField}' has high cardinality`,
+ ),
+ });
+ },
+ );
+
+ it("should allow high cardinality fields in filters", async () => {
+ const query = {
+ view: "observations",
+ dimensions: [{ field: "name" }],
metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "traceId",
+ operator: "=",
+ value: traceId,
+ type: "string",
+ },
+ ],
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
toTimestamp: new Date().toISOString(),
};
@@ -736,11 +798,19 @@ describe("/api/public/v2/metrics API Endpoint", () => {
);
});
- it("should support sessionId dimension from scores table", async () => {
+ it("should support filtering by sessionId from scores table", async () => {
const query = {
view: "scores-numeric",
- dimensions: [{ field: "sessionId" }],
+ dimensions: [{ field: "name" }],
metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "sessionId",
+ operator: "=",
+ value: scoreSessionId,
+ type: "string",
+ },
+ ],
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
toTimestamp: new Date().toISOString(),
};
@@ -753,12 +823,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
-
- // Find our test session
- const nonEmptyRows = response.body.data.filter(
- (row: any) => row.sessionId && row.count_count > 0,
- );
- expect(nonEmptyRows.length).toBeGreaterThanOrEqual(1);
+ expect(response.body.data.length).toBeGreaterThan(0);
});
it("should support filtering by sessionId", async () => {
@@ -896,11 +961,6 @@ describe("/api/public/v2/metrics API Endpoint", () => {
eventsScoreTraceName,
(row: any) => row.traceName === eventsScoreTraceName,
],
- [
- "userId",
- eventsScoreUserId,
- (row: any) => row.userId === eventsScoreUserId,
- ],
["tags", eventsScoreTags, (row: any) => Array.isArray(row.tags)],
[
"traceRelease",
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index 61c4aa47de..4b4e3a8519 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -164,6 +164,7 @@ export const eventsTracesView: ViewDeclarationType = {
alias: "id",
type: "string",
description: "Unique identifier of the trace.",
+ highCardinality: true,
// This is the GROUP BY identity column
},
name: {
@@ -190,6 +191,7 @@ export const eventsTracesView: ViewDeclarationType = {
description: "Identifier of the user triggering the trace.",
aggregationFunction:
"argMaxIf(events_traces.user_id, events_traces.event_ts, events_traces.user_id <> '')",
+ highCardinality: true,
},
sessionId: {
sql: "nullIf(events_traces.session_id, '')",
@@ -198,6 +200,7 @@ export const eventsTracesView: ViewDeclarationType = {
description: "Identifier of the session triggering the trace.",
aggregationFunction:
"argMaxIf(events_traces.session_id, events_traces.event_ts, events_traces.session_id <> '')",
+ highCardinality: true,
},
release: {
sql: "nullIf(events_traces.release, '')",
@@ -641,6 +644,7 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {
alias: "sessionId",
type: "string",
description: "Identifier of the session.",
+ highCardinality: true,
},
// Trace metadata on events table (accessed via events_traces JOIN)
traceName: {
@@ -656,6 +660,7 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {
type: "string",
relationTable: "events_traces",
description: "Identifier of the user.",
+ highCardinality: true,
},
tags: {
sql: "events_traces.tags",
@@ -712,12 +717,14 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {
// Factory for shared score-specific dimensions (both numeric and categorical)
const createScoreSpecificDimensions = (
tableAlias: string,
+ isV2: boolean = false,
): DimensionsDeclarationType => ({
id: {
sql: `${tableAlias}.id`,
alias: "id",
type: "string",
description: "Unique identifier of the score entry.",
+ ...(isV2 && { highCardinality: true }),
},
environment: {
sql: `${tableAlias}.environment`,
@@ -749,6 +756,7 @@ const createScoreSpecificDimensions = (
alias: "traceId",
type: "string",
description: "Identifier of the parent trace.",
+ ...(isV2 && { highCardinality: true }),
},
configId: {
sql: `${tableAlias}.config_id`,
@@ -773,6 +781,7 @@ const createScoreSpecificDimensions = (
alias: "observationId",
type: "string",
description: "Identifier of the observation associated with the score.",
+ ...(isV2 && { highCardinality: true }),
},
});
@@ -825,7 +834,7 @@ function scoresNumericViewBase(version: "v1" | "v2"): ViewDeclarationType {
"Scores are flexible objects that are used for evaluations. This view contains numeric and boolean scores.",
dimensions: {
...baseDimensions, // v1 keeps trace-JOIN dimensions
- ...createScoreSpecificDimensions("scores_numeric"),
+ ...createScoreSpecificDimensions("scores_numeric", version === "v2"),
value: {
sql: "scores_numeric.value",
alias: "value",
@@ -872,7 +881,7 @@ function scoresCategoricalViewBase(version: "v1" | "v2"): ViewDeclarationType {
"Scores are flexible objects that are used for evaluations. This view contains categorical scores.",
dimensions: {
...baseDimensions,
- ...createScoreSpecificDimensions("scores_categorical"),
+ ...createScoreSpecificDimensions("scores_categorical", version === "v2"),
stringValue: {
sql: "string_value",
alias: "stringValue",
@@ -927,12 +936,14 @@ export const eventsObservationsView: ViewDeclarationType = {
alias: "id",
type: "string",
description: "Unique identifier for the observation.",
+ highCardinality: true,
},
traceId: {
sql: "events_observations.trace_id",
alias: "traceId",
type: "string",
description: "Identifier linking the observation to its parent trace.",
+ highCardinality: true,
},
environment: {
sql: "nullIf(events_observations.environment, '')",
@@ -946,6 +957,7 @@ export const eventsObservationsView: ViewDeclarationType = {
type: "string",
description:
"Identifier of the parent observation. Empty for the root span.",
+ highCardinality: true,
},
type: {
sql: "events_observations.type",
@@ -978,12 +990,14 @@ export const eventsObservationsView: ViewDeclarationType = {
alias: "userId",
type: "string",
description: "Identifier of the user triggering the observation.",
+ highCardinality: true,
},
sessionId: {
sql: "nullIf(events_observations.session_id, '')",
alias: "sessionId",
type: "string",
description: "Identifier of the session triggering the observation.",
+ highCardinality: true,
},
tags: {
sql: "events_observations.tags",
diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.ts
index 2fa4ca12f0..0c289716ea 100644
--- a/web/src/features/query/types.ts
+++ b/web/src/features/query/types.ts
@@ -21,6 +21,7 @@ export const viewDeclaration = z.object({
type: z.string().optional(),
unit: z.string().optional(),
aggregationFunction: z.string().optional(),
+ highCardinality: z.boolean().optional(),
}),
),
measures: z.record(
diff --git a/web/src/pages/api/public/v2/metrics.ts b/web/src/pages/api/public/v2/metrics.ts
index b70da26005..abdd0fc476 100644
--- a/web/src/pages/api/public/v2/metrics.ts
+++ b/web/src/pages/api/public/v2/metrics.ts
@@ -6,9 +6,36 @@ import {
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 } from "@langfuse/shared";
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",
@@ -26,6 +53,9 @@ export default withMiddlewares({
},
};
+ // Validate no high cardinality dimensions are used
+ validateNoHighCardinalityDimensions(queryParams);
+
logger.info("Received v2 metrics query", {
query: queryParams,
version: "v2",