Skip to content

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

fix(trace): show trace-level scores in the root span Scores tab (LFE-14850) (#15876)

Nikita Kabardin8598b826790a
diff --git a/packages/shared/src/server/tableMappings/mapScoresTable.ts b/packages/shared/src/server/tableMappings/mapScoresTable.ts
index 3e81f5f15c..804c4cc921 100644
--- a/packages/shared/src/server/tableMappings/mapScoresTable.ts
+++ b/packages/shared/src/server/tableMappings/mapScoresTable.ts
@@ -41,6 +41,9 @@ export const scoresTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "observation_id",
queryPrefix: "s",
+ // A score either has an observation id or it does not: the column is
+ // Nullable(String), so '' and NULL denote the same "trace-level" score.
+ emptyEqualsNull: true,
},
{
uiTableName: "Session ID",
diff --git a/web/src/__tests__/server/scores-trpc.servertest.ts b/web/src/__tests__/server/scores-trpc.servertest.ts
index 4e5ed3d99a..3d62cba367 100644
--- a/web/src/__tests__/server/scores-trpc.servertest.ts
+++ b/web/src/__tests__/server/scores-trpc.servertest.ts
@@ -52,6 +52,7 @@ import {
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
+import { observationScopeFilter } from "@/src/features/filters/config/scores-config";
import { randomUUID } from "crypto";
const maybeEvents =
@@ -186,6 +187,81 @@ describe("scores trpc", () => {
});
});
+ describe("observation scope filter", () => {
+ it("lists trace-level scores for a trace-level owner span and for no other span", async () => {
+ const traceId = randomUUID();
+ const rootObservationId = randomUUID();
+ const childObservationId = randomUUID();
+
+ const traceLevelScore = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ name: "trace-level-score",
+ });
+ const rootObservationScore = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: rootObservationId,
+ name: "root-observation-score",
+ });
+ const childObservationScore = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: childObservationId,
+ name: "child-observation-score",
+ });
+
+ await createScoresCh([
+ traceLevelScore,
+ rootObservationScore,
+ childObservationScore,
+ ]);
+
+ const scoreIdsFor = async (
+ observationId: string,
+ includeTraceLevelScores: boolean,
+ ) => {
+ const payload = {
+ projectId,
+ filter: [
+ {
+ column: "traceId",
+ type: "string" as const,
+ operator: "=" as const,
+ value: traceId,
+ },
+ ...observationScopeFilter(observationId, includeTraceLevelScores),
+ ],
+ orderBy: { column: "timestamp", order: "DESC" as const },
+ page: 0,
+ limit: 50,
+ };
+ const [v3, v4] = await Promise.all([
+ caller.scores.all(payload),
+ caller.scores.allFromEvents(payload),
+ ]);
+ return {
+ v3: v3.scores.map((score) => score.id).sort(),
+ v4: v4.scores.map((score) => score.id).sort(),
+ };
+ };
+
+ // Trace-level owner: its own score plus the trace-level one, each once.
+ const owner = await scoreIdsFor(rootObservationId, true);
+ const expectedOwnerScoreIds = [
+ traceLevelScore.id,
+ rootObservationScore.id,
+ ].sort();
+ expect(owner.v3).toEqual(expectedOwnerScoreIds);
+ expect(owner.v4).toEqual(expectedOwnerScoreIds);
+
+ // Any other span stays observation-scoped.
+ const child = await scoreIdsFor(childObservationId, false);
+ expect(child.v3).toEqual([childObservationScore.id]);
+ expect(child.v4).toEqual([childObservationScore.id]);
+ });
+ });
+
maybeEvents("scores.allFromEvents trace-name filters", () => {
it("keeps scores for semantic roots without a stored trace name", async () => {
const traceId = randomUUID();
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index bd9a815edf..9c57922495 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -22,6 +22,7 @@ import {
import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";
import {
getScoreFilterConfig,
+ observationScopeFilter,
SCORE_COLUMN_TO_BACKEND_KEY,
type ScoresTableHiddenColumn,
} from "@/src/features/filters/config/scores-config";
@@ -103,6 +104,12 @@ export type ScoresTableProps = {
userId?: string;
traceId?: string;
observationId?: string;
+ /**
+ * Widen the `observationId` scope to also list the trace's trace-level scores
+ * (no `observationId`). Set when the observation stands in for the trace — the
+ * top-level span of a v4 trace, which carries them on its badge too.
+ */
+ includeTraceLevelScores?: boolean;
hiddenColumns?: ScoresTableHiddenColumn[];
localStorageSuffix?: string;
disableUrlPersistence?: boolean;
@@ -136,6 +143,7 @@ export default function ScoresTable({
userId,
traceId,
observationId,
+ includeTraceLevelScores = false,
hiddenColumns = [],
localStorageSuffix = "",
disableUrlPersistence = false,
@@ -391,13 +399,13 @@ export default function ScoresTable({
);
const filterState = createFilterState(
- queryFilter.effectiveFilterState.concat(rowDateRangeFilter),
+ queryFilter.effectiveFilterState.concat(
+ rowDateRangeFilter,
+ observationScopeFilter(observationId, includeTraceLevelScores),
+ ),
[
...(userId ? [{ key: "User ID", value: userId }] : []),
...(traceId ? [{ key: "Trace ID", value: traceId }] : []),
- ...(observationId
- ? [{ key: "Observation ID", value: observationId }]
- : []),
],
);
diff --git a/web/src/features/filters/config/scores-config.clienttest.ts b/web/src/features/filters/config/scores-config.clienttest.ts
index 0240e768aa..8ac950d668 100644
--- a/web/src/features/filters/config/scores-config.clienttest.ts
+++ b/web/src/features/filters/config/scores-config.clienttest.ts
@@ -1,4 +1,4 @@
-import { getScoreFilterConfig } from "./scores-config";
+import { getScoreFilterConfig, observationScopeFilter } from "./scores-config";
describe("getScoreFilterConfig", () => {
it("omits sidebar facets for hidden score columns", () => {
@@ -20,3 +20,25 @@ describe("getScoreFilterConfig", () => {
expect(config.facets.map((facet) => facet.column)).toContain("userId");
});
});
+
+describe("observationScopeFilter", () => {
+ it("includes trace-level scores only for a trace-level owner", () => {
+ expect(observationScopeFilter("obs-1", true)).toEqual([
+ {
+ column: "observationId",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["", "obs-1"],
+ },
+ ]);
+ expect(observationScopeFilter("obs-1", false)).toEqual([
+ {
+ column: "observationId",
+ type: "string",
+ operator: "=",
+ value: "obs-1",
+ },
+ ]);
+ expect(observationScopeFilter(undefined, true)).toEqual([]);
+ });
+});
diff --git a/web/src/features/filters/config/scores-config.ts b/web/src/features/filters/config/scores-config.ts
index ee052668e9..c2cf316f00 100644
--- a/web/src/features/filters/config/scores-config.ts
+++ b/web/src/features/filters/config/scores-config.ts
@@ -1,6 +1,7 @@
import { scoresTableCols } from "@/src/server/api/definitions/scoresTable";
import type { FilterConfig } from "@/src/features/filters/lib/filter-config";
import type { ColumnToBackendKeyMap } from "@/src/features/filters/lib/filter-transform";
+import { type FilterState } from "@langfuse/shared";
// Maps frontend column IDs to backend-expected column IDs
// Frontend uses "tags" but backend CH mapping expects "trace_tags" for trace tags on scores table
@@ -109,6 +110,36 @@ export const scoreFilterConfig: FilterConfig = {
],
};
+/**
+ * Scopes the scores table to one observation. `includeTraceLevelScores` widens it
+ * to the trace's trace-level scores as well — `observation_id` is `''`-equals-NULL
+ * in the ClickHouse mapping, so "any of ['', id]" is the OR, matching each score
+ * row once (LFE-14405).
+ */
+export function observationScopeFilter(
+ observationId: string | undefined,
+ includeTraceLevelScores: boolean,
+): FilterState {
+ if (!observationId) return [];
+ return includeTraceLevelScores
+ ? [
+ {
+ column: "observationId",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["", observationId],
+ },
+ ]
+ : [
+ {
+ column: "observationId",
+ type: "string",
+ operator: "=",
+ value: observationId,
+ },
+ ];
+}
+
export function getScoreFilterConfig(
hiddenColumns: ScoresTableHiddenColumn[] = [],
): FilterConfig {
diff --git a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
index 1d81a0c7bb..7ffc5b5117 100644
--- a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
@@ -87,7 +87,8 @@ export function ObservationDetailView({
// V4 beta mode and observations for log tab
const { isBetaEnabled: isV4Enabled } = useV4Beta();
- const { observations, roots, nodeMap } = useTraceData();
+ const { observations, roots, nodeMap, traceLevelScoreOwnerIds } =
+ useTraceData();
const isLogViewVirtualized =
observations.length >= TRACE_VIEW_CONFIG.logView.virtualizationThreshold;
@@ -115,6 +116,10 @@ export function ObservationDetailView({
const treeNode = nodeMap.get(observation.id);
const isRoot = roots.some((root) => root.id === observation.id);
+ // Without a TRACE row (v4) this span stands in for the trace, so its badge and
+ // its Scores tab both cover the trace-level scores.
+ const ownsTraceLevelScores = traceLevelScoreOwnerIds.has(observation.id);
+
// For root observations, compute subtree metrics for badge tooltips.
// We compute this lazily here rather than in tree-building.ts because:
// - TreeNode.totalCost just has the aggregated cost, we use it
@@ -539,6 +544,7 @@ export function ObservationDetailView({
projectId={projectId}
traceId={traceId}
observationId={observation.id}
+ includeTraceLevelScores={ownsTraceLevelScores}
hiddenColumns={[
"traceId",
"observationId",
diff --git a/web/src/features/traces/components/SpanContent.tsx b/web/src/features/traces/components/SpanContent.tsx
index 796f66ce83..09b6135357 100644
--- a/web/src/features/traces/components/SpanContent.tsx
+++ b/web/src/features/traces/components/SpanContent.tsx
@@ -29,6 +29,7 @@ import { getSubtreeDurationOverflowMs } from "@/src/features/traces/fns/getSubtr
import { heatMapTextColor } from "@/src/features/traces/fns/heatMapTextColor";
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
+import { selectNodeScores } from "@/src/features/traces/fns/nodeScores";
import type Decimal from "decimal.js";
// How many distinct score groups to show inline on a tree/search row before
@@ -55,7 +56,7 @@ export function SpanContent({
onHover,
className,
}: SpanContentProps) {
- const { mergedScores, roots } = useTraceData();
+ const { mergedScores, traceLevelScoreOwnerIds } = useTraceData();
const {
showDuration,
showCostTokens,
@@ -97,21 +98,11 @@ export function SpanContent({
const shouldRenderAnyMetrics = shouldRenderDuration || shouldRenderCostTokens;
- const hasTraceNode = roots.some((r) => r.type === "TRACE");
-
- // Filter scores for this node
- // - TRACE nodes: show trace-level scores (observationId === null)
- // - Top-level observations in rendered v4 tree (no TRACE node): show trace-level + observation-level scores
- // - All other observations: show only observation-level scores
- const isTopLevelTreeNode = roots.some((root) => root.id === node.id);
- const nodeScores =
- node.type === "TRACE"
- ? mergedScores.filter((s) => s.observationId === null)
- : isTopLevelTreeNode && !hasTraceNode
- ? mergedScores.filter(
- (s) => s.observationId === node.id || s.observationId === null,
- )
- : mergedScores.filter((s) => s.observationId === node.id);
+ const nodeScores = selectNodeScores(
+ mergedScores,
+ node.id,
+ traceLevelScoreOwnerIds,
+ );
const nodeDisplayName = node.name || `Unnamed ${node.type.toLowerCase()}`;
diff --git a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx b/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx
index 0d53f5968f..ba7e0ad029 100644
--- a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx
+++ b/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx
@@ -230,6 +230,7 @@ export function TraceTimeline() {
const {
roots,
serverScores: scores,
+ traceLevelScoreOwnerIds,
comments,
traceStartTime,
traceDuration,
@@ -461,26 +462,28 @@ export function TraceTimeline() {
// duration label dark red.
const parentTotalDuration = traceDuration * 1000;
- // Score lookup: one pass over the scores instead of an O(scores) filter per
- // row per render. Two maps preserve the exact TRACE-vs-observation keying:
- // trace rows show every score of the trace, observation rows only their own.
- const { scoresByObservationId, scoresByTraceId } = useMemo(() => {
- const byObservation = new Map<string, typeof scores>();
- const byTrace = new Map<string, typeof scores>();
+ // Score lookup keyed by tree-node id: one pass over the scores instead of an
+ // O(scores) filter per row per render. Trace-level scores land on their owner
+ // node(s) — the TRACE row, or every top-level span when there is none — so the
+ // timeline badge matches the tree badge and the node's Scores tab.
+ const scoresByNodeId = useMemo(() => {
+ const byNode = new Map<string, typeof scores>();
+ const pushTo = (key: string, score: (typeof scores)[number]) => {
+ const arr = byNode.get(key);
+ if (arr) arr.push(score);
+ else byNode.set(key, [score]);
+ };
for (const score of scores) {
if (score.observationId) {
- const arr = byObservation.get(score.observationId);
- if (arr) arr.push(score);
- else byObservation.set(score.observationId, [score]);
- }
- if (score.traceId) {
- const arr = byTrace.get(score.traceId);
- if (arr) arr.push(score);
- else byTrace.set(score.traceId, [score]);
+ pushTo(score.observationId, score);
+ } else {
+ for (const ownerId of traceLevelScoreOwnerIds) {
+ pushTo(ownerId, score);
+ }
}
}
- return { scoresByObservationId: byObservation, scoresByTraceId: byTrace };
- }, [scores]);
+ return byNode;
+ }, [scores, traceLevelScoreOwnerIds]);
const totalSize = rowVirtualizer.getTotalSize();
const virtualItems = rowVirtualizer.getVirtualItems();
@@ -707,11 +710,7 @@ export function TraceTimeline() {
parentTotalCost={parentTotalCost}
parentTotalDuration={parentTotalDuration}
commentCount={comments.get(nodeId) ?? 0}
- nodeScores={
- (item.node.type === "TRACE"
- ? scoresByTraceId.get(nodeId)
- : scoresByObservationId.get(nodeId)) ?? EMPTY_SCORES
- }
+ nodeScores={scoresByNodeId.get(nodeId) ?? EMPTY_SCORES}
onSelect={handleSelectNode}
onHover={handleHoverNode}
/>
diff --git a/web/src/features/traces/contexts/TraceDataContext.tsx b/web/src/features/traces/contexts/TraceDataContext.tsx
index f5b43b2af2..56ffa6a4a4 100644
--- a/web/src/features/traces/contexts/TraceDataContext.tsx
+++ b/web/src/features/traces/contexts/TraceDataContext.tsx
@@ -33,6 +33,7 @@ import {
} from "@/src/features/traces/fns/timelineCalculations";
import { useViewPreferences } from "./ViewPreferencesContext";
import { useMergedScores } from "@/src/features/scores/lib/useMergedScores";
+import { traceLevelScoreOwnerIds } from "@/src/features/traces/fns/nodeScores";
type TraceType = Omit<
WithStringifiedMetadata<TraceDomain>,
@@ -49,6 +50,10 @@ interface TraceDataContextValue {
mergedScores: WithStringifiedMetadata<ScoreDomain>[];
corrections: ScoreDomain[];
roots: TreeNode[];
+ /** Node ids that own the trace's trace-level scores. Derived from the
+ * STRUCTURAL roots, never the level-filtered ones — hiding a root promotes its
+ * children into `roots`, and a promoted child is not a stand-in for the trace. */
+ traceLevelScoreOwnerIds: Set<string>;
nodeMap: Map<string, TreeNode>;
searchItems: TraceSearchListItem[];
hiddenObservationsCount: number;
@@ -150,6 +155,11 @@ export function TraceDataProvider({
[filteredRoots, traceStartTime],
);
+ const traceLevelScoreOwnerIdSet = useMemo(
+ () => traceLevelScoreOwnerIds(uiData.roots),
+ [uiData.roots],
+ );
+
// Merge scores with optimistic cache
const mergedScores = useMergedScores(
serverScores,
@@ -168,6 +178,7 @@ export function TraceDataProvider({
mergedScores,
corrections,
roots: filteredRoots,
+ traceLevelScoreOwnerIds: traceLevelScoreOwnerIdSet,
nodeMap: uiData.nodeMap,
searchItems: filteredSearchItems,
hiddenObservationsCount,
@@ -182,6 +193,7 @@ export function TraceDataProvider({
mergedScores,
corrections,
filteredRoots,
+ traceLevelScoreOwnerIdSet,
filteredSearchItems,
hiddenObservationsCount,
uiData.nodeMap,
diff --git a/web/src/features/traces/fns/nodeScores.clienttest.ts b/web/src/features/traces/fns/nodeScores.clienttest.ts
new file mode 100644
index 0000000000..0b37591de4
--- /dev/null
+++ b/web/src/features/traces/fns/nodeScores.clienttest.ts
@@ -0,0 +1,53 @@
+import { selectNodeScores, traceLevelScoreOwnerIds } from "./nodeScores";
+
+const roots = (
+ ...nodes: { id: string; type: "TRACE" | "SPAN" }[]
+): { id: string; type: "TRACE" | "SPAN" }[] => nodes;
+
+const scores = [
+ { id: "trace-level", observationId: null },
+ { id: "root-level", observationId: "root" },
+ { id: "child-level", observationId: "child" },
+];
+
+describe("traceLevelScoreOwnerIds", () => {
+ it("owns trace-level scores on the TRACE row, else on every top-level span", () => {
+ // v3: the TRACE wrapper owns them, its root observations do not.
+ expect([
+ ...traceLevelScoreOwnerIds(
+ roots({ id: "trace", type: "TRACE" }, { id: "root", type: "SPAN" }),
+ ),
+ ]).toEqual(["trace"]);
+
+ // v4: no TRACE row, so every top-level span stands in for the trace.
+ expect([
+ ...traceLevelScoreOwnerIds(
+ roots({ id: "root", type: "SPAN" }, { id: "orphan", type: "SPAN" }),
+ ),
+ ]).toEqual(["root", "orphan"]);
+ });
+
+ it("is input-sensitive: level-filtered roots would hand ownership to a promoted child", () => {
+ // A level filter that hides "root" promotes "child" to the top of the
+ // rendered tree. Ownership must come from the structural roots, or a
+ // non-root span starts claiming the trace's scores.
+ const structuralRoots = roots({ id: "root", type: "SPAN" });
+ const levelFilteredRoots = roots({ id: "child", type: "SPAN" });
+
+ expect(traceLevelScoreOwnerIds(structuralRoots).has("child")).toBe(false);
+ expect(traceLevelScoreOwnerIds(levelFilteredRoots).has("child")).toBe(true);
+ });
+});
+
+describe("selectNodeScores", () => {
+ const ownerIds = traceLevelScoreOwnerIds(roots({ id: "root", type: "SPAN" }));
+
+ it("adds trace-level scores to the owner once and leaves other nodes alone", () => {
+ expect(selectNodeScores(scores, "root", ownerIds).map((s) => s.id)).toEqual(
+ ["trace-level", "root-level"],
+ );
+ expect(
+ selectNodeScores(scores, "child", ownerIds).map((s) => s.id),
+ ).toEqual(["child-level"]);
+ });
+});
diff --git a/web/src/features/traces/fns/nodeScores.ts b/web/src/features/traces/fns/nodeScores.ts
new file mode 100644
index 0000000000..50d17b8a33
--- /dev/null
+++ b/web/src/features/traces/fns/nodeScores.ts
@@ -0,0 +1,42 @@
+/**
+ * Which tree node owns a trace's trace-level scores (`observationId === null`).
+ *
+ * v3 traces render a TRACE wrapper row that owns them. v4 events-based traces
+ * have no such row, so the top-level span(s) stand in for the trace and own
+ * them alongside their own observation-level scores.
+ *
+ * Single source of this rule: the tree badge, the timeline badge and the Scores
+ * tab all derive from it, so a node's badge count and its Scores tab agree
+ * (LFE-14405).
+ */
+
+import { type TreeNode } from "../types/treeNode";
+
+type LeveledScore = { observationId: string | null };
+
+/**
+ * Pass the STRUCTURAL roots, never the level-filtered ones: hiding a root
+ * promotes its children to the top of the rendered tree, and a promoted child is
+ * not a stand-in for the trace. TraceDataContext owns the one call site.
+ */
+export function traceLevelScoreOwnerIds(
+ roots: Pick<TreeNode, "id" | "type">[],
+): Set<string> {
+ const traceNodes = roots.filter((root) => root.type === "TRACE");
+ const owners = traceNodes.length > 0 ? traceNodes : roots;
+ return new Set(owners.map((owner) => owner.id));
+}
+
+/** Scores to show for one node, in the order they were given. */
+export function selectNodeScores<T extends LeveledScore>(
+ scores: T[],
+ nodeId: string,
+ traceLevelOwnerIds: Set<string>,
+): T[] {
+ return traceLevelOwnerIds.has(nodeId)
+ ? scores.filter(
+ (score) =>
+ score.observationId === nodeId || score.observationId === null,
+ )
+ : scores.filter((score) => score.observationId === nodeId);
+}