Skip to content

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

fix(dashboards): preserve legacy traces v4 compatibility (#15687)

Valery Meleshkincfac48524365
diff --git a/packages/shared/src/features/query/dataModel.ts b/packages/shared/src/features/query/dataModel.ts
index c63f625fa3..a450e89f89 100644
--- a/packages/shared/src/features/query/dataModel.ts
+++ b/packages/shared/src/features/query/dataModel.ts
@@ -160,12 +160,16 @@ export const eventsTracesView: ViewDeclarationType = {
description:
"Traces built from events table aggregation - mirrors v1 traces view with 100% API compatibility.",
dimensions: {
+ // This is an internal compatibility declaration for persisted v1 trace
+ // widgets. Keep id/userId/sessionId cardinality metadata aligned with v1:
+ // enabling V4 must not invalidate existing time-series breakdowns. New
+ // traces widgets remain unavailable through the public V4 widget path. Do
+ // not add highCardinality here: v1 does not set it for these dimensions.
id: {
sql: "events_traces.trace_id",
alias: "id",
type: "string",
description: "Unique identifier of the trace.",
- highCardinality: true,
// This is the GROUP BY identity column
},
name: {
@@ -198,7 +202,6 @@ 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, '')",
@@ -207,7 +210,6 @@ 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, '')",
@@ -266,22 +268,48 @@ export const eventsTracesView: ViewDeclarationType = {
unit: "scores",
},
uniqueUserIds: {
- sql: "@@AGG@@(nullIf(events_traces.user_id, ''))",
- aggs: { agg: "any" },
+ // Keep this numeric base aligned with v1: persisted widgets may use any
+ // numeric aggregation. The count/uniq overrides below preserve distinct
+ // identifier semantics over the denormalized events table.
+ sql: "uniq(nullIf(events_traces.user_id, ''))",
alias: "uniqueUserIds",
- type: "string",
- description:
- "User identifier; apply uniq aggregation to count distinct users.",
+ type: "integer",
+ description: "Count of unique userIds.",
unit: "users",
+ aggregationOverrides: {
+ // Legacy widgets called this aggregation `count`, but its intended
+ // result is distinct users. Remap only the generated query to `uniq`
+ // while preserving the persisted aggregation and `count_*` alias.
+ count: {
+ sql: "argMaxIf(nullIf(events_traces.user_id, ''), events_traces.event_ts, events_traces.user_id <> '')",
+ type: "string",
+ queryAggregation: "uniq",
+ },
+ uniq: {
+ sql: "argMaxIf(nullIf(events_traces.user_id, ''), events_traces.event_ts, events_traces.user_id <> '')",
+ type: "string",
+ },
+ },
},
uniqueSessionIds: {
- sql: "@@AGG@@(nullIf(events_traces.session_id, ''))",
- aggs: { agg: "any" },
+ sql: "uniq(nullIf(events_traces.session_id, ''))",
alias: "uniqueSessionIds",
- type: "string",
- description:
- "Session identifier; apply uniq aggregation to count distinct sessions.",
+ type: "integer",
+ description: "Count of unique sessionIds.",
unit: "sessions",
+ aggregationOverrides: {
+ // See uniqueUserIds: keep the legacy `count` contract while executing
+ // the aggregation with distinct-value semantics.
+ count: {
+ sql: "argMaxIf(nullIf(events_traces.session_id, ''), events_traces.event_ts, events_traces.session_id <> '')",
+ type: "string",
+ queryAggregation: "uniq",
+ },
+ uniq: {
+ sql: "argMaxIf(nullIf(events_traces.session_id, ''), events_traces.event_ts, events_traces.session_id <> '')",
+ type: "string",
+ },
+ },
},
latency: {
sql: "date_diff('millisecond', minIf(events_traces.start_time, events_traces.parent_span_id != ''), maxIf(events_traces.end_time, events_traces.parent_span_id != ''))",
diff --git a/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.ts b/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.ts
index 7888b2472f..b29cc4160a 100644
--- a/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.ts
+++ b/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import type { FilterCondition } from "../../../types";
import { getViewDeclaration } from "../dataModel";
import type { QueryType, ViewVersion } from "../types";
+import { validateQuery } from "../validateQuery";
import { QueryBuilder } from "./queryBuilder";
// QueryBuilder.build checks the OTEL FINAL optimization before filter lowering.
@@ -200,3 +201,115 @@ describe("queryBuilder filter type validation", () => {
).rejects.toThrow(/Invalid filter column isRootObservation/);
});
});
+
+describe("legacy traces compatibility when routed through v2", () => {
+ it.each([
+ ["uniqueUserIds", "user_id"],
+ ["uniqueSessionIds", "session_id"],
+ ] as const)(
+ "preserves the legacy numeric fallback for max(%s) in v2",
+ async (measure, column) => {
+ const query = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure, aggregation: "max" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: "2025-01-01T00:00:00.000Z",
+ toTimestamp: "2025-01-02T00:00:00.000Z",
+ orderBy: null,
+ } as QueryType;
+
+ await expect(
+ new QueryBuilder(undefined, "v1").build(query, "test-project"),
+ ).resolves.toBeDefined();
+
+ const { query: compiledQuery } = await new QueryBuilder(
+ undefined,
+ "v2",
+ ).build(query, "test-project", true);
+
+ expect(compiledQuery).toContain(
+ `uniq(nullIf(events_traces.${column}, '')) as ${measure}`,
+ );
+ expect(compiledQuery).toContain(`max(${measure}) as max_${measure}`);
+ },
+ );
+
+ it.each([
+ ["uniqueUserIds", "user_id"],
+ ["uniqueSessionIds", "session_id"],
+ ] as const)(
+ "remaps count(%s) to uniq while preserving the legacy result alias",
+ async (measure, column) => {
+ const query = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure, aggregation: "count" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: "2025-01-01T00:00:00.000Z",
+ toTimestamp: "2025-01-02T00:00:00.000Z",
+ orderBy: null,
+ } as QueryType;
+
+ const { query: twoLevelQuery } = await new QueryBuilder(
+ undefined,
+ "v2",
+ ).build(query, "test-project");
+
+ expect(twoLevelQuery).toContain(
+ `argMaxIf(nullIf(events_traces.${column}, ''), events_traces.event_ts, events_traces.${column} <> '') as ${measure}`,
+ );
+ expect(twoLevelQuery).toContain(`uniq(${measure}) as count_${measure}`);
+ },
+ );
+
+ it.each([
+ ["uniqueUserIds", "user_id"],
+ ["uniqueSessionIds", "session_id"],
+ ] as const)(
+ "uses canonical per-trace uniq aggregation for %s",
+ async (measure, column) => {
+ const query = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure, aggregation: "uniq" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: "2025-01-01T00:00:00.000Z",
+ toTimestamp: "2025-01-02T00:00:00.000Z",
+ orderBy: null,
+ } as QueryType;
+
+ const { query: compiledQuery } = await new QueryBuilder(
+ undefined,
+ "v2",
+ ).build(query, "test-project");
+
+ expect(compiledQuery).toContain(
+ `argMaxIf(nullIf(events_traces.${column}, ''), events_traces.event_ts, events_traces.${column} <> '') as ${measure}`,
+ );
+ expect(compiledQuery).toContain(`uniq(${measure}) as uniq_${measure}`);
+ },
+ );
+
+ it.each(["id", "userId", "sessionId"] as const)(
+ "keeps a legacy %s time-series breakdown valid in v2",
+ (dimension) => {
+ const query = {
+ view: "traces",
+ dimensions: [{ field: dimension }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: { granularity: "auto" },
+ fromTimestamp: "2025-01-01T00:00:00.000Z",
+ toTimestamp: "2025-01-02T00:00:00.000Z",
+ orderBy: null,
+ } as QueryType;
+
+ expect(validateQuery(query, "v1")).toEqual({ valid: true });
+ expect(validateQuery(query, "v2")).toEqual({ valid: true });
+ },
+ );
+});
diff --git a/packages/shared/src/features/query/server/queryBuilder.ts b/packages/shared/src/features/query/server/queryBuilder.ts
index 425f97ff80..46f426c1d8 100644
--- a/packages/shared/src/features/query/server/queryBuilder.ts
+++ b/packages/shared/src/features/query/server/queryBuilder.ts
@@ -43,6 +43,7 @@ type AppliedDimensionType = {
type AppliedMetricType = {
sql: string;
aggregation: z.infer<typeof metricAggregations>;
+ queryAggregation?: z.infer<typeof metricAggregations>;
alias?: string;
relationTable?: string;
aggs?: Record<string, string>;
@@ -135,7 +136,9 @@ export class QueryBuilder {
}
private translateAggregation(metric: AppliedMetricType): string {
- switch (metric.aggregation) {
+ const aggregation = metric.queryAggregation ?? metric.aggregation;
+
+ switch (aggregation) {
case "sum":
return `sum(${metric.alias || metric.sql})`;
case "avg":
@@ -165,9 +168,9 @@ export class QueryBuilder {
return `uniq(${metric.alias || metric.sql})`;
default: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
- const exhaustiveCheck: never = metric.aggregation;
+ const exhaustiveCheck: never = aggregation;
throw new InvalidRequestError(
- `Invalid aggregation: ${metric.aggregation satisfies never}`,
+ `Invalid aggregation: ${aggregation satisfies never}`,
);
}
}
@@ -301,16 +304,23 @@ export class QueryBuilder {
);
}
const measureDef = view.measures[metric.measure];
- const validAggs = getValidAggregationsForMeasureType(measureDef.type);
+ const aggregationOverride =
+ measureDef.aggregationOverrides?.[metric.aggregation];
+ const resolvedMeasureDef = aggregationOverride
+ ? { ...measureDef, ...aggregationOverride }
+ : measureDef;
+ const validAggs = getValidAggregationsForMeasureType(
+ resolvedMeasureDef.type,
+ );
if (!validAggs.includes(metric.aggregation)) {
throw new InvalidRequestError(
- `Aggregation "${metric.aggregation}" is not valid for measure "${metric.measure}" (type: ${measureDef.type}). Valid aggregations: ${validAggs.join(", ")}`,
+ `Aggregation "${metric.aggregation}" is not valid for measure "${metric.measure}" (type: ${resolvedMeasureDef.type}). Valid aggregations: ${validAggs.join(", ")}`,
);
}
return {
- ...view.measures[metric.measure],
+ ...resolvedMeasureDef,
aggregation: metric.aggregation,
- aggs: view.measures[metric.measure].aggs,
+ aggs: resolvedMeasureDef.aggs,
measureName: metric.measure,
};
});
diff --git a/packages/shared/src/features/query/types.ts b/packages/shared/src/features/query/types.ts
index a80c1447a1..039734e3a5 100644
--- a/packages/shared/src/features/query/types.ts
+++ b/packages/shared/src/features/query/types.ts
@@ -1,6 +1,21 @@
import { z } from "zod";
import { singleFilter } from "../../interfaces/filters";
+export const metricAggregations = z.enum([
+ "sum",
+ "avg",
+ "count",
+ "max",
+ "min",
+ "p50",
+ "p75",
+ "p90",
+ "p95",
+ "p99",
+ "histogram",
+ "uniq",
+]);
+
export type ViewDeclarationType = z.infer<typeof viewDeclaration>;
export type DimensionsDeclarationType = z.infer<
typeof viewDeclaration
@@ -50,6 +65,19 @@ export const viewDeclaration = z.object({
type: z.string().optional(),
unit: z.string().optional(),
aggs: z.record(z.string(), z.string()).optional(),
+ // Override query semantics for specific user-selected aggregations while
+ // keeping the base declaration as the UI/default compatibility contract.
+ aggregationOverrides: z
+ .record(
+ z.string(),
+ z.object({
+ sql: z.string(),
+ type: z.string().optional(),
+ aggs: z.record(z.string(), z.string()).optional(),
+ queryAggregation: metricAggregations.optional(),
+ }),
+ )
+ .optional(),
// When set, the query builder will auto-include this dimension if it is absent.
// Used for pairExpand value-alias measures (e.g. costByType requires costType so
// the ARRAY JOIN is emitted and "cost_value" is in scope).
@@ -107,21 +135,6 @@ export const dimension = z.object({
field: z.string(),
});
-export const metricAggregations = z.enum([
- "sum",
- "avg",
- "count",
- "max",
- "min",
- "p50",
- "p75",
- "p90",
- "p95",
- "p99",
- "histogram",
- "uniq",
-]);
-
/** MeasureDefinition is a single `measures` entry on a ViewDeclaration. */
export type MeasureDefinition = ViewDeclarationType["measures"][string];
diff --git a/web/src/__tests__/server/queryBuilder.servertest.ts b/web/src/__tests__/server/queryBuilder.servertest.ts
index 0f5c07e47a..b94814fbf1 100644
--- a/web/src/__tests__/server/queryBuilder.servertest.ts
+++ b/web/src/__tests__/server/queryBuilder.servertest.ts
@@ -4807,24 +4807,6 @@ describe("query builder measure-aggregation validation", () => {
expect(result.query).toBeDefined();
});
- it("should reject sum aggregation for uniqueUserIds on traces view", async () => {
- const query: QueryType = {
- view: "traces",
- dimensions: [],
- metrics: [{ measure: "uniqueUserIds", aggregation: "sum" }],
- filters: [],
- timeDimension: null,
- fromTimestamp: "2025-01-01T00:00:00.000Z",
- toTimestamp: "2025-03-01T00:00:00.000Z",
- orderBy: null,
- };
-
- const queryBuilder = new QueryBuilder(undefined, "v2");
- await expect(queryBuilder.build(query, randomUUID())).rejects.toThrow(
- /not valid for measure/,
- );
- });
-
it("should accept uniq aggregation for uniqueUserIds on traces view", async () => {
const query: QueryType = {
view: "traces",