🪢 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
fix(dashboard,widgets): correct silent aggregation errors in score histogram and pivot averages (#15208) (#15209)
Muhammad Hassaan23ce058f5821
diff --git a/web/src/__tests__/server/pivot-table-utils.servertest.ts b/web/src/__tests__/server/pivot-table-utils.servertest.tsindex 2d83e30d8d..ed84f00877 100644--- a/web/src/__tests__/server/pivot-table-utils.servertest.ts+++ b/web/src/__tests__/server/pivot-table-utils.servertest.ts@@ -353,10 +353,49 @@ describe("pivot-table-utils", () => {expect(result).toEqual({count: 45,- avg_cost: 0.5,+ // count-weighted average, not an average of averages:+ // (0.5*10 + 0.6*15 + 0.4*20) / (10+15+20) = 22/45+ avg_cost: 0.4888888889,});});+ it("never lets metric order pick the weight for an average", () => {+ // Each average is weighted by its own count_<measure>, in either order.+ const paired: DatabaseRow[] = [+ { count_cost: 10, count_latency: 1, avg_cost: 1, avg_latency: 100 },+ { count_cost: 1, count_latency: 10, avg_cost: 3, avg_latency: 200 },+ ];+ const metrics = [+ "count_cost",+ "count_latency",+ "avg_cost",+ "avg_latency",+ ];+ const expected = {+ count_cost: 11,+ count_latency: 11,+ avg_cost: 1.1818181818, // (1*10 + 3*1) / 11+ avg_latency: 190.9090909091, // (100*1 + 200*10) / 11+ };+ expect(calculateSubtotals(paired, metrics)).toEqual(expected);+ expect(calculateSubtotals(paired, [...metrics].reverse())).toEqual(+ expected,+ );++ // Two unrelated count columns and no match: unweighted mean, not a guess.+ const ambiguous: DatabaseRow[] = [+ { count_traces: 10, count_observations: 30, avg_latency: 100 },+ { count_traces: 5, count_observations: 25, avg_latency: 200 },+ ];+ expect(+ calculateSubtotals(ambiguous, [+ "count_observations",+ "count_traces",+ "avg_latency",+ ]).avg_latency,+ ).toBe(150);+ });+it("should handle missing values", () => {const data: DatabaseRow[] = [{ count: 10 },@@ -368,7 +407,10 @@ describe("pivot-table-utils", () => {expect(result).toEqual({count: 25,- avg_cost: 0.3,+ // Weighted by count (missing fields coerce to 0, as elsewhere in this+ // file): (0*10 + 0.6*15) / (10+15) = 0.36. The row with no count carries+ // no weight and drops out.+ avg_cost: 0.36,});});@@ -388,7 +430,9 @@ describe("pivot-table-utils", () => {expect(result).toEqual({count: 75, // 10 + 15 + 20 + 25 + 5- avg_cost: 0.5, // (0.5 + 0.6 + 0.2 + 0.4 + 0.8) / 5+ // count-weighted average, not an average of averages:+ // (0.5*10 + 0.6*15 + 0.2*20 + 0.4*25 + 0.8*5) / 75 = 32/75+ avg_cost: 0.4266666667,});});@@ -456,7 +500,8 @@ describe("pivot-table-utils", () => {});expect(result[0].values).toEqual({count: 75,- avg_cost: 0.5,+ // count-weighted grand-total average (32/75), see calculateGrandTotals+ avg_cost: 0.4266666667,});});@@ -767,8 +812,10 @@ describe("pivot-table-utils", () => {// Sum should be summed: 5000 + 8000 + 2500 = 15500expect(totalRow.values.sum_tokens).toBe(15500);- // Average should be averaged: (120 + 80 + 140) / 3 = 113.33...- expect(totalRow.values.avg_latency).toBeCloseTo(113.33, 2);+ // Average is weighted by each row's count, so the total equals the+ // true overall average rather than an average of averages:+ // (120*100 + 80*200 + 140*50) / 350 = 35000 / 350 = 100+ expect(totalRow.values.avg_latency).toBeCloseTo(100, 2);// Min should be minimum: min(0.05, 0.02, 0.06) = 0.02expect(totalRow.values.min_cost).toBe(0.02);@@ -776,8 +823,10 @@ describe("pivot-table-utils", () => {// Max should be maximum: max(0.15, 0.08, 0.18) = 0.18expect(totalRow.values.max_cost).toBe(0.18);- // Percentile should be averaged: (250 + 150 + 300) / 3 = 233.33...- expect(totalRow.values.p95_duration).toBeCloseTo(233.33, 2);+ // Percentiles cannot be recombined exactly, but weighting by count is+ // strictly closer than an unweighted mean of per-group percentiles:+ // (250*100 + 150*200 + 300*50) / 350 = 70000 / 350 = 200+ expect(totalRow.values.p95_duration).toBeCloseTo(200, 2);}});@@ -843,8 +892,9 @@ describe("pivot-table-utils", () => {// Count: 100 + 200 = 300 (strings parsed correctly)expect(totalRow.values.count_requests).toBe(300);- // Average: (120.5 + 80.2) / 2 = 100.35- expect(totalRow.values.avg_latency).toBeCloseTo(100.35, 2);+ // Average weighted by count (strings parsed correctly):+ // (120.5*100 + 80.2*200) / 300 = 28090 / 300 = 93.6333...+ expect(totalRow.values.avg_latency).toBeCloseTo(93.6333, 2);// Sum: 5000 + 8000 = 13000 (strings parsed correctly)expect(totalRow.values.sum_tokens).toBe(13000);@@ -928,8 +978,9 @@ describe("pivot-table-utils", () => {// Production tokens: 5000 + 8000 = 13000expect(productionSubtotal.values.sum_tokens).toBe(13000);- // Production avg latency: (120 + 80) / 2 = 100- expect(productionSubtotal.values.avg_latency).toBe(100);+ // Production avg latency weighted by count:+ // (120*100 + 80*200) / 300 = 28000 / 300 = 93.333...+ expect(productionSubtotal.values.avg_latency).toBeCloseTo(93.3333, 2);// Production min cost: min(0.05, 0.02) = 0.02expect(productionSubtotal.values.min_cost).toBe(0.02);diff --git a/web/src/features/dashboard/lib/score-analytics-utils.clienttest.ts b/web/src/features/dashboard/lib/score-analytics-utils.clienttest.tsnew file mode 100644index 0000000000..cf7196cefb--- /dev/null+++ b/web/src/features/dashboard/lib/score-analytics-utils.clienttest.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";+import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";+import { createHistogramData } from "@/src/features/dashboard/lib/score-analytics-utils";++const rows = (values: number[]): DatabaseRow[] =>+ values.map((value) => ({ value }) as unknown as DatabaseRow);++describe("createHistogramData", () => {+ it("bins values by their raw magnitude, not a 2-decimal rounding of them", () => {+ // 0.146 belongs in [0.14, 0.15). The previous implementation rounded values+ // to 2 decimals before binning, so 0.146 -> 0.15 landed in the next bin.+ const { chartData } = createHistogramData(rows([0.14, 0.146, 0.16]), 2, 10);++ expect(chartData).toHaveLength(2);+ expect(chartData[0]).toMatchObject({ binLabel: "[0.14, 0.15]", count: 2 });+ expect(chartData[1]).toMatchObject({ binLabel: "[0.15, 0.16]", count: 1 });+ });++ it("does not push a value into a bucket whose range excludes it", () => {+ // Regression for the reported symptom: a score of 0.857 was counted in the+ // "[0.86, 1]" bucket. It must land in the bucket that actually contains it.+ const { chartData } = createHistogramData(rows([0, 0.857, 0.86, 1]), 7, 7);++ const topBin = chartData[chartData.length - 1];+ expect(topBin.binLabel).toBe("[0.86, 1]");+ expect(topBin.count).toBe(2); // 0.86 and 1.0 — NOT 0.857++ const bin = chartData[5];+ expect(bin.binLabel).toBe("[0.71, 0.86]");+ expect(bin.count).toBe(1); // 0.857+ });++ it("preserves the total count across all bins", () => {+ const values = [0.1, 0.25, 0.4, 0.55, 0.7, 0.85, 0.99, 0.05, 0.5, 0.95];+ const { chartData } = createHistogramData(rows(values));+ const total = chartData.reduce((sum, bin) => sum + bin.count, 0);+ expect(total).toBe(values.length);+ });++ it("does not emit degenerate zero-width labels for narrow ranges", () => {+ const { chartData } = createHistogramData(+ rows([0.801, 0.803, 0.811, 0.822, 0.828, 0.834, 0.841, 0.849]),+ );+ for (const bin of chartData) {+ const [lo, hi] = bin.binLabel+ .replace(/[[\]]/g, "")+ .split(",")+ .map((s) => parseFloat(s));+ expect(hi).toBeGreaterThan(lo); // never "[0.85, 0.85]"+ }+ });++ it("handles identical values as a single populated bin", () => {+ const { chartData } = createHistogramData(rows([0.5, 0.5, 0.5]));+ expect(chartData).toHaveLength(1);+ expect(chartData[0].count).toBe(3);+ });++ it("returns empty data for no values", () => {+ expect(createHistogramData(rows([]))).toEqual({+ chartData: [],+ chartLabels: [],+ });+ });+});diff --git a/web/src/features/dashboard/lib/score-analytics-utils.ts b/web/src/features/dashboard/lib/score-analytics-utils.tsindex 7dc1ac0954..3099537bb4 100644--- a/web/src/features/dashboard/lib/score-analytics-utils.ts+++ b/web/src/features/dashboard/lib/score-analytics-utils.ts@@ -40,6 +40,15 @@ function computeBinSize(: Math.min(Math.max(minBins, Math.floor(Math.sqrt(valueCount))), maxBins);}+// Decimals needed so adjacent bin edges stay distinct in labels. Values are+// binned on their raw magnitude (see below); rounding is display-only. Without+// this, small ranges collapse edges to the same 2dp value and produce+// degenerate labels like "[0.85, 0.85]".+function labelPrecision(binSize: number): number {+ if (!Number.isFinite(binSize) || binSize <= 0 || binSize >= 1) return 2;+ return Math.min(10, Math.max(2, -Math.floor(Math.log10(binSize)) + 1));+}+export function createHistogramData(data: DatabaseRow[],minBins = 1,@@ -49,8 +58,14 @@ export function createHistogramData(if (!Boolean(numericScoreValues.length))return { chartData: [], chartLabels: [] };- const min = round(Math.min(...numericScoreValues));- const range = round(Math.max(...numericScoreValues)) - min;+ // Bin edges are derived from the RAW min/max, and values are assigned by their+ // RAW magnitude. Previously both were rounded to 2 decimals before binning,+ // which pushed values across boundaries (e.g. 0.857 counted in the "[0.86, 1]"+ // bucket) and disagreed with a standard histogram. Rounding is now applied to+ // the display labels only.+ const min = Math.min(...numericScoreValues);+ const max = Math.max(...numericScoreValues);+ const range = max - min;const bins = computeBinSize(minBins,maxBins,@@ -58,17 +73,19 @@ export function createHistogramData(numericScoreValues.length,);const binSize = range / bins || 1;+ const precision = labelPrecision(binSize);const baseChartData = Array.from({ length: bins }).map((_, index: number) => ({count: 0,- binLabel: `[${round(min + index * binSize)}, ${round(min + (index + 1) * binSize)}]`,+ binLabel: `[${round(min + index * binSize, precision)}, ${round(min + (index + 1) * binSize, precision)}]`,}),);const chartData = numericScoreValues.reduce((acc, value) => {- const shiftedValue = round(value) - min;- const binIndex = Math.min(Math.floor(shiftedValue / binSize), bins - 1);+ // The maximum value falls into the last (closed) bin, matching a standard+ // equal-width histogram.+ const binIndex = Math.min(Math.floor((value - min) / binSize), bins - 1);acc[binIndex].count++;return acc;}, baseChartData);diff --git a/web/src/features/widgets/utils/pivot-table-utils.ts b/web/src/features/widgets/utils/pivot-table-utils.tsindex 9810f74183..e33cd7db18 100644--- a/web/src/features/widgets/utils/pivot-table-utils.ts+++ b/web/src/features/widgets/utils/pivot-table-utils.ts@@ -507,8 +507,9 @@ function applyAggregation(values: number[], aggregationType: string): number {return Math.max(...values);case "percentile":- // For percentiles in subtotals/totals, we'll use the average of the percentile values- // This is a reasonable approximation since we can't recalculate the true percentile+ // Percentiles cannot be recalculated exactly from per-group percentiles;+ // this unweighted mean is only the fallback used when no count/weight+ // metric is available (see calculateSubtotals for the weighted path).return values.reduce((sum, val) => sum + val, 0) / values.length;default:@@ -517,6 +518,46 @@ function applyAggregation(values: number[], aggregationType: string): number {}}+/**+ * Picks the column to weight `metric` by when aggregating per-row averages:+ * its own `count_<measure>`, else the row count (`count_count` or `count`),+ * else the only count column. With several unrelated count columns there is no+ * safe choice, so this returns null rather than letting metric order decide.+ */+function findWeightMetric(metric: string, metrics: string[]): string | null {+ const counts = metrics.filter(+ (m) =>+ m !== metric &&+ (detectAggregationType(m) === "count" ||+ m.toLowerCase().startsWith("count")),+ );+ const measure = metric.slice(metric.indexOf("_") + 1);++ return (+ counts.find((m) => m === `count_${measure}`) ??+ counts.find((m) => m === "count_count" || m === "count") ??+ (counts.length === 1 ? counts[0] : null)+ );+}++/**+ * Weighted mean of (value, weight) pairs, or null when the total weight is 0+ * (so callers can fall back to an unweighted aggregation).+ */+function weightedMean(+ pairs: Array<{ value: number; weight: number }>,+): number | null {+ let weightedSum = 0;+ let totalWeight = 0;+ for (const { value, weight } of pairs) {+ if (weight > 0) {+ weightedSum += value * weight;+ totalWeight += weight;+ }+ }+ return totalWeight > 0 ? weightedSum / totalWeight : null;+}+/*** Calculates subtotals for a group of data rows* Aggregates metric values across all rows in the group using the correct aggregation function@@ -532,14 +573,38 @@ export function calculateSubtotals(const subtotals: Record<string, number> = {};for (const metric of metrics) {- // Extract all values for this metric using the utility function- const values = data- .map((row) => extractMetricValues(row, [metric])[metric])- .filter(isNotNullOrUndefined);-- // Detect aggregation type and apply correct functionconst aggregationType = detectAggregationType(metric);- const result = applyAggregation(values, aggregationType);+ const weightMetric =+ aggregationType === "avg" || aggregationType === "percentile"+ ? findWeightMetric(metric, metrics)+ : null;++ let result: number;+ if (weightMetric) {+ // Weight each row's value by its count so the group aggregate equals the+ // true overall average (rather than an average of averages). Missing+ // fields coerce to 0 via extractMetricValues, as elsewhere in this file;+ // a row with no count carries weight 0 and drops out of the weighted mean.+ const pairs = data.map((row) => {+ const extracted = extractMetricValues(row, [metric, weightMetric]);+ return { value: extracted[metric], weight: extracted[weightMetric] };+ });++ const weighted = weightedMean(pairs);+ result =+ weighted ??+ // No usable weights (e.g. no count column populated) → best-effort+ // unweighted aggregation, matching prior behavior.+ applyAggregation(+ pairs.map((p) => p.value),+ aggregationType,+ );+ } else {+ const values = data+ .map((row) => extractMetricValues(row, [metric])[metric])+ .filter(isNotNullOrUndefined);+ result = applyAggregation(values, aggregationType);+ }// Round to 10 decimal places to avoid floating-point precision issuessubtotals[metric] = Math.round(result * 1e10) / 1e10;