Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(dashboard): optimize v2 traces queries via observations view with root-event filter (#12166)

Valery Meleshkin7745b4db4f72
diff --git a/packages/shared/src/server/queries/clickhouse-sql/factory.ts b/packages/shared/src/server/queries/clickhouse-sql/factory.ts
index 0fa7cfd458..fcc919aa1e 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/factory.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/factory.ts
@@ -25,6 +25,9 @@ export class QueryBuilderError extends Error {
}
}
+// Matches nullIf(expr, '') wrappers used in dimension SQL for display purposes.
+const NULL_IF_EMPTY_RE = /^nullIf\((.+),\s*''\)$/;
+
// This function ensures that the user only selects valid columns from the clickhouse schema.
// The filter property in this column needs to be zod verified.
// User input for values (e.g. project_id = <value>) are sent to Clickhouse as parameters to prevent SQL injection
@@ -124,20 +127,23 @@ export const createFilterFromFilterState = (
column.clickhouseTableName.startsWith("events")
) {
const isNull = frontEndFilter.operator === "is null";
+ // When the dimension SQL wraps the column with nullIf(col, ''), the value
+ // is already NULL for empty strings β€” use a standard IS NULL / IS NOT NULL check.
+ // When there is no nullIf wrapper, the column stores '' directly β€” use = '' / != ''.
+ const hasNullIf = NULL_IF_EMPTY_RE.test(column.clickhouseSelect);
const fieldWithPrefix = column.queryPrefix
? `${column.queryPrefix}.${column.clickhouseSelect}`
: column.clickhouseSelect;
+ const query = hasNullIf
+ ? `${fieldWithPrefix} IS ${isNull ? "" : "NOT "}NULL`
+ : `${fieldWithPrefix} ${isNull ? "=" : "!="} ''`;
- // Create an inline filter for empty string comparison
return {
clickhouseTable: column.clickhouseTableName,
field: column.clickhouseSelect,
operator: isNull ? ("=" as const) : ("!=" as const),
tablePrefix: column.queryPrefix,
- apply: () => ({
- query: `${fieldWithPrefix} ${isNull ? "=" : "!="} ''`,
- params: {},
- }),
+ apply: () => ({ query, params: {} }),
};
}
diff --git a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts
index fff4332dd4..74b7ced0dc 100644
--- a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts
+++ b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts
@@ -1472,4 +1472,179 @@ describe("dashboard v1 vs v2 consistency", () => {
});
});
});
+
+ // ─── v2 traces optimization: observations-based queries ────────────────
+
+ maybe("v2 traces optimization: observations-based queries", () => {
+ const rootFilter = {
+ type: "null" as const,
+ column: "parentObservationId",
+ operator: "is null" as const,
+ value: "" as const,
+ };
+
+ it.each(["1d", "7d"] as const)(
+ "total count: observations with root filter matches traces for %s window",
+ async (window) => {
+ const tracesQuery: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: null,
+ filters: [],
+ orderBy: null,
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ };
+ const obsQuery: QueryType = {
+ view: "observations",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: null,
+ filters: [rootFilter],
+ orderBy: null,
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ };
+ const [tracesResult, obsResult] = await Promise.all([
+ executeQuery(projectId, tracesQuery, "v2", true),
+ executeQuery(projectId, obsQuery, "v2", true),
+ ]);
+ const sum = (rows: Array<Record<string, unknown>>) =>
+ rows.reduce((s, r) => s + Number(r.count_count), 0);
+ expect(sum(obsResult)).toBe(sum(tracesResult));
+ },
+ );
+
+ it.each(["1d", "7d"] as const)(
+ "grouped by trace name: observations traceName matches traces name for %s window",
+ async (window) => {
+ const tracesQuery: QueryType = {
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: null,
+ filters: [],
+ orderBy: [{ field: "count_count", direction: "desc" }],
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ chartConfig: { type: "table", row_limit: 20 },
+ };
+ const obsQuery: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "traceName" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: null,
+ filters: [rootFilter],
+ orderBy: [{ field: "count_count", direction: "desc" }],
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ chartConfig: { type: "table", row_limit: 20 },
+ };
+ const [tracesResult, obsResult] = await Promise.all([
+ executeQuery(projectId, tracesQuery, "v2", true),
+ executeQuery(projectId, obsQuery, "v2", true),
+ ]);
+ const tracesMap = toMap(tracesResult, "name");
+ const obsMap = toMap(obsResult, "traceName");
+
+ expect(obsMap.size).toBe(tracesMap.size);
+ for (const [name, tracesRow] of tracesMap) {
+ const obsRow = obsMap.get(name);
+ expect(obsRow).toBeDefined();
+ expect(Number(obsRow!.count_count)).toBe(
+ Number(tracesRow.count_count),
+ );
+ }
+ },
+ );
+
+ it.each(["1d", "7d"] as const)(
+ "time series: observations with root filter matches traces per-bucket for %s window",
+ async (window) => {
+ const tracesQuery: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: { granularity: "day" },
+ filters: [],
+ orderBy: null,
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ };
+ const obsQuery: QueryType = {
+ view: "observations",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: { granularity: "day" },
+ filters: [rootFilter],
+ orderBy: null,
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ };
+ const [tracesResult, obsResult] = await Promise.all([
+ executeQuery(projectId, tracesQuery, "v2", true),
+ executeQuery(projectId, obsQuery, "v2", true),
+ ]);
+ const tracesMap = toMap(
+ tracesResult.filter((r) => Number(r.count_count) > 0),
+ "time_dimension",
+ );
+ const obsMap = toMap(
+ obsResult.filter((r) => Number(r.count_count) > 0),
+ "time_dimension",
+ );
+
+ expect(obsMap.size).toBe(tracesMap.size);
+ for (const [ts, tracesRow] of tracesMap) {
+ const obsRow = obsMap.get(ts);
+ expect(obsRow).toBeDefined();
+ expect(Number(obsRow!.count_count)).toBe(
+ Number(tracesRow.count_count),
+ );
+ }
+ },
+ );
+
+ it.each(["1d", "7d"] as const)(
+ "grouped by userId: observations with root filter matches traces for %s window",
+ async (window) => {
+ const tracesQuery: QueryType = {
+ view: "traces",
+ dimensions: [{ field: "userId" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: null,
+ filters: [],
+ orderBy: null,
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ };
+ const obsQuery: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "userId" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: null,
+ filters: [rootFilter],
+ orderBy: null,
+ fromTimestamp: fromFor(window),
+ toTimestamp,
+ };
+ const [tracesResult, obsResult] = await Promise.all([
+ executeQuery(projectId, tracesQuery, "v2", true),
+ executeQuery(projectId, obsQuery, "v2", true),
+ ]);
+ const tracesMap = toMap(tracesResult, "userId");
+ const obsMap = toMap(obsResult, "userId");
+
+ expect(obsMap.size).toBe(tracesMap.size);
+ for (const [userId, tracesRow] of tracesMap) {
+ const obsRow = obsMap.get(userId);
+ expect(obsRow).toBeDefined();
+ expect(Number(obsRow!.count_count)).toBe(
+ Number(tracesRow.count_count),
+ );
+ }
+ },
+ );
+ });
});
diff --git a/web/src/__tests__/createFilterFromFilterState-nullIf.servertest.ts b/web/src/__tests__/createFilterFromFilterState-nullIf.servertest.ts
new file mode 100644
index 0000000000..1a6098ba2e
--- /dev/null
+++ b/web/src/__tests__/createFilterFromFilterState-nullIf.servertest.ts
@@ -0,0 +1,97 @@
+import { createFilterFromFilterState } from "@langfuse/shared/src/server";
+
+/**
+ * Unit tests for the parentObservationId null-filter special case in
+ * createFilterFromFilterState (factory.ts).
+ *
+ * events_core stores parent_span_id as a non-nullable String β€” root events
+ * have ''. The view layer may wrap this with nullIf(col, '') so the UI sees
+ * NULL instead. The factory must detect the wrapper and emit IS NULL / IS NOT
+ * NULL (not = '' / != '') when nullIf is present.
+ */
+describe("createFilterFromFilterState parentObservationId on events tables", () => {
+ const baseMapping = {
+ uiTableName: "parentObservationId",
+ uiTableId: "parentObservationId",
+ type: "string",
+ };
+
+ // Column mapping that mirrors eventsObservationsView (nullIf wrapper present)
+ const withNullIf = {
+ ...baseMapping,
+ clickhouseTableName: "events_core",
+ clickhouseSelect: "nullIf(events_observations.parent_span_id, '')",
+ queryPrefix: "",
+ };
+
+ // Column mapping without nullIf (raw column, e.g. eventsTracesView)
+ const withoutNullIf = {
+ ...baseMapping,
+ clickhouseTableName: "events_core",
+ clickhouseSelect: "events_traces.parent_span_id",
+ queryPrefix: "",
+ };
+
+ // Non-events table β€” should fall through to standard NullFilter
+ const nonEvents = {
+ ...baseMapping,
+ clickhouseTableName: "observations",
+ clickhouseSelect: "observations.parent_observation_id",
+ queryPrefix: "",
+ };
+
+ it.each<{
+ desc: string;
+ operator: "is null" | "is not null";
+ mapping: typeof withNullIf;
+ expected: string;
+ }>([
+ {
+ desc: "nullIf + is null β†’ IS NULL",
+ operator: "is null",
+ mapping: withNullIf,
+ expected: "nullIf(events_observations.parent_span_id, '') IS NULL",
+ },
+ {
+ desc: "nullIf + is not null β†’ IS NOT NULL",
+ operator: "is not null",
+ mapping: withNullIf,
+ expected: "nullIf(events_observations.parent_span_id, '') IS NOT NULL",
+ },
+ {
+ desc: "raw column + is null β†’ = ''",
+ operator: "is null",
+ mapping: withoutNullIf,
+ expected: "events_traces.parent_span_id = ''",
+ },
+ {
+ desc: "raw column + is not null β†’ != ''",
+ operator: "is not null",
+ mapping: withoutNullIf,
+ expected: "events_traces.parent_span_id != ''",
+ },
+ {
+ desc: "raw column + queryPrefix",
+ operator: "is null",
+ mapping: { ...withoutNullIf, queryPrefix: "eo" },
+ expected: "eo.events_traces.parent_span_id = ''",
+ },
+ {
+ desc: "non-events table falls through to standard NullFilter",
+ operator: "is null",
+ mapping: nonEvents,
+ expected: "observations.parent_observation_id is null",
+ },
+ ])("$desc", ({ operator, mapping, expected }) => {
+ const filter = {
+ type: "null" as const,
+ column: "parentObservationId",
+ operator,
+ value: "" as const,
+ };
+ const [result] = createFilterFromFilterState([filter], [mapping]);
+ const { query, params } = result.apply();
+ expect(query).toBe(expected);
+ expect(params).toEqual({});
+ });
+});
diff --git a/web/src/features/dashboard/components/TracesBarListChart.tsx b/web/src/features/dashboard/components/TracesBarListChart.tsx
index 1f2f31a758..27444b47a9 100644
--- a/web/src/features/dashboard/components/TracesBarListChart.tsx
+++ b/web/src/features/dashboard/components/TracesBarListChart.tsx
@@ -6,13 +6,10 @@ import { DashboardCard } from "@/src/features/dashboard/components/cards/Dashboa
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
import { compactNumberFormatter, numberFormatter } from "@/src/utils/numbers";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
-import {
- type QueryType,
- type ViewVersion,
- mapLegacyUiTableFilterToView,
-} from "@/src/features/query";
+import { type QueryType, type ViewVersion } from "@/src/features/query";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { barListToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";
+import { traceViewQuery } from "@/src/features/dashboard/lib/dashboard-utils";
export const TracesBarListChart = ({
className,
@@ -33,12 +30,15 @@ export const TracesBarListChart = ({
}) => {
const [isExpanded, setIsExpanded] = useState(false);
+ const isV2 = metricsVersion === "v2";
+ const traceBase = traceViewQuery(metricsVersion, globalFilterState);
+ const traceNameField = isV2 ? "traceName" : "name";
+
// Total traces query using executeQuery
const totalTracesQuery: QueryType = {
- view: "traces",
+ ...traceBase,
dimensions: [],
metrics: [{ measure: "count", aggregation: "count" }],
- filters: mapLegacyUiTableFilterToView("traces", globalFilterState),
timeDimension: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
@@ -63,10 +63,9 @@ export const TracesBarListChart = ({
// Traces grouped by name query using executeQuery
const tracesQuery: QueryType = {
- view: "traces",
- dimensions: [{ field: "name" }],
+ ...traceBase,
+ dimensions: [{ field: traceNameField }],
metrics: [{ measure: "count", aggregation: "count" }],
- filters: mapLegacyUiTableFilterToView("traces", globalFilterState),
timeDimension: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
@@ -94,7 +93,9 @@ export const TracesBarListChart = ({
const transformedTraces =
traces.data?.map((item: any) => {
return {
- name: item.name ? (item.name as string) : "Unknown",
+ name: item[traceNameField]
+ ? (item[traceNameField] as string)
+ : "Unknown",
value: Number(item.count_count),
};
}) ?? [];
diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index f1739495ab..d5c9600b97 100644
--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -17,6 +17,7 @@ import {
} from "@/src/features/query";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";
+import { traceViewQuery } from "@/src/features/dashboard/lib/dashboard-utils";
export const TracesAndObservationsTimeSeriesChart = ({
className,
@@ -38,10 +39,9 @@ export const TracesAndObservationsTimeSeriesChart = ({
metricsVersion?: ViewVersion;
}) => {
const tracesQuery: QueryType = {
- view: "traces",
+ ...traceViewQuery(metricsVersion, globalFilterState),
dimensions: [],
metrics: [{ measure: "count", aggregation: "count" }],
- filters: mapLegacyUiTableFilterToView("traces", globalFilterState),
timeDimension: {
granularity:
dashboardDateRangeAggregationSettings[agg].dateTrunc ?? "day",
diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsx
index fdba1dfc38..8fb15f6bbe 100644
--- a/web/src/features/dashboard/components/UserChart.tsx
+++ b/web/src/features/dashboard/components/UserChart.tsx
@@ -15,6 +15,7 @@ import {
} from "@/src/features/query";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { barListToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";
+import { traceViewQuery } from "@/src/features/dashboard/lib/dashboard-utils";
type BarChartDataPoint = {
name: string;
@@ -78,10 +79,9 @@ export const UserChart = ({
);
const traceCountQuery: QueryType = {
- view: "traces",
+ ...traceViewQuery(metricsVersion, globalFilterState),
dimensions: [{ field: "userId" }],
metrics: [{ measure: "count", aggregation: "count" }],
- filters: mapLegacyUiTableFilterToView("traces", globalFilterState),
timeDimension: null,
fromTimestamp: fromTimestamp.toISOString(),
toTimestamp: toTimestamp.toISOString(),
diff --git a/web/src/features/dashboard/lib/dashboard-utils.ts b/web/src/features/dashboard/lib/dashboard-utils.ts
index c2c7383c50..5d64f55eec 100644
--- a/web/src/features/dashboard/lib/dashboard-utils.ts
+++ b/web/src/features/dashboard/lib/dashboard-utils.ts
@@ -1,5 +1,11 @@
-import { type FilterState } from "@langfuse/shared";
+import { type z } from "zod/v4";
+import { type FilterState, type singleFilter } from "@langfuse/shared";
import { usdFormatter } from "@/src/utils/numbers";
+import {
+ type QueryType,
+ type ViewVersion,
+ mapLegacyUiTableFilterToView,
+} from "@/src/features/query";
// traces do not have a startTime or endTime column, so we need to map these to the timestamp column
export const createTracesTimeFilter = (
@@ -25,3 +31,34 @@ export const totalCostDashboardFormatted = (totalCost?: number) => {
: usdFormatter(totalCost, 2, 2)
: usdFormatter(0);
};
+
+export const ROOT_OBSERVATION_FILTER: z.infer<typeof singleFilter> = {
+ type: "null",
+ column: "parentObservationId",
+ operator: "is null",
+ value: "",
+};
+
+/**
+ * Returns the view name and filters for a "traces-like" query that works in
+ * both v1 (queries the traces table) and v2 (queries observations with a
+ * root-event filter so counting root observations equals counting traces).
+ */
+export function traceViewQuery(
+ metricsVersion: ViewVersion | undefined,
+ globalFilterState: FilterState,
+): Pick<QueryType, "view" | "filters"> {
+ if (metricsVersion === "v2") {
+ return {
+ view: "observations",
+ filters: [
+ ...mapLegacyUiTableFilterToView("observations", globalFilterState),
+ ROOT_OBSERVATION_FILTER,
+ ],
+ };
+ }
+ return {
+ view: "traces",
+ filters: mapLegacyUiTableFilterToView("traces", globalFilterState),
+ };
+}