🪢 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(experiments): support charting in experiment list (#13686)
marliessophie38cf286ea21f
diff --git a/packages/shared/src/features/query/dataModel.ts b/packages/shared/src/features/query/dataModel.tsindex 01633374c7..4b639505b4 100644--- a/packages/shared/src/features/query/dataModel.ts+++ b/packages/shared/src/features/query/dataModel.ts@@ -690,6 +690,16 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {description: "Identifier of the session.",highCardinality: true,},+ // Run-level scores (dataset_run_id on scores table). Used by experiment+ // widgets via entityDimension + filters.+ datasetRunId: {+ sql: "nullIf(scores.dataset_run_id, '')",+ alias: "datasetRunId",+ type: "string",+ description: "Identifier of the dataset run (experiment) for the score.",+ highCardinality: true,+ uiHidden: true,+ },// Trace metadata on events table (accessed via events_traces JOIN)traceName: {sql: "COALESCE(nullIf(events_traces.trace_name, ''), nullIf(events_traces.name, ''))",@@ -756,6 +766,27 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {relationTable: "events_observations",description: "Version of the prompt used for the observation.",},+ // Experiment fields for observation-attached scores. These stay hidden from+ // the custom dashboard builder for now and are used by internal experiment+ // widgets via entityDimension + filters.+ experimentName: {+ sql: "nullIf(events_observations.experiment_name, '')",+ alias: "experimentName",+ type: "string",+ relationTable: "events_observations",+ description: "Name of the experiment associated with the score.",+ highCardinality: true,+ uiHidden: true,+ },+ experimentId: {+ sql: "nullIf(events_observations.experiment_id, '')",+ alias: "experimentId",+ type: "string",+ relationTable: "events_observations",+ description: "ID of the experiment associated with the score.",+ highCardinality: true,+ uiHidden: true,+ },};// Factory for shared score-specific dimensions (both numeric and categorical)diff --git a/packages/shared/src/features/query/server/queryBuilder.ts b/packages/shared/src/features/query/server/queryBuilder.tsindex 76103ed237..8f8ec00095 100644--- a/packages/shared/src/features/query/server/queryBuilder.ts+++ b/packages/shared/src/features/query/server/queryBuilder.ts@@ -51,6 +51,20 @@ type MappedFilters = {whereRawParts: RawSqlPart[];};+type AppliedBucketingDimension =+ | { type: "none" }+ | {+ type: "time";+ bucketDimensionAlias: "time_dimension";+ granularity: z.infer<typeof granularities>;+ }+ | {+ type: "entity";+ bucketDimensionAlias: "entity_dimension";+ field: string;+ dimension: AppliedDimensionType;+ };+export class QueryBuilder {private chartConfig?: { bins?: number; row_limit?: number };private version: ViewVersion;@@ -114,6 +128,94 @@ export class QueryBuilder {return getViewDeclaration(viewName, this.version);}+ private applyBucketingDimension(+ query: QueryType,+ view: ViewDeclarationType,+ ): AppliedBucketingDimension {+ if (query.timeDimension && query.entityDimension) {+ throw new InvalidRequestError(+ "timeDimension and entityDimension are mutually exclusive",+ );+ }++ if (query.timeDimension) {+ const granularity =+ query.timeDimension.granularity === "auto"+ ? this.determineTimeGranularity(+ query.fromTimestamp,+ query.toTimestamp,+ )+ : query.timeDimension.granularity;++ return {+ type: "time",+ bucketDimensionAlias: "time_dimension",+ granularity,+ };+ }++ if (query.entityDimension) {+ if (this.version !== "v2") {+ throw new InvalidRequestError(+ "entityDimension is only supported for v2 queries",+ );+ }++ const field = query.entityDimension.field;+ const dimension = this.getEntityDimensionDefinition(view, field);++ // Entity buckets reuse view dimensions for SQL/relation metadata, but they are+ // not regular dimensions. Only declared relations are allowed; do not infer+ // broader join paths or propagation behavior here.+ if (+ dimension.relationTable &&+ !(dimension.relationTable in view.tableRelations)+ ) {+ throw new InvalidRequestError(+ `Invalid relationTable for entity dimension ${field}: ${dimension.relationTable}. Must be one of ${Object.keys(view.tableRelations)}`,+ );+ }++ return {+ type: "entity",+ bucketDimensionAlias: "entity_dimension",+ field,+ dimension: {+ ...dimension,+ table: dimension.relationTable || view.name,+ explodeArray: dimension.explodeArray,+ pairExpand: dimension.pairExpand,+ },+ };+ }++ return { type: "none" };+ }++ private getEntityDimensionDefinition(+ view: ViewDeclarationType,+ field: string,+ ) {+ const dimension = view.dimensions[field];+ if (!dimension) {+ throw new InvalidRequestError(+ `Invalid entity dimension: ${field}. Must be one of ${Object.keys(view.dimensions)}`,+ );+ }++ if (+ dimension.explodeArray ||+ dimension.pairExpand ||+ dimension.aggregationFunction+ ) {+ throw new InvalidRequestError(+ `Invalid entity dimension: ${field}. Entity dimensions must be scalar view dimensions.`,+ );+ }++ return dimension;+ }+private mapDimensions(dimensions: Array<{ field: string }>,view: ViewDeclarationType,@@ -517,10 +619,20 @@ export class QueryBuilder {appliedDimensions: AppliedDimensionType[],appliedMetrics: AppliedMetricType[],filters: FilterList,+ appliedBucketingDimension: AppliedBucketingDimension,) {const relationTables = new Set<string>();const actualTableName = this.actualTableName(view);+ // The bucket dimension is a separate first-class grouping axis. If an entity+ // bucket is relation-backed, include its declared relation without adding it to+ // appliedDimensions and inheriting regular-dimension behavior.+ if (+ appliedBucketingDimension.type === "entity" &&+ appliedBucketingDimension.dimension.relationTable+ ) {+ relationTables.add(appliedBucketingDimension.dimension.relationTable);+ }appliedDimensions.forEach((dimension) => {if (dimension.relationTable) {relationTables.add(dimension.relationTable);@@ -736,22 +848,16 @@ export class QueryBuilder {private buildTimeDimensionSql(view: ViewDeclarationType,- query: QueryType,+ appliedBucketingDimension: Extract<+ AppliedBucketingDimension,+ { type: "time" }+ >,wrapInAgg?: string,): string {- if (!query.timeDimension) {- return "";- }-const actualTableName = this.actualTableName(view);- const granularity =- query.timeDimension.granularity === "auto"- ? this.determineTimeGranularity(query.fromTimestamp, query.toTimestamp)- : query.timeDimension.granularity;-const timeDimensionSql = this.getTimeDimensionSql(`${actualTableName}.${view.timeDimension}`,- granularity,+ appliedBucketingDimension.granularity,);// Optionally wrap in aggregation function (e.g., "any" for two-level inner SELECT).@@ -771,10 +877,37 @@ export class QueryBuilder {return `${wrappedSql} as time_dimension`;}+ private buildBucketDimensionSql(+ view: ViewDeclarationType,+ appliedBucketingDimension: AppliedBucketingDimension,+ wrapInAgg?: string,+ ): string {+ switch (appliedBucketingDimension.type) {+ case "none":+ return "";+ case "time":+ return this.buildTimeDimensionSql(+ view,+ appliedBucketingDimension,+ wrapInAgg,+ );+ case "entity": {+ const sql = wrapInAgg+ ? `${wrapInAgg}(${appliedBucketingDimension.dimension.sql})`+ : appliedBucketingDimension.dimension.sql;+ return `${sql} as ${appliedBucketingDimension.bucketDimensionAlias}`;+ }+ default: {+ const exhaustiveCheck: never = appliedBucketingDimension;+ return exhaustiveCheck;+ }+ }+ }+private buildInnerDimensionsPart(appliedDimensions: AppliedDimensionType[],- query: QueryType,view: ViewDeclarationType,+ appliedBucketingDimension: AppliedBucketingDimension,) {let dimensions = "";@@ -807,10 +940,14 @@ export class QueryBuilder {.join(",\n")},`;}- // Add time dimension if specified - reuse unified builder with any() wrapper- const timeDimensionSql = this.buildTimeDimensionSql(view, query, "any");- if (timeDimensionSql) {- dimensions += `${timeDimensionSql},`;+ // Add the bucket dimension if specified - use any() for two-level inner SELECTs.+ const bucketDimensionSql = this.buildBucketDimensionSql(+ view,+ appliedBucketingDimension,+ "any",+ );+ if (bucketDimensionSql) {+ dimensions += `${bucketDimensionSql},`;}return dimensions;@@ -878,7 +1015,7 @@ export class QueryBuilder {private buildOuterDimensionsPart(appliedDimensions: AppliedDimensionType[],- hasTimeDimension: boolean,+ appliedBucketingDimension: AppliedBucketingDimension,) {let dimensions = "";@@ -892,9 +1029,8 @@ export class QueryBuilder {.join(",\n")},`;}- // Add time dimension if it exists- if (hasTimeDimension) {- dimensions += `time_dimension,`;+ if (appliedBucketingDimension.type !== "none") {+ dimensions += `${appliedBucketingDimension.bucketDimensionAlias},`;}return dimensions;@@ -908,7 +1044,7 @@ export class QueryBuilder {private buildGroupByClause(appliedDimensions: AppliedDimensionType[],- hasTimeDimension: boolean,+ appliedBucketingDimension: AppliedBucketingDimension,) {const dimensions = [];@@ -921,9 +1057,8 @@ export class QueryBuilder {);}- // Add time dimension if it exists- if (hasTimeDimension) {- dimensions.push("time_dimension");+ if (appliedBucketingDimension.type !== "none") {+ dimensions.push(appliedBucketingDimension.bucketDimensionAlias);}return dimensions.length > 0 ? `GROUP BY ${dimensions.join(",\n")}` : "";@@ -935,15 +1070,13 @@ export class QueryBuilder {* Only applied if timeDimension is used and no ORDER BY is specified.*/private buildWithFillClause(- timeDimension: {- granularity: z.infer<typeof granularities>;- } | null,+ appliedBucketingDimension: AppliedBucketingDimension,fromTimestamp: string,toTimestamp: string,orderBy: Array<{ field: string; direction: string }> | null,parameters: Record<string, unknown>,): string {- if (!timeDimension) {+ if (appliedBucketingDimension.type !== "time") {return "";}@@ -951,15 +1084,9 @@ export class QueryBuilder {return ""; // Skip WITH FILL if ORDER BY is specified}- // Determine granularity for WITH FILL if timeDimension is used- const granularity =- timeDimension.granularity === "auto"- ? this.determineTimeGranularity(fromTimestamp, toTimestamp)- : timeDimension.granularity;-// Calculate appropriate STEP for WITH FILL based on granularitylet step: string;- switch (granularity) {+ switch (appliedBucketingDimension.granularity) {case "minute":step = "INTERVAL 1 MINUTE";break;@@ -986,7 +1113,7 @@ export class QueryBuilder {new Date(toTimestamp),);- return ` WITH FILL FROM ${this.getTimeDimensionSql("{fillFromDate: DateTime64(3)}", granularity)} TO ${this.getTimeDimensionSql("{fillToDate: DateTime64(3)}", granularity)} STEP ${step}`;+ return ` WITH FILL FROM ${this.getTimeDimensionSql("{fillFromDate: DateTime64(3)}", appliedBucketingDimension.granularity)} TO ${this.getTimeDimensionSql("{fillToDate: DateTime64(3)}", appliedBucketingDimension.granularity)} STEP ${step}`;}/**@@ -1049,8 +1176,8 @@ export class QueryBuilder {private buildSingleLevelDimensionsPart(appliedDimensions: AppliedDimensionType[],- query: QueryType,view: ViewDeclarationType,+ appliedBucketingDimension: AppliedBucketingDimension,): string {let dimensionsPart = "";if (appliedDimensions.length > 0) {@@ -1069,10 +1196,13 @@ export class QueryBuilder {.join(",\n") + ",\n";}- // Reuse unified time dimension builder (no wrapper for single-level)- const timeDimensionSql = this.buildTimeDimensionSql(view, query);- if (timeDimensionSql) {- dimensionsPart += `${timeDimensionSql},\n`;+ // Reuse unified bucket dimension builder (no wrapper for single-level).+ const bucketDimensionSql = this.buildBucketDimensionSql(+ view,+ appliedBucketingDimension,+ );+ if (bucketDimensionSql) {+ dimensionsPart += `${bucketDimensionSql},\n`;}return dimensionsPart;@@ -1082,7 +1212,7 @@ export class QueryBuilder {view: ViewDeclarationType,appliedDimensions: AppliedDimensionType[],appliedMetrics: AppliedMetricType[],- query: QueryType,+ appliedBucketingDimension: AppliedBucketingDimension,fromClause: string,groupByClause: string,orderByClause: string,@@ -1092,8 +1222,8 @@ export class QueryBuilder {// Build dimensions using dedicated helperconst dimensionsPart = this.buildSingleLevelDimensionsPart(appliedDimensions,- query,view,+ appliedBucketingDimension,);// Build optimized metrics (strip templates, apply user aggregation)@@ -1117,12 +1247,17 @@ export class QueryBuilder {orderBy: Array<{ field: string; direction: string }> | null,appliedDimensions: AppliedDimensionType[],appliedMetrics: AppliedMetricType[],- hasTimeDimension: boolean,+ appliedBucketingDimension: AppliedBucketingDimension,): Array<{ field: string; direction: string }> {if (!orderBy || orderBy.length === 0) {// Default order: time dimension if available, otherwise first metric, otherwise first dimension- if (hasTimeDimension) {- return [{ field: "time_dimension", direction: "asc" }];+ if (appliedBucketingDimension.type === "time") {+ return [+ {+ field: appliedBucketingDimension.bucketDimensionAlias,+ direction: "asc",+ },+ ];} else if (appliedMetrics.length > 0) {const firstMetric = appliedMetrics[0];return [@@ -1131,6 +1266,13 @@ export class QueryBuilder {direction: "desc",},];+ } else if (appliedBucketingDimension.type !== "none") {+ return [+ {+ field: appliedBucketingDimension.bucketDimensionAlias,+ direction: "asc",+ },+ ];} else if (appliedDimensions.length > 0) {const firstDimension = appliedDimensions[0];return [@@ -1145,8 +1287,10 @@ export class QueryBuilder {// Validate that each orderBy field exists in dimensions or metricsreturn orderBy.map((item) => {- // Check if the field is a time dimension- if (hasTimeDimension && item.field === "time_dimension") {+ if (+ appliedBucketingDimension.type !== "none" &&+ item.field === appliedBucketingDimension.bucketDimensionAlias+ ) {return item;}@@ -1276,6 +1420,7 @@ export class QueryBuilder {// Map dimensions and metricsconst appliedDimensions = this.mapDimensions(query.dimensions, view);const appliedMetrics = this.mapMetrics(query.metrics, view);+ const appliedBucketingDimension = this.applyBucketingDimension(query, view);// Auto-include dimensions required by pairExpand-dependent measures.// e.g. costByType.requiresDimension = "costType": without that dimension the@@ -1321,6 +1466,7 @@ export class QueryBuilder {appliedDimensions,appliedMetrics,filterList,+ appliedBucketingDimension,);if (relationTables.size > 0) {const relationJoins = this.buildJoins(@@ -1394,7 +1540,7 @@ export class QueryBuilder {// Build GROUP BY clause (used by both single-level and two-level queries)const groupByClause = this.buildGroupByClause(appliedDimensions,- !!query.timeDimension,+ appliedBucketingDimension,);// Process and validate orderBy fields@@ -1402,7 +1548,7 @@ export class QueryBuilder {query.orderBy,appliedDimensions,appliedMetrics,- !!query.timeDimension,+ appliedBucketingDimension,);// Build ORDER BY clause@@ -1410,7 +1556,7 @@ export class QueryBuilder {// Build WITH FILL clause for time dimension to fill gaps in timeseriesconst withFillClause = this.buildWithFillClause(- query.timeDimension,+ appliedBucketingDimension,query.fromTimestamp,query.toTimestamp,query.orderBy,@@ -1428,7 +1574,7 @@ export class QueryBuilder {view,appliedDimensions,appliedMetrics,- query,+ appliedBucketingDimension,fromClause,groupByClause,orderByClause,@@ -1440,8 +1586,8 @@ export class QueryBuilder {// Build inner SELECT partsconst innerDimensionsPart = this.buildInnerDimensionsPart(appliedDimensions,- query,view,+ appliedBucketingDimension,);const innerMetricsPart = this.buildInnerMetricsPart(appliedMetrics);@@ -1457,7 +1603,7 @@ export class QueryBuilder {// Build outer SELECT partsconst outerDimensionsPart = this.buildOuterDimensionsPart(appliedDimensions,- !!query.timeDimension,+ appliedBucketingDimension,);const outerMetricsPart = this.buildOuterMetricsPart(appliedMetrics);diff --git a/packages/shared/src/features/query/types.ts b/packages/shared/src/features/query/types.tsindex 2919d32129..76c2821a31 100644--- a/packages/shared/src/features/query/types.ts+++ b/packages/shared/src/features/query/types.ts@@ -167,6 +167,16 @@ export const query = zgranularity: granularities,}).nullable(),+ // Entity dimension for bucketing by a categorical field (e.g., experimentName).+ // IMPORTANT: Unlike timeDimension which has implicit bucket limits (24 hours/day),+ // entityDimension has NO cardinality guarantee. Callers MUST filter the same+ // entity field in WHERE before GROUP BY runs (max ~50 values).+ // Without this pre-filtering, GROUP BY on high-cardinality columns will be slow/OOM.+ entityDimension: z+ .object({+ field: z.string(), // e.g., "experimentName"+ })+ .nullish(),fromTimestamp: stringDateTime,toTimestamp: stringDateTime,orderBy: z@@ -190,6 +200,13 @@ export const query = z(query) =>// Ensure fromTimestamp is before toTimestampnew Date(query.fromTimestamp) < new Date(query.toTimestamp),+ { message: "fromTimestamp must be before toTimestamp" },+ )+ .refine(+ (query) =>+ // timeDimension and entityDimension are mutually exclusive+ !(query.timeDimension && query.entityDimension),+ { message: "timeDimension and entityDimension are mutually exclusive" },);export const useEventsTableSchema = zdiff --git a/packages/shared/src/features/query/validateQuery.ts b/packages/shared/src/features/query/validateQuery.tsindex 449dc3626d..7846f5dd92 100644--- a/packages/shared/src/features/query/validateQuery.ts+++ b/packages/shared/src/features/query/validateQuery.ts@@ -9,6 +9,34 @@ export type QueryValidationResult =| { valid: true }| { valid: false; reason: string };+const MAX_ENTITY_DIMENSION_BOUND_VALUES = 50;++function hasSameFieldEntityDimensionBound(+ filters: QueryType["filters"],+ field: string,+): boolean {+ return filters.some((filter) => {+ if (filter.column !== field) {+ return false;+ }++ if (filter.type === "string") {+ return filter.operator === "=" && filter.value.length > 0;+ }++ if (filter.type === "stringOptions" || filter.type === "categoryOptions") {+ return (+ filter.operator === "any of" &&+ filter.value.length > 0 &&+ filter.value.length <= MAX_ENTITY_DIMENSION_BOUND_VALUES &&+ filter.value.every((value) => value.length > 0)+ );+ }++ return false;+ });+}+/*** Gets the list of high cardinality dimension fields used in the query.*@@ -58,6 +86,39 @@ function findMeasureInOrderByField(return null;}+function validateEntityDimension(+ query: QueryType,+ version: ViewVersion,+): QueryValidationResult {+ const view = getViewDeclaration(query.view, version);++ const field = query.entityDimension!.field;+ const dimension = view.dimensions[field];++ if (+ !dimension ||+ dimension.explodeArray ||+ dimension.pairExpand ||+ dimension.aggregationFunction+ )+ return {+ valid: false,+ reason: `Invalid entity dimension: ${field}. Entity dimensions must be scalar view dimensions.`,+ };++ if (+ dimension.highCardinality &&+ !hasSameFieldEntityDimensionBound(query.filters, field)+ ) {+ return {+ valid: false,+ reason: `High cardinality dimension '${field}' must be filtered with a finite positive filter.`,+ };+ }++ return { valid: true };+}+/*** Validates a query for safety before execution.* Performs sanity checks for high cardinality dimension validation.@@ -67,6 +128,8 @@ function findMeasureInOrderByField(* 2. config.row_limit (or chartConfig.row_limit) is explicitly specified (LIMIT)* 3. orderBy with direction 'desc' on a measure field is specified (for top-N queries)*+ * High cardinality entityDimension can also be allowed by a finite positive+ * same-field filter, which bounds the grouped keyspace before GROUP BY.* @param query - The query configuration (with original config, before defaults applied)* @param version - The view version (v1 or v2)* @returns Validation result: { valid: true } or { valid: false, reason: string }@@ -75,12 +138,33 @@ export function validateQuery(query: QueryType,version: ViewVersion,): QueryValidationResult {- // Only enforce validation for v2 queries+ if (query.timeDimension && query.entityDimension) {+ return {+ valid: false,+ reason: "timeDimension and entityDimension are mutually exclusive",+ };+ }++ if (query.entityDimension && version !== "v2") {+ return {+ valid: false,+ reason: "entityDimension is only supported for v2 queries",+ };+ }++ // Only enforce remaining high-cardinality validation for v2 queries.if (version !== "v2") {return { valid: true };}- // 1. Check for high cardinality dimensions+ if (query.entityDimension) {+ const validation = validateEntityDimension(query, version);+ if (!validation.valid) {+ return validation;+ }+ }++ // 1. Check for high cardinality dimensions, including entityDimension.const highCardDims = getHighCardinalityDimensions(query, version);if (highCardDims.length === 0) {@@ -97,6 +181,14 @@ export function validateQuery(};}+ // An entity-dimension query with additional high cardinality dimensions produces unbounded result sets and cannot be meaningfully limited with row_limit.+ if (query.entityDimension) {+ return {+ valid: false,+ reason: `High cardinality dimension(s) '${highCardDims.join(", ")}' cannot be used with entityDimension. Entity-dimension queries with additional high cardinality dimensions produce unbounded result sets.`,+ };+ }+// 3. Validate required conditions for high cardinality// Support both public API "config" and internal "chartConfig" field namesconst chartConfig =diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.tsindex cdf26f7d5a..f1d875679a 100644--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts@@ -10,6 +10,7 @@ import {ExperimentsAggregationQueryBuilder,type CTEWithSchema,} from "./event-query-builder";+import { AGGREGATABLE_SCORE_TYPES } from "../../../domain/scores";/*** Lightweight trace metadata query: one row per trace with name, user_id, tags.@@ -370,6 +371,54 @@ export const eventsExperimentTraceIds = (.selectRaw("e.project_id", "e.experiment_id", "e.trace_id").limitBy("e.trace_id");+export const buildScoreRowsCTE = (params: BaseScoresParams): CTEWithSchema => {+ const queryParams: Record<string, any> = {+ projectId: params.projectId,+ dataTypes: AGGREGATABLE_SCORE_TYPES,+ };++ if (params.startTimeFrom) {+ queryParams.startTimeFrom = params.startTimeFrom;+ }++ const isTraceLevel = params.level === "trace";+ const observationFilter = isTraceLevel+ ? "AND observation_id IS NULL"+ : "AND observation_id IS NOT NULL";++ const query = `+ SELECT+ project_id,+ trace_id,+ observation_id,+ name,+ source,+ data_type,+ string_value+ FROM scores s+ WHERE+ project_id = {projectId: String}+ AND trace_id != ''+ ${observationFilter}+ AND data_type IN ({dataTypes: Array(String)})+ ${params.startTimeFrom ? `AND timestamp >= {startTimeFrom: DateTime64(3)}` : ""}+ `.trim();++ return {+ query,+ params: queryParams,+ schema: [+ "project_id",+ "trace_id",+ "observation_id",+ "name",+ "source",+ "data_type",+ "string_value",+ ],+ };+};+export const buildScoresCTE = (params: BaseScoresParams): CTEWithSchema => {const queryParams: Record<string, any> = {projectId: params.projectId,diff --git a/packages/shared/src/server/repositories/experiments.ts b/packages/shared/src/server/repositories/experiments.tsindex 82d7fbe396..0d1e7d2160 100644--- a/packages/shared/src/server/repositories/experiments.ts+++ b/packages/shared/src/server/repositories/experiments.ts@@ -1,4 +1,5 @@import { env } from "../../env";+import { type ScoreSourceType } from "../../domain";import { type OrderByState } from "../../interfaces/orderBy";import { type FilterState } from "../../types";import { measureAndReturn } from "../clickhouse/measureAndReturn";@@ -13,6 +14,7 @@ import {} from "../queries";import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";import {+ buildScoreRowsCTE,buildScoresCTE,eventsExperimentsRootSpans,eventsExperiments,@@ -476,6 +478,334 @@ export const getExperimentItemsCountFromEvents = async (return rows.length > 0 ? Number(rows[0].count) : 0;};+type ExperimentItemsFilterOptionsInput = {+ projectId: string;+ experimentIds: string[];+};++type ExperimentScoreOptionsInput = ExperimentItemsFilterOptionsInput;++// Whitelist of score data types to include+const ALLOWED_SCORE_DATA_TYPES = ["NUMERIC", "CATEGORICAL", "BOOLEAN"] as const;+type ExperimentChartableScoreDataType =+ (typeof ALLOWED_SCORE_DATA_TYPES)[number];++type ScoreFilterOptionsRow = {+ name: string;+ source: ScoreSourceType;+ data_type: ExperimentChartableScoreDataType;+ values: string[];+};++const SCORE_FILTER_OPTIONS_LIMIT = 1000;+const SCORE_CATEGORICAL_VALUE_LIMIT = 20;++/**+ * Build query for experiment-run-level scores (scores with dataset_run_id matching experiment IDs).+ * These are scores directly attached to the experiment/dataset run, not to traces or observations.+ */+const buildExperimentRunScoreFilterOptionsQuery = (params: {+ projectId: string;+ experimentIds: string[];+}): { query: string; params: Record<string, unknown> } => {+ const { projectId, experimentIds } = params;++ // Simple query on scores table filtering by dataset_run_id+ const query = `+ SELECT+ name AS name,+ source AS source,+ data_type AS data_type,+ groupUniqArrayIf(${SCORE_CATEGORICAL_VALUE_LIMIT})(string_value, data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS values+ FROM scores+ WHERE project_id = {projectId: String}+ AND dataset_run_id IN ({experimentIds: Array(String)})+ AND data_type IN ({allowedDataTypes: Array(String)})+ GROUP BY name, data_type, source+ ORDER BY name ASC+ LIMIT ${SCORE_FILTER_OPTIONS_LIMIT}+ `;++ return {+ query,+ params: {+ projectId,+ experimentIds,+ allowedDataTypes: ALLOWED_SCORE_DATA_TYPES,+ },+ };+};++const buildScoreFilterOptionsQuery = (params: {+ projectId: string;+ experimentIds: string[];+ level: "observation" | "trace";+}): { query: string; params: Record<string, unknown> } => {+ const { projectId, experimentIds, level } = params;++ // Build experiment events CTE using existing fragment+ const experimentEventsCTE = eventsExperimentsRootSpans({+ projectId,+ experimentIds,+ })+ .selectRaw("e.project_id", "e.trace_id", "e.span_id")+ .limitBy("e.project_id", "e.trace_id", "e.span_id")+ .buildWithParams();++ // Build unaggregated score rows so the experiment join happens before grouping+ const scoreRowsCTE = buildScoreRowsCTE({+ projectId,+ level,+ });++ // Build the join condition based on level+ const joinCondition =+ level === "trace"+ ? "ON s.project_id = ee.project_id AND s.trace_id = ee.trace_id"+ : "ON s.project_id = ee.project_id AND s.trace_id = ee.trace_id AND s.observation_id = ee.span_id";++ // Compose the full query using CTEQueryBuilder+ // Excludes CORRECTION scores by whitelisting allowed data types+ const queryBuilder = new CTEQueryBuilder()+ .withCTE("experiment_events", {+ ...experimentEventsCTE,+ schema: ["project_id", "trace_id", "span_id"],+ })+ .withCTE("score_rows", scoreRowsCTE)+ .from("score_rows", "s")+ .innerJoin("experiment_events", "ee", joinCondition)+ .select(+ "s.name AS name",+ "s.data_type AS data_type",+ "s.source AS source",+ `groupUniqArrayIf(${SCORE_CATEGORICAL_VALUE_LIMIT})(s.string_value, s.data_type = 'CATEGORICAL' AND notEmpty(s.string_value)) AS values`,+ )+ .groupBy("s.name", "s.data_type", "s.source")+ .orderBy("ORDER BY s.name ASC")+ .limit(SCORE_FILTER_OPTIONS_LIMIT);++ return queryBuilder.buildWithParams();+};++export type ScoreColumnDefinition = {+ name: string;+ dataType: "NUMERIC" | "BOOLEAN" | "CATEGORICAL";+ source: string;+};++type ProcessedScoreFilterOptions = {+ numeric: string[];+ categorical: Array<{ label: string; values: string[] }>;+ scoreColumns: ScoreColumnDefinition[];+};++const processScoreFilterOptionsResults = (+ rows: ScoreFilterOptionsRow[],+): ProcessedScoreFilterOptions => {+ const numeric = new Set<string>();+ const categorical = new Map<string, Set<string>>();+ const scoreColumns: ScoreColumnDefinition[] = [];++ for (const row of rows) {+ // Always add to scoreColumns (unique by name+source+data_type combination)+ scoreColumns.push({+ name: row.name,+ dataType: row.data_type as "NUMERIC" | "BOOLEAN" | "CATEGORICAL",+ source: row.source,+ });++ if (row.data_type === "NUMERIC" || row.data_type === "BOOLEAN") {+ numeric.add(row.name);+ } else if (row.data_type === "CATEGORICAL") {+ const existingValues = categorical.get(row.name) ?? new Set<string>();+ row.values.forEach((value) => existingValues.add(value));+ categorical.set(row.name, existingValues);+ }+ }++ return {+ numeric: Array.from(numeric),+ categorical: Array.from(categorical.entries()).map(([label, values]) => ({+ label,+ values: Array.from(values),+ })),+ scoreColumns,+ };+};++const emptyScoreFilterOptions = (): ProcessedScoreFilterOptions => ({+ numeric: [],+ categorical: [],+ scoreColumns: [],+});++type ExperimentItemScoreOptionsByLevel = {+ observation: ProcessedScoreFilterOptions;+ trace: ProcessedScoreFilterOptions;+};++type ExperimentScoreOptionsByLevel = {+ observation: ProcessedScoreFilterOptions;+ experiment: ProcessedScoreFilterOptions;+};++const getExperimentItemScoreOptionsByLevel = async ({+ projectId,+ experimentIds,+}: ExperimentItemsFilterOptionsInput): Promise<ExperimentItemScoreOptionsByLevel> => {+ const uniqueExperimentIds = Array.from(new Set(experimentIds));++ if (uniqueExperimentIds.length === 0) {+ return {+ observation: emptyScoreFilterOptions(),+ trace: emptyScoreFilterOptions(),+ };+ }++ const traceQuery = buildScoreFilterOptionsQuery({+ projectId,+ experimentIds: uniqueExperimentIds,+ level: "trace",+ });++ const obsQuery = buildScoreFilterOptionsQuery({+ projectId,+ experimentIds: uniqueExperimentIds,+ level: "observation",+ });++ const [traceResults, obsResults] = await Promise.all([+ queryClickhouse<ScoreFilterOptionsRow>({+ query: traceQuery.query,+ params: traceQuery.params,+ tags: {+ feature: "experiments",+ type: "filter-options",+ kind: "trace-scores",+ projectId,+ },+ preferredClickhouseService: "ReadOnly",+ }),+ queryClickhouse<ScoreFilterOptionsRow>({+ query: obsQuery.query,+ params: obsQuery.params,+ tags: {+ feature: "experiments",+ type: "filter-options",+ kind: "observation-scores",+ projectId,+ },+ preferredClickhouseService: "ReadOnly",+ }),+ ]);++ return {+ observation: processScoreFilterOptionsResults(obsResults),+ trace: processScoreFilterOptionsResults(traceResults),+ };+};++export const getExperimentItemsFilterOptions = async (+ props: ExperimentItemsFilterOptionsInput,+): Promise<{+ obs_scores_avg: string[];+ obs_score_categories: Array<{ label: string; values: string[] }>;+ obs_score_columns: ScoreColumnDefinition[];+ trace_scores_avg: string[];+ trace_score_categories: Array<{ label: string; values: string[] }>;+ trace_score_columns: ScoreColumnDefinition[];+}> => {+ const { observation, trace } =+ await getExperimentItemScoreOptionsByLevel(props);++ return {+ obs_scores_avg: observation.numeric,+ obs_score_categories: observation.categorical,+ obs_score_columns: observation.scoreColumns,+ trace_scores_avg: trace.numeric,+ trace_score_categories: trace.categorical,+ trace_score_columns: trace.scoreColumns,+ };+};++const getExperimentScoreOptionsByLevel = async ({+ projectId,+ experimentIds,+}: ExperimentScoreOptionsInput): Promise<ExperimentScoreOptionsByLevel> => {+ const uniqueExperimentIds = Array.from(new Set(experimentIds));++ if (uniqueExperimentIds.length === 0) {+ return {+ observation: emptyScoreFilterOptions(),+ experiment: emptyScoreFilterOptions(),+ };+ }++ const obsQuery = buildScoreFilterOptionsQuery({+ projectId,+ experimentIds: uniqueExperimentIds,+ level: "observation",+ });++ const runQuery = buildExperimentRunScoreFilterOptionsQuery({+ projectId,+ experimentIds: uniqueExperimentIds,+ });++ const [obsResults, runResults] = await Promise.all([+ queryClickhouse<ScoreFilterOptionsRow>({+ query: obsQuery.query,+ params: obsQuery.params,+ tags: {+ feature: "experiments",+ type: "filter-options",+ kind: "observation-scores",+ projectId,+ },+ preferredClickhouseService: "ReadOnly",+ }),+ queryClickhouse<ScoreFilterOptionsRow>({+ query: runQuery.query,+ params: runQuery.params,+ tags: {+ feature: "experiments",+ type: "filter-options",+ kind: "run-scores",+ projectId,+ },+ preferredClickhouseService: "ReadOnly",+ }),+ ]);++ return {+ observation: processScoreFilterOptionsResults(obsResults),+ experiment: processScoreFilterOptionsResults(runResults),+ };+};++export const getExperimentScoreOptions = async (+ props: ExperimentScoreOptionsInput,+): Promise<{+ obs_scores_avg: string[];+ obs_score_categories: Array<{ label: string; values: string[] }>;+ obs_score_columns: ScoreColumnDefinition[];+ experiment_scores_avg: string[];+ experiment_score_categories: Array<{ label: string; values: string[] }>;+ experiment_score_columns: ScoreColumnDefinition[];+}> => {+ const { observation, experiment } =+ await getExperimentScoreOptionsByLevel(props);++ return {+ obs_scores_avg: observation.numeric,+ obs_score_categories: observation.categorical,+ obs_score_columns: observation.scoreColumns,+ experiment_scores_avg: experiment.numeric,+ experiment_score_categories: experiment.categorical,+ experiment_score_columns: experiment.scoreColumns,+ };+};+type FilterByExperiment = {experimentId: string;filters: FilterState;diff --git a/web/src/__tests__/server/queryBuilder.servertest.ts b/web/src/__tests__/server/queryBuilder.servertest.tsindex 6c4b255d25..ebff56477b 100644--- a/web/src/__tests__/server/queryBuilder.servertest.ts+++ b/web/src/__tests__/server/queryBuilder.servertest.ts@@ -4232,6 +4232,126 @@ describe("validateQuery", () => {);});+ it("should return valid when high cardinality entityDimension has same-field bound", () => {+ const query: QueryType = {+ ...baseQuery,+ entityDimension: { field: "experimentName" },+ filters: [+ {+ column: "experimentName",+ operator: "any of",+ value: ["experiment-a"],+ type: "stringOptions",+ },+ ],+ };++ const result = validateQuery(query, "v2");++ expect(result).toEqual({ valid: true });+ });++ it("should return invalid when high cardinality entityDimension is unbounded", () => {+ const query: QueryType = {+ ...baseQuery,+ entityDimension: { field: "experimentName" },+ };++ const result = validateQuery(query, "v2");++ expect(result.valid).toBe(false);+ expect((result as { valid: false; reason: string }).reason).toContain(+ "High cardinality dimension 'experimentName'",+ );+ expect((result as { valid: false; reason: string }).reason).toContain(+ "finite positive filter",+ );+ });++ it("should return invalid when high cardinality entityDimension has only wrong-field bound", () => {+ const query: QueryType = {+ ...baseQuery,+ entityDimension: { field: "experimentName" },+ filters: [+ {+ column: "experimentId",+ operator: "any of",+ value: ["experiment-id-a"],+ type: "stringOptions",+ },+ ],+ };++ const result = validateQuery(query, "v2");++ expect(result.valid).toBe(false);+ expect((result as { valid: false; reason: string }).reason).toContain(+ "High cardinality dimension 'experimentName'",+ );+ expect((result as { valid: false; reason: string }).reason).toContain(+ "finite positive filter",+ );+ });++ it("should return invalid when high cardinality entityDimension only has top-N protection", () => {+ const query: QueryType = {+ ...baseQuery,+ entityDimension: { field: "experimentName" },+ chartConfig: { type: "table", row_limit: 10 },+ orderBy: [{ field: "sum_totalCost", direction: "desc" }],+ };++ const result = validateQuery(query, "v2");++ expect(result.valid).toBe(false);+ expect((result as { valid: false; reason: string }).reason).toContain(+ "High cardinality dimension 'experimentName'",+ );+ expect((result as { valid: false; reason: string }).reason).toContain(+ "finite positive filter",+ );+ });++ it("should return invalid when entityDimension is used with v1", () => {+ const query: QueryType = {+ ...baseQuery,+ entityDimension: { field: "name" },+ };++ const result = validateQuery(query, "v1");++ expect(result.valid).toBe(false);+ expect((result as { valid: false; reason: string }).reason).toContain(+ "entityDimension is only supported for v2 queries",+ );+ });++ it("should return invalid when high cardinality regular dimension is used with entityDimension", () => {+ const query: QueryType = {+ ...baseQuery,+ dimensions: [{ field: "traceId" }],+ entityDimension: { field: "experimentName" },+ filters: [+ {+ column: "experimentName",+ operator: "any of",+ value: ["experiment-a"],+ type: "stringOptions",+ },+ ],+ };++ const result = validateQuery(query, "v2");++ expect(result.valid).toBe(false);+ expect((result as { valid: false; reason: string }).reason).toContain(+ "High cardinality dimension(s) 'traceId'",+ );+ expect((result as { valid: false; reason: string }).reason).toContain(+ "entityDimension",+ );+ });+it("should return invalid when high cardinality dimension is used without ORDER DESC", () => {const query: QueryType = {...baseQuery,@@ -4403,6 +4523,143 @@ describe("getValidAggregationsForMeasureType", () => {});describe("query builder measure-aggregation validation", () => {+ it("should build base-table entity dimension queries without time-series SQL", async () => {+ const query: QueryType = {+ view: "observations",+ dimensions: [],+ metrics: [{ measure: "totalCost", aggregation: "sum" }],+ filters: [+ {+ column: "experimentName",+ operator: "any of",+ value: ["experiment-a"],+ type: "stringOptions",+ },+ {+ column: "experimentId",+ operator: "any of",+ value: ["experiment-id-a"],+ type: "stringOptions",+ },+ ],+ timeDimension: null,+ entityDimension: { field: "experimentName" },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: [{ field: "sum_totalCost", direction: "asc" }],+ };++ const queryBuilder = new QueryBuilder(undefined, "v2");+ const result = await queryBuilder.build(query, randomUUID());++ expect(result.query).toContain("as entity_dimension");+ expect(result.query).toContain("GROUP BY entity_dimension");+ expect(result.query).not.toContain("time_dimension");+ expect(result.query).not.toContain("WITH FILL");+ });++ it("should include declared relation for relation-backed entity dimensions", async () => {+ const query: QueryType = {+ view: "scores-numeric",+ dimensions: [],+ metrics: [{ measure: "value", aggregation: "avg" }],+ filters: [],+ timeDimension: null,+ entityDimension: { field: "experimentName" },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: [{ field: "avg_value", direction: "desc" }],+ };++ const queryBuilder = new QueryBuilder(undefined, "v2");+ const result = await queryBuilder.build(query, randomUUID());++ expect(result.query).toContain(+ "INNER JOIN events_core AS events_observations",+ );+ expect(result.query).toContain("events_observations.experiment_name");+ expect(result.query).toContain("as entity_dimension");+ expect(result.query).toContain("GROUP BY entity_dimension");+ });++ it("should build run-level score entity queries without joining events", async () => {+ const query: QueryType = {+ view: "scores-numeric",+ dimensions: [],+ metrics: [{ measure: "value", aggregation: "avg" }],+ filters: [+ {+ column: "datasetRunId",+ operator: "is not null",+ value: "",+ type: "null",+ },+ {+ column: "name",+ operator: "=",+ value: "run_accuracy",+ type: "string",+ },+ {+ column: "datasetRunId",+ operator: "any of",+ value: ["experiment-1", "experiment-2"],+ type: "stringOptions",+ },+ ],+ timeDimension: null,+ entityDimension: { field: "datasetRunId" },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: [{ field: "avg_value", direction: "desc" }],+ };++ const queryBuilder = new QueryBuilder(undefined, "v2");+ const result = await queryBuilder.build(query, randomUUID());++ expect(result.query).toContain("scores.dataset_run_id");+ expect(result.query).toContain("entity_dimension");+ expect(result.query).not.toContain("JOIN events_core");+ });++ it("should reject queries with both timeDimension and entityDimension", async () => {+ const query: QueryType = {+ view: "observations",+ dimensions: [],+ metrics: [{ measure: "totalCost", aggregation: "sum" }],+ filters: [],+ timeDimension: { granularity: "day" },+ entityDimension: { field: "experimentName" },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ };++ const queryBuilder = new QueryBuilder(undefined, "v2");+ await expect(queryBuilder.build(query, randomUUID())).rejects.toThrow(+ "timeDimension and entityDimension are mutually exclusive",+ );+ });++ it("should reject v1 entityDimension queries at query-builder runtime", async () => {+ const query: QueryType = {+ view: "observations",+ dimensions: [],+ metrics: [{ measure: "totalCost", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ entityDimension: { field: "name" },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ };++ const queryBuilder = new QueryBuilder(undefined, "v1");+ await expect(queryBuilder.build(query, randomUUID())).rejects.toThrow(+ "entityDimension is only supported for v2 queries",+ );+ });+it("should reject invalid aggregation for string measure", async () => {const query: QueryType = {view: "observations",diff --git a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts b/web/src/__tests__/server/repositories/experiment-repository.servertest.tsindex 040a46fb23..281d84a54f 100644--- a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/experiment-repository.servertest.ts@@ -6,7 +6,10 @@ import {getExperimentsCountFromEvents,getExperimentsFromEvents,getExperimentMetricsFromEvents,+ getExperimentItemsFilterOptions,+ getExperimentScoreOptions,createTraceScore,+ createDatasetRunScore,createScoresCh,} from "@langfuse/shared/src/server";@@ -1148,4 +1151,418 @@ describe("Clickhouse Experiment Repository Test", () => {expect(excludedExperiment).toBeUndefined();});});++ maybe("getExperimentItemsFilterOptions", () => {+ it("should return empty arrays when no experiment IDs provided", async () => {+ const result = await getExperimentItemsFilterOptions({+ projectId,+ experimentIds: [],+ });++ expect(result).toEqual({+ obs_scores_avg: [],+ obs_score_categories: [],+ obs_score_columns: [],+ trace_scores_avg: [],+ trace_score_categories: [],+ trace_score_columns: [],+ });+ });++ it("should return empty arrays for non-existent experiments", async () => {+ const result = await getExperimentItemsFilterOptions({+ projectId,+ experimentIds: [randomUUID()],+ });++ expect(result).toEqual({+ obs_scores_avg: [],+ obs_score_categories: [],+ obs_score_columns: [],+ trace_scores_avg: [],+ trace_score_categories: [],+ trace_score_columns: [],+ });+ });++ it("should return trace-level score filter options", async () => {+ const experimentId = randomUUID();+ const experimentName = "filter-options-trace-" + randomUUID();+ const datasetId = randomUUID();+ const traceId = randomUUID();+ const rootSpanId = randomUUID();++ const now = new Date().getTime();++ // Create experiment event+ const event = createEvent({+ id: randomUUID(),+ span_id: rootSpanId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "test-generation",+ experiment_id: experimentId,+ experiment_name: experimentName,+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_dataset_id: datasetId,+ experiment_item_id: randomUUID(),+ experiment_item_version: null,+ experiment_item_root_span_id: rootSpanId,+ start_time: now * 1000,+ });++ await createEventsCh([event]);++ // Create trace-level numeric score+ const numericScore = createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: null,+ name: "accuracy",+ value: 0.85,+ source: "API",+ data_type: "NUMERIC",+ });++ // Create trace-level categorical score+ const categoricalScore = createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: null,+ name: "quality",+ value: null,+ string_value: "good",+ source: "API",+ data_type: "CATEGORICAL",+ });++ await createScoresCh([numericScore, categoricalScore]);++ const result = await getExperimentItemsFilterOptions({+ projectId,+ experimentIds: [experimentId],+ });++ expect(result.trace_scores_avg).toContain("accuracy");+ expect(result.trace_score_categories).toContainEqual({+ label: "quality",+ values: expect.arrayContaining(["good"]),+ });+ });++ it("should return observation-level score filter options", async () => {+ const experimentId = randomUUID();+ const experimentName = "filter-options-obs-" + randomUUID();+ const datasetId = randomUUID();+ const traceId = randomUUID();+ const rootSpanId = randomUUID();++ const now = new Date().getTime();++ // Create experiment event+ const event = createEvent({+ id: randomUUID(),+ span_id: rootSpanId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "test-generation",+ experiment_id: experimentId,+ experiment_name: experimentName,+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_dataset_id: datasetId,+ experiment_item_id: randomUUID(),+ experiment_item_version: null,+ experiment_item_root_span_id: rootSpanId,+ start_time: now * 1000,+ });++ await createEventsCh([event]);++ // Create observation-level numeric score (on the root span)+ const numericScore = createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: rootSpanId,+ name: "relevance",+ value: 0.9,+ source: "API",+ data_type: "NUMERIC",+ });++ // Create observation-level categorical score+ const categoricalScore = createTraceScore({+ project_id: projectId,+ trace_id: traceId,+ observation_id: rootSpanId,+ name: "sentiment",+ value: null,+ string_value: "positive",+ source: "API",+ data_type: "CATEGORICAL",+ });++ await createScoresCh([numericScore, categoricalScore]);++ const result = await getExperimentItemsFilterOptions({+ projectId,+ experimentIds: [experimentId],+ });++ expect(result.obs_scores_avg).toContain("relevance");+ expect(result.obs_score_categories).toContainEqual({+ label: "sentiment",+ values: expect.arrayContaining(["positive"]),+ });+ });++ it("should return both trace and observation scores for multiple experiments", async () => {+ const experimentId1 = randomUUID();+ const experimentId2 = randomUUID();+ const datasetId = randomUUID();++ const now = new Date().getTime();++ // Experiment 1+ const traceId1 = randomUUID();+ const rootSpanId1 = randomUUID();+ const event1 = createEvent({+ id: randomUUID(),+ span_id: rootSpanId1,+ project_id: projectId,+ trace_id: traceId1,+ type: "GENERATION",+ name: "test-generation",+ experiment_id: experimentId1,+ experiment_name: "exp1-" + randomUUID(),+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_dataset_id: datasetId,+ experiment_item_id: randomUUID(),+ experiment_item_version: null,+ experiment_item_root_span_id: rootSpanId1,+ start_time: now * 1000,+ });++ // Experiment 2+ const traceId2 = randomUUID();+ const rootSpanId2 = randomUUID();+ const event2 = createEvent({+ id: randomUUID(),+ span_id: rootSpanId2,+ project_id: projectId,+ trace_id: traceId2,+ type: "GENERATION",+ name: "test-generation",+ experiment_id: experimentId2,+ experiment_name: "exp2-" + randomUUID(),+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_dataset_id: datasetId,+ experiment_item_id: randomUUID(),+ experiment_item_version: null,+ experiment_item_root_span_id: rootSpanId2,+ start_time: now * 1000,+ });++ await createEventsCh([event1, event2]);++ // Scores for experiment 1+ const traceScore1 = createTraceScore({+ project_id: projectId,+ trace_id: traceId1,+ observation_id: null,+ name: "score_from_exp1",+ value: 0.7,+ source: "API",+ data_type: "NUMERIC",+ });++ // Scores for experiment 2+ const obsScore2 = createTraceScore({+ project_id: projectId,+ trace_id: traceId2,+ observation_id: rootSpanId2,+ name: "score_from_exp2",+ value: 0.8,+ source: "API",+ data_type: "NUMERIC",+ });++ await createScoresCh([traceScore1, obsScore2]);++ const result = await getExperimentItemsFilterOptions({+ projectId,+ experimentIds: [experimentId1, experimentId2],+ });++ // Should include scores from both experiments+ expect(result.trace_scores_avg).toContain("score_from_exp1");+ expect(result.obs_scores_avg).toContain("score_from_exp2");+ });++ it("should aggregate categorical score values across experiments", async () => {+ const experimentId1 = randomUUID();+ const experimentId2 = randomUUID();+ const datasetId = randomUUID();++ const now = new Date().getTime();++ // Experiment 1+ const traceId1 = randomUUID();+ const rootSpanId1 = randomUUID();+ const event1 = createEvent({+ id: randomUUID(),+ span_id: rootSpanId1,+ project_id: projectId,+ trace_id: traceId1,+ type: "GENERATION",+ name: "test-generation",+ experiment_id: experimentId1,+ experiment_name: "exp1-" + randomUUID(),+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_dataset_id: datasetId,+ experiment_item_id: randomUUID(),+ experiment_item_version: null,+ experiment_item_root_span_id: rootSpanId1,+ start_time: now * 1000,+ });++ // Experiment 2+ const traceId2 = randomUUID();+ const rootSpanId2 = randomUUID();+ const event2 = createEvent({+ id: randomUUID(),+ span_id: rootSpanId2,+ project_id: projectId,+ trace_id: traceId2,+ type: "GENERATION",+ name: "test-generation",+ experiment_id: experimentId2,+ experiment_name: "exp2-" + randomUUID(),+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_dataset_id: datasetId,+ experiment_item_id: randomUUID(),+ experiment_item_version: null,+ experiment_item_root_span_id: rootSpanId2,+ start_time: now * 1000,+ });++ await createEventsCh([event1, event2]);++ // Same categorical score name with different values+ const catScore1 = createTraceScore({+ project_id: projectId,+ trace_id: traceId1,+ observation_id: null,+ name: "rating",+ value: null,+ string_value: "excellent",+ source: "API",+ data_type: "CATEGORICAL",+ });++ const catScore2 = createTraceScore({+ project_id: projectId,+ trace_id: traceId2,+ observation_id: null,+ name: "rating",+ value: null,+ string_value: "poor",+ source: "API",+ data_type: "CATEGORICAL",+ });++ await createScoresCh([catScore1, catScore2]);++ const result = await getExperimentItemsFilterOptions({+ projectId,+ experimentIds: [experimentId1, experimentId2],+ });++ // Should aggregate values from both experiments+ const ratingCategory = result.trace_score_categories.find(+ (c) => c.label === "rating",+ );+ expect(ratingCategory).toBeDefined();+ expect(ratingCategory?.values).toContain("excellent");+ expect(ratingCategory?.values).toContain("poor");+ });+ });++ maybe("getExperimentScoreOptions", () => {+ it("should return empty arrays when no experiment IDs provided", async () => {+ const result = await getExperimentScoreOptions({+ projectId,+ experimentIds: [],+ });++ expect(result).toEqual({+ obs_scores_avg: [],+ obs_score_categories: [],+ obs_score_columns: [],+ experiment_scores_avg: [],+ experiment_score_categories: [],+ experiment_score_columns: [],+ });+ expect(result).not.toHaveProperty("trace_scores_avg");+ expect(result).not.toHaveProperty("trace_score_categories");+ expect(result).not.toHaveProperty("trace_score_columns");+ });++ it("should return experiment-run score filter options", async () => {+ const experimentId = randomUUID();++ const numericScore = createDatasetRunScore({+ project_id: projectId,+ dataset_run_id: experimentId,+ name: "run_accuracy",+ value: 0.91,+ source: "API",+ data_type: "NUMERIC",+ });++ const categoricalScore = createDatasetRunScore({+ project_id: projectId,+ dataset_run_id: experimentId,+ name: "run_grade",+ value: null,+ string_value: "pass",+ source: "API",+ data_type: "CATEGORICAL",+ });++ await createScoresCh([numericScore, categoricalScore]);++ const result = await getExperimentScoreOptions({+ projectId,+ experimentIds: [experimentId],+ });++ expect(result.experiment_scores_avg).toContain("run_accuracy");+ expect(result.experiment_score_categories).toContainEqual({+ label: "run_grade",+ values: expect.arrayContaining(["pass"]),+ });+ expect(result.experiment_score_columns).toEqual(+ expect.arrayContaining([+ {+ name: "run_accuracy",+ dataType: "NUMERIC",+ source: "API",+ },+ {+ name: "run_grade",+ dataType: "CATEGORICAL",+ source: "API",+ },+ ]),+ );+ });+ });});diff --git a/web/src/features/experiments/components/ExperimentChartSlot.tsx b/web/src/features/experiments/components/ExperimentChartSlot.tsxnew file mode 100644index 0000000000..1b47a0ac48--- /dev/null+++ b/web/src/features/experiments/components/ExperimentChartSlot.tsx@@ -0,0 +1,230 @@+import { useMemo } from "react";+import { X } from "lucide-react";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { Button } from "@/src/components/ui/button";+import { WidgetContent } from "@/src/features/widgets/components/InlineWidget";+import { type QueryType } from "@langfuse/shared/query";+import type { MetricOption } from "../types/charts";+import { Skeleton } from "@/src/components/ui/skeleton";+import { buildWidgetConfigFromId } from "@/src/features/experiments/utils/charts";+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";++type ExperimentChartSlotProps = {+ chartIndex: number;+ selectedMetricId: string;+ onMetricChange: (metricId: string) => void;+ onRemove: () => void;+ canDelete: boolean;+ availableMetricOptions: MetricOption[];+ projectId: string;+ experiments: Array<{ id: string; name: string }>;+ fromTimestamp: Date;+ toTimestamp: Date;+ isExternalLoading?: boolean;+};++/**+ * A single chart slot with an embedded metric dropdown and hover-to-delete.+ */+export function ExperimentChartSlot({+ chartIndex,+ selectedMetricId,+ onMetricChange,+ onRemove,+ canDelete,+ availableMetricOptions,+ projectId,+ experiments,+ fromTimestamp,+ toTimestamp,+ isExternalLoading = false,+}: ExperimentChartSlotProps) {+ const { selectedMetricOption, widgetConfig } = useMemo(+ () => ({+ selectedMetricOption: availableMetricOptions.find(+ (opt) => opt.id === selectedMetricId,+ ),+ widgetConfig: buildWidgetConfigFromId(selectedMetricId),+ }),+ [availableMetricOptions, selectedMetricId],+ );++ const entityDimensionLabelMap = useMemo(+ () =>+ Object.fromEntries(+ experiments.map((experiment) => [experiment.id, experiment.name]),+ ),+ [experiments],+ );++ // Build query from widget config+ const query: QueryType | null = useMemo(() => {+ if (!widgetConfig) return null;++ const experimentIds = experiments.map((experiment) => experiment.id);+ const experimentNames = Array.from(+ new Set(+ experiments+ .map((experiment) => experiment.name)+ .filter((name) => name.length > 0),+ ),+ );+ const entityDimensionField = widgetConfig.entityDimension?.field;++ return {+ view: widgetConfig.view,+ dimensions: [...widgetConfig.dimensions],+ orderBy: widgetConfig.orderBy ? [...widgetConfig.orderBy] : null,+ timeDimension: widgetConfig.timeDimension,+ entityDimension: widgetConfig.entityDimension,+ metrics: widgetConfig.metrics.map((m) => ({+ measure: m.measure,+ aggregation: m.agg,+ })),+ filters: [+ ...(widgetConfig.filters ?? []),+ ...(entityDimensionField === "experimentName" &&+ experimentNames.length > 0+ ? [+ {+ column: "experimentName" as const,+ operator: "any of" as const,+ value: experimentNames,+ type: "stringOptions" as const,+ },+ {+ column: "experimentId" as const,+ operator: "any of" as const,+ value: experimentIds,+ type: "stringOptions" as const,+ },+ ]+ : []),+ ...(entityDimensionField === "datasetRunId"+ ? [+ {+ column: "datasetRunId" as const,+ operator: "any of" as const,+ value: experimentIds,+ type: "stringOptions" as const,+ },+ ]+ : []),+ ],+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ };+ }, [widgetConfig, experiments, fromTimestamp, toTimestamp]);++ // Group options by their group for the dropdown+ const groupedOptions = useMemo(() => {+ const groups = new Map<MetricOption["group"], MetricOption[]>();++ for (const option of availableMetricOptions) {+ const existing = groups.get(option.group) ?? [];+ existing.push(option);+ groups.set(option.group, existing);+ }++ return groups;+ }, [availableMetricOptions]);++ // Get the selected option label for display+ // If not in available options, extract label from ID (for stale selections)+ const selectedLabel = useMemo(() => {+ if (selectedMetricOption) {+ return selectedMetricOption.label;+ }+ // Extract label from ID for stale selections+ if (selectedMetricId.startsWith("base:")) {+ return selectedMetricId === "base:cost" ? "Cost ($)" : "Latency (ms)";+ }+ // Score IDs like "obs-score-numeric:helpfulness" -> "helpfulness"+ const scoreName = selectedMetricId.split(":").pop();+ return scoreName ?? selectedMetricId;+ }, [selectedMetricOption, selectedMetricId]);++ // Check if metric is available for current experiments+ const isMetricAvailable = Boolean(selectedMetricOption);++ const isEnabled = experiments.length > 0;++ return (+ <div className="group relative">+ {/* Hover-to-delete button - fades in on hover */}+ {canDelete && (+ <Button+ variant="ghost"+ size="icon"+ onClick={onRemove}+ className="absolute top-1 right-1 z-10 h-6 w-6 opacity-0 transition-opacity duration-200 group-hover:opacity-100"+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ )}++ {/* Header with dropdown */}+ <div className="flex items-center">+ <Select value={selectedMetricId} onValueChange={onMetricChange}>+ <SelectTrigger className="h-7 w-44 text-xs">+ <SelectValue placeholder="Select metric...">+ {selectedLabel}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {Array.from(groupedOptions.entries()).map(([group, options]) => (+ <SelectGroup key={group}>+ <SelectLabel className="text-xs font-semibold">+ {group}+ </SelectLabel>+ {options.map((option) => (+ <SelectItem key={option.id} value={option.id}>+ {option.label}+ </SelectItem>+ ))}+ </SelectGroup>+ ))}+ </SelectContent>+ </Select>+ </div>++ {/* Chart content area */}+ <div className="mt-1 flex h-56 flex-col">+ {isExternalLoading ? (+ <Skeleton className="h-[190px] w-full" />+ ) : !isMetricAvailable || !isEnabled ? (+ <NoDataOrLoading isLoading={false} className="h-[190px]" />+ ) : widgetConfig && query ? (+ <WidgetContent+ projectId={projectId}+ query={query}+ version={widgetConfig.minVersion}+ chartType={widgetConfig.chartType}+ chartConfig={widgetConfig.chartConfig}+ metrics={[...widgetConfig.metrics]}+ dimensions={[...widgetConfig.dimensions]}+ view={widgetConfig.view}+ schedulerId={`chart-slot-${chartIndex}-${selectedMetricId}`}+ isExternalLoading={isExternalLoading}+ layoutHint="compact"+ entityDimensionLabelMap={entityDimensionLabelMap}+ />+ ) : (+ <div className="flex h-full items-center justify-center rounded-lg border-2 border-dashed">+ <span className="text-muted-foreground text-sm">+ Select a metric+ </span>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/src/features/experiments/components/ExperimentChartsGrid.tsx b/web/src/features/experiments/components/ExperimentChartsGrid.tsxnew file mode 100644index 0000000000..378b2c3e83--- /dev/null+++ b/web/src/features/experiments/components/ExperimentChartsGrid.tsx@@ -0,0 +1,112 @@+import { Plus } from "lucide-react";+import { useMemo } from "react";+import { ExperimentChartSlot } from "./ExperimentChartSlot";+import { useExperimentChartsGridSelection } from "../hooks/useExperimentChartsGridSelection";++type ExperimentChartsGridProps = {+ projectId: string;+ experiments: Array<{ id: string; name: string }>;+ fromTimestamp: Date;+ toTimestamp: Date;+ isExternalLoading?: boolean;+};++/**+ * Compact Add Button - small inline button to add a new chart.+ */+function AddChartButton({ onClick }: { onClick: () => void }) {+ return (+ <button+ onClick={onClick}+ className="border-muted-foreground/25 hover:border-muted-foreground/50 hover:bg-muted/50 flex h-56 w-12 cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed transition-colors duration-200"+ >+ <Plus className="text-muted-foreground/50 h-5 w-5" />+ </button>+ );+}++/**+ * Get grid template columns based on chart count.+ * Uses responsive layouts with min 300px per chart.+ * - 4 charts: xl+ for 1x4, md+ for 2x2 (always wraps in pairs, never 3+1)+ * - 3 charts + add: lg+ for full row, md for 2-col wrap+ * - 2 charts + add: md+ for full row+ * - 1 chart + add: sm+ for full row+ */+function getGridClass(chartCount: number): string {+ if (chartCount === 4) {+ // 4 charts: xl+ (1280px) for 1x4, md+ for 2x2, mobile stacked+ // Uses explicit breakpoints to ensure charts wrap in pairs (never 3+1)+ return "grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4";+ }+ if (chartCount === 3) {+ // 3 charts + add button: lg+ (1024px) for full row, md for 2-col+ return "grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-[1fr_1fr_1fr_auto]";+ }+ if (chartCount === 2) {+ // 2 charts + add button: md+ (768px) for full row+ return "grid grid-cols-1 gap-4 md:grid-cols-[1fr_1fr_auto]";+ }+ // 1 chart + add button: sm+ (640px) for full row+ return "grid grid-cols-1 gap-4 sm:grid-cols-[1fr_auto]";+}++/**+ * A responsive grid for experiment charts with dynamic add/remove.+ * - Max 4 charts+ * - Layout: adapts based on chart count+ * - Compact add button inline at the end+ * - Hover-to-delete on each chart+ */+export function ExperimentChartsGrid({+ projectId,+ experiments,+ fromTimestamp,+ toTimestamp,+ isExternalLoading = false,+}: ExperimentChartsGridProps) {+ const experimentIds = useMemo(+ () => experiments.map((experiment) => experiment.id),+ [experiments],+ );+ const {+ charts,+ updateChart,+ addChart,+ removeChart,+ canAddChart,+ canDeleteChart,+ availableMetricOptions,+ isLoading,+ } = useExperimentChartsGridSelection({+ projectId,+ experimentIds,+ });++ const gridClass = getGridClass(charts.length);++ return (+ <div className={gridClass}>+ {/* Active chart slots */}+ {charts.map((metricId, index) => (+ <ExperimentChartSlot+ key={`${index}-${metricId}`}+ chartIndex={index}+ selectedMetricId={metricId}+ onMetricChange={(newMetricId) => updateChart(index, newMetricId)}+ onRemove={() => removeChart(index)}+ canDelete={canDeleteChart}+ availableMetricOptions={availableMetricOptions}+ projectId={projectId}+ experiments={experiments}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isExternalLoading={isExternalLoading || isLoading}+ />+ ))}++ {/* Compact Add Button - inline at the end */}+ {canAddChart && <AddChartButton onClick={addChart} />}+ </div>+ );+}diff --git a/web/src/features/experiments/components/table/ExperimentItemsTable.tsx b/web/src/features/experiments/components/table/ExperimentItemsTable.tsxindex 12d4c19492..fc8dc87889 100644--- a/web/src/features/experiments/components/table/ExperimentItemsTable.tsx+++ b/web/src/features/experiments/components/table/ExperimentItemsTable.tsx@@ -52,11 +52,15 @@ import {import { MemoizedIOTableCell } from "@/src/components/ui/IOTableCell";import { type DataTablePeekViewProps } from "@/src/components/table/peek";import { cn } from "@/src/utils/tailwind";-import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";-import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";+import { createScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";+import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";import { Skeleton } from "@/src/components/ui/skeleton";import { ExperimentCompareTable } from "./ExperimentCompareTable";import { useExperimentNames } from "@/src/features/experiments/hooks/useExperimentNames";+import {+ useExperimentItemsFilterOptions,+ type ScoreColumnDef,+} from "@/src/features/experiments/hooks/useExperimentItemsFilterOptions";import { DiffLabel } from "@/src/features/datasets/components/DiffLabel";import { computeScoreDiffs } from "@/src/features/datasets/lib/computeScoreDiffs";import { TablePeekViewExperimentItemDetail } from "@/src/components/table/peek/peek-experiment-item-detail";@@ -65,6 +69,28 @@ const renderExperimentSpecificHeader = (label: string) => (<span className="text-muted-foreground">{label}</span>);+/**+ * Transforms score column definitions to the format expected by createScoreColumns.+ * Computes the aggregate key from name/source/dataType.+ */+function toScoreColumnInput(scoreColumnDefs: ScoreColumnDef[]): Array<{+ key: string;+ name: string;+ source: string;+ dataType: "NUMERIC" | "BOOLEAN" | "CATEGORICAL";+}> {+ return scoreColumnDefs.map(({ name, dataType, source }) => ({+ key: composeAggregateScoreKey({+ name,+ source: source as "API" | "ANNOTATION" | "EVAL",+ dataType,+ }),+ name,+ source,+ dataType,+ }));+}+export const getDefaultExperimentFilterTarget = (props: {baselineId?: string;comparisonIds: string[];@@ -247,6 +273,13 @@ export default function ExperimentItemsTable({: comparisonIds,[comparisonIds, fallbackBaselineId],);+ // All experiment IDs (base first, then comparisons)+ const allExperimentIds = useMemo(() => {+ return fallbackBaselineId+ ? [fallbackBaselineId, ...comparisonIdsWithoutFallbackBaseline]+ : [];+ }, [fallbackBaselineId, comparisonIdsWithoutFallbackBaseline]);+const defaultFilterTargetExperimentId = getDefaultExperimentFilterTarget({baselineId,comparisonIds,@@ -285,12 +318,22 @@ export default function ExperimentItemsTable({order: "DESC",});+ // Fetch score filter options scoped to selected experiments+ const {+ filterOptions: scoreFilterOptions,+ scoreColumns: scoreColumnDefs,+ isLoading: isFilterOptionsLoading,+ } = useExperimentItemsFilterOptions({+ projectId,+ experimentIds: allExperimentIds,+ });+// Use sidebar filter state for the sidebar UI (provides proper facets, options, etc.)// This is the single source of truth for filtersconst queryFilter = useSidebarFilterState(experimentItemsFilterConfig,- {},- { stateLocation: "url" },+ scoreFilterOptions,+ { stateLocation: "url", loading: isFilterOptionsLoading },);// Create ref-based wrapper to avoid stale closure when queryFilter updates@@ -471,44 +514,42 @@ export default function ExperimentItemsTable({},);- // All experiment IDs for color coding (base first, then comparisons)- const allExperimentIds = useMemo(() => {- return fallbackBaselineId- ? [fallbackBaselineId, ...comparisonIdsWithoutFallbackBaseline]- : [];- }, [fallbackBaselineId, comparisonIdsWithoutFallbackBaseline]);const colorExperimentIds = useMemo(() => (hasBaseline ? allExperimentIds : []),[hasBaseline, allExperimentIds],);- const {- scoreColumns: observationScoreColumns,- isLoading: isObservationScoreColumnsLoading,- } = useScoreColumns<ExperimentItemData>({- scoreColumnKey: "observationScores",- projectId,- rawKey: true,- filter: scoreFilters.forExperimentItems({- experimentIds: allExperimentIds,- }),- isFilterDataPending: allExperimentIds.length === 0,- });+ // Create score columns from the shared filter options data+ // This ensures sidebar filters and column visibility use the same data source+ const observationScoreColumns = useMemo(+ () =>+ createScoreColumns<ExperimentItemData>(+ toScoreColumnInput(scoreColumnDefs.observationScoreColumns),+ "observationScores",+ "smart",+ undefined,+ undefined,+ true,+ ),+ [scoreColumnDefs.observationScoreColumns],+ );- const {- scoreColumns: traceScoreColumns,- isLoading: isTraceScoreColumnsLoading,- } = useScoreColumns<ExperimentItemData>({- scoreColumnKey: "traceScores",- projectId,- rawKey: true,- filter: scoreFilters.forExperimentItems({- experimentIds: allExperimentIds,- }),- prefix: "Trace",- defaultHidden: true,- isFilterDataPending: allExperimentIds.length === 0,- });+ const traceScoreColumns = useMemo(+ () =>+ createScoreColumns<ExperimentItemData>(+ toScoreColumnInput(scoreColumnDefs.traceScoreColumns),+ "traceScores",+ "smart",+ "Trace",+ true,+ true,+ ),+ [scoreColumnDefs.traceScoreColumns],+ );++ // Use the shared loading state for both sidebar and columns+ const isObservationScoreColumnsLoading = isFilterOptionsLoading;+ const isTraceScoreColumnsLoading = isFilterOptionsLoading;const buildExperimentScoreColumns = useCallback((diff --git a/web/src/features/experiments/components/table/ExperimentsTable.tsx b/web/src/features/experiments/components/table/ExperimentsTable.tsxindex ed69f86668..38dabf1d86 100644--- a/web/src/features/experiments/components/table/ExperimentsTable.tsx+++ b/web/src/features/experiments/components/table/ExperimentsTable.tsx@@ -53,6 +53,14 @@ import { type ExperimentsTableRow, type ExperimentsTableProps } from "./types";import { useExperimentFilterOptions } from "../../hooks/useExperimentFilterOptions";import { RunEvaluationDialog } from "@/src/features/batch-actions/components/RunEvaluationDialog";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/src/components/ui/accordion";+import { ExperimentChartsGrid } from "../ExperimentChartsGrid";+import { useExperimentChartsAccordion } from "../../hooks/useExperimentChartsAccordion";export default function ExperimentsTable({projectId,@@ -501,6 +509,15 @@ export default function ExperimentsTable({: [];}, [experiments]);+ // Get experiments from the current query result (for charts)+ const chartExperiments = useMemo(() => {+ return rows.map((row) => ({ id: row.id, name: row.name }));+ }, [rows]);++ // Charts accordion collapsed state (persisted in session storage)+ const { accordionValue, setAccordionValue } =+ useExperimentChartsAccordion(projectId);+// Get selected experiment IDs in the order they appear in the tableconst selectedExperimentIds = useMemo(() => {const selectedIds = Object.keys(selectedRows).filter((id) =>@@ -620,8 +637,8 @@ export default function ExperimentsTable({setRowHeight={setRowHeight}timeRange={timeRange}setTimeRange={setTimeRange}- actionButtons={- shouldShowActions+ actionButtons={[+ ...(shouldShowActions? [<TableActionMenukey="experiments-multi-select-actions"@@ -641,10 +658,37 @@ export default function ExperimentsTable({}}/>,]- : undefined- }+ : []),+ ]}/>+ {/* Charts section - Collapsible Accordion */}+ {tableDateRange && (+ <Accordion+ type="single"+ collapsible+ value={accordionValue}+ onValueChange={setAccordionValue}+ >+ <AccordionItem value="charts" className="border-t">+ <AccordionTrigger className="px-3 pt-2 pb-1 hover:no-underline">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">Charts</span>+ </div>+ </AccordionTrigger>+ <AccordionContent className="max-h-[40dvh] overflow-x-auto px-3 pt-1 pb-1">+ <ExperimentChartsGrid+ projectId={projectId}+ experiments={chartExperiments}+ fromTimestamp={tableDateRange.from}+ toTimestamp={tableDateRange.to}+ isExternalLoading={experiments.status === "loading"}+ />+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ )}+{/* Content area with sidebar and table */}<ResizableFilterLayout><DataTableControlsdiff --git a/web/src/features/experiments/constants/charts.ts b/web/src/features/experiments/constants/charts.tsnew file mode 100644index 0000000000..1a92f79eac--- /dev/null+++ b/web/src/features/experiments/constants/charts.ts@@ -0,0 +1,127 @@+import type {+ ScoreLevel,+ ScoreMetricSpec,+} from "@/src/features/experiments/types/charts";+import type { WidgetDimensionConfig } from "@/src/features/widgets/hooks/useWidgetQuery";+import type { FilterCondition } from "@langfuse/shared";++// Base chart IDs+export const BASE_CHART_IDS = {+ COST: "base:cost",+ LATENCY: "base:latency",+} as const;++export const MAX_CHARTS = 4;++export const SCORE_METRIC_SPECS: ScoreMetricSpec = {+ "obs:numeric": {+ level: "obs",+ dataType: "numeric",+ filterKey: "obs_scores_avg",+ group: "Observation Scores",+ },+ "obs:categorical": {+ level: "obs",+ dataType: "categorical",+ filterKey: "obs_score_categories",+ group: "Observation Scores",+ },+ "experiment:numeric": {+ level: "experiment",+ dataType: "numeric",+ filterKey: "experiment_scores_avg",+ group: "Experiment Scores",+ },+ "experiment:categorical": {+ level: "experiment",+ dataType: "categorical",+ filterKey: "experiment_score_categories",+ group: "Experiment Scores",+ },+};++const BASE_EXPERIMENT_WIDGET_CONFIG = {+ view: "observations",+ minVersion: "v2",+ dimensions: [] as WidgetDimensionConfig[],+ // Entity (x-axis) order follows the experiments table order, applied+ // client-side in InlineWidget, so no query-side ordering is needed.+ orderBy: null,+ chartType: "LINE_TIME_SERIES",+ chartConfig: { type: "LINE_TIME_SERIES" },+ timeDimension: null,+ entityDimension: { field: "experimentName" },+ filters: [],+} as const;++/**+ * Full configuration for experiment cost widget.+ * Used for both query building and widget display.+ */+export const EXPERIMENT_COST_WIDGET_CONFIG = {+ ...BASE_EXPERIMENT_WIDGET_CONFIG,+ metrics: [{ measure: "totalCost", agg: "sum" }],+ schedulerId: "experiments:cost-chart",+} as const;++export const EXPERIMENT_LATENCY_WIDGET_CONFIG = {+ ...BASE_EXPERIMENT_WIDGET_CONFIG,+ metrics: [{ measure: "latency", agg: "avg" }],+ schedulerId: "experiments:latency-chart",+} as const;++const BASE_SCORE_CHART_CONFIG = {+ entityDimension: { field: "experimentName" },+ timeDimension: null,+ minVersion: "v2",+ // Entity (x-axis) order follows the experiments table order, applied+ // client-side in InlineWidget, so no query-side ordering is needed.+ orderBy: null,+} as const;++export const SCORE_LEVEL_ENTITY_DIMENSIONS: Record<+ ScoreLevel,+ { field: string }+> = {+ obs: { field: "experimentName" },+ experiment: { field: "datasetRunId" },+};++export const NUMERIC_SCORE_CHART_CONFIG = {+ ...BASE_SCORE_CHART_CONFIG,+ view: "scores-numeric",+ dimensions: [],+ metrics: [{ measure: "value", agg: "avg" }],+ filters: [],+ chartType: "LINE_TIME_SERIES",+ chartConfig: { type: "LINE_TIME_SERIES" },+} as const;++export const CATEGORICAL_SCORE_CHART_CONFIG = {+ ...BASE_SCORE_CHART_CONFIG,+ view: "scores-categorical",+ dimensions: [{ field: "stringValue" }],+ metrics: [{ measure: "count", agg: "count" }],+ filters: [],+ chartType: "BAR_TIME_SERIES",+ chartConfig: { type: "BAR_TIME_SERIES" },+} as const;++export const SCORE_LEVEL_FILTERS: Record<ScoreLevel, FilterCondition[]> = {+ obs: [+ {+ column: "observationId",+ operator: "is not null",+ value: "",+ type: "null",+ },+ ],+ experiment: [+ {+ column: "datasetRunId",+ operator: "is not null",+ value: "",+ type: "null",+ },+ ],+};diff --git a/web/src/features/experiments/hooks/useExperimentChartsAccordion.ts b/web/src/features/experiments/hooks/useExperimentChartsAccordion.tsnew file mode 100644index 0000000000..3ca9ff663f--- /dev/null+++ b/web/src/features/experiments/hooks/useExperimentChartsAccordion.ts@@ -0,0 +1,30 @@+import { useCallback } from "react";+import useSessionStorage from "@/src/components/useSessionStorage";++const CHARTS_ACCORDION_VALUE = "charts";++/**+ * Hook to manage the charts accordion collapsed state with session storage persistence.+ */+export function useExperimentChartsAccordion(projectId: string) {+ const [accordionValue, setAccordionValue] = useSessionStorage<+ string | undefined+ >(`experiment-charts-accordion-${projectId}`, CHARTS_ACCORDION_VALUE);++ const isChartsExpanded = accordionValue === CHARTS_ACCORDION_VALUE;++ const setChartsExpanded = useCallback(+ (expanded: boolean) => {+ setAccordionValue(expanded ? CHARTS_ACCORDION_VALUE : undefined);+ },+ [setAccordionValue],+ );++ return {+ isChartsExpanded,+ setChartsExpanded,+ // Raw accordion props for direct binding to Accordion component+ accordionValue,+ setAccordionValue,+ };+}diff --git a/web/src/features/experiments/hooks/useExperimentChartsGridSelection.ts b/web/src/features/experiments/hooks/useExperimentChartsGridSelection.tsnew file mode 100644index 0000000000..995020e67a--- /dev/null+++ b/web/src/features/experiments/hooks/useExperimentChartsGridSelection.ts@@ -0,0 +1,143 @@+import { useMemo, useCallback } from "react";+import useSessionStorage from "@/src/components/useSessionStorage";+import {+ buildMetricOptions,+ getDefaultCharts,+ isValidChartSelection,+} from "@/src/features/experiments/utils/charts";+import { MAX_CHARTS } from "@/src/features/experiments/constants/charts";+import { api } from "@/src/utils/api";+import { type ScoreFilterOptions } from "@/src/features/experiments/types/charts";++const processCategoricalScoreOptions = (+ categories: Array<{ label: string; values: string[] }>,+): Record<string, string[]> =>+ Object.fromEntries(categories.map(({ label, values }) => [label, values]));++/**+ * Hook to manage dynamic experiment chart selection with session storage persistence.+ * Supports add/remove operations with a max of 4 charts.+ */+export function useExperimentChartsGridSelection({+ projectId,+ experimentIds,+}: {+ projectId: string;+ experimentIds: string[];+}) {+ // Default charts+ const defaultCharts = useMemo(() => getDefaultCharts(), []);++ const scoreOptions = api.experiments.scoreOptions.useQuery(+ {+ projectId,+ experimentIds,+ },+ { enabled: experimentIds.length > 0 },+ );++ // Session storage for chart selections+ const [rawCharts, setCharts] = useSessionStorage<string[]>(+ `experiment-charts-grid-${projectId}`,+ defaultCharts,+ );++ // Validate stored data format - fall back to defaults if invalid+ const charts: string[] = useMemo(() => {+ if (isValidChartSelection(rawCharts) && rawCharts.length > 0) {+ return rawCharts;+ }+ // Invalid or empty data - return defaults+ return defaultCharts;+ }, [rawCharts, defaultCharts]);++ // Transform API response to ScoreFilterOptions format+ const transformedScoreOptions = useMemo((): ScoreFilterOptions => {+ if (!scoreOptions.data) {+ return {};+ }+ return {+ obs_scores_avg: scoreOptions.data.obs_scores_avg,+ obs_score_categories: processCategoricalScoreOptions(+ scoreOptions.data.obs_score_categories,+ ),+ experiment_scores_avg: scoreOptions.data.experiment_scores_avg,+ experiment_score_categories: processCategoricalScoreOptions(+ scoreOptions.data.experiment_score_categories,+ ),+ };+ }, [scoreOptions.data]);++ // Build all available metric options for the dropdowns+ const availableMetricOptions = useMemo(+ () => buildMetricOptions(transformedScoreOptions),+ [transformedScoreOptions],+ );++ const availableMetric = useMemo(() => {+ const usedMetrics = new Set(charts);+ return availableMetricOptions.find((opt) => !usedMetrics.has(opt.id));+ }, [charts, availableMetricOptions]);++ // Check if we can add more charts+ const canAddChart = charts.length < MAX_CHARTS && Boolean(availableMetric);++ // Check if we can delete charts (must have more than 1)+ const canDeleteChart = charts.length > 1;++ // Update a specific chart's metric+ const updateChart = useCallback(+ (index: number, metricId: string) => {+ if (index < 0 || index >= charts.length) return;+ const next = [...charts];+ next[index] = metricId;+ setCharts(next);+ },+ [setCharts, charts],+ );++ // Add a new chart with the first available metric not already selected+ const addChart = useCallback(() => {+ if (!canAddChart || !availableMetric) return;++ setCharts([...charts, availableMetric.id]);+ }, [canAddChart, charts, availableMetric, setCharts]);++ // Remove a chart at a specific index+ const removeChart = useCallback(+ (index: number) => {+ if (!canDeleteChart) return;+ if (index < 0 || index >= charts.length) return;++ const next = charts.filter((_, i) => i !== index);+ setCharts(next);+ },+ [canDeleteChart, charts, setCharts],+ );++ // Reset to defaults+ const resetToDefaults = useCallback(() => {+ setCharts(defaultCharts);+ }, [setCharts, defaultCharts]);++ return {+ // Current chart selections (metric IDs)+ charts,+ // Update a chart's metric+ updateChart,+ // Add a new chart+ addChart,+ // Remove a chart+ removeChart,+ // Can add more charts?+ canAddChart,+ // Can delete charts? (more than 1)+ canDeleteChart,+ // Reset to defaults+ resetToDefaults,+ // All available metric options (for dropdown)+ availableMetricOptions,+ // Loading state+ isLoading: scoreOptions.isLoading,+ };+}diff --git a/web/src/features/experiments/hooks/useExperimentItemsFilterOptions.ts b/web/src/features/experiments/hooks/useExperimentItemsFilterOptions.tsnew file mode 100644index 0000000000..6025b8dc57--- /dev/null+++ b/web/src/features/experiments/hooks/useExperimentItemsFilterOptions.ts@@ -0,0 +1,83 @@+import { api } from "@/src/utils/api";+import { useMemo } from "react";+import { type ExperimentItemScoreFilterOptions } from "@/src/features/experiments/types/charts";++export type ScoreColumnDef = {+ name: string;+ dataType: "NUMERIC" | "BOOLEAN" | "CATEGORICAL";+ source: string;+};++const processCategoricalScoreOptions = (+ categories: Array<{ label: string; values: string[] }>,+): Record<string, string[]> =>+ categories.reduce(+ (acc, score) => {+ acc[score.label] = score.values;+ return acc;+ },+ {} as Record<string, string[]>,+ );++/**+ * Hook to fetch experiment item filter options (scores) scoped to specific experiment IDs.+ * Returns score filter options for both observation-level and trace-level scores,+ * plus full score column definitions for table column visibility.+ */+export const useExperimentItemsFilterOptions = ({+ projectId,+ experimentIds,+}: {+ projectId: string;+ experimentIds: string[];+}) => {+ const filterOptions = api.experiments.itemsFilterOptions.useQuery(+ { projectId, experimentIds },+ {+ enabled: experimentIds.length > 0,+ staleTime: Infinity,+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ },+ );++ // Transform categorical scores into key-value format for sidebar filters+ const transformedOptions = useMemo(() => {+ if (!filterOptions.data) {+ return {+ obs_scores_avg: undefined,+ obs_score_categories: undefined,+ trace_scores_avg: undefined,+ trace_score_categories: undefined,+ } satisfies ExperimentItemScoreFilterOptions;+ }++ return {+ obs_scores_avg: filterOptions.data.obs_scores_avg,+ obs_score_categories: processCategoricalScoreOptions(+ filterOptions.data.obs_score_categories,+ ),+ trace_scores_avg: filterOptions.data.trace_scores_avg,+ trace_score_categories: processCategoricalScoreOptions(+ filterOptions.data.trace_score_categories,+ ),+ } satisfies ExperimentItemScoreFilterOptions;+ }, [filterOptions.data]);++ // Extract score column definitions for table columns+ const scoreColumns = useMemo(+ () => ({+ observationScoreColumns: (filterOptions.data?.obs_score_columns ??+ []) as ScoreColumnDef[],+ traceScoreColumns: (filterOptions.data?.trace_score_columns ??+ []) as ScoreColumnDef[],+ }),+ [filterOptions.data],+ );++ return {+ filterOptions: transformedOptions,+ scoreColumns,+ isLoading: filterOptions.isLoading,+ };+};diff --git a/web/src/features/experiments/server/router.ts b/web/src/features/experiments/server/router.tsindex 8013ad69d1..5765bf9fab 100644--- a/web/src/features/experiments/server/router.ts+++ b/web/src/features/experiments/server/router.ts@@ -25,6 +25,8 @@ import {getScoresForTraces,traceException,getExperimentNamesFromEvents,+ getExperimentItemsFilterOptions,+ getExperimentScoreOptions,} from "@langfuse/shared/src/server";import {createTRPCRouter,@@ -672,6 +674,46 @@ export const experimentsRouter = createTRPCRouter({};}),+ itemsFilterOptions: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ experimentIds: z.array(z.string()).min(1),+ }),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "promptExperiments:read",+ });++ return getExperimentItemsFilterOptions({+ projectId: input.projectId,+ experimentIds: input.experimentIds,+ });+ }),++ scoreOptions: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ experimentIds: z.array(z.string()).min(1),+ }),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "promptExperiments:read",+ });++ return getExperimentScoreOptions({+ projectId: input.projectId,+ experimentIds: input.experimentIds,+ });+ }),+batchIO: protectedProjectProcedure.input(z.object({diff --git a/web/src/features/experiments/types/charts.ts b/web/src/features/experiments/types/charts.tsnew file mode 100644index 0000000000..f6cb006575--- /dev/null+++ b/web/src/features/experiments/types/charts.ts@@ -0,0 +1,44 @@+import type { WidgetConfig } from "@/src/features/widgets/hooks/useWidgetQuery";++// Extended widget config for experiment charts with query-building fields+// Omit conflicting properties from WidgetConfig that have readonly/mutable mismatches+export interface ExperimentWidgetConfig extends WidgetConfig {+ orderBy: readonly { field: string; direction: "asc" | "desc" }[];+ timeDimension: null;+ entityDimension: { field: string };+ schedulerId?: string;+}++// Metric option for the per-slot dropdown+export type MetricOption = {+ id: string;+ label: string;+ group: "Base Metrics" | "Observation Scores" | "Experiment Scores";+};++export type ScoreFilterOptions = {+ obs_scores_avg?: string[];+ obs_score_categories?: Record<string, string[]>;+ experiment_scores_avg?: string[];+ experiment_score_categories?: Record<string, string[]>;+};++export type ExperimentItemScoreFilterOptions = {+ obs_scores_avg?: string[];+ obs_score_categories?: Record<string, string[]>;+ trace_scores_avg?: string[];+ trace_score_categories?: Record<string, string[]>;+};++export type ScoreLevel = "obs" | "experiment";+export type ScoreChartDataType = "numeric" | "categorical";++export type ScoreMetricSpec = Record<+ `${ScoreLevel}:${ScoreChartDataType}`,+ {+ level: ScoreLevel;+ dataType: ScoreChartDataType;+ filterKey: keyof ScoreFilterOptions;+ group: Exclude<MetricOption["group"], "Base Metrics">;+ }+>;diff --git a/web/src/features/experiments/utils/charts.ts b/web/src/features/experiments/utils/charts.tsnew file mode 100644index 0000000000..f9ae4bbcc2--- /dev/null+++ b/web/src/features/experiments/utils/charts.ts@@ -0,0 +1,156 @@+import {+ BASE_CHART_IDS,+ CATEGORICAL_SCORE_CHART_CONFIG,+ EXPERIMENT_COST_WIDGET_CONFIG,+ EXPERIMENT_LATENCY_WIDGET_CONFIG,+ MAX_CHARTS,+ NUMERIC_SCORE_CHART_CONFIG,+ SCORE_LEVEL_ENTITY_DIMENSIONS,+ SCORE_LEVEL_FILTERS,+ SCORE_METRIC_SPECS,+} from "@/src/features/experiments/constants/charts";+import type {+ MetricOption,+ ScoreChartDataType,+ ScoreFilterOptions,+ ScoreLevel,+} from "@/src/features/experiments/types/charts";++// Build chart ID from type and score name+export const buildScoreChartId = (+ level: ScoreLevel,+ dataType: "numeric" | "categorical",+ scoreName: string,+): string => `${level}-score-${dataType}:${scoreName}`;++// Parse chart ID to extract components+const parseScoreChartId = (+ chartId: string,+): {+ level: ScoreLevel;+ dataType: "numeric" | "categorical";+ scoreName: string;+} | null => {+ const match = chartId.match(+ /^(obs|experiment)-score-(numeric|categorical):(.+)$/,+ );+ if (!match) return null;+ return {+ level: match[1] as ScoreLevel,+ dataType: match[2] as "numeric" | "categorical",+ scoreName: match[3],+ };+};++function getScoreNamesFromFilterOption(+ value: string[] | Record<string, string[]> | undefined,+ dataType: ScoreChartDataType,+): string[] {+ if (!value) return [];+ return dataType === "numeric"+ ? (value as string[])+ : Object.keys(value as Record<string, string[]>);+}++export function createScoreWidgetConfig(params: {+ level: ScoreLevel;+ dataType: "numeric" | "categorical";+ scoreName: string;+}) {+ const levelFilters = SCORE_LEVEL_FILTERS[params.level];++ // Filter by score name AND level+ const scoreNameFilter = {+ column: "name" as const,+ operator: "=" as const,+ value: params.scoreName,+ type: "string" as const,+ };++ return {+ ...(params.dataType === "numeric"+ ? NUMERIC_SCORE_CHART_CONFIG+ : CATEGORICAL_SCORE_CHART_CONFIG),+ entityDimension: SCORE_LEVEL_ENTITY_DIMENSIONS[params.level],+ filters: [...levelFilters, scoreNameFilter],+ };+}++/**+ * Build widget config from a chart ID.+ * Works for both base charts and score charts (parsed from ID).+ */+export function buildWidgetConfigFromId(chartId: string) {+ // Base charts+ if (chartId === BASE_CHART_IDS.COST) {+ return EXPERIMENT_COST_WIDGET_CONFIG;+ }+ if (chartId === BASE_CHART_IDS.LATENCY) {+ return EXPERIMENT_LATENCY_WIDGET_CONFIG;+ }++ // Score charts - parse ID to get score name and level+ const parsed = parseScoreChartId(chartId);+ if (!parsed) return null;++ const { level, dataType, scoreName } = parsed;++ return createScoreWidgetConfig({+ level,+ dataType,+ scoreName,+ });+}++/**+ * Get smart default charts based on available scores.+ * Starts with Cost and Latency.+ */+export function getDefaultCharts(): string[] {+ return [BASE_CHART_IDS.COST, BASE_CHART_IDS.LATENCY];+}++/**+ * Build all available metric options from score filter options for the dropdown.+ */+export function buildMetricOptions(+ scoreFilterOptions: ScoreFilterOptions,+): MetricOption[] {+ const scoreOptions = Object.values(SCORE_METRIC_SPECS).flatMap(+ ({ level, dataType, filterKey, group }) => {+ const scoreNames = getScoreNamesFromFilterOption(+ scoreFilterOptions[filterKey],+ dataType,+ );++ return scoreNames.map((scoreName) => ({+ id: buildScoreChartId(level, dataType, scoreName),+ label: scoreName,+ group,+ }));+ },+ );++ return [+ {+ id: BASE_CHART_IDS.COST,+ label: "Cost ($)",+ group: "Base Metrics",+ },+ {+ id: BASE_CHART_IDS.LATENCY,+ label: "Latency (ms)",+ group: "Base Metrics",+ },+ ...scoreOptions,+ ];+}++/**+ * Validate that stored data is a valid ChartSelection (array of strings, max 4).+ */+export function isValidChartSelection(data: unknown): data is string[] {+ if (!Array.isArray(data)) return false;+ if (data.length > MAX_CHARTS) return false;+ return data.every((item) => typeof item === "string" && item.length > 0);+}diff --git a/web/src/features/scores/hooks/useScoreColumns.ts b/web/src/features/scores/hooks/useScoreColumns.tsindex 14bcafd600..6517720234 100644--- a/web/src/features/scores/hooks/useScoreColumns.ts+++ b/web/src/features/scores/hooks/useScoreColumns.ts@@ -10,8 +10,8 @@ import { ScoresTableCell } from "@/src/components/scores-table-cell";import { toOrderedScoresList } from "@/src/features/scores/lib/helpers";import { getScoreDataTypeIcon } from "@/src/features/scores/lib/scoreColumns";-// Simple score column creation-function createScoreColumns<T extends Record<string, any>>(+// Simple score column creation - exported for reuse+export function createScoreColumns<T extends Record<string, any>>(scoreColumns: Array<{key: string;name: string;diff --git a/web/src/features/widgets/components/InlineWidget.tsx b/web/src/features/widgets/components/InlineWidget.tsxnew file mode 100644index 0000000000..6cdb38c052--- /dev/null+++ b/web/src/features/widgets/components/InlineWidget.tsx@@ -0,0 +1,424 @@+import { useMemo, useState, useCallback } from "react";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import { type OrderByState } from "@langfuse/shared";+import {+ type QueryType,+ type ViewVersion,+ getResultUnit,+} from "@langfuse/shared/query";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";+import { Chart } from "@/src/features/widgets/chart-library/Chart";+import { ChartLoadingState } from "@/src/features/widgets/chart-library/ChartLoadingState";+import {+ getChartLoadingProgress,+ getChartLoadingStateProps,+} from "@/src/features/widgets/chart-library/chartLoadingStateUtils";+import {+ formatMetricName,+ shouldUseWidgetSSE,+ getWidgetMetricPresentation,+ type WidgetChartConfig,+} from "@/src/features/widgets/utils";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import { cn } from "@/src/utils/tailwind";++// ============================================================================+// Types+// ============================================================================++export interface WidgetMetricConfig {+ measure: string;+ agg: string;+}++export interface WidgetDimensionConfig {+ field: string;+}++export interface WidgetContentProps {+ projectId: string;+ query: QueryType;+ version: ViewVersion;+ chartType: DashboardWidgetChartType;+ chartConfig: WidgetChartConfig;+ metrics: WidgetMetricConfig[];+ dimensions: WidgetDimensionConfig[];+ view: string;+ /**+ * External loading state - when true, shows loading overlay even if query is complete.+ * Useful when parent component needs to load data before the widget can be meaningful.+ */+ isExternalLoading?: boolean;+ /**+ * Unique ID for query scheduling.+ */+ schedulerId: string;+ /**+ * Layout hint for loading state display. Affects spacing and text size.+ */+ layoutHint?: "default" | "compact" | "tight";+ /**+ * Pivot table sort state (only used for PIVOT_TABLE chart type)+ */+ sortState?: OrderByState | null;+ /**+ * Callback when pivot table sort changes+ */+ onSortChange?: (sort: OrderByState | null) => void;+ /**+ * Additional class names for the container+ */+ className?: string;+ /**+ * Optional presentation-only labels for entity_dimension values.+ */+ entityDimensionLabelMap?: Record<string, string>;+}++export interface WidgetHeaderProps {+ title: string;+ description?: string;+ /**+ * Action buttons to render on the right side of the header+ */+ actions?: React.ReactNode;+ className?: string;+}++export interface WidgetWrapperProps {+ children: React.ReactNode;+ className?: string;+}++// ============================================================================+// Components+// ============================================================================++/**+ * Simple wrapper providing consistent widget styling (border, padding, background).+ */+export function WidgetWrapper({ children, className }: WidgetWrapperProps) {+ return (+ <div+ className={cn(+ "bg-background group flex h-full w-full flex-col overflow-hidden rounded-lg border p-4",+ className,+ )}+ >+ {children}+ </div>+ );+}++/**+ * Widget header with title, description, and optional action buttons.+ */+export function WidgetHeader({+ title,+ description,+ actions,+ className,+}: WidgetHeaderProps) {+ return (+ <div className={cn("mb-4", className)}>+ <div className="flex items-center justify-between">+ <span className="truncate font-medium" title={title}>+ {title}+ </span>+ {actions && <div className="flex space-x-2">{actions}</div>}+ </div>+ {description && (+ <div+ className="text-muted-foreground truncate text-sm"+ title={description}+ >+ {description}+ </div>+ )}+ </div>+ );+}++const getXAxisValue = (+ item: Record<string, unknown>,+ entityDimensionLabelMap?: Record<string, string>,+) => {+ const entityDimensionValue = String(item["entity_dimension"]);+ const entityDimensionLabel = entityDimensionLabelMap?.[entityDimensionValue];+ return entityDimensionLabel && entityDimensionLabel.length > 0+ ? entityDimensionLabel+ : entityDimensionValue;+};++/**+ * Core widget content: executes query, transforms data, renders chart with loading states.+ *+ * This component handles:+ * - Query execution via useScheduledDashboardExecuteQuery+ * - Data transformation for chart consumption (time_dimension, entity_dimension, dimension, metric)+ * - Chart rendering with the appropriate chart type+ * - Loading and error states+ *+ * For pivot tables, pass sortState and onSortChange to enable sorting.+ */+export function WidgetContent({+ projectId,+ query,+ version,+ chartType,+ chartConfig,+ metrics,+ dimensions,+ view,+ // equals widget is pending+ isExternalLoading = false,+ schedulerId,+ layoutHint = "default",+ sortState,+ onSortChange,+ className,+ entityDimensionLabelMap,+}: WidgetContentProps) {+ const { isBetaEnabled } = useV4Beta();+ const [retryCount, setRetryCount] = useState(0);++ const handleRetry = useCallback(() => {+ setRetryCount((current) => current + 1);+ }, []);++ // Execute the query+ const queryResult = useScheduledDashboardExecuteQuery(+ {+ projectId,+ version,+ query,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ queryId: schedulerId,+ meta: {+ silentHttpCodes: [422],+ },+ refreshKey: retryCount,+ useSSE: shouldUseWidgetSSE({+ isV4Enabled: isBetaEnabled,+ version,+ }),+ enabled: !isExternalLoading,+ },+ );++ // Transform data for chart consumption+ const transformedData = useMemo(() => {+ if (!queryResult.data) {+ return [];+ }++ const mapped = queryResult.data.map((item: Record<string, unknown>) => {+ if (chartType === "PIVOT_TABLE") {+ // For pivot tables, preserve all raw data fields+ const timeDimension = item["time_dimension"];+ return {+ dimension:+ dimensions.length > 0+ ? (dimensions[0]?.field ?? "dimension")+ : "dimension",+ metric: 0,+ time_dimension:+ typeof timeDimension === "string"+ ? timeDimension+ : String(timeDimension ?? "n/a"),+ ...item,+ };+ }++ // Regular chart processing+ const metric = metrics.slice().shift() ?? {+ measure: "count",+ agg: "count",+ };+ const metricField = `${metric.agg}_${metric.measure}`;+ const metricValue = item[metricField];++ const dimensionField = dimensions.slice().shift()?.field ?? "none";++ // Handle x-axis: prefer entity_dimension, then time_dimension+ let xAxisValue: string | undefined;+ if (item["entity_dimension"] !== undefined) {+ xAxisValue = getXAxisValue(item, entityDimensionLabelMap);+ } else if (item["time_dimension"] !== undefined) {+ xAxisValue = String(item["time_dimension"]);+ }++ // Handle series dimension (for legend)+ let seriesDimension: string;+ if (item[dimensionField] !== undefined) {+ const val = item[dimensionField];+ if (typeof val === "string") {+ seriesDimension = val;+ } else if (val === null || val === undefined || val === "") {+ seriesDimension = "n/a";+ } else if (Array.isArray(val)) {+ seriesDimension = val.join(", ");+ } else {+ seriesDimension = String(val);+ }+ } else {+ seriesDimension = formatMetricName(metricField);+ }++ return {+ // time_dimension is used as x-axis for charts (works for both time and entity dimensions)+ time_dimension: xAxisValue,+ dimension: seriesDimension,+ metric: Array.isArray(metricValue)+ ? metricValue+ : Number(metricValue || 0),+ };+ });++ // Entity-dimension charts have no meaningful query-side order (the server+ // falls back to first-metric DESC, which differs per chart). Order the+ // x-axis to match the experiments table order provided via+ // entityDimensionLabelMap so the same entity lines up across chart slots.+ if (+ chartType !== "PIVOT_TABLE" &&+ entityDimensionLabelMap &&+ Object.keys(entityDimensionLabelMap).length > 0+ ) {+ const order = new Map<string, number>();+ Object.entries(entityDimensionLabelMap).forEach(([id, name], index) => {+ order.set(id, index);+ order.set(name, index);+ });+ return mapped+ .slice()+ .sort(+ (a, b) =>+ (order.get(b.time_dimension ?? "") ?? Number.MAX_SAFE_INTEGER) -+ (order.get(a.time_dimension ?? "") ?? Number.MAX_SAFE_INTEGER),+ );+ }++ return mapped;+ }, [+ queryResult.data,+ chartType,+ metrics,+ dimensions,+ entityDimensionLabelMap,+ ]);++ // Chart presentation (label and formatter)+ const chartPresentation = useMemo(() => {+ if (chartType === "PIVOT_TABLE" || metrics.length === 0) {+ return undefined;+ }++ const metric = metrics[0];+ return getWidgetMetricPresentation({+ metric,+ view,+ version,+ });+ }, [chartType, metrics, view, version]);++ // Loading state+ const chartLoadingState = getChartLoadingStateProps({+ isPending: queryResult.isPending,+ isError: queryResult.isError,+ errorMessage: queryResult.error,+ });++ const usesBackendProgress = shouldUseWidgetSSE({+ isV4Enabled: isBetaEnabled,+ version,+ });++ const loadingProgress = getChartLoadingProgress({+ isPending: queryResult.isPending,+ progress: queryResult.progress,+ useBackendProgress: usesBackendProgress,+ });++ // Determine row limit+ const effectiveRowLimit = useMemo(() => {+ if (+ chartType === "LINE_TIME_SERIES" ||+ chartType === "BAR_TIME_SERIES" ||+ chartType === "AREA_TIME_SERIES"+ ) {+ return 100;+ }+ return chartConfig.row_limit ?? 100;+ }, [chartType, chartConfig.row_limit]);++ // Build chart config with units+ const fullChartConfig = useMemo(() => {+ const baseConfig = { ...chartConfig };++ if (chartType === "PIVOT_TABLE") {+ return {+ ...baseConfig,+ dimensions: dimensions.map((dim) => dim.field),+ metrics: metrics.map((m) => `${m.agg}_${m.measure}`),+ units: metrics.map((m) =>+ getResultUnit(view, m.measure, m.agg, version),+ ),+ };+ }++ if (metrics.length > 0) {+ return {+ ...baseConfig,+ unit: getResultUnit(view, metrics[0].measure, metrics[0].agg, version),+ };+ }++ return baseConfig;+ }, [chartConfig, chartType, dimensions, metrics, view, version]);++ if (isExternalLoading) {+ return (+ <div+ className={`bg-background flex items-center justify-center rounded-lg border p-4`}+ >+ <div className="text-muted-foreground">Loading...</div>+ </div>+ );+ }++ return (+ <div className={cn("relative min-h-0 flex-1", className)}>+ <Chart+ chartType={chartType}+ data={transformedData}+ config={+ chartPresentation+ ? { metric: { label: chartPresentation.label } }+ : undefined+ }+ rowLimit={effectiveRowLimit}+ chartConfig={fullChartConfig}+ sortState={chartType === "PIVOT_TABLE" ? sortState : undefined}+ onSortChange={chartType === "PIVOT_TABLE" ? onSortChange : undefined}+ isLoading={queryResult.isPending || isExternalLoading}+ metricFormatter={chartPresentation?.metricFormatter}+ />+ <ChartLoadingState+ isLoading={chartLoadingState.isLoading}+ showSpinner={chartLoadingState.showSpinner}+ showHintImmediately={chartLoadingState.showHintImmediately}+ hintText={chartLoadingState.hintText}+ onRetry={queryResult.isError ? handleRetry : undefined}+ progress={loadingProgress}+ layout={layoutHint}+ className="bg-background/80 absolute inset-0 z-20 backdrop-blur-xs"+ />+ </div>+ );+}diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsxindex b88f1b7e0b..2a00823cb8 100644--- a/web/src/features/widgets/components/WidgetForm.tsx+++ b/web/src/features/widgets/components/WidgetForm.tsx@@ -752,7 +752,6 @@ export function WidgetForm({viewVersion === "v2"? eventsFilterOptions.data?.calledToolNames || []: generationsFilterOptions.data?.calledToolNames || [];-// Experiment options only available in v2 (from events table)const experimentNameOptions =viewVersion === "v2" ? eventsFilterOptions.data?.experimentName || [] : [];diff --git a/web/src/features/widgets/hooks/useWidgetQuery.ts b/web/src/features/widgets/hooks/useWidgetQuery.tsnew file mode 100644index 0000000000..9c129474a5--- /dev/null+++ b/web/src/features/widgets/hooks/useWidgetQuery.ts@@ -0,0 +1,208 @@+import { useMemo } from "react";+import { type z } from "zod";+import { type FilterState } from "@langfuse/shared";+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";+import {+ type QueryType,+ type ViewVersion,+ type views,+ type metricAggregations,+ requiresV2,+ validateQuery,+ toQueryChartConfig,+ isV2BreakdownChart,+ buildWidgetOrderBy,+ type QueryValidationResult,+} from "@langfuse/shared/query";+import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";+import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";++// ============================================================================+// Types+// ============================================================================++export interface WidgetMetricConfig {+ measure: string;+ agg: string;+}++export interface WidgetDimensionConfig {+ field: string;+}++export interface WidgetChartConfig {+ type: DashboardWidgetChartType;+ row_limit?: number;+ bins?: number;+ defaultSort?: {+ column: string;+ order: "ASC" | "DESC";+ };+}++/**+ * Widget configuration - the shape of data stored in DB or passed programmatically.+ */+export interface WidgetConfig {+ view: z.infer<typeof views>;+ dimensions: WidgetDimensionConfig[];+ metrics: WidgetMetricConfig[];+ filters: FilterState;+ chartType: DashboardWidgetChartType;+ chartConfig: WidgetChartConfig;+ /**+ * Minimum version required by this widget config.+ * When >= 2, forces v2 regardless of beta toggle.+ */+ minVersion?: number;+}++export interface UseWidgetQueryParams {+ widgetConfig: WidgetConfig;+ dateRange: { from: Date; to: Date } | undefined;+ /**+ * Additional filters from parent context (e.g., dashboard-level filters).+ * These are merged with widget filters.+ */+ filterState?: FilterState;+ /**+ * Sort state for pivot tables.+ */+ sortState?: { column: string; order: string } | null;+}++export interface UseWidgetQueryResult {+ query: QueryType;+ version: ViewVersion;+ validation: QueryValidationResult;+}++// ============================================================================+// Hook+// ============================================================================++/**+ * Hook that builds a QueryType from widget configuration.+ *+ * Handles:+ * - Version computation (v1 vs v2) based on widget config and beta toggle+ * - Query building with proper time dimension, order by, and chart config+ * - Filter merging and mapping from UI labels to view field names+ * - Query validation for high cardinality dimensions+ *+ * @example+ * ```tsx+ * const { query, version, validation } = useWidgetQuery({+ * widgetConfig: widget.data,+ * dateRange,+ * filterState: dashboardFilters,+ * sortState,+ * });+ *+ * if (!validation.valid) {+ * return <Error message={validation.reason} />;+ * }+ *+ * return <WidgetContent query={query} version={version} ... />;+ * ```+ */+export function useWidgetQuery({+ widgetConfig,+ dateRange,+ filterState = [],+ sortState = null,+}: UseWidgetQueryParams): UseWidgetQueryResult {+ const { isBetaEnabled } = useV4Beta();++ // Compute version based on widget requirements and beta toggle+ const version: ViewVersion = useMemo(() => {+ const widgetRequiresV2 = requiresV2({+ view: widgetConfig.view,+ dimensions: widgetConfig.dimensions,+ measures: widgetConfig.metrics.map((m) => ({ measure: m.measure })),+ filters: widgetConfig.filters,+ });++ // If widget requires v2 features (minVersion >= 2), must use v2.+ // Otherwise follow the beta toggle (except for traces view which has no v2).+ if (widgetRequiresV2 || (widgetConfig.minVersion ?? 1) >= 2) {+ return "v2";+ }++ if (isBetaEnabled && widgetConfig.view !== "traces") {+ return "v2";+ }++ return "v1";+ }, [widgetConfig, isBetaEnabled]);++ // Build the query+ const query: QueryType = useMemo(() => {+ const fromTimestamp = dateRange+ ? dateRange.from+ : new Date(Date.now() - 1000);+ const toTimestamp = dateRange ? dateRange.to : new Date();++ const isTimeSeries = isTimeSeriesChart(widgetConfig.chartType);+ const hasDimension = widgetConfig.dimensions.length > 0;+ const chartType = widgetConfig.chartConfig.type;++ // Check if this is a v2 breakdown chart that needs top-N enforcement+ const needsTopN = isV2BreakdownChart({+ version,+ hasDimension,+ isTimeSeries,+ chartType,+ });++ // Build order by clause+ const firstMetric = widgetConfig.metrics[0];+ const orderBy = buildWidgetOrderBy({+ chartType,+ sortState,+ needsTopN,+ firstMetric: firstMetric+ ? { aggregation: firstMetric.agg, measure: firstMetric.measure }+ : undefined,+ });++ // Build chart config (strip rendering-only fields, add defaults)+ const queryChartConfig = toQueryChartConfig(widgetConfig.chartConfig, {+ defaultRowLimit: needsTopN ? 100 : undefined,+ });++ // Merge and map filters+ const mappedWidgetFilters = mapLegacyUiTableFilterToView(+ widgetConfig.view,+ widgetConfig.filters,+ );+ const mappedDashboardFilters = mapLegacyUiTableFilterToView(+ widgetConfig.view,+ filterState,+ );++ return {+ view: widgetConfig.view,+ dimensions: widgetConfig.dimensions,+ metrics: widgetConfig.metrics.map((metric) => ({+ measure: metric.measure,+ aggregation: metric.agg as z.infer<typeof metricAggregations>,+ })),+ filters: [...mappedWidgetFilters, ...mappedDashboardFilters],+ timeDimension: isTimeSeries ? { granularity: "auto" as const } : null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy,+ chartConfig: queryChartConfig,+ };+ }, [widgetConfig, dateRange, filterState, sortState, version]);++ // Validate the query+ const validation = useMemo(+ () => validateQuery(query, version),+ [query, version],+ );++ return { query, version, validation };+}