πͺ’ 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(scores): unite score filtering across levels + ScoreTag level coding (LFE-10596) (#14692)
Nikita Kabardin3738c8e81210
diff --git a/packages/shared/scripts/seeder/scenarios/scored-traces.ts b/packages/shared/scripts/seeder/scenarios/scored-traces.tsindex b2cf0260db..1937281a97 100644--- a/packages/shared/scripts/seeder/scenarios/scored-traces.ts+++ b/packages/shared/scripts/seeder/scenarios/scored-traces.ts@@ -43,6 +43,27 @@ const TRACE_NUMERIC_CONTROL_SCORE = "accuracy"; // no space β controlconst TRACE_CATEGORICAL_SCORE = "Hallucination Check";const TRACE_CATEGORIES = ["faithful", "hallucinated"] as const;+// Dual-level names: the SAME score name exists at BOTH observation and trace+// level on every trace (LFE-10596 edge case β one `scores.<name>` entry with+// both level tags; the level-agnostic filter matches either level). Values are+// split by level so a threshold demonstrates the union: observation-level+// `confidence` stays < 0.5 while trace-level is >= 0.5, so+// `scores.confidence:>0.5` matches ONLY via the trace side; likewise+// `scores.verdict:pass` exists only at trace level while "fail" is+// observation-only ("borderline" occurs at both).+const DUAL_NUMERIC_SCORE = "confidence";+const DUAL_CATEGORICAL_SCORE = "verdict";+const DUAL_OBSERVATION_CATEGORIES = ["fail", "borderline"] as const;+const DUAL_TRACE_CATEGORIES = ["pass", "borderline"] as const;++// Cross-TYPE name collision: the same name used for a NUMERIC score at+// observation level and an unrelated CATEGORICAL score at trace level. Level+// provenance is data-type-scoped (LFE-10596): the Numeric facet must tag+// "grade" Observation-only, the Categorical facet Trace-only, while the+// search bar's merged `scores.grade` suggestion shows both.+const CROSS_TYPE_SCORE = "grade";+const CROSS_TYPE_TRACE_CATEGORIES = ["A", "B", "C"] as const;+const TRACE_NAMES = ["qa-eval-run","summarize-doc",@@ -85,8 +106,11 @@ const run = async (counts: {traces: traceCount,observations: traceCount,- // 3 observation-level + 3 trace-level scores per trace- scores: traceCount * 6,+ // 6 observation-level + 6 trace-level scores per trace (incl. the+ // dual-level `confidence`/`verdict` pair present at both levels and+ // the cross-type `grade` collision), plus one obs-level score on the+ // v4 root span (mixed-level root)+ scores: traceCount * (withV4 ? 13 : 12),events: withV4 ? traceCount * 2 : 0,},verified: {},@@ -189,6 +213,72 @@ const run = async (}),);+ // Cross-type collision, observation side: NUMERIC "grade".+ scores.push(+ createTraceScore({+ id: `${obsId}-score-${CROSS_TYPE_SCORE}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ observation_id: obsId,+ environment: ctx.environment,+ name: CROSS_TYPE_SCORE,+ value: Math.round(rng.next() * 100) / 100,+ data_type: "NUMERIC",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp,+ }),+ // Cross-type collision, trace side: CATEGORICAL "grade".+ createTraceScore({+ id: `${traceId}-score-${CROSS_TYPE_SCORE}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ environment: ctx.environment,+ name: CROSS_TYPE_SCORE,+ value: 0,+ string_value: rng.pick(CROSS_TYPE_TRACE_CATEGORIES),+ data_type: "CATEGORICAL",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp,+ }),+ );++ // Dual-level pair, observation side: confidence < 0.5; verdict never "pass".+ scores.push(+ createTraceScore({+ id: `${obsId}-score-${DUAL_NUMERIC_SCORE}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ observation_id: obsId,+ environment: ctx.environment,+ name: DUAL_NUMERIC_SCORE,+ value: Math.round(rng.next() * 49) / 100,+ data_type: "NUMERIC",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp,+ }),+ createTraceScore({+ id: `${obsId}-score-${DUAL_CATEGORICAL_SCORE}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ observation_id: obsId,+ environment: ctx.environment,+ name: DUAL_CATEGORICAL_SCORE,+ value: 0,+ string_value: rng.pick(DUAL_OBSERVATION_CATEGORIES),+ data_type: "CATEGORICAL",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp,+ }),+ );+// Trace-level scores (-> `traceScores.<name>` in the grammar). These are the// eval-style scores attached to the whole trace (observation_id stays null).for (const name of [TRACE_NUMERIC_SCORE, TRACE_NUMERIC_CONTROL_SCORE]) {@@ -225,9 +315,63 @@ const run = async (}),);+ // Dual-level pair, trace side: confidence >= 0.5; verdict can be "pass".+ scores.push(+ createTraceScore({+ id: `${traceId}-score-${DUAL_NUMERIC_SCORE}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ environment: ctx.environment,+ name: DUAL_NUMERIC_SCORE,+ value: (50 + Math.round(rng.next() * 50)) / 100,+ data_type: "NUMERIC",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp,+ }),+ createTraceScore({+ id: `${traceId}-score-${DUAL_CATEGORICAL_SCORE}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ environment: ctx.environment,+ name: DUAL_CATEGORICAL_SCORE,+ value: 0,+ string_value: rng.pick(DUAL_TRACE_CATEGORIES),+ data_type: "CATEGORICAL",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp,+ }),+ );+if (withV4) {- events.push(traceToEvent(trace));+ const traceEvent = traceToEvent(trace);+ events.push(traceEvent);events.push(observationToEvent(observation, trace));++ // Observation-level score attached to the v4 ROOT span (`t-<traceId>`):+ // the root's inline chips then MIX trace-level and observation-level+ // scores β the shape where per-chip level tags must appear (a+ // single-level node shows none). v4-only: in the v3 rendering no+ // observation has this id, so the score would simply not display there.+ scores.push(+ createTraceScore({+ id: `${traceId}-root-score-${DUAL_NUMERIC_SCORE}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ observation_id: traceEvent.span_id,+ environment: ctx.environment,+ name: DUAL_NUMERIC_SCORE,+ value: Math.round(rng.next() * 49) / 100,+ data_type: "NUMERIC",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp,+ }),+ );}}@@ -318,7 +462,7 @@ const run = async (export const scoredTracesScenario: ScenarioDefinition = {name: "scored-traces",description:- 'Standalone traces each carrying numeric + categorical scores whose names contain SPACES (e.g. "Rouge Score", "Score With A Space") at both observation level (scores.) and trace level (traceScores.). For exercising the score filter sidebar and the grammar search bar with quoted score names.',+ 'Standalone traces each carrying numeric + categorical scores whose names contain SPACES (e.g. "Rouge Score") at observation and trace level, plus DUAL-LEVEL names ("confidence", "verdict") that exist at BOTH levels on the same trace β observation confidence < 0.5 <= trace confidence, verdict "pass" trace-only β for the level-agnostic scores filter + ScoreTag edge case (LFE-10596).',supportsV4: true,flags: [{diff --git a/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.ts b/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.tsindex c63ad6380d..1faf499e72 100644--- a/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.ts@@ -4,7 +4,14 @@ import type { TracingSearchType } from "../../../interfaces/search";import { findUiColumnMapping } from "../../../tableDefinitions";import type { FilterCondition } from "../../../types";import { eventsTableUiColumnDefinitions } from "../../tableMappings/mapEventsTable";-import { FilterList, filtersRequireEventsFull } from "./clickhouse-filter";+import {+ BooleanObjectFilter,+ CategoryOptionsFilter,+ type Filter,+ FilterList,+ filtersRequireEventsFull,+ NumberObjectFilter,+} from "./clickhouse-filter";import { EventsQueryBuilder } from "./event-query-builder";import {createFilterFromFilterState,@@ -61,6 +68,12 @@ type ObservationScoreDependency = {joinTable: string;joinCondition: string;selectExpressions?: string[];+ /**+ * Blob export: also join the trace-score CTE (with tuple encoding) so the+ * `ts.*` select expressions resolve and trace-level scores land in the+ * export like they do in the UI's unified Scores column (LFE-10596).+ */+ includeTraceScores?: boolean;};type ObservationScoreDependencyFactory = (input: {@@ -89,9 +102,106 @@ const buildBlobExportObservationScoreDependency: ObservationScoreDependencyFacto"s.scores_avg as scores_avg","s.score_categories as score_categories","s.score_categories_tuples as score_categories_tuples",+ "ts.scores_avg as trace_scores_avg",+ "ts.score_categories_tuples as trace_score_categories_tuples",],+ includeTraceScores: true,});+// LFE-10596: in v4 the events table splits scores into observation-scoped+// columns (`s.scores_avg` / `s.score_categories` / `s.score_booleans`, joined+// on span_id) and trace-scoped columns (`ts.*`, joined on trace_id). A+// trace-level score only ever lands in the trace column, so a filter on the+// observation-scoped columns (the customer's saved filter, the sidebar+// "Scores" facets, and the search bar's `scores.` namespace) never matched+// trace-level scores. These helpers make those columns LEVEL-AGNOSTIC: the+// predicate matches if the score is found at observation OR trace level,+// restoring v3 "has it anywhere" semantics. `trace_scores_avg` /+// `trace_score_categories` / `trace_score_booleans` (the search bar's+// `traceScores.`) stay trace-only.+const OBSERVATION_SCORE_FIELDS = {+ "s.scores_avg": "ts.scores_avg",+ "s.score_categories": "ts.score_categories",+ "s.score_booleans": "ts.score_booleans",+} as const;++/** A Filter whose predicate combines its children with a single junction. */+const unionFilter = (filters: Filter[], junction: "AND" | "OR"): Filter => ({+ clickhouseTable: filters[0].clickhouseTable,+ field: filters[0].field,+ operator: filters[0].operator,+ tablePrefix: filters[0].tablePrefix,+ apply() {+ const compiled = filters.map((f) => f.apply());+ return {+ query: `(${compiled.map((c) => `(${c.query})`).join(` ${junction} `)})`,+ params: Object.assign({}, ...compiled.map((c) => c.params)),+ };+ },+});++/**+ * Rewrites an observation-scoped score filter into a level-agnostic union+ * across the observation (`s.`) and trace (`ts.`) score columns. Filters on any+ * other column (including the trace-only `ts.*` columns) are returned as-is.+ *+ * Junction: numeric operators (`= > < >= <=`), categorical `any of`, and+ * boolean `=` are existence checks -> OR. Categorical `none of` and boolean+ * `<>` are exclusions, which over a union must be `NOT-obs AND NOT-trace`+ * (De Morgan), not `NOT(obs OR trace)`, so they use AND.+ */+export const toLevelAgnosticScoreFilter = (filter: Filter): Filter => {+ if (filter instanceof NumberObjectFilter && filter.field === "s.scores_avg") {+ const traceFilter = new NumberObjectFilter({+ clickhouseTable: filter.clickhouseTable,+ field: OBSERVATION_SCORE_FIELDS["s.scores_avg"],+ key: filter.key,+ operator: filter.operator,+ value: filter.value,+ tablePrefix: filter.tablePrefix,+ });+ return unionFilter([filter, traceFilter], "OR");+ }++ if (+ filter instanceof CategoryOptionsFilter &&+ filter.field === "s.score_categories"+ ) {+ const traceFilter = new CategoryOptionsFilter({+ clickhouseTable: filter.clickhouseTable,+ field: OBSERVATION_SCORE_FIELDS["s.score_categories"],+ key: filter.key,+ operator: filter.operator,+ values: filter.values,+ tablePrefix: filter.tablePrefix,+ });+ return unionFilter(+ [filter, traceFilter],+ filter.operator === "none of" ? "AND" : "OR",+ );+ }++ if (+ filter instanceof BooleanObjectFilter &&+ filter.field === "s.score_booleans"+ ) {+ const traceFilter = new BooleanObjectFilter({+ clickhouseTable: filter.clickhouseTable,+ field: OBSERVATION_SCORE_FIELDS["s.score_booleans"],+ key: filter.key,+ operator: filter.operator,+ value: filter.value,+ tablePrefix: filter.tablePrefix,+ });+ return unionFilter(+ [filter, traceFilter],+ filter.operator === "<>" ? "AND" : "OR",+ );+ }++ return filter;+};+const classifyFilter = (filter: FilterCondition): EventFilterGroup => {const filterColumn = resolveLegacyScoreFilterColumn(filter,@@ -156,22 +266,32 @@ const buildEventsObservationRowSelectionInternal = ();}+ // Observation-scoped score filters are rewritten into a level-agnostic+ // union across the obs (`s.`) and trace (`ts.`) score columns (LFE-10596),+ // for every caller of this planner (events list, blob export, stream).const eventsFilter = new FilterList(createFilterFromFilterState(filter ?? [],eventsTableUiColumnDefinitions,eventsTableCols,- ),+ ).map(toLevelAgnosticScoreFilter),);const startTimeFrom = extractTimeFilter(eventsFilter);const hasObservationScoreFilter = filterGroups.observationScores.length > 0;- const hasTraceScoreFilter = filterGroups.traceScores.length > 0;const queryBuilder = new EventsQueryBuilder({ projectId });const observationScoreDependency =observationScoreDependencyFactory?.({ projectId, startTimeFrom }) ??(hasObservationScoreFilter? buildObservationScoreFilterDependency({ projectId, startTimeFrom }): undefined);+ // The trace-score CTE is needed for explicit trace-only filters, for the+ // level-agnostic union (an observation-scoped filter now references `ts.*`+ // too), and whenever the score dependency selects `ts.*` so trace-level+ // scores land in exports like they do in the UI's unified Scores column.+ const hasTraceScoreFilter =+ filterGroups.traceScores.length > 0 ||+ hasObservationScoreFilter ||+ Boolean(observationScoreDependency?.includeTraceScores);const search = eventSearchCondition({ query: searchQuery, searchType });if (observationScoreDependency) {@@ -195,6 +315,9 @@ const buildEventsObservationRowSelectionInternal = (projectId,startTimeFrom,hasScoreAggregationFilters: true,+ includeTupleEncoding: Boolean(+ observationScoreDependency?.includeTraceScores,+ ),}),),)diff --git a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.tsindex 678730a217..b3b02c0403 100644--- a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts@@ -149,6 +149,27 @@ describe("buildEventsStreamQuery", () => {);});+ it("exports trace-level scores alongside observation-level ones (LFE-10596)", () => {+ // No score filter at all: the export must still join and select the+ // trace-score aggregate so trace-level scores land in the file exactly+ // like the UI's unified Scores column.+ const { queryBuilder } = buildEventsBlobExportStreamQuery({+ projectId,+ filter: [],+ rowLimit: 7,+ });+ const { query } = queryBuilder.buildWithParams();++ expect(query.match(/\btrace_scores_agg AS \(/g)).toHaveLength(1);+ expect(query).toContain("ts.scores_avg as trace_scores_avg");+ expect(query).toContain(+ "ts.score_categories_tuples as trace_score_categories_tuples",+ );+ expect(query).toContain(+ "ON ts.trace_id = e.trace_id AND ts.project_id = e.project_id",+ );+ });+it("applies score filters without exposing them as native event filters", () => {const { queryBuilder } = buildEventsStreamQuery({projectId,diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.tsindex 5846197fce..7098e33177 100644--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts@@ -264,10 +264,14 @@ interface EventsTracesScoresAggregationParams {projectId: string;startTimeFrom?: string | null;hasScoreAggregationFilters?: boolean;- // Note: includeTupleEncoding is intentionally omitted. This function is only used- // in UI table queries where score_categories are used for filtering, not programmatic- // parsing. If this is ever used in an export path, add includeTupleEncoding here and- // pass it through to buildScoresAggregationCTE (see EventsScoresAggregationParams).+ /**+ * Adds the `score_categories_tuples` column for programmatic parsing (see+ * BaseScoresAggregationParams). Only meaningful together with+ * `hasScoreAggregationFilters` (the flat branch returns score ids only);+ * used by the blob-export path so trace-level categorical scores export+ * safely even when names contain colons.+ */+ includeTupleEncoding?: boolean;}/**diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex 83348a0f2f..1852adc6e1 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -100,6 +100,7 @@ export {buildEventsObservationRowSelection,eventSearchCondition,groupEventsObservationFilters,+ toLevelAgnosticScoreFilter,type EventsObservationFilterGroups,type EventsObservationRowSelectionInput,} from "./clickhouse-sql/events-observation-row-selection";diff --git a/web/AGENTS.md b/web/AGENTS.mdindex 3ad7558b5a..0a5dea6345 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -100,6 +100,10 @@ action should emit an analytics event.- Entitlements guidance lives in `src/features/entitlements/README.md`.- Prefer Shadcn/ui primitives from `src/components/ui`; if a missing componentmust be installed, ask the user before doing so.+- When you surface a score in the UI, always show its level+ (trace/observation/session/experiment) with the `<ScoreTag>` component+ (`src/components/score-tag.tsx`) and its global color coding (see the+ ScoreTag Storybook story).- Tailwind is the default styling layer; use the shared palette and globals in`src/styles/globals.css`.- Do not add `useEffect` by default. Use it only when a component mustdiff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tsindex 576ba783b0..0a38b434e4 100644--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts@@ -3708,14 +3708,21 @@ describe("Clickhouse Events Repository Test", () => {});});- // LFE-10596: trace-level score filtering returned empty in v4. The events- // table splits scores into observation-scoped (`scores_avg`, joined on- // span_id) and trace-scoped (`trace_scores_avg`, joined on trace_id). A- // trace-level score (observation_id NULL) can only match the trace-scoped- // column, so its NAME must be offered under `trace_scores_avg` only β never- // under `scores_avg`, where a filter on it can never match.- maybe("LFE-10596 trace-level score filtering", () => {- it("trace-level score matches trace_scores_avg but not scores_avg", async () => {+ // LFE-10596: in v4 the traces/observations list is served from the events+ // table, which splits scores into an observation-scoped column (`scores_avg`+ // / `score_categories`, joined on span_id) and a trace-scoped column+ // (`trace_scores_avg` / `trace_score_categories`, joined on trace_id). A+ // trace-level score (observation_id NULL) only ever lands in the trace+ // column, so the customer's saved `scores_avg;CSAT=1` filter returned empty.+ //+ // The fix makes the `scores_avg` / `score_categories` columns LEVEL-AGNOSTIC:+ // they match if the score is found at observation OR trace level (a+ // server-side union), restoring v3 "has it anywhere" semantics.+ // `trace_scores_avg` / `trace_score_categories` stay an explicit trace-only+ // escape hatch, and both levels' names are offered under the single+ // `scores_avg` / `score_categories` groups.+ maybe("LFE-10596 level-agnostic score filtering", () => {+ it("scores_avg matches a trace-level score (union), and trace_scores_avg still does", async () => {const uniqueProjectId = randomUUID();const traceId = randomUUID();const spanId = randomUUID();@@ -3774,11 +3781,192 @@ describe("Clickhouse Events Repository Test", () => {]);expect(noFilterCount).toBe(1);+ // Level-agnostic union: a trace-level score now matches via scores_avg,+ // not only via trace_scores_avg. Before the fix scoresAvgCount was 0.+ expect(scoresAvgCount).toBe(1);expect(traceScoresAvgCount).toBe(1);- expect(scoresAvgCount).toBe(0);});- it("offers a trace-level numeric score under trace_scores_avg, not scores_avg", async () => {+ it("scores_avg still matches an observation-level score", async () => {+ const uniqueProjectId = randomUUID();+ const traceId = randomUUID();+ const spanId = randomUUID();++ await createEventsCh([+ createEvent({+ id: spanId,+ span_id: spanId,+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "SPAN",+ name: "Help Assistant",+ }),+ ]);++ await createScoresCh([+ // Observation-level score keyed to the span (scores_avg joins on span_id).+ createTraceScore({+ project_id: uniqueProjectId,+ trace_id: traceId,+ observation_id: spanId,+ name: "CSAT",+ value: 1,+ data_type: "NUMERIC",+ }),+ ]);++ const scoresAvgCount = await getObservationsCountFromEventsTable({+ projectId: uniqueProjectId,+ filter: [+ {+ type: "numberObject",+ column: "scores_avg",+ operator: "=",+ key: "CSAT",+ value: 1,+ },+ ],+ });++ expect(scoresAvgCount).toBe(1);+ });++ it("trace_scores_avg stays trace-only (does not match an observation-level score)", async () => {+ const uniqueProjectId = randomUUID();+ const traceId = randomUUID();+ const spanId = randomUUID();++ await createEventsCh([+ createEvent({+ id: spanId,+ span_id: spanId,+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "SPAN",+ name: "Help Assistant",+ }),+ ]);++ await createScoresCh([+ // Observation-level score keyed to the span.+ createTraceScore({+ project_id: uniqueProjectId,+ trace_id: traceId,+ observation_id: spanId,+ name: "CSAT",+ value: 1,+ data_type: "NUMERIC",+ }),+ ]);++ const [scoresAvgCount, traceScoresAvgCount] = await Promise.all([+ getObservationsCountFromEventsTable({+ projectId: uniqueProjectId,+ filter: [+ {+ type: "numberObject",+ column: "scores_avg",+ operator: "=",+ key: "CSAT",+ value: 1,+ },+ ],+ }),+ getObservationsCountFromEventsTable({+ projectId: uniqueProjectId,+ filter: [+ {+ type: "numberObject",+ column: "trace_scores_avg",+ operator: "=",+ key: "CSAT",+ value: 1,+ },+ ],+ }),+ ]);++ // scores_avg is level-agnostic (matches the obs score); trace_scores_avg+ // is the explicit trace-only escape hatch and must not match it.+ expect(scoresAvgCount).toBe(1);+ expect(traceScoresAvgCount).toBe(0);+ });++ it("categorical score_categories unions any-of and excludes none-of correctly (De Morgan)", async () => {+ const uniqueProjectId = randomUUID();+ const traceWithScore = randomUUID();+ const spanWithScore = randomUUID();+ const traceWithoutScore = randomUUID();+ const spanWithoutScore = randomUUID();+ const scoreName = `sentiment-${randomUUID()}`;++ await createEventsCh([+ createEvent({+ id: spanWithScore,+ span_id: spanWithScore,+ project_id: uniqueProjectId,+ trace_id: traceWithScore,+ type: "SPAN",+ name: "Help Assistant",+ }),+ createEvent({+ id: spanWithoutScore,+ span_id: spanWithoutScore,+ project_id: uniqueProjectId,+ trace_id: traceWithoutScore,+ type: "SPAN",+ name: "Help Assistant",+ }),+ ]);++ await createScoresCh([+ // Trace-level categorical (observation_id NULL) on the first trace only.+ createTraceScore({+ project_id: uniqueProjectId,+ trace_id: traceWithScore,+ observation_id: null,+ name: scoreName,+ value: 0,+ string_value: "positive",+ data_type: "CATEGORICAL",+ }),+ ]);++ const [anyOfCount, noneOfCount] = await Promise.all([+ getObservationsCountFromEventsTable({+ projectId: uniqueProjectId,+ filter: [+ {+ type: "categoryOptions",+ column: "score_categories",+ operator: "any of",+ key: scoreName,+ value: ["positive"],+ },+ ],+ }),+ getObservationsCountFromEventsTable({+ projectId: uniqueProjectId,+ filter: [+ {+ type: "categoryOptions",+ column: "score_categories",+ operator: "none of",+ key: scoreName,+ value: ["positive"],+ },+ ],+ }),+ ]);++ // any of: union OR -> only the trace that has the trace-level value.+ expect(anyOfCount).toBe(1);+ // none of: union AND (De Morgan) -> the trace WITH the value is excluded,+ // the trace without it is kept.+ expect(noneOfCount).toBe(1);+ });++ it("offers all numeric score names under scores_avg, trace-only names under trace_scores_avg", async () => {const uniqueProjectId = randomUUID();const traceId = randomUUID();const spanId = randomUUID();@@ -3798,7 +3986,7 @@ describe("Clickhouse Events Repository Test", () => {]);await createScoresCh([- // Trace-level score (observation_id NULL) -> trace_scores_avg only.+ // Trace-level score (observation_id NULL).createTraceScore({project_id: uniqueProjectId,trace_id: traceId,@@ -3807,7 +3995,7 @@ describe("Clickhouse Events Repository Test", () => {value: 1,data_type: "NUMERIC",}),- // Observation-level score -> scores_avg only.+ // Observation-level score.createTraceScore({project_id: uniqueProjectId,trace_id: traceId,@@ -3822,10 +4010,13 @@ describe("Clickhouse Events Repository Test", () => {projectId: uniqueProjectId,});- expect(options.trace_scores_avg).toContain(traceScoreName);- expect(options.scores_avg).not.toContain(traceScoreName);-+ // Single "Scores" group offers BOTH levels' names (level-agnostic union).expect(options.scores_avg).toContain(observationScoreName);+ expect(options.scores_avg).toContain(traceScoreName);++ // trace_scores_avg remains the trace-only escape hatch (search bar+ // traceScores.): trace-level names only.+ expect(options.trace_scores_avg).toContain(traceScoreName);expect(options.trace_scores_avg).not.toContain(observationScoreName);});@@ -3880,10 +4071,12 @@ describe("Clickhouse Events Repository Test", () => {(c) => c.label,);- expect(traceScoreCategoryLabels).toContain(traceCategoryName);- expect(scoreCategoryLabels).not.toContain(traceCategoryName);-+ // Single "Scores" group offers BOTH levels' categorical names.expect(scoreCategoryLabels).toContain(observationCategoryName);+ expect(scoreCategoryLabels).toContain(traceCategoryName);++ // trace_score_categories remains the trace-only escape hatch.+ expect(traceScoreCategoryLabels).toContain(traceCategoryName);expect(traceScoreCategoryLabels).not.toContain(observationCategoryName);});});diff --git a/web/src/components/ScoreLevels.mdx b/web/src/components/ScoreLevels.mdxnew file mode 100644index 0000000000..2916280b28--- /dev/null+++ b/web/src/components/ScoreLevels.mdx@@ -0,0 +1,46 @@+import { Meta, Canvas } from "@storybook/addon-docs/blocks";+import * as ScoreTagStories from "./score-tag.stories";++<Meta title="components/ScoreTag/Guidance" />++# Score levels & the `ScoreTag` color coding++A score's meaning depends on the **context it was created in** β its _level_.+Most users don't understand the distinction, so the platform surfaces it+everywhere a score appears: **if you show a score in the UI, tag its level+with `<ScoreTag>`.**++## The four levels++| Level | The evaluation context | Color | Status |+| --------------- | --------------------------- | ------ | ---------------------------------------------- |+| **Observation** | a single observation (span) | blue | live |+| **Trace** | the whole trace | violet | live β most scores today are trace-level |+| **Session** | a session of traces | teal | future β session ids not yet written on scores |+| **Experiment** | an experiment / dataset run | yellow | future β experiment ids not yet written |++The coding is **global**: one hue per level, identical on every surface+(filter bar, sidebar facets, trace Scores tab, tree/timeline, tables). The+hues are theme tokens in `globals.css` (light + dark) and live only in+`score-tag.tsx` β never restate them at a call site.++<Canvas of={ScoreTagStories.AllLevels} />++## Full vs compact++- **Full** (`<ScoreTag level="trace" />`) β colored pill with the level word.+ Use in lists, option rows, and tables where a word fits.+- **Compact** (`<ScoreTag level="trace" compact />`) β color dot with the+ level in a tooltip + `aria-label`. Use only in dense views (trace tree /+ timeline rows).++Never rely on color alone: the full variant carries the word, the compact+variant carries it via tooltip and `aria-label`.++<Canvas of={ScoreTagStories.InContext} />++## Deriving the level++Stored scores have no explicit level field. Use `scoreLevelFromScore(score)`+(exported next to `ScoreTag`): `observationId` set β observation, otherwise+trace. Extend it there when session/experiment ids land on scores.diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsxindex 6b23a47c33..53f69fb57e 100644--- a/web/src/components/grouped-score-badge.tsx+++ b/web/src/components/grouped-score-badge.tsx@@ -1,9 +1,11 @@-import { Badge } from "@/src/components/ui/badge";+import { useState } from "react";+import { Badge, badgeVariants } from "@/src/components/ui/badge";import {HoverCard,HoverCardContent,HoverCardTrigger,} from "@/src/components/ui/hover-card";+import { cn } from "@/src/utils/tailwind";import { type LastUserScore, type ScoreDomain } from "@langfuse/shared";import {BracesIcon,@@ -14,6 +16,7 @@ import { JSONView } from "@/src/components/ui/CodeJsonViewer";import Link from "next/link";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { ScoreTag, scoreLevelFromScore } from "@/src/components/score-tag";const partitionScores = <T extends WithStringifiedMetadata<ScoreDomain> | LastUserScore,@@ -53,20 +56,34 @@ const ScoreGroupBadge = <scores,compact,badgeClassName,+ showLevels,}: {name: string;scores: T[];compact?: boolean;badgeClassName?: string;+ /** Render this group's level tag(s). Set by GroupedScoreBadges only when+ * the whole selection mixes levels (LFE-10596). */+ showLevels?: boolean;}) => {const projectId = useProjectIdFromURL();+ // Score-level color coding (LFE-10596): one full tag per distinct level in+ // the group (a name can exist at both trace and observation level). Full+ // pill, not the compact dot β the level must be readable without hovering.+ const levels = showLevels+ ? Array.from(new Set(scores.map((score) => scoreLevelFromScore(score))))+ : [];+return (<Badgevariant="tertiary"key={name}className={`flex max-w-full min-w-0 items-center gap-1 ${compact ? "px-1.5 leading-tight" : "px-2.5"} text-xs font-normal${badgeClassName ? " " + badgeClassName : ""}`}>+ {levels.map((level) => (+ <ScoreTag key={level} level={level} />+ ))}<divclassName={`w-fit max-w-20 shrink-0 truncate ${compact ? "leading-tight" : ""}`}title={name}@@ -148,9 +165,31 @@ export const GroupedScoreBadges = <return acc;}, {});+ // Level tags only when this selection MIXES levels (LFE-10596): a row whose+ // scores all share one level (the common case β e.g. a span's own+ // observation-level scores) needs no per-chip disambiguation; a mixed row+ // (e.g. the root carrying trace-level and observation-level scores) tags+ // each group so the levels are tellable apart.+ const showLevels =+ new Set(scores.map((score) => scoreLevelFromScore(score))).size > 1;++ // "+N" expands IN PLACE on click (hover still previews the hidden chips);+ // the trailing "β" collapses back to the capped view.+ const [expanded, setExpanded] = useState(false);+ const overflows =+ maxVisible !== undefined && Object.keys(groupedScores).length > maxVisible;+const { visibleScores, hiddenScores } = partitionScores(groupedScores,- maxVisible,+ expanded ? undefined : maxVisible,+ );++ const overflowButtonClassName = cn(+ badgeVariants({ variant: "tertiary" }),+ "cursor-pointer",+ compact ? "px-0.5 py-0 leading-tight" : "px-1",+ "text-xs font-bold",+ badgeClassName,);return (@@ -162,19 +201,31 @@ export const GroupedScoreBadges = <scores={scores}compact={compact}badgeClassName={badgeClassName}+ showLevels={showLevels}/>))}{Boolean(hiddenScores.length) && (<HoverCard>- <HoverCardTrigger className="inline-block rounded-sm">- <Badge- className={`cursor-pointer ${compact ? "px-0.5 py-0 leading-tight" : "px-1"} text-xs font-bold${badgeClassName ? " " + badgeClassName : ""}`}- variant="tertiary"+ <HoverCardTrigger asChild>+ <button+ type="button"+ // aria-label, not title: a native tooltip would stack on top of+ // the hover-card preview.+ aria-label={`Show ${hiddenScores.length} more score${hiddenScores.length === 1 ? "" : "s"}`}+ // Chips render inside clickable rows (tree nodes, table rows) β+ // expanding must not also select/navigate the row.+ onClick={(event) => {+ event.stopPropagation();+ setExpanded(true);+ }}+ className={overflowButtonClassName}>+{hiddenScores.length}- </Badge>+ </button></HoverCardTrigger>- <HoverCardContent className="max-h-[300px] max-w-[200px] overflow-y-auto p-2">+ {/* w-max overrides the fixed w-64 base so the card adapts to its+ chips; the cap makes long selections wrap instead of clipping. */}+ <HoverCardContent className="max-h-[300px] w-max max-w-[min(420px,90vw)] overflow-y-auto p-2"><div className="flex flex-wrap gap-1">{hiddenScores.map(([name, scores]) => (<ScoreGroupBadge@@ -183,12 +234,27 @@ export const GroupedScoreBadges = <scores={scores}compact={compact}badgeClassName={badgeClassName}+ showLevels={showLevels}/>))}</div></HoverCardContent></HoverCard>)}+ {expanded && overflows && (+ <button+ type="button"+ title="Show fewer scores"+ aria-label="Show fewer scores"+ onClick={(event) => {+ event.stopPropagation();+ setExpanded(false);+ }}+ className={overflowButtonClassName}+ >+ β+ </button>+ )}</>);};diff --git a/web/src/components/score-tag.stories.tsx b/web/src/components/score-tag.stories.tsxnew file mode 100644index 0000000000..a239b7fd9d--- /dev/null+++ b/web/src/components/score-tag.stories.tsx@@ -0,0 +1,83 @@+import { Fragment } from "react";++import preview from "../../.storybook/preview";+import { ScoreTag, SCORE_LEVEL_LABELS, type ScoreLevel } from "./score-tag";++const meta = preview.meta({+ title: "components/ScoreTag",+ component: ScoreTag,+});++export const Default = meta.story({+ args: {+ level: "trace",+ },+});++export const Compact = meta.story({+ args: {+ level: "trace",+ compact: true,+ },+});++const ALL_LEVELS = Object.keys(SCORE_LEVEL_LABELS) as ScoreLevel[];++// The global score-level color coding at a glance: all four levels, full pill+// and compact dot. Flip the toolbar theme to check the dark-mode tokens.+export const AllLevels = meta.story({+ args: {+ level: "trace",+ },+ render: () => (+ <div className="grid w-fit grid-cols-[auto_auto_auto] items-center gap-x-6 gap-y-2 text-sm">+ <span className="text-muted-foreground text-xs">Level</span>+ <span className="text-muted-foreground text-xs">Full</span>+ <span className="text-muted-foreground text-xs">Compact</span>+ {ALL_LEVELS.map((level) => (+ <Fragment key={level}>+ <span>{SCORE_LEVEL_LABELS[level]}</span>+ <span>+ <ScoreTag level={level} />+ </span>+ <span className="inline-flex items-center">+ <ScoreTag level={level} compact />+ </span>+ </Fragment>+ ))}+ </div>+ ),+});++// The tag next to real score chips, at the density it ships in: full pill in+// list/option rows, compact dot in dense tree/timeline rows.+export const InContext = meta.story({+ args: {+ level: "trace",+ },+ render: () => (+ <div className="flex w-fit flex-col gap-3">+ <div className="flex items-center gap-2 rounded-md border px-2 py-1 text-sm">+ <span className="font-mono">scores.CSAT</span>+ <span className="text-muted-foreground text-xs">numeric score</span>+ <ScoreTag level="trace" />+ </div>+ <div className="flex items-center gap-2 rounded-md border px-2 py-1 text-sm">+ <span className="font-mono">scores.accuracy</span>+ <span className="text-muted-foreground text-xs">numeric score</span>+ <ScoreTag level="observation" />+ </div>+ <div className="flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs">+ <span>generate-answer</span>+ <span className="bg-tertiary text-tertiary-foreground inline-flex items-center gap-1 rounded-md px-1">+ accuracy: 0.92+ <ScoreTag level="observation" compact />+ </span>+ <span className="bg-tertiary text-tertiary-foreground inline-flex items-center gap-1 rounded-md px-1">+ CSAT: 1+ <ScoreTag level="trace" compact />+ </span>+ </div>+ </div>+ ),+});diff --git a/web/src/components/score-tag.tsx b/web/src/components/score-tag.tsxnew file mode 100644index 0000000000..b67a9a6fc5--- /dev/null+++ b/web/src/components/score-tag.tsx@@ -0,0 +1,137 @@+import { cva, type VariantProps } from "class-variance-authority";++import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { cn } from "@/src/utils/tailwind";++/**+ * The context a score was created in β its "level". A score's meaning depends+ * on this context, so every surface that shows a score must show its level+ * (LFE-10596; see the ScoreTag Storybook story for the full guidance).+ *+ * Only `trace` and `observation` are derivable from data today. `session` and+ * `experiment` are defined ahead of the backend writing session_id /+ * experiment_id onto scores, so the coding is stable when they arrive.+ */+export type ScoreLevel = "trace" | "observation" | "session" | "experiment";++export const SCORE_LEVEL_LABELS: Record<ScoreLevel, string> = {+ trace: "Trace",+ observation: "Observation",+ session: "Session",+ experiment: "Experiment",+};++const SCORE_LEVEL_DESCRIPTIONS: Record<ScoreLevel, string> = {+ trace: "Trace-level score: the whole trace was the evaluation context",+ observation:+ "Observation-level score: a single observation was the evaluation context",+ session: "Session-level score: a session was the evaluation context",+ experiment:+ "Experiment-level score: an experiment run was the evaluation context",+};++/**+ * Stored scores carry no explicit level field β level is derived from which+ * context id is set, narrowest first (an observation score also carries its+ * traceId). Callers with an implicit trace context (e.g. the trace detail+ * view) may pass just `observationId`; the fallback is trace.+ */+export const scoreLevelFromScore = (score: {+ observationId?: string | null;+ traceId?: string | null;+ sessionId?: string | null;+ datasetRunId?: string | null;+}): ScoreLevel =>+ score.observationId != null+ ? "observation"+ : score.traceId != null+ ? "trace"+ : score.sessionId != null+ ? "session"+ : score.datasetRunId != null+ ? "experiment"+ : "trace";++// The global score-level color coding: one hue per level, used identically on+// every surface (do not restate these colors at call sites). Hue pairs live in+// globals.css (light + dark themes): observation=blue, trace=violet,+// session=teal, experiment=yellow.+const scoreTagVariants = cva(+ "inline-flex shrink-0 items-center rounded-sm px-1 py-0 text-xs",+ {+ variants: {+ level: {+ observation: "bg-light-blue text-dark-blue",+ trace: "bg-light-violet text-dark-violet",+ session: "bg-light-teal text-dark-teal",+ experiment: "bg-light-yellow text-dark-yellow",+ },+ },+ },+);++const scoreDotVariants = cva("inline-block size-2 shrink-0 rounded-full", {+ variants: {+ level: {+ observation: "bg-dark-blue",+ trace: "bg-dark-violet",+ session: "bg-dark-teal",+ experiment: "bg-dark-yellow",+ },+ },+});++export interface ScoreTagProps extends VariantProps<typeof scoreTagVariants> {+ level: ScoreLevel;+ /**+ * Dense-view variant (trace tree / timeline rows): a color dot carrying the+ * level name via tooltip + aria-label instead of a visible word.+ */+ compact?: boolean;+ className?: string;+}++/**+ * Tags a score with the level it was created at, using the global score-level+ * color coding. Never color-alone: the full variant shows the level word, the+ * compact dot carries it via tooltip and aria-label.+ */+export const ScoreTag = ({+ level,+ compact = false,+ className,+}: ScoreTagProps) => {+ if (compact) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ role="img"+ aria-label={SCORE_LEVEL_DESCRIPTIONS[level]}+ className={cn(scoreDotVariants({ level }), className)}+ />+ </TooltipTrigger>+ <TooltipContent className="text-xs">+ {SCORE_LEVEL_DESCRIPTIONS[level]}+ </TooltipContent>+ </Tooltip>+ );+ }++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className={cn(scoreTagVariants({ level }), className)}>+ {SCORE_LEVEL_LABELS[level]}+ </span>+ </TooltipTrigger>+ <TooltipContent className="text-xs">+ {SCORE_LEVEL_DESCRIPTIONS[level]}+ </TooltipContent>+ </Tooltip>+ );+};diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex 8ba122874d..41ee2a50b5 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -63,6 +63,7 @@ import { X as IconX, Search, WandSparkles, InfoIcon } from "lucide-react";import DocPopup from "@/src/components/layouts/doc-popup";import type {UIFilter,+ KeyScoreLevels,KeyValueFilterEntry,NumericKeyValueFilterEntry,BooleanKeyValueFilterEntry,@@ -446,6 +447,7 @@ export function DataTableControls({expanded={filter.expanded}loading={filter.loading}keyOptions={filter.keyOptions}+ keyLevels={filter.keyLevels}availableValues={filter.availableValues}value={filter.value}onChange={filter.onChange}@@ -470,6 +472,7 @@ export function DataTableControls({expanded={filter.expanded}loading={filter.loading}keyOptions={filter.keyOptions}+ keyLevels={filter.keyLevels}value={filter.value}onChange={filter.onChange}isActive={filter.isActive}@@ -493,6 +496,7 @@ export function DataTableControls({expanded={filter.expanded}loading={filter.loading}keyOptions={filter.keyOptions}+ keyLevels={filter.keyLevels}value={filter.value}onChange={filter.onChange}isActive={filter.isActive}@@ -928,6 +932,7 @@ interface StringFacetProps extends BaseFacetProps {interface KeyValueFacetProps extends BaseFacetProps {keyOptions?: string[];+ keyLevels?: KeyScoreLevels;availableValues: Record<string, string[]>;value: KeyValueFilterEntry[];onChange: (filters: KeyValueFilterEntry[]) => void;@@ -936,6 +941,7 @@ interface KeyValueFacetProps extends BaseFacetProps {interface NumericKeyValueFacetProps extends BaseFacetProps {keyOptions?: string[];+ keyLevels?: KeyScoreLevels;value: NumericKeyValueFilterEntry[];onChange: (filters: NumericKeyValueFilterEntry[]) => void;keyPlaceholder?: string;@@ -943,6 +949,7 @@ interface NumericKeyValueFacetProps extends BaseFacetProps {interface BooleanKeyValueFacetProps extends BaseFacetProps {keyOptions?: string[];+ keyLevels?: KeyScoreLevels;value: BooleanKeyValueFilterEntry[];onChange: (filters: BooleanKeyValueFilterEntry[]) => void;keyPlaceholder?: string;@@ -1902,6 +1909,7 @@ export function KeyValueFacet({expanded: _expanded,loading,keyOptions,+ keyLevels,availableValues,value,onChange,@@ -1931,6 +1939,7 @@ export function KeyValueFacet({<KeyValueFilterBuildermode="categorical"keyOptions={keyOptions}+ keyLevels={keyLevels}availableValues={availableValues}activeFilters={value}onChange={onChange}@@ -1950,6 +1959,7 @@ export function NumericKeyValueFacet({expanded: _expanded,loading,keyOptions,+ keyLevels,value,onChange,isActive,@@ -1978,6 +1988,7 @@ export function NumericKeyValueFacet({<KeyValueFilterBuildermode="numeric"keyOptions={keyOptions}+ keyLevels={keyLevels}activeFilters={value}onChange={onChange}keyPlaceholder={keyPlaceholder}@@ -1996,6 +2007,7 @@ export function BooleanKeyValueFacet({expanded: _expanded,loading,keyOptions,+ keyLevels,value,onChange,isActive,@@ -2024,6 +2036,7 @@ export function BooleanKeyValueFacet({<KeyValueFilterBuildermode="boolean"keyOptions={keyOptions}+ keyLevels={keyLevels}activeFilters={value}onChange={onChange}keyPlaceholder={keyPlaceholder}diff --git a/web/src/components/table/key-value-filter-builder.tsx b/web/src/components/table/key-value-filter-builder.tsxindex 068f4cbeed..c039ec46c4 100644--- a/web/src/components/table/key-value-filter-builder.tsx+++ b/web/src/components/table/key-value-filter-builder.tsx@@ -24,7 +24,9 @@ import {import { MultiSelect } from "@/src/features/filters/components/multi-select";import { Plus, X, Check, ChevronDown } from "lucide-react";import { cn } from "@/src/utils/tailwind";+import { ScoreTag } from "@/src/components/score-tag";import type {+ KeyScoreLevels,KeyValueFilterEntry,NumericKeyValueFilterEntry,BooleanKeyValueFilterEntry,@@ -35,6 +37,7 @@ type KeyValueFilterBuilderProps =| {mode: "categorical";keyOptions?: string[];+ keyLevels?: KeyScoreLevels;availableValues: Record<string, string[]>;activeFilters: KeyValueFilterEntry[];onChange: (filters: KeyValueFilterEntry[]) => void;@@ -43,6 +46,7 @@ type KeyValueFilterBuilderProps =| {mode: "numeric";keyOptions?: string[];+ keyLevels?: KeyScoreLevels;activeFilters: NumericKeyValueFilterEntry[];onChange: (filters: NumericKeyValueFilterEntry[]) => void;keyPlaceholder?: string;@@ -50,6 +54,7 @@ type KeyValueFilterBuilderProps =| {mode: "boolean";keyOptions?: string[];+ keyLevels?: KeyScoreLevels;activeFilters: BooleanKeyValueFilterEntry[];onChange: (filters: BooleanKeyValueFilterEntry[]) => void;keyPlaceholder?: string;@@ -57,6 +62,7 @@ type KeyValueFilterBuilderProps =| {mode: "string";keyOptions?: string[];+ keyLevels?: KeyScoreLevels;activeFilters: StringKeyValueFilterEntry[];onChange: (filters: StringKeyValueFilterEntry[]) => void;keyPlaceholder?: string;@@ -86,6 +92,7 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {const {mode,keyOptions,+ keyLevels,activeFilters,onChange,keyPlaceholder = "Key",@@ -253,10 +260,17 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {<Buttonvariant="outline"role="combobox"- className="flex-1 justify-between text-left font-normal"+ className="min-w-0 flex-1 justify-between overflow-hidden text-left font-normal">+ {/* Selected name renders plain β level tags show only in+ the option rows below (design call: a selected filter+ needs no level tag, and long names must truncate). */}<span- className={cn(!filter.key && "text-muted-foreground")}+ className={cn(+ "min-w-0 truncate",+ !filter.key && "text-muted-foreground",+ )}+ title={filter.key || keyPlaceholder}>{filter.key || keyPlaceholder}</span>@@ -292,7 +306,19 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {: "invisible",)}/>- {option}+ <span+ className="min-w-0 flex-1 truncate"+ title={option}+ >+ {option}+ </span>+ {keyLevels?.[option]?.map((level) => (+ <ScoreTag+ key={level}+ level={level}+ className="ml-1.5"+ />+ ))}</InputCommandItem>))}</InputCommandGroup>diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsxindex 6ebf0d1bf1..026da15c04 100644--- a/web/src/components/table/use-cases/scores.tsx+++ b/web/src/components/table/use-cases/scores.tsx@@ -63,14 +63,22 @@ import { useTableViewManager } from "@/src/components/table/table-view-presets/himport TableIdOrName from "@/src/components/table/table-id";import { usePaginationState } from "@/src/hooks/usePaginationState";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import {+ ScoreTag,+ scoreLevelFromScore,+ type ScoreLevel,+} from "@/src/components/score-tag";export type ScoresTableRow = {id: string;traceId?: string;sessionId?: string;+ datasetRunId?: string;timestamp: Date;source: string;name: string;+ /** Derived from the score's context ids (scoreLevelFromScore). */+ level: ScoreLevel;dataType: ScoreDataTypeType;value: string;author: {@@ -638,6 +646,22 @@ export default function ScoresTable({enableSorting: true,size: 150,},+ {+ accessorKey: "level",+ header: "Level",+ id: "level",+ enableHiding: true,+ // Derived client-side from the score's context ids β not a sortable+ // backend column.+ enableSorting: false,+ size: 110,+ cell: ({ row }) => {+ // Level tag (LFE-10596): trace- vs observation- (vs session-) level+ // scores look identical here otherwise.+ const level: ScoresTableRow["level"] = row.getValue("level");+ return <ScoreTag level={level} />;+ },+ },{accessorKey: "dataType",header: "Data Type",@@ -820,6 +844,7 @@ export default function ScoresTable({timestamp: score.timestamp,source: score.source,name: score.name,+ level: scoreLevelFromScore(score),dataType: score.dataType,value:isNumericDataType(score.dataType) && isPresent(score.value)@@ -835,6 +860,7 @@ export default function ScoresTable({comment: score.comment ?? undefined,observationId: score.observationId ?? undefined,sessionId: score.sessionId ?? undefined,+ datasetRunId: score.datasetRunId ?? undefined,traceId: score.traceId ?? undefined,traceName: score.traceName ?? undefined,userId: score.traceUserId ?? undefined,@@ -865,6 +891,7 @@ export default function ScoresTable({timestamp: score.timestamp,source: score.source,name: score.name,+ level: scoreLevelFromScore(score),dataType: score.dataType,value:isNumericDataType(score.dataType) && isPresent(score.value)@@ -880,6 +907,7 @@ export default function ScoresTable({comment: score.comment ?? undefined,observationId: score.observationId ?? undefined,sessionId: score.sessionId ?? undefined,+ datasetRunId: score.datasetRunId ?? undefined,traceId: score.traceId ?? undefined,traceName: meta?.traceName ?? undefined,userId: meta?.userId ?? undefined,diff --git a/web/src/components/trace/components/SpanContent.tsx b/web/src/components/trace/components/SpanContent.tsxindex 2ae879a62d..0b8911ff81 100644--- a/web/src/components/trace/components/SpanContent.tsx+++ b/web/src/components/trace/components/SpanContent.tsx@@ -124,7 +124,9 @@ export function SpanContent({onSelect?.();}}onMouseEnter={onHover}- title={node.name}+ // No row-level title: it would pop a native tooltip from ANYWHERE in the+ // row β stacking on the score chips' own titles and the ScoreTag level+ // tooltip. The truncating name span below carries its own title.className={cn("peer relative flex min-w-0 flex-1 items-center rounded-md py-0.5 pr-2 pl-1 text-left",className,diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 1d604c9d38..c7023e70cc 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -81,10 +81,7 @@ import { TableActionMenu } from "@/src/features/table/components/TableActionMenuimport { type TableAction } from "@/src/features/table/types";import { type DataTablePeekViewProps } from "@/src/components/table/peek";import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";-import {- addPrefixToScoreKeys,- scoreFilters,-} from "@/src/features/scores/lib/scoreColumns";+import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { MemoizedIOTableCell } from "@/src/components/ui/IOTableCell";import { useEventsTableData } from "@/src/features/events/hooks/useEventsTableData";@@ -205,9 +202,8 @@ export type EventsTableRow = {traceTags?: string[];traceName?: string;- // Scores+ // Scores (level-agnostic: observation- and trace-level rolled up together)scores: ScoreAggregate;- traceScores: ScoreAggregate;};export type EventsTableProps = {@@ -873,21 +869,17 @@ export default function ObservationsEventsTable({[searchBarMode, observedOptions],);+ // Level-agnostic "Scores": one column group covering every score attached to+ // the trace (observation- AND trace-level). The row's `scores` aggregate is+ // rolled up server-side across both levels, so a trace-level score (e.g.+ // CSAT) shows here even on observation rows β matching the level-agnostic+ // score filter (LFE-10596). No separate "Trace Scores" group.const { scoreColumns, isLoading: isColumnLoading } =useScoreColumns<EventsTableRow>({scoreColumnKey: "scores",projectId,- filter: scoreFilters.forObservations(),- fromTimestamp: dateRange?.from,- defaultHidden: true,- });- const { scoreColumns: traceScoreColumns, isLoading: isTraceColumnLoading } =- useScoreColumns<EventsTableRow>({- scoreColumnKey: "traceScores",- projectId,- filter: scoreFilters.forTraceLevel(),+ filter: scoreFilters.forTraceScopedAggregates(),fromTimestamp: dateRange?.from,- prefix: "Trace",defaultHidden: true,});@@ -1603,17 +1595,6 @@ export default function ObservationsEventsTable({},columns: scoreColumns,},- {- accessorKey: "traceScores",- header: "Trace Scores",- id: "traceScores",- enableHiding: true,- defaultHidden: true,- cell: () => {- return isTraceColumnLoading ? <TableTextLoadingCell /> : null;- },- columns: traceScoreColumns,- },{accessorKey: "endTime",id: "endTime",@@ -1756,10 +1737,6 @@ export default function ObservationsEventsTable({endTime: observation.endTime ?? undefined,timeToFirstToken: observation.timeToFirstToken ?? undefined,scores: observation.scores ?? {},- traceScores: addPrefixToScoreKeys(- observation.traceScores ?? {},- "Trace",- ),latency: observation.latency ?? undefined,totalCost: observation.totalCost ?? undefined,cost: {diff --git a/web/src/features/events/config/filter-config.ts b/web/src/features/events/config/filter-config.tsindex 6f956eb31a..d20a1b56be 100644--- a/web/src/features/events/config/filter-config.ts+++ b/web/src/features/events/config/filter-config.ts@@ -284,6 +284,12 @@ export const observationEventsFilterConfig: FilterConfig = {min: 0,max: 25,},+ // The "Scores" facets are level-agnostic: their filter matches a score at+ // observation OR trace level (LFE-10596), and their options list all score+ // names. The trace-only `trace_scores_avg` / `trace_score_categories` /+ // `trace_score_booleans` columns stay valid (search bar `traceScores.` ++ // existing saved views) but are no longer offered as separate sidebar+ // facets β one "Scores" group.{type: "keyValue" as const,column: "score_categories",@@ -299,21 +305,6 @@ export const observationEventsFilterConfig: FilterConfig = {column: "score_booleans",label: "Boolean Scores",},- {- type: "keyValue" as const,- column: "trace_score_categories",- label: "Trace Categorical Scores",- },- {- type: "numericKeyValue" as const,- column: "trace_scores_avg",- label: "Trace Numeric Scores",- },- {- type: "booleanKeyValue" as const,- column: "trace_score_booleans",- label: "Trace Boolean Scores",- },{type: "numeric" as const,column: "commentCount",diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.tsindex f18b11584c..3e30d2ea58 100644--- a/web/src/features/events/hooks/useEventsFilterOptions.ts+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts@@ -300,6 +300,13 @@ export function useEventsFilterOptions({trace_score_categories: traceScoreCategories,trace_scores_avg: traceScoresNumeric,trace_score_booleans: rawData.trace_score_booleans ?? undefined,+ // Level provenance for the level-agnostic score groups (ScoreTag,+ // LFE-10596): name β the level(s) it exists at, per data-type class so+ // a name reused across types never inherits the other type's level.+ score_name_levels_numeric: rawData.score_name_levels_numeric ?? undefined,+ score_name_levels_categorical:+ rawData.score_name_levels_categorical ?? undefined,+ score_name_levels_boolean: rawData.score_name_levels_boolean ?? undefined,};}, [rawData]);diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex 2b9ce557ab..e422bbb729 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -43,13 +43,13 @@ const TRACE_SCORE_SCOPE_FILTER: FilterCondition[] = [},];-// Observation-level scores: written against a specific observation-// (observation_id set). These are the scores the observation `scores_avg` /-// `score_categories` columns aggregate and filter on (joined by span_id).-// Trace-level scores (observation_id NULL) live under `trace_scores_avg` /-// `trace_score_categories` instead, so they must NOT be offered here β filtering-// a trace-level score name via the observation column can never match (LFE-10596).const OBSERVATION_SCORE_SCOPE_FILTER: FilterCondition[] = [+ {+ type: "null",+ column: "traceId",+ operator: "is not null",+ value: "",+ },{type: "null",column: "observationId",@@ -58,6 +58,21 @@ const OBSERVATION_SCORE_SCOPE_FILTER: FilterCondition[] = [},];+// The level-agnostic "Scores" groups (`scores_avg` / `score_categories`) match a+// score whether it sits at observation or trace level, but only if it rolls up+// into a trace β i.e. `trace_id IS NOT NULL`. Session-level and dataset-run+// scores (`trace_id IS NULL`) can never match the events union, so scope+// discovery to trace-attached scores to keep offered-set == matchable-set+// (LFE-10596). Mirrors `scoreFilters.forTraceScopedAggregates`.+const TRACE_SCOPED_SCORE_FILTER: FilterCondition[] = [+ {+ type: "null",+ column: "traceId",+ operator: "is not null",+ value: "",+ },+];+interface GetObservationsListParams {projectId: string;filter: any[];@@ -316,13 +331,23 @@ export async function getEventList(params: GetObservationsListParams) {}}- const observationsWithScores = observations.map((observation) => ({- ...observation,- scores: aggregateScores(scoresByObservationId.get(observation.id) ?? []),- traceScores: observation.traceId- ? aggregateScores(scoresByTraceId.get(observation.traceId) ?? [])- : {},- }));+ const observationsWithScores = observations.map((observation) => {+ const observationScores = scoresByObservationId.get(observation.id) ?? [];+ const traceScores = observation.traceId+ ? (scoresByTraceId.get(observation.traceId) ?? [])+ : [];+ return {+ ...observation,+ // Level-agnostic "Scores": roll up this observation's scores together with+ // the trace's trace-level scores into a single aggregate, so a trace-level+ // score (e.g. CSAT) shows in the one "Scores" column β matching the+ // level-agnostic score filter (LFE-10596). aggregateScores groups by+ // name/source/dataType, so a score present at both levels merges cleanly.+ scores: aggregateScores([...observationScores, ...traceScores]),+ // Trace-only aggregate, retained for callers that need the breakdown.+ traceScores: aggregateScores(traceScores),+ };+ });return { observations: observationsWithScores, hasMore };}@@ -546,9 +571,20 @@ export async function getEventFilterOptions(const shouldLoadTraceScoreBooleans = requestedColumns.has("trace_score_booleans",);-- // Observation-scoped and trace-scoped discovery are kept separate so each- // score column only offers names its filter/join can actually match.+ // Level provenance for the level-agnostic "Scores" groups: which level(s)+ // each offered score name exists at, so the UI can tag every score option+ // with its level (ScoreTag, LFE-10596). Loaded with the agnostic groups.+ const shouldLoadScoreNameLevels =+ shouldLoadScoresAvg || shouldLoadScoreCategories || shouldLoadScoreBooleans;++ // The `scores_avg` / `score_categories` / `score_booleans` groups are+ // level-agnostic (their filter matches observation- OR trace-level scores;+ // see `toLevelAgnosticScoreFilter` in events-observation-row-selection.ts),+ // so they offer every score that rolls up into a trace β matchable-set ==+ // offered-set (LFE-10596). Scoping to trace-attached scores (`trace_id IS+ // NOT NULL`) excludes session-/dataset-run scores the union can never match.+ // The trace-scoped discovery below stays trace-only to back the search bar's+ // `traceScores.` escape hatch.const [numericScoreNames,booleanScoreNames,@@ -556,23 +592,25 @@ export async function getEventFilterOptions(traceScoreColumns,traceCategoricalScoreColumns,traceBooleanScoreColumns,+ observationLevelScoreNames,+ traceLevelScoreNames,eventFilterOptions,] = await Promise.all([shouldLoadScoresAvg? getNumericScoresGroupedByName(projectId, [- ...OBSERVATION_SCORE_SCOPE_FILTER,+ ...TRACE_SCOPED_SCORE_FILTER,...traceTimestampFilters,]): Promise.resolve([]),shouldLoadScoreBooleans? getBooleanScoresGroupedByName(projectId, [- ...OBSERVATION_SCORE_SCOPE_FILTER,+ ...TRACE_SCOPED_SCORE_FILTER,...traceTimestampFilters,]): Promise.resolve([]),shouldLoadScoreCategories? getCategoricalScoresGroupedByName(projectId, [- ...OBSERVATION_SCORE_SCOPE_FILTER,+ ...TRACE_SCOPED_SCORE_FILTER,...traceTimestampFilters,]): Promise.resolve([]),@@ -594,6 +632,21 @@ export async function getEventFilterOptions(...traceTimestampFilters,]): Promise.resolve([]),+ shouldLoadScoreNameLevels+ ? getScoresGroupedByNameSourceType({+ projectId,+ filter: [+ ...OBSERVATION_SCORE_SCOPE_FILTER,+ ...traceScoreTimestampFilters,+ ],+ })+ : Promise.resolve([]),+ shouldLoadScoreNameLevels+ ? getScoresGroupedByNameSourceType({+ projectId,+ filter: [...TRACE_SCORE_SCOPE_FILTER, ...traceScoreTimestampFilters],+ })+ : Promise.resolve([]),eventColumns.length > 0? getEventsFilterOptionsForColumns({projectId,@@ -617,6 +670,35 @@ export async function getEventFilterOptions(eventColumns,);+ // name β the level(s) the name actually exists at, SPLIT PER DATA-TYPE+ // class: a name can be reused across types at different levels (a NUMERIC+ // observation-level "accuracy" next to an unrelated CATEGORICAL trace-level+ // "accuracy"), and a name-only map would mislabel both. Each type-scoped+ // facet reads its own map; the search bar's merged suggestion unions them.+ // Discovery rows are grouped by (name, source, dataType) β dedupe per level.+ const scoreNameLevelsByType = {+ numeric: {} as Record<string, ("observation" | "trace")[]>,+ categorical: {} as Record<string, ("observation" | "trace")[]>,+ boolean: {} as Record<string, ("observation" | "trace")[]>,+ };+ const addScoreNameLevel = (+ score: { name: string; dataType: string },+ level: "observation" | "trace",+ ): void => {+ const typeClass =+ score.dataType === "NUMERIC"+ ? "numeric"+ : score.dataType === "BOOLEAN"+ ? "boolean"+ : "categorical"; // CATEGORICAL + TEXT+ const levels = (scoreNameLevelsByType[typeClass][score.name] ??= []);+ if (!levels.includes(level)) levels.push(level);+ };+ observationLevelScoreNames.forEach((score) =>+ addScoreNameLevel(score, "observation"),+ );+ traceLevelScoreNames.forEach((score) => addScoreNameLevel(score, "trace"));+// Only include a score key when its column was requested, so an unrequested// (lazily-loadable) score facet stays absent from the payload rather than// arriving as an empty list (which the client cannot tell from "loaded, no@@ -647,6 +729,13 @@ export async function getEventFilterOptions(),}: {}),+ ...(shouldLoadScoreNameLevels+ ? {+ score_name_levels_numeric: scoreNameLevelsByType.numeric,+ score_name_levels_categorical: scoreNameLevelsByType.categorical,+ score_name_levels_boolean: scoreNameLevelsByType.boolean,+ }+ : {}),};}diff --git a/web/src/features/filters/components/multi-select.tsx b/web/src/features/filters/components/multi-select.tsxindex 7e1b356d19..1ee9476a9e 100644--- a/web/src/features/filters/components/multi-select.tsx+++ b/web/src/features/filters/components/multi-select.tsx@@ -140,13 +140,15 @@ export function MultiSelect({<Buttonvariant="outline"className={cn(- "border-input ring-offset-background placeholder:text-foreground-tertiary focus:ring-ring flex h-8 w-full items-center justify-between gap-x-2 rounded-md border px-3 py-2 text-sm focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",+ // min-w-0 + overflow-hidden: the trigger must never grow past its+ // container β wide selected values truncate instead.+ "border-input ring-offset-background placeholder:text-foreground-tertiary focus:ring-ring flex h-8 w-full min-w-0 items-center justify-between gap-x-2 overflow-hidden rounded-md border px-3 py-2 text-sm focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",className,)}disabled={disabled}>{label ?? "Select"}- <ChevronDown className="h-4 w-4 opacity-50" />+ <ChevronDown className="h-4 w-4 shrink-0 opacity-50" />{selectedValues.size > 0 && (<><Separator orientation="vertical" className="mr-auto h-4" />@@ -156,7 +158,7 @@ export function MultiSelect({>{selectedValues.size}</Badge>- <div className="hidden space-x-1 lg:flex">+ <div className="hidden min-w-0 space-x-1 overflow-hidden lg:flex">{selectedValues.size > labelTruncateCutOff ? (<Badgevariant="secondary"@@ -174,11 +176,13 @@ export function MultiSelect({variant="secondary"key={option.value}className={cn(- "rounded-sm px-1 font-normal",+ "min-w-0 rounded-sm px-1 font-normal",option.value === "" && "italic",)}>- {displayValue}+ <span className="truncate" title={displayValue}>+ {displayValue}+ </span></Badge>);})diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex 399eb627f0..d172e60207 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -232,6 +232,17 @@ export interface StringUIFilter extends BaseUIFilter {onChange: (value: string) => void;}+/**+ * Score-name β the level(s) it exists at, for tagging each offered name with+ * a ScoreTag (LFE-10596). Only present on the level-agnostic score facets+ * (`scores_avg` / `score_categories` / `score_booleans`), fed by the+ * filter-options `score_name_levels` payload.+ */+export type KeyScoreLevels = Record<+ string,+ readonly ("observation" | "trace")[]+>;+// The keyed-facet row shapes live beside the pure state transitions in// sidebar-filter-actions; re-exported here so existing consumers keep their// import path.@@ -246,6 +257,7 @@ export interface KeyValueUIFilter extends BaseUIFilter {type: "keyValue";value: KeyValueFilterEntry[]; // Array of active filter rowskeyOptions?: string[];+ keyLevels?: KeyScoreLevels;availableValues: Record<string, string[]>;onChange: (filters: KeyValueFilterEntry[]) => void;}@@ -254,6 +266,7 @@ export interface NumericKeyValueUIFilter extends BaseUIFilter {type: "numericKeyValue";value: NumericKeyValueFilterEntry[]; // Array of active filter rowskeyOptions?: string[];+ keyLevels?: KeyScoreLevels;onChange: (filters: NumericKeyValueFilterEntry[]) => void;}@@ -261,6 +274,7 @@ export interface BooleanKeyValueUIFilter extends BaseUIFilter {type: "booleanKeyValue";value: BooleanKeyValueFilterEntry[]; // Array of active filter rowskeyOptions?: string[];+ keyLevels?: KeyScoreLevels;onChange: (filters: BooleanKeyValueFilterEntry[]) => void;}@@ -289,6 +303,39 @@ const mergeUniqueStrings = (...lists: (string[] | undefined)[]): string[] =>),);+// The level-agnostic score facet columns whose name pickers carry ScoreTag+// level provenance (LFE-10596), each reading its OWN data-type-scoped level+// map β a name reused across types at different levels must not inherit the+// other type's level. Other keyValue facets (metadata) never carry levels.+const SCORE_LEVEL_TAGGED_COLUMNS: Readonly<Record<string, string>> = {+ scores_avg: "score_name_levels_numeric",+ score_categories: "score_name_levels_categorical",+ score_booleans: "score_name_levels_boolean",+};++const resolveKeyScoreLevels = (+ column: string,+ options: Record<+ string,+ (string | SingleValueOption)[] | Record<string, string[]> | undefined+ >,+): KeyScoreLevels | undefined => {+ const levelsKey = SCORE_LEVEL_TAGGED_COLUMNS[column];+ const scoreNameLevels = levelsKey ? options[levelsKey] : undefined;+ if (scoreNameLevels === undefined || Array.isArray(scoreNameLevels)) {+ return undefined;+ }+ const out: Record<string, ("observation" | "trace")[]> = {};+ for (const [name, levels] of Object.entries(scoreNameLevels)) {+ const valid = levels.filter(+ (level): level is "observation" | "trace" =>+ level === "observation" || level === "trace",+ );+ if (valid.length > 0) out[name] = valid;+ }+ return out;+};+const resolveKnownKeyOptions = (facetKeyOptions: string[] | undefined,availableKeys:@@ -1295,6 +1342,7 @@ export function useSidebarFilterState(value: activeFilters,keyOptions,+ keyLevels: resolveKeyScoreLevels(facet.column, options),availableValues: mergedAvailableValues,loading: shouldShowLoading(facet.column),expanded: expandedSet.has(facet.column),@@ -1376,6 +1424,7 @@ export function useSidebarFilterState(value: activeFilters,keyOptions,+ keyLevels: resolveKeyScoreLevels(facet.column, options),loading: shouldShowLoading(facet.column),expanded: expandedSet.has(facet.column),isActive,@@ -1427,6 +1476,7 @@ export function useSidebarFilterState(value: activeFilters,keyOptions,+ keyLevels: resolveKeyScoreLevels(facet.column, options),loading: shouldShowLoading(facet.column),expanded: expandedSet.has(facet.column),isActive,diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.mdindex 6419328908..f7b26dee77 100644--- a/web/src/features/search-bar/README.md+++ b/web/src/features/search-bar/README.md@@ -45,11 +45,14 @@ Generally available on the v4 events tables (no opt-in). Based on the`statusMessage:chat` bare (contains default), `statusMessage:=chat` exact(quote a literal `*`, e.g. `statusMessage:"a*b"`). `name:`/`id:` work the sameway (bare = contains, `:=` = exact) but still suggest observed values.-- `metadata.region:eu`, `scores.accuracy:>0.8`, `traceScores.nps:positive`+- `metadata.region:eu`, `scores.accuracy:>0.8` β `scores.` is level-agnostic+ (matches a score at observation OR trace level, LFE-10596). The legacy+ `traceScores.` namespace (trace-only) still parses/lowers so saved queries+ and URLs keep working, but it is no longer offered in suggestions.- dot-path names with spaces/grammar chars are **quoted after the prefix**:- `scores."Rouge Score":>=1`, `traceScores."Hallucination Check":faithful`,- `metadata."my key":eu` (the quotes are stripped to the real key when lowering;- the reverse adapter and completions re-quote them β so they round-trip)+ `scores."Rouge Score":>=1`, `metadata."my key":eu` (the quotes are stripped+ to the real key when lowering; the reverse adapter and completions re-quote+ them β so they round-trip)- `has:endTime` / `-has:endTime` null checks- full-text search (see below): bare text, or `input:`/`output:`/`name:`/`id:`diff --git a/web/src/features/search-bar/components/AutocompleteListbox.tsx b/web/src/features/search-bar/components/AutocompleteListbox.tsxindex 9a16b43d47..33a2dca41f 100644--- a/web/src/features/search-bar/components/AutocompleteListbox.tsx+++ b/web/src/features/search-bar/components/AutocompleteListbox.tsx@@ -7,6 +7,7 @@ import * as React from "react";import { Check, Clock, Parentheses, Search } from "lucide-react";import { cn } from "@/src/utils/tailwind";+import { ScoreTag } from "@/src/components/score-tag";import type {CompletionOption,CompletionPlan,@@ -133,6 +134,10 @@ export function AutocompleteListbox({>{o.label}</span>+ {o.kind === "field" &&+ o.scoreLevels?.map((level) => (+ <ScoreTag key={level} level={level} className="flex-none" />+ ))}{o.kind === "value" && o.active && (<CheckclassName="text-foreground/80 h-3.5 w-3.5 flex-none"diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.tsindex 8d240ca0df..9126b642f1 100644--- a/web/src/features/search-bar/lib/completions.ts+++ b/web/src/features/search-bar/lib/completions.ts@@ -45,6 +45,9 @@ export type CompletionOption =label: string;detail?: string;fieldId: string;+ /** Score-name options only: the level(s) the name exists at, rendered as+ * ScoreTag(s) in the listbox (global score-level coding, LFE-10596). */+ scoreLevels?: readonly ("observation" | "trace")[];}| {id: string;@@ -191,6 +194,10 @@ function fieldOptions(includeVirtual = true): CompletionOption[] {detail: "metadata key path, e.g. metadata.region:eu",fieldId: "metadata.",},+ // `scores.` is level-agnostic (LFE-10596): one entry point for every+ // score. The legacy `traceScores.` namespace still parses and lowers+ // (saved queries/URLs keep working) but is no longer offered β two+ // score entry points confused users.{id: "field:scores.",kind: "field",@@ -199,13 +206,6 @@ function fieldOptions(includeVirtual = true): CompletionOption[] {"score by name, e.g. scores.accuracy:>0.8 or scores.feedback:positive",fieldId: "scores.",},- {- id: "field:traceScores.",- kind: "field",- label: "traceScores.",- detail: "trace-level score by name, e.g. traceScores.nps:>8",- fieldId: "traceScores.",- },{id: "field:has",kind: "field",@@ -594,12 +594,36 @@ function keyPathOptions(: "boolean score",);}+ // Level provenance for the ScoreTag on each option (LFE-10596): the+ // `traceScores.` namespace is trace-only by construction; `scores.` is+ // level-agnostic, so tag the level(s) the name actually exists at (from the+ // per-data-type `score_name_levels_*` payloads β absent levels mean no tag,+ // never a guess). One suggestion covers every data type the name has, so+ // its tags are the union across those type-scoped maps.+ const levelsOf = (+ name: string,+ ): readonly ("observation" | "trace")[] | undefined => {+ if (kind.level === "trace") return ["trace"];+ const levels = [+ ...observedValues(observed, `score_name_levels_numeric.${name}`),+ ...observedValues(observed, `score_name_levels_categorical.${name}`),+ ...observedValues(observed, `score_name_levels_boolean.${name}`),+ ]+ .map((o) => o.value)+ .filter((v) => v === "observation" || v === "trace") as (+ | "observation"+ | "trace"+ )[];+ const unique = Array.from(new Set(levels));+ return unique.length > 0 ? unique : undefined;+ };const options = [...seen.entries()].map(([name, detail]) => ({id: `key:${kind.canonical}${name}`,kind: "field" as const,label: `${kind.canonical}${name}`,detail,fieldId: keyText(name),+ scoreLevels: levelsOf(name),}));return {title: SECTION_SCORE_NAMES,diff --git a/web/src/features/search-bar/server/buildFilterPrompt.ts b/web/src/features/search-bar/server/buildFilterPrompt.tsindex abd0b9c43c..3ceb206bec 100644--- a/web/src/features/search-bar/server/buildFilterPrompt.ts+++ b/web/src/features/search-bar/server/buildFilterPrompt.ts@@ -182,11 +182,12 @@ phrase (e.g. "routing queue" β metadata.routing.queue), use that exact key. Us## Scores (evaluation results)-Filter by score NAME via the "key" field. Default to OBSERVATION-level scores-unless the request clearly means trace-level scores.-- Numeric score: {"type": "numberObject", "column": "${SCORE_COLUMNS.observation.numeric}" (observation) or "${SCORE_COLUMNS.trace.numeric}" (trace), "key": "<score name>", "operator": ">" | "<" | ">=" | "<=" | "=", "value": <number>}-- Categorical score: {"type": "categoryOptions", "column": "${SCORE_COLUMNS.observation.categorical}" (observation) or "${SCORE_COLUMNS.trace.categorical}" (trace), "key": "<score name>", "operator": "any of" | "none of", "value": ["<category>"]}-- Boolean score: {"type": "booleanObject", "column": "${SCORE_COLUMNS.observation.boolean}" (observation) or "${SCORE_COLUMNS.trace.boolean}" (trace), "key": "<score name>", "operator": "=" | "<>", "value": true | false}+Filter by score NAME via the "key" field. The score columns+(${SCORE_COLUMNS.observation.numeric} / ${SCORE_COLUMNS.observation.categorical} / ${SCORE_COLUMNS.observation.boolean}) are level-agnostic: they match a score+whether it was recorded at observation or trace level β always use them.+- Numeric score: {"type": "numberObject", "column": "${SCORE_COLUMNS.observation.numeric}", "key": "<score name>", "operator": ">" | "<" | ">=" | "<=" | "=", "value": <number>}+- Categorical score: {"type": "categoryOptions", "column": "${SCORE_COLUMNS.observation.categorical}", "key": "<score name>", "operator": "any of" | "none of", "value": ["<category>"]}+- Boolean score: {"type": "booleanObject", "column": "${SCORE_COLUMNS.observation.boolean}", "key": "<score name>", "operator": "=" | "<>", "value": true | false}NEVER use ${SCORE_COLUMNS.observation.numeric} / ${SCORE_COLUMNS.observation.categorical} / ${SCORE_COLUMNS.observation.boolean} / ${SCORE_COLUMNS.trace.numeric} / ${SCORE_COLUMNS.trace.categorical} / ${SCORE_COLUMNS.trace.boolean} as a plain column (no bare {"type":"number","column":"${SCORE_COLUMNS.observation.numeric}"} etc.) β they REQUIRE the keyed numberObject/categoryOptions/booleanObject shape above with the score name in "key". Only use a score name that appears in the observed data; do not invent one.diff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex 3a12219595..f57b7af3ea 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -81,6 +81,10 @@--color-dark-blue: hsl(var(--dark-blue));--color-accent-light-blue: hsl(var(--accent-light-blue));--color-accent-dark-blue: hsl(var(--accent-dark-blue));+ --color-light-violet: hsl(var(--light-violet));+ --color-dark-violet: hsl(var(--dark-violet));+ --color-light-teal: hsl(var(--light-teal));+ --color-dark-teal: hsl(var(--dark-teal));/* Search-bar query syntax highlighting (key:value token parts). Operators(`:` `-` `(` `)`) reuse muted-foreground, so no token for them here. */@@ -318,6 +322,16 @@--accent-light-blue: 251 95.2% 91.8%;--accent-dark-blue: 224 76.3% 38%;+ /* Violet + teal hue pairs, same bg/fg recipe as the light-X/dark-X pairs+ above. Added for the score-level color coding (ScoreTag, LFE-10596):+ observation=blue, trace=violet, session=teal, experiment=yellow β the+ blue and yellow pairs are reused from above. */+ --light-violet: 251 91% 95.5%;+ --dark-violet: 262 72% 54%;++ --light-teal: 167 85% 89%;+ --dark-teal: 175 84% 28%;+/* Search-bar query syntax highlighting β a DELIBERATE editor-style syntaxtheme (like a code editor's theme), intentionally its own thing ratherthan the app palette: field=violet, value=green, number=orange,@@ -469,6 +483,13 @@--accent-light-blue: 240 32.4% 13.9%;--accent-dark-blue: 246 70% 76%;+ /* Score-level violet + teal (see :root): dark tinted bg + bright fg. */+ --light-violet: 258 40% 16%;+ --dark-violet: 255 92% 76%;++ --light-teal: 175 40% 12%;+ --dark-teal: 172 66% 50%;+/* Search-bar query syntax highlighting (dark). Brighter than light so thekey/value read against the dark surface. See :root for the contract. */--qlang-field: 255 92% 76%;diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.tsindex 55dc6bfd3e..0c334ed62e 100644--- a/worker/src/__tests__/batchExport.test.ts+++ b/worker/src/__tests__/batchExport.test.ts@@ -2734,6 +2734,117 @@ describe("batch export test suite", () => {expect(generationRow?.totalUsage).toBeGreaterThan(0);});+ it("matches a trace-level score via the observation-scoped score filter on export (LFE-10596)", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const scoredTraceId = randomUUID();+ const now = Date.now() * 1000;++ const events = [+ createEvent({+ project_id: projectId,+ trace_id: scoredTraceId,+ type: "SPAN",+ name: "help-assistant",+ start_time: now,+ }),+ createEvent({+ project_id: projectId,+ trace_id: randomUUID(),+ type: "SPAN",+ name: "unscored-trace",+ start_time: now,+ }),+ ];+ await createEventsCh(events);++ // Trace-level score (observation_id NULL) on the first trace only.+ await createScoresCh([+ createTraceScore({+ project_id: projectId,+ trace_id: scoredTraceId,+ observation_id: null,+ name: "CSAT",+ value: 1,+ data_type: "NUMERIC",+ }),+ ]);++ const stream = await getObservationStream({+ projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ // The observation-scoped `scores_avg` filter is level-agnostic on export+ // too: it must match the trace-level CSAT (pre-fix this returned empty,+ // diverging from the UI β LFE-10596).+ filter: [+ {+ type: "numberObject",+ column: "scores_avg",+ key: "CSAT",+ operator: ">",+ value: 0,+ },+ ],+ useEventsTable: true,+ });++ const rows: any[] = [];+ for await (const chunk of stream) {+ rows.push(chunk);+ }++ expect(rows).toHaveLength(1);+ expect(rows[0].name).toBe("help-assistant");+ // The matched row must also EXPORT the trace-level score's value β+ // matching-but-blank diverges from the UI's unified Scores column.+ expect(rows[0].CSAT).toEqual([1]);+ });++ it("exports trace-level score values without any score filter (LFE-10596)", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const scoredTraceId = randomUUID();+ const now = Date.now() * 1000;++ await createEventsCh([+ createEvent({+ project_id: projectId,+ trace_id: scoredTraceId,+ type: "SPAN",+ name: "help-assistant",+ start_time: now,+ }),+ ]);++ await createScoresCh([+ createTraceScore({+ project_id: projectId,+ trace_id: scoredTraceId,+ observation_id: null,+ name: "CSAT",+ value: 1,+ data_type: "NUMERIC",+ }),+ ]);++ // No filter: the export must still carry the trace-level score value,+ // mirroring the UI's unified Scores column (LFE-10596).+ const stream = await getObservationStream({+ projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [],+ useEventsTable: true,+ });++ const rows: any[] = [];+ for await (const chunk of stream) {+ rows.push(chunk);+ }++ expect(rows).toHaveLength(1);+ expect(rows[0].CSAT).toEqual([1]);+ });+it("should apply observation-level score filters and ignore trace-level score filters when useEventsTable is true", async () => {const { projectId } = await createOrgProjectAndApiKey();@@ -2793,9 +2904,11 @@ describe("batch export test suite", () => {];await createScoresCh(scores);- // Observation-level score filter applies (accuracy >= 0.7); the- // trace-level score filter references the trace_scores_agg CTE that the- // export does not join, so it is dropped rather than failing the export.+ // Observation-scoped score filter applies (accuracy >= 0.7). The explicit+ // trace-only "Trace Scores (numeric)" filter is dropped before the query+ // (the `traceScores.` escape hatch is not wired on this export path), so+ // it is ignored rather than failing the export. Here `accuracy` exists+ // only at observation level, so the level-agnostic union adds nothing.const stream = await getObservationStream({projectId,cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),@@ -3018,6 +3131,63 @@ describe("batch export test suite", () => {);});+ it("exports trace-level score values on the events export (LFE-10596)", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const scoredTraceId = randomUUID();+ const now = Date.now() * 1000;++ await createEventsCh([+ createEvent({+ project_id: projectId,+ trace_id: scoredTraceId,+ type: "SPAN",+ name: "help-assistant",+ start_time: now,+ }),+ ]);++ // One trace-level (observation_id NULL) numeric score and one+ // trace-level categorical score: both must land in the exported row β+ // pre-fix this path never joined the trace-score aggregate, so every+ // trace-level score exported blank (diverging from the UI's unified+ // Scores column).+ await createScoresCh([+ createTraceScore({+ project_id: projectId,+ trace_id: scoredTraceId,+ observation_id: null,+ name: "CSAT",+ value: 1,+ data_type: "NUMERIC",+ }),+ createTraceScore({+ project_id: projectId,+ trace_id: scoredTraceId,+ observation_id: null,+ name: "sentiment",+ value: null,+ string_value: "positive",+ data_type: "CATEGORICAL",+ }),+ ]);++ const stream = await getEventsStream({+ projectId: projectId,+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),+ filter: [],+ });++ const rows: any[] = [];+ for await (const chunk of stream) {+ rows.push(chunk);+ }++ expect(rows).toHaveLength(1);+ expect(rows[0].name).toBe("help-assistant");+ expect(rows[0].CSAT).toEqual([1]);+ expect(rows[0].sentiment).toEqual(["positive"]);+ });it("should export events with filters", async () => {const { projectId } = await createOrgProjectAndApiKey();diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex 14746bad4a..e25610c4ed 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -130,6 +130,20 @@ export const getEventsStream = async (props: {| undefined;score_categories: string[] | undefined;score_categories_tuples: [string, string | null, string][] | undefined;+ // Trace-level scores (observation_id NULL) live in their own aggregate;+ // exported rows merge them with the observation-level ones so the export+ // matches the UI's unified Scores column (LFE-10596).+ trace_scores_avg:+ | {+ name: string;+ value: number;+ dataType: ScoreDataTypeType;+ stringValue: string;+ }[]+ | undefined;+ trace_score_categories_tuples:+ | [string, string | null, string][]+ | undefined;};const asyncGenerator = queryClickhouseStream<EventRow>({@@ -145,8 +159,13 @@ export const getEventsStream = async (props: {bufferedRow: EventRow,commentsByEvent: Map<string, any[]>,) => {- // Process numeric/boolean scores (tuples from ClickHouse)- const numericScores = (bufferedRow.scores_avg ?? []).map((score: any) => ({+ // Process numeric/boolean scores (tuples from ClickHouse), merging the+ // observation-level and trace-level aggregates so the export matches the+ // UI's unified Scores column (LFE-10596).+ const numericScores = [+ ...(bufferedRow.scores_avg ?? []),+ ...(bufferedRow.trace_scores_avg ?? []),+ ].map((score: any) => ({name: score[0],value: score[1],dataType: score[2],@@ -154,14 +173,15 @@ export const getEventsStream = async (props: {}));// Process categorical scores (tuples from ClickHouse)- const categoricalScores = (bufferedRow.score_categories_tuples ?? []).map(- (cat: [string, string | null, string]) => ({- name: cat[0],- value: null,- dataType: cat[2],- stringValue: cat[1],- }),- );+ const categoricalScores = [+ ...(bufferedRow.score_categories_tuples ?? []),+ ...(bufferedRow.trace_score_categories_tuples ?? []),+ ].map((cat: [string, string | null, string]) => ({+ name: cat[0],+ value: null,+ dataType: cat[2],+ stringValue: cat[1],+ }));const outputScores: Record<string, string[] | number[]> =prepareScoresForOutput([...numericScores, ...categoricalScores]);diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.tsindex d10b735ce2..fea0e74492 100644--- a/worker/src/features/database-read-stream/observation-stream.ts+++ b/worker/src/features/database-read-stream/observation-stream.ts@@ -26,6 +26,8 @@ import {EventsQueryBuilder,eventSearchCondition,eventsScoresAggregation,+ eventsTracesScoresAggregation,+ toLevelAgnosticScoreFilter,scoreBooleansAggregation,} from "@langfuse/shared/src/server";import { Readable } from "stream";@@ -450,20 +452,22 @@ const getObservationStreamFromEvents = async (};// Trace-level filters are kept: the events table carries trace fields- // denormalized, so they apply directly. Observation-level score filters are- // kept too β they map to the scores_agg CTE (s.*) joined below, matching the- // legacy export. Dropped are trace-level score filters (they reference a- // trace_scores_agg CTE this query does not join) and comment filters- // (comments live in Postgres and are resolved before the stream via- // applyCommentFilters).+ // denormalized, so they apply directly. Observation-scoped score filters+ // (`scores_avg` / `score_categories`, the "s." alias) are kept too β they are+ // rewritten below into a level-agnostic union across the obs (`s.`) and trace+ // (`ts.`) score CTEs so a trace-level score matches on export exactly as it+ // does in the UI (LFE-10596). Dropped are the explicit trace-only score+ // filters (the "ts." alias β the `traceScores.` escape hatch, not wired on+ // this export path) and comment filters (comments live in Postgres and are+ // resolved before the stream via applyCommentFilters).const exportableFilters = (filter ?? []).filter((f) => {const columnDef = eventsTableUiColumnDefinitions.find((col) => col.uiTableName === f.column || col.uiTableId === f.column,);if (columnDef?.clickhouseTableName === "comments") return false;if (columnDef?.clickhouseTableName === "scores") {- // Observation-level score columns select from the "s." alias,- // trace-level ones from "ts.".+ // Observation-scoped score columns select from the "s." alias,+ // trace-only ones from "ts.".return columnDef.clickhouseSelect.startsWith("s.");}return true;@@ -498,7 +502,7 @@ const getObservationStreamFromEvents = async (],eventsTableUiColumnDefinitions,eventsTableCols,- ),+ ).map(toLevelAgnosticScoreFilter),);const appliedEventsFilter = eventsFilter.apply();@@ -516,6 +520,8 @@ const getObservationStreamFromEvents = async ("s.scores_avg as scores_avg","s.score_categories as score_categories","s.score_categories_tuples as score_categories_tuples",+ "ts.scores_avg as trace_scores_avg",+ "ts.score_categories_tuples as trace_score_categories_tuples",).withCTE("scores_agg",@@ -525,6 +531,21 @@ const getObservationStreamFromEvents = async ("scores_agg s","ON s.trace_id = e.trace_id AND s.observation_id = e.span_id",)+ // Trace-level scores are always joined and exported so the export matches+ // the UI's unified Scores column, and so the level-agnostic score-filter+ // union (which references `ts.*`) resolves (LFE-10596).+ .withCTE(+ "trace_scores_agg",+ eventsTracesScoresAggregation({+ projectId,+ hasScoreAggregationFilters: true,+ includeTupleEncoding: true,+ }),+ )+ .leftJoin(+ "trace_scores_agg AS ts",+ "ON ts.trace_id = e.trace_id AND ts.project_id = e.project_id",+ ).when(search.requiresEventsFull, (b) => b.forceFullTable()).where(appliedEventsFilter).where(search)@@ -546,6 +567,19 @@ const getObservationStreamFromEvents = async (| undefined;score_categories: string[] | undefined;score_categories_tuples: [string, string | null, string][] | undefined;+ // Trace-level scores (observation_id NULL), merged into the exported+ // scores so the export matches the UI's unified Scores column (LFE-10596).+ trace_scores_avg:+ | {+ name: string;+ value: number;+ dataType: ScoreDataTypeType;+ stringValue: string;+ }[]+ | undefined;+ trace_score_categories_tuples:+ | [string, string | null, string][]+ | undefined;};const asyncGenerator = queryClickhouseStream<EventsObservationRow>({@@ -575,8 +609,13 @@ const getObservationStreamFromEvents = async (const model = await modelCache.getModel(converted.internalModelId);const modelData = enrichObservationWithModelData(model);- // Process numeric/boolean scores (tuples from ClickHouse)- const numericScores = (bufferedRow.scores_avg ?? []).map((score: any) => ({+ // Process numeric/boolean scores (tuples from ClickHouse), merging the+ // observation-level and trace-level aggregates so the export matches the+ // UI's unified Scores column (LFE-10596).+ const numericScores = [+ ...(bufferedRow.scores_avg ?? []),+ ...(bufferedRow.trace_scores_avg ?? []),+ ].map((score: any) => ({name: score[0],value: score[1],dataType: score[2],@@ -584,14 +623,15 @@ const getObservationStreamFromEvents = async (}));// Process categorical scores (tuples from ClickHouse)- const categoricalScores = (bufferedRow.score_categories_tuples ?? []).map(- (cat) => ({- name: cat[0],- value: null,- dataType: cat[2],- stringValue: cat[1],- }),- );+ const categoricalScores = [+ ...(bufferedRow.score_categories_tuples ?? []),+ ...(bufferedRow.trace_score_categories_tuples ?? []),+ ].map((cat) => ({+ name: cat[0],+ value: null,+ dataType: cat[2],+ stringValue: cat[1],+ }));const outputScores: Record<string, string[] | number[]> =prepareScoresForOutput([...numericScores, ...categoricalScores]);