Skip to content

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

chore(metrics-api): return bad request errors for invalid query (#6826)

Steffen Schmitzafbd45b9c396
diff --git a/web/src/__tests__/async/metrics-api.servertest.ts b/web/src/__tests__/async/metrics-api.servertest.ts
index ea32505805..8c8fb0e17e 100644
--- a/web/src/__tests__/async/metrics-api.servertest.ts
+++ b/web/src/__tests__/async/metrics-api.servertest.ts
@@ -299,4 +299,104 @@ describe("/api/public/metrics API Endpoint", () => {
expect(status).toBe(400);
});
+
+ it("should return 400 for invalid metric measure", async () => {
+ // Build a query with an invalid metric measure (name)
+ const invalidMetricNameQuery = {
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "invalidMetric", aggregation: "count" }],
+ fromTimestamp: new Date(
+ new Date().getTime() - 3600 * 24 * 1000,
+ ).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const { status, body } = await makeAPICall(
+ "GET",
+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidMetricNameQuery))}`,
+ undefined,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toHaveProperty("error");
+ expect(body.message).toMatch(/Invalid metric/);
+ });
+
+ it("should return 400 for invalid metric aggregation", async () => {
+ // Build a query with an invalid aggregation method
+ const invalidAggregationQuery = {
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "invalidAggregation" }],
+ fromTimestamp: new Date(
+ new Date().getTime() - 3600 * 24 * 1000,
+ ).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const { status, body } = await makeAPICall(
+ "GET",
+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidAggregationQuery))}`,
+ undefined,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toHaveProperty("error");
+ expect(body.message).toMatch(/Invalid request data/);
+ });
+
+ it("should return 400 for invalid dimension", async () => {
+ // Build a query with an invalid dimension
+ const invalidDimensionQuery = {
+ view: "traces",
+ dimensions: [{ field: "nonExistentDimension" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(
+ new Date().getTime() - 3600 * 24 * 1000,
+ ).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const { status, body } = await makeAPICall(
+ "GET",
+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidDimensionQuery))}`,
+ undefined,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toHaveProperty("error");
+ expect(body.message).toMatch(/Invalid dimension/);
+ });
+
+ it("should return 400 for invalid filter column", async () => {
+ // Build a query with an invalid filter column
+ const invalidFilterQuery = {
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "nonExistentColumn",
+ operator: "=",
+ value: "test",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(
+ new Date().getTime() - 3600 * 24 * 1000,
+ ).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const { status, body } = await makeAPICall(
+ "GET",
+ `/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidFilterQuery))}`,
+ undefined,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toHaveProperty("error");
+ expect(body.message).toMatch(/Invalid filter column/);
+ });
});
diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.ts
index df94fed792..c5409993a9 100644
--- a/web/src/features/query/server/queryBuilder.ts
+++ b/web/src/features/query/server/queryBuilder.ts
@@ -13,6 +13,7 @@ import {
FilterList,
createFilterFromFilterState,
} from "@langfuse/shared/src/server";
+import { InvalidRequestError } from "@langfuse/shared";
type AppliedDimensionType = {
table: string;
@@ -56,7 +57,7 @@ export class QueryBuilder {
default:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const exhaustiveCheck: never = aggregation;
- throw new Error(`Invalid aggregation: ${aggregation}`);
+ throw new InvalidRequestError(`Invalid aggregation: ${aggregation}`);
}
}
@@ -64,7 +65,7 @@ export class QueryBuilder {
viewName: z.infer<typeof views>,
): ViewDeclarationType {
if (!(viewName in viewDeclarations)) {
- throw new Error(
+ throw new InvalidRequestError(
`Invalid view. Must be one of ${Object.keys(viewDeclarations)}`,
);
}
@@ -77,7 +78,7 @@ export class QueryBuilder {
): AppliedDimensionType[] {
return dimensions.map((dimension) => {
if (!(dimension.field in view.dimensions)) {
- throw new Error(
+ throw new InvalidRequestError(
`Invalid dimension ${dimension.field}. Must be one of ${Object.keys(view.dimensions)}`,
);
}
@@ -95,7 +96,7 @@ export class QueryBuilder {
): AppliedMetricType[] {
return metrics.map((metric) => {
if (!(metric.measure in view.measures)) {
- throw new Error(
+ throw new InvalidRequestError(
`Invalid metric ${metric.measure}. Must be one of ${Object.keys(view.measures)}`,
);
}
@@ -138,7 +139,7 @@ export class QueryBuilder {
clickhouseSelect = "metadata";
type = "stringObject";
} else {
- throw new Error(
+ throw new InvalidRequestError(
`Invalid filter column ${filter.column}. Must be one of ${Object.keys(view.dimensions)} or ${view.timeDimension}`,
);
}
@@ -281,7 +282,7 @@ export class QueryBuilder {
const relationJoins = [];
for (const relationTableName of relationTables) {
if (!(relationTableName in view.tableRelations)) {
- throw new Error(
+ throw new InvalidRequestError(
`Invalid relationTable: ${relationTableName}. Must be one of ${Object.keys(view.tableRelations)}`,
);
}
@@ -393,7 +394,7 @@ export class QueryBuilder {
default:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const exhaustiveCheck: never = granularity;
- throw new Error(
+ throw new InvalidRequestError(
`Invalid time granularity: ${granularity}. Must be one of minute, hour, day, week, month`,
);
}
@@ -659,7 +660,7 @@ export class QueryBuilder {
}
}
- throw new Error(
+ throw new InvalidRequestError(
`Invalid orderBy field: ${item.field}. Must be one of the dimension or metric fields.`,
);
});
@@ -709,7 +710,7 @@ export class QueryBuilder {
// Run zod validation
const parseResult = queryModel.safeParse(query);
if (!parseResult.success) {
- throw new Error(
+ throw new InvalidRequestError(
`Invalid query: ${JSON.stringify(parseResult.error.errors)}`,
);
}