Skip to content

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

chore(score-analytics): refactor directory structure (#10415)

Michael Fröhlichd0f229438d9f
diff --git a/web/src/__tests__/async/score-comparison-analytics.servertest.ts b/web/src/__tests__/async/score-comparison-analytics.servertest.ts
index 35fe3771f3..9d3f8561b2 100644
--- a/web/src/__tests__/async/score-comparison-analytics.servertest.ts
+++ b/web/src/__tests__/async/score-comparison-analytics.servertest.ts
@@ -52,6 +52,7 @@ describe("Score Comparison Analytics tRPC", () => {
admin: true,
},
environment: {} as any,
+ expires: new Date().toISOString(),
};
const ctx = createInnerTRPCContext({ session, headers: {} });
@@ -98,7 +99,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh([score1, score2]);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: scoreName1,
@@ -161,7 +162,7 @@ describe("Score Comparison Analytics tRPC", () => {
const fromTimestamp = new Date("2020-01-01");
const toTimestamp = new Date("2020-01-02");
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: "nonexistent1",
@@ -200,7 +201,7 @@ describe("Score Comparison Analytics tRPC", () => {
const now = new Date();
await expect(
- caller.scores.getScoreComparisonAnalytics({
+ caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: "score1",
@@ -220,7 +221,7 @@ describe("Score Comparison Analytics tRPC", () => {
).rejects.toThrow();
await expect(
- caller.scores.getScoreComparisonAnalytics({
+ caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: "score1",
@@ -280,7 +281,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh([score1, score2]);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: scoreName1,
@@ -393,7 +394,7 @@ describe("Score Comparison Analytics tRPC", () => {
console.log(`Inserted ${batchSize} traces and ${batchSize * 2} scores`);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: scoreName1,
@@ -530,7 +531,7 @@ describe("Score Comparison Analytics tRPC", () => {
console.log(`Inserted ${batchSize} traces and ${batchSize * 2} scores`);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: scoreName1,
@@ -655,7 +656,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createTracesCh(tracesBatch);
await createScoresCh([...score1Batch, ...score2Batch]);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: scoreName1,
@@ -760,7 +761,7 @@ describe("Score Comparison Analytics tRPC", () => {
console.log(`Inserted ${batchSize} traces and scores`);
// Compare score to itself
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: {
name: scoreName,
@@ -795,12 +796,12 @@ describe("Score Comparison Analytics tRPC", () => {
// Verify all heatmap points are on the diagonal (bin1Index === bin2Index)
// For identical scores, every point should have the same bin for both axes
const offDiagonalPoints = result.heatmap.filter(
- (point) => point.bin1Index !== point.bin2Index,
+ (point) => point.binX !== point.binY,
);
expect(offDiagonalPoints.length).toBe(0); // No points off diagonal
// Verify correlation is skipped for identical scores (as per existing logic)
- expect(result.statistics.spearmanCorrelation).toBeNull();
+ expect(result.statistics?.spearmanCorrelation).toBeNull();
}, 180000); // 3 minute timeout for large data insertion
// Test 9: Calculates counts correctly with partial matches
@@ -868,7 +869,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -926,7 +927,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -984,7 +985,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1057,7 +1058,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
// Test with 5 bins
- const result5 = await caller.scores.getScoreComparisonAnalytics({
+ const result5 = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1073,7 +1074,7 @@ describe("Score Comparison Analytics tRPC", () => {
});
// Test with 20 bins
- const result20 = await caller.scores.getScoreComparisonAnalytics({
+ const result20 = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1133,7 +1134,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1197,7 +1198,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "BOOLEAN", source: "API" },
score2: { name: scoreName2, dataType: "BOOLEAN", source: "API" },
@@ -1271,7 +1272,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "CATEGORICAL", source: "API" },
score2: { name: scoreName2, dataType: "CATEGORICAL", source: "API" },
@@ -1348,7 +1349,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1409,7 +1410,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1504,7 +1505,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh([...scores, ...matchedScores]);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1586,7 +1587,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1646,28 +1647,30 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
// Test 7-day interval (week equivalent)
- const weekResult = await caller.scores.getScoreComparisonAnalytics({
- projectId,
- score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
- score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
- fromTimestamp,
- toTimestamp,
- interval: { count: 7, unit: "day" },
- nBins: 10,
- });
+ const weekResult =
+ await caller.scoreAnalytics.getScoreComparisonAnalytics({
+ projectId,
+ score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
+ score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 7, unit: "day" },
+ nBins: 10,
+ });
expect(weekResult.timeSeries.length).toBeGreaterThan(0);
// Test month interval
- const monthResult = await caller.scores.getScoreComparisonAnalytics({
- projectId,
- score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
- score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
- fromTimestamp,
- toTimestamp,
- interval: { count: 1, unit: "month" },
- nBins: 10,
- });
+ const monthResult =
+ await caller.scoreAnalytics.getScoreComparisonAnalytics({
+ projectId,
+ score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
+ score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 1, unit: "month" },
+ nBins: 10,
+ });
expect(monthResult.timeSeries.length).toBeGreaterThan(0);
});
@@ -1712,7 +1715,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1779,7 +1782,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1853,7 +1856,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1935,7 +1938,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -1995,7 +1998,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2089,7 +2092,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2152,7 +2155,7 @@ describe("Score Comparison Analytics tRPC", () => {
);
const toTimestamp = new Date(monday.getTime() + 24 * 60 * 60 * 1000); // Day after Monday
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2249,7 +2252,7 @@ describe("Score Comparison Analytics tRPC", () => {
const fromTimestamp = new Date(day.getTime() - 24 * 60 * 60 * 1000); // Day before
const toTimestamp = new Date(day.getTime() + 2 * 24 * 60 * 60 * 1000); // Day after
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2371,7 +2374,7 @@ describe("Score Comparison Analytics tRPC", () => {
const fromTimestamp = new Date("2025-10-01T00:00:00.000Z"); // Oct 1
const toTimestamp = new Date("2025-12-01T00:00:00.000Z"); // Dec 1
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2467,7 +2470,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2549,7 +2552,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2667,7 +2670,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2746,7 +2749,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2837,7 +2840,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -2916,7 +2919,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "CATEGORICAL", source: "API" },
score2: { name: scoreName2, dataType: "CATEGORICAL", source: "API" },
@@ -2974,7 +2977,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "CATEGORICAL", source: "API" },
@@ -3114,7 +3117,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -3238,7 +3241,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -3346,7 +3349,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
// Query with same score for both score1 and score2 (single-score mode)
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName, dataType: "NUMERIC", source: "API" },
@@ -3406,7 +3409,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -3493,7 +3496,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -3553,7 +3556,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -3612,7 +3615,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName, dataType: "NUMERIC", source: "API" },
@@ -3683,7 +3686,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
@@ -3758,7 +3761,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "BOOLEAN", source: "API" },
score2: { name: scoreName2, dataType: "BOOLEAN", source: "API" },
@@ -3838,7 +3841,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "CATEGORICAL", source: "API" },
score2: { name: scoreName2, dataType: "CATEGORICAL", source: "API" },
@@ -3951,7 +3954,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "BOOLEAN", source: "API" },
score2: { name: scoreName2, dataType: "BOOLEAN", source: "API" },
@@ -4041,7 +4044,7 @@ describe("Score Comparison Analytics tRPC", () => {
await createScoresCh(scores);
- const result = await caller.scores.getScoreComparisonAnalytics({
+ const result = await caller.scoreAnalytics.getScoreComparisonAnalytics({
projectId,
score1: { name: scoreName1, dataType: "CATEGORICAL", source: "API" },
score2: { name: scoreName2, dataType: "CATEGORICAL", source: "API" },
@@ -4195,48 +4198,52 @@ describe("Score Comparison Analytics tRPC", () => {
};
// Test 1: objectType = "all" should return all 4 matched pairs
- const resultAll = await caller.scores.getScoreComparisonAnalytics({
- ...baseParams,
- objectType: "all",
- });
+ const resultAll = await caller.scoreAnalytics.getScoreComparisonAnalytics(
+ {
+ ...baseParams,
+ objectType: "all",
+ },
+ );
expect(resultAll.counts.matchedCount).toBe(4);
expect(resultAll.counts.score1Total).toBe(4);
expect(resultAll.counts.score2Total).toBe(4);
// Test 2: objectType = "trace" should return only trace-level scores (1 pair)
- const resultTrace = await caller.scores.getScoreComparisonAnalytics({
- ...baseParams,
- objectType: "trace",
- });
+ const resultTrace =
+ await caller.scoreAnalytics.getScoreComparisonAnalytics({
+ ...baseParams,
+ objectType: "trace",
+ });
expect(resultTrace.counts.matchedCount).toBe(1);
expect(resultTrace.counts.score1Total).toBe(1);
expect(resultTrace.counts.score2Total).toBe(1);
// Test 3: objectType = "observation" should return only observation-level scores (1 pair)
- const resultObservation = await caller.scores.getScoreComparisonAnalytics(
- {
+ const resultObservation =
+ await caller.scoreAnalytics.getScoreComparisonAnalytics({
...baseParams,
objectType: "observation",
- },
- );
+ });
expect(resultObservation.counts.matchedCount).toBe(1);
expect(resultObservation.counts.score1Total).toBe(1);
expect(resultObservation.counts.score2Total).toBe(1);
// Test 4: objectType = "session" should return only session-level scores (1 pair)
- const resultSession = await caller.scores.getScoreComparisonAnalytics({
- ...baseParams,
- objectType: "session",
- });
+ const resultSession =
+ await caller.scoreAnalytics.getScoreComparisonAnalytics({
+ ...baseParams,
+ objectType: "session",
+ });
expect(resultSession.counts.matchedCount).toBe(1);
expect(resultSession.counts.score1Total).toBe(1);
expect(resultSession.counts.score2Total).toBe(1);
// Test 5: objectType = "dataset_run" should return only dataset_run-level scores (1 pair)
- const resultDatasetRun = await caller.scores.getScoreComparisonAnalytics({
- ...baseParams,
- objectType: "dataset_run",
- });
+ const resultDatasetRun =
+ await caller.scoreAnalytics.getScoreComparisonAnalytics({
+ ...baseParams,
+ objectType: "dataset_run",
+ });
expect(resultDatasetRun.counts.matchedCount).toBe(1);
expect(resultDatasetRun.counts.score1Total).toBe(1);
expect(resultDatasetRun.counts.score2Total).toBe(1);
diff --git a/web/src/__tests__/heatmap-utils.clienttest.ts b/web/src/__tests__/heatmap-utils.clienttest.ts
index 2eb8f53aaf..3ae0918772 100644
--- a/web/src/__tests__/heatmap-utils.clienttest.ts
+++ b/web/src/__tests__/heatmap-utils.clienttest.ts
@@ -2,7 +2,7 @@ import {
generateNumericHeatmapData,
generateConfusionMatrixData,
fillMissingBins,
-} from "@/src/features/scores/components/score-analytics/libs/heatmap-utils";
+} from "@/src/features/score-analytics/lib/heatmap-utils";
describe("heatmap-utils", () => {
describe("generateNumericHeatmapData", () => {
diff --git a/web/src/__tests__/statistics-utils.clienttest.ts b/web/src/__tests__/statistics-utils.clienttest.ts
index 6b7f882cd1..48e38e7dfe 100644
--- a/web/src/__tests__/statistics-utils.clienttest.ts
+++ b/web/src/__tests__/statistics-utils.clienttest.ts
@@ -12,7 +12,7 @@ import {
interpretF1Score,
interpretOverallAgreement,
type ConfusionMatrixRow,
-} from "@/src/features/scores/components/score-analytics/libs/statistics-utils";
+} from "@/src/features/score-analytics/lib/statistics-utils";
describe("Cohen's Kappa Calculation", () => {
it("should calculate perfect agreement (κ = 1.0)", () => {
diff --git a/web/src/features/scores/components/score-analytics/README.md b/web/src/features/score-analytics/README.md
similarity index 69%
rename from web/src/features/scores/components/score-analytics/README.md
rename to web/src/features/score-analytics/README.md
index 30d921f2ae..32ddefa5cc 100644
--- a/web/src/features/scores/components/score-analytics/README.md
+++ b/web/src/features/score-analytics/README.md
@@ -15,13 +15,21 @@ Score Analytics provides a comprehensive dashboard for analyzing score data with
## Folder Structure
```
-/score-analytics/
+/web/src/features/score-analytics/
+├── /server/
+│ └── scoreAnalyticsRouter.ts # tRPC router with 3 procedures:
+│ # - getScoreIdentifiers
+│ # - estimateScoreComparisonSize
+│ # - getScoreComparisonAnalytics
+│
├── /components/
│ ├── /cards/ # Smart cards (consume context)
│ │ ├── StatisticsCard.tsx # Summary metrics
│ │ ├── TimelineChartCard.tsx # Time series trends
│ │ ├── DistributionChartCard.tsx # Score distributions
-│ │ └── HeatmapCard.tsx # Score comparisons (heatmap/confusion matrix)
+│ │ ├── HeatmapCard.tsx # Score comparisons (heatmap/confusion matrix)
+│ │ ├── EstimateLoadingCard.tsx # Loading state during estimation
+│ │ └── SamplingBadge.tsx # Badge showing sampling status
│ │
│ ├── /charts/ # Reusable chart components (presentation only)
│ │ ├── ScoreDistribution*.tsx # Distribution charts (Numeric/Boolean/Categorical)
@@ -38,8 +46,14 @@ Score Analytics provides a comprehensive dashboard for analyzing score data with
├── /hooks/
│ └── useScoreAnalyticsQuery.ts # Data fetching + transformation hook
│
-├── /transformers/
-│ └── scoreAnalyticsTransformers.ts # Pure transformation functions
+├── /lib/ # Utility functions and transformers
+│ ├── scoreAnalyticsTransformers.ts # Pure transformation functions
+│ ├── analytics-url-state.ts # URL state management hook
+│ ├── clickhouse-time-utils.ts # ClickHouse time interval utilities
+│ ├── color-scales.ts # Color scheme generation
+│ ├── heatmap-utils.ts # Heatmap data processing
+│ ├── score-formatter.ts # Score value formatting
+│ └── statistics-utils.ts # Statistical calculations
│
└── README.md # This file
```
@@ -50,10 +64,14 @@ Score Analytics provides a comprehensive dashboard for analyzing score data with
Page (analytics.tsx)
↓
ScoreAnalyticsProvider (wraps dashboard)
+ ↓ (runs estimate query first)
+ ↓ api.scoreAnalytics.estimateScoreComparisonSize
+ ↓ (then runs main query)
↓
useScoreAnalyticsQuery hook
↓ (fetches data via tRPC)
- ↓ (transforms using pure functions)
+ ↓ api.scoreAnalytics.getScoreComparisonAnalytics
+ ↓ (transforms using pure functions from /lib/)
↓ (returns structured data)
↓
React Context
@@ -94,8 +112,8 @@ Chart Components (receive props)
**Purpose**: Fetches data from API and transforms it ONCE using pure functions.
**Responsibilities**:
-- Fetch data via tRPC (`api.scores.getScoreComparisonAnalytics`)
-- Transform data using functions from `scoreAnalyticsTransformers.ts`:
+- Fetch data via tRPC (`api.scoreAnalytics.getScoreComparisonAnalytics`)
+- Transform data using functions from `/lib/scoreAnalyticsTransformers.ts`:
- Extract categories (categorical/boolean only)
- Fill distribution bins (ensure all bins have data)
- Generate bin labels (numeric only)
@@ -175,7 +193,7 @@ export function ExampleChart({ data, dataType, score1Name, score2Name }: ChartPr
}
```
-### 5. Transformers (`/transformers/scoreAnalyticsTransformers.ts`)
+### 5. Transformers (`/lib/scoreAnalyticsTransformers.ts`)
**Purpose**: Pure functions for data transformation (no side effects).
@@ -192,6 +210,37 @@ export function ExampleChart({ data, dataType, score1Name, score2Name }: ChartPr
- Fully typed
- JSDoc documented
+### 6. Utilities (`/lib/`)
+
+**Purpose**: Helper functions for specific domains:
+
+- **`analytics-url-state.ts`**: Manages URL query parameters for filters and selections
+- **`clickhouse-time-utils.ts`**: ClickHouse interval normalization and time bucketing
+- **`color-scales.ts`**: Generates consistent color schemes for charts
+- **`heatmap-utils.ts`**: Heatmap-specific data processing and calculations
+- **`score-formatter.ts`**: Formats score values for display
+- **`statistics-utils.ts`**: Statistical calculations (correlation, Cohen's Kappa, F1, etc.)
+
+### 7. Server Router (`/server/scoreAnalyticsRouter.ts`)
+
+**Purpose**: tRPC router exposing score analytics API endpoints.
+
+**Procedures**:
+- **`getScoreIdentifiers`**: Returns all available scores in a project (name, dataType, source)
+- **`estimateScoreComparisonSize`**: Estimates query size and determines if sampling is needed
+ - Returns: score counts, estimated matched count, willSample flag, estimatedQueryTime
+ - Used to show loading states and sampling badges
+- **`getScoreComparisonAnalytics`**: Main analytics query with adaptive optimizations
+ - Hash-based sampling for large datasets (>100k matches)
+ - Adaptive FINAL optimization (skipped for >70k scores)
+ - Returns: statistics, distributions, time series, heatmap data
+
+**ClickHouse Optimizations**:
+- Uses `cityHash64` for consistent sampling
+- Dynamic FINAL application based on dataset size
+- Proper time interval alignment (ISO 8601 weeks, calendar months)
+- Efficient aggregation queries for statistics and distributions
+
## Data Types Supported
1. **NUMERIC**: Continuous numeric scores
@@ -248,7 +297,7 @@ export function ExampleChart({ data, dataType, score1Name, score2Name }: ChartPr
### Add a New Transformation
-1. Add pure function to `/transformers/scoreAnalyticsTransformers.ts`
+1. Add pure function to `/lib/scoreAnalyticsTransformers.ts`
2. Call it in `useScoreAnalyticsQuery` hook's `useMemo`
3. Add to return object interface
@@ -305,15 +354,26 @@ if (isSingleScoreColors(colors)) {
**Page**: `/web/src/pages/project/[projectId]/scores/analytics.tsx`
+**Feature Directory**: `/web/src/features/score-analytics/`
+
+**Server (tRPC)**:
+- Router: `/web/src/features/score-analytics/server/scoreAnalyticsRouter.ts`
+- Registered as: `api.scoreAnalytics.*`
+- Root registration: `/web/src/server/api/root.ts`
+
**Utilities**:
-- Color scales: `/web/src/features/scores/lib/color-scales.ts`
-- Statistics utils: `/web/src/features/scores/lib/statistics-utils.ts`
-- Heatmap utils: `/web/src/features/scores/lib/heatmap-utils.ts`
+- All utilities: `/web/src/features/score-analytics/lib/`
+ - `scoreAnalyticsTransformers.ts` - Pure transformation functions
+ - `analytics-url-state.ts` - URL state management
+ - `clickhouse-time-utils.ts` - ClickHouse time utilities
+ - `color-scales.ts` - Color scheme generation
+ - `heatmap-utils.ts` - Heatmap processing
+ - `score-formatter.ts` - Score formatting
+ - `statistics-utils.ts` - Statistical calculations
- Time series gap filling: `/web/src/utils/fill-time-series-gaps.ts`
-**API**:
-- tRPC route: `/web/src/server/api/routers/scores.ts`
-- Backend: `/packages/shared/src/server/repositories/score-analytics.ts`
+**Backend Repositories**:
+- Score analytics queries: `/packages/shared/src/server/repositories/score-analytics.ts`
## Performance Considerations
@@ -331,6 +391,14 @@ Test coverage:
- All modes (single, two-score, same-score-twice)
- Edge cases (empty data, missing bins, timezone handling)
- Statistical calculations (correlation, Cohen's Kappa, F1, etc.)
+- Adaptive FINAL optimization (small vs large datasets)
+- Hash-based sampling (consistent sampling for large datasets)
+- Object type filtering (trace, observation, session, dataset_run)
+
+Run tests:
+```bash
+pnpm --filter=web test -- --testPathPattern="score-comparison-analytics"
+```
## Troubleshooting
@@ -340,6 +408,6 @@ Test coverage:
**Type errors**: Check interfaces in `useScoreAnalyticsQuery.ts` and `ScoreAnalyticsProvider.tsx`
-**Color issues**: Check `color-scales.ts` and color assignment in `ScoreAnalyticsProvider.tsx`
+**Color issues**: Check `/lib/color-scales.ts` and color assignment in `ScoreAnalyticsProvider.tsx`
-**Category collisions in timeline**: Check namespace logic in `useScoreAnalyticsQuery.ts` (lines 376-412)
+**Category collisions in timeline**: Check namespace logic in `useScoreAnalyticsQuery.ts` (categorical time series transformation)
diff --git a/web/src/features/score-analytics/components/SamplingDetailsHoverCard.tsx b/web/src/features/score-analytics/components/SamplingDetailsHoverCard.tsx
new file mode 100644
index 0000000000..2d51d20768
--- /dev/null
+++ b/web/src/features/score-analytics/components/SamplingDetailsHoverCard.tsx
@@ -0,0 +1,125 @@
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@/src/components/ui/hover-card";
+import { Info } from "lucide-react";
+
+interface SamplingMetadata {
+ samplingRate: number;
+ preflightEstimates?: {
+ score1Count: number;
+ score2Count: number;
+ estimatedMatchedCount: number;
+ };
+ adaptiveFinal?: {
+ usedFinal: boolean;
+ reason: string;
+ };
+}
+
+interface SamplingDetailsHoverCardProps {
+ samplingMetadata: SamplingMetadata;
+ mode?: "single" | "two";
+ showLabel?: boolean;
+}
+
+export function SamplingDetailsHoverCard({
+ samplingMetadata,
+ mode = "two",
+ showLabel = false,
+}: SamplingDetailsHoverCardProps) {
+ return (
+ <HoverCard>
+ <HoverCardTrigger asChild>
+ <button
+ className={
+ showLabel
+ ? "inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
+ : "inline-flex h-4 w-4 items-center justify-center rounded-full hover:bg-muted-foreground/10"
+ }
+ aria-label="View sampling details"
+ >
+ {showLabel && <span>Sampled Data</span>}
+ <Info
+ className={showLabel ? "h-3 w-3" : "h-3 w-3 text-muted-foreground"}
+ />
+ </button>
+ </HoverCardTrigger>
+ <HoverCardContent className="w-80" align="start">
+ <div className="space-y-3">
+ <div>
+ <h4 className="mb-2 text-sm font-semibold">
+ {mode === "single" ? "Estimated Score Count" : "Estimated Scores"}
+ </h4>
+ <dl className="space-y-1 text-sm">
+ {mode === "single" ? (
+ <div className="flex justify-between">
+ <dt className="text-muted-foreground">Total Scores:</dt>
+ <dd className="font-medium">
+ ~
+ {samplingMetadata.preflightEstimates?.score1Count.toLocaleString()}
+ </dd>
+ </div>
+ ) : (
+ <>
+ <div className="flex justify-between">
+ <dt className="text-muted-foreground">Score 1:</dt>
+ <dd className="font-medium">
+ ~
+ {samplingMetadata.preflightEstimates?.score1Count.toLocaleString()}
+ </dd>
+ </div>
+ <div className="flex justify-between">
+ <dt className="text-muted-foreground">Score 2:</dt>
+ <dd className="font-medium">
+ ~
+ {samplingMetadata.preflightEstimates?.score2Count.toLocaleString()}
+ </dd>
+ </div>
+ <div className="flex justify-between">
+ <dt className="text-muted-foreground">
+ Estimated Matches:
+ </dt>
+ <dd className="font-medium">
+ ~
+ {samplingMetadata.preflightEstimates?.estimatedMatchedCount.toLocaleString()}
+ </dd>
+ </div>
+ </>
+ )}
+ </dl>
+ </div>
+
+ <div>
+ <h4 className="mb-2 text-sm font-semibold">Query Optimizations</h4>
+ <dl className="space-y-1 text-sm">
+ <div className="flex justify-between">
+ <dt className="text-muted-foreground">Sampling:</dt>
+ <dd className="font-medium">
+ {(samplingMetadata.samplingRate * 100).toFixed(1)}%
+ (hash-based)
+ </dd>
+ </div>
+ {samplingMetadata.adaptiveFinal && (
+ <div className="flex justify-between">
+ <dt className="text-muted-foreground">Deduplication:</dt>
+ <dd className="font-medium">
+ {samplingMetadata.adaptiveFinal.usedFinal
+ ? "Enabled"
+ : "Skipped for performance"}
+ </dd>
+ </div>
+ )}
+ </dl>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ Hash-based sampling ensures consistent, repeatable results while
+ maintaining statistical accuracy.
+ </p>
+ </div>
+ </HoverCardContent>
+ </HoverCard>
+ );
+}
diff --git a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsDashboard.tsx b/web/src/features/score-analytics/components/ScoreAnalyticsDashboard.tsx
similarity index 100%
rename from web/src/features/scores/components/score-analytics/components/ScoreAnalyticsDashboard.tsx
rename to web/src/features/score-analytics/components/ScoreAnalyticsDashboard.tsx
diff --git a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsHeader.tsx b/web/src/features/score-analytics/components/ScoreAnalyticsHeader.tsx
similarity index 97%
rename from web/src/features/scores/components/score-analytics/components/ScoreAnalyticsHeader.tsx
rename to web/src/features/score-analytics/components/ScoreAnalyticsHeader.tsx
index eb02df0251..2cf84f2cfc 100644
--- a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsHeader.tsx
+++ b/web/src/features/score-analytics/components/ScoreAnalyticsHeader.tsx
@@ -4,7 +4,7 @@ import { ScoreCombobox } from "./charts/ScoreCombobox";
import { ObjectTypeFilter } from "./charts/ObjectTypeFilter";
import { TimeRangePicker } from "@/src/components/date-picker";
import { DASHBOARD_AGGREGATION_OPTIONS } from "@/src/utils/date-range-utils";
-import { useAnalyticsUrlState } from "@/src/features/scores/components/score-analytics/libs/analytics-url-state";
+import { useAnalyticsUrlState } from "@/src/features/score-analytics/lib/analytics-url-state";
import { type TimeRange } from "@/src/utils/date-range-utils";
import { type ScoreOption } from "./charts/ScoreCombobox";
import { Badge } from "@/src/components/ui/badge";
diff --git a/web/src/features/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx b/web/src/features/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx
new file mode 100644
index 0000000000..88db706bfe
--- /dev/null
+++ b/web/src/features/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx
@@ -0,0 +1,94 @@
+import { Clock, Info } from "lucide-react";
+import { useScoreAnalytics } from "./ScoreAnalyticsProvider";
+import { useState, useEffect } from "react";
+import { SamplingDetailsHoverCard } from "./SamplingDetailsHoverCard";
+
+export function ScoreAnalyticsNoticeBanner() {
+ const { isEstimating, estimate, isLoading, data } = useScoreAnalytics();
+ const [showLoadingBanner, setShowLoadingBanner] = useState(false);
+
+ // Track when estimation starts and set delay for showing loading banner
+ useEffect(() => {
+ if (isEstimating || (estimate && isLoading)) {
+ // Start timer - show banner after 1.5 seconds
+ const timer = setTimeout(() => {
+ setShowLoadingBanner(true);
+ }, 1500);
+
+ return () => clearTimeout(timer);
+ } else {
+ // Reset when loading completes
+ setShowLoadingBanner(false);
+ }
+ }, [isEstimating, estimate, isLoading]);
+
+ // Don't show anything if we haven't started
+ if (!isEstimating && !estimate) return null;
+
+ // State 1: Estimating (loading)
+ if (isEstimating || (estimate && isLoading)) {
+ const showLargeDataset =
+ estimate && estimate.estimatedMatchedCount > 100_000;
+
+ // Only show banner if:
+ // 1. Delay has passed, OR
+ // 2. We have estimate data showing it's a large dataset
+ if (!showLoadingBanner && !showLargeDataset) {
+ return null;
+ }
+
+ return (
+ <div className="mb-4 rounded-md bg-muted px-4 py-3">
+ <div className="flex items-start gap-3">
+ <Clock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="flex-1 space-y-1">
+ <div className="text-sm font-medium">
+ {showLargeDataset
+ ? "Processing large dataset..."
+ : "Loading analytics..."}
+ </div>
+ {estimate && (
+ <div className="text-sm text-muted-foreground">
+ {estimate.mode === "single"
+ ? `Analyzing ~${estimate.score1Count.toLocaleString()} scores`
+ : `Analyzing ~${estimate.score1Count.toLocaleString()} (Score 1) and ~${estimate.score2Count.toLocaleString()} (Score 2) scores`}
+ {estimate.willSample && " • Sampling will be applied"}
+ {estimate.estimatedQueryTime && (
+ <> • Est. time: {estimate.estimatedQueryTime}</>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ // State 2: Loaded with sampling
+ if (data?.samplingMetadata.isSampled) {
+ return (
+ <div className="mb-4 rounded-md bg-muted px-4 py-3">
+ <div className="flex items-start gap-3">
+ <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="flex-1 space-y-1">
+ <div className="flex items-center gap-2 text-sm font-medium">
+ Sampled Data
+ <SamplingDetailsHoverCard
+ samplingMetadata={data.samplingMetadata}
+ mode={data.metadata.mode}
+ />
+ </div>
+ <div className="text-sm text-muted-foreground">
+ {data.metadata.mode === "single"
+ ? `Results based on a ${(data.samplingMetadata.samplingRate * 100).toFixed(2)}% sample of ~${data.samplingMetadata.preflightEstimates?.score1Count.toLocaleString()} scores.`
+ : `Results based on a ${(data.samplingMetadata.samplingRate * 100).toFixed(2)}% sample of ~${data.samplingMetadata.preflightEstimates?.score1Count.toLocaleString()} Score 1 and ~${data.samplingMetadata.preflightEstimates?.score2Count.toLocaleString()} Score 2 data.`}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ // State 3: Loaded without sampling (don't show banner)
+ return null;
+}
diff --git a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsProvider.tsx b/web/src/features/score-analytics/components/ScoreAnalyticsProvider.tsx
similarity index 91%
rename from web/src/features/scores/components/score-analytics/components/ScoreAnalyticsProvider.tsx
rename to web/src/features/score-analytics/components/ScoreAnalyticsProvider.tsx
index 9c965eb530..0cd84df211 100644
--- a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsProvider.tsx
+++ b/web/src/features/score-analytics/components/ScoreAnalyticsProvider.tsx
@@ -9,7 +9,7 @@ import {
getTwoScoreColors,
getScoreNumericColor,
buildColorMappings,
-} from "@/src/features/scores/components/score-analytics/libs/color-scales";
+} from "@/src/features/score-analytics/lib/color-scales";
import { api } from "@/src/utils/api";
// Re-export types for convenience
@@ -116,7 +116,7 @@ export function ScoreAnalyticsProvider({
// Determine mode: "single" when only score1 selected, "two" when score2 explicitly provided
const mode: "single" | "two" = params.score2 === undefined ? "single" : "two";
- const estimateQuery = api.scores.estimateScoreComparisonSize.useQuery(
+ const estimateQuery = api.scoreAnalytics.estimateScoreComparisonSize.useQuery(
{
projectId: params.projectId,
score1: params.score1 ?? { name: "", dataType: "", source: "" },
@@ -137,9 +137,22 @@ export function ScoreAnalyticsProvider({
// Step 2: Only run main query after estimate succeeds
// This applies to both single-score and two-score modes now
- const queryResult = useScoreAnalyticsQuery(params, {
- enabled: !canEstimate || estimateQuery.isSuccess,
- });
+ // Pass estimate results to avoid duplicate preflight query
+ const queryResult = useScoreAnalyticsQuery(
+ {
+ ...params,
+ estimateResults: estimateQuery.data
+ ? {
+ score1Count: estimateQuery.data.score1Count,
+ score2Count: estimateQuery.data.score2Count,
+ estimatedMatchedCount: estimateQuery.data.estimatedMatchedCount,
+ }
+ : undefined,
+ },
+ {
+ enabled: !canEstimate || estimateQuery.isSuccess,
+ },
+ );
// Determine color scheme based on mode
const colors = useMemo(() => {
diff --git a/web/src/features/scores/components/score-analytics/components/cards/DistributionBooleanCard.tsx b/web/src/features/score-analytics/components/cards/DistributionBooleanCard.tsx
similarity index 99%
rename from web/src/features/scores/components/score-analytics/components/cards/DistributionBooleanCard.tsx
rename to web/src/features/score-analytics/components/cards/DistributionBooleanCard.tsx
index 865d79eb63..70a59c5c10 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/DistributionBooleanCard.tsx
+++ b/web/src/features/score-analytics/components/cards/DistributionBooleanCard.tsx
@@ -10,7 +10,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { Loader2 } from "lucide-react";
import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { ScoreDistributionBooleanChart } from "../charts/ScoreDistributionBooleanChart";
-import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
+import { SamplingDetailsHoverCard } from "../SamplingDetailsHoverCard";
type DistributionTab = "score1" | "score2" | "all" | "matched";
diff --git a/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx b/web/src/features/score-analytics/components/cards/DistributionCategoricalCard.tsx
similarity index 98%
rename from web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
rename to web/src/features/score-analytics/components/cards/DistributionCategoricalCard.tsx
index 4c2385195f..77dc6a9025 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
+++ b/web/src/features/score-analytics/components/cards/DistributionCategoricalCard.tsx
@@ -10,8 +10,8 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { Loader2 } from "lucide-react";
import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { ScoreDistributionCategoricalChart } from "../charts/ScoreDistributionCategoricalChart";
-import { getScoreCategoryColors } from "../../libs/color-scales";
-import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
+import { getScoreCategoryColors } from "../../lib/color-scales";
+import { SamplingDetailsHoverCard } from "../SamplingDetailsHoverCard";
type DistributionTab = "score1" | "score2" | "all" | "matched";
diff --git a/web/src/features/scores/components/score-analytics/components/cards/DistributionNumericCard.tsx b/web/src/features/score-analytics/components/cards/DistributionNumericCard.tsx
similarity index 99%
rename from web/src/features/scores/components/score-analytics/components/cards/DistributionNumericCard.tsx
rename to web/src/features/score-analytics/components/cards/DistributionNumericCard.tsx
index 7441c54944..3949bf5005 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/DistributionNumericCard.tsx
+++ b/web/src/features/score-analytics/components/cards/DistributionNumericCard.tsx
@@ -10,7 +10,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { Loader2 } from "lucide-react";
import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { ScoreDistributionNumericChart } from "../charts/ScoreDistributionNumericChart";
-import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
+import { SamplingDetailsHoverCard } from "../SamplingDetailsHoverCard";
type DistributionTab = "score1" | "score2" | "all" | "matched";
diff --git a/web/src/features/scores/components/score-analytics/components/cards/HeatmapCard.tsx b/web/src/features/score-analytics/components/cards/HeatmapCard.tsx
similarity index 97%
rename from web/src/features/scores/components/score-analytics/components/cards/HeatmapCard.tsx
rename to web/src/features/score-analytics/components/cards/HeatmapCard.tsx
index 2dd859c8f6..2006ea71a9 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/HeatmapCard.tsx
+++ b/web/src/features/score-analytics/components/cards/HeatmapCard.tsx
@@ -10,11 +10,11 @@ import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { Heatmap } from "../charts/Heatmap";
import { HeatmapLegend } from "../charts/HeatmapLegend";
import { HeatmapSkeleton } from "../charts/HeatmapSkeleton";
-import { getHeatmapCellColor } from "@/src/features/scores/components/score-analytics/libs/color-scales";
-import { type HeatmapCell } from "@/src/features/scores/components/score-analytics/libs/heatmap-utils";
+import { getHeatmapCellColor } from "@/src/features/score-analytics/lib/color-scales";
+import { type HeatmapCell } from "@/src/features/score-analytics/lib/heatmap-utils";
import { useCallback } from "react";
import type { ScoreDataType } from "@langfuse/shared";
-import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
+import { SamplingDetailsHoverCard } from "../SamplingDetailsHoverCard";
interface HeatmapTooltipContentProps {
cell: HeatmapCell;
diff --git a/web/src/features/scores/components/score-analytics/components/cards/StatisticsCard.tsx b/web/src/features/score-analytics/components/cards/StatisticsCard.tsx
similarity index 99%
rename from web/src/features/scores/components/score-analytics/components/cards/StatisticsCard.tsx
rename to web/src/features/score-analytics/components/cards/StatisticsCard.tsx
index dcd816cad7..bbc053f608 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/StatisticsCard.tsx
+++ b/web/src/features/score-analytics/components/cards/StatisticsCard.tsx
@@ -8,7 +8,7 @@ import {
import { Loader2 } from "lucide-react";
import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { MetricCard } from "../charts/MetricCard";
-import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
+import { SamplingDetailsHoverCard } from "../SamplingDetailsHoverCard";
import {
calculateCohensKappa,
calculateWeightedF1Score,
@@ -20,7 +20,7 @@ import {
interpretOverallAgreement,
interpretMAE,
interpretRMSE,
-} from "@/src/features/scores/components/score-analytics/libs/statistics-utils";
+} from "@/src/features/score-analytics/lib/statistics-utils";
/**
* StatisticsCard - Smart card component for displaying score statistics
diff --git a/web/src/features/scores/components/score-analytics/components/cards/TimelineChartCard.tsx b/web/src/features/score-analytics/components/cards/TimelineChartCard.tsx
similarity index 98%
rename from web/src/features/scores/components/score-analytics/components/cards/TimelineChartCard.tsx
rename to web/src/features/score-analytics/components/cards/TimelineChartCard.tsx
index 5554d6a66b..134427e9bc 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/TimelineChartCard.tsx
+++ b/web/src/features/score-analytics/components/cards/TimelineChartCard.tsx
@@ -10,11 +10,11 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { Loader2 } from "lucide-react";
import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { ScoreTimeSeriesChart } from "../charts/ScoreTimeSeriesChart";
-import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
+import { SamplingDetailsHoverCard } from "../SamplingDetailsHoverCard";
import {
getScoreCategoryColors,
getScoreBooleanColors,
-} from "@/src/features/scores/components/score-analytics/libs/color-scales";
+} from "@/src/features/score-analytics/lib/color-scales";
type TimelineTab = "score1" | "score2" | "all" | "matched";
diff --git a/web/src/features/scores/components/score-analytics/components/charts/Heatmap.tsx b/web/src/features/score-analytics/components/charts/Heatmap.tsx
similarity index 99%
rename from web/src/features/scores/components/score-analytics/components/charts/Heatmap.tsx
rename to web/src/features/score-analytics/components/charts/Heatmap.tsx
index fbe2629c48..52b183f971 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/Heatmap.tsx
+++ b/web/src/features/score-analytics/components/charts/Heatmap.tsx
@@ -1,5 +1,5 @@
import { useMemo, useLayoutEffect, useState, useRef } from "react";
-import { type HeatmapCell } from "@/src/features/scores/components/score-analytics/libs/heatmap-utils";
+import { type HeatmapCell } from "@/src/features/score-analytics/lib/heatmap-utils";
import { HeatmapCellComponent } from "./HeatmapCell";
import { TooltipProvider } from "@/src/components/ui/tooltip";
import {
diff --git a/web/src/features/scores/components/score-analytics/components/charts/HeatmapCell.tsx b/web/src/features/score-analytics/components/charts/HeatmapCell.tsx
similarity index 95%
rename from web/src/features/scores/components/score-analytics/components/charts/HeatmapCell.tsx
rename to web/src/features/score-analytics/components/charts/HeatmapCell.tsx
index 4221601218..d3ca791ed6 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/HeatmapCell.tsx
+++ b/web/src/features/score-analytics/components/charts/HeatmapCell.tsx
@@ -1,5 +1,5 @@
-import { type HeatmapCell } from "@/src/features/scores/components/score-analytics/libs/heatmap-utils";
-import { getContrastColor } from "@/src/features/scores/components/score-analytics/libs/color-scales";
+import { type HeatmapCell } from "@/src/features/score-analytics/lib/heatmap-utils";
+import { getContrastColor } from "@/src/features/score-analytics/lib/color-scales";
import {
Tooltip,
TooltipContent,
diff --git a/web/src/features/scores/components/score-analytics/components/charts/HeatmapLegend.tsx b/web/src/features/score-analytics/components/charts/HeatmapLegend.tsx
similarity index 97%
rename from web/src/features/scores/components/score-analytics/components/charts/HeatmapLegend.tsx
rename to web/src/features/score-analytics/components/charts/HeatmapLegend.tsx
index 28168dd54d..158dd155dd 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/HeatmapLegend.tsx
+++ b/web/src/features/score-analytics/components/charts/HeatmapLegend.tsx
@@ -1,4 +1,4 @@
-import { getHeatmapCellColor } from "@/src/features/scores/components/score-analytics/libs/color-scales";
+import { getHeatmapCellColor } from "@/src/features/score-analytics/lib/color-scales";
import { cn } from "@/src/utils/tailwind";
import { useState } from "react";
import chroma from "chroma-js";
diff --git a/web/src/features/scores/components/score-analytics/components/charts/HeatmapPlaceholder.tsx b/web/src/features/score-analytics/components/charts/HeatmapPlaceholder.tsx
similarity index 100%
rename from web/src/features/scores/components/score-analytics/components/charts/HeatmapPlaceholder.tsx
rename to web/src/features/score-analytics/components/charts/HeatmapPlaceholder.tsx
diff --git a/web/src/features/scores/components/score-analytics/components/charts/HeatmapSkeleton.tsx b/web/src/features/score-analytics/components/charts/HeatmapSkeleton.tsx
similarity index 100%
rename from web/src/features/scores/components/score-analytics/components/charts/HeatmapSkeleton.tsx
rename to web/src/features/score-analytics/components/charts/HeatmapSkeleton.tsx
diff --git a/web/src/features/scores/components/score-analytics/components/charts/MetricCard.tsx b/web/src/features/score-analytics/components/charts/MetricCard.tsx
similarity index 97%
rename from web/src/features/scores/components/score-analytics/components/charts/MetricCard.tsx
rename to web/src/features/score-analytics/components/charts/MetricCard.tsx
index 3e0e16c7ee..00135d237c 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/MetricCard.tsx
+++ b/web/src/features/score-analytics/components/charts/MetricCard.tsx
@@ -11,7 +11,7 @@ import {
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
import { HelpCircle, AlertCircle } from "lucide-react";
-import type { InterpretationResult } from "@/src/features/scores/components/score-analytics/libs/statistics-utils";
+import type { InterpretationResult } from "@/src/features/score-analytics/lib/statistics-utils";
interface MetricCardProps {
label: string;
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ObjectTypeFilter.tsx b/web/src/features/score-analytics/components/charts/ObjectTypeFilter.tsx
similarity index 90%
rename from web/src/features/scores/components/score-analytics/components/charts/ObjectTypeFilter.tsx
rename to web/src/features/score-analytics/components/charts/ObjectTypeFilter.tsx
index 0e36ae9ce8..72705e322a 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ObjectTypeFilter.tsx
+++ b/web/src/features/score-analytics/components/charts/ObjectTypeFilter.tsx
@@ -5,7 +5,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
-import { type ObjectType } from "@/src/features/scores/components/score-analytics/libs/analytics-url-state";
+import { type ObjectType } from "@/src/features/score-analytics/lib/analytics-url-state";
const OBJECT_TYPE_OPTIONS: Array<{ value: ObjectType; label: string }> = [
{ value: "all", label: "All Objects" },
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreChartLegendContent.tsx b/web/src/features/score-analytics/components/charts/ScoreChartLegendContent.tsx
similarity index 100%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreChartLegendContent.tsx
rename to web/src/features/score-analytics/components/charts/ScoreChartLegendContent.tsx
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreCombobox.tsx b/web/src/features/score-analytics/components/charts/ScoreCombobox.tsx
similarity index 100%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreCombobox.tsx
rename to web/src/features/score-analytics/components/charts/ScoreCombobox.tsx
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx b/web/src/features/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
similarity index 99%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
rename to web/src/features/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
index 4129943080..14399a052e 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreDistributionBooleanChart.tsx
@@ -6,7 +6,7 @@ import {
type ChartConfig,
} from "@/src/components/ui/chart";
import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
-import { ScoreChartTooltip } from "../../libs/ScoreChartTooltip";
+import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
interface BooleanChartProps {
distribution1: Array<{ binIndex: number; count: number }>;
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx b/web/src/features/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
similarity index 99%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
rename to web/src/features/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
index 53946181ad..b85f39ff64 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreDistributionCategoricalChart.tsx
@@ -6,7 +6,7 @@ import {
type ChartConfig,
} from "@/src/components/ui/chart";
import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
-import { ScoreChartTooltip } from "../../libs/ScoreChartTooltip";
+import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
interface CategoricalChartProps {
distribution1: Array<{ binIndex: number; count: number }>;
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionNumericChart.tsx b/web/src/features/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
similarity index 98%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
rename to web/src/features/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
index 3e278c3a74..84614f91b7 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreDistributionNumericChart.tsx
@@ -7,7 +7,7 @@ import {
} from "@/src/components/ui/chart";
import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
import { compactNumberFormatter } from "@/src/utils/numbers";
-import { ScoreChartTooltip } from "../../libs/ScoreChartTooltip";
+import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
interface NumericChartProps {
distribution1: Array<{ binIndex: number; count: number }>;
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
similarity index 97%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
rename to web/src/features/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
index e6a5ba44ba..104b02feb7 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesBooleanChart.tsx
@@ -9,8 +9,8 @@ import {
type IntervalConfig,
type TimeRange,
} from "@/src/utils/date-range-utils";
-import { formatChartTimestamp } from "../../libs/chart-formatters";
-import { ScoreChartTooltip } from "../../libs/ScoreChartTooltip";
+import { formatChartTimestamp } from "../../lib/chart-formatters";
+import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
export interface BooleanTimeSeriesChartProps {
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
similarity index 97%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
rename to web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
index c7aa6713b9..686107dbc4 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesCategoricalChart.tsx
@@ -9,8 +9,8 @@ import {
type IntervalConfig,
type TimeRange,
} from "@/src/utils/date-range-utils";
-import { formatChartTimestamp } from "../../libs/chart-formatters";
-import { ScoreChartTooltip } from "../../libs/ScoreChartTooltip";
+import { formatChartTimestamp } from "../../lib/chart-formatters";
+import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
export interface CategoricalTimeSeriesChartProps {
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesChart.tsx
similarity index 100%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesChart.tsx
rename to web/src/features/score-analytics/components/charts/ScoreTimeSeriesChart.tsx
diff --git a/web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
similarity index 97%
rename from web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
rename to web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
index 965bc7157f..78d51dd399 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
+++ b/web/src/features/score-analytics/components/charts/ScoreTimeSeriesNumericChart.tsx
@@ -10,8 +10,8 @@ import {
type TimeRange,
} from "@/src/utils/date-range-utils";
import { compactNumberFormatter } from "@/src/utils/numbers";
-import { formatChartTimestamp } from "../../libs/chart-formatters";
-import { ScoreChartTooltip } from "../../libs/ScoreChartTooltip";
+import { formatChartTimestamp } from "../../lib/chart-formatters";
+import { ScoreChartTooltip } from "../../lib/ScoreChartTooltip";
import { ScoreChartLegendContent } from "./ScoreChartLegendContent";
export interface NumericTimeSeriesChartProps {
diff --git a/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts b/web/src/features/score-analytics/hooks/useScoreAnalyticsQuery.ts
similarity index 98%
rename from web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
rename to web/src/features/score-analytics/hooks/useScoreAnalyticsQuery.ts
index 190c6aefc6..f034a28da9 100644
--- a/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
+++ b/web/src/features/score-analytics/hooks/useScoreAnalyticsQuery.ts
@@ -11,7 +11,7 @@ import {
calculateModeMetrics,
transformHeatmapData,
generateBinLabels,
-} from "../transformers/scoreAnalyticsTransformers";
+} from "../lib/score-analytics-transformers";
// ============================================================================
// Type Definitions
@@ -47,6 +47,12 @@ export interface ScoreAnalyticsQueryParams {
interval: IntervalConfig;
objectType?: ObjectType;
nBins?: number; // Default: 10
+ // Optional: Pass estimate results to avoid duplicate preflight query
+ estimateResults?: {
+ score1Count: number;
+ score2Count: number;
+ estimatedMatchedCount: number;
+ };
}
/**
@@ -207,6 +213,7 @@ export function useScoreAnalyticsQuery(
interval,
objectType,
nBins = 10,
+ estimateResults,
} = params;
// Determine mode: "single" when only score1 selected, "two" when score2 explicitly provided
@@ -217,7 +224,7 @@ export function useScoreAnalyticsQuery(
data: apiData,
isLoading,
error,
- } = api.scores.getScoreComparisonAnalytics.useQuery(
+ } = api.scoreAnalytics.getScoreComparisonAnalytics.useQuery(
{
projectId,
score1,
@@ -227,6 +234,7 @@ export function useScoreAnalyticsQuery(
toTimestamp,
interval,
objectType,
+ estimateResults, // Pass estimate results to avoid duplicate preflight query
},
{
enabled: (options?.enabled ?? true) && !!(projectId && score1),
diff --git a/web/src/features/scores/components/score-analytics/libs/ScoreChartTooltip.tsx b/web/src/features/score-analytics/lib/ScoreChartTooltip.tsx
similarity index 100%
rename from web/src/features/scores/components/score-analytics/libs/ScoreChartTooltip.tsx
rename to web/src/features/score-analytics/lib/ScoreChartTooltip.tsx
diff --git a/web/src/features/scores/components/score-analytics/libs/analytics-url-state.ts b/web/src/features/score-analytics/lib/analytics-url-state.ts
similarity index 100%
rename from web/src/features/scores/components/score-analytics/libs/analytics-url-state.ts
rename to web/src/features/score-analytics/lib/analytics-url-state.ts
diff --git a/web/src/features/scores/components/score-analytics/libs/chart-formatters.ts b/web/src/features/score-analytics/lib/chart-formatters.ts
similarity index 100%
rename from web/src/features/scores/components/score-analytics/libs/chart-formatters.ts
rename to web/src/features/score-analytics/lib/chart-formatters.ts
diff --git a/web/src/features/scores/components/score-analytics/libs/clickhouse-time-utils.ts b/web/src/features/score-analytics/lib/clickhouse-time-utils.ts
similarity index 100%
rename from web/src/features/scores/components/score-analytics/libs/clickhouse-time-utils.ts
rename to web/src/features/score-analytics/lib/clickhouse-time-utils.ts
diff --git a/web/src/features/scores/components/score-analytics/libs/color-scales.ts b/web/src/features/score-analytics/lib/color-scales.ts
similarity index 100%
rename from web/src/features/scores/components/score-analytics/libs/color-scales.ts
rename to web/src/features/score-analytics/lib/color-scales.ts
diff --git a/web/src/features/scores/components/score-analytics/libs/heatmap-utils.ts b/web/src/features/score-analytics/lib/heatmap-utils.ts
similarity index 100%
rename from web/src/features/scores/components/score-analytics/libs/heatmap-utils.ts
rename to web/src/features/score-analytics/lib/heatmap-utils.ts
diff --git a/web/src/features/scores/components/score-analytics/transformers/scoreAnalyticsTransformers.ts b/web/src/features/score-analytics/lib/score-analytics-transformers.ts
similarity index 98%
rename from web/src/features/scores/components/score-analytics/transformers/scoreAnalyticsTransformers.ts
rename to web/src/features/score-analytics/lib/score-analytics-transformers.ts
index eab0559477..704e460b52 100644
--- a/web/src/features/scores/components/score-analytics/transformers/scoreAnalyticsTransformers.ts
+++ b/web/src/features/score-analytics/lib/score-analytics-transformers.ts
@@ -8,7 +8,7 @@ import type { RouterOutputs } from "@/src/utils/api";
import {
generateNumericHeatmapData,
generateConfusionMatrixData,
-} from "@/src/features/scores/components/score-analytics/libs/heatmap-utils";
+} from "@/src/features/score-analytics/lib/heatmap-utils";
// Type aliases for cleaner code
type ConfusionMatrixRow = {
@@ -214,7 +214,7 @@ export function calculateModeMetrics(params: {
* ```
*/
export function transformHeatmapData(params: {
- apiData: RouterOutputs["scores"]["getScoreComparisonAnalytics"];
+ apiData: RouterOutputs["scoreAnalytics"]["getScoreComparisonAnalytics"];
dataType: DataType;
parsedScore1: { name: string; dataType: string; source: string };
}):
diff --git a/web/src/features/scores/components/score-analytics/libs/statistics-utils.ts b/web/src/features/score-analytics/lib/statistics-utils.ts
similarity index 100%
rename from web/src/features/scores/components/score-analytics/libs/statistics-utils.ts
rename to web/src/features/score-analytics/lib/statistics-utils.ts
diff --git a/web/src/features/score-analytics/server/buildEstimateQuery.ts b/web/src/features/score-analytics/server/buildEstimateQuery.ts
new file mode 100644
index 0000000000..ec68526b1b
--- /dev/null
+++ b/web/src/features/score-analytics/server/buildEstimateQuery.ts
@@ -0,0 +1,120 @@
+import { queryClickhouse } from "@langfuse/shared/src/server";
+import { buildObjectTypeFilter, buildSamplingExpression } from "./queryHelpers";
+
+/**
+ * Build and execute estimation query for score comparison
+ *
+ * Uses 1% hash sample for fast count approximation without FINAL merge overhead.
+ * Returns estimates for score1 count, score2 count, and matched count.
+ *
+ * This preflight query helps determine:
+ * - Whether to apply sampling (if counts exceed thresholds)
+ * - Whether to use FINAL merge (adaptive for small datasets)
+ * - Expected query time for user feedback
+ *
+ * @param params - Query parameters
+ * @returns Estimated counts for score1, score2, and matched scores
+ */
+export async function buildEstimateQuery(params: {
+ projectId: string;
+ score1Name: string;
+ score1Source: string;
+ score1DataType: string;
+ score2Name: string;
+ score2Source: string;
+ score2DataType: string;
+ fromTimestamp: Date;
+ toTimestamp: Date;
+ objectType: string;
+}): Promise<{
+ score1Count: number;
+ score2Count: number;
+ estimatedMatchedCount: number;
+}> {
+ const {
+ projectId,
+ score1Name,
+ score1Source,
+ score1DataType,
+ score2Name,
+ score2Source,
+ score2DataType,
+ fromTimestamp,
+ toTimestamp,
+ objectType,
+ } = params;
+
+ // Build filter based on object type
+ const objectTypeFilter = buildObjectTypeFilter(objectType);
+
+ // Use 1% hash sample for fast count estimation
+ const samplingExpression = buildSamplingExpression(1);
+
+ const preflightQuery = `
+ WITH
+ score1_sample AS (
+ SELECT trace_id, observation_id, session_id, dataset_run_id
+ FROM scores
+ PREWHERE project_id = {projectId: String}
+ AND name = {score1Name: String}
+ WHERE source = {score1Source: String}
+ AND data_type = {score1DataType: String}
+ AND timestamp >= {fromTimestamp: DateTime64(3)}
+ AND timestamp <= {toTimestamp: DateTime64(3)}
+ AND is_deleted = 0
+ AND ${samplingExpression}
+ ${objectTypeFilter}
+ ),
+ score2_sample AS (
+ SELECT trace_id, observation_id, session_id, dataset_run_id
+ FROM scores
+ PREWHERE project_id = {projectId: String}
+ AND name = {score2Name: String}
+ WHERE source = {score2Source: String}
+ AND data_type = {score2DataType: String}
+ AND timestamp >= {fromTimestamp: DateTime64(3)}
+ AND timestamp <= {toTimestamp: DateTime64(3)}
+ AND is_deleted = 0
+ AND ${samplingExpression}
+ ${objectTypeFilter}
+ )
+ SELECT
+ (SELECT count() FROM score1_sample) * 100 as score1_count,
+ (SELECT count() FROM score2_sample) * 100 as score2_count,
+ (
+ SELECT count() * 100
+ FROM score1_sample s1
+ INNER JOIN score2_sample s2
+ ON ifNull(s1.trace_id, '') = ifNull(s2.trace_id, '')
+ AND ifNull(s1.observation_id, '') = ifNull(s2.observation_id, '')
+ AND ifNull(s1.session_id, '') = ifNull(s2.session_id, '')
+ AND ifNull(s1.dataset_run_id, '') = ifNull(s2.dataset_run_id, '')
+ ) as estimated_matched_count
+ `;
+
+ const result = await queryClickhouse<{
+ score1_count: string;
+ score2_count: string;
+ estimated_matched_count: string;
+ }>({
+ query: preflightQuery,
+ params: {
+ projectId,
+ score1Name,
+ score1Source,
+ score1DataType: score1DataType,
+ score2Name,
+ score2Source,
+ score2DataType: score2DataType,
+ fromTimestamp,
+ toTimestamp,
+ },
+ });
+
+ const row = result[0];
+ return {
+ score1Count: parseInt(row?.score1_count ?? "0", 10),
+ score2Count: parseInt(row?.score2_count ?? "0", 10),
+ estimatedMatchedCount: parseInt(row?.estimated_matched_count ?? "0", 10),
+ };
+}
diff --git a/web/src/features/score-analytics/server/buildScoreComparisonQuery.ts b/web/src/features/score-analytics/server/buildScoreComparisonQuery.ts
new file mode 100644
index 0000000000..dce75e6152
--- /dev/null
+++ b/web/src/features/score-analytics/server/buildScoreComparisonQuery.ts
@@ -0,0 +1,1014 @@
+/**
+ * ClickHouse Query Builder for Score Comparison Analytics
+ *
+ * This module contains the comprehensive query logic for score comparison analytics.
+ * The query uses a WITH (CTE) chain to compute multiple analytics in a single query:
+ * - Filtering and sampling
+ * - Matching scores across attachment points (trace/observation/session/run)
+ * - Heatmaps and confusion matrices
+ * - Statistical metrics (mean, std, correlations)
+ * - Time series aggregations
+ * - Distributions (numeric and categorical)
+ *
+ * PERFORMANCE NOTE:
+ * Most of the query is memory-light, but needs to scan lots of data. This is the
+ * main driver of runtime. We would expect similar performance, but better separation
+ * if each of the CTEs runs separately and scans through the scores on their own.
+ * If we proceed with this feature, we may separate the queries for better dev
+ * experience and maintainability. That would also allow us to gradually move queries
+ * into any centrally developed metric query builder interface.
+ *
+ * The current CTE-based approach keeps dependencies visible and ensures data flows
+ * logically through the query plan. CTEs like `score1_filtered`, `score2_filtered`,
+ * and `matched_scores` are referenced by downstream CTEs (bounds, heatmap, stats, etc.),
+ * so the entire query must remain cohesive.
+ */
+
+import {
+ normalizeIntervalForClickHouse,
+ getClickHouseTimeBucketFunction,
+} from "@/src/features/score-analytics/lib/clickhouse-time-utils";
+import { type IntervalConfig } from "@/src/utils/date-range-utils";
+import { buildObjectTypeFilter, buildSamplingExpression } from "./queryHelpers";
+
+/**
+ * Build comprehensive score comparison analytics query
+ *
+ * Returns a single UNION ALL query that computes:
+ * - Counts (total scores and matched pairs)
+ * - Heatmap (for numeric comparisons)
+ * - Confusion matrix (for categorical/boolean comparisons)
+ * - Statistics (mean, std, correlations, MAE, RMSE)
+ * - Time series (aggregated by intervals)
+ * - Distributions (numeric bins or categorical counts)
+ * - Stacked distributions (for categorical comparisons)
+ * - Categorical time series (category counts over time)
+ *
+ * @param params - Query configuration parameters
+ * @returns ClickHouse SQL query string
+ */
+export function buildScoreComparisonQuery(params: {
+ projectId: string;
+ score1: { name: string; dataType: string; source: string };
+ score2: { name: string; dataType: string; source: string };
+ fromTimestamp: Date;
+ toTimestamp: Date;
+ interval: IntervalConfig;
+ nBins: number;
+ objectType: string;
+ shouldUseFinal: boolean;
+ shouldSample: boolean;
+ samplingPercent: number;
+ isIdenticalScores: boolean;
+ isSingleScore: boolean;
+ isNumeric: boolean;
+ isCategoricalComparison: boolean;
+}): string {
+ const {
+ objectType,
+ shouldUseFinal,
+ shouldSample,
+ samplingPercent,
+ isIdenticalScores,
+ isSingleScore,
+ isNumeric,
+ isCategoricalComparison,
+ } = params;
+
+ // Normalize the interval for ClickHouse (always single-unit except 7-day weeks)
+ const normalizedInterval = normalizeIntervalForClickHouse(params.interval);
+
+ // Build object type filter based on selection
+ const objectTypeFilter = buildObjectTypeFilter(objectType);
+
+ // Build sampling expression
+ const samplingExpression = shouldSample
+ ? buildSamplingExpression(samplingPercent)
+ : null;
+
+ // ============================================
+ // CONDITIONAL CTE BUILDERS
+ // ============================================
+
+ // Build distribution CTEs conditionally based on data type
+ const distribution1CTE = isNumeric
+ ? `-- CTE 9: Distribution for score1 (numeric, using global bounds)
+ distribution1 AS (
+ SELECT
+ floor((s.value - b.global_min) /
+ ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
+ count() as count
+ FROM score1_filtered s
+ CROSS JOIN bounds b
+ GROUP BY bin_index
+ )`
+ : `-- CTE 9: Distribution for score1 (categorical/boolean or cross-type)
+ distribution1 AS (
+ SELECT
+ (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value, toString(value))) - 1) as bin_index,
+ count() as count
+ FROM score1_filtered
+ WHERE string_value IS NOT NULL OR value IS NOT NULL
+ GROUP BY COALESCE(string_value, toString(value))
+ ORDER BY bin_index
+ )`;
+
+ const distribution2CTE = isNumeric
+ ? `-- CTE 10: Distribution for score2 (numeric, using global bounds)
+ distribution2 AS (
+ SELECT
+ floor((s.value - b.global_min) /
+ ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
+ count() as count
+ FROM score2_filtered s
+ CROSS JOIN bounds b
+ GROUP BY bin_index
+ )`
+ : `-- CTE 10: Distribution for score2 (categorical/boolean or cross-type)
+ distribution2 AS (
+ SELECT
+ (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value, toString(value))) - 1) as bin_index,
+ count() as count
+ FROM score2_filtered
+ WHERE string_value IS NOT NULL OR value IS NOT NULL
+ GROUP BY COALESCE(string_value, toString(value))
+ ORDER BY bin_index
+ )`;
+
+ // Build time series CTE conditionally based on single vs two-score
+ const timeseriesCTE = isSingleScore
+ ? `-- CTE 8: Time series (single score)
+ timeseries AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
+ avg(value) as avg1,
+ CAST(NULL AS Nullable(Float64)) as avg2,
+ count() as count
+ FROM score1_filtered
+ WHERE value IS NOT NULL
+ GROUP BY ts
+ ORDER BY ts
+ )`
+ : `-- CTE 8: Time series (two scores - ALL data, includes unmatched)
+ timeseries AS (
+ WITH
+ score1_time_agg AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
+ avg(value) as avg1,
+ count() as count1
+ FROM score1_filtered
+ WHERE value IS NOT NULL
+ GROUP BY ts
+ ),
+ score2_time_agg AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
+ avg(value) as avg2,
+ count() as count2
+ FROM score2_filtered
+ WHERE value IS NOT NULL
+ GROUP BY ts
+ )
+ SELECT
+ COALESCE(s1.ts, s2.ts) as ts,
+ s1.avg1 as avg1,
+ s2.avg2 as avg2,
+ (COALESCE(s1.count1, 0) + COALESCE(s2.count2, 0)) as count
+ FROM score1_time_agg s1
+ FULL OUTER JOIN score2_time_agg s2 ON s1.ts = s2.ts
+ ORDER BY ts
+ )`;
+
+ // Build matched-only CTEs for distributions and single-score time series
+ const distribution1MatchedCTE = isNumeric
+ ? `-- CTE 11: Distribution for score1 (numeric, matched only)
+ distribution1_matched AS (
+ SELECT
+ floor((m.value1 - b.global_min) /
+ ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
+ count() as count
+ FROM matched_scores m
+ CROSS JOIN bounds b
+ GROUP BY bin_index
+ )`
+ : `-- CTE 11: Distribution for score1 (categorical/boolean or cross-type, matched only)
+ distribution1_matched AS (
+ SELECT
+ (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value1, toString(value1))) - 1) as bin_index,
+ count() as count
+ FROM matched_scores
+ WHERE string_value1 IS NOT NULL OR value1 IS NOT NULL
+ GROUP BY COALESCE(string_value1, toString(value1))
+ ORDER BY bin_index
+ )`;
+
+ const distribution2MatchedCTE = isNumeric
+ ? `-- CTE 12: Distribution for score2 (numeric, matched only)
+ distribution2_matched AS (
+ SELECT
+ floor((m.value2 - b.global_min) /
+ ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
+ count() as count
+ FROM matched_scores m
+ CROSS JOIN bounds b
+ GROUP BY bin_index
+ )`
+ : `-- CTE 12: Distribution for score2 (categorical/boolean or cross-type, matched only)
+ distribution2_matched AS (
+ SELECT
+ (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value2, toString(value2))) - 1) as bin_index,
+ count() as count
+ FROM matched_scores
+ WHERE string_value2 IS NOT NULL OR value2 IS NOT NULL
+ GROUP BY COALESCE(string_value2, toString(value2))
+ ORDER BY bin_index
+ )`;
+
+ // Build individual-bound distributions for single-score display
+ const distribution1IndividualCTE = isNumeric
+ ? `-- CTE 13: Distribution for score1 (numeric, using individual bounds for single-score view)
+ distribution1_individual AS (
+ SELECT
+ floor((s.value - b.min1) /
+ ((b.max1 - b.min1 + 0.0001) / {nBins: UInt8})) as bin_index,
+ count() as count
+ FROM score1_filtered s
+ CROSS JOIN bounds b
+ GROUP BY bin_index
+ )`
+ : `-- CTE 13: Distribution for score1 (categorical/boolean, same as distribution1)
+ distribution1_individual AS (
+ SELECT bin_index, count
+ FROM distribution1
+ ORDER BY bin_index
+ )`;
+
+ const distribution2IndividualCTE = isNumeric
+ ? `-- CTE 14: Distribution for score2 (numeric, using individual bounds for single-score view)
+ distribution2_individual AS (
+ SELECT
+ floor((s.value - b.min2) /
+ ((b.max2 - b.min2 + 0.0001) / {nBins: UInt8})) as bin_index,
+ count() as count
+ FROM score2_filtered s
+ CROSS JOIN bounds b
+ GROUP BY bin_index
+ )`
+ : `-- CTE 14: Distribution for score2 (categorical/boolean, same as distribution2)
+ distribution2_individual AS (
+ SELECT bin_index, count
+ FROM distribution2
+ ORDER BY bin_index
+ )`;
+
+ // Build matched-only time series for single-score mode
+ const timeseriesMatchedCTE = isSingleScore
+ ? `-- CTE 15: Time series (single score, matched only)
+ timeseries_matched AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
+ avg(value1) as avg1,
+ CAST(NULL AS Nullable(Float64)) as avg2,
+ count() as count
+ FROM matched_scores
+ WHERE value1 IS NOT NULL
+ GROUP BY ts
+ ORDER BY ts
+ )`
+ : `-- CTE 15: Time series (two scores, matched only - re-query matched_scores)
+ timeseries_matched AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
+ avg(value1) as avg1,
+ avg(value2) as avg2,
+ count() as count
+ FROM matched_scores
+ GROUP BY ts
+ ORDER BY ts
+ )`;
+
+ // Build categorical/boolean time series CTEs
+ // These show counts per category over time (not averages)
+ const timeseriesCategorical1CTE = isSingleScore
+ ? `-- CTE 16: Categorical time series for score1 (single score mode)
+ timeseries_categorical1 AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
+ COALESCE(string_value, toString(value)) as category,
+ count() as count
+ FROM score1_filtered
+ WHERE string_value IS NOT NULL OR value IS NOT NULL
+ GROUP BY ts, category
+ ORDER BY ts, category
+ )`
+ : `-- CTE 16: Categorical time series for score1 (two score mode)
+ timeseries_categorical1 AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
+ COALESCE(string_value, toString(value)) as category,
+ count() as count
+ FROM score1_filtered
+ WHERE string_value IS NOT NULL OR value IS NOT NULL
+ GROUP BY ts, category
+ ORDER BY ts, category
+ )`;
+
+ const timeseriesCategorical2CTE = isSingleScore
+ ? `-- CTE 17: Categorical time series for score2 (not needed in single score mode)
+ timeseries_categorical2 AS (
+ SELECT
+ CAST(NULL AS Nullable(DateTime)) as ts,
+ CAST(NULL AS Nullable(String)) as category,
+ CAST(NULL AS Nullable(UInt64)) as count
+ WHERE 1 = 0
+ )`
+ : `-- CTE 17: Categorical time series for score2 (two score mode)
+ timeseries_categorical2 AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
+ COALESCE(string_value, toString(value)) as category,
+ count() as count
+ FROM score2_filtered
+ WHERE string_value IS NOT NULL OR value IS NOT NULL
+ GROUP BY ts, category
+ ORDER BY ts, category
+ )`;
+
+ const timeseriesCategorical1MatchedCTE = isSingleScore
+ ? `-- CTE 18: Categorical time series for score1 (single score, matched only)
+ timeseries_categorical1_matched AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
+ COALESCE(string_value1, toString(value1)) as category,
+ count() as count
+ FROM matched_scores
+ WHERE string_value1 IS NOT NULL OR value1 IS NOT NULL
+ GROUP BY ts, category
+ ORDER BY ts, category
+ )`
+ : `-- CTE 18: Categorical time series for score1 (two scores, matched only)
+ timeseries_categorical1_matched AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
+ COALESCE(string_value1, toString(value1)) as category,
+ count() as count
+ FROM matched_scores
+ WHERE string_value1 IS NOT NULL OR value1 IS NOT NULL
+ GROUP BY ts, category
+ ORDER BY ts, category
+ )`;
+
+ const timeseriesCategorical2MatchedCTE = isSingleScore
+ ? `-- CTE 19: Categorical time series for score2 (not needed in single score mode)
+ timeseries_categorical2_matched AS (
+ SELECT
+ CAST(NULL AS Nullable(DateTime)) as ts,
+ CAST(NULL AS Nullable(String)) as category,
+ CAST(NULL AS Nullable(UInt64)) as count
+ WHERE 1 = 0
+ )`
+ : `-- CTE 19: Categorical time series for score2 (two scores, matched only)
+ timeseries_categorical2_matched AS (
+ SELECT
+ ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
+ COALESCE(string_value2, toString(value2)) as category,
+ count() as count
+ FROM matched_scores
+ WHERE string_value2 IS NOT NULL OR value2 IS NOT NULL
+ GROUP BY ts, category
+ ORDER BY ts, category
+ )`;
+
+ // ============================================
+ // MAIN QUERY CONSTRUCTION
+ // ============================================
+
+ return `
+ WITH
+ -- ============================================
+ -- FILTERING CTEs (produce filtered datasets)
+ -- ============================================
+
+ -- CTE 1: Filter score 1
+ -- PREWHERE optimization: Apply most selective filters (project_id, name) early
+ -- to reduce data read from disk before applying other filters
+ -- Adaptive FINAL: Only use FINAL for small datasets (<100k) to balance accuracy vs performance
+ -- Hash-based sampling: Applied when estimated matched count exceeds threshold
+ score1_filtered AS (
+ SELECT
+ id, value, string_value,
+ trace_id, observation_id, session_id, dataset_run_id as run_id,
+ timestamp
+ FROM scores ${shouldUseFinal ? "FINAL" : ""}
+ PREWHERE project_id = {projectId: String}
+ AND name = {score1Name: String}
+ WHERE source = {score1Source: String}
+ AND data_type = {dataType1: String}
+ AND timestamp >= {fromTimestamp: DateTime64(3)}
+ AND timestamp <= {toTimestamp: DateTime64(3)}
+ AND is_deleted = 0
+ ${objectTypeFilter}
+ ${shouldSample ? `AND ${samplingExpression}` : ""}
+ ),
+
+ -- CTE 2: Filter score 2
+ -- PREWHERE optimization: Apply most selective filters (project_id, name) early
+ -- Adaptive FINAL: Only use FINAL for small datasets (<100k)
+ -- Hash-based sampling: Applied when estimated matched count exceeds threshold
+ -- Special case: When comparing identical scores, reuse score1_filtered to ensure perfect correlation
+ score2_filtered AS (
+ ${
+ isIdenticalScores
+ ? `SELECT * FROM score1_filtered`
+ : `SELECT
+ id, value, string_value,
+ trace_id, observation_id, session_id, dataset_run_id as run_id,
+ timestamp
+ FROM scores ${shouldUseFinal ? "FINAL" : ""}
+ PREWHERE project_id = {projectId: String}
+ AND name = {score2Name: String}
+ WHERE source = {score2Source: String}
+ AND data_type = {dataType2: String}
+ AND timestamp >= {fromTimestamp: DateTime64(3)}
+ AND timestamp <= {toTimestamp: DateTime64(3)}
+ AND is_deleted = 0
+ ${objectTypeFilter}
+ ${shouldSample ? `AND ${samplingExpression}` : ""}`
+ }
+ ),
+
+ -- CTE 3: Match scores - must have exact same attachment (trace/obs/session/run)
+ -- NULL-safe comparison: convert NULL to empty string for comparison
+ -- Special case: For identical scores, use self-join on ID to ensure perfect pairing
+ -- Note: No LIMIT needed - sampling already ensures score1_filtered and score2_filtered are ~100k rows max
+ matched_scores AS (
+ SELECT
+ s1.value as value1,
+ s1.string_value as string_value1,
+ ${isIdenticalScores ? "s1.value" : "s2.value"} as value2,
+ ${isIdenticalScores ? "s1.string_value" : "s2.string_value"} as string_value2,
+ s1.timestamp as timestamp1,
+ ${isIdenticalScores ? "s1.timestamp" : "s2.timestamp"} as timestamp2,
+ ${isIdenticalScores ? "s1.trace_id" : "coalesce(s1.trace_id, s2.trace_id)"} as trace_id,
+ ${isIdenticalScores ? "s1.observation_id" : "coalesce(s1.observation_id, s2.observation_id)"} as observation_id,
+ ${isIdenticalScores ? "s1.session_id" : "coalesce(s1.session_id, s2.session_id)"} as session_id,
+ ${isIdenticalScores ? "s1.run_id" : "coalesce(s1.run_id, s2.run_id)"} as run_id
+ FROM score1_filtered s1
+ INNER JOIN ${isIdenticalScores ? "score1_filtered" : "score2_filtered"} s2
+ ON ${
+ isIdenticalScores
+ ? "s1.id = s2.id"
+ : `ifNull(s1.trace_id, '') = ifNull(s2.trace_id, '')
+ AND ifNull(s1.observation_id, '') = ifNull(s2.observation_id, '')
+ AND ifNull(s1.session_id, '') = ifNull(s2.session_id, '')
+ AND ifNull(s1.run_id, '') = ifNull(s2.run_id, '')`
+ }
+ LIMIT 1000000 -- Safety limit to prevent Cartesian product explosions when multiple scores of same name/source exist on one attachment point (trace/observation/session/run)
+ ),
+
+ -- CTE 3a: Count all matched score pairs
+ -- Counts all rows in matched_scores (not unique attachment points).
+ -- NOTE: When multiple scores of same name/source exist on one attachment point,
+ -- matched count can exceed both score1Total and score2Total due to Cartesian product.
+ -- Example: 2 "gpt4" scores + 3 "gemini" scores on same trace = 6 matched pairs (2 × 3 = 6).
+ -- This is correct behavior - each score pair combination is a valid match.
+ matched_count AS (
+ SELECT count(*) as cnt
+ FROM matched_scores
+ ),
+
+ -- ============================================
+ -- BOUNDS CTEs (calculate ranges for binning)
+ -- ============================================
+
+ -- CTE 4: Bounds (for numeric heatmap and distribution binning)
+ -- Calculate global bounds across ALL scores (not just matched) for consistent binning
+ bounds AS (
+ SELECT
+ least(
+ (SELECT min(value) FROM score1_filtered),
+ (SELECT min(value) FROM score2_filtered)
+ ) as global_min,
+ greatest(
+ (SELECT max(value) FROM score1_filtered),
+ (SELECT max(value) FROM score2_filtered)
+ ) as global_max,
+ -- Keep individual bounds for reference (used in response)
+ (SELECT min(value) FROM score1_filtered) as min1,
+ (SELECT max(value) FROM score1_filtered) as max1,
+ (SELECT min(value) FROM score2_filtered) as min2,
+ (SELECT max(value) FROM score2_filtered) as max2
+ ),
+
+ -- ============================================
+ -- ANALYTICS CTEs (use filtered data + bounds)
+ -- ============================================
+
+ -- CTE 5: Heatmap (numeric only, NxN grid using independent bounds per score)
+ heatmap AS (
+ SELECT
+ floor((m.value1 - b.min1) / ((b.max1 - b.min1 + 0.0001) / {nBins: UInt8})) as bin_x,
+ floor((m.value2 - b.min2) / ((b.max2 - b.min2 + 0.0001) / {nBins: UInt8})) as bin_y,
+ count() as count,
+ b.global_min, b.global_max,
+ b.min1, b.max1, b.min2, b.max2
+ FROM matched_scores m
+ CROSS JOIN bounds b
+ GROUP BY bin_x, bin_y, b.global_min, b.global_max, b.min1, b.max1, b.min2, b.max2
+ ),
+
+ -- CTE 6: Confusion matrix (categorical/boolean and cross-type)
+ confusion AS (
+ SELECT
+ COALESCE(string_value1, toString(value1)) as row_category,
+ COALESCE(string_value2, toString(value2)) as col_category,
+ count() as count
+ FROM matched_scores
+ GROUP BY row_category, col_category
+ ),
+
+ ${
+ isCategoricalComparison
+ ? `-- CTE 6a: LEFT JOIN score1 with score2 for stacked distribution
+ score1_with_score2 AS (
+ SELECT
+ -- Use string_value for categorical/boolean, convert value to string for numeric
+ COALESCE(s1.string_value, toString(s1.value)) as score1_category,
+ COALESCE(s2.string_value, toString(s2.value)) as score2_category
+ FROM score1_filtered s1
+ LEFT JOIN score2_filtered s2
+ ON ifNull(s1.trace_id, '') = ifNull(s2.trace_id, '')
+ AND ifNull(s1.observation_id, '') = ifNull(s2.observation_id, '')
+ AND ifNull(s1.session_id, '') = ifNull(s2.session_id, '')
+ AND ifNull(s1.run_id, '') = ifNull(s2.run_id, '')
+ LIMIT 1000000 -- Safety limit for categorical LEFT JOIN (more prone to expansion than INNER JOIN)
+ ),
+
+ -- CTE 6b: Stacked distribution (score1 categories with score2 breakdowns)
+ stacked_distribution AS (
+ SELECT
+ score1_category,
+ coalesce(score2_category, '__unmatched__') as score2_stack,
+ count() as count
+ FROM score1_with_score2
+ WHERE score1_category IS NOT NULL
+ GROUP BY score1_category, score2_stack
+ ORDER BY score1_category, score2_stack
+ ),
+
+ -- CTE 6c: All score2 categories for legend
+ score2_categories AS (
+ SELECT DISTINCT COALESCE(string_value, toString(value)) as category
+ FROM score2_filtered
+ WHERE string_value IS NOT NULL OR value IS NOT NULL
+ ORDER BY category
+ ),
+
+ -- CTE 6d: Stacked distribution (matched only - no __unmatched__)
+ stacked_distribution_matched AS (
+ SELECT
+ COALESCE(string_value1, toString(value1)) as score1_category,
+ COALESCE(string_value2, toString(value2)) as score2_stack,
+ count() as count
+ FROM matched_scores
+ WHERE (string_value1 IS NOT NULL OR value1 IS NOT NULL)
+ AND (string_value2 IS NOT NULL OR value2 IS NOT NULL)
+ GROUP BY score1_category, score2_stack
+ ORDER BY score1_category, score2_stack
+ ),`
+ : ""
+ }
+
+ -- CTE 7: Correlation safety check
+ -- Pre-compute whether it's safe to calculate correlations
+ -- Requires at least 2 data points and non-zero variance in both samples
+ correlation_check AS (
+ SELECT
+ count() >= 2
+ AND stddevPop(value1) > 0
+ AND stddevPop(value2) > 0 as is_safe
+ FROM matched_scores
+ ),
+
+ -- CTE 8: Statistics
+ -- IMPORTANT: Calculate mean/std from individual filtered scores, NOT matched_scores
+ -- This ensures statistics are available even when matchedCount = 0
+ -- Comparison metrics (mae/rmse/correlations) still use matched_scores since they require pairs
+ stats AS (
+ SELECT
+ (SELECT count() FROM matched_scores) as matched_count,
+ ${
+ isNumeric
+ ? `-- Individual score statistics from filtered tables (not matched pairs)
+ (SELECT avg(value) FROM score1_filtered) as mean1,
+ (SELECT avg(value) FROM score2_filtered) as mean2,
+ (SELECT stddevPop(value) FROM score1_filtered) as std1,
+ (SELECT stddevPop(value) FROM score2_filtered) as std2,
+ -- Comparison metrics require matched pairs
+ (SELECT avg(abs(value1 - value2)) FROM matched_scores) as mae,
+ (SELECT sqrt(avg(pow(value1 - value2, 2))) FROM matched_scores) as rmse,
+ -- Conditional correlation: only execute subquery if safe
+ -- Uses short-circuit evaluation to prevent errors with insufficient data
+ ${
+ isIdenticalScores
+ ? "NULL"
+ : `if(
+ (SELECT is_safe FROM correlation_check),
+ (SELECT corr(value1, value2) FROM matched_scores),
+ NULL
+ )`
+ } as pearson_correlation,
+ ${
+ isIdenticalScores
+ ? "NULL"
+ : `if(
+ (SELECT is_safe FROM correlation_check),
+ (SELECT rankCorr(value1, value2) FROM matched_scores),
+ NULL
+ )`
+ } as spearman_correlation`
+ : `-- Categorical/boolean scores: statistical metrics are not meaningful
+ NULL as mean1,
+ NULL as mean2,
+ NULL as std1,
+ NULL as std2,
+ NULL as pearson_correlation,
+ NULL as spearman_correlation,
+ NULL as mae,
+ NULL as rmse`
+ }
+ ),
+
+ ${timeseriesCTE},
+
+ ${distribution1CTE},
+
+ ${distribution2CTE},
+
+ ${distribution1MatchedCTE},
+
+ ${distribution2MatchedCTE},
+
+ ${distribution1IndividualCTE},
+
+ ${distribution2IndividualCTE},
+
+ ${timeseriesMatchedCTE},
+
+ ${timeseriesCategorical1CTE},
+
+ ${timeseriesCategorical2CTE},
+
+ ${timeseriesCategorical1MatchedCTE},
+
+ ${timeseriesCategorical2MatchedCTE}
+
+ -- ============================================
+ -- UNION ALL RESULTS (return multiple result sets)
+ -- ============================================
+ SELECT
+ 'counts' as result_type,
+ CAST((SELECT count() FROM score1_filtered) AS Float64) as col1,
+ CAST((SELECT count() FROM score2_filtered) AS Float64) as col2,
+ CAST((SELECT cnt FROM matched_count) AS Float64) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+
+ UNION ALL
+
+ SELECT
+ 'heatmap' as result_type,
+ CAST(bin_x AS Float64) as col1,
+ CAST(bin_y AS Float64) as col2,
+ CAST(count AS Float64) as col3,
+ min1 as col4, -- Individual bounds for score1
+ max1 as col5,
+ min2 as col6, -- Individual bounds for score2
+ max2 as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ global_min as col11, -- Global bounds for comparison
+ global_max as col12
+ FROM heatmap
+
+ UNION ALL
+
+ SELECT
+ 'confusion' as result_type,
+ CAST(count AS Float64) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ row_category as col9,
+ col_category as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM confusion
+
+ UNION ALL
+
+ SELECT
+ 'stats' as result_type,
+ CAST(matched_count AS Float64) as col1,
+ mean1 as col2,
+ mean2 as col3,
+ std1 as col4,
+ std2 as col5,
+ pearson_correlation as col6,
+ mae as col7,
+ rmse as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ spearman_correlation as col12
+ FROM stats
+
+ UNION ALL
+
+ SELECT
+ 'timeseries' as result_type,
+ CAST(toUnixTimestamp(ts) AS Float64) as col1,
+ CAST(avg1 AS Nullable(Float64)) as col2,
+ CAST(avg2 AS Nullable(Float64)) as col3,
+ CAST(count AS Float64) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM timeseries
+
+ UNION ALL
+
+ SELECT
+ 'distribution1' as result_type,
+ CAST(bin_index AS Float64) as col1,
+ CAST(count AS Float64) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM distribution1
+
+ UNION ALL
+
+ SELECT
+ 'distribution2' as result_type,
+ CAST(bin_index AS Float64) as col1,
+ CAST(count AS Float64) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM distribution2
+
+ ${
+ isCategoricalComparison
+ ? `
+ UNION ALL
+
+ SELECT
+ 'stacked' as result_type,
+ CAST(count AS Float64) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ score1_category as col9,
+ score2_stack as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM stacked_distribution
+
+ UNION ALL
+
+ SELECT
+ 'score2_categories' as result_type,
+ CAST(NULL AS Nullable(Float64)) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ category as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM score2_categories
+
+ UNION ALL
+
+ SELECT
+ 'stacked_matched' as result_type,
+ CAST(count AS Float64) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ score1_category as col9,
+ score2_stack as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM stacked_distribution_matched`
+ : ""
+ }
+
+ UNION ALL
+
+ SELECT
+ 'distribution1_matched' as result_type,
+ CAST(bin_index AS Float64) as col1,
+ CAST(count AS Float64) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM distribution1_matched
+
+ UNION ALL
+
+ SELECT
+ 'distribution2_matched' as result_type,
+ CAST(bin_index AS Float64) as col1,
+ CAST(count AS Float64) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM distribution2_matched
+
+ UNION ALL
+
+ SELECT
+ 'distribution1_individual' as result_type,
+ CAST(bin_index AS Float64) as col1,
+ CAST(count AS Float64) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM distribution1_individual
+
+ UNION ALL
+
+ SELECT
+ 'distribution2_individual' as result_type,
+ CAST(bin_index AS Float64) as col1,
+ CAST(count AS Float64) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(NULL AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM distribution2_individual
+
+ UNION ALL
+
+ SELECT
+ 'timeseries_matched' as result_type,
+ CAST(toUnixTimestamp(ts) AS Float64) as col1,
+ CAST(avg1 AS Nullable(Float64)) as col2,
+ CAST(avg2 AS Nullable(Float64)) as col3,
+ CAST(count AS Float64) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ CAST(NULL AS Nullable(String)) as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM timeseries_matched
+
+ UNION ALL
+
+ SELECT
+ 'timeseries_categorical1' as result_type,
+ CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(count AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ category as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM timeseries_categorical1
+
+ UNION ALL
+
+ SELECT
+ 'timeseries_categorical2' as result_type,
+ CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(count AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ category as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM timeseries_categorical2
+
+ UNION ALL
+
+ SELECT
+ 'timeseries_categorical1_matched' as result_type,
+ CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(count AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ category as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM timeseries_categorical1_matched
+
+ UNION ALL
+
+ SELECT
+ 'timeseries_categorical2_matched' as result_type,
+ CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
+ CAST(NULL AS Nullable(Float64)) as col2,
+ CAST(NULL AS Nullable(Float64)) as col3,
+ CAST(count AS Nullable(Float64)) as col4,
+ CAST(NULL AS Nullable(Float64)) as col5,
+ CAST(NULL AS Nullable(Float64)) as col6,
+ CAST(NULL AS Nullable(Float64)) as col7,
+ CAST(NULL AS Nullable(Float64)) as col8,
+ category as col9,
+ CAST(NULL AS Nullable(String)) as col10,
+ CAST(NULL AS Nullable(Float64)) as col11,
+ CAST(NULL AS Nullable(Float64)) as col12
+ FROM timeseries_categorical2_matched
+ `;
+}
diff --git a/web/src/features/score-analytics/server/queryHelpers.ts b/web/src/features/score-analytics/server/queryHelpers.ts
new file mode 100644
index 0000000000..2a0596c5d0
--- /dev/null
+++ b/web/src/features/score-analytics/server/queryHelpers.ts
@@ -0,0 +1,68 @@
+/**
+ * Shared ClickHouse query building utilities for score analytics
+ *
+ * These helpers are used by both buildEstimateQuery and buildScoreComparisonQuery
+ * to construct SQL fragments for filtering and sampling.
+ */
+
+/**
+ * Build object type filter for score queries
+ *
+ * Generates SQL WHERE clause fragment to filter scores by attachment type.
+ * Ensures exclusive filtering (exactly one non-NULL ID) for trace, observation,
+ * session, and dataset_run types.
+ *
+ * @param objectType - The object type to filter by
+ * @returns SQL WHERE clause fragment for object type filtering
+ *
+ * @example
+ * ```typescript
+ * buildObjectTypeFilter("trace")
+ * // Returns: "AND trace_id IS NOT NULL AND observation_id IS NULL AND session_id IS NULL AND dataset_run_id IS NULL"
+ *
+ * buildObjectTypeFilter("all")
+ * // Returns: ""
+ * ```
+ */
+export function buildObjectTypeFilter(objectType: string): string {
+ if (objectType === "all") return "";
+ if (objectType === "trace")
+ return "AND trace_id IS NOT NULL AND observation_id IS NULL AND session_id IS NULL AND dataset_run_id IS NULL";
+ if (objectType === "observation") return "AND observation_id IS NOT NULL";
+ if (objectType === "session")
+ return "AND session_id IS NOT NULL AND observation_id IS NULL AND trace_id IS NULL AND dataset_run_id IS NULL";
+ if (objectType === "dataset_run")
+ return "AND dataset_run_id IS NOT NULL AND trace_id IS NULL AND observation_id IS NULL AND session_id IS NULL";
+ return "";
+}
+
+/**
+ * Build sampling expression for hash-based sampling
+ *
+ * Uses cityHash64 on composite key (trace_id, observation_id, session_id, dataset_run_id)
+ * to ensure deterministic pseudo-random sampling that preserves matched pairs across
+ * score1 and score2 queries.
+ *
+ * The cityHash64 function provides uniform distribution, and modulo operation ensures
+ * consistent sampling across different score tables.
+ *
+ * @param samplingPercent - Percentage to sample (0-100)
+ * @returns SQL expression for hash-based sampling
+ *
+ * @example
+ * ```typescript
+ * buildSamplingExpression(10)
+ * // Returns: "cityHash64(...) % 100 < 10"
+ *
+ * buildSamplingExpression(100)
+ * // Returns: "cityHash64(...) % 100 < 100" (no sampling, all data)
+ * ```
+ */
+export function buildSamplingExpression(samplingPercent: number): string {
+ return `cityHash64(
+ coalesce(trace_id, ''),
+ coalesce(observation_id, ''),
+ coalesce(session_id, ''),
+ coalesce(dataset_run_id, '')
+ ) % 100 < ${samplingPercent}`;
+}
diff --git a/web/src/features/score-analytics/server/scoreAnalyticsRouter.ts b/web/src/features/score-analytics/server/scoreAnalyticsRouter.ts
new file mode 100644
index 0000000000..3c7348313f
--- /dev/null
+++ b/web/src/features/score-analytics/server/scoreAnalyticsRouter.ts
@@ -0,0 +1,563 @@
+import { z } from "zod/v4";
+
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import {
+ getScoresGroupedByNameSourceType,
+ queryClickhouse,
+ convertDateToClickhouseDateTime,
+} from "@langfuse/shared/src/server";
+import { buildEstimateQuery } from "./buildEstimateQuery";
+import { buildScoreComparisonQuery } from "./buildScoreComparisonQuery";
+
+/**
+ * Adaptive FINAL threshold
+ * - Use FINAL for datasets < 100k to ensure accuracy
+ * - Skip FINAL for datasets >= 100k to improve query performance
+ */
+const ADAPTIVE_FINAL_THRESHOLD = 100_000;
+
+/**
+ * Hash-based sampling thresholds
+ * - SAMPLING_THRESHOLD: Sample when either score table exceeds this count
+ * - TARGET_SAMPLE_SIZE: Target number of rows to sample from each table
+ */
+const SAMPLING_THRESHOLD = 100_000; // Start sampling if either table > 100k
+const TARGET_SAMPLE_SIZE = 100_000; // Aim for 100k samples from each table
+
+export const scoreAnalyticsRouter = createTRPCRouter({
+ /**
+ * Get available score identifiers for analytics dropdown
+ */
+ getScoreIdentifiers: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ }),
+ )
+ .query(async ({ input }) => {
+ const { projectId } = input;
+
+ // Query ClickHouse for distinct score names, data types, and sources
+ const groupedScores = await getScoresGroupedByNameSourceType({
+ projectId,
+ filter: [],
+ });
+
+ // Format for ScoreSelector component: "name-dataType-source"
+ const scores = groupedScores.map(({ name, source, dataType }) => ({
+ value: `${name}-${dataType}-${source}`,
+ name,
+ dataType,
+ source,
+ }));
+
+ return { scores };
+ }),
+
+ /**
+ * Estimate score comparison size for UI loading indicators
+ * Returns quick estimates without running full analytics query
+ */
+ estimateScoreComparisonSize: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ score1: z.object({
+ name: z.string(),
+ dataType: z.string(),
+ source: z.string(),
+ }),
+ score2: z.object({
+ name: z.string(),
+ dataType: z.string(),
+ source: z.string(),
+ }),
+ fromTimestamp: z.date(),
+ toTimestamp: z.date(),
+ objectType: z
+ .enum(["all", "trace", "session", "observation", "dataset_run"])
+ .default("all"),
+ mode: z.enum(["single", "two"]).optional(), // Frontend passes "single" when only score1 selected
+ }),
+ )
+ .query(async ({ input }) => {
+ const {
+ projectId,
+ score1,
+ score2,
+ fromTimestamp,
+ toTimestamp,
+ objectType,
+ } = input;
+
+ // Run preflight estimate (uses 1% sampling)
+ const estimates = await buildEstimateQuery({
+ projectId,
+ score1Name: score1.name,
+ score1Source: score1.source,
+ score1DataType: score1.dataType,
+ score2Name: score2.name,
+ score2Source: score2.source,
+ score2DataType: score2.dataType,
+ fromTimestamp,
+ toTimestamp,
+ objectType,
+ });
+
+ // Determine if sampling and FINAL will be used
+ const willSample =
+ estimates.score1Count > SAMPLING_THRESHOLD ||
+ estimates.score2Count > SAMPLING_THRESHOLD;
+
+ const willSkipFinal =
+ estimates.score1Count >= ADAPTIVE_FINAL_THRESHOLD ||
+ estimates.score2Count >= ADAPTIVE_FINAL_THRESHOLD;
+
+ // Estimate query time based on dataset size
+ const estimatedQueryTime =
+ estimates.estimatedMatchedCount > 1_000_000
+ ? "30-60s"
+ : estimates.estimatedMatchedCount > 500_000
+ ? "15-30s"
+ : estimates.estimatedMatchedCount > 100_000
+ ? "10-20s"
+ : "<10s";
+
+ return {
+ score1Count: estimates.score1Count,
+ score2Count: estimates.score2Count,
+ estimatedMatchedCount: estimates.estimatedMatchedCount,
+ willSample,
+ willSkipFinal,
+ estimatedQueryTime,
+ mode: input.mode ?? "two", // Echo back the mode from frontend
+ };
+ }),
+ /**
+ * Get comprehensive score comparison analytics using single UNION ALL query
+ * Returns counts, heatmap, confusion matrix, statistics, time series, and distributions
+ */
+ getScoreComparisonAnalytics: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ score1: z.object({
+ name: z.string(),
+ dataType: z.string(),
+ source: z.string(),
+ }),
+ score2: z.object({
+ name: z.string(),
+ dataType: z.string(),
+ source: z.string(),
+ }),
+ mode: z.enum(["single", "two"]).optional(), // Frontend passes "single" when only score1 selected
+ fromTimestamp: z.date(),
+ toTimestamp: z.date(),
+ interval: z
+ .object({
+ count: z.number().int().positive(),
+ unit: z.enum(["second", "minute", "hour", "day", "month", "year"]),
+ })
+ .refine(
+ (val) => {
+ // Validate against allowed intervals
+ const allowed = [
+ // Seconds
+ { count: 1, unit: "second" },
+ { count: 5, unit: "second" },
+ { count: 10, unit: "second" },
+ { count: 30, unit: "second" },
+ // Minutes
+ { count: 1, unit: "minute" },
+ { count: 5, unit: "minute" },
+ { count: 10, unit: "minute" },
+ { count: 30, unit: "minute" },
+ // Hours
+ { count: 1, unit: "hour" },
+ { count: 3, unit: "hour" },
+ { count: 6, unit: "hour" },
+ { count: 12, unit: "hour" },
+ // Days
+ { count: 1, unit: "day" },
+ { count: 2, unit: "day" },
+ { count: 5, unit: "day" },
+ { count: 7, unit: "day" },
+ { count: 14, unit: "day" },
+ // Months
+ { count: 1, unit: "month" },
+ { count: 3, unit: "month" },
+ { count: 6, unit: "month" },
+ // Years
+ { count: 1, unit: "year" },
+ ];
+ return allowed.some(
+ (a) => a.count === val.count && a.unit === val.unit,
+ );
+ },
+ {
+ message:
+ "Invalid interval. Must be one of the allowed interval combinations.",
+ },
+ )
+ .default({ count: 1, unit: "day" }),
+ nBins: z.number().int().min(5).max(50).default(10),
+ objectType: z
+ .enum(["all", "trace", "session", "observation", "dataset_run"])
+ .default("all"),
+ // Optional: Pass estimate results from client to avoid duplicate preflight query
+ estimateResults: z
+ .object({
+ score1Count: z.number(),
+ score2Count: z.number(),
+ estimatedMatchedCount: z.number(),
+ })
+ .optional(),
+ }),
+ )
+ .query(async ({ input }) => {
+ const {
+ projectId,
+ score1,
+ score2,
+ fromTimestamp,
+ toTimestamp,
+ interval,
+ nBins,
+ objectType,
+ } = input;
+
+ // Note: The backend always returns both matched and unmatched datasets,
+ // as well as individual-bound distributions. The frontend chooses which
+ // to display based on the selected tab.
+
+ // Detect if comparing identical scores (same name, source, and dataType)
+ // When true, certain statistical calculations (like Spearman correlation)
+ // will be skipped since they're undefined for identical datasets
+ const isIdenticalScores =
+ score1.name === score2.name &&
+ score1.source === score2.source &&
+ score1.dataType === score2.dataType;
+
+ // Use estimate results passed from client if available, otherwise run preflight query
+ // This avoids duplicate estimate queries when client already called estimateScoreComparisonSize
+ const estimates =
+ input.estimateResults ??
+ (await buildEstimateQuery({
+ projectId,
+ score1Name: score1.name,
+ score1Source: score1.source,
+ score1DataType: score1.dataType,
+ score2Name: score2.name,
+ score2Source: score2.source,
+ score2DataType: score2.dataType,
+ fromTimestamp,
+ toTimestamp,
+ objectType,
+ }));
+
+ // Adaptive FINAL logic: Only use FINAL for small datasets to avoid expensive merge
+ // For large datasets, skip FINAL to improve performance (scores can be updated, so accuracy matters for recent data)
+ const shouldUseFinal =
+ estimates.score1Count < ADAPTIVE_FINAL_THRESHOLD &&
+ estimates.score2Count < ADAPTIVE_FINAL_THRESHOLD;
+
+ // Hash-based sampling decision: Sample when either score table exceeds threshold
+ const shouldSample =
+ estimates.score1Count > SAMPLING_THRESHOLD ||
+ estimates.score2Count > SAMPLING_THRESHOLD;
+
+ // Calculate rate based on larger table to ensure both tables sample to ~100k rows
+ const maxCount = Math.max(estimates.score1Count, estimates.score2Count);
+ const samplingRate = shouldSample
+ ? Math.min(1.0, TARGET_SAMPLE_SIZE / maxCount)
+ : 1.0;
+ const samplingPercent = Math.round(samplingRate * 100); // Convert to 0-100 for modulo
+
+ // Sampling expression using cityHash64 on composite key (trace_id, observation_id, session_id, dataset_run_id)
+ // This ensures deterministic pseudo-random sampling that preserves matched pairs
+ const samplingExpression = shouldSample
+ ? `cityHash64(
+ coalesce(trace_id, ''),
+ coalesce(observation_id, ''),
+ coalesce(session_id, ''),
+ coalesce(dataset_run_id, '')
+ ) % 100 < ${samplingPercent}`
+ : null;
+
+ // Determine if this is a single-score or two-score query
+ const isSingleScore =
+ score1.name === score2.name && score1.source === score2.source;
+
+ // Determine if we're dealing with numeric or categorical/boolean data
+ // Cross-type comparisons: treat as categorical if either score is non-numeric
+ const isCrossType =
+ score1.dataType !== score2.dataType &&
+ (score1.dataType !== "NUMERIC" || score2.dataType !== "NUMERIC");
+
+ const isNumeric =
+ score1.dataType === "NUMERIC" && score2.dataType === "NUMERIC";
+ const isCategoricalComparison =
+ !isNumeric && // Any non-numeric comparison
+ (score1.dataType === "CATEGORICAL" ||
+ score2.dataType === "CATEGORICAL" ||
+ isCrossType);
+
+ // Build comprehensive analytics query
+ const query = buildScoreComparisonQuery({
+ projectId,
+ score1,
+ score2,
+ fromTimestamp,
+ toTimestamp,
+ interval,
+ nBins,
+ objectType,
+ shouldUseFinal,
+ shouldSample,
+ samplingPercent,
+ isIdenticalScores,
+ isSingleScore,
+ isNumeric,
+ isCategoricalComparison,
+ });
+
+ // Execute query
+ const results = await queryClickhouse<{
+ result_type: string;
+ col1: number | null;
+ col2: number | null;
+ col3: number | null;
+ col4: number | null;
+ col5: number | null;
+ col6: number | null;
+ col7: number | null;
+ col8: number | null;
+ col9: string | null;
+ col10: string | null;
+ col11: number | null;
+ col12: number | null;
+ }>({
+ query,
+ params: {
+ projectId,
+ score1Name: score1.name,
+ score1Source: score1.source,
+ score2Name: score2.name,
+ score2Source: score2.source,
+ dataType1: score1.dataType,
+ dataType2: score2.dataType,
+ fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp),
+ toTimestamp: convertDateToClickhouseDateTime(toTimestamp),
+ nBins,
+ },
+ tags: {
+ feature: "scores",
+ type: "analytics",
+ kind: "comparison",
+ projectId,
+ },
+ clickhouseSettings: {
+ // Enable short-circuit evaluation to prevent correlation errors
+ // This ensures if() conditions are evaluated before function calls
+ short_circuit_function_evaluation: "enable",
+ },
+ });
+
+ // Parse results by result_type
+ const countsRow = results.find((r) => r.result_type === "counts");
+ const heatmapRows = results.filter((r) => r.result_type === "heatmap");
+ const confusionRows = results.filter(
+ (r) => r.result_type === "confusion",
+ );
+ const statsRow = results.find((r) => r.result_type === "stats");
+ const timeseriesRows = results.filter(
+ (r) => r.result_type === "timeseries",
+ );
+ const dist1Rows = results.filter(
+ (r) => r.result_type === "distribution1",
+ );
+ const dist2Rows = results.filter(
+ (r) => r.result_type === "distribution2",
+ );
+ const stackedRows = results.filter((r) => r.result_type === "stacked");
+ const stackedMatchedRows = results.filter(
+ (r) => r.result_type === "stacked_matched",
+ );
+ const score2CategoriesRows = results.filter(
+ (r) => r.result_type === "score2_categories",
+ );
+ const dist1MatchedRows = results.filter(
+ (r) => r.result_type === "distribution1_matched",
+ );
+ const dist2MatchedRows = results.filter(
+ (r) => r.result_type === "distribution2_matched",
+ );
+ const dist1IndividualRows = results.filter(
+ (r) => r.result_type === "distribution1_individual",
+ );
+ const dist2IndividualRows = results.filter(
+ (r) => r.result_type === "distribution2_individual",
+ );
+ const timeseriesMatchedRows = results.filter(
+ (r) => r.result_type === "timeseries_matched",
+ );
+ const timeseriesCategorical1Rows = results.filter(
+ (r) => r.result_type === "timeseries_categorical1",
+ );
+ const timeseriesCategorical2Rows = results.filter(
+ (r) => r.result_type === "timeseries_categorical2",
+ );
+ const timeseriesCategorical1MatchedRows = results.filter(
+ (r) => r.result_type === "timeseries_categorical1_matched",
+ );
+ const timeseriesCategorical2MatchedRows = results.filter(
+ (r) => r.result_type === "timeseries_categorical2_matched",
+ );
+
+ // Build structured response
+ return {
+ counts: {
+ score1Total: countsRow?.col1 ?? 0,
+ score2Total: countsRow?.col2 ?? 0,
+ matchedCount: countsRow?.col3 ?? 0,
+ },
+ heatmap: heatmapRows.map((row) => ({
+ binX: row.col1 ?? 0,
+ binY: row.col2 ?? 0,
+ count: row.col3 ?? 0,
+ min1: row.col4 ?? 0,
+ max1: row.col5 ?? 0,
+ min2: row.col6 ?? 0,
+ max2: row.col7 ?? 0,
+ globalMin: row.col11 ?? 0,
+ globalMax: row.col12 ?? 0,
+ })),
+ confusionMatrix: confusionRows.map((row) => ({
+ rowCategory: row.col9 ?? "",
+ colCategory: row.col10 ?? "",
+ count: row.col1 ?? 0,
+ })),
+ statistics: statsRow
+ ? {
+ matchedCount: statsRow.col1 ?? 0,
+ mean1: statsRow.col2 ?? null,
+ mean2: statsRow.col3 ?? null,
+ std1: statsRow.col4 ?? null,
+ std2: statsRow.col5 ?? null,
+ pearsonCorrelation: statsRow.col6 ?? null,
+ mae: statsRow.col7 ?? null,
+ rmse: statsRow.col8 ?? null,
+ spearmanCorrelation: statsRow.col12 ?? null,
+ }
+ : null,
+ timeSeries: timeseriesRows.map((row) => ({
+ timestamp: new Date((row.col1 ?? 0) * 1000),
+ avg1: row.col2 ?? null,
+ avg2: row.col3 ?? null,
+ count: row.col4 ?? 0,
+ })),
+ distribution1: dist1Rows.map((row) => ({
+ binIndex: row.col1 ?? 0,
+ count: row.col2 ?? 0,
+ })),
+ distribution2: dist2Rows.map((row) => ({
+ binIndex: row.col1 ?? 0,
+ count: row.col2 ?? 0,
+ })),
+ stackedDistribution: stackedRows.map((row) => ({
+ score1Category: row.col9 ?? "",
+ score2Stack: row.col10 ?? "",
+ count: row.col1 ?? 0,
+ })),
+ stackedDistributionMatched: stackedMatchedRows.map((row) => ({
+ score1Category: row.col9 ?? "",
+ score2Stack: row.col10 ?? "",
+ count: row.col1 ?? 0,
+ })),
+ score2Categories: score2CategoriesRows
+ .map((row) => row.col9 ?? "")
+ .filter((c) => c !== ""),
+ // Matched-only datasets for toggle
+ timeSeriesMatched: timeseriesMatchedRows.map((row) => ({
+ timestamp: new Date((row.col1 ?? 0) * 1000),
+ avg1: row.col2 ?? null,
+ avg2: row.col3 ?? null,
+ count: row.col4 ?? 0,
+ })),
+ distribution1Matched: dist1MatchedRows.map((row) => ({
+ binIndex: row.col1 ?? 0,
+ count: row.col2 ?? 0,
+ })),
+ distribution2Matched: dist2MatchedRows.map((row) => ({
+ binIndex: row.col1 ?? 0,
+ count: row.col2 ?? 0,
+ })),
+ // Individual-bound distributions for single-score display
+ distribution1Individual: dist1IndividualRows.map((row) => ({
+ binIndex: row.col1 ?? 0,
+ count: row.col2 ?? 0,
+ })),
+ distribution2Individual: dist2IndividualRows.map((row) => ({
+ binIndex: row.col1 ?? 0,
+ count: row.col2 ?? 0,
+ })),
+ // Categorical/boolean time series (counts per category over time)
+ timeSeriesCategorical1: timeseriesCategorical1Rows.map((row) => ({
+ timestamp: new Date((row.col1 ?? 0) * 1000),
+ category: row.col9 ?? "",
+ count: row.col4 ?? 0,
+ })),
+ timeSeriesCategorical2: timeseriesCategorical2Rows.map((row) => ({
+ timestamp: new Date((row.col1 ?? 0) * 1000),
+ category: row.col9 ?? "",
+ count: row.col4 ?? 0,
+ })),
+ timeSeriesCategorical1Matched: timeseriesCategorical1MatchedRows.map(
+ (row) => ({
+ timestamp: new Date((row.col1 ?? 0) * 1000),
+ category: row.col9 ?? "",
+ count: row.col4 ?? 0,
+ }),
+ ),
+ timeSeriesCategorical2Matched: timeseriesCategorical2MatchedRows.map(
+ (row) => ({
+ timestamp: new Date((row.col1 ?? 0) * 1000),
+ category: row.col9 ?? "",
+ count: row.col4 ?? 0,
+ }),
+ ),
+ // Sampling metadata for transparency
+ samplingMetadata: {
+ isSampled: shouldSample,
+ samplingMethod: shouldSample ? ("hash" as const) : ("none" as const),
+ samplingRate,
+ estimatedTotalMatches: estimates.estimatedMatchedCount,
+ actualSampleSize: countsRow?.col3 ?? 0,
+ samplingExpression,
+ // Include preflight estimates for testing and transparency
+ preflightEstimates: {
+ score1Count: estimates.score1Count,
+ score2Count: estimates.score2Count,
+ estimatedMatchedCount: estimates.estimatedMatchedCount,
+ },
+ // Include adaptive FINAL decision for testing and transparency
+ adaptiveFinal: {
+ usedFinal: shouldUseFinal,
+ reason: shouldUseFinal
+ ? "Small dataset - using FINAL for accuracy"
+ : "Large dataset - skipping FINAL for performance",
+ },
+ },
+ // Metadata about query mode and score comparison
+ metadata: {
+ mode: input.mode ?? "two", // Echo back the mode from frontend
+ isSameScore: isIdenticalScores,
+ dataType: score1.dataType,
+ },
+ };
+ }),
+});
diff --git a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx b/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx
deleted file mode 100644
index ab1549c710..0000000000
--- a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx
+++ /dev/null
@@ -1,216 +0,0 @@
-import {
- HoverCard,
- HoverCardContent,
- HoverCardTrigger,
-} from "@/src/components/ui/hover-card";
-import { Clock, Info } from "lucide-react";
-import { useScoreAnalytics } from "./ScoreAnalyticsProvider";
-import { useState, useEffect } from "react";
-
-export function ScoreAnalyticsNoticeBanner() {
- const { isEstimating, estimate, isLoading, data } = useScoreAnalytics();
- const [showLoadingBanner, setShowLoadingBanner] = useState(false);
-
- // Track when estimation starts and set delay for showing loading banner
- useEffect(() => {
- if (isEstimating || (estimate && isLoading)) {
- // Start timer - show banner after 1.5 seconds
- const timer = setTimeout(() => {
- setShowLoadingBanner(true);
- }, 1500);
-
- return () => clearTimeout(timer);
- } else {
- // Reset when loading completes
- setShowLoadingBanner(false);
- }
- }, [isEstimating, estimate, isLoading]);
-
- // Don't show anything if we haven't started
- if (!isEstimating && !estimate) return null;
-
- // State 1: Estimating (loading)
- if (isEstimating || (estimate && isLoading)) {
- const showLargeDataset =
- estimate && estimate.estimatedMatchedCount > 100_000;
-
- // Only show banner if:
- // 1. Delay has passed, OR
- // 2. We have estimate data showing it's a large dataset
- if (!showLoadingBanner && !showLargeDataset) {
- return null;
- }
-
- return (
- <div className="mb-4 rounded-md bg-muted px-4 py-3">
- <div className="flex items-start gap-3">
- <Clock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="flex-1 space-y-1">
- <div className="text-sm font-medium">
- {showLargeDataset
- ? "Processing large dataset..."
- : "Loading analytics..."}
- </div>
- {estimate && (
- <div className="text-sm text-muted-foreground">
- {estimate.mode === "single"
- ? `Analyzing ~${estimate.score1Count.toLocaleString()} scores`
- : `Analyzing ~${estimate.score1Count.toLocaleString()} (Score 1) and ~${estimate.score2Count.toLocaleString()} (Score 2) scores`}
- {estimate.willSample && " • Sampling will be applied"}
- {estimate.estimatedQueryTime && (
- <> • Est. time: {estimate.estimatedQueryTime}</>
- )}
- </div>
- )}
- </div>
- </div>
- </div>
- );
- }
-
- // State 2: Loaded with sampling
- if (data?.samplingMetadata.isSampled) {
- return (
- <div className="mb-4 rounded-md bg-muted px-4 py-3">
- <div className="flex items-start gap-3">
- <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="flex-1 space-y-1">
- <div className="flex items-center gap-2 text-sm font-medium">
- Sampled Data
- <SamplingDetailsHoverCard
- samplingMetadata={data.samplingMetadata}
- mode={data.metadata.mode}
- />
- </div>
- <div className="text-sm text-muted-foreground">
- {data.metadata.mode === "single"
- ? `Results based on a ${(data.samplingMetadata.samplingRate * 100).toFixed(2)}% sample of ~${data.samplingMetadata.preflightEstimates?.score1Count.toLocaleString()} scores.`
- : `Results based on a ${(data.samplingMetadata.samplingRate * 100).toFixed(2)}% sample of ~${data.samplingMetadata.preflightEstimates?.score1Count.toLocaleString()} Score 1 and ~${data.samplingMetadata.preflightEstimates?.score2Count.toLocaleString()} Score 2 data.`}
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- // State 3: Loaded without sampling (don't show banner)
- return null;
-}
-
-function SamplingDetailsHoverCard({
- samplingMetadata,
- mode = "two",
- showLabel = false,
-}: {
- samplingMetadata: {
- samplingRate: number;
- preflightEstimates?: {
- score1Count: number;
- score2Count: number;
- estimatedMatchedCount: number;
- };
- adaptiveFinal?: {
- usedFinal: boolean;
- reason: string;
- };
- };
- mode?: "single" | "two";
- showLabel?: boolean;
-}) {
- return (
- <HoverCard>
- <HoverCardTrigger asChild>
- <button
- className={
- showLabel
- ? "inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
- : "inline-flex h-4 w-4 items-center justify-center rounded-full hover:bg-muted-foreground/10"
- }
- aria-label="View sampling details"
- >
- {showLabel && <span>Sampled Data</span>}
- <Info
- className={showLabel ? "h-3 w-3" : "h-3 w-3 text-muted-foreground"}
- />
- </button>
- </HoverCardTrigger>
- <HoverCardContent className="w-80" align="start">
- <div className="space-y-3">
- <div>
- <h4 className="mb-2 text-sm font-semibold">
- {mode === "single" ? "Estimated Score Count" : "Estimated Scores"}
- </h4>
- <dl className="space-y-1 text-sm">
- {mode === "single" ? (
- <div className="flex justify-between">
- <dt className="text-muted-foreground">Total Scores:</dt>
- <dd className="font-medium">
- ~
- {samplingMetadata.preflightEstimates?.score1Count.toLocaleString()}
- </dd>
- </div>
- ) : (
- <>
- <div className="flex justify-between">
- <dt className="text-muted-foreground">Score 1:</dt>
- <dd className="font-medium">
- ~
- {samplingMetadata.preflightEstimates?.score1Count.toLocaleString()}
- </dd>
- </div>
- <div className="flex justify-between">
- <dt className="text-muted-foreground">Score 2:</dt>
- <dd className="font-medium">
- ~
- {samplingMetadata.preflightEstimates?.score2Count.toLocaleString()}
- </dd>
- </div>
- <div className="flex justify-between">
- <dt className="text-muted-foreground">
- Estimated Matches:
- </dt>
- <dd className="font-medium">
- ~
- {samplingMetadata.preflightEstimates?.estimatedMatchedCount.toLocaleString()}
- </dd>
- </div>
- </>
- )}
- </dl>
- </div>
-
- <div>
- <h4 className="mb-2 text-sm font-semibold">Query Optimizations</h4>
- <dl className="space-y-1 text-sm">
- <div className="flex justify-between">
- <dt className="text-muted-foreground">Sampling:</dt>
- <dd className="font-medium">
- {(samplingMetadata.samplingRate * 100).toFixed(1)}%
- (hash-based)
- </dd>
- </div>
- {samplingMetadata.adaptiveFinal && (
- <div className="flex justify-between">
- <dt className="text-muted-foreground">Deduplication:</dt>
- <dd className="font-medium">
- {samplingMetadata.adaptiveFinal.usedFinal
- ? "Enabled"
- : "Skipped for performance"}
- </dd>
- </div>
- )}
- </dl>
- </div>
-
- <p className="text-xs text-muted-foreground">
- Hash-based sampling ensures consistent, repeatable results while
- maintaining statistical accuracy.
- </p>
- </div>
- </HoverCardContent>
- </HoverCard>
- );
-}
-
-// Export the hover card component for reuse in StatisticsCard
-export { SamplingDetailsHoverCard };
diff --git a/web/src/pages/project/[projectId]/scores/analytics.tsx b/web/src/pages/project/[projectId]/scores/analytics.tsx
index 094d0062a6..91103f8b04 100644
--- a/web/src/pages/project/[projectId]/scores/analytics.tsx
+++ b/web/src/pages/project/[projectId]/scores/analytics.tsx
@@ -5,8 +5,8 @@ import {
getScoresTabs,
SCORES_TABS,
} from "@/src/features/navigation/utils/scores-tabs";
-import { useAnalyticsUrlState } from "@/src/features/scores/components/score-analytics/libs/analytics-url-state";
-import { type ScoreOption } from "@/src/features/scores/components/score-analytics/components/charts/ScoreCombobox";
+import { useAnalyticsUrlState } from "@/src/features/score-analytics/lib/analytics-url-state";
+import { type ScoreOption } from "@/src/features/score-analytics/components/charts/ScoreCombobox";
import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";
import {
toAbsoluteTimeRange,
@@ -17,9 +17,9 @@ import { api } from "@/src/utils/api";
import {
ScoreAnalyticsProvider,
type DataType,
-} from "@/src/features/scores/components/score-analytics/components/ScoreAnalyticsProvider";
-import { ScoreAnalyticsHeader } from "@/src/features/scores/components/score-analytics/components/ScoreAnalyticsHeader";
-import { ScoreAnalyticsDashboard } from "@/src/features/scores/components/score-analytics/components/ScoreAnalyticsDashboard";
+} from "@/src/features/score-analytics/components/ScoreAnalyticsProvider";
+import { ScoreAnalyticsHeader } from "@/src/features/score-analytics/components/ScoreAnalyticsHeader";
+import { ScoreAnalyticsDashboard } from "@/src/features/score-analytics/components/ScoreAnalyticsDashboard";
/**
* Score Analytics V2 - Refactored Architecture
@@ -34,12 +34,6 @@ import { ScoreAnalyticsDashboard } from "@/src/features/scores/components/score-
* - DistributionChartCard: Score distributions
* - HeatmapCard: Score comparison heatmaps
*
- * Benefits over old implementation:
- * - Single data fetch (no prop drilling)
- * - Eliminated ~400 lines of duplicated code
- * - Type-safe with proper interfaces
- * - Clean separation of concerns
- * - Easy to test and maintain
*/
export default function ScoresAnalyticsV2Page() {
const router = useRouter();
@@ -55,7 +49,7 @@ export default function ScoresAnalyticsV2Page() {
data: scoresData,
isLoading: scoresLoading,
error: scoresError,
- } = api.scores.getScoreIdentifiers.useQuery(
+ } = api.scoreAnalytics.getScoreIdentifiers.useQuery(
{ projectId },
{ enabled: !!projectId },
);
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 0463e0726e..01e6d801c2 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -3,6 +3,7 @@ import { traceRouter } from "./routers/traces";
import { generationsRouter } from "./routers/generations";
import { eventsRouter } from "@/src/features/events/server/eventsRouter";
import { scoresRouter } from "./routers/scores";
+import { scoreAnalyticsRouter } from "@/src/features/score-analytics/server/scoreAnalyticsRouter";
import { dashboardRouter } from "@/src/features/dashboard/server/dashboard-router";
import { projectsRouter } from "@/src/features/projects/server/projectsRouter";
import { projectApiKeysRouter } from "@/src/features/public-api/server/projectApiKeyRouter";
@@ -67,6 +68,7 @@ export const appRouter = createTRPCRouter({
generations: generationsRouter,
events: eventsRouter,
scores: scoresRouter,
+ scoreAnalytics: scoreAnalyticsRouter,
scoreConfigs: scoreConfigsRouter,
dashboard: dashboardRouter,
organizations: organizationsRouter,
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index ca6df25c9a..6bcb64e253 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -3,10 +3,6 @@ import { z } from "zod/v4";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";
-import {
- normalizeIntervalForClickHouse,
- getClickHouseTimeBucketFunction,
-} from "@/src/features/scores/components/score-analytics/libs/clickhouse-time-utils";
import {
getDateFromOption,
SelectedTimeOptionSchema,
@@ -47,7 +43,6 @@ import {
logger,
getTraceById,
getScoreById,
- queryClickhouse,
convertDateToClickhouseDateTime,
searchExistingAnnotationScore,
hasAnyScore,
@@ -88,135 +83,6 @@ type AllScoresReturnType = Omit<ScoreDomain, "metadata"> & {
hasMetadata: boolean;
};
-/**
- * Threshold for adaptive FINAL optimization
- * Use FINAL for datasets smaller than this to ensure accuracy (scores can be updated)
- * Skip FINAL for larger datasets to avoid expensive merge overhead
- */
-const ADAPTIVE_FINAL_THRESHOLD = 100_000;
-
-/**
- * Hash-based sampling thresholds
- * - SAMPLING_THRESHOLD: Sample when either score table exceeds this count
- * - TARGET_SAMPLE_SIZE: Target number of rows to sample from each table
- */
-const SAMPLING_THRESHOLD = 100_000; // Start sampling if either table > 100k
-const TARGET_SAMPLE_SIZE = 100_000; // Aim for 100k samples from each table
-
-/**
- * Helper function: Estimate score match count using lightweight preflight query
- * Uses 1% hash sample for fast approximation without FINAL merge overhead
- * Returns estimates for score1 count, score2 count, and matched count
- */
-async function estimateScoreMatchCount(params: {
- projectId: string;
- score1Name: string;
- score1Source: string;
- score1DataType: string;
- score2Name: string;
- score2Source: string;
- score2DataType: string;
- fromTimestamp: Date;
- toTimestamp: Date;
- objectTypeFilter: string;
-}): Promise<{
- score1Count: number;
- score2Count: number;
- estimatedMatchedCount: number;
-}> {
- const {
- projectId,
- score1Name,
- score1Source,
- score1DataType,
- score2Name,
- score2Source,
- score2DataType,
- fromTimestamp,
- toTimestamp,
- objectTypeFilter,
- } = params;
-
- // Use 1% hash sample for fast count estimation
- // cityHash64 provides uniform distribution for sampling
- const samplingExpression = `
- cityHash64(
- coalesce(trace_id, ''),
- coalesce(observation_id, ''),
- coalesce(session_id, ''),
- coalesce(dataset_run_id, '')
- ) % 100 < 1
- `;
-
- const preflightQuery = `
- WITH
- score1_sample AS (
- SELECT trace_id, observation_id, session_id, dataset_run_id
- FROM scores
- PREWHERE project_id = {projectId: String}
- AND name = {score1Name: String}
- WHERE source = {score1Source: String}
- AND data_type = {score1DataType: String}
- AND timestamp >= {fromTimestamp: DateTime64(3)}
- AND timestamp <= {toTimestamp: DateTime64(3)}
- AND is_deleted = 0
- AND ${samplingExpression}
- ${objectTypeFilter}
- ),
- score2_sample AS (
- SELECT trace_id, observation_id, session_id, dataset_run_id
- FROM scores
- PREWHERE project_id = {projectId: String}
- AND name = {score2Name: String}
- WHERE source = {score2Source: String}
- AND data_type = {score2DataType: String}
- AND timestamp >= {fromTimestamp: DateTime64(3)}
- AND timestamp <= {toTimestamp: DateTime64(3)}
- AND is_deleted = 0
- AND ${samplingExpression}
- ${objectTypeFilter}
- )
- SELECT
- (SELECT count() FROM score1_sample) * 100 as score1_count,
- (SELECT count() FROM score2_sample) * 100 as score2_count,
- (
- SELECT count() * 100
- FROM score1_sample s1
- INNER JOIN score2_sample s2
- ON ifNull(s1.trace_id, '') = ifNull(s2.trace_id, '')
- AND ifNull(s1.observation_id, '') = ifNull(s2.observation_id, '')
- AND ifNull(s1.session_id, '') = ifNull(s2.session_id, '')
- AND ifNull(s1.dataset_run_id, '') = ifNull(s2.dataset_run_id, '')
- ) as estimated_matched_count
- `;
-
- const result = await queryClickhouse<{
- score1_count: string;
- score2_count: string;
- estimated_matched_count: string;
- }>({
- query: preflightQuery,
- params: {
- projectId,
- score1Name,
- score1Source,
- score1DataType: score1DataType,
- score2Name,
- score2Source,
- score2DataType: score2DataType,
- fromTimestamp,
- toTimestamp,
- },
- });
-
- const row = result[0];
- return {
- score1Count: parseInt(row?.score1_count ?? "0", 10),
- score2Count: parseInt(row?.score2_count ?? "0", 10),
- estimatedMatchedCount: parseInt(row?.estimated_matched_count ?? "0", 10),
- };
-}
-
export const scoresRouter = createTRPCRouter({
/**
* Get all scores for a project, meant for internal use and *excludes metadata of scores*
@@ -920,1461 +786,4 @@ export const scoresRouter = createTRPCRouter({
.query(async ({ input }) => {
return (await getScoreMetadataById(input.projectId, input.id)) ?? null;
}),
-
- /**
- * Get available score identifiers for analytics dropdown
- */
- getScoreIdentifiers: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- }),
- )
- .query(async ({ input }) => {
- const { projectId } = input;
-
- // Query ClickHouse for distinct score names, data types, and sources
- const groupedScores = await getScoresGroupedByNameSourceType({
- projectId,
- filter: [],
- });
-
- // Format for ScoreSelector component: "name-dataType-source"
- const scores = groupedScores.map(({ name, source, dataType }) => ({
- value: `${name}-${dataType}-${source}`,
- name,
- dataType,
- source,
- }));
-
- return { scores };
- }),
-
- /**
- * Estimate score comparison size for UI loading indicators
- * Returns quick estimates without running full analytics query
- */
- estimateScoreComparisonSize: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- score1: z.object({
- name: z.string(),
- dataType: z.string(),
- source: z.string(),
- }),
- score2: z.object({
- name: z.string(),
- dataType: z.string(),
- source: z.string(),
- }),
- fromTimestamp: z.date(),
- toTimestamp: z.date(),
- objectType: z
- .enum(["all", "trace", "session", "observation", "dataset_run"])
- .default("all"),
- mode: z.enum(["single", "two"]).optional(), // Frontend passes "single" when only score1 selected
- }),
- )
- .query(async ({ input }) => {
- const {
- projectId,
- score1,
- score2,
- fromTimestamp,
- toTimestamp,
- objectType,
- } = input;
-
- // Build object type filter
- const objectTypeFilter =
- objectType === "all"
- ? ""
- : objectType === "trace"
- ? "AND trace_id IS NOT NULL AND observation_id IS NULL AND session_id IS NULL AND dataset_run_id IS NULL"
- : objectType === "session"
- ? "AND session_id IS NOT NULL"
- : objectType === "observation"
- ? "AND observation_id IS NOT NULL"
- : objectType === "dataset_run"
- ? "AND dataset_run_id IS NOT NULL"
- : "";
-
- // Run preflight estimate (uses 1% sampling)
- const estimates = await estimateScoreMatchCount({
- projectId,
- score1Name: score1.name,
- score1Source: score1.source,
- score1DataType: score1.dataType,
- score2Name: score2.name,
- score2Source: score2.source,
- score2DataType: score2.dataType,
- fromTimestamp,
- toTimestamp,
- objectTypeFilter,
- });
-
- // Determine if sampling and FINAL will be used
- const willSample =
- estimates.score1Count > SAMPLING_THRESHOLD ||
- estimates.score2Count > SAMPLING_THRESHOLD;
-
- const willSkipFinal =
- estimates.score1Count >= ADAPTIVE_FINAL_THRESHOLD ||
- estimates.score2Count >= ADAPTIVE_FINAL_THRESHOLD;
-
- // Estimate query time based on dataset size
- const estimatedQueryTime =
- estimates.estimatedMatchedCount > 1_000_000
- ? "30-60s"
- : estimates.estimatedMatchedCount > 500_000
- ? "15-30s"
- : estimates.estimatedMatchedCount > 100_000
- ? "10-20s"
- : "<10s";
-
- return {
- score1Count: estimates.score1Count,
- score2Count: estimates.score2Count,
- estimatedMatchedCount: estimates.estimatedMatchedCount,
- willSample,
- willSkipFinal,
- estimatedQueryTime,
- mode: input.mode ?? "two", // Echo back the mode from frontend
- };
- }),
-
- /**
- * Get comprehensive score comparison analytics using single UNION ALL query
- * Returns counts, heatmap, confusion matrix, statistics, time series, and distributions
- */
- getScoreComparisonAnalytics: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- score1: z.object({
- name: z.string(),
- dataType: z.string(),
- source: z.string(),
- }),
- score2: z.object({
- name: z.string(),
- dataType: z.string(),
- source: z.string(),
- }),
- mode: z.enum(["single", "two"]).optional(), // Frontend passes "single" when only score1 selected
- fromTimestamp: z.date(),
- toTimestamp: z.date(),
- interval: z
- .object({
- count: z.number().int().positive(),
- unit: z.enum(["second", "minute", "hour", "day", "month", "year"]),
- })
- .refine(
- (val) => {
- // Validate against allowed intervals
- const allowed = [
- // Seconds
- { count: 1, unit: "second" },
- { count: 5, unit: "second" },
- { count: 10, unit: "second" },
- { count: 30, unit: "second" },
- // Minutes
- { count: 1, unit: "minute" },
- { count: 5, unit: "minute" },
- { count: 10, unit: "minute" },
- { count: 30, unit: "minute" },
- // Hours
- { count: 1, unit: "hour" },
- { count: 3, unit: "hour" },
- { count: 6, unit: "hour" },
- { count: 12, unit: "hour" },
- // Days
- { count: 1, unit: "day" },
- { count: 2, unit: "day" },
- { count: 5, unit: "day" },
- { count: 7, unit: "day" },
- { count: 14, unit: "day" },
- // Months
- { count: 1, unit: "month" },
- { count: 3, unit: "month" },
- { count: 6, unit: "month" },
- // Years
- { count: 1, unit: "year" },
- ];
- return allowed.some(
- (a) => a.count === val.count && a.unit === val.unit,
- );
- },
- {
- message:
- "Invalid interval. Must be one of the allowed interval combinations.",
- },
- )
- .default({ count: 1, unit: "day" }),
- nBins: z.number().int().min(5).max(50).default(10),
- objectType: z
- .enum(["all", "trace", "session", "observation", "dataset_run"])
- .default("all"),
- }),
- )
- .query(async ({ input }) => {
- const {
- projectId,
- score1,
- score2,
- fromTimestamp,
- toTimestamp,
- interval,
- nBins,
- objectType,
- } = input;
-
- // Note: The backend always returns both matched and unmatched datasets,
- // as well as individual-bound distributions. The frontend chooses which
- // to display based on the selected tab.
-
- // Detect if comparing identical scores (same name, source, and dataType)
- // When true, certain statistical calculations (like Spearman correlation)
- // will be skipped since they're undefined for identical datasets
- const isIdenticalScores =
- score1.name === score2.name &&
- score1.source === score2.source &&
- score1.dataType === score2.dataType;
-
- /**
- * Normalize interval to single-unit for ClickHouse aggregation.
- *
- * IMPORTANT: ClickHouse's toStartOfInterval with multi-unit intervals (e.g., INTERVAL 2 DAY)
- * aligns to Unix epoch (Jan 1, 1970), which causes unintuitive bucketing. For example,
- * with 7-day intervals, buckets start on Thursdays instead of Mondays.
- *
- * WORKAROUND: We always query ClickHouse with SINGLE-UNIT intervals (1 second, 1 minute,
- * 1 hour, 1 day, 1 month, 1 year) which use calendar-aligned functions. The frontend
- * then aggregates these single-unit buckets into the requested multi-unit buckets,
- * working backwards from toTimestamp to ensure "today's" data appears in the rightmost bucket.
- *
- * This approach ensures consistent, calendar-aligned behavior across all time ranges.
- *
- * See: /web/src/features/scores/lib/clickhouse-time-utils.ts for implementation details
- */
-
- // Normalize the interval for ClickHouse (always single-unit except 7-day weeks)
- const normalizedInterval = normalizeIntervalForClickHouse(interval);
-
- // Build object type filter based on selection
- const objectTypeFilter =
- objectType === "all"
- ? ""
- : objectType === "trace"
- ? "AND trace_id IS NOT NULL AND observation_id IS NULL AND session_id IS NULL AND dataset_run_id IS NULL"
- : objectType === "observation"
- ? "AND observation_id IS NOT NULL"
- : objectType === "session"
- ? "AND session_id IS NOT NULL AND observation_id IS NULL AND trace_id IS NULL AND dataset_run_id IS NULL"
- : objectType === "dataset_run"
- ? "AND dataset_run_id IS NOT NULL"
- : "";
-
- // Run preflight query to estimate data size and determine optimization strategy
- const estimates = await estimateScoreMatchCount({
- projectId,
- score1Name: score1.name,
- score1Source: score1.source,
- score1DataType: score1.dataType,
- score2Name: score2.name,
- score2Source: score2.source,
- score2DataType: score2.dataType,
- fromTimestamp,
- toTimestamp,
- objectTypeFilter,
- });
-
- // Adaptive FINAL logic: Only use FINAL for small datasets to avoid expensive merge
- // For large datasets, skip FINAL to improve performance (scores can be updated, so accuracy matters for recent data)
- const shouldUseFinal =
- estimates.score1Count < ADAPTIVE_FINAL_THRESHOLD &&
- estimates.score2Count < ADAPTIVE_FINAL_THRESHOLD;
-
- // Hash-based sampling decision: Sample when either score table exceeds threshold
- const shouldSample =
- estimates.score1Count > SAMPLING_THRESHOLD ||
- estimates.score2Count > SAMPLING_THRESHOLD;
-
- // Calculate rate based on larger table to ensure both tables sample to ~100k rows
- const maxCount = Math.max(estimates.score1Count, estimates.score2Count);
- const samplingRate = shouldSample
- ? Math.min(1.0, TARGET_SAMPLE_SIZE / maxCount)
- : 1.0;
- const samplingPercent = Math.round(samplingRate * 100); // Convert to 0-100 for modulo
-
- // Sampling expression using cityHash64 on composite key (trace_id, observation_id, session_id, dataset_run_id)
- // This ensures deterministic pseudo-random sampling that preserves matched pairs
- const samplingExpression = shouldSample
- ? `cityHash64(
- coalesce(trace_id, ''),
- coalesce(observation_id, ''),
- coalesce(session_id, ''),
- coalesce(dataset_run_id, '')
- ) % 100 < ${samplingPercent}`
- : null;
-
- // Determine if this is a single-score or two-score query
- const isSingleScore =
- score1.name === score2.name && score1.source === score2.source;
-
- // Determine if we're dealing with numeric or categorical/boolean data
- // Cross-type comparisons: treat as categorical if either score is non-numeric
- const isCrossType =
- score1.dataType !== score2.dataType &&
- (score1.dataType !== "NUMERIC" || score2.dataType !== "NUMERIC");
-
- const isNumeric =
- score1.dataType === "NUMERIC" && score2.dataType === "NUMERIC";
- const isCategoricalComparison =
- !isNumeric && // Any non-numeric comparison
- (score1.dataType === "CATEGORICAL" ||
- score2.dataType === "CATEGORICAL" ||
- isCrossType);
-
- // Build distribution CTEs conditionally based on data type
- const distribution1CTE = isNumeric
- ? `-- CTE 9: Distribution for score1 (numeric, using global bounds)
- distribution1 AS (
- SELECT
- floor((s.value - b.global_min) /
- ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
- count() as count
- FROM score1_filtered s
- CROSS JOIN bounds b
- GROUP BY bin_index
- )`
- : `-- CTE 9: Distribution for score1 (categorical/boolean or cross-type)
- distribution1 AS (
- SELECT
- (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value, toString(value))) - 1) as bin_index,
- count() as count
- FROM score1_filtered
- WHERE string_value IS NOT NULL OR value IS NOT NULL
- GROUP BY COALESCE(string_value, toString(value))
- ORDER BY bin_index
- )`;
-
- const distribution2CTE = isNumeric
- ? `-- CTE 10: Distribution for score2 (numeric, using global bounds)
- distribution2 AS (
- SELECT
- floor((s.value - b.global_min) /
- ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
- count() as count
- FROM score2_filtered s
- CROSS JOIN bounds b
- GROUP BY bin_index
- )`
- : `-- CTE 10: Distribution for score2 (categorical/boolean or cross-type)
- distribution2 AS (
- SELECT
- (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value, toString(value))) - 1) as bin_index,
- count() as count
- FROM score2_filtered
- WHERE string_value IS NOT NULL OR value IS NOT NULL
- GROUP BY COALESCE(string_value, toString(value))
- ORDER BY bin_index
- )`;
-
- // Build time series CTE conditionally based on single vs two-score
- const timeseriesCTE = isSingleScore
- ? `-- CTE 8: Time series (single score)
- timeseries AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
- avg(value) as avg1,
- CAST(NULL AS Nullable(Float64)) as avg2,
- count() as count
- FROM score1_filtered
- WHERE value IS NOT NULL
- GROUP BY ts
- ORDER BY ts
- )`
- : `-- CTE 8: Time series (two scores - ALL data, includes unmatched)
- timeseries AS (
- WITH
- score1_time_agg AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
- avg(value) as avg1,
- count() as count1
- FROM score1_filtered
- WHERE value IS NOT NULL
- GROUP BY ts
- ),
- score2_time_agg AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
- avg(value) as avg2,
- count() as count2
- FROM score2_filtered
- WHERE value IS NOT NULL
- GROUP BY ts
- )
- SELECT
- COALESCE(s1.ts, s2.ts) as ts,
- s1.avg1 as avg1,
- s2.avg2 as avg2,
- (COALESCE(s1.count1, 0) + COALESCE(s2.count2, 0)) as count
- FROM score1_time_agg s1
- FULL OUTER JOIN score2_time_agg s2 ON s1.ts = s2.ts
- ORDER BY ts
- )`;
-
- // Build matched-only CTEs for distributions and single-score time series
- const distribution1MatchedCTE = isNumeric
- ? `-- CTE 11: Distribution for score1 (numeric, matched only)
- distribution1_matched AS (
- SELECT
- floor((m.value1 - b.global_min) /
- ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
- count() as count
- FROM matched_scores m
- CROSS JOIN bounds b
- GROUP BY bin_index
- )`
- : `-- CTE 11: Distribution for score1 (categorical/boolean or cross-type, matched only)
- distribution1_matched AS (
- SELECT
- (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value1, toString(value1))) - 1) as bin_index,
- count() as count
- FROM matched_scores
- WHERE string_value1 IS NOT NULL OR value1 IS NOT NULL
- GROUP BY COALESCE(string_value1, toString(value1))
- ORDER BY bin_index
- )`;
-
- const distribution2MatchedCTE = isNumeric
- ? `-- CTE 12: Distribution for score2 (numeric, matched only)
- distribution2_matched AS (
- SELECT
- floor((m.value2 - b.global_min) /
- ((b.global_max - b.global_min + 0.0001) / {nBins: UInt8})) as bin_index,
- count() as count
- FROM matched_scores m
- CROSS JOIN bounds b
- GROUP BY bin_index
- )`
- : `-- CTE 12: Distribution for score2 (categorical/boolean or cross-type, matched only)
- distribution2_matched AS (
- SELECT
- (ROW_NUMBER() OVER (ORDER BY COALESCE(string_value2, toString(value2))) - 1) as bin_index,
- count() as count
- FROM matched_scores
- WHERE string_value2 IS NOT NULL OR value2 IS NOT NULL
- GROUP BY COALESCE(string_value2, toString(value2))
- ORDER BY bin_index
- )`;
-
- // Build individual-bound distributions for single-score display
- const distribution1IndividualCTE = isNumeric
- ? `-- CTE 13: Distribution for score1 (numeric, using individual bounds for single-score view)
- distribution1_individual AS (
- SELECT
- floor((s.value - b.min1) /
- ((b.max1 - b.min1 + 0.0001) / {nBins: UInt8})) as bin_index,
- count() as count
- FROM score1_filtered s
- CROSS JOIN bounds b
- GROUP BY bin_index
- )`
- : `-- CTE 13: Distribution for score1 (categorical/boolean, same as distribution1)
- distribution1_individual AS (
- SELECT bin_index, count
- FROM distribution1
- ORDER BY bin_index
- )`;
-
- const distribution2IndividualCTE = isNumeric
- ? `-- CTE 14: Distribution for score2 (numeric, using individual bounds for single-score view)
- distribution2_individual AS (
- SELECT
- floor((s.value - b.min2) /
- ((b.max2 - b.min2 + 0.0001) / {nBins: UInt8})) as bin_index,
- count() as count
- FROM score2_filtered s
- CROSS JOIN bounds b
- GROUP BY bin_index
- )`
- : `-- CTE 14: Distribution for score2 (categorical/boolean, same as distribution2)
- distribution2_individual AS (
- SELECT bin_index, count
- FROM distribution2
- ORDER BY bin_index
- )`;
-
- // Build matched-only time series for single-score mode
- const timeseriesMatchedCTE = isSingleScore
- ? `-- CTE 15: Time series (single score, matched only)
- timeseries_matched AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
- avg(value1) as avg1,
- CAST(NULL AS Nullable(Float64)) as avg2,
- count() as count
- FROM matched_scores
- WHERE value1 IS NOT NULL
- GROUP BY ts
- ORDER BY ts
- )`
- : `-- CTE 15: Time series (two scores, matched only - re-query matched_scores)
- timeseries_matched AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
- avg(value1) as avg1,
- avg(value2) as avg2,
- count() as count
- FROM matched_scores
- GROUP BY ts
- ORDER BY ts
- )`;
-
- // Build categorical/boolean time series CTEs
- // These show counts per category over time (not averages)
- const timeseriesCategorical1CTE = isSingleScore
- ? `-- CTE 16: Categorical time series for score1 (single score mode)
- timeseries_categorical1 AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
- COALESCE(string_value, toString(value)) as category,
- count() as count
- FROM score1_filtered
- WHERE string_value IS NOT NULL OR value IS NOT NULL
- GROUP BY ts, category
- ORDER BY ts, category
- )`
- : `-- CTE 16: Categorical time series for score1 (two score mode)
- timeseries_categorical1 AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
- COALESCE(string_value, toString(value)) as category,
- count() as count
- FROM score1_filtered
- WHERE string_value IS NOT NULL OR value IS NOT NULL
- GROUP BY ts, category
- ORDER BY ts, category
- )`;
-
- const timeseriesCategorical2CTE = isSingleScore
- ? `-- CTE 17: Categorical time series for score2 (not needed in single score mode)
- timeseries_categorical2 AS (
- SELECT
- CAST(NULL AS Nullable(DateTime)) as ts,
- CAST(NULL AS Nullable(String)) as category,
- CAST(NULL AS Nullable(UInt64)) as count
- WHERE 1 = 0
- )`
- : `-- CTE 17: Categorical time series for score2 (two score mode)
- timeseries_categorical2 AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp", normalizedInterval)} as ts,
- COALESCE(string_value, toString(value)) as category,
- count() as count
- FROM score2_filtered
- WHERE string_value IS NOT NULL OR value IS NOT NULL
- GROUP BY ts, category
- ORDER BY ts, category
- )`;
-
- const timeseriesCategorical1MatchedCTE = isSingleScore
- ? `-- CTE 18: Categorical time series for score1 (single score, matched only)
- timeseries_categorical1_matched AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
- COALESCE(string_value1, toString(value1)) as category,
- count() as count
- FROM matched_scores
- WHERE string_value1 IS NOT NULL OR value1 IS NOT NULL
- GROUP BY ts, category
- ORDER BY ts, category
- )`
- : `-- CTE 18: Categorical time series for score1 (two scores, matched only)
- timeseries_categorical1_matched AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
- COALESCE(string_value1, toString(value1)) as category,
- count() as count
- FROM matched_scores
- WHERE string_value1 IS NOT NULL OR value1 IS NOT NULL
- GROUP BY ts, category
- ORDER BY ts, category
- )`;
-
- const timeseriesCategorical2MatchedCTE = isSingleScore
- ? `-- CTE 19: Categorical time series for score2 (not needed in single score mode)
- timeseries_categorical2_matched AS (
- SELECT
- CAST(NULL AS Nullable(DateTime)) as ts,
- CAST(NULL AS Nullable(String)) as category,
- CAST(NULL AS Nullable(UInt64)) as count
- WHERE 1 = 0
- )`
- : `-- CTE 19: Categorical time series for score2 (two scores, matched only)
- timeseries_categorical2_matched AS (
- SELECT
- ${getClickHouseTimeBucketFunction("timestamp1", normalizedInterval)} as ts,
- COALESCE(string_value2, toString(value2)) as category,
- count() as count
- FROM matched_scores
- WHERE string_value2 IS NOT NULL OR value2 IS NOT NULL
- GROUP BY ts, category
- ORDER BY ts, category
- )`;
-
- // Construct comprehensive UNION ALL query
- const query = `
- WITH
- -- CTE 1: Filter score 1
- -- PREWHERE optimization: Apply most selective filters (project_id, name) early
- -- to reduce data read from disk before applying other filters
- -- Adaptive FINAL: Only use FINAL for small datasets (<100k) to balance accuracy vs performance
- -- Hash-based sampling: Applied when estimated matched count exceeds threshold
- score1_filtered AS (
- SELECT
- id, value, string_value,
- trace_id, observation_id, session_id, dataset_run_id as run_id,
- timestamp
- FROM scores ${shouldUseFinal ? "FINAL" : ""}
- PREWHERE project_id = {projectId: String}
- AND name = {score1Name: String}
- WHERE source = {score1Source: String}
- AND data_type = {dataType1: String}
- AND timestamp >= {fromTimestamp: DateTime64(3)}
- AND timestamp <= {toTimestamp: DateTime64(3)}
- AND is_deleted = 0
- ${objectTypeFilter}
- ${shouldSample ? `AND ${samplingExpression}` : ""}
- ),
-
- -- CTE 2: Filter score 2
- -- PREWHERE optimization: Apply most selective filters (project_id, name) early
- -- Adaptive FINAL: Only use FINAL for small datasets (<100k)
- -- Hash-based sampling: Applied when estimated matched count exceeds threshold
- -- Special case: When comparing identical scores, reuse score1_filtered to ensure perfect correlation
- score2_filtered AS (
- ${
- isIdenticalScores
- ? `SELECT * FROM score1_filtered`
- : `SELECT
- id, value, string_value,
- trace_id, observation_id, session_id, dataset_run_id as run_id,
- timestamp
- FROM scores ${shouldUseFinal ? "FINAL" : ""}
- PREWHERE project_id = {projectId: String}
- AND name = {score2Name: String}
- WHERE source = {score2Source: String}
- AND data_type = {dataType2: String}
- AND timestamp >= {fromTimestamp: DateTime64(3)}
- AND timestamp <= {toTimestamp: DateTime64(3)}
- AND is_deleted = 0
- ${objectTypeFilter}
- ${shouldSample ? `AND ${samplingExpression}` : ""}`
- }
- ),
-
- -- CTE 3: Match scores - must have exact same attachment (trace/obs/session/run)
- -- NULL-safe comparison: convert NULL to empty string for comparison
- -- Special case: For identical scores, use self-join on ID to ensure perfect pairing
- -- Note: No LIMIT needed - sampling already ensures score1_filtered and score2_filtered are ~100k rows max
- matched_scores AS (
- SELECT
- s1.value as value1,
- s1.string_value as string_value1,
- ${isIdenticalScores ? "s1.value" : "s2.value"} as value2,
- ${isIdenticalScores ? "s1.string_value" : "s2.string_value"} as string_value2,
- s1.timestamp as timestamp1,
- ${isIdenticalScores ? "s1.timestamp" : "s2.timestamp"} as timestamp2,
- ${isIdenticalScores ? "s1.trace_id" : "coalesce(s1.trace_id, s2.trace_id)"} as trace_id,
- ${isIdenticalScores ? "s1.observation_id" : "coalesce(s1.observation_id, s2.observation_id)"} as observation_id,
- ${isIdenticalScores ? "s1.session_id" : "coalesce(s1.session_id, s2.session_id)"} as session_id,
- ${isIdenticalScores ? "s1.run_id" : "coalesce(s1.run_id, s2.run_id)"} as run_id
- FROM score1_filtered s1
- INNER JOIN ${isIdenticalScores ? "score1_filtered" : "score2_filtered"} s2
- ON ${
- isIdenticalScores
- ? "s1.id = s2.id"
- : `ifNull(s1.trace_id, '') = ifNull(s2.trace_id, '')
- AND ifNull(s1.observation_id, '') = ifNull(s2.observation_id, '')
- AND ifNull(s1.session_id, '') = ifNull(s2.session_id, '')
- AND ifNull(s1.run_id, '') = ifNull(s2.run_id, '')`
- }
- LIMIT 1000000 -- Safety limit to prevent Cartesian product explosions when multiple scores of same name/source exist on one attachment point (trace/observation/session/run)
- ),
-
- -- CTE 3a: Count all matched score pairs
- -- Counts all rows in matched_scores (not unique attachment points).
- -- NOTE: When multiple scores of same name/source exist on one attachment point,
- -- matched count can exceed both score1Total and score2Total due to Cartesian product.
- -- Example: 2 "gpt4" scores + 3 "gemini" scores on same trace = 6 matched pairs (2 × 3 = 6).
- -- This is correct behavior - each score pair combination is a valid match.
- matched_count AS (
- SELECT count(*) as cnt
- FROM matched_scores
- ),
-
- -- CTE 4: Bounds (for numeric heatmap and distribution binning)
- -- Calculate global bounds across ALL scores (not just matched) for consistent binning
- bounds AS (
- SELECT
- least(
- (SELECT min(value) FROM score1_filtered),
- (SELECT min(value) FROM score2_filtered)
- ) as global_min,
- greatest(
- (SELECT max(value) FROM score1_filtered),
- (SELECT max(value) FROM score2_filtered)
- ) as global_max,
- -- Keep individual bounds for reference (used in response)
- (SELECT min(value) FROM score1_filtered) as min1,
- (SELECT max(value) FROM score1_filtered) as max1,
- (SELECT min(value) FROM score2_filtered) as min2,
- (SELECT max(value) FROM score2_filtered) as max2
- ),
-
- -- CTE 5: Heatmap (numeric only, NxN grid using independent bounds per score)
- heatmap AS (
- SELECT
- floor((m.value1 - b.min1) / ((b.max1 - b.min1 + 0.0001) / {nBins: UInt8})) as bin_x,
- floor((m.value2 - b.min2) / ((b.max2 - b.min2 + 0.0001) / {nBins: UInt8})) as bin_y,
- count() as count,
- b.global_min, b.global_max,
- b.min1, b.max1, b.min2, b.max2
- FROM matched_scores m
- CROSS JOIN bounds b
- GROUP BY bin_x, bin_y, b.global_min, b.global_max, b.min1, b.max1, b.min2, b.max2
- ),
-
- -- CTE 6: Confusion matrix (categorical/boolean and cross-type)
- confusion AS (
- SELECT
- COALESCE(string_value1, toString(value1)) as row_category,
- COALESCE(string_value2, toString(value2)) as col_category,
- count() as count
- FROM matched_scores
- GROUP BY row_category, col_category
- ),
-
- ${
- isCategoricalComparison
- ? `-- CTE 6a: LEFT JOIN score1 with score2 for stacked distribution
- score1_with_score2 AS (
- SELECT
- -- Use string_value for categorical/boolean, convert value to string for numeric
- COALESCE(s1.string_value, toString(s1.value)) as score1_category,
- COALESCE(s2.string_value, toString(s2.value)) as score2_category
- FROM score1_filtered s1
- LEFT JOIN score2_filtered s2
- ON ifNull(s1.trace_id, '') = ifNull(s2.trace_id, '')
- AND ifNull(s1.observation_id, '') = ifNull(s2.observation_id, '')
- AND ifNull(s1.session_id, '') = ifNull(s2.session_id, '')
- AND ifNull(s1.run_id, '') = ifNull(s2.run_id, '')
- LIMIT 1000000 -- Safety limit for categorical LEFT JOIN (more prone to expansion than INNER JOIN)
- ),
-
- -- CTE 6b: Stacked distribution (score1 categories with score2 breakdowns)
- stacked_distribution AS (
- SELECT
- score1_category,
- coalesce(score2_category, '__unmatched__') as score2_stack,
- count() as count
- FROM score1_with_score2
- WHERE score1_category IS NOT NULL
- GROUP BY score1_category, score2_stack
- ORDER BY score1_category, score2_stack
- ),
-
- -- CTE 6c: All score2 categories for legend
- score2_categories AS (
- SELECT DISTINCT COALESCE(string_value, toString(value)) as category
- FROM score2_filtered
- WHERE string_value IS NOT NULL OR value IS NOT NULL
- ORDER BY category
- ),
-
- -- CTE 6d: Stacked distribution (matched only - no __unmatched__)
- stacked_distribution_matched AS (
- SELECT
- COALESCE(string_value1, toString(value1)) as score1_category,
- COALESCE(string_value2, toString(value2)) as score2_stack,
- count() as count
- FROM matched_scores
- WHERE (string_value1 IS NOT NULL OR value1 IS NOT NULL)
- AND (string_value2 IS NOT NULL OR value2 IS NOT NULL)
- GROUP BY score1_category, score2_stack
- ORDER BY score1_category, score2_stack
- ),`
- : ""
- }
-
- -- CTE 7: Correlation safety check
- -- Pre-compute whether it's safe to calculate correlations
- -- Requires at least 2 data points and non-zero variance in both samples
- correlation_check AS (
- SELECT
- count() >= 2
- AND stddevPop(value1) > 0
- AND stddevPop(value2) > 0 as is_safe
- FROM matched_scores
- ),
-
- -- CTE 8: Statistics
- -- IMPORTANT: Calculate mean/std from individual filtered scores, NOT matched_scores
- -- This ensures statistics are available even when matchedCount = 0
- -- Comparison metrics (mae/rmse/correlations) still use matched_scores since they require pairs
- stats AS (
- SELECT
- (SELECT count() FROM matched_scores) as matched_count,
- ${
- isNumeric
- ? `-- Individual score statistics from filtered tables (not matched pairs)
- (SELECT avg(value) FROM score1_filtered) as mean1,
- (SELECT avg(value) FROM score2_filtered) as mean2,
- (SELECT stddevPop(value) FROM score1_filtered) as std1,
- (SELECT stddevPop(value) FROM score2_filtered) as std2,
- -- Comparison metrics require matched pairs
- (SELECT avg(abs(value1 - value2)) FROM matched_scores) as mae,
- (SELECT sqrt(avg(pow(value1 - value2, 2))) FROM matched_scores) as rmse,
- -- Conditional correlation: only execute subquery if safe
- -- Uses short-circuit evaluation to prevent errors with insufficient data
- ${
- isIdenticalScores
- ? "NULL"
- : `if(
- (SELECT is_safe FROM correlation_check),
- (SELECT corr(value1, value2) FROM matched_scores),
- NULL
- )`
- } as pearson_correlation,
- ${
- isIdenticalScores
- ? "NULL"
- : `if(
- (SELECT is_safe FROM correlation_check),
- (SELECT rankCorr(value1, value2) FROM matched_scores),
- NULL
- )`
- } as spearman_correlation`
- : `-- Categorical/boolean scores: statistical metrics are not meaningful
- NULL as mean1,
- NULL as mean2,
- NULL as std1,
- NULL as std2,
- NULL as pearson_correlation,
- NULL as spearman_correlation,
- NULL as mae,
- NULL as rmse`
- }
- ),
-
- ${timeseriesCTE},
-
- ${distribution1CTE},
-
- ${distribution2CTE},
-
- ${distribution1MatchedCTE},
-
- ${distribution2MatchedCTE},
-
- ${distribution1IndividualCTE},
-
- ${distribution2IndividualCTE},
-
- ${timeseriesMatchedCTE},
-
- ${timeseriesCategorical1CTE},
-
- ${timeseriesCategorical2CTE},
-
- ${timeseriesCategorical1MatchedCTE},
-
- ${timeseriesCategorical2MatchedCTE}
-
- -- Return multiple result sets via UNION ALL
- SELECT
- 'counts' as result_type,
- CAST((SELECT count() FROM score1_filtered) AS Float64) as col1,
- CAST((SELECT count() FROM score2_filtered) AS Float64) as col2,
- CAST((SELECT cnt FROM matched_count) AS Float64) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
-
- UNION ALL
-
- SELECT
- 'heatmap' as result_type,
- CAST(bin_x AS Float64) as col1,
- CAST(bin_y AS Float64) as col2,
- CAST(count AS Float64) as col3,
- min1 as col4, -- Individual bounds for score1
- max1 as col5,
- min2 as col6, -- Individual bounds for score2
- max2 as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- global_min as col11, -- Global bounds for comparison
- global_max as col12
- FROM heatmap
-
- UNION ALL
-
- SELECT
- 'confusion' as result_type,
- CAST(count AS Float64) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- row_category as col9,
- col_category as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM confusion
-
- UNION ALL
-
- SELECT
- 'stats' as result_type,
- CAST(matched_count AS Float64) as col1,
- mean1 as col2,
- mean2 as col3,
- std1 as col4,
- std2 as col5,
- pearson_correlation as col6,
- mae as col7,
- rmse as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- spearman_correlation as col12
- FROM stats
-
- UNION ALL
-
- SELECT
- 'timeseries' as result_type,
- CAST(toUnixTimestamp(ts) AS Float64) as col1,
- CAST(avg1 AS Nullable(Float64)) as col2,
- CAST(avg2 AS Nullable(Float64)) as col3,
- CAST(count AS Float64) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM timeseries
-
- UNION ALL
-
- SELECT
- 'distribution1' as result_type,
- CAST(bin_index AS Float64) as col1,
- CAST(count AS Float64) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM distribution1
-
- UNION ALL
-
- SELECT
- 'distribution2' as result_type,
- CAST(bin_index AS Float64) as col1,
- CAST(count AS Float64) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM distribution2
-
- ${
- isCategoricalComparison
- ? `
- UNION ALL
-
- SELECT
- 'stacked' as result_type,
- CAST(count AS Float64) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- score1_category as col9,
- score2_stack as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM stacked_distribution
-
- UNION ALL
-
- SELECT
- 'score2_categories' as result_type,
- CAST(NULL AS Nullable(Float64)) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- category as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM score2_categories
-
- UNION ALL
-
- SELECT
- 'stacked_matched' as result_type,
- CAST(count AS Float64) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- score1_category as col9,
- score2_stack as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM stacked_distribution_matched`
- : ""
- }
-
- UNION ALL
-
- SELECT
- 'distribution1_matched' as result_type,
- CAST(bin_index AS Float64) as col1,
- CAST(count AS Float64) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM distribution1_matched
-
- UNION ALL
-
- SELECT
- 'distribution2_matched' as result_type,
- CAST(bin_index AS Float64) as col1,
- CAST(count AS Float64) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM distribution2_matched
-
- UNION ALL
-
- SELECT
- 'distribution1_individual' as result_type,
- CAST(bin_index AS Float64) as col1,
- CAST(count AS Float64) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM distribution1_individual
-
- UNION ALL
-
- SELECT
- 'distribution2_individual' as result_type,
- CAST(bin_index AS Float64) as col1,
- CAST(count AS Float64) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(NULL AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM distribution2_individual
-
- UNION ALL
-
- SELECT
- 'timeseries_matched' as result_type,
- CAST(toUnixTimestamp(ts) AS Float64) as col1,
- CAST(avg1 AS Nullable(Float64)) as col2,
- CAST(avg2 AS Nullable(Float64)) as col3,
- CAST(count AS Float64) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- CAST(NULL AS Nullable(String)) as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM timeseries_matched
-
- UNION ALL
-
- SELECT
- 'timeseries_categorical1' as result_type,
- CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(count AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- category as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM timeseries_categorical1
-
- UNION ALL
-
- SELECT
- 'timeseries_categorical2' as result_type,
- CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(count AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- category as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM timeseries_categorical2
-
- UNION ALL
-
- SELECT
- 'timeseries_categorical1_matched' as result_type,
- CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(count AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- category as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM timeseries_categorical1_matched
-
- UNION ALL
-
- SELECT
- 'timeseries_categorical2_matched' as result_type,
- CAST(toUnixTimestamp(ts) AS Nullable(Float64)) as col1,
- CAST(NULL AS Nullable(Float64)) as col2,
- CAST(NULL AS Nullable(Float64)) as col3,
- CAST(count AS Nullable(Float64)) as col4,
- CAST(NULL AS Nullable(Float64)) as col5,
- CAST(NULL AS Nullable(Float64)) as col6,
- CAST(NULL AS Nullable(Float64)) as col7,
- CAST(NULL AS Nullable(Float64)) as col8,
- category as col9,
- CAST(NULL AS Nullable(String)) as col10,
- CAST(NULL AS Nullable(Float64)) as col11,
- CAST(NULL AS Nullable(Float64)) as col12
- FROM timeseries_categorical2_matched
- `;
-
- // Execute query
- const results = await queryClickhouse<{
- result_type: string;
- col1: number | null;
- col2: number | null;
- col3: number | null;
- col4: number | null;
- col5: number | null;
- col6: number | null;
- col7: number | null;
- col8: number | null;
- col9: string | null;
- col10: string | null;
- col11: number | null;
- col12: number | null;
- }>({
- query,
- params: {
- projectId,
- score1Name: score1.name,
- score1Source: score1.source,
- score2Name: score2.name,
- score2Source: score2.source,
- dataType1: score1.dataType,
- dataType2: score2.dataType,
- fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp),
- toTimestamp: convertDateToClickhouseDateTime(toTimestamp),
- nBins,
- },
- tags: {
- feature: "scores",
- type: "analytics",
- kind: "comparison",
- projectId,
- },
- clickhouseSettings: {
- // Enable short-circuit evaluation to prevent correlation errors
- // This ensures if() conditions are evaluated before function calls
- short_circuit_function_evaluation: "enable",
- },
- });
-
- // Parse results by result_type
- const countsRow = results.find((r) => r.result_type === "counts");
- const heatmapRows = results.filter((r) => r.result_type === "heatmap");
- const confusionRows = results.filter(
- (r) => r.result_type === "confusion",
- );
- const statsRow = results.find((r) => r.result_type === "stats");
- const timeseriesRows = results.filter(
- (r) => r.result_type === "timeseries",
- );
- const dist1Rows = results.filter(
- (r) => r.result_type === "distribution1",
- );
- const dist2Rows = results.filter(
- (r) => r.result_type === "distribution2",
- );
- const stackedRows = results.filter((r) => r.result_type === "stacked");
- const stackedMatchedRows = results.filter(
- (r) => r.result_type === "stacked_matched",
- );
- const score2CategoriesRows = results.filter(
- (r) => r.result_type === "score2_categories",
- );
- const dist1MatchedRows = results.filter(
- (r) => r.result_type === "distribution1_matched",
- );
- const dist2MatchedRows = results.filter(
- (r) => r.result_type === "distribution2_matched",
- );
- const dist1IndividualRows = results.filter(
- (r) => r.result_type === "distribution1_individual",
- );
- const dist2IndividualRows = results.filter(
- (r) => r.result_type === "distribution2_individual",
- );
- const timeseriesMatchedRows = results.filter(
- (r) => r.result_type === "timeseries_matched",
- );
- const timeseriesCategorical1Rows = results.filter(
- (r) => r.result_type === "timeseries_categorical1",
- );
- const timeseriesCategorical2Rows = results.filter(
- (r) => r.result_type === "timeseries_categorical2",
- );
- const timeseriesCategorical1MatchedRows = results.filter(
- (r) => r.result_type === "timeseries_categorical1_matched",
- );
- const timeseriesCategorical2MatchedRows = results.filter(
- (r) => r.result_type === "timeseries_categorical2_matched",
- );
-
- // Build structured response
- return {
- counts: {
- score1Total: countsRow?.col1 ?? 0,
- score2Total: countsRow?.col2 ?? 0,
- matchedCount: countsRow?.col3 ?? 0,
- },
- heatmap: heatmapRows.map((row) => ({
- binX: row.col1 ?? 0,
- binY: row.col2 ?? 0,
- count: row.col3 ?? 0,
- min1: row.col4 ?? 0,
- max1: row.col5 ?? 0,
- min2: row.col6 ?? 0,
- max2: row.col7 ?? 0,
- globalMin: row.col11 ?? 0,
- globalMax: row.col12 ?? 0,
- })),
- confusionMatrix: confusionRows.map((row) => ({
- rowCategory: row.col9 ?? "",
- colCategory: row.col10 ?? "",
- count: row.col1 ?? 0,
- })),
- statistics: statsRow
- ? {
- matchedCount: statsRow.col1 ?? 0,
- mean1: statsRow.col2 ?? null,
- mean2: statsRow.col3 ?? null,
- std1: statsRow.col4 ?? null,
- std2: statsRow.col5 ?? null,
- pearsonCorrelation: statsRow.col6 ?? null,
- mae: statsRow.col7 ?? null,
- rmse: statsRow.col8 ?? null,
- spearmanCorrelation: statsRow.col12 ?? null,
- }
- : null,
- timeSeries: timeseriesRows.map((row) => ({
- timestamp: new Date((row.col1 ?? 0) * 1000),
- avg1: row.col2 ?? null,
- avg2: row.col3 ?? null,
- count: row.col4 ?? 0,
- })),
- distribution1: dist1Rows.map((row) => ({
- binIndex: row.col1 ?? 0,
- count: row.col2 ?? 0,
- })),
- distribution2: dist2Rows.map((row) => ({
- binIndex: row.col1 ?? 0,
- count: row.col2 ?? 0,
- })),
- stackedDistribution: stackedRows.map((row) => ({
- score1Category: row.col9 ?? "",
- score2Stack: row.col10 ?? "",
- count: row.col1 ?? 0,
- })),
- stackedDistributionMatched: stackedMatchedRows.map((row) => ({
- score1Category: row.col9 ?? "",
- score2Stack: row.col10 ?? "",
- count: row.col1 ?? 0,
- })),
- score2Categories: score2CategoriesRows
- .map((row) => row.col9 ?? "")
- .filter((c) => c !== ""),
- // Matched-only datasets for toggle
- timeSeriesMatched: timeseriesMatchedRows.map((row) => ({
- timestamp: new Date((row.col1 ?? 0) * 1000),
- avg1: row.col2 ?? null,
- avg2: row.col3 ?? null,
- count: row.col4 ?? 0,
- })),
- distribution1Matched: dist1MatchedRows.map((row) => ({
- binIndex: row.col1 ?? 0,
- count: row.col2 ?? 0,
- })),
- distribution2Matched: dist2MatchedRows.map((row) => ({
- binIndex: row.col1 ?? 0,
- count: row.col2 ?? 0,
- })),
- // Individual-bound distributions for single-score display
- distribution1Individual: dist1IndividualRows.map((row) => ({
- binIndex: row.col1 ?? 0,
- count: row.col2 ?? 0,
- })),
- distribution2Individual: dist2IndividualRows.map((row) => ({
- binIndex: row.col1 ?? 0,
- count: row.col2 ?? 0,
- })),
- // Categorical/boolean time series (counts per category over time)
- timeSeriesCategorical1: timeseriesCategorical1Rows.map((row) => ({
- timestamp: new Date((row.col1 ?? 0) * 1000),
- category: row.col9 ?? "",
- count: row.col4 ?? 0,
- })),
- timeSeriesCategorical2: timeseriesCategorical2Rows.map((row) => ({
- timestamp: new Date((row.col1 ?? 0) * 1000),
- category: row.col9 ?? "",
- count: row.col4 ?? 0,
- })),
- timeSeriesCategorical1Matched: timeseriesCategorical1MatchedRows.map(
- (row) => ({
- timestamp: new Date((row.col1 ?? 0) * 1000),
- category: row.col9 ?? "",
- count: row.col4 ?? 0,
- }),
- ),
- timeSeriesCategorical2Matched: timeseriesCategorical2MatchedRows.map(
- (row) => ({
- timestamp: new Date((row.col1 ?? 0) * 1000),
- category: row.col9 ?? "",
- count: row.col4 ?? 0,
- }),
- ),
- // Sampling metadata for transparency
- samplingMetadata: {
- isSampled: shouldSample,
- samplingMethod: shouldSample ? ("hash" as const) : ("none" as const),
- samplingRate,
- estimatedTotalMatches: estimates.estimatedMatchedCount,
- actualSampleSize: countsRow?.col3 ?? 0,
- samplingExpression,
- // Include preflight estimates for testing and transparency
- preflightEstimates: {
- score1Count: estimates.score1Count,
- score2Count: estimates.score2Count,
- estimatedMatchedCount: estimates.estimatedMatchedCount,
- },
- // Include adaptive FINAL decision for testing and transparency
- adaptiveFinal: {
- usedFinal: shouldUseFinal,
- reason: shouldUseFinal
- ? "Small dataset - using FINAL for accuracy"
- : "Large dataset - skipping FINAL for performance",
- },
- },
- // Metadata about query mode and score comparison
- metadata: {
- mode: input.mode ?? "two", // Echo back the mode from frontend
- isSameScore: isIdenticalScores,
- dataType: score1.dataType,
- },
- };
- }),
});