πͺ’ 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: add v2 backend path for score histogram dashboard query (#12140)
Valery Meleshkina587ce69f052
diff --git a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.tsindex 4b720e3654..9c9c3ec7c8 100644--- a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts+++ b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts@@ -460,6 +460,49 @@ describe("dashboard v1 vs v2 consistency", () => {return window === "1d" ? fromTimestamp1d : fromTimestamp7d;}+ function makeCaller() {+ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Test User",+ organizations: [+ {+ id: orgId,+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ hasTraces: true,+ metadata: {},+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ },+ admin: true,+ },+ environment: {} as any,+ };+ const ctx = createInnerTRPCContext({ session, headers: {} });+ return appRouter.createCaller({ ...ctx, prisma });+ }+async function runBothVersions(query: QueryType): Promise<{v1: Array<Record<string, unknown>>;v2: Array<Record<string, unknown>>;@@ -777,49 +820,6 @@ describe("dashboard v1 vs v2 consistency", () => {// βββ 7. Score-aggregate tRPC endpoint (full getScoreAggregateV2 path) βmaybe("score-aggregate tRPC endpoint v2", () => {- function makeCaller() {- const session: Session = {- expires: "1",- user: {- id: "user-1",- canCreateOrganizations: true,- name: "Test User",- organizations: [- {- id: orgId,- name: "Test Organization",- role: "OWNER",- plan: "cloud:hobby",- cloudConfig: undefined,- metadata: {},- aiFeaturesEnabled: false,- projects: [- {- id: projectId,- role: "ADMIN",- retentionDays: 30,- deletedAt: null,- name: "Test Project",- hasTraces: true,- metadata: {},- },- ],- },- ],- featureFlags: {- excludeClickhouseRead: false,- templateFlag: true,- v4BetaToggleVisible: false,- observationEvals: false,- },- admin: true,- },- environment: {} as any,- };- const ctx = createInnerTRPCContext({ session, headers: {} });- return appRouter.createCaller({ ...ctx, prisma });- }-const chartInput = (version: "v1" | "v2",extraFilters: FilterCondition[] = [],@@ -1086,4 +1086,222 @@ describe("dashboard v1 vs v2 consistency", () => {}});});++ // βββ 8. ScoreHistogram tRPC endpoint (v2 via executeQuery histogram) ββ++ // Seed data uses "metric_*" names; synthetic data uses "accuracy"/"relevance".+ const HIST_NUMERIC =+ DATA_MODE === "seeder"+ ? { name: "metric_46", source: "API", dataType: "NUMERIC" }+ : { name: "accuracy", source: "API", dataType: "NUMERIC" };+ const HIST_BOOLEAN =+ DATA_MODE === "seeder"+ ? { name: "metric_32", source: "API", dataType: "BOOLEAN" }+ : { name: "relevance", source: "API", dataType: "BOOLEAN" };++ maybe("scoreHistogram tRPC endpoint v2", () => {+ const histInput = (+ version: "v1" | "v2",+ scoreName: string,+ scoreSource: string,+ scoreDataType: string,+ ) => ({+ projectId,+ from: "traces_scores" as const,+ select: [{ column: "value" }],+ filter: [+ {+ column: "scoreTimestamp",+ operator: ">=" as const,+ value: new Date(fromTimestamp7d),+ type: "datetime" as const,+ },+ {+ column: "scoreTimestamp",+ operator: "<" as const,+ value: new Date(toTimestamp),+ type: "datetime" as const,+ },+ {+ type: "string" as const,+ column: "scoreName",+ value: scoreName,+ operator: "=" as const,+ },+ {+ type: "string" as const,+ column: "scoreSource",+ value: scoreSource,+ operator: "=" as const,+ },+ {+ type: "string" as const,+ column: "scoreDataType",+ value: scoreDataType,+ operator: "=" as const,+ },+ ],+ limit: 10000,+ version,+ });++ /**+ * Parse histogram bins into (lower, upper, count) tuples.+ * Bin labels follow the format "[lower, upper]".+ */+ function parseBins(+ chartData: Array<Record<string, unknown>>,+ ): Array<{ lower: number; upper: number; count: number }> {+ return chartData.map((bin) => {+ const match = (bin.binLabel as string).match(+ /\[(-?[\d.]+),\s*(-?[\d.]+)\]/,+ );+ expect(match).not.toBeNull();+ return {+ lower: Number(match![1]),+ upper: Number(match![2]),+ count: Number((bin as Record<string, number>).count ?? 0),+ };+ });+ }++ /**+ * Sum bin counts whose midpoint falls below each threshold.+ */+ function cumulativeCountsAt(+ bins: Array<{ lower: number; upper: number; count: number }>,+ thresholds: number[],+ ): number[] {+ return thresholds.map((t) =>+ bins+ .filter((b) => (b.lower + b.upper) / 2 < t)+ .reduce((s, b) => s + b.count, 0),+ );+ }++ it("should return valid histogram data for v2", async () => {+ const caller = makeCaller();+ const result = await caller.dashboard.scoreHistogram(+ histInput(+ "v2",+ HIST_NUMERIC.name,+ HIST_NUMERIC.source,+ HIST_NUMERIC.dataType,+ ),+ );++ expect(result.chartLabels).toEqual(["count"]);+ expect(result.chartData.length).toBeGreaterThan(0);++ // Each bin should have binLabel and count+ for (const bin of result.chartData) {+ expect(bin).toHaveProperty("binLabel");+ expect(bin).toHaveProperty("count");+ expect(typeof bin.count).toBe("number");+ expect(bin.count).toBeGreaterThanOrEqual(0);+ }+ });++ it("should return matching histogram shape between v1 and v2 for NUMERIC scores", async () => {+ const caller = makeCaller();+ const [v1Result, v2Result] = await Promise.all([+ caller.dashboard.scoreHistogram(+ histInput(+ "v1",+ HIST_NUMERIC.name,+ HIST_NUMERIC.source,+ HIST_NUMERIC.dataType,+ ),+ ),+ caller.dashboard.scoreHistogram(+ histInput(+ "v2",+ HIST_NUMERIC.name,+ HIST_NUMERIC.source,+ HIST_NUMERIC.dataType,+ ),+ ),+ ]);++ expect(v1Result.chartData.length).toBeGreaterThan(0);+ expect(v2Result.chartData.length).toBeGreaterThan(0);++ const v1Bins = parseBins(v1Result.chartData);+ const v2Bins = parseBins(v2Result.chartData);++ const v1Total = v1Bins.reduce((s, b) => s + b.count, 0);+ const v2Total = v2Bins.reduce((s, b) => s + b.count, 0);++ // Total count: allow Β±1. ClickHouse histogram() returns float counts+ // per bin (it distributes points across bins using an adaptive algorithm).+ // Math.round() on each bin independently can shift the sum by Β±1.+ expect(Math.abs(v2Total - v1Total)).toBeLessThanOrEqual(1);++ // Value range should be similar+ const v1Min = Math.min(...v1Bins.map((b) => b.lower));+ const v2Min = Math.min(...v2Bins.map((b) => b.lower));+ const v1Max = Math.max(...v1Bins.map((b) => b.upper));+ const v2Max = Math.max(...v2Bins.map((b) => b.upper));+ expect(Math.abs(v1Min - v2Min)).toBeLessThan(0.5);+ expect(Math.abs(v1Max - v2Max)).toBeLessThan(0.5);++ // Cumulative distribution at data-relative quartile points.+ const range = v1Max - v1Min;+ const thresholds = [0.25, 0.5, 0.75].map((q) => v1Min + q * range);+ const v1Cum = cumulativeCountsAt(v1Bins, thresholds);+ const v2Cum = cumulativeCountsAt(v2Bins, thresholds);+ const tolerance = Math.ceil(v1Total * 0.15);+ for (let i = 0; i < thresholds.length; i++) {+ expect(Math.abs(v1Cum[i] - v2Cum[i])).toBeLessThanOrEqual(tolerance);+ }+ });++ it("should return matching histogram shape between v1 and v2 for BOOLEAN scores", async () => {+ const caller = makeCaller();+ const [v1Result, v2Result] = await Promise.all([+ caller.dashboard.scoreHistogram(+ histInput(+ "v1",+ HIST_BOOLEAN.name,+ HIST_BOOLEAN.source,+ HIST_BOOLEAN.dataType,+ ),+ ),+ caller.dashboard.scoreHistogram(+ histInput(+ "v2",+ HIST_BOOLEAN.name,+ HIST_BOOLEAN.source,+ HIST_BOOLEAN.dataType,+ ),+ ),+ ]);++ expect(v1Result.chartData.length).toBeGreaterThan(0);+ expect(v2Result.chartData.length).toBeGreaterThan(0);++ const v1Bins = parseBins(v1Result.chartData);+ const v2Bins = parseBins(v2Result.chartData);++ const v1Total = v1Bins.reduce((s, b) => s + b.count, 0);+ const v2Total = v2Bins.reduce((s, b) => s + b.count, 0);++ // Total count: allow Β±1+ expect(Math.abs(v2Total - v1Total)).toBeLessThanOrEqual(1);++ // Value range: BOOLEAN scores are 0 or 1, both versions should span [0, 1]+ const v1Min = Math.min(...v1Bins.map((b) => b.lower));+ const v2Min = Math.min(...v2Bins.map((b) => b.lower));+ const v1Max = Math.max(...v1Bins.map((b) => b.upper));+ const v2Max = Math.max(...v2Bins.map((b) => b.upper));+ expect(Math.abs(v1Min - v2Min)).toBeLessThan(0.5);+ expect(Math.abs(v1Max - v2Max)).toBeLessThan(0.5);++ // Cumulative distribution at midpoint should roughly agree.+ const v1Lower = cumulativeCountsAt(v1Bins, [0.5])[0];+ const v2Lower = cumulativeCountsAt(v2Bins, [0.5])[0];+ const tolerance = Math.ceil(v1Total * 0.15);+ expect(Math.abs(v1Lower - v2Lower)).toBeLessThanOrEqual(tolerance);+ });+ });});diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsxindex be40877eb5..96ff090508 100644--- a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx@@ -19,9 +19,11 @@ export function NumericScoreHistogram(props: {globalFilterState: FilterState;metricsVersion?: ViewVersion;}) {+ const version = props.metricsVersion ?? "v1";const histogram = api.dashboard.scoreHistogram.useQuery({projectId: props.projectId,+ version,from: "traces_scores",select: [{ column: "value" }],filter: [@@ -45,7 +47,9 @@ export function NumericScoreHistogram(props: {operator: "=",},],- limit: 10000,+ // v1 fetches raw values client-side (capped at 10k rows).+ // v2 aggregates server-side via histogram() β limit is unused.+ ...(version === "v1" ? { limit: 10000 } : {}),},{trpc: {diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsxindex 8e17eed558..885eccbd40 100644--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx@@ -114,6 +114,8 @@ export function ScoreAnalytics(props: {<div className="mb-2 text-sm text-muted-foreground">Total aggregate scores{isNumericDataType(dataType) && (+ // TODO: v2 histogram aggregates all rows server-side (no 10k cap).+ // Make this tooltip conditional on metricsVersion.<DocPopup description="Aggregate of up to 10,000 scores" />)}</div>diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 783825c588..403d2f0cfd 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -33,7 +33,6 @@ import {InvalidRequestError,singleFilter,type FilterState,- type TimeFilter,} from "@langfuse/shared";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { executeQuery } from "@/src/features/query/server/queryExecutor";@@ -86,25 +85,96 @@ const UpdateDashboardFiltersInput = z.object({filters: z.array(singleFilter),});+// Map camelCase legacy column names (used by scoreHistogram component)+// to view-native field names before passing through the general mapper.+const LEGACY_CAMEL_CASE_MAP: Record<string, string> = {+ scoreName: "name",+ scoreSource: "source",+ scoreDataType: "dataType",+};++/**+ * Shared filter preparation for scores-numeric v2 queries.+ * Extracts time boundaries, strips time filters, and maps legacy UI column+ * names to view-native field names.+ */+function prepareScoresNumericV2Params(filter: FilterState) {+ const [from, to] = extractFromAndToTimestampsFromFilter(filter);+ // Fallback to 2000-01-01 instead of epoch 0 β ClickHouse DateTimeFilter+ // passes new Date(value).getTime() as the parameter, and the value 0+ // (epoch) is rejected by ClickHouse's DateTime64(3) parameter parser.+ const fromIso = from?.value+ ? new Date(from.value as Date).toISOString()+ : new Date("2000-01-01T00:00:00.000Z").toISOString();+ const toIso = to?.value+ ? new Date(to.value as Date).toISOString()+ : new Date().toISOString();+ const nonTimeFilters = filter.filter(+ (f) => f.column !== "scoreTimestamp" && f.column !== "startTime",+ );+ const normalizedFilters = nonTimeFilters.map((f) => {+ const mapped = LEGACY_CAMEL_CASE_MAP[f.column];+ return mapped ? { ...f, column: mapped } : f;+ });++ const mappedFilters = mapLegacyUiTableFilterToView(+ "scores-numeric",+ normalizedFilters,+ );+ return { fromIso, toIso, mappedFilters };+}++/**+ * Converts ClickHouse histogram(N)(...) output to the { chartData, chartLabels }+ * shape returned by createHistogramData (used by the NumericScoreHistogram component).+ *+ * ClickHouse histogram() returns an Array(Tuple(Float64, Float64, Float64))+ * where each tuple is (lower_bound, upper_bound, count).+ * The result column is named "histogram_value" by QueryBuilder+ * (pattern: `${aggregation}_${alias}`).+ */+function clickhouseHistogramToChartData(+ result: Array<Record<string, unknown>>,+): {+ chartData: Array<{ binLabel: string; count: number }>;+ chartLabels: string[];+} {+ if (result.length > 0 && !("histogram_value" in result[0])) {+ throw new Error(+ `Expected histogram_value column in QueryBuilder result, got: ${Object.keys(result[0]).join(", ")}`,+ );+ }+ const histogramBins = result[0]?.histogram_value as+ | Array<[number, number, number]>+ | undefined;+ if (!histogramBins?.length) return { chartData: [], chartLabels: [] };++ const round = (v: number) => parseFloat(v.toFixed(2));+ return {+ chartLabels: ["count"],+ chartData: histogramBins.map(([lower, upper, count]) => ({+ binLabel: `[${round(lower)}, ${round(upper)}]`,+ count: Math.round(count),+ })),+ };+}+async function getScoreAggregateV2({projectId,filter,- fromFilter,- toFilter,}: {projectId: string;filter: FilterState;- fromFilter: TimeFilter | undefined;- toFilter: TimeFilter | undefined;}): Promise<DatabaseRow[]> {- const fromIso = fromFilter?.value- ? new Date(fromFilter.value).toISOString()- : new Date(0).toISOString();- const toIso = toFilter?.value- ? new Date(toFilter.value).toISOString()- : new Date().toISOString();-- // Strip time filters, keep non-time filters+ // prepareScoresNumericV2Params also applies LEGACY_CAMEL_CASE_MAP for+ // scoreHistogram callers. For score-aggregate calls, the only camelCase+ // column is "scoreTimestamp" which is stripped as a time filter before+ // LEGACY_CAMEL_CASE_MAP runs, making the normalization step a no-op here.+ const { fromIso, toIso, mappedFilters } =+ prepareScoresNumericV2Params(filter);++ // Non-time filters in their original form β used for categorical query+ // filter mapping and value filter detection below.const nonTimeFilters = filter.filter((f) => f.column !== "scoreTimestamp" && f.column !== "startTime",);@@ -124,7 +194,7 @@ async function getScoreAggregateV2({{ measure: "count", aggregation: "sum" },{ measure: "value", aggregation: "avg" },],- filters: mapLegacyUiTableFilterToView("scores-numeric", nonTimeFilters),+ filters: mappedFilters,};// The scores-categorical view has no "value" dimension, so we handle value@@ -208,8 +278,6 @@ export const dashboardRouter = createTRPCRouter({return getScoreAggregateV2({projectId: input.projectId,filter: input.filter ?? [],- fromFilter: from as TimeFilter | undefined,- toFilter: to as TimeFilter | undefined,});}const scores = await getScoreAggregate(@@ -247,9 +315,35 @@ export const dashboardRouter = createTRPCRouter({sqlInterface.extend({projectId: z.string(),filter: filterInterface.optional(),+ version: viewVersions.optional().default("v1"),}),).query(async ({ input }) => {+ if (input.version === "v2") {+ // v2: ClickHouse histogram() aggregates all matching rows server-side.+ // `input.limit` is ignored β no row-level cap is needed.+ const { fromIso, toIso, mappedFilters } = prepareScoresNumericV2Params(+ input.filter ?? [],+ );+ const histogramQuery: QueryType = {+ view: "scores-numeric",+ dimensions: [],+ metrics: [{ measure: "value", aggregation: "histogram" }],+ filters: mappedFilters,+ fromTimestamp: fromIso,+ toTimestamp: toIso,+ timeDimension: null,+ orderBy: null,+ chartConfig: { type: "HISTOGRAM", bins: 10 },+ };+ const result = await executeQuery(+ input.projectId,+ histogramQuery,+ "v2",+ );+ return clickhouseHistogramToChartData(result);+ }+const data = await getNumericScoreHistogram(input.projectId,input.filter ?? [],