Skip to content

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

feat(score-analytics): query performance and ux improvements (#10304)

Michael Fröhlicha99876715ab0
diff --git a/web/src/__tests__/async/score-comparison-analytics.servertest.ts b/web/src/__tests__/async/score-comparison-analytics.servertest.ts
index d22dc88eec..35fe3771f3 100644
--- a/web/src/__tests__/async/score-comparison-analytics.servertest.ts
+++ b/web/src/__tests__/async/score-comparison-analytics.servertest.ts
@@ -12,6 +12,7 @@ import {
createObservation,
createObservationsCh,
createSessionScore,
+ createDatasetRunScore,
} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
@@ -142,6 +143,17 @@ describe("Score Comparison Analytics tRPC", () => {
expect(result.distribution2).toBeDefined();
expect(Array.isArray(result.distribution2)).toBe(true);
+
+ // Verify sampling metadata is present
+ expect(result.samplingMetadata).toBeDefined();
+ expect(result.samplingMetadata.isSampled).toBe(false); // No sampling for small dataset
+ expect(result.samplingMetadata.samplingMethod).toBe("none");
+ expect(result.samplingMetadata.samplingRate).toBe(1.0);
+ expect(
+ result.samplingMetadata.estimatedTotalMatches,
+ ).toBeGreaterThanOrEqual(0);
+ expect(result.samplingMetadata.actualSampleSize).toBe(1); // Matches matchedCount
+ expect(result.samplingMetadata.samplingExpression).toBeNull();
});
// Test 2: Returns empty results when no scores exist
@@ -175,6 +187,12 @@ describe("Score Comparison Analytics tRPC", () => {
expect(result.timeSeries).toEqual([]);
expect(result.distribution1).toEqual([]);
expect(result.distribution2).toEqual([]);
+
+ // Verify sampling metadata even when no data
+ expect(result.samplingMetadata).toBeDefined();
+ expect(result.samplingMetadata.isSampled).toBe(false);
+ expect(result.samplingMetadata.samplingMethod).toBe("none");
+ expect(result.samplingMetadata.actualSampleSize).toBe(0);
});
// Test 3: Validates input schema
@@ -222,7 +240,570 @@ describe("Score Comparison Analytics tRPC", () => {
).rejects.toThrow();
});
- // Test 4: Calculates counts correctly with partial matches
+ // Test 4: Adaptive FINAL optimization with small dataset
+ // For datasets with estimated counts < 100k: uses FINAL for accuracy
+ // For datasets with estimated counts >= 100k: skips FINAL for performance
+ it("should use FINAL for small datasets (adaptive FINAL)", async () => {
+ const traceId = v4();
+ const trace = createTrace({ id: traceId, project_id: projectId });
+ await createTracesCh([trace]);
+
+ const now = new Date();
+ const fromTimestamp = new Date(now.getTime() - 3600000);
+ const toTimestamp = new Date(now.getTime() + 3600000);
+
+ const scoreName1 = `test-adaptive-score1-${v4()}`;
+ const scoreName2 = `test-adaptive-score2-${v4()}`;
+
+ // Create a small dataset (will use FINAL)
+ const score1 = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName1,
+ source: "ANNOTATION",
+ data_type: "NUMERIC",
+ value: 0.5,
+ timestamp: now.getTime(),
+ });
+
+ const score2 = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName2,
+ source: "ANNOTATION",
+ data_type: "NUMERIC",
+ value: 0.6,
+ timestamp: now.getTime(),
+ });
+
+ await createScoresCh([score1, score2]);
+
+ const result = await caller.scores.getScoreComparisonAnalytics({
+ projectId,
+ score1: {
+ name: scoreName1,
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ },
+ score2: {
+ name: scoreName2,
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 1, unit: "day" },
+ nBins: 10,
+ });
+
+ // Verify query succeeded
+ expect(result.counts).toBeDefined();
+ expect(result.counts.matchedCount).toBe(1);
+
+ // Verify adaptive FINAL decision via samplingMetadata
+ expect(result.samplingMetadata.adaptiveFinal).toBeDefined();
+ expect(result.samplingMetadata.adaptiveFinal?.usedFinal).toBe(true);
+ expect(result.samplingMetadata.adaptiveFinal?.reason).toContain(
+ "Small dataset - using FINAL for accuracy",
+ );
+
+ // Verify preflight estimates are included
+ expect(result.samplingMetadata.preflightEstimates).toBeDefined();
+ expect(
+ result.samplingMetadata.preflightEstimates?.score1Count,
+ ).toBeLessThan(100_000);
+ expect(
+ result.samplingMetadata.preflightEstimates?.score2Count,
+ ).toBeLessThan(100_000);
+ });
+
+ // Test 5: Adaptive FINAL skips FINAL for large datasets (>100k scores)
+ it("should skip FINAL for large datasets to improve performance", async () => {
+ const now = new Date();
+ const fromTimestamp = new Date(now.getTime() - 3600000);
+ const toTimestamp = new Date(now.getTime() + 3600000);
+
+ const scoreName1 = `test-large-score1-${v4()}`;
+ const scoreName2 = `test-large-score2-${v4()}`;
+
+ // Create 101k scores for score1 and 101k for score2
+ // This exceeds ADAPTIVE_FINAL_THRESHOLD (100k)
+ const score1Batch: ReturnType<typeof createTraceScore>[] = [];
+ const score2Batch: ReturnType<typeof createTraceScore>[] = [];
+ const tracesBatch: ReturnType<typeof createTrace>[] = [];
+
+ const batchSize = 101_000; // Exceed threshold
+
+ console.log(
+ `Creating ${batchSize} scores for adaptive FINAL test (this may take a moment)...`,
+ );
+
+ for (let i = 0; i < batchSize; i++) {
+ const traceId = v4();
+
+ // Create trace
+ tracesBatch.push(
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime(),
+ }),
+ );
+
+ // Create score1
+ score1Batch.push(
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName1,
+ source: "ANNOTATION",
+ data_type: "NUMERIC",
+ value: Math.random(),
+ timestamp: now.getTime(),
+ }),
+ );
+
+ // Create score2
+ score2Batch.push(
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName2,
+ source: "ANNOTATION",
+ data_type: "NUMERIC",
+ value: Math.random(),
+ timestamp: now.getTime(),
+ }),
+ );
+ }
+
+ // Insert in batches to avoid memory issues
+ const insertBatchSize = 10_000;
+ for (let i = 0; i < batchSize; i += insertBatchSize) {
+ await createTracesCh(tracesBatch.slice(i, i + insertBatchSize));
+ await createScoresCh([
+ ...score1Batch.slice(i, i + insertBatchSize),
+ ...score2Batch.slice(i, i + insertBatchSize),
+ ]);
+ }
+
+ console.log(`Inserted ${batchSize} traces and ${batchSize * 2} scores`);
+
+ const result = await caller.scores.getScoreComparisonAnalytics({
+ projectId,
+ score1: {
+ name: scoreName1,
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ },
+ score2: {
+ name: scoreName2,
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 1, unit: "day" },
+ nBins: 10,
+ });
+
+ // Verify query succeeded
+ expect(result.counts).toBeDefined();
+
+ // Note: With 101k scores, sampling may or may not trigger depending on
+ // preflight variance (1% sample of 101k = ~1010 samples, extrapolated = 95k-105k)
+ // If sampling triggers: ~100k rows each (rate ≈ 99%)
+ // If no sampling: full 101k rows each
+ // Hash-based sampling (cityHash64) provides uniform distribution on average,
+ // but can have ~6% variance. With 101k scores, actual results range 94k-106k.
+ // Using 90k threshold (not 95k) to account for this probabilistic variance.
+ expect(result.counts.score1Total).toBeGreaterThan(90_000);
+ expect(result.counts.score2Total).toBeGreaterThan(90_000);
+
+ // matchedCount should be close to score totals (all scores match in this test)
+ // Same 90k threshold to account for hash sampling variance
+ expect(result.counts.matchedCount).toBeGreaterThan(90_000);
+ expect(result.counts.matchedCount).toBeLessThanOrEqual(101_000);
+
+ // Verify preflight estimates via samplingMetadata
+ expect(result.samplingMetadata.preflightEstimates).toBeDefined();
+ // Preflight uses 1% sampling, so estimates may have variance
+ // For 101k scores, 1% sample could estimate anywhere from ~95k-105k
+ expect(
+ result.samplingMetadata.preflightEstimates?.score1Count,
+ ).toBeGreaterThan(90_000);
+ expect(
+ result.samplingMetadata.preflightEstimates?.score2Count,
+ ).toBeGreaterThan(90_000);
+ expect(
+ result.samplingMetadata.preflightEstimates?.estimatedMatchedCount,
+ ).toBeGreaterThan(90_000);
+
+ // Verify adaptive FINAL decision via samplingMetadata
+ expect(result.samplingMetadata.adaptiveFinal).toBeDefined();
+ // The decision logic should evaluate based on estimates
+ // If estimates are >= 100k threshold, usedFinal = false
+ // If estimates are < 100k threshold, usedFinal = true
+ // Both outcomes are valid for this test - what matters is the query completes successfully
+ expect(typeof result.samplingMetadata.adaptiveFinal?.usedFinal).toBe(
+ "boolean",
+ );
+ expect(result.samplingMetadata.adaptiveFinal?.reason).toBeDefined();
+ }, 120000); // 2 minute timeout for large data insertion
+
+ // Test 6: Adaptive FINAL with 150k scores - should definitively skip FINAL
+ it("should skip FINAL for 150k+ scores with high confidence", async () => {
+ const now = new Date();
+ const fromTimestamp = new Date(now.getTime() - 3600000);
+ const toTimestamp = new Date(now.getTime() + 3600000);
+
+ const scoreName1 = `test-xlarge-score1-${v4()}`;
+ const scoreName2 = `test-xlarge-score2-${v4()}`;
+
+ // Create 150k scores for score1 and 150k for score2
+ // This is well above ADAPTIVE_FINAL_THRESHOLD (100k)
+ // Even with 1% sampling variance, should reliably estimate >100k
+ const score1Batch: ReturnType<typeof createTraceScore>[] = [];
+ const score2Batch: ReturnType<typeof createTraceScore>[] = [];
+ const tracesBatch: ReturnType<typeof createTrace>[] = [];
+
+ const batchSize = 150_000; // Well above threshold
+
+ console.log(
+ `Creating ${batchSize} scores for large-scale adaptive FINAL test (this may take a moment)...`,
+ );
+
+ for (let i = 0; i < batchSize; i++) {
+ const traceId = v4();
+
+ // Create trace
+ tracesBatch.push(
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime(),
+ }),
+ );
+
+ // Create score1
+ score1Batch.push(
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName1,
+ source: "ANNOTATION",
+ data_type: "NUMERIC",
+ value: Math.random(),
+ timestamp: now.getTime(),
+ }),
+ );
+
+ // Create score2
+ score2Batch.push(
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName2,
+ source: "ANNOTATION",
+ data_type: "NUMERIC",
+ value: Math.random(),
+ timestamp: now.getTime(),
+ }),
+ );
+ }
+
+ // Insert in batches to avoid memory issues
+ const insertBatchSize = 10_000;
+ for (let i = 0; i < batchSize; i += insertBatchSize) {
+ await createTracesCh(tracesBatch.slice(i, i + insertBatchSize));
+ await createScoresCh([
+ ...score1Batch.slice(i, i + insertBatchSize),
+ ...score2Batch.slice(i, i + insertBatchSize),
+ ]);
+ }
+
+ console.log(`Inserted ${batchSize} traces and ${batchSize * 2} scores`);
+
+ const result = await caller.scores.getScoreComparisonAnalytics({
+ projectId,
+ score1: {
+ name: scoreName1,
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ },
+ score2: {
+ name: scoreName2,
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 1, unit: "day" },
+ nBins: 10,
+ });
+
+ // Verify query succeeded
+ expect(result.counts).toBeDefined();
+
+ // Note: With 150k scores in each table, sampling will trigger (threshold = 100k)
+ // Sampling rate = 100k / 150k = 67%, so we expect ~100k from each table
+ // Allow variance due to hash distribution
+ expect(result.counts.score1Total).toBeGreaterThan(90_000);
+ expect(result.counts.score1Total).toBeLessThan(110_000);
+ expect(result.counts.score2Total).toBeGreaterThan(90_000);
+ expect(result.counts.score2Total).toBeLessThan(110_000);
+
+ // matchedCount should be similar to sample size (not the full 150k)
+ expect(result.counts.matchedCount).toBeGreaterThan(90_000);
+ expect(result.counts.matchedCount).toBeLessThan(110_000);
+
+ // Verify preflight estimates via samplingMetadata
+ expect(result.samplingMetadata.preflightEstimates).toBeDefined();
+ // For 150k scores, even with 1% sampling variance, should reliably estimate >100k
+ // 150k * 1% = 1500 sampled → extrapolated estimate should be 140k-160k range
+ expect(
+ result.samplingMetadata.preflightEstimates?.score1Count,
+ ).toBeGreaterThan(100_000);
+ expect(
+ result.samplingMetadata.preflightEstimates?.score2Count,
+ ).toBeGreaterThan(100_000);
+ expect(
+ result.samplingMetadata.preflightEstimates?.estimatedMatchedCount,
+ ).toBeGreaterThan(100_000);
+
+ // Verify adaptive FINAL decision via samplingMetadata
+ // For 150k scores, should definitively skip FINAL for performance
+ expect(result.samplingMetadata.adaptiveFinal).toBeDefined();
+ expect(result.samplingMetadata.adaptiveFinal?.usedFinal).toBe(false);
+ expect(result.samplingMetadata.adaptiveFinal?.reason).toContain(
+ "Large dataset - skipping FINAL for performance",
+ );
+
+ // Verify sampling was applied (150k > 100k threshold)
+ expect(result.samplingMetadata.isSampled).toBe(true);
+ expect(result.samplingMetadata.samplingMethod).toBe("hash");
+ expect(result.samplingMetadata.samplingRate).toBeCloseTo(0.67, 1); // 100k/150k ≈ 0.67
+ }, 180000); // 3 minute timeout for large data insertion
+
+ // Test 7: Hash-based sampling for datasets with >100k estimated matched scores
+ it("should apply hash-based sampling when estimated matched count exceeds threshold", async () => {
+ const now = new Date();
+ const fromTimestamp = new Date(now.getTime() - 3600000);
+ const toTimestamp = new Date(now.getTime() + 3600000);
+
+ const scoreName1 = `test-hash-sample-s1-${v4()}`;
+ const scoreName2 = `test-hash-sample-s2-${v4()}`;
+
+ // Create 120k matched scores (both scores on same traces)
+ // This should trigger hash-based sampling (threshold = 100k)
+ const score1Batch: ReturnType<typeof createTraceScore>[] = [];
+ const score2Batch: ReturnType<typeof createTraceScore>[] = [];
+ const tracesBatch: ReturnType<typeof createTrace>[] = [];
+
+ const batchSize = 120_000;
+
+ console.log(
+ `Creating ${batchSize} matched scores for hash-based sampling test...`,
+ );
+
+ for (let i = 0; i < batchSize; i++) {
+ const traceId = v4();
+ const scoreTimestamp =
+ now.getTime() - Math.floor(Math.random() * 3600000);
+
+ tracesBatch.push(
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime(),
+ }),
+ );
+
+ score1Batch.push(
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName1,
+ source: "ANNOTATION",
+ value: Math.random() * 100,
+ data_type: "NUMERIC",
+ timestamp: scoreTimestamp,
+ }),
+ );
+
+ score2Batch.push(
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName2,
+ source: "ANNOTATION",
+ value: Math.random() * 100,
+ data_type: "NUMERIC",
+ timestamp: scoreTimestamp,
+ }),
+ );
+ }
+
+ await createTracesCh(tracesBatch);
+ await createScoresCh([...score1Batch, ...score2Batch]);
+
+ const result = await caller.scores.getScoreComparisonAnalytics({
+ projectId,
+ score1: {
+ name: scoreName1,
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ },
+ score2: {
+ name: scoreName2,
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 1, unit: "hour" as const },
+ objectType: "all",
+ });
+
+ // Verify query succeeded
+ expect(result.counts).toBeDefined();
+
+ // Verify sampling was applied
+ expect(result.samplingMetadata.isSampled).toBe(true);
+ expect(result.samplingMetadata.samplingMethod).toBe("hash");
+ expect(result.samplingMetadata.samplingRate).toBeLessThan(1.0);
+ expect(result.samplingMetadata.samplingRate).toBeGreaterThan(0);
+ expect(result.samplingMetadata.samplingExpression).toContain(
+ "cityHash64",
+ );
+
+ // Verify preflight estimates triggered sampling
+ expect(
+ result.samplingMetadata.preflightEstimates?.estimatedMatchedCount,
+ ).toBeGreaterThan(100_000);
+
+ // Verify actualSampleSize is approximately TARGET_SAMPLE_SIZE (100k)
+ // Allow for variance due to hash distribution
+ expect(result.samplingMetadata.actualSampleSize).toBeGreaterThan(80_000);
+ expect(result.samplingMetadata.actualSampleSize).toBeLessThan(120_000);
+
+ // Verify counts reflect sampling
+ expect(result.counts.matchedCount).toBe(
+ result.samplingMetadata.actualSampleSize,
+ );
+
+ // Verify data quality - all result arrays should have data
+ expect(result.heatmap.length).toBeGreaterThan(0);
+ expect(result.timeSeries.length).toBeGreaterThan(0);
+ }, 180000); // 3 minute timeout for large data insertion
+
+ // Test 8: Identical scores with sampling show perfect correlation
+ it("should return perfect correlation for identical scores with sampling", async () => {
+ const now = new Date();
+ const fromTimestamp = new Date(now.getTime() - 3600000);
+ const toTimestamp = new Date(now.getTime() + 3600000);
+
+ const scoreName = `test-identical-${v4()}`;
+
+ // Create 150k scores (exceeds sampling threshold)
+ const scoreBatch: ReturnType<typeof createTraceScore>[] = [];
+ const tracesBatch: ReturnType<typeof createTrace>[] = [];
+
+ const batchSize = 150_000;
+
+ console.log(
+ `Creating ${batchSize} identical scores for perfect correlation test...`,
+ );
+
+ for (let i = 0; i < batchSize; i++) {
+ const traceId = v4();
+ const scoreTimestamp =
+ now.getTime() - Math.floor(Math.random() * 3600000);
+
+ tracesBatch.push(
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime(),
+ }),
+ );
+
+ scoreBatch.push(
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: scoreName,
+ source: "ANNOTATION",
+ value: Math.random() * 100,
+ data_type: "NUMERIC",
+ timestamp: scoreTimestamp,
+ }),
+ );
+ }
+
+ // Insert in batches
+ const insertBatchSize = 10_000;
+ for (let i = 0; i < batchSize; i += insertBatchSize) {
+ await createTracesCh(tracesBatch.slice(i, i + insertBatchSize));
+ await createScoresCh(scoreBatch.slice(i, i + insertBatchSize));
+ }
+
+ console.log(`Inserted ${batchSize} traces and scores`);
+
+ // Compare score to itself
+ const result = await caller.scores.getScoreComparisonAnalytics({
+ projectId,
+ score1: {
+ name: scoreName,
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ },
+ score2: {
+ name: scoreName,
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 1, unit: "hour" as const },
+ objectType: "all",
+ });
+
+ // Verify sampling occurred (150k > 100k threshold)
+ expect(result.samplingMetadata.isSampled).toBe(true);
+ expect(result.samplingMetadata.samplingMethod).toBe("hash");
+
+ // CRITICAL: For identical scores, score1Total === score2Total === matchedCount
+ // This ensures the same sample was used for both CTEs
+ expect(result.counts.score1Total).toBe(result.counts.score2Total);
+ expect(result.counts.matchedCount).toBe(result.counts.score1Total);
+ expect(result.counts.matchedCount).toBe(result.counts.score2Total);
+
+ // Verify sample size is within expected range (~100k)
+ expect(result.counts.matchedCount).toBeGreaterThan(90_000);
+ expect(result.counts.matchedCount).toBeLessThan(110_000);
+
+ // 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,
+ );
+ 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();
+ }, 180000); // 3 minute timeout for large data insertion
+
+ // Test 9: Calculates counts correctly with partial matches
it("should calculate counts correctly with partial matches", async () => {
const trace1 = v4();
const trace2 = v4();
@@ -1428,61 +2009,6 @@ describe("Score Comparison Analytics tRPC", () => {
expect(result.counts.matchedCount).toBe(1);
});
- // Test 21: Enforces max matched scores limit
- it("should enforce maxMatchedScoresLimit", async () => {
- const traces = Array.from({ length: 150 }, () => v4());
- await createTracesCh(
- traces.map((id) => createTrace({ id, project_id: projectId })),
- );
-
- const now = new Date();
- const fromTimestamp = new Date(now.getTime() - 3600000);
- const toTimestamp = new Date(now.getTime() + 3600000);
-
- const scoreName1 = `test21-limit1-${v4()}`;
- const scoreName2 = `test21-limit2-${v4()}`;
-
- // Create 150 matched pairs
- const scores = traces.flatMap((traceId) => [
- createTraceScore({
- project_id: projectId,
- trace_id: traceId,
- observation_id: null,
- name: scoreName1,
- source: "API",
- data_type: "NUMERIC",
- value: 1,
- timestamp: now.getTime(),
- }),
- createTraceScore({
- project_id: projectId,
- trace_id: traceId,
- observation_id: null,
- name: scoreName2,
- source: "API",
- data_type: "NUMERIC",
- value: 2,
- timestamp: now.getTime(),
- }),
- ]);
-
- await createScoresCh(scores);
-
- const result = 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: "day" },
- nBins: 10,
- maxMatchedScoresLimit: 100,
- });
-
- // Matched count should be limited to 100
- expect(result.counts.matchedCount).toBeLessThanOrEqual(100);
- });
-
// Test 22: Handles out-of-order timestamps
it("should handle scores created in random order", async () => {
const traces = [v4(), v4(), v4()];
@@ -3540,5 +4066,180 @@ describe("Score Comparison Analytics tRPC", () => {
expect(entry.count).toBe(2);
});
});
+
+ // Test: ObjectType filtering works correctly for all types
+ it("should filter scores correctly by objectType (trace, observation, session, dataset_run)", async () => {
+ const traceId = v4();
+ const observationId = v4();
+ const sessionId = v4();
+ const datasetRunId = v4();
+
+ const now = new Date();
+ const fromTimestamp = new Date(now.getTime() - 3600000);
+ const toTimestamp = new Date(now.getTime() + 3600000);
+
+ const scoreName1 = `objectType-test-score1-${v4()}`;
+ const scoreName2 = `objectType-test-score2-${v4()}`;
+
+ // Create trace for trace-level scores
+ const trace = createTrace({ id: traceId, project_id: projectId });
+ await createTracesCh([trace]);
+
+ // Create observation for observation-level scores
+ const observation = createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ });
+ await createObservationsCh([observation]);
+
+ const scores = [
+ // Trace-level scores (2 pairs)
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ session_id: null,
+ name: scoreName1,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 1.0,
+ timestamp: now.getTime(),
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: null,
+ session_id: null,
+ name: scoreName2,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 2.0,
+ timestamp: now.getTime(),
+ }),
+
+ // Observation-level scores (2 pairs)
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ session_id: null,
+ name: scoreName1,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 3.0,
+ timestamp: now.getTime(),
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ session_id: null,
+ name: scoreName2,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 4.0,
+ timestamp: now.getTime(),
+ }),
+
+ // Session-level scores (2 pairs)
+ createSessionScore({
+ project_id: projectId,
+ session_id: sessionId,
+ name: scoreName1,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 5.0,
+ timestamp: now.getTime(),
+ }),
+ createSessionScore({
+ project_id: projectId,
+ session_id: sessionId,
+ name: scoreName2,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 6.0,
+ timestamp: now.getTime(),
+ }),
+
+ // Dataset run-level scores (2 pairs)
+ createDatasetRunScore({
+ project_id: projectId,
+ dataset_run_id: datasetRunId,
+ name: scoreName1,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 7.0,
+ timestamp: now.getTime(),
+ }),
+ createDatasetRunScore({
+ project_id: projectId,
+ dataset_run_id: datasetRunId,
+ name: scoreName2,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 8.0,
+ timestamp: now.getTime(),
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ const baseParams = {
+ projectId,
+ score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },
+ score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },
+ fromTimestamp,
+ toTimestamp,
+ interval: { count: 1, unit: "hour" as const },
+ };
+
+ // Test 1: objectType = "all" should return all 4 matched pairs
+ const resultAll = await caller.scores.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",
+ });
+ 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(
+ {
+ ...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",
+ });
+ 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",
+ });
+ expect(resultDatasetRun.counts.matchedCount).toBe(1);
+ expect(resultDatasetRun.counts.score1Total).toBe(1);
+ expect(resultDatasetRun.counts.score2Total).toBe(1);
+ });
});
});
diff --git a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsDashboard.tsx b/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsDashboard.tsx
index 02dd2944df..20aecc3ad1 100644
--- a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsDashboard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsDashboard.tsx
@@ -5,6 +5,7 @@ import { DistributionCategoricalCard } from "./cards/DistributionCategoricalCard
import { DistributionBooleanCard } from "./cards/DistributionBooleanCard";
import { HeatmapCard } from "./cards/HeatmapCard";
import { useScoreAnalytics } from "./ScoreAnalyticsProvider";
+import { ScoreAnalyticsNoticeBanner } from "./ScoreAnalyticsNoticeBanner";
/**
* ScoreAnalyticsDashboard - Layout component for score analytics
@@ -53,11 +54,17 @@ export function ScoreAnalyticsDashboard() {
};
return (
- <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
- <StatisticsCard />
- <TimelineChartCard />
- {renderDistributionCard()}
- <HeatmapCard />
- </div>
+ <>
+ {/* Unified notice banner (transitions: loading → sampling notice) */}
+ <ScoreAnalyticsNoticeBanner />
+
+ {/* Main grid */}
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
+ <StatisticsCard />
+ <TimelineChartCard />
+ {renderDistributionCard()}
+ <HeatmapCard />
+ </div>
+ </>
);
}
diff --git a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx b/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx
new file mode 100644
index 0000000000..68970ac4d1
--- /dev/null
+++ b/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsNoticeBanner.tsx
@@ -0,0 +1,200 @@
+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">
+ 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}
+ />
+ </div>
+ <div className="text-sm text-muted-foreground">
+ 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,
+ showLabel = false,
+}: {
+ samplingMetadata: {
+ samplingRate: number;
+ preflightEstimates?: {
+ score1Count: number;
+ score2Count: number;
+ estimatedMatchedCount: number;
+ };
+ adaptiveFinal?: {
+ usedFinal: boolean;
+ reason: string;
+ };
+ };
+ 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">Estimated Scores</h4>
+ <dl className="space-y-1 text-sm">
+ <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/features/scores/components/score-analytics/components/ScoreAnalyticsProvider.tsx b/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsProvider.tsx
index f201a04266..ab0de2194f 100644
--- a/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsProvider.tsx
+++ b/web/src/features/scores/components/score-analytics/components/ScoreAnalyticsProvider.tsx
@@ -10,6 +10,7 @@ import {
getScoreNumericColor,
buildColorMappings,
} from "@/src/features/scores/components/score-analytics/libs/color-scales";
+import { api } from "@/src/utils/api";
// Re-export types for convenience
export type {
@@ -55,12 +56,23 @@ function getScoreColors(mode: "single" | "two" | undefined): ScoreColors {
// Context Definition
// ============================================================================
+export interface EstimateData {
+ score1Count: number;
+ score2Count: number;
+ estimatedMatchedCount: number;
+ willSample: boolean;
+ willSkipFinal: boolean;
+ estimatedQueryTime: string;
+}
+
export interface ScoreAnalyticsContextValue
extends UseScoreAnalyticsQueryResult {
colors: ScoreColors;
params: ScoreAnalyticsQueryParams;
colorMappings: Record<string, string>;
getColorForScore: (scoreNumber: 1 | 2) => string;
+ estimate: EstimateData | undefined;
+ isEstimating: boolean;
}
const ScoreAnalyticsContext = createContext<
@@ -95,8 +107,31 @@ export function ScoreAnalyticsProvider({
params,
children,
}: ScoreAnalyticsProviderProps) {
- // Fetch and transform data using the hook
- const queryResult = useScoreAnalyticsQuery(params);
+ // Step 1: Run estimate query first
+ const canEstimate =
+ params.score1 !== undefined && params.score2 !== undefined;
+
+ const estimateQuery = api.scores.estimateScoreComparisonSize.useQuery(
+ {
+ projectId: params.projectId,
+ score1: params.score1 ?? { name: "", dataType: "", source: "" },
+ score2: params.score2 ?? { name: "", dataType: "", source: "" },
+ fromTimestamp: params.fromTimestamp,
+ toTimestamp: params.toTimestamp,
+ objectType: params.objectType ?? "all",
+ },
+ {
+ enabled: canEstimate,
+ staleTime: 30_000, // Cache for 30 seconds
+ trpc: { abortOnUnmount: true },
+ },
+ );
+
+ // Step 2: Only run main query after estimate succeeds (two-score mode)
+ // For single-score mode, run immediately without estimate
+ const queryResult = useScoreAnalyticsQuery(params, {
+ enabled: !canEstimate || estimateQuery.isSuccess,
+ });
// Determine color scheme based on mode
const colors = useMemo(() => {
@@ -134,8 +169,18 @@ export function ScoreAnalyticsProvider({
params,
colorMappings,
getColorForScore,
+ estimate: estimateQuery.data,
+ isEstimating: estimateQuery.isLoading,
}),
- [queryResult, colors, params, colorMappings, getColorForScore],
+ [
+ queryResult,
+ colors,
+ params,
+ colorMappings,
+ getColorForScore,
+ estimateQuery.data,
+ estimateQuery.isLoading,
+ ],
);
return (
diff --git a/web/src/features/scores/components/score-analytics/components/cards/DistributionBooleanCard.tsx b/web/src/features/scores/components/score-analytics/components/cards/DistributionBooleanCard.tsx
index 88f7b1553c..865d79eb63 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/DistributionBooleanCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/cards/DistributionBooleanCard.tsx
@@ -10,6 +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";
type DistributionTab = "score1" | "score2" | "all" | "matched";
@@ -157,8 +158,8 @@ export function DistributionBooleanCard() {
// Helper function to truncate tab labels with max character limit
const truncateLabel = (label: string): string => {
- if (label.length <= 10) return label;
- return label.substring(0, 7) + "...";
+ if (label.length <= 20) return label;
+ return label.substring(0, 17) + "...";
};
// Build full tab labels for title attribute (hover tooltip)
@@ -178,44 +179,45 @@ export function DistributionBooleanCard() {
<CardHeader>
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between">
- <div>
- <CardTitle>Distribution</CardTitle>
+ <div className="flex-1">
+ <CardTitle className="flex items-center gap-2">
+ Distribution
+ {data.samplingMetadata.isSampled && (
+ <SamplingDetailsHoverCard
+ samplingMetadata={data.samplingMetadata}
+ showLabel
+ />
+ )}
+ </CardTitle>
<CardDescription>{description}</CardDescription>
</div>
- {showTabs && (
- <Tabs
- value={activeTab}
- onValueChange={(v) => setActiveTab(v as DistributionTab)}
- className="hidden xl:block"
- >
- <TabsList className="grid w-[400px] grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
- {truncateLabel(score1FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
- {truncateLabel(score2FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
- </TabsList>
- </Tabs>
- )}
</div>
{showTabs && (
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as DistributionTab)}
- className="xl:hidden"
>
- <TabsList className="grid w-full grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
+ <TabsList className="h-7">
+ <TabsTrigger
+ value="score1"
+ title={score1FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score1FullLabel)}
</TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
+ <TabsTrigger
+ value="score2"
+ title={score2FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score2FullLabel)}
</TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
+ <TabsTrigger value="all" className="h-5 px-2 text-xs">
+ all
+ </TabsTrigger>
+ <TabsTrigger value="matched" className="h-5 px-2 text-xs">
+ matched
+ </TabsTrigger>
</TabsList>
</Tabs>
)}
diff --git a/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx b/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
index a2d84886ad..4c2385195f 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/cards/DistributionCategoricalCard.tsx
@@ -11,6 +11,7 @@ import { Loader2 } from "lucide-react";
import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { ScoreDistributionCategoricalChart } from "../charts/ScoreDistributionCategoricalChart";
import { getScoreCategoryColors } from "../../libs/color-scales";
+import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
type DistributionTab = "score1" | "score2" | "all" | "matched";
@@ -248,8 +249,8 @@ export function DistributionCategoricalCard() {
// Helper function to truncate tab labels with max character limit
const truncateLabel = (label: string): string => {
- if (label.length <= 10) return label;
- return label.substring(0, 7) + "...";
+ if (label.length <= 20) return label;
+ return label.substring(0, 17) + "...";
};
// Build full tab labels for title attribute (hover tooltip)
@@ -269,44 +270,45 @@ export function DistributionCategoricalCard() {
<CardHeader>
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between">
- <div>
- <CardTitle>Distribution</CardTitle>
+ <div className="flex-1">
+ <CardTitle className="flex items-center gap-2">
+ Distribution
+ {data.samplingMetadata.isSampled && (
+ <SamplingDetailsHoverCard
+ samplingMetadata={data.samplingMetadata}
+ showLabel
+ />
+ )}
+ </CardTitle>
<CardDescription>{chartData.description}</CardDescription>
</div>
- {showTabs && (
- <Tabs
- value={activeTab}
- onValueChange={(v) => setActiveTab(v as DistributionTab)}
- className="hidden xl:block"
- >
- <TabsList className="grid w-[400px] grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
- {truncateLabel(score1FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
- {truncateLabel(score2FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
- </TabsList>
- </Tabs>
- )}
</div>
{showTabs && (
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as DistributionTab)}
- className="xl:hidden"
>
- <TabsList className="grid w-full grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
+ <TabsList className="h-7">
+ <TabsTrigger
+ value="score1"
+ title={score1FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score1FullLabel)}
</TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
+ <TabsTrigger
+ value="score2"
+ title={score2FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score2FullLabel)}
</TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
+ <TabsTrigger value="all" className="h-5 px-2 text-xs">
+ all
+ </TabsTrigger>
+ <TabsTrigger value="matched" className="h-5 px-2 text-xs">
+ matched
+ </TabsTrigger>
</TabsList>
</Tabs>
)}
diff --git a/web/src/features/scores/components/score-analytics/components/cards/DistributionNumericCard.tsx b/web/src/features/scores/components/score-analytics/components/cards/DistributionNumericCard.tsx
index 7b22d751a6..7441c54944 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/DistributionNumericCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/cards/DistributionNumericCard.tsx
@@ -10,6 +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";
type DistributionTab = "score1" | "score2" | "all" | "matched";
@@ -185,8 +186,8 @@ export function DistributionNumericCard() {
// Helper function to truncate tab labels with max character limit
const truncateLabel = (label: string): string => {
- if (label.length <= 10) return label;
- return label.substring(0, 7) + "...";
+ if (label.length <= 20) return label;
+ return label.substring(0, 17) + "...";
};
// Build full tab labels for title attribute (hover tooltip)
@@ -206,44 +207,45 @@ export function DistributionNumericCard() {
<CardHeader>
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between">
- <div>
- <CardTitle>Distribution</CardTitle>
+ <div className="flex-1">
+ <CardTitle className="flex items-center gap-2">
+ Distribution
+ {data.samplingMetadata.isSampled && (
+ <SamplingDetailsHoverCard
+ samplingMetadata={data.samplingMetadata}
+ showLabel
+ />
+ )}
+ </CardTitle>
<CardDescription>{description}</CardDescription>
</div>
- {showTabs && (
- <Tabs
- value={activeTab}
- onValueChange={(v) => setActiveTab(v as DistributionTab)}
- className="hidden xl:block"
- >
- <TabsList className="grid w-[400px] grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
- {truncateLabel(score1FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
- {truncateLabel(score2FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
- </TabsList>
- </Tabs>
- )}
</div>
{showTabs && (
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as DistributionTab)}
- className="xl:hidden"
>
- <TabsList className="grid w-full grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
+ <TabsList className="h-7">
+ <TabsTrigger
+ value="score1"
+ title={score1FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score1FullLabel)}
</TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
+ <TabsTrigger
+ value="score2"
+ title={score2FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score2FullLabel)}
</TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
+ <TabsTrigger value="all" className="h-5 px-2 text-xs">
+ all
+ </TabsTrigger>
+ <TabsTrigger value="matched" className="h-5 px-2 text-xs">
+ matched
+ </TabsTrigger>
</TabsList>
</Tabs>
)}
diff --git a/web/src/features/scores/components/score-analytics/components/cards/HeatmapCard.tsx b/web/src/features/scores/components/score-analytics/components/cards/HeatmapCard.tsx
index 91a554189f..2dd859c8f6 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/HeatmapCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/cards/HeatmapCard.tsx
@@ -14,6 +14,7 @@ import { getHeatmapCellColor } from "@/src/features/scores/components/score-anal
import { type HeatmapCell } from "@/src/features/scores/components/score-analytics/libs/heatmap-utils";
import { useCallback } from "react";
import type { ScoreDataType } from "@langfuse/shared";
+import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
interface HeatmapTooltipContentProps {
cell: HeatmapCell;
@@ -246,20 +247,32 @@ export function HeatmapCard() {
return (
<Card>
<CardHeader>
- <div className="flex items-start justify-between">
- <div>
- <CardTitle>{title}</CardTitle>
- <CardDescription>{description}</CardDescription>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-start justify-between">
+ <div className="flex-1">
+ <CardTitle className="flex items-center gap-2">
+ {title}
+ {data.samplingMetadata.isSampled && (
+ <SamplingDetailsHoverCard
+ samplingMetadata={data.samplingMetadata}
+ showLabel
+ />
+ )}
+ </CardTitle>
+ <CardDescription>{description}</CardDescription>
+ </div>
+ {hasData && (
+ <HeatmapLegend
+ min={0}
+ max={maxValue}
+ scoreNumber={1}
+ orientation="horizontal"
+ steps={5}
+ />
+ )}
</div>
- {hasData && (
- <HeatmapLegend
- min={0}
- max={maxValue}
- scoreNumber={1}
- orientation="horizontal"
- steps={5}
- />
- )}
+ {/* Placeholder to align with tabs in other cards */}
+ <div className="h-10" />
</div>
</CardHeader>
<CardContent className="flex flex-1 flex-col items-center gap-4 pl-0">
diff --git a/web/src/features/scores/components/score-analytics/components/cards/StatisticsCard.tsx b/web/src/features/scores/components/score-analytics/components/cards/StatisticsCard.tsx
index 6e50bdbe1e..b7995cd3b5 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/StatisticsCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/cards/StatisticsCard.tsx
@@ -8,6 +8,7 @@ import {
import { Loader2 } from "lucide-react";
import { useScoreAnalytics } from "../ScoreAnalyticsProvider";
import { MetricCard } from "../charts/MetricCard";
+import { SamplingDetailsHoverCard } from "../ScoreAnalyticsNoticeBanner";
import {
calculateCohensKappa,
calculateWeightedF1Score,
@@ -73,6 +74,13 @@ export function StatisticsCard() {
const { dataType } = metadata;
const { score1, score2 } = params;
+ // Check if Cartesian product occurred (matched count exceeds both individual counts)
+ const hasCartesianProduct =
+ statistics.comparison &&
+ statistics.comparison.matchedCount > statistics.score1.total &&
+ statistics.score2 &&
+ statistics.comparison.matchedCount > statistics.score2.total;
+
// Determine what to show
const showScore1Data = statistics.score1.total > 0;
const showScore2Data = statistics.score2 !== null;
@@ -100,7 +108,15 @@ export function StatisticsCard() {
return (
<Card>
<CardHeader>
- <CardTitle>Statistics</CardTitle>
+ <CardTitle className="flex items-center gap-2">
+ Statistics
+ {data.samplingMetadata.isSampled && (
+ <SamplingDetailsHoverCard
+ samplingMetadata={data.samplingMetadata}
+ showLabel
+ />
+ )}
+ </CardTitle>
<CardDescription>
{score2
? `${score1.name} vs ${score2.name}`
@@ -309,6 +325,33 @@ export function StatisticsCard() {
: "--"
}
helpText="Number of observations with both scores"
+ warning={
+ hasCartesianProduct
+ ? {
+ show: true,
+ content: (
+ <div className="space-y-2 text-xs">
+ <p className="font-semibold">
+ Matched count exceeds individual score counts
+ due to Cartesian product
+ </p>
+ <p>
+ This occurs when multiple scores of the same
+ name/source exist on a single attachment point
+ (trace/observation/session/run). Each
+ combination creates a match.
+ </p>
+ <p className="text-muted-foreground">
+ <strong>Example:</strong> If one trace has 2
+ &quot;gpt4&quot; scores and 3
+ &quot;gemini&quot; scores, this creates 6
+ matched pairs (2 × 3 = 6).
+ </p>
+ </div>
+ ),
+ }
+ : undefined
+ }
isContext
isPlaceholder={!showComparisonMetrics}
/>
@@ -418,6 +461,33 @@ export function StatisticsCard() {
: "--"
}
helpText="Number of observations with both scores"
+ warning={
+ hasCartesianProduct
+ ? {
+ show: true,
+ content: (
+ <div className="space-y-2 text-xs">
+ <p className="font-semibold">
+ Matched count exceeds individual score counts
+ due to Cartesian product
+ </p>
+ <p>
+ This occurs when multiple scores of the same
+ name/source exist on a single attachment point
+ (trace/observation/session/run). Each
+ combination creates a match.
+ </p>
+ <p className="text-muted-foreground">
+ <strong>Example:</strong> If one trace has 2
+ &quot;gpt4&quot; scores and 3
+ &quot;gemini&quot; scores, this creates 6
+ matched pairs (2 × 3 = 6).
+ </p>
+ </div>
+ ),
+ }
+ : undefined
+ }
isContext
isPlaceholder={!showComparisonMetrics}
/>
diff --git a/web/src/features/scores/components/score-analytics/components/cards/TimelineChartCard.tsx b/web/src/features/scores/components/score-analytics/components/cards/TimelineChartCard.tsx
index 9f5095863a..5554d6a66b 100644
--- a/web/src/features/scores/components/score-analytics/components/cards/TimelineChartCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/cards/TimelineChartCard.tsx
@@ -10,6 +10,7 @@ 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 {
getScoreCategoryColors,
getScoreBooleanColors,
@@ -247,8 +248,8 @@ export function TimelineChartCard() {
// Helper function to truncate tab labels with max character limit
const truncateLabel = (label: string): string => {
- if (label.length <= 10) return label;
- return label.substring(0, 7) + "...";
+ if (label.length <= 20) return label;
+ return label.substring(0, 17) + "...";
};
// Build full tab labels for title attribute (hover tooltip)
@@ -268,44 +269,45 @@ export function TimelineChartCard() {
<CardHeader>
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between">
- <div>
- <CardTitle>Trend Over Time</CardTitle>
+ <div className="flex-1">
+ <CardTitle className="flex items-center gap-2">
+ Trend Over Time
+ {data.samplingMetadata.isSampled && (
+ <SamplingDetailsHoverCard
+ samplingMetadata={data.samplingMetadata}
+ showLabel
+ />
+ )}
+ </CardTitle>
<CardDescription>{description}</CardDescription>
</div>
- {showTabs && (
- <Tabs
- value={activeTab}
- onValueChange={(v) => setActiveTab(v as TimelineTab)}
- className="hidden xl:block"
- >
- <TabsList className="grid w-[400px] grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
- {truncateLabel(score1FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
- {truncateLabel(score2FullLabel)}
- </TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
- </TabsList>
- </Tabs>
- )}
</div>
{showTabs && (
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as TimelineTab)}
- className="xl:hidden"
>
- <TabsList className="grid w-full grid-cols-4">
- <TabsTrigger value="score1" title={score1FullLabel}>
+ <TabsList className="h-7">
+ <TabsTrigger
+ value="score1"
+ title={score1FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score1FullLabel)}
</TabsTrigger>
- <TabsTrigger value="score2" title={score2FullLabel}>
+ <TabsTrigger
+ value="score2"
+ title={score2FullLabel}
+ className="h-5 px-2 text-xs"
+ >
{truncateLabel(score2FullLabel)}
</TabsTrigger>
- <TabsTrigger value="all">all</TabsTrigger>
- <TabsTrigger value="matched">matched</TabsTrigger>
+ <TabsTrigger value="all" className="h-5 px-2 text-xs">
+ all
+ </TabsTrigger>
+ <TabsTrigger value="matched" className="h-5 px-2 text-xs">
+ matched
+ </TabsTrigger>
</TabsList>
</Tabs>
)}
diff --git a/web/src/features/scores/components/score-analytics/components/charts/MetricCard.tsx b/web/src/features/scores/components/score-analytics/components/charts/MetricCard.tsx
index f5ca0d5036..3e0e16c7ee 100644
--- a/web/src/features/scores/components/score-analytics/components/charts/MetricCard.tsx
+++ b/web/src/features/scores/components/score-analytics/components/charts/MetricCard.tsx
@@ -5,7 +5,12 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/src/components/ui/tooltip";
-import { HelpCircle } from "lucide-react";
+import {
+ HoverCard,
+ HoverCardContent,
+ 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";
interface MetricCardProps {
@@ -13,6 +18,10 @@ interface MetricCardProps {
value: string | number;
interpretation?: InterpretationResult;
helpText?: string;
+ warning?: {
+ show: boolean;
+ content: React.ReactNode;
+ };
isPlaceholder?: boolean;
isContext?: boolean; // Data context metrics (counts) vs analysis metrics (statistics)
}
@@ -27,6 +36,7 @@ export function MetricCard({
value,
interpretation,
helpText,
+ warning,
isPlaceholder = false,
isContext = false,
}: MetricCardProps) {
@@ -107,6 +117,16 @@ export function MetricCard({
</Tooltip>
</TooltipProvider>
)}
+ {warning?.show && !isPlaceholder && !isNA && (
+ <HoverCard>
+ <HoverCardTrigger asChild>
+ <AlertCircle className="h-4 w-4 cursor-help text-amber-500" />
+ </HoverCardTrigger>
+ <HoverCardContent className="w-80">
+ {warning.content}
+ </HoverCardContent>
+ </HoverCard>
+ )}
</div>
</div>
);
diff --git a/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts b/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
index f385fbb733..059bee2ed5 100644
--- a/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
+++ b/web/src/features/scores/components/score-analytics/hooks/useScoreAnalyticsQuery.ts
@@ -127,6 +127,29 @@ export interface TimeSeries {
};
}
+/**
+ * Sampling metadata for query transparency
+ */
+export interface SamplingMetadata {
+ isSampled: boolean;
+ samplingMethod: "none" | "hash" | "limit";
+ samplingRate: number; // 0-1 (e.g., 0.1 = 10% sample)
+ estimatedTotalMatches: number;
+ actualSampleSize: number;
+ samplingExpression: string | null; // e.g., "cityHash64(...) % 100 < 10"
+ // Preflight query estimates (used for adaptive FINAL optimization)
+ preflightEstimates?: {
+ score1Count: number;
+ score2Count: number;
+ estimatedMatchedCount: number;
+ };
+ // Adaptive FINAL optimization decision
+ adaptiveFinal?: {
+ usedFinal: boolean;
+ reason: string;
+ };
+}
+
/**
* Complete transformed score analytics data
*/
@@ -144,6 +167,7 @@ export interface ScoreAnalyticsData {
isSameScore: boolean;
dataType: DataType;
};
+ samplingMetadata: SamplingMetadata;
}
/**
@@ -172,6 +196,7 @@ export interface UseScoreAnalyticsQueryResult {
*/
export function useScoreAnalyticsQuery(
params: ScoreAnalyticsQueryParams,
+ options?: { enabled?: boolean },
): UseScoreAnalyticsQueryResult {
const {
projectId,
@@ -200,7 +225,8 @@ export function useScoreAnalyticsQuery(
objectType,
},
{
- enabled: !!(projectId && score1),
+ enabled: (options?.enabled ?? true) && !!(projectId && score1),
+ trpc: { abortOnUnmount: true },
},
);
@@ -614,6 +640,7 @@ export function useScoreAnalyticsQuery(
isSameScore,
dataType,
},
+ samplingMetadata: apiData.samplingMetadata,
};
}, [apiData, score1, score2, fromTimestamp, toTimestamp, interval, nBins]);
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index b8f26082ce..5daf02a044 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -83,6 +83,135 @@ type AllScoresReturnType = Omit<ScoreDomain, "metadata"> & {
executionTraceId: string | null;
};
+/**
+ * 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*
@@ -779,6 +908,98 @@ export const scoresRouter = createTRPCRouter({
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"),
+ }),
+ )
+ .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,
+ };
+ }),
+
/**
* Get comprehensive score comparison analytics using single UNION ALL query
* Returns counts, heatmap, confusion matrix, statistics, time series, and distributions
@@ -847,7 +1068,6 @@ export const scoresRouter = createTRPCRouter({
)
.default({ count: 1, unit: "day" }),
nBins: z.number().int().min(5).max(50).default(10),
- maxMatchedScoresLimit: z.number().int().default(100000),
objectType: z
.enum(["all", "trace", "session", "observation", "dataset_run"])
.default("all"),
@@ -862,7 +1082,6 @@ export const scoresRouter = createTRPCRouter({
toTimestamp,
interval,
nBins,
- maxMatchedScoresLimit,
objectType,
} = input;
@@ -903,15 +1122,58 @@ export const scoresRouter = createTRPCRouter({
objectType === "all"
? ""
: objectType === "trace"
- ? "AND trace_id IS NOT NULL AND observation_id IS NULL AND session_id IS NULL AND run_id IS NULL"
+ ? "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 run_id IS NULL"
+ ? "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 run_id IS NOT NULL"
+ ? "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;
@@ -1224,60 +1486,91 @@ export const scoresRouter = createTRPCRouter({
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 FINAL
- WHERE project_id = {projectId: String}
+ FROM scores ${shouldUseFinal ? "FINAL" : ""}
+ PREWHERE project_id = {projectId: String}
AND name = {score1Name: String}
- AND source = {score1Source: 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 (
- SELECT
- id, value, string_value,
- trace_id, observation_id, session_id, dataset_run_id as run_id,
- timestamp
- FROM scores FINAL
- WHERE project_id = {projectId: String}
- AND name = {score2Name: String}
- AND source = {score2Source: String}
- AND data_type = {dataType2: String}
- AND timestamp >= {fromTimestamp: DateTime64(3)}
- AND timestamp <= {toTimestamp: DateTime64(3)}
- AND is_deleted = 0
- ${objectTypeFilter}
+ ${
+ 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,
- s2.value as value2,
- s2.string_value as string_value2,
+ ${isIdenticalScores ? "s1.value" : "s2.value"} as value2,
+ ${isIdenticalScores ? "s1.string_value" : "s2.string_value"} as string_value2,
s1.timestamp as timestamp1,
- s2.timestamp as timestamp2,
- coalesce(s1.trace_id, s2.trace_id) as trace_id,
- coalesce(s1.observation_id, s2.observation_id) as observation_id,
- coalesce(s1.session_id, s2.session_id) as session_id,
- coalesce(s1.run_id, s2.run_id) as run_id
+ ${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 score2_filtered s2
- ON ifNull(s1.trace_id, '') = ifNull(s2.trace_id, '')
+ 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 {maxMatchedScoresLimit: UInt32}
+ 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)
@@ -1336,7 +1629,7 @@ export const scoresRouter = createTRPCRouter({
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 {maxMatchedScoresLimit: UInt32}
+ LIMIT 1000000 -- Safety limit for categorical LEFT JOIN (more prone to expansion than INNER JOIN)
),
-- CTE 6b: Stacked distribution (score1 categories with score2 breakdowns)
@@ -1463,7 +1756,7 @@ export const scoresRouter = createTRPCRouter({
'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 count() FROM matched_scores) AS Float64) as col3,
+ 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,
@@ -1832,7 +2125,6 @@ export const scoresRouter = createTRPCRouter({
fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp),
toTimestamp: convertDateToClickhouseDateTime(toTimestamp),
nBins,
- maxMatchedScoresLimit,
},
tags: {
feature: "scores",
@@ -2010,6 +2302,28 @@ export const scoresRouter = createTRPCRouter({
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",
+ },
+ },
};
}),
});