Skip to content

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

fix(api): fix scores behaviour in metrics v2 (#10940)

Valery Meleshkinea6bfec9d773
diff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/async/metrics-v2-api.servertest.ts
index fabee39b44..4b90a4be2b 100644
--- a/web/src/__tests__/async/metrics-v2-api.servertest.ts
+++ b/web/src/__tests__/async/metrics-v2-api.servertest.ts
@@ -6,9 +6,9 @@ import {
import { GetMetricsV2Response } from "@/src/features/public-api/types/metrics";
import {
createEvent,
- createTrace,
- createTracesCh,
createEventsCh,
+ createScoresCh,
+ createTraceScore,
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
@@ -34,17 +34,6 @@ describe("/api/public/v2/metrics API Endpoint", () => {
traceId = randomUUID();
observationIds = [];
- // Create trace in ClickHouse
- const trace = createTrace({
- id: traceId,
- project_id: projectId,
- user_id: "test-user-v2",
- session_id: "test-session-v2",
- tags: ["v2-test", "events-table"],
- release: "v2.0.0",
- });
- await createTracesCh([trace]);
-
// Create observations in events table
const observations = [];
for (let i = 0; i < 5; i++) {
@@ -84,7 +73,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
await createEventsCh(observations);
// Wait a bit for ClickHouse to process
- await new Promise((resolve) => setTimeout(resolve, 500));
+ await new Promise((resolve) => setTimeout(resolve, 50));
});
it("should kill redis connection", () => {
@@ -551,16 +540,6 @@ describe("/api/public/v2/metrics API Endpoint", () => {
const taggedObsId = randomUUID();
const taggedTraceId = randomUUID();
- await createTracesCh([
- createTrace({
- id: taggedTraceId,
- name: "tagged-observation-trace",
- project_id: projectId,
- timestamp: Date.now(),
- tags: ["v2-filter-test", "array-test"],
- }),
- ]);
-
await createEventsCh([
createEvent({
id: taggedObsId,
@@ -611,7 +590,426 @@ describe("/api/public/v2/metrics API Endpoint", () => {
(row: any) => row.name === "tagged-observation",
);
expect(taggedObsResult).toBeDefined();
- expect(Number(taggedObsResult.count_count)).toBeGreaterThanOrEqual(1);
+ expect(Number(taggedObsResult?.count_count)).toBeGreaterThanOrEqual(1);
+ });
+ });
+
+ maybe("Scores Views - Denormalized Fields", () => {
+ const scoreTraceId = randomUUID();
+ const scoreIds: string[] = [];
+ const scoreObservationId = randomUUID();
+ const scoreSessionId = randomUUID();
+
+ beforeAll(async () => {
+ if (!hasEvents) return;
+
+ // Create observation in events table for scores to reference
+ await createEventsCh([
+ createEvent({
+ id: scoreObservationId,
+ span_id: scoreObservationId,
+ trace_id: scoreTraceId,
+ project_id: projectId,
+ name: "test-observation-for-scores",
+ start_time: Date.now() * 1000,
+ session_id: scoreSessionId,
+ }),
+ ]);
+
+ const scores = [];
+ for (let i = 0; i < 3; i++) {
+ const scoreId = randomUUID();
+ scoreIds.push(scoreId);
+
+ scores.push({
+ ...createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ trace_id: scoreTraceId,
+ observation_id: scoreObservationId,
+ name: `test-score-${i}`,
+ value: i * 10,
+ data_type: "NUMERIC",
+ timestamp: Date.now() + i * 1000,
+ }),
+ session_id: scoreSessionId,
+ });
+ }
+
+ await createScoresCh(scores);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+ it("should support sessionId dimension from scores table", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "sessionId" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ // Find our test session
+ const nonEmptyRows = response.body.data.filter(
+ (row: any) => row.sessionId && row.count_count > 0,
+ );
+ expect(nonEmptyRows.length).toBeGreaterThanOrEqual(1);
+ });
+
+ it("should support filtering by sessionId", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "sessionId",
+ operator: "=",
+ value: scoreSessionId,
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ expect(response.body.data.length).toBeGreaterThan(0);
+ });
+
+ it("should support value aggregations for numeric scores", async () => {
+ const query = {
+ view: "scores-numeric",
+ metrics: [
+ { measure: "value", aggregation: "avg" },
+ { measure: "value", aggregation: "max" },
+ { measure: "value", aggregation: "min" },
+ ],
+ filters: [
+ {
+ column: "sessionId",
+ operator: "=",
+ value: scoreSessionId,
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data.length).toBeGreaterThan(0);
+
+ const data = response.body.data[0];
+ expect(data.avg_value).toBeDefined();
+ expect(data.max_value).toBeDefined();
+ expect(data.min_value).toBeDefined();
+ });
+ });
+
+ maybe("Scores Views - Denormalized Trace Fields via Events", () => {
+ let eventsScoreTraceId: string;
+ let eventsObservationId: string;
+ const eventsScoreSessionId = "events-score-session";
+ const eventsScoreUserId = "events-score-user";
+ const eventsScoreTags = ["events-tag-1", "events-tag-2"];
+ const eventsScoreRelease = "events-v3.0.0";
+
+ beforeAll(async () => {
+ if (!hasEvents) return;
+
+ eventsScoreTraceId = randomUUID();
+ eventsObservationId = randomUUID();
+
+ // Create observation in events table (v2 source)
+ await createEventsCh([
+ createEvent({
+ id: eventsObservationId,
+ span_id: eventsObservationId,
+ trace_id: eventsScoreTraceId,
+ project_id: projectId,
+ name: "test-observation-for-score",
+ provided_model_name: "gpt-4-turbo",
+ start_time: Date.now() * 1000,
+ user_id: eventsScoreUserId,
+ session_id: eventsScoreSessionId,
+ tags: eventsScoreTags,
+ release: eventsScoreRelease,
+ }),
+ ]);
+
+ await createScoresCh([
+ createTraceScore({
+ id: randomUUID(),
+ project_id: projectId,
+ trace_id: eventsScoreTraceId,
+ observation_id: eventsObservationId,
+ session_id: eventsScoreSessionId,
+ name: "score-with-events",
+ value: 95,
+ data_type: "NUMERIC",
+ timestamp: Date.now(),
+ }),
+ ]);
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+ it("should support userId dimension via events JOIN", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "userId" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "score-with-events",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ const userData = response.body.data.find(
+ (row: any) => row.userId === eventsScoreUserId,
+ );
+ expect(userData).toBeDefined();
+ });
+
+ it("should support tags dimension via events JOIN", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "tags" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "score-with-events",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ expect(response.body.data.length).toBeGreaterThan(0);
+ });
+
+ it("should support release dimension via events JOIN", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "release" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "score-with-events",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ const releaseData = response.body.data.find(
+ (row: any) => row.release === eventsScoreRelease,
+ );
+ expect(releaseData).toBeDefined();
+ });
+ });
+
+ maybe("Scores Views - Validation (Reject traceName)", () => {
+ it("should reject traceName dimension in scores-numeric (not on events table)", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "traceName" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeAPICall(
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(400);
+ expect(response.body.message).toContain("Invalid request data");
+ });
+
+ it("should reject traceName in scores-categorical view", async () => {
+ const query = {
+ view: "scores-categorical",
+ dimensions: [{ field: "traceName" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeAPICall(
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(400);
+ expect(response.body.message).toContain("Invalid request data");
+ });
+ });
+
+ maybe("Scores Views - Observation Dimensions via Events", () => {
+ let obsEventsTraceId: string;
+ let obsEventsObservationId: string;
+
+ beforeAll(async () => {
+ if (!hasEvents) return;
+
+ obsEventsTraceId = randomUUID();
+ obsEventsObservationId = randomUUID();
+
+ await createEventsCh([
+ createEvent({
+ id: obsEventsObservationId,
+ span_id: obsEventsObservationId,
+ trace_id: obsEventsTraceId,
+ project_id: projectId,
+ name: "test-observation-for-score-v2",
+ provided_model_name: "gpt-4-turbo",
+ start_time: Date.now() * 1000,
+ }),
+ ]);
+
+ await createScoresCh([
+ createTraceScore({
+ id: randomUUID(),
+ project_id: projectId,
+ trace_id: obsEventsTraceId,
+ observation_id: obsEventsObservationId,
+ session_id: "obs-events-test-session",
+ name: "score-with-observation-v2",
+ value: 95,
+ data_type: "NUMERIC",
+ timestamp: Date.now(),
+ }),
+ ]);
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+ it("should support observationModelName dimension via events table JOIN", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "observationModelName" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "score-with-observation-v2",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ // Should be able to access observation fields via events table JOIN
+ const modelData = response.body.data.find(
+ (row: any) => row.observationModelName === "gpt-4-turbo",
+ );
+ expect(modelData).toBeDefined();
+ });
+
+ it("should support observationName dimension from events table", async () => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: "observationName" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "score-with-observation-v2",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ const obsNameData = response.body.data.find(
+ (row: any) => row.observationName === "test-observation-for-score-v2",
+ );
+ expect(obsNameData).toBeDefined();
});
});
});
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index ae3f6c500a..96301bea9d 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -471,236 +471,273 @@ const scoreBaseDimensions: DimensionsDeclarationType = {
},
};
-export const scoresNumericView: ViewDeclarationType = {
- name: "scores_numeric",
- description:
- "Scores are flexible objects that are used for evaluations. This view contains numeric and boolean scores.",
- dimensions: {
- ...scoreBaseDimensions,
- id: {
- sql: "scores_numeric.id",
- alias: "id",
- type: "string",
- description: "Unique identifier of the score entry.",
- },
- environment: {
- sql: "scores_numeric.environment",
- alias: "environment",
- type: "string",
- description: "Deployment environment (e.g., production, staging).",
- },
- name: {
- sql: "scores_numeric.name",
- alias: "name",
- type: "string",
- description: "Name of the score (e.g., accuracy, toxicity).",
- },
- source: {
- sql: "scores_numeric.source",
- alias: "source",
- type: "string",
- description: "Origin of the score. Can be API, ANNOTATION, or EVAL.",
- },
- dataType: {
- sql: "scores_numeric.data_type",
- alias: "dataType",
- type: "string",
- description:
- "Internal data type of the score (NUMERIC, BOOLEAN, CATEGORICAL).",
- },
- traceId: {
- sql: "scores_numeric.trace_id",
- alias: "traceId",
- type: "string",
- description: "Identifier of the parent trace.",
- },
- configId: {
- sql: "scores_numeric.config_id",
- alias: "configId",
- type: "string",
- description: "Identifier of the config associated with the score.",
- },
- timestampMonth: {
- sql: "formatDateTime(scores_numeric.timestamp, '%Y-%m')",
- alias: "timestampMonth",
- type: "string",
- description: "Month of the score timestamp in YYYY-MM format.",
- },
- timestampDay: {
- sql: "formatDateTime(scores_numeric.timestamp, '%Y-%m-%d')",
- alias: "timestampDay",
- type: "string",
- description: "Day of the score timestamp in YYYY-MM-DD format.",
- },
- observationId: {
- sql: "scores_numeric.observation_id",
- alias: "observationId",
- type: "string",
- description: "Identifier of the observation associated with the score.",
- },
- value: {
- sql: "scores_numeric.value",
- alias: "value",
- type: "number",
- description: "Value of the score.",
- },
+// v2 scores dimensions
+const scoresV2BaseDimensions: DimensionsDeclarationType = {
+ sessionId: {
+ sql: "scores.session_id",
+ alias: "sessionId",
+ type: "string",
+ description: "Identifier of the session.",
},
- measures: {
- count: {
- sql: "count(*)",
- alias: "count",
- type: "integer",
- description: "Total number of scores.",
- unit: "scores",
- },
- value: {
- sql: "any(value)",
- alias: "value",
- type: "number",
- description: "Value of the score.",
- },
+ // Trace metadata on events table (accessed via events JOIN)
+ userId: {
+ sql: "events.user_id",
+ alias: "userId",
+ type: "string",
+ relationTable: "events",
+ description: "Identifier of the user.",
},
- tableRelations: {
- traces: {
- name: "traces",
- joinConditionSql:
- "ON scores.trace_id = traces.id AND scores.project_id = traces.project_id",
- timeDimension: "timestamp",
- },
- observations: {
- name: "observations",
- joinConditionSql:
- "ON scores.observation_id = observations.id AND scores.project_id = observations.project_id",
- timeDimension: "start_time",
- },
+ tags: {
+ sql: "events.tags",
+ alias: "tags",
+ type: "string[]",
+ relationTable: "events",
+ description: "User-defined tags.",
+ },
+ release: {
+ sql: "events.release",
+ alias: "release",
+ type: "string",
+ relationTable: "events",
+ description: "Release version.",
+ },
+ // Observation fields from events table
+ observationName: {
+ sql: "events.name",
+ alias: "observationName",
+ type: "string",
+ relationTable: "events",
+ description: "Name of the observation associated with the score.",
+ },
+ observationModelName: {
+ sql: "events.provided_model_name",
+ alias: "observationModelName",
+ type: "string",
+ relationTable: "events",
+ description: "Name of the model used for the observation.",
+ },
+ observationPromptName: {
+ sql: "events.prompt_name",
+ alias: "observationPromptName",
+ type: "string",
+ relationTable: "events",
+ description: "Name of the prompt used for the observation.",
+ },
+ observationPromptVersion: {
+ sql: "events.prompt_version",
+ alias: "observationPromptVersion",
+ type: "string",
+ relationTable: "events",
+ description: "Version of the prompt used for the observation.",
},
- segments: [
- {
- column: "data_type",
- // We consider NUMERIC and BOOLEAN scores as numeric.
- operator: "does not contain",
- value: "CATEGORICAL",
- type: "string",
- },
- ],
- timeDimension: "timestamp",
- baseCte: `scores scores_numeric FINAL`,
};
-export const scoresCategoricalView: ViewDeclarationType = {
- name: "scores_categorical",
- description:
- "Scores are flexible objects that are used for evaluations. This view contains categorical scores.",
- dimensions: {
- ...scoreBaseDimensions,
- id: {
- sql: "scores_categorical.id",
- alias: "id",
- type: "string",
- description: "Unique identifier of the score entry.",
- },
- environment: {
- sql: "scores_categorical.environment",
- alias: "environment",
- type: "string",
- description: "Deployment environment (e.g., production, staging).",
- },
- name: {
- sql: "scores_categorical.name",
- alias: "name",
- type: "string",
- description: "Name of the score (e.g., accuracy, toxicity).",
- },
- source: {
- sql: "scores_categorical.source",
- alias: "source",
- type: "string",
- description: "Origin of the score. Can be API, ANNOTATION, or EVAL.",
- },
- dataType: {
- sql: "scores_categorical.data_type",
- alias: "dataType",
- type: "string",
- description:
- "Internal data type of the score (NUMERIC, BOOLEAN, CATEGORICAL).",
- },
- traceId: {
- sql: "scores_categorical.trace_id",
- alias: "traceId",
- type: "string",
- description: "Identifier of the parent trace.",
- },
- configId: {
- sql: "scores_categorical.config_id",
- alias: "configId",
- type: "string",
- description: "Identifier of the config associated with the score.",
- },
- timestampMonth: {
- sql: "formatDateTime(scores_categorical.timestamp, '%Y-%m')",
- alias: "timestampMonth",
- type: "string",
- description: "Month of the score timestamp in YYYY-MM format.",
- },
- timestampDay: {
- sql: "formatDateTime(scores_categorical.timestamp, '%Y-%m-%d')",
- alias: "timestampDay",
- type: "string",
- description: "Day of the score timestamp in YYYY-MM-DD format.",
- },
- observationId: {
- sql: "scores_categorical.observation_id",
- alias: "observationId",
- type: "string",
- description: "Identifier of the observation associated with the score.",
- },
- stringValue: {
- sql: "string_value",
- alias: "stringValue",
- type: "string",
- description: "Value of the score.",
- },
+// Factory for shared score-specific dimensions (both numeric and categorical)
+const createScoreSpecificDimensions = (
+ tableAlias: string,
+): DimensionsDeclarationType => ({
+ id: {
+ sql: `${tableAlias}.id`,
+ alias: "id",
+ type: "string",
+ description: "Unique identifier of the score entry.",
},
- measures: {
- count: {
- sql: "count(*)",
- alias: "count",
- type: "integer",
- description: "Total number of scores.",
- unit: "scores",
- },
+ environment: {
+ sql: `${tableAlias}.environment`,
+ alias: "environment",
+ type: "string",
+ description: "Deployment environment (e.g., production, staging).",
},
- tableRelations: {
- traces: {
- name: "traces",
- joinConditionSql:
- "ON scores.trace_id = traces.id AND scores.project_id = traces.project_id",
- timeDimension: "timestamp",
- },
- observations: {
- name: "observations",
- joinConditionSql:
- "ON scores.observation_id = observations.id AND scores.project_id = observations.project_id",
- timeDimension: "start_time",
- },
+ name: {
+ sql: `${tableAlias}.name`,
+ alias: "name",
+ type: "string",
+ description: "Name of the score (e.g., accuracy, toxicity).",
},
- segments: [
- {
- column: "data_type",
- operator: "=",
- value: "CATEGORICAL",
- type: "string",
- },
- ],
- timeDimension: "timestamp",
- baseCte: `scores scores_categorical FINAL`,
+ source: {
+ sql: `${tableAlias}.source`,
+ alias: "source",
+ type: "string",
+ description: "Origin of the score. Can be API, ANNOTATION, or EVAL.",
+ },
+ dataType: {
+ sql: `${tableAlias}.data_type`,
+ alias: "dataType",
+ type: "string",
+ description:
+ "Internal data type of the score (NUMERIC, BOOLEAN, CATEGORICAL).",
+ },
+ traceId: {
+ sql: `${tableAlias}.trace_id`,
+ alias: "traceId",
+ type: "string",
+ description: "Identifier of the parent trace.",
+ },
+ configId: {
+ sql: `${tableAlias}.config_id`,
+ alias: "configId",
+ type: "string",
+ description: "Identifier of the config associated with the score.",
+ },
+ timestampMonth: {
+ sql: `formatDateTime(${tableAlias}.timestamp, '%Y-%m')`,
+ alias: "timestampMonth",
+ type: "string",
+ description: "Month of the score timestamp in YYYY-MM format.",
+ },
+ timestampDay: {
+ sql: `formatDateTime(${tableAlias}.timestamp, '%Y-%m-%d')`,
+ alias: "timestampDay",
+ type: "string",
+ description: "Day of the score timestamp in YYYY-MM-DD format.",
+ },
+ observationId: {
+ sql: `${tableAlias}.observation_id`,
+ alias: "observationId",
+ type: "string",
+ description: "Identifier of the observation associated with the score.",
+ },
+});
+
+// Shared table relations factory
+const createScoreTableRelations = (
+ version: "v1" | "v2",
+): Record<
+ string,
+ { name: string; joinConditionSql: string; timeDimension: string }
+> => {
+ if (version === "v1") {
+ return {
+ traces: {
+ name: "traces",
+ joinConditionSql:
+ "ON scores.trace_id = traces.id AND scores.project_id = traces.project_id",
+ timeDimension: "timestamp",
+ },
+ observations: {
+ name: "observations",
+ joinConditionSql:
+ "ON scores.observation_id = observations.id AND scores.project_id = observations.project_id",
+ timeDimension: "start_time",
+ },
+ };
+ } else {
+ return {
+ events: {
+ name: "events",
+ joinConditionSql:
+ "ON scores.observation_id = events.span_id AND scores.project_id = events.project_id",
+ timeDimension: "start_time",
+ },
+ };
+ }
};
+function scoresNumericViewBase(version: "v1" | "v2"): ViewDeclarationType {
+ const baseDimensions =
+ version === "v1" ? scoreBaseDimensions : scoresV2BaseDimensions;
+ return {
+ name: "scores_numeric",
+ description:
+ "Scores are flexible objects that are used for evaluations. This view contains numeric and boolean scores.",
+ dimensions: {
+ ...baseDimensions, // v1 keeps trace-JOIN dimensions
+ ...createScoreSpecificDimensions("scores_numeric"),
+ value: {
+ sql: "scores_numeric.value",
+ alias: "value",
+ type: "number",
+ description: "Value of the score.",
+ },
+ },
+ measures: {
+ count: {
+ sql: "count(*)",
+ alias: "count",
+ type: "integer",
+ description: "Total number of scores.",
+ unit: "scores",
+ },
+ value: {
+ sql: "any(value)",
+ alias: "value",
+ type: "number",
+ description: "Value of the score.",
+ },
+ },
+ tableRelations: createScoreTableRelations(version),
+ segments: [
+ {
+ column: "data_type",
+ // We consider NUMERIC and BOOLEAN scores as numeric.
+ operator: "does not contain" as const,
+ value: "CATEGORICAL",
+ type: "string" as const,
+ },
+ ], // Numeric
+ timeDimension: "timestamp",
+ baseCte: `scores scores_numeric FINAL`,
+ };
+}
+
+function scoresCategoricalViewBase(version: "v1" | "v2"): ViewDeclarationType {
+ const baseDimensions =
+ version === "v1" ? scoreBaseDimensions : scoresV2BaseDimensions;
+ return {
+ name: "scores_categorical",
+ description:
+ "Scores are flexible objects that are used for evaluations. This view contains categorical scores.",
+ dimensions: {
+ ...baseDimensions,
+ ...createScoreSpecificDimensions("scores_categorical"),
+ stringValue: {
+ sql: "string_value",
+ alias: "stringValue",
+ type: "string",
+ description: "Value of the score.",
+ },
+ },
+ measures: {
+ count: {
+ sql: "count(*)",
+ alias: "count",
+ type: "integer",
+ description: "Total number of scores.",
+ unit: "scores",
+ },
+ },
+ tableRelations: createScoreTableRelations(version),
+ segments: [
+ {
+ column: "data_type",
+ operator: "=" as const,
+ value: "CATEGORICAL",
+ type: "string" as const,
+ },
+ ], // Categorical
+ timeDimension: "timestamp",
+ baseCte: `scores scores_categorical FINAL`,
+ };
+}
+
+export const scoresNumericView: ViewDeclarationType =
+ scoresNumericViewBase("v1");
+
+export const scoresCategoricalView: ViewDeclarationType =
+ scoresCategoricalViewBase("v1");
+
+// v2 Scores Views
+export const scoresNumericViewV2: ViewDeclarationType =
+ scoresNumericViewBase("v2");
+
+export const scoresCategoricalViewV2: ViewDeclarationType =
+ scoresCategoricalViewBase("v2");
+
// Events-Observations View - queries from events table instead of observations table
export const eventsObservationsView: ViewDeclarationType = {
name: "events_observations",
description:
- "Observations from the events table. Supports denormalized trace fields (userId, sessionId, tags, release) but not trace-JOIN dimensions (traceName, traceRelease, traceVersion).",
+ "Observations represent individual requests or operations within a trace. They are grouped into Spans, Generations, and Events.",
dimensions: {
id: {
sql: "events_observations.span_id",
@@ -757,28 +794,25 @@ export const eventsObservationsView: ViewDeclarationType = {
sql: "events_observations.user_id",
alias: "userId",
type: "string",
- description:
- "Identifier of the user triggering the observation (denormalized from trace).",
+ description: "Identifier of the user triggering the observation.",
},
sessionId: {
sql: "events_observations.session_id",
alias: "sessionId",
type: "string",
- description:
- "Identifier of the session triggering the observation (denormalized from trace).",
+ description: "Identifier of the session triggering the observation.",
},
tags: {
sql: "events_observations.tags",
alias: "tags",
type: "string[]",
- description:
- "User-defined tags associated with the trace (denormalized from trace).",
+ description: "User-defined tags associated with the trace.",
},
release: {
sql: "events_observations.release",
alias: "release",
type: "string",
- description: "Release version (denormalized from trace).",
+ description: "Release version.",
},
providedModelName: {
sql: "events_observations.provided_model_name",
@@ -919,9 +953,19 @@ export const eventsObservationsView: ViewDeclarationType = {
};
// Define versioned structure type
+// v1 has all views including traces (normalized model with traces table)
+// v2 omits traces (denormalized model with events table only)
type VersionedViewDeclarations = {
- readonly [version in ViewVersion]: {
- readonly [K in z.infer<typeof views>]: ViewDeclarationType;
+ readonly v1: {
+ readonly traces: ViewDeclarationType;
+ readonly observations: ViewDeclarationType;
+ readonly "scores-numeric": ViewDeclarationType;
+ readonly "scores-categorical": ViewDeclarationType;
+ };
+ readonly v2: {
+ readonly observations: ViewDeclarationType;
+ readonly "scores-numeric": ViewDeclarationType;
+ readonly "scores-categorical": ViewDeclarationType;
};
};
@@ -934,10 +978,10 @@ export const viewDeclarations: VersionedViewDeclarations = {
"scores-categorical": scoresCategoricalView,
},
v2: {
- traces: traceView,
- observations: eventsObservationsView, // New: events table
- "scores-numeric": scoresNumericView,
- "scores-categorical": scoresCategoricalView,
+ // No traces in v2 - trace metadata is denormalized in events table
+ observations: eventsObservationsView,
+ "scores-numeric": scoresNumericViewV2,
+ "scores-categorical": scoresCategoricalViewV2,
},
} as const;
@@ -946,11 +990,16 @@ export function getViewDeclaration(
viewName: z.infer<typeof views>,
version: ViewVersion = "v1",
): ViewDeclarationType {
- const viewDecl = viewDeclarations[version]?.[viewName];
- if (!viewDecl) {
+ const versionViews = viewDeclarations[version];
+
+ // TypeScript knows the exact shape of each version now
+ if (!(viewName in versionViews)) {
+ const supportedViews = Object.keys(versionViews).join(", ");
throw new InvalidRequestError(
- `Invalid view '${viewName}' for version '${version}'. Must be one of ${Object.keys(viewDeclarations[version])}`,
+ `View '${viewName}' is not supported in version '${version}'. ` +
+ `Supported views for ${version}: ${supportedViews}`,
);
}
- return viewDecl;
+
+ return versionViews[viewName as keyof typeof versionViews];
}