🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(metrics): expose semantic roots in v2 API (#15633)
Valery Meleshkin2cb776a61623
diff --git a/fern/apis/server/definition/metrics.yml b/fern/apis/server/definition/metrics.ymlindex bafa18f054..a11c9f4fa5 100644--- a/fern/apis/server/definition/metrics.yml+++ b/fern/apis/server/definition/metrics.yml@@ -13,6 +13,7 @@ service:## V2 Differences- Supports `observations`, `scores-numeric`, `scores-boolean`, and `scores-categorical` views only (traces view not supported)- Direct access to tags and release fields on observations+ - Semantic-root filtering and grouping through the v2-only `isRootObservation` dimension- Backwards-compatible: traceName, traceRelease, traceVersion dimensions are still available on observations view- High cardinality dimensions are not supported and will return a 400 error (see below)@@ -37,6 +38,7 @@ service:- `providedModelName` - Name of the model used- `promptName` - Name of the prompt used- `promptVersion` - Version of the prompt used+ - `isRootObservation` - Boolean semantic-root status. `true` includes physical roots and app roots whose SDK parent is external (so `parentObservationId` may be non-null).- `startTimeMonth` - Month of start_time in YYYY-MM format**Measures:**@@ -176,6 +178,17 @@ service:}}```++ For example, to count semantic roots (including app roots with a non-null external parent), use a boolean filter:+ ```json+ {+ "view": "observations",+ "metrics": [{"measure": "count", "aggregation": "count"}],+ "filters": [{"column": "isRootObservation", "operator": "=", "value": true, "type": "boolean"}],+ "fromTimestamp": "2025-01-01T00:00:00.000Z",+ "toTimestamp": "2025-02-01T00:00:00.000Z"+ }+ ```response: MetricsV2Responsetypes:MetricsV2Response:diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.tsindex cb7ac9aac6..0683c04d15 100644--- a/packages/shared/src/eventsTable.ts+++ b/packages/shared/src/eventsTable.ts@@ -1,8 +1,10 @@import { type ColumnDefinition } from "./tableDefinitions";export const eventsTableHasParentObservationSql = "e.parent_span_id != ''";+export const eventsTableIsRootObservationSqlForAlias = (alias: string) =>+ `(${alias}.parent_span_id = '' OR ${alias}.is_app_root = true)`;export const eventsTableIsRootObservationSql =- "(e.parent_span_id = '' OR e.is_app_root = true)";+ eventsTableIsRootObservationSqlForAlias("e");export const isRootObservation = ({parentObservationId,@@ -11,7 +13,6 @@ export const isRootObservation = ({parentObservationId: string | null | undefined;isAppRoot: boolean | null | undefined;}): boolean => !parentObservationId || isAppRoot === true;-// True when the observation carries input / output. NULL/'' both count as// absent (NULL != '' is NULL, i.e. not true), so only real payloads match.export const eventsTableHasInputSql = "e.input != ''";diff --git a/packages/shared/src/features/query/dataModel.ts b/packages/shared/src/features/query/dataModel.tsindex 90aa6a26bc..c63f625fa3 100644--- a/packages/shared/src/features/query/dataModel.ts+++ b/packages/shared/src/features/query/dataModel.ts@@ -6,6 +6,7 @@ import {type views,} from "./types";import { InvalidRequestError } from "../../errors";+import { eventsTableIsRootObservationSqlForAlias } from "../../eventsTable";// The data model defines all available dimensions, measures, and the timeDimension for a given view.// Make sure to update web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts if you make changes@@ -1098,6 +1099,14 @@ export const eventsObservationsView: ViewDeclarationType = {highCardinality: true,uiHidden: true,},+ isRootObservation: {+ sql: `toBool(${eventsTableIsRootObservationSqlForAlias("events_observations")})`,+ alias: "isRootObservation",+ type: "boolean",+ description:+ "Whether the observation is a semantic root, including app roots with an external parent.",+ uiHidden: true,+ },type: {sql: "events_observations.type",alias: "type",diff --git a/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.ts b/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.tsindex 15d71da95b..7888b2472f 100644--- a/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.ts+++ b/packages/shared/src/features/query/server/queryBuilder.filterValidation.test.ts@@ -168,4 +168,35 @@ describe("queryBuilder filter type validation", () => {expect(query).toContain("toBool(scores_boolean.value) = {booleanFilter");expect(query).toContain(": Boolean}");});++ it("lowers the semantic-root observation filter only in the v2 events view", async () => {+ const { query } = await buildQueryWithFilter(+ {+ column: "isRootObservation",+ operator: "=",+ value: true,+ type: "boolean",+ },+ undefined,+ "v2",+ );++ expect(query).toContain(+ "toBool((events_observations.parent_span_id = '' OR events_observations.is_app_root = true)) = {booleanFilter",+ );+ expect(query).toContain(": Boolean}");++ await expect(+ buildQueryWithFilter(+ {+ column: "isRootObservation",+ operator: "=",+ value: true,+ type: "boolean",+ },+ undefined,+ "v1",+ ),+ ).rejects.toThrow(/Invalid filter column isRootObservation/);+ });});diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex a0173eb6a0..50c874edca 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -2765,6 +2765,9 @@ paths:- Direct access to tags and release fields on observations+ - Semantic-root filtering and grouping through the v2-only+ `isRootObservation` dimension+- Backwards-compatible: traceName, traceRelease, traceVersion dimensionsare still available on observations view@@ -2814,6 +2817,10 @@ paths:- `promptVersion` - Version of the prompt used+ - `isRootObservation` - Boolean semantic-root status. `true` includes+ physical roots and app roots whose SDK parent is external (so+ `parentObservationId` may be non-null).+- `startTimeMonth` - Month of start_time in YYYY-MM format@@ -3031,6 +3038,22 @@ paths:}```+++ For example, to count semantic roots (including app roots with a+ non-null external parent), use a boolean filter:++ ```json++ {+ "view": "observations",+ "metrics": [{"measure": "count", "aggregation": "count"}],+ "filters": [{"column": "isRootObservation", "operator": "=", "value": true, "type": "boolean"}],+ "fromTimestamp": "2025-01-01T00:00:00.000Z",+ "toTimestamp": "2025-02-01T00:00:00.000Z"+ }++ ```required: trueschema:type: stringdiff --git a/web/src/__tests__/server/dashboard-widget-version.servertest.ts b/web/src/__tests__/server/dashboard-widget-version.servertest.tsindex 6f7f35c320..bdcf558179 100644--- a/web/src/__tests__/server/dashboard-widget-version.servertest.ts+++ b/web/src/__tests__/server/dashboard-widget-version.servertest.ts@@ -150,6 +150,13 @@ describe("dashboard widget minVersion", () => {[{ column: "experimentDatasetId" }],true,],+ [+ "observations",+ [],+ [{ measure: "count" }],+ [{ column: "isRootObservation" }],+ true,+ ],// v1-compatible fields["observations",@@ -680,6 +687,7 @@ describe("dashboard widget minVersion", () => {["id", true],["traceId", true],["parentObservationId", true],+ ["isRootObservation", true],["name", false],])("create with dimension '%s' on shape-required v2 observations → rejected=%s",@@ -734,5 +742,27 @@ describe("dashboard widget minVersion", () => {}),).rejects.toThrow(/not available for widgets/);});++ it.each([undefined, 1])(+ "rejects isRootObservation as a breakdown when minVersion is %s",+ async (minVersion) => {+ const caller = makeCaller();++ await expect(+ caller.dashboardWidgets.create({+ projectId,+ name: "semantic root breakdown",+ description: "root status is filter-only",+ view: "observations",+ dimensions: [{ field: "isRootObservation" }],+ metrics: [{ measure: "count", agg: "count" }],+ filters: [],+ chartType: "NUMBER",+ chartConfig: { type: "NUMBER" },+ ...(minVersion === undefined ? {} : { minVersion }),+ }),+ ).rejects.toThrow(/not available for widgets/);+ },+ );});});diff --git a/web/src/__tests__/server/metrics-v2-api.servertest.ts b/web/src/__tests__/server/metrics-v2-api.servertest.tsindex 4bfed6f19b..640dd83408 100644--- a/web/src/__tests__/server/metrics-v2-api.servertest.ts+++ b/web/src/__tests__/server/metrics-v2-api.servertest.ts@@ -13,8 +13,9 @@ import {} from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";import waitForExpect from "wait-for-expect";+import { isMetricsV2Available } from "@/src/pages/api/public/v2/metrics";-const hasV2Apis = env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";+const hasV2Apis = isMetricsV2Available();const maybe = hasV2Apis ? describe : describe.skip;describe("/api/public/v2/metrics API Endpoint", () => {@@ -27,6 +28,24 @@ describe("/api/public/v2/metrics API Endpoint", () => {const timeValue = timestamp.getTime() * 1000; // microseconds for events tableconst testMetadataValue = randomUUID();+ it("gates v2 metrics on a non-legacy write mode", () => {+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ const originalPreviewOptIn = env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN;++ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+ (env as any).LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";+ try {+ expect(isMetricsV2Available()).toBe(false);++ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ expect(isMetricsV2Available()).toBe(true);+ } finally {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ (env as any).LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN =+ originalPreviewOptIn;+ }+ });+beforeAll(async () => {if (!hasV2Apis) {// don't attempt data setup if events table is disabled@@ -216,6 +235,14 @@ describe("/api/public/v2/metrics API Endpoint", () => {const query = {view: "observations",metrics: [{ measure: "latency", aggregation: "avg" }],+ filters: [+ {+ column: "traceId",+ operator: "=",+ value: traceId,+ type: "string",+ },+ ],fromTimestamp: new Date(Date.now() - 86400000).toISOString(),toTimestamp: new Date().toISOString(),};@@ -357,6 +384,111 @@ describe("/api/public/v2/metrics API Endpoint", () => {});});+ maybe("Semantic root observation dimension", () => {+ it("groups and filters physical and app roots independently of parent span", async () => {+ const semanticRootTraceId = randomUUID();+ const timestamp = Date.now() * 1000;+ const observations = [+ ["physical-root", "", false],+ ["app-root-with-external-parent", "external-parent", true],+ ["ordinary-child", "physical-root", false],+ ] as const;++ await createEventsCh(+ observations.map(([name, parentSpanId, isAppRoot], index) =>+ createEvent({+ id: randomUUID(),+ span_id: `${semanticRootTraceId}-${index}`,+ trace_id: semanticRootTraceId,+ project_id: projectId,+ parent_span_id: parentSpanId,+ is_app_root: isAppRoot,+ type: "SPAN",+ name,+ start_time: timestamp + index,+ end_time: timestamp + index + 1,+ }),+ ),+ );++ await waitForExpect(+ async () => {+ const result = await queryClickhouse<{ count: string }>({+ query: `SELECT count() AS count FROM events_core WHERE project_id = {projectId: String} AND trace_id = {traceId: String}`,+ params: { projectId, traceId: semanticRootTraceId },+ });+ expect(Number(result[0]?.count)).toBe(3);+ },+ 5000,+ 10,+ );++ const baseQuery = {+ view: "observations",+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "traceId",+ operator: "=",+ value: semanticRootTraceId,+ type: "string",+ },+ ],+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ };++ const groupedResponse = await makeZodVerifiedAPICall(+ GetMetricsV1Response,+ "GET",+ `/api/public/v2/metrics?query=${encodeURIComponent(+ JSON.stringify({+ ...baseQuery,+ dimensions: [{ field: "isRootObservation" }],+ }),+ )}`,+ );++ expect(groupedResponse.status).toBe(200);+ const grouped = groupedResponse.body.data;+ expect(grouped).toHaveLength(2);+ expect(+ Number(+ grouped.find((row) => row.isRootObservation === true)?.count_count,+ ),+ ).toBe(2);+ expect(+ Number(+ grouped.find((row) => row.isRootObservation === false)?.count_count,+ ),+ ).toBe(1);++ const filteredResponse = await makeZodVerifiedAPICall(+ GetMetricsV1Response,+ "GET",+ `/api/public/v2/metrics?query=${encodeURIComponent(+ JSON.stringify({+ ...baseQuery,+ dimensions: [],+ filters: [+ ...baseQuery.filters,+ {+ column: "isRootObservation",+ operator: "=",+ value: true,+ type: "boolean",+ },+ ],+ }),+ )}`,+ );++ expect(filteredResponse.status).toBe(200);+ expect(filteredResponse.body.data).toHaveLength(1);+ expect(Number(filteredResponse.body.data[0]?.count_count)).toBe(2);+ });+ });+maybe("Denormalized Trace Fields", () => {it.each([["tags"], ["release"]])("Denormalized field: %s",diff --git a/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.ts b/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.tsindex 0c07662cb3..6a91a557aa 100644--- a/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.ts+++ b/web/src/__tests__/server/unit/dashboard-widget-min-version.servertest.ts@@ -48,6 +48,24 @@ describe("public dashboard widget version validation", () => {),).toThrow(/v2-only fields/i);});++ it("rejects a semantic-root filter instead of persisting a v1 widget", () => {+ expect(() =>+ validatePublicDashboardWidgetInput(+ normalizePublicDashboardWidgetInput({+ ...baseInput,+ filters: [+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: true,+ },+ ],+ }),+ ),+ ).toThrow(/v2-only fields/i);+ });});it("only suggests dimensions that widget validation accepts", () => {@@ -101,4 +119,22 @@ describe("public dashboard widget version validation", () => {),).not.toThrow();});++ it("promotes a semantic-root filter to v2 on a dual deployment", () => {+ setWriteMode("dual");++ const normalized = normalizePublicDashboardWidgetInput({+ ...baseInput,+ filters: [+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: true,+ },+ ],+ });++ expect(() => validatePublicDashboardWidgetInput(normalized)).not.toThrow();+ });});diff --git a/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts b/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.tsindex e2d1ff8561..f6420be0f3 100644--- a/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts+++ b/web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts@@ -162,6 +162,10 @@ const viewFilterDefinitions: Record<"experimentId",sourceSpec("Experiment ID", { uiTableId: "experimentId" }),),+ defineField(+ "isRootObservation",+ sourceSpec("Is Root Observation", { uiTableId: "isRootObservation" }),+ ),],"scores-numeric": [defineField("name", sourceSpec("Score Name", { uiTableId: "scoreName" })),diff --git a/web/src/pages/api/public/v2/metrics.ts b/web/src/pages/api/public/v2/metrics.tsindex b153c01478..17c654b25a 100644--- a/web/src/pages/api/public/v2/metrics.ts+++ b/web/src/pages/api/public/v2/metrics.ts@@ -11,6 +11,13 @@ import { executeQuery } from "@langfuse/shared/query/server";import { validateQuery } from "@langfuse/shared/query";const DEFAULT_ROW_LIMIT = 100;+export function isMetricsV2Available(): boolean {+ return (+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true" &&+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy"+ );+}+export default withMiddlewares({GET: createAuthedProjectAPIRoute({name: "Get Metrics V2",@@ -18,7 +25,7 @@ export default withMiddlewares({querySchema: GetMetricsV2Query,responseSchema: GetMetricsV2Response,fn: async ({ query, auth }) => {- if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") {+ if (!isMetricsV2Available()) {throw new LangfuseNotFoundError("The metrics v2 API is only available in a Langfuse v4 write mode. Learn more at: https://langfuse.com/docs/v4",);