🪢 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
fix: fix the behaviour of nulls and score joins on the metrics v2 path (#11148)
Valery Meleshkin04d812f0fdca
diff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/async/metrics-v2-api.servertest.tsindex 022b636a61..29316ac28f 100644--- a/web/src/__tests__/async/metrics-v2-api.servertest.ts+++ b/web/src/__tests__/async/metrics-v2-api.servertest.ts@@ -9,8 +9,10 @@ import {createEventsCh,createScoresCh,createTraceScore,+ queryClickhouse,} from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";+import waitForExpect from "wait-for-expect";const hasEvents = env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true";const maybe = hasEvents ? describe : describe.skip;@@ -72,8 +74,20 @@ describe("/api/public/v2/metrics API Endpoint", () => {await createEventsCh(observations);- // Wait a bit for ClickHouse to process- await new Promise((resolve) => setTimeout(resolve, 50));+ // Wait for ClickHouse to process+ await waitForExpect(+ async () => {+ const result = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,+ params: { projectId, ids: observationIds },+ });+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(+ observationIds.length,+ );+ },+ 5000,+ 10,+ );});it("should kill redis connection", () => {@@ -605,7 +619,21 @@ describe("/api/public/v2/metrics API Endpoint", () => {}await createScoresCh(scores);- await new Promise((resolve) => setTimeout(resolve, 50));++ // Wait for ClickHouse to process+ await waitForExpect(+ async () => {+ const result = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM scores WHERE project_id = {projectId: String} AND id IN ({ids: Array(String)})`,+ params: { projectId, ids: scoreIds },+ });+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(+ scoreIds.length,+ );+ },+ 5000,+ 10,+ );});it("should support sessionId dimension from scores table", async () => {@@ -700,6 +728,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {maybe("Scores Views - Denormalized Trace Fields via Events", () => {let eventsScoreTraceId: string;let eventsObservationId: string;+ let eventsScoreId: string;const eventsScoreSessionId = "events-score-session";const eventsScoreUserId = "events-score-user";const eventsScoreTags = ["events-tag-1", "events-tag-2"];@@ -712,6 +741,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {eventsScoreTraceId = randomUUID();eventsObservationId = randomUUID();+ eventsScoreId = randomUUID();// Create observation in events table (v2 source)await createEventsCh([@@ -734,7 +764,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {await createScoresCh([createTraceScore({- id: randomUUID(),+ id: eventsScoreId,project_id: projectId,trace_id: eventsScoreTraceId,observation_id: eventsObservationId,@@ -746,7 +776,18 @@ describe("/api/public/v2/metrics API Endpoint", () => {}),]);- await new Promise((resolve) => setTimeout(resolve, 50));+ // Wait for ClickHouse to process+ await waitForExpect(+ async () => {+ const result = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM scores WHERE project_id = {projectId: String} AND id IN ({ids: Array(String)})`,+ params: { projectId, ids: [eventsScoreId] },+ });+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);+ },+ 5000,+ 10,+ );});it.each([@@ -812,12 +853,14 @@ describe("/api/public/v2/metrics API Endpoint", () => {maybe("Scores Views - Observation Dimensions via Events", () => {let obsEventsTraceId: string;let obsEventsObservationId: string;+ let obsEventsScoreId: string;beforeAll(async () => {if (!hasEvents) return;obsEventsTraceId = randomUUID();obsEventsObservationId = randomUUID();+ obsEventsScoreId = randomUUID();await createEventsCh([createEvent({@@ -833,7 +876,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {await createScoresCh([createTraceScore({- id: randomUUID(),+ id: obsEventsScoreId,project_id: projectId,trace_id: obsEventsTraceId,observation_id: obsEventsObservationId,@@ -845,7 +888,18 @@ describe("/api/public/v2/metrics API Endpoint", () => {}),]);- await new Promise((resolve) => setTimeout(resolve, 50));+ // Wait for ClickHouse to process+ await waitForExpect(+ async () => {+ const result = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM scores WHERE project_id = {projectId: String} AND id IN ({ids: Array(String)})`,+ params: { projectId, ids: [obsEventsScoreId] },+ });+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);+ },+ 5000,+ 10,+ );});it.each([@@ -896,6 +950,8 @@ describe("/api/public/v2/metrics API Endpoint", () => {maybe("Traces View - V2 Events Table", () => {let testTraceId: string;+ let traceEventIds: string[];+ let traceScoreId: string;const nowMs = Date.now();const now = nowMs * 1000; // microseconds@@ -903,12 +959,14 @@ describe("/api/public/v2/metrics API Endpoint", () => {if (!hasEvents) return;testTraceId = randomUUID();+ traceEventIds = [randomUUID(), randomUUID()];+ traceScoreId = randomUUID();// Create multiple observations with different tags to test aggregationconst traceEvents = [createEvent({- id: randomUUID(),- span_id: randomUUID(),+ id: traceEventIds[0],+ span_id: traceEventIds[0],trace_id: testTraceId,project_id: projectId,trace_name: "test-trace-v2",@@ -926,8 +984,8 @@ describe("/api/public/v2/metrics API Endpoint", () => {total_cost: 0.01,}),createEvent({- id: randomUUID(),- span_id: randomUUID(),+ id: traceEventIds[1],+ span_id: traceEventIds[1],trace_id: testTraceId,project_id: projectId,trace_name: "test-trace-v2",@@ -949,7 +1007,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {// Create a trace-level scoreawait createScoresCh([{- id: randomUUID(),+ id: traceScoreId,trace_id: testTraceId,project_id: projectId,name: "trace-quality",@@ -966,7 +1024,31 @@ describe("/api/public/v2/metrics API Endpoint", () => {},]);- await new Promise((resolve) => setTimeout(resolve, 100));+ // Wait for ClickHouse to process events and scores+ await waitForExpect(+ async () => {+ const eventsResult = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,+ params: { projectId, ids: traceEventIds },+ });+ expect(Number(eventsResult[0]?.count)).toBeGreaterThanOrEqual(+ traceEventIds.length,+ );+ },+ 5000,+ 10,+ );+ await waitForExpect(+ async () => {+ const scoresResult = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM scores WHERE project_id = {projectId: String} AND id IN ({ids: Array(String)})`,+ params: { projectId, ids: [traceScoreId] },+ });+ expect(Number(scoresResult[0]?.count)).toBeGreaterThanOrEqual(1);+ },+ 5000,+ 10,+ );});it.each([diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.tsindex 0753428217..61c4aa47de 100644--- a/web/src/features/query/dataModel.ts+++ b/web/src/features/query/dataModel.ts@@ -167,7 +167,7 @@ export const eventsTracesView: ViewDeclarationType = {// This is the GROUP BY identity column},name: {- sql: "events_traces.trace_name",+ sql: "nullIf(events_traces.trace_name, '')",alias: "name",type: "string",description:@@ -184,7 +184,7 @@ export const eventsTracesView: ViewDeclarationType = {"arrayDistinct(flatten(groupArray(events_traces.tags)))",},userId: {- sql: "events_traces.user_id",+ sql: "nullIf(events_traces.user_id, '')",alias: "userId",type: "string",description: "Identifier of the user triggering the trace.",@@ -192,7 +192,7 @@ export const eventsTracesView: ViewDeclarationType = {"argMaxIf(events_traces.user_id, events_traces.event_ts, events_traces.user_id <> '')",},sessionId: {- sql: "events_traces.session_id",+ sql: "nullIf(events_traces.session_id, '')",alias: "sessionId",type: "string",description: "Identifier of the session triggering the trace.",@@ -200,7 +200,7 @@ export const eventsTracesView: ViewDeclarationType = {"argMaxIf(events_traces.session_id, events_traces.event_ts, events_traces.session_id <> '')",},release: {- sql: "events_traces.release",+ sql: "nullIf(events_traces.release, '')",alias: "release",type: "string",description: "Release version of the trace.",@@ -208,7 +208,7 @@ export const eventsTracesView: ViewDeclarationType = {"argMaxIf(events_traces.release, events_traces.event_ts, events_traces.release <> '')",},version: {- sql: "events_traces.version",+ sql: "nullIf(events_traces.version, '')",alias: "version",type: "string",description: "Version of the trace.",@@ -216,7 +216,7 @@ export const eventsTracesView: ViewDeclarationType = {"argMaxIf(events_traces.version, events_traces.event_ts, events_traces.version <> '')",},environment: {- sql: "events_traces.environment",+ sql: "nullIf(events_traces.environment, '')",alias: "environment",type: "string",description: "Deployment environment (e.g., production, staging).",@@ -492,7 +492,7 @@ export const observationsView: ViewDeclarationType = {unit: "tokens/s",},tokensPerSecond: {- sql: "@@AGG1@@(usage_details)['total'] / date_diff('second', @@AGG2@@(observations.start_time), @@AGG2@@(observations.end_time))",+ sql: "@@AGG1@@(usage_details)['total'] / nullIf(date_diff('second', @@AGG2@@(observations.start_time), @@AGG2@@(observations.end_time)), 0)",aggs: { agg1: "sumMap", agg2: "any" },alias: "tokensPerSecond",type: "decimal",@@ -642,69 +642,69 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {type: "string",description: "Identifier of the session.",},- // Trace metadata on events table (accessed via events JOIN)+ // Trace metadata on events table (accessed via events_traces JOIN)traceName: {- sql: "events.trace_name",+ sql: "nullIf(events_traces.trace_name, '')",alias: "traceName",type: "string",- relationTable: "events",+ relationTable: "events_traces",description: "Name of the parent trace.",},userId: {- sql: "events.user_id",+ sql: "nullIf(events_traces.user_id, '')",alias: "userId",type: "string",- relationTable: "events",+ relationTable: "events_traces",description: "Identifier of the user.",},tags: {- sql: "events.tags",+ sql: "events_traces.tags",alias: "tags",type: "string[]",- relationTable: "events",+ relationTable: "events_traces",description: "User-defined tags.",},traceRelease: {- sql: "events.release",+ sql: "nullIf(events_traces.release, '')",alias: "traceRelease",type: "string",- relationTable: "events",+ relationTable: "events_traces",description: "Release version.",},traceVersion: {- sql: "events.version",+ sql: "nullIf(events_traces.version, '')",alias: "traceVersion",type: "string",- relationTable: "events",+ relationTable: "events_traces",description: "Version of the parent trace.",},- // Observation fields from events table+ // Observation fields from events table (accessed via events_observations JOIN)observationName: {- sql: "events.name",+ sql: "events_observations.name",alias: "observationName",type: "string",- relationTable: "events",+ relationTable: "events_observations",description: "Name of the observation associated with the score.",},observationModelName: {- sql: "events.provided_model_name",+ sql: "nullIf(events_observations.provided_model_name, '')",alias: "observationModelName",type: "string",- relationTable: "events",+ relationTable: "events_observations",description: "Name of the model used for the observation.",},observationPromptName: {- sql: "events.prompt_name",+ sql: "nullIf(events_observations.prompt_name, '')",alias: "observationPromptName",type: "string",- relationTable: "events",+ relationTable: "events_observations",description: "Name of the prompt used for the observation.",},observationPromptVersion: {- sql: "events.prompt_version",+ sql: "events_observations.prompt_version",alias: "observationPromptVersion",type: "string",- relationTable: "events",+ relationTable: "events_observations",description: "Version of the prompt used for the observation.",},};@@ -800,10 +800,16 @@ const createScoreTableRelations = (};} else {return {- events: {+ events_traces: {name: "events",joinConditionSql:- "ON (scores.trace_id = events.span_id OR scores.observation_id = events.span_id) AND scores.project_id = events.project_id",+ "ON scores.trace_id = events_traces.trace_id AND scores.project_id = events_traces.project_id AND events_traces.parent_span_id = ''",+ timeDimension: "start_time",+ },+ events_observations: {+ name: "events",+ joinConditionSql:+ "ON scores.project_id = events_observations.project_id AND scores.trace_id = events_observations.trace_id AND scores.observation_id = events_observations.span_id",timeDimension: "start_time",},};@@ -929,13 +935,13 @@ export const eventsObservationsView: ViewDeclarationType = {description: "Identifier linking the observation to its parent trace.",},environment: {- sql: "events_observations.environment",+ sql: "nullIf(events_observations.environment, '')",alias: "environment",type: "string",description: "Deployment environment (e.g., production, staging).",},parentObservationId: {- sql: "events_observations.parent_span_id",+ sql: "nullIf(events_observations.parent_span_id, '')",alias: "parentObservationId",type: "string",description:@@ -961,20 +967,20 @@ export const eventsObservationsView: ViewDeclarationType = {description: "Logging level of the observation.",},version: {- sql: "events_observations.version",+ sql: "nullIf(events_observations.version, '')",alias: "version",type: "string",description: "Version of the observation.",},// Denormalized trace fields from events tableuserId: {- sql: "events_observations.user_id",+ sql: "nullIf(events_observations.user_id, '')",alias: "userId",type: "string",description: "Identifier of the user triggering the observation.",},sessionId: {- sql: "events_observations.session_id",+ sql: "nullIf(events_observations.session_id, '')",alias: "sessionId",type: "string",description: "Identifier of the session triggering the observation.",@@ -986,40 +992,40 @@ export const eventsObservationsView: ViewDeclarationType = {description: "User-defined tags associated with the trace.",},release: {- sql: "events_observations.release",+ sql: "nullIf(events_observations.release, '')",alias: "release",type: "string",description: "Release version.",},// Backwards-compatible field definitions (for API parity with v1)traceName: {- sql: "events_observations.trace_name",+ sql: "nullIf(events_observations.trace_name, '')",alias: "traceName",type: "string",description: "Name of the parent trace (backwards-compatible with v1).",},traceRelease: {- sql: "events_observations.release",+ sql: "nullIf(events_observations.release, '')",alias: "traceRelease",type: "string",description:"Release version of the parent trace (backwards-compatible with v1, maps to denormalized release field).",},traceVersion: {- sql: "events_observations.version",+ sql: "nullIf(events_observations.version, '')",alias: "traceVersion",type: "string",description:"Version of the parent trace (backwards-compatible with v1, maps to denormalized version field).",},providedModelName: {- sql: "events_observations.provided_model_name",+ sql: "nullIf(events_observations.provided_model_name, '')",alias: "providedModelName",type: "string",description: "Name of the model used for the observation.",},promptName: {- sql: "events_observations.prompt_name",+ sql: "nullIf(events_observations.prompt_name, '')",alias: "promptName",type: "string",description: "Name of the prompt used for the observation.",@@ -1098,7 +1104,7 @@ export const eventsObservationsView: ViewDeclarationType = {unit: "tokens/s",},tokensPerSecond: {- sql: "@@AGG1@@(usage_details)['total'] / date_diff('second', @@AGG2@@(events_observations.start_time), @@AGG2@@(events_observations.end_time))",+ sql: "@@AGG1@@(usage_details)['total'] / nullIf(date_diff('second', @@AGG2@@(events_observations.start_time), @@AGG2@@(events_observations.end_time)), 0)",aggs: { agg1: "sumMap", agg2: "any" },alias: "tokensPerSecond",type: "decimal",diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex d27bd7cfa1..0b03d47a80 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -429,7 +429,9 @@ export class QueryBuilder {const shouldUseFinal = !(relation.name === "observations" && skipObservationsFinal);- let joinStatement = `LEFT JOIN ${relation.name}${shouldUseFinal ? " FINAL" : ""} ${relation.joinConditionSql}`;+ const alias =+ relation.name !== relationTableName ? ` AS ${relationTableName}` : "";+ let joinStatement = `LEFT JOIN ${relation.name}${alias}${shouldUseFinal ? " FINAL" : ""} ${relation.joinConditionSql}`;// Create time dimension mapping for the relation tableconst relationTimeDimensionMapping = {