Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(aio): reduce evaluation metrics query scans (#78920)

Radu Raicea92790a6efa98
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
index 74d94326e196..d5f84535961d 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
@@ -47,22 +47,16 @@ function SummaryCard({
export function EvaluationMetrics(): JSX.Element {
const { summaryMetrics, statsLoading, chartQuery } = useValues(evaluationMetricsLogic)
- const { evaluations } = useValues(llmEvaluationsLogic)
+ const { evaluations, evaluationsLoading } = useValues(llmEvaluationsLogic)
const enabledEvaluationsCount = evaluations.filter((e) => e.enabled && !e.deleted).length
- if (statsLoading) {
- return (
- <div className="space-y-4 mb-6">
- <LemonSkeleton className="h-96 w-full" />
- </div>
- )
- }
-
return (
<div className="mb-6">
<div className="flex gap-4 h-96">
- {chartQuery ? (
+ {evaluationsLoading ? (
+ <LemonSkeleton className="flex-1 h-full" />
+ ) : chartQuery ? (
<div className="flex-1 bg-bg-light rounded p-4 flex flex-col InsightCard h-full">
<h3 className="text-lg font-semibold mb-2">Pass rate over time</h3>
<p className="text-muted text-sm mb-4">Showing pass rate trends for enabled evaluations</p>
@@ -89,31 +83,40 @@ export function EvaluationMetrics(): JSX.Element {
</div>
)}
- {/* Summary cards on the right in 2x2 grid */}
<div className="flex-1 grid grid-cols-2 gap-4">
- <SummaryCard
- title="Enabled evaluations"
- value={enabledEvaluationsCount}
- subtitle={`${evaluations.length} total`}
- />
- <SummaryCard
- title="Runs"
- value={summaryMetrics.total_runs}
- subtitle={summaryMetrics.total_runs === 0 ? 'No activity' : undefined}
- />
- <SummaryCard
- title="Pass rate"
- value={summaryMetrics.total_runs === 0 ? 'N/A' : `${summaryMetrics.overall_pass_rate}%`}
- colorClass={
- summaryMetrics.total_runs > 0 ? getPassRateColor(summaryMetrics.overall_pass_rate) : ''
- }
- />
- <SummaryCard
- title="Failing evaluations"
- value={summaryMetrics.failing_evaluations_count}
- subtitle="< 70% pass rate"
- colorClass={summaryMetrics.failing_evaluations_count > 0 ? 'text-danger' : 'text-success'}
- />
+ {statsLoading ? (
+ Array.from({ length: 4 }, (_, index) => <LemonSkeleton key={index} className="h-full w-full" />)
+ ) : (
+ <>
+ <SummaryCard
+ title="Enabled evaluations"
+ value={enabledEvaluationsCount}
+ subtitle={`${evaluations.length} total`}
+ />
+ <SummaryCard
+ title="Runs"
+ value={summaryMetrics.total_runs}
+ subtitle={summaryMetrics.total_runs === 0 ? 'No activity' : undefined}
+ />
+ <SummaryCard
+ title="Pass rate"
+ value={summaryMetrics.total_runs === 0 ? 'N/A' : `${summaryMetrics.overall_pass_rate}%`}
+ colorClass={
+ summaryMetrics.total_runs > 0
+ ? getPassRateColor(summaryMetrics.overall_pass_rate)
+ : ''
+ }
+ />
+ <SummaryCard
+ title="Failing evaluations"
+ value={summaryMetrics.failing_evaluations_count}
+ subtitle="< 70% pass rate"
+ colorClass={
+ summaryMetrics.failing_evaluations_count > 0 ? 'text-danger' : 'text-success'
+ }
+ />
+ </>
+ )}
</div>
</div>
</div>
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
index 8201136fe491..5531dfb78f7f 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
@@ -23,9 +23,9 @@ jest.mock('lib/api', () => {
}
})
-const evaluation = (id: string, directoryId: string | null): LLMJudgeEvaluation => ({
+const evaluation = (id: string, directoryId: string | null, name = `Evaluation ${id}`): LLMJudgeEvaluation => ({
id,
- name: `Evaluation ${id}`,
+ name,
description: '',
directory_id: directoryId,
enabled: true,
@@ -85,17 +85,36 @@ describe('evaluationMetricsLogic', () => {
evaluationsLogic.unmount()
})
- it('scopes the graph and summary metrics when a directory is selected', () => {
- const rootEvaluation = evaluation('root', null)
+ it('uses one filtered breakdown query and scopes metrics to the selected directory', () => {
+ const firstRootEvaluation = evaluation('root-one', null, "Root's evaluation")
+ const secondRootEvaluation = evaluation('root-two', null, "Root's evaluation")
const directoryEvaluation = evaluation('inside', 'directory-a')
- evaluationsLogic.actions.loadEvaluationsSuccess([rootEvaluation, directoryEvaluation])
- metricsLogic.actions.loadStatsSuccess([stats(rootEvaluation.id, 4), stats(directoryEvaluation.id, 2)])
+ evaluationsLogic.actions.loadEvaluationsSuccess([
+ firstRootEvaluation,
+ secondRootEvaluation,
+ directoryEvaluation,
+ ])
+ metricsLogic.actions.loadStatsSuccess([
+ stats(firstRootEvaluation.id, 4),
+ stats(secondRootEvaluation.id, 3),
+ stats(directoryEvaluation.id, 2),
+ ])
expect(metricsLogic.values.chartQuery?.series).toEqual([
- expect.objectContaining({ custom_name: rootEvaluation.name }),
+ expect.objectContaining({
+ properties: [expect.objectContaining({ value: [firstRootEvaluation.id, secondRootEvaluation.id] })],
+ }),
])
- expect(metricsLogic.values.summaryMetrics.total_runs).toBe(4)
+ expect(metricsLogic.values.chartQuery?.breakdownFilter).toEqual(
+ expect.objectContaining({
+ breakdown_type: 'hogql',
+ breakdown_hide_other_aggregation: true,
+ })
+ )
+ expect(metricsLogic.values.chartQuery?.breakdownFilter?.breakdown).toContain("'Root\\'s evaluation (1)'")
+ expect(metricsLogic.values.chartQuery?.breakdownFilter?.breakdown).toContain("'Root\\'s evaluation (2)'")
+ expect(metricsLogic.values.summaryMetrics.total_runs).toBe(7)
router.actions.push(
combineUrl(urls.aiObservabilityEvaluations(), {
@@ -104,8 +123,12 @@ describe('evaluationMetricsLogic', () => {
)
expect(metricsLogic.values.chartQuery?.series).toEqual([
- expect.objectContaining({ custom_name: directoryEvaluation.name }),
+ expect.objectContaining({
+ properties: [expect.objectContaining({ value: [directoryEvaluation.id] })],
+ }),
])
+ expect(metricsLogic.values.chartQuery?.breakdownFilter?.breakdown).toContain(directoryEvaluation.name)
+ expect(metricsLogic.values.chartQuery?.breakdownFilter?.breakdown).not.toContain(firstRootEvaluation.id)
expect(metricsLogic.values.summaryMetrics.total_runs).toBe(2)
})
})
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
index 1b2ad208420f..6028ad568f0f 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
@@ -5,7 +5,8 @@ import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { HogQLQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
-import { ChartDisplayType, HogQLMathType } from '~/types'
+import { escapeHogQLString } from '~/queries/utils'
+import { ChartDisplayType, HogQLMathType, PropertyFilterType, PropertyOperator } from '~/types'
// eslint-disable-next-line import/no-cycle
import { PASS_RATE_SUCCESS_THRESHOLD } from './components/EvaluationMetrics'
@@ -14,6 +15,7 @@ import { llmEvaluationsLogic } from './llmEvaluationsLogic'
import { EvaluationConfig } from './types'
const MIN_RUNS_FOR_FAILING_STATUS = 3
+const MAX_EVALUATION_CHART_SERIES = 10
export interface EvaluationStats {
evaluation_id: string
@@ -59,6 +61,26 @@ function getIntervalFromDateRange(dateFrom: string | null): 'hour' | 'day' {
return duration.asDays() <= 1 ? 'hour' : 'day'
}
+function buildEvaluationBreakdownExpression(evaluations: EvaluationConfig[]): string {
+ const evaluationNameCounts = new Map<string, number>()
+ const evaluationNameIndexes = new Map<string, number>()
+
+ for (const evaluation of evaluations) {
+ evaluationNameCounts.set(evaluation.name, (evaluationNameCounts.get(evaluation.name) ?? 0) + 1)
+ }
+
+ const conditionsAndLabels = evaluations.flatMap((evaluation) => {
+ const nameIndex = (evaluationNameIndexes.get(evaluation.name) ?? 0) + 1
+ evaluationNameIndexes.set(evaluation.name, nameIndex)
+ const label =
+ evaluationNameCounts.get(evaluation.name) === 1 ? evaluation.name : `${evaluation.name} (${nameIndex})`
+
+ return [`properties.$ai_evaluation_id = ${escapeHogQLString(evaluation.id)}`, escapeHogQLString(label)]
+ })
+
+ return `multiIf(${conditionsAndLabels.join(', ')}, toString(properties.$ai_evaluation_id))`
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface evaluationMetricsLogicValues {
dateFilter: {
@@ -279,7 +301,9 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
evaluationsForMetrics: EvaluationConfig[],
dateFilter: { dateFrom: string | null; dateTo: string | null }
): TrendsQuery | null => {
- const enabledEvaluations = evaluationsForMetrics.filter((e) => e.enabled && !e.deleted)
+ const enabledEvaluations = evaluationsForMetrics
+ .filter((evaluation) => evaluation.enabled && !evaluation.deleted)
+ .slice(0, MAX_EVALUATION_CHART_SERIES)
if (enabledEvaluations.length === 0) {
return null
@@ -291,14 +315,29 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
return {
kind: NodeKind.TrendsQuery,
- series: enabledEvaluations.slice(0, 10).map((evaluation) => ({
- kind: NodeKind.EventsNode,
- event: '$ai_evaluation',
- custom_name: evaluation.name,
- math: HogQLMathType.HogQL,
- // Pass rate excludes N/A results, returns 0 if all results are N/A
- math_hogql: `if(countIf(properties.$ai_evaluation_id = '${evaluation.id}' AND properties.$ai_evaluation_result IS NOT NULL) > 0, countIf(properties.$ai_evaluation_id = '${evaluation.id}' AND ${EVALUATION_PASSED_HOGQL}) / countIf(properties.$ai_evaluation_id = '${evaluation.id}' AND properties.$ai_evaluation_result IS NOT NULL) * 100, 0)`,
- })),
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: '$ai_evaluation',
+ math: HogQLMathType.HogQL,
+ // Pass rate excludes N/A results, returns 0 if all results are N/A
+ math_hogql: `if(countIf(properties.$ai_evaluation_result IS NOT NULL) > 0, countIf(${EVALUATION_PASSED_HOGQL}) / countIf(properties.$ai_evaluation_result IS NOT NULL) * 100, 0)`,
+ properties: [
+ {
+ key: '$ai_evaluation_id',
+ value: enabledEvaluations.map((evaluation) => evaluation.id),
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ },
+ ],
+ breakdownFilter: {
+ breakdown: buildEvaluationBreakdownExpression(enabledEvaluations),
+ breakdown_type: 'hogql',
+ breakdown_limit: MAX_EVALUATION_CHART_SERIES,
+ breakdown_hide_other_aggregation: true,
+ },
trendsFilter: {
display: ChartDisplayType.ActionsLineGraph,
},