Skip to content

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

fix(traces): include trace-scoped score columns (#12978)

Hassieb Pakzad863de18f6801
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 5711c50432..ed66083ee1 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -838,22 +838,20 @@ export const getScoresGroupedByNameSourceType = async ({
export const getNumericScoresGroupedByName = async (
projectId: string,
- timestampFilter?: FilterState,
+ filter?: FilterState,
) => {
- const chFilter = timestampFilter
- ? createFilterFromFilterState(timestampFilter, [
- {
- uiTableName: "Timestamp",
- uiTableId: "timestamp",
- clickhouseTableName: "scores",
- clickhouseSelect: "timestamp",
- },
- ])
+ // Despite the historical name of some callers, this accepts any score-table
+ // compatible filter. Trace tables use this to scope discovery to scores that
+ // roll up into trace aggregates, not just direct trace-level scores.
+ const chFilter = filter
+ ? createFilterFromFilterState(
+ filter,
+ scoresColumnsTableUiColumnDefinitions,
+ scoresTableCols,
+ )
: undefined;
- const timestampFilterRes = chFilter
- ? new FilterList(chFilter).apply()
- : undefined;
+ const filterRes = chFilter ? new FilterList(chFilter).apply() : undefined;
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
@@ -863,7 +861,7 @@ export const getNumericScoresGroupedByName = async (
from scores s
WHERE s.project_id = {projectId: String}
AND has(['NUMERIC', 'BOOLEAN'], s.data_type)
- ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
+ ${filterRes?.query ? `AND ${filterRes.query}` : ""}
GROUP BY name
ORDER BY count() desc
LIMIT 1000;
@@ -875,7 +873,7 @@ export const getNumericScoresGroupedByName = async (
query: query,
params: {
projectId: projectId,
- ...(timestampFilterRes ? timestampFilterRes.params : {}),
+ ...(filterRes ? filterRes.params : {}),
},
tags: {
feature: "tracing",
@@ -891,22 +889,19 @@ export const getNumericScoresGroupedByName = async (
export const getCategoricalScoresGroupedByName = async (
projectId: string,
- timestampFilter?: FilterState,
+ filter?: FilterState,
) => {
- const chFilter = timestampFilter
- ? createFilterFromFilterState(timestampFilter, [
- {
- uiTableName: "Timestamp",
- uiTableId: "timestamp",
- clickhouseTableName: "scores",
- clickhouseSelect: "timestamp",
- },
- ])
+ // Mirrors `getNumericScoresGroupedByName`: callers can provide any score
+ // scope filters, not just timestamp predicates.
+ const chFilter = filter
+ ? createFilterFromFilterState(
+ filter,
+ scoresColumnsTableUiColumnDefinitions,
+ scoresTableCols,
+ )
: undefined;
- const timestampFilterRes = chFilter
- ? new FilterList(chFilter).apply()
- : undefined;
+ const filterRes = chFilter ? new FilterList(chFilter).apply() : undefined;
const query = `
SELECT
@@ -915,7 +910,7 @@ export const getCategoricalScoresGroupedByName = async (
FROM scores s
WHERE s.project_id = {projectId: String}
AND s.data_type = 'CATEGORICAL'
- ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
+ ${filterRes?.query ? `AND ${filterRes.query}` : ""}
GROUP BY name
ORDER BY count() DESC
LIMIT 1000;
@@ -928,7 +923,7 @@ export const getCategoricalScoresGroupedByName = async (
query: query,
params: {
projectId: projectId,
- ...(timestampFilterRes ? timestampFilterRes.params : {}),
+ ...(filterRes ? filterRes.params : {}),
},
tags: {
feature: "tracing",
diff --git a/web/src/__tests__/server/scores-trpc.servertest.ts b/web/src/__tests__/server/scores-trpc.servertest.ts
index 1be381bd83..ec32d35ce4 100644
--- a/web/src/__tests__/server/scores-trpc.servertest.ts
+++ b/web/src/__tests__/server/scores-trpc.servertest.ts
@@ -25,7 +25,11 @@ import { prisma } from "@langfuse/shared/src/db";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import {
+ createObservation,
+ createObservationsCh,
+ createTrace,
createTraceScore,
+ createTracesCh,
createScoresCh,
ScoreDeleteQueue,
BatchActionQueue,
@@ -171,4 +175,88 @@ describe("scores trpc", () => {
});
});
});
+
+ describe("scores.getScoreColumns", () => {
+ it("should distinguish trace-level from trace-scoped score discovery", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ }),
+ ]);
+ await createObservationsCh([
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ }),
+ ]);
+
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: "trace_level_score",
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.9,
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ name: "observation_level_score",
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.7,
+ }),
+ ]);
+
+ const traceScopedColumns = await caller.scores.getScoreColumns({
+ projectId,
+ filter: [
+ {
+ column: "traceId",
+ operator: "is not null",
+ value: "",
+ type: "null",
+ },
+ ],
+ });
+
+ const traceLevelColumns = await caller.scores.getScoreColumns({
+ projectId,
+ filter: [
+ {
+ column: "traceId",
+ operator: "is not null",
+ value: "",
+ type: "null",
+ },
+ {
+ column: "observationId",
+ operator: "is null",
+ value: "",
+ type: "null",
+ },
+ ],
+ });
+
+ expect(
+ traceScopedColumns.scoreColumns.map((column) => column.name),
+ ).toEqual(
+ expect.arrayContaining([
+ "trace_level_score",
+ "observation_level_score",
+ ]),
+ );
+ expect(
+ traceLevelColumns.scoreColumns.map((column) => column.name),
+ ).toEqual(["trace_level_score"]);
+ });
+ });
});
diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.ts
index 902070e619..3f95b82a79 100644
--- a/web/src/__tests__/server/traces-trpc.servertest.ts
+++ b/web/src/__tests__/server/traces-trpc.servertest.ts
@@ -19,6 +19,7 @@ import {
import waitForExpect from "wait-for-expect";
import { randomUUID } from "crypto";
import { env } from "@/src/env.mjs";
+import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";
describe("traces trpc", () => {
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -455,6 +456,104 @@ describe("traces trpc", () => {
// Should include all possible values from config, not just the actual score value
expect(sentimentScore?.values).toHaveLength(4);
});
+
+ it("should include observation-only score names for trace-scoped aggregates", async () => {
+ const trace = createTrace({
+ project_id: projectId,
+ });
+ const observation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ });
+ await createTracesCh([trace]);
+ await createObservationsCh([observation]);
+
+ const observationScore = createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: "observation_only_quality",
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.7,
+ });
+ const sessionScore = createTraceScore({
+ project_id: projectId,
+ trace_id: null,
+ session_id: randomUUID(),
+ name: "session_only_quality",
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.5,
+ });
+ await createScoresCh([observationScore, sessionScore]);
+
+ const filterOptions = await caller.traces.filterOptions({
+ projectId,
+ });
+
+ expect(filterOptions.scores_avg).toEqual(
+ expect.arrayContaining(["observation_only_quality"]),
+ );
+ expect(filterOptions.scores_avg).not.toContain("session_only_quality");
+ });
+ });
+
+ describe("traces.metrics", () => {
+ it("should aggregate observation-only scores onto the trace row", async () => {
+ const trace = createTrace({
+ project_id: projectId,
+ });
+ const firstObservation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ });
+ const secondObservation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ });
+
+ await createTracesCh([trace]);
+ await createObservationsCh([firstObservation, secondObservation]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: firstObservation.id,
+ name: "quality",
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.4,
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: secondObservation.id,
+ name: "quality",
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.8,
+ }),
+ ]);
+
+ const metrics = await caller.traces.metrics({
+ projectId,
+ traceIds: [trace.id],
+ filter: [],
+ });
+
+ const aggregateKey = composeAggregateScoreKey({
+ name: "quality",
+ source: "API",
+ dataType: "NUMERIC",
+ });
+
+ expect(metrics).toHaveLength(1);
+ expect(metrics[0]?.scores[aggregateKey]?.average).toBeCloseTo(0.6, 5);
+ expect(metrics[0]?.scores[aggregateKey]?.values).toEqual(
+ expect.arrayContaining([0.4, 0.8]),
+ );
+ });
});
describe("traces.getAgentGraphData", () => {
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 659098861e..7cc4a46c6b 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -432,11 +432,13 @@ export default function TracesTable({
);
const rowHeight = hideControls ? "s" : storedRowHeight;
+ // Trace rows render trace-scoped aggregates: direct trace scores plus
+ // observation scores that belong to the same trace.
const { scoreColumns, isLoading: isColumnLoading } =
useScoreColumns<TracesTableRow>({
scoreColumnKey: "scores",
projectId,
- filter: scoreFilters.forTraces(),
+ filter: scoreFilters.forTraceScopedAggregates(),
fromTimestamp: dateRange?.from,
});
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 2ddb1bf4a0..5fc7422325 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -471,7 +471,7 @@ export default function ObservationsEventsTable({
useScoreColumns<EventsTableRow>({
scoreColumnKey: "traceScores",
projectId,
- filter: scoreFilters.forTraces(),
+ filter: scoreFilters.forTraceLevel(),
fromTimestamp: dateRange?.from,
prefix: "Trace",
});
diff --git a/web/src/features/scores/lib/scoreColumns.ts b/web/src/features/scores/lib/scoreColumns.ts
index f29dd656c6..2cad6bbd3c 100644
--- a/web/src/features/scores/lib/scoreColumns.ts
+++ b/web/src/features/scores/lib/scoreColumns.ts
@@ -5,21 +5,47 @@ import {
type ScoreSourceType,
} from "@langfuse/shared";
+const traceLevelScoreFilter = (): FilterCondition[] => [
+ {
+ type: "null",
+ column: "traceId",
+ operator: "is not null",
+ value: "",
+ },
+ {
+ type: "null",
+ column: "observationId",
+ operator: "is null",
+ value: "",
+ },
+];
+
+/**
+ * Scope helpers for score discovery.
+ *
+ * - Trace-level: scores written directly to the trace. These have a `traceId`
+ * and no `observationId`.
+ * - Trace-scoped: any score row attached to a trace. This includes trace-level
+ * scores plus observation-level scores whose observations belong to the
+ * trace.
+ * - Aggregate: the UI groups all score rows returned for a given scope by
+ * `name/source/dataType` and renders one aggregate column per group.
+ */
export const scoreFilters = {
- // Filter for trace level scores
- forTraces: (): FilterCondition[] => [
+ // Scores written directly to the trace itself.
+ forTraceLevel: traceLevelScoreFilter,
+
+ // Historical alias for trace-level semantics. Prefer `forTraceLevel`.
+ forTraces: traceLevelScoreFilter,
+
+ // Any score row that rolls up into a trace aggregate column.
+ forTraceScopedAggregates: (): FilterCondition[] => [
{
type: "null",
column: "traceId",
operator: "is not null",
value: "",
},
- {
- type: "null",
- column: "observationId",
- operator: "is null",
- value: "",
- },
],
// Filter for session level scores
diff --git a/web/src/pages/project/[projectId]/prompts/metrics.tsx b/web/src/pages/project/[projectId]/prompts/metrics.tsx
index 2da9451e25..5686e0f138 100644
--- a/web/src/pages/project/[projectId]/prompts/metrics.tsx
+++ b/web/src/pages/project/[projectId]/prompts/metrics.tsx
@@ -136,7 +136,7 @@ export default function PromptVersionTable({
useScoreColumns<PromptVersionTableRow>({
scoreColumnKey: "traceScores",
projectId: projectId,
- filter: scoreFilters.forTraces(),
+ filter: scoreFilters.forTraceLevel(),
prefix: "Trace",
});
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index cef6b5479d..67fb5e9b48 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -62,6 +62,7 @@ import {
toDomainWithStringifiedMetadata,
toDomainArrayWithStringifiedMetadata,
} from "@/src/utils/clientSideDomainTypes";
+import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
import partition from "lodash/partition";
const TraceFilterOptions = z.object({
@@ -264,6 +265,13 @@ export const traceRouter = createTRPCRouter({
)
.query(async ({ input }) => {
const { timestampFilter } = input;
+ // Trace table filters/columns operate on trace-scoped aggregates: any
+ // score row attached to the trace, whether it lives on the trace itself
+ // or on one of the trace's observations.
+ const traceScopedScoreFilters = [
+ ...(timestampFilter ?? []),
+ ...scoreFilters.forTraceScopedAggregates(),
+ ];
const [
numericScoreNames,
@@ -273,10 +281,10 @@ export const traceRouter = createTRPCRouter({
userIds,
sessionIds,
] = await Promise.all([
- getNumericScoresGroupedByName(input.projectId, timestampFilter ?? []),
+ getNumericScoresGroupedByName(input.projectId, traceScopedScoreFilters),
getCategoricalScoresGroupedByName(
input.projectId,
- timestampFilter ?? [],
+ traceScopedScoreFilters,
),
getTracesGroupedByName(
input.projectId,