Skip to content

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

fix(score-analytics): categorical distribution improvements (LF-1987) (#10293)

Michael Fröhlichfdd65c873445
diff --git a/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx b/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
index 1e36fde420..a2d84886ad 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
@@ -14,6 +14,82 @@ import { getScoreCategoryColors } from "../../libs/color-scales";
type DistributionTab = "score1" | "score2" | "all" | "matched";
+/**
+ * Calculate score2 items that have no matching score1 items
+ * by comparing total score2Individual counts vs matched counts in stackedDistribution
+ */
+function calculateUnmatchedScore2Distribution(
+ score2Individual: Array<{ binIndex: number; count: number }>,
+ stackedDistribution: Array<{
+ score1Category: string;
+ score2Stack: string;
+ count: number;
+ }>,
+ score2Categories: string[],
+): Array<{
+ score1Category: string;
+ score2Stack: string;
+ count: number;
+}> {
+ // Helper to check if a key represents an unmatched category
+ const isUnmatchedKey = (key: string): boolean => {
+ return (
+ key === "__unmatched__" || key === "0" || key === "" || key === "null"
+ );
+ };
+
+ // Build total counts map from score2Individual
+ const totalCountsMap = new Map<string, number>();
+ score2Individual.forEach((item) => {
+ // Bounds check
+ if (item.binIndex >= 0 && item.binIndex < score2Categories.length) {
+ const category = score2Categories[item.binIndex];
+ if (category) {
+ totalCountsMap.set(category, item.count);
+ }
+ }
+ });
+
+ // Build matched counts map, excluding already-unmatched items
+ const matchedCountsMap = new Map<string, number>();
+ stackedDistribution.forEach((item) => {
+ // Skip existing unmatched markers
+ if (
+ !isUnmatchedKey(item.score2Stack) &&
+ !isUnmatchedKey(item.score1Category)
+ ) {
+ const currentCount = matchedCountsMap.get(item.score2Stack) || 0;
+ matchedCountsMap.set(item.score2Stack, currentCount + item.count);
+ }
+ });
+
+ // Calculate unmatched counts with edge case handling
+ const unmatchedDistribution: Array<{
+ score1Category: string;
+ score2Stack: string;
+ count: number;
+ }> = [];
+
+ score2Categories.forEach((category) => {
+ const totalCount = totalCountsMap.get(category) || 0;
+ const matchedCount = matchedCountsMap.get(category) || 0;
+
+ // Prevent negative counts (edge case: race conditions)
+ const unmatchedCount = Math.max(0, totalCount - matchedCount);
+
+ // Only add if there are unmatched items
+ if (unmatchedCount > 0) {
+ unmatchedDistribution.push({
+ score1Category: "__unmatched__",
+ score2Stack: category,
+ count: unmatchedCount,
+ });
+ }
+ });
+
+ return unmatchedDistribution;
+}
+
/**
* DistributionCategoricalCard - Distribution chart card for CATEGORICAL scores
*
@@ -75,14 +151,28 @@ export function DistributionCategoricalCard() {
score2Categories: undefined,
description: `${score2?.name ?? "Score 2"} - ${statistics.score2?.total.toLocaleString()} observations`,
};
- case "all":
+ case "all": {
+ // Calculate unmatched score2 items and augment stackedDistribution
+ const unmatchedScore2 = calculateUnmatchedScore2Distribution(
+ distribution.score2Individual,
+ distribution.stackedDistribution ?? [],
+ distribution.score2Categories ?? [],
+ );
+
+ // Combine original stacked data with unmatched score2 items
+ const augmentedStackedDistribution = [
+ ...(distribution.stackedDistribution ?? []),
+ ...unmatchedScore2,
+ ];
+
return {
- distribution1: distribution.score1Individual,
+ distribution1: undefined, // Not used in stacked mode
categories: distribution.categories ?? [],
- stackedDistribution: undefined,
+ stackedDistribution: augmentedStackedDistribution,
score2Categories: distribution.score2Categories ?? [],
description: `${score1.name} (${statistics.score1.total.toLocaleString()}) vs ${score2?.name} (${statistics.score2?.total.toLocaleString()})`,
};
+ }
case "matched":
return {
distribution1: undefined, // Not used in stacked mode
diff --git a/web/src/features/scores/components/score-analytics/components/charts/Heatmap.tsx b/web/src/features/scores/components/score-analytics/components/charts/Heatmap.tsx
index 3184ee363a..fbe2629c48 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/Heatmap.tsx
+++ b/web/src/features/scores/components/score-analytics/components/charts/Heatmap.tsx
@@ -117,35 +117,19 @@ export function Heatmap({
if (rowLabelsRef.current && rowLabels && rowLabels.length > 0) {
const container = rowLabelsRef.current;
- console.log("[Heatmap] Container measurements:", {
- clientWidth: container.clientWidth,
- scrollWidth: container.scrollWidth,
- offsetWidth: container.offsetWidth,
- });
-
// Find the widest label by measuring each label element
const labelElements = container.querySelectorAll("span");
let maxLabelWidth = 0;
- labelElements.forEach((element, idx) => {
+ labelElements.forEach((element) => {
const width = element.offsetWidth;
- console.log(
- `[Heatmap] Label ${idx} width:`,
- width,
- "text:",
- element.textContent,
- );
maxLabelWidth = Math.max(maxLabelWidth, width);
});
- console.log("[Heatmap] Max label width found:", maxLabelWidth);
-
// Add padding (pr-1 is 4px on small screens, pr-2 is 8px on larger)
const totalWidth = maxLabelWidth + 8;
- console.log("[Heatmap] Total width with padding:", totalWidth);
const finalWidth = Math.max(36, Math.min(totalWidth, 120)); // Min 36px, max 120px
- console.log("[Heatmap] Final constrained width:", finalWidth);
setRowLabelsWidth(finalWidth);
}
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreChartLegendContent.tsx b/web/src/features/scores/components/score-analytics/components/charts/ScoreChartLegendContent.tsx
index 496cb91a4a..25da918ef1 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreChartLegendContent.tsx
+++ b/web/src/features/scores/components/score-analytics/components/charts/ScoreChartLegendContent.tsx
@@ -423,16 +423,10 @@ export const ScoreChartLegendContent = React.forwardRef<
? (item.payload as { fill: string }).fill
: "hsl(var(--chart-1))");
- // Special color for "unmatched" category
- const isUnmatched = key === "__unmatched__" || key === "unmatched";
- const finalColor = isUnmatched
- ? "hsl(var(--muted-foreground))"
- : color;
-
return (
<LegendItem
key={key}
- color={finalColor}
+ color={color}
label={getFormattedLabel(item)}
visible={visible}
interactive={interactive}
@@ -493,19 +487,13 @@ export const ScoreChartLegendContent = React.forwardRef<
? (item.payload as { fill: string }).fill
: "hsl(var(--chart-1))");
- const isUnmatched =
- key === "__unmatched__" || key === "unmatched";
- const finalColor = isUnmatched
- ? "hsl(var(--muted-foreground))"
- : color;
-
return (
<div
key={key}
className="rounded-sm px-2 py-1.5 hover:bg-accent/50"
>
<LegendItem
- color={finalColor}
+ color={color}
label={getFormattedLabel(item)}
visible={visible}
interactive={interactive}
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx b/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
index b1d9ab5c49..53946181ad 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
+++ b/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
@@ -43,6 +43,14 @@ export function ScoreDistributionCategoricalChart({
stackedDistribution && stackedDistribution.length > 0,
);
+ // Helper: Check if a key represents an unmatched category
+ // Backend can send: "__unmatched__", "0", "", or null
+ const isUnmatchedKey = (key: string): boolean => {
+ return (
+ key === "__unmatched__" || key === "0" || key === "" || key === "null"
+ );
+ };
+
// Calculate all possible stack keys from actual data
// This ensures we include ALL categories present in the data, including those
// not in score2Categories (e.g., "0" or other values) and __unmatched__
@@ -57,17 +65,21 @@ export function ScoreDistributionCategoricalChart({
stacksFromData.add(item.score2Stack);
});
+ // Normalize all unmatched variations to "__unmatched__" for consistent handling
+ const normalizedStacks = Array.from(stacksFromData).map((key) =>
+ isUnmatchedKey(key) ? "__unmatched__" : key,
+ );
+
// Separate regular categories from __unmatched__
// This ensures __unmatched__ is always last for consistent color assignment
const regularStacks = Array.from(
- new Set([...Array.from(stacksFromData), ...score2Categories]),
+ new Set([...normalizedStacks, ...score2Categories]),
)
.filter((key) => key !== "__unmatched__")
- .sort();
+ .sort(); // Sort alphabetically for stable color assignment
// Add __unmatched__ at the end if it exists in the actual data
- // Don't add it based on score2Categories since that never includes __unmatched__
- const hasUnmatched = stacksFromData.has("__unmatched__");
+ const hasUnmatched = normalizedStacks.includes("__unmatched__");
return hasUnmatched ? [...regularStacks, "__unmatched__"] : regularStacks;
}, [hasStackedData, stackedDistribution, score2Categories]);
@@ -82,19 +94,28 @@ export function ScoreDistributionCategoricalChart({
if (!grouped.has(item.score1Category)) {
grouped.set(item.score1Category, {});
}
- grouped.get(item.score1Category)![item.score2Stack] = item.count;
+ // Normalize unmatched keys to "__unmatched__"
+ const normalizedKey = isUnmatchedKey(item.score2Stack)
+ ? "__unmatched__"
+ : item.score2Stack;
+ grouped.get(item.score1Category)![normalizedKey] = item.count;
});
// Normalize: ensure every category has all stack keys, even if count is 0
return Array.from(grouped.entries())
- .sort()
+ .sort((a, b) => {
+ // Put __unmatched__ last (rightmost column)
+ if (a[0] === "__unmatched__") return 1;
+ if (b[0] === "__unmatched__") return -1;
+ return a[0].localeCompare(b[0]);
+ })
.map(([category, stacks]) => {
const normalizedStacks: Record<string, number> = {};
allStackKeys.forEach((stackKey) => {
normalizedStacks[stackKey] = stacks[stackKey] ?? 0;
});
return {
- name: category,
+ name: category === "__unmatched__" ? "no match" : category,
...normalizedStacks,
};
});
@@ -154,30 +175,36 @@ export function ScoreDistributionCategoricalChart({
// Stacked mode: create config for all stack keys using color mappings
const stackConfig: ChartConfig = {};
allStackKeys.forEach((key) => {
+ // Special handling for unmatched category
+ if (key === "__unmatched__") {
+ stackConfig[key] = {
+ label: "no match",
+ color: "hsl(var(--muted))", // Light grey for unmatched
+ };
+ return;
+ }
+
// Try namespaced key first (for when score1 and score2 have same category names)
// Format: "ScoreName (source): category"
let color: string | undefined;
- if (key !== "__unmatched__" && score2Name && score2Source) {
+ if (score2Name && score2Source) {
const namespacedKey = `${score2Name} (${score2Source}): ${key}`;
color = colors[namespacedKey];
}
// Fallback to non-namespaced key
- if (!color && key !== "__unmatched__") {
+ if (!color) {
color = colors[key];
}
- // Final fallback
+ // Final fallback to first available color
if (!color) {
- color =
- key === "__unmatched__"
- ? "hsl(var(--muted-foreground))"
- : Object.values(colors)[0];
+ color = Object.values(colors)[0];
}
stackConfig[key] = {
- label: key === "__unmatched__" ? "Unmatched" : key,
+ label: key,
color,
};
});
diff --git a/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts b/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
index e632c42e32..f385fbb733 100644
--- a/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
+++ b/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
@@ -232,6 +232,15 @@ export function useScoreAnalyticsQuery(
stackedDistribution: apiData.stackedDistribution,
});
+ // Extract score2 categories for proper binning
+ // When comparing two different categorical scores, score2 may have different categories
+ const score2Categories =
+ apiData.score2Categories && apiData.score2Categories.length > 0
+ ? apiData.score2Categories
+ : mode === "two" && categories
+ ? categories // Fallback to score1 categories if score2Categories empty
+ : undefined;
+
// ========================================================================
// 2. Fill distribution bins (categorical/boolean only)
// Note: Sort all distributions by binIndex to ensure deterministic ordering
@@ -253,8 +262,9 @@ export function useScoreAnalyticsQuery(
.slice()
.sort((a, b) => a.binIndex - b.binIndex);
- const distribution2Individual = categories
- ? fillDistributionBins(apiData.distribution2Individual, categories)
+ // Use score2Categories for score2Individual (not score1 categories)
+ const distribution2Individual = score2Categories
+ ? fillDistributionBins(apiData.distribution2Individual, score2Categories)
: apiData.distribution2Individual
.slice()
.sort((a, b) => a.binIndex - b.binIndex);
@@ -265,8 +275,9 @@ export function useScoreAnalyticsQuery(
.slice()
.sort((a, b) => a.binIndex - b.binIndex);
- const distribution2Matched = categories
- ? fillDistributionBins(apiData.distribution2Matched, categories)
+ // Use score2Categories for score2Matched (not score1 categories)
+ const distribution2Matched = score2Categories
+ ? fillDistributionBins(apiData.distribution2Matched, score2Categories)
: apiData.distribution2Matched
.slice()
.sort((a, b) => a.binIndex - b.binIndex);
diff --git a/web/src/features/scores/components/score-analytics/libs/ScoreChartTooltip.tsx b/web/src/features/scores/components/score-analytics/libs/ScoreChartTooltip.tsx
index 5758d070bd..df014755ad 100644
--- a/web/src/features/scores/components/score-analytics/libs/ScoreChartTooltip.tsx
+++ b/web/src/features/scores/components/score-analytics/libs/ScoreChartTooltip.tsx
@@ -65,14 +65,31 @@ export function ScoreChartTooltip({
return null;
}
- // Filter out duplicates and sort by value in descending order
+ // Filter out duplicates
const uniquePayload = Array.from(
new Map(payload.map((item) => [item.name ?? item.dataKey, item])).values(),
);
- const sortedPayload = uniquePayload.sort(
- (a, b) => (Number(b.value) ?? 0) - (Number(a.value) ?? 0),
- );
+ // Sort payload by config key order for stable tooltip across columns
+ // This maintains consistent ordering (e.g., alphabetical + unmatched last)
+ // REVERSED to mirror the visual stack order (bottom-to-top becomes top-to-bottom in tooltip)
+ // Falls back to value-based sorting if config keys not available
+ const configKeys = Object.keys(config);
+ const sortedPayload = uniquePayload.sort((a, b) => {
+ const keyA = a.name ?? a.dataKey ?? "";
+ const keyB = b.name ?? b.dataKey ?? "";
+
+ // If both keys exist in config, sort by config order (reversed)
+ const indexA = configKeys.indexOf(keyA);
+ const indexB = configKeys.indexOf(keyB);
+
+ if (indexA !== -1 && indexB !== -1) {
+ return indexB - indexA; // Reversed: mirror visual stack order
+ }
+
+ // Fallback to value-based sorting (descending) for non-config keys
+ return (Number(b.value) ?? 0) - (Number(a.value) ?? 0);
+ });
// Format the label (timestamp)
let formattedLabel: string;
diff --git a/web/src/features/scores/components/score-analytics/libs/color-scales.ts b/web/src/features/scores/components/score-analytics/libs/color-scales.ts
index 03d058b2f7..25b7513230 100644
--- a/web/src/features/scores/components/score-analytics/libs/color-scales.ts
+++ b/web/src/features/scores/components/score-analytics/libs/color-scales.ts
@@ -404,6 +404,11 @@ export function getMonochromeScale(
/**
* Get monochrome color mapping for categorical values
* All categories of the same score use shades of the same base color
+ *
+ * IMPORTANT: Sorts categories alphabetically before assigning colors to ensure
+ * stable color assignment regardless of category order in the input array.
+ * This prevents colors from shifting when categories are hidden/shown.
+ *
* @param scoreNumber - Which score (1 or 2)
* @param categories - Array of category names
* @param options - Optional configuration
@@ -417,17 +422,21 @@ export function getScoreCategoryColors(
const baseColor =
scoreNumber === 1 ? SCORE_BASE_COLORS.score1 : SCORE_BASE_COLORS.score2;
+ // Sort categories alphabetically for stable color assignment
+ // This ensures the same category always gets the same color
+ const sortedCategories = [...categories].sort();
+
// Generate scale with even distribution across percentage range
// Wider range (20%-100%) for better distinction between categories
- const steps = Math.max(categories.length, 2);
+ const steps = Math.max(sortedCategories.length, 2);
const colors = getMonochromeScale(baseColor, steps, "white", 0.2, 1.0);
// Reverse if requested (for different visual ordering)
const colorArray = options?.reverse ? [...colors].reverse() : colors;
- // Map categories to colors
+ // Map categories to colors using sorted order
const mapping: Record<string, string> = {};
- categories.forEach((category, index) => {
+ sortedCategories.forEach((category, index) => {
mapping[category] = colorArray[index] || colorArray[0];
});