: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): page and filter evaluation runs past the newest 250 (#111999)
posthog[bot]9f4832c0089f
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex 66198f9c39c4..d9127bfa7721 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -49,12 +49,7 @@ import { EvaluationReportsTab } from './components/EvaluationReportsTab'import { EvaluationRunsTable } from './components/EvaluationRunsTable'import { EvaluationTriggers } from './components/EvaluationTriggers'import { NumericEvaluationConfig } from './components/NumericEvaluationConfig'-import {- EVALUATION_RUNS_QUERY_LIMIT,- formatNumericEvaluationScore,- numericOutputConfigError,- categoricalOutputConfigError,-} from './constants'+import { formatNumericEvaluationScore, numericOutputConfigError, categoricalOutputConfigError } from './constants'import {evaluationOffersSessionTarget,evaluationSupportsReportHistory,@@ -373,12 +368,6 @@ export function AIObservabilityEvaluation(): JSX.Element {<div className="min-w-0"><p className="text-muted text-sm m-0">History of when this evaluation has been executed.- {runsSummary && runsSummary.total > EVALUATION_RUNS_QUERY_LIMIT && (- <>- {' '}- The table below shows the latest {EVALUATION_RUNS_QUERY_LIMIT} runs.- </>- )}</p>{isReportableEvaluation && (diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsxindex 6c5bf1f5b6fd..73711c8e3668 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx@@ -2,13 +2,16 @@ import '@testing-library/jest-dom'import { cleanup, render, screen } from '@testing-library/react'import { BindLogic, Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { getEvaluationResultDisplay } from '../../components/EvaluationResultTag'import { llmEvaluationLogic } from '../llmEvaluationLogic'-import { EvaluationRun } from '../types'+import { EvaluationConfig, EvaluationRun } from '../types'import { EvaluationRunsTable } from './EvaluationRunsTable'const props = { evaluationId: 'eval-123' }@@ -74,6 +77,7 @@ describe('EvaluationRunsTable', () => {})afterEach(() => {+ jest.restoreAllMocks()cleanup()logic?.unmount()})@@ -99,9 +103,15 @@ describe('EvaluationRunsTable', () => {expect(screen.getByText('Good')).toBeInTheDocument()})- it('says a filter is hiding rows when the evaluation has runs but none match', () => {- logic.actions.loadEvaluationRunsSuccess([passingRun])+ it('says a filter is hiding rows when the evaluation has runs but none match', async () => {+ jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.loadEvaluationSuccess({+ output_type: 'boolean',+ output_config: { allows_na: false },+ } as EvaluationConfig)logic.actions.setEvaluationRunsFilter('fail', 'all')+ await expectLogic(logic).toFinishAllListeners()renderTable()expect(screen.getByText('No runs match this filter')).toBeInTheDocument()diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsxindex c39aab70bc86..00025325db83 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx@@ -10,10 +10,10 @@ import { EvaluationExplanation } from '../../components/EvaluationExplanation'import { EvaluationResultTag, compareEvaluationResults } from '../../components/EvaluationResultTag'import { EvaluationRunTargetCell } from '../../components/EvaluationRunTargetCell'import { EvaluationRunTimestampCell } from '../../components/EvaluationRunTimestampCell'-import { evaluationIsDetector } from '../constants'+import { EVALUATION_RUNS_QUERY_LIMIT, evaluationIsDetector } from '../constants'import { evaluationSupportsRunOutcomes } from '../evaluationCapabilities'import { llmEvaluationLogic } from '../llmEvaluationLogic'-import { EvaluationRun, SentimentEvaluationRunsFilter } from '../types'+import { EvaluationRun, EvaluationRunsFilter, SentimentEvaluationRunsFilter } from '../types'import { EvaluationRunsFilters } from './EvaluationRunsFilters'const SENTIMENT_FILTER_OPTIONS: { value: SentimentEvaluationRunsFilter; label: string }[] = [@@ -49,8 +49,11 @@ export function EvaluationRunsTable(): JSX.Element {evaluationRunsLoading,runsDateRange,runsBackfillId,+ evaluationRunsHasMore,+ evaluationRunsFilter,+ runsSummary,} = useValues(llmEvaluationLogic)- const { refreshEvaluationRuns, setRunsDates } = useActions(llmEvaluationLogic)+ const { refreshEvaluationRuns, setRunsDates, loadOlderEvaluationRuns } = useActions(llmEvaluationLogic)const showOutcomeFilters =evaluation?.output_type === 'numeric' ||evaluation?.output_type === 'categorical' ||@@ -59,8 +62,13 @@ export function EvaluationRunsTable(): JSX.Element {// Every run in this table belongs to `evaluation`, so its polarity applies to the whole column.const trueIsFailure = !!evaluation && evaluationIsDetector(evaluation)+ // Pass and fail counts come from the stats query, so the total matches the header over the whole range.+ const filterTotals: Partial<Record<EvaluationRunsFilter, number>> = runsSummary+ ? { all: runsSummary.total, pass: runsSummary.successful, fail: runsSummary.failed }+ : {}+ const matchingRunsTotal = filterTotals[evaluationRunsFilter]// A filter is hiding rows when the evaluation has runs but none match the current filter.- const filterHidesRuns = evaluationRuns.length > 0 && filteredEvaluationRuns.length === 0+ const filterHidesRuns = evaluationRunsFilter !== 'all' && filteredEvaluationRuns.length === 0// LemonTable drops its empty state as soon as it has rows, so a failed refresh over rows that// are already on screen needs its own surface. Without it the spinner just stops and the user// reads the stale rows as current.@@ -160,16 +168,41 @@ export function EvaluationRunsTable(): JSX.Element {<SentimentEvaluationRunsFilters />) : null}</div>- <LemonButton- type="secondary"- icon={<IconRefresh />}- onClick={refreshEvaluationRuns}- loading={evaluationRunsLoading}- size="small"- data-attr="llma-evaluation-refresh-runs"- >- Refresh- </LemonButton>+ <div className="flex flex-wrap items-center gap-2">+ {(evaluationRunsHasMore || evaluationRuns.length > EVALUATION_RUNS_QUERY_LIMIT) &&+ !evaluationRunsError && (+ <>+ <span className="text-muted text-sm">+ {!evaluationRunsHasMore+ ? `Showing all ${evaluationRuns.length.toLocaleString()} runs.`+ : matchingRunsTotal && matchingRunsTotal > evaluationRuns.length+ ? `Showing the latest ${evaluationRuns.length.toLocaleString()} of ${matchingRunsTotal.toLocaleString()} runs.`+ : `Showing the latest ${evaluationRuns.length.toLocaleString()} runs.`}+ </span>+ {evaluationRunsHasMore && (+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => loadOlderEvaluationRuns()}+ loading={evaluationRunsLoading}+ data-attr="llma-evaluation-runs-load-older"+ >+ Load older runs+ </LemonButton>+ )}+ </>+ )}+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ onClick={refreshEvaluationRuns}+ loading={evaluationRunsLoading}+ size="small"+ data-attr="llma-evaluation-refresh-runs"+ >+ Refresh+ </LemonButton>+ </div></div>{showStaleRunsBanner && (diff --git a/products/ai_observability/frontend/evaluations/constants.ts b/products/ai_observability/frontend/evaluations/constants.tsindex ce665c88d0aa..d82b11511241 100644--- a/products/ai_observability/frontend/evaluations/constants.ts+++ b/products/ai_observability/frontend/evaluations/constants.ts@@ -1,6 +1,6 @@import { escapeHogQLString } from '~/queries/utils'-import type { EvaluationConfig, EvaluationOutputConfig } from './types'+import type { EvaluationConfig, EvaluationOutputConfig, EvaluationRunsFilter } from './types'// Most-recent runs fetched for an evaluation's runs table and its result badgesexport const EVALUATION_RUNS_QUERY_LIMIT = 250@@ -136,6 +136,38 @@ export function categoricalEvaluationPassedHogQL(evaluation: Pick<EvaluationConfreturn `notEmpty(${EVALUATION_CATEGORIES_HOGQL}) AND hasAll([${categories}], ${EVALUATION_CATEGORIES_HOGQL})`}+// The table pages through the newest runs, so the filter runs in the query to reach every match in the range.+// Keep it in step with filterEvaluationRuns in llmEvaluationLogic.ts.+export function evaluationRunsFilterHogQL(+ filter: EvaluationRunsFilter,+ evaluation: Pick<EvaluationConfig, 'output_type' | 'output_config'> | null+): string | null {+ if (filter === 'all') {+ return null+ }+ if (filter === 'negative' || filter === 'positive' || filter === 'neutral') {+ return `lower(properties.$ai_sentiment_label) = '${filter}'`+ }+ if (evaluation?.output_type === 'numeric' || evaluation?.output_type === 'categorical') {+ if (filter === 'na') {+ return `properties.$ai_evaluation_applicable = 'false' AND ${EVALUATION_NOT_SKIPPED_HOGQL}`+ }+ if (!evaluation.output_config.passing_rule) {+ return 'false'+ }+ const [graded, passed] =+ evaluation.output_type === 'numeric'+ ? [EVALUATION_NUMERIC_GRADED_HOGQL, numericEvaluationPassedHogQL(evaluation)]+ : [EVALUATION_CATEGORICAL_GRADED_HOGQL, categoricalEvaluationPassedHogQL(evaluation)]+ return `${graded} AND ${filter === 'pass' ? '' : 'NOT '}(${passed})`+ }+ if (filter === 'na') {+ return `properties.$ai_evaluation_result IS NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}`+ }+ const passed = evaluation ? evaluationPassedHogQL(evaluation) : EVALUATION_RESULT_TRUE_HOGQL+ return `${EVALUATION_BOOLEAN_GRADED_HOGQL} AND ${filter === 'pass' ? '' : 'NOT '}(${passed})`+}+export const MAX_CATEGORICAL_OPTIONS = 100export function categoricalOptionsError(config: EvaluationOutputConfig): string | null {diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex b34060e17310..d7eca15b684e 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -1,6 +1,7 @@import { combineUrl, router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { urls } from 'scenes/urls'@@ -12,7 +13,7 @@ import { ActivityScope } from '~/types'import type { TestHogResponseApi } from '../generated/api.schemas'import { modelPickerLogic } from '../modelPickerLogic'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'-import { numericScorePasses } from './constants'+import { EVALUATION_RUNS_QUERY_LIMIT, numericScorePasses } from './constants'import { evaluationReportLogic } from './evaluationReportLogic'import { DEFAULT_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'import { llmEvaluationsLogic } from './llmEvaluationsLogic'@@ -1268,6 +1269,75 @@ return result`,})})})++ describe('loadOlderEvaluationRuns', () => {+ const runRow = (id: string, timestamp: string): unknown[] => {+ const row: unknown[] = new Array(22).fill(null)+ row[0] = id+ row[1] = timestamp+ row[2] = 'eval-123'+ return row+ }++ it('pages past the first runs with a timestamp cursor and appends the older runs', async () => {+ const newest = Array.from({ length: EVALUATION_RUNS_QUERY_LIMIT }, (_, i) =>+ runRow(+ `new-${i}`,+ i < EVALUATION_RUNS_QUERY_LIMIT - 2 ? '2024-01-02T00:00:00Z' : '2024-01-01T00:00:00Z'+ )+ )+ const queryHogQL = jest.spyOn(api, 'queryHogQL').mockImplementation(async (query) => {+ if (query.includes('count() as total')) {+ return { results: [[EVALUATION_RUNS_QUERY_LIMIT + 1]] } as any+ }+ return {+ results: query.includes('uuid NOT IN') ? [runRow('old-1', '2023-12-31T00:00:00Z')] : newest,+ } as any+ })++ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadEvaluationRunsSuccess']).toMatchValues({+ evaluationRunsHasMore: true,+ })++ logic.actions.loadOlderEvaluationRuns()+ await expectLogic(logic).toDispatchActions(['loadOlderEvaluationRunsSuccess']).toMatchValues({+ evaluationRunsHasMore: false,+ })++ expect(logic.values.evaluationRuns.map((run) => run.id).slice(-3)).toEqual([+ `new-${EVALUATION_RUNS_QUERY_LIMIT - 2}`,+ `new-${EVALUATION_RUNS_QUERY_LIMIT - 1}`,+ 'old-1',+ ])+ const olderQuery = queryHogQL.mock.calls.find(([query]) => String(query).includes('uuid NOT IN'))+ expect(olderQuery?.[0]).toContain(+ `AND timestamp <= toDateTime('2024-01-01T00:00:00Z') AND uuid NOT IN ['new-${EVALUATION_RUNS_QUERY_LIMIT - 2}', 'new-${EVALUATION_RUNS_QUERY_LIMIT - 1}']`+ )+ queryHogQL.mockRestore()+ })++ it('reloads runs with the filter in the query, so failures past the newest page are reachable', async () => {+ const queryHogQL = jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)+ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })+ logic.mount()+ logic.actions.loadEvaluationSuccess({+ ...mockEvaluation,+ output_config: { allows_na: false, true_is_failure: true },+ })+ queryHogQL.mockClear()++ logic.actions.setEvaluationRunsFilter('fail', 'all')+ await expectLogic(logic).toDispatchActions(['loadEvaluationRunsSuccess'])++ const runsQuery = queryHogQL.mock.calls.find(([query]) =>+ String(query).includes('ORDER BY timestamp DESC')+ )+ expect(runsQuery?.[0]).toContain(`NOT (properties.$ai_evaluation_result = 'false')`)+ queryHogQL.mockRestore()+ })+ })})describe('runs filtering', () => {diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex 9a87aeb6ab95..fb0717145b77 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -42,6 +42,8 @@ import {categoricalOutputConfigError,categoricalEvaluationPassedHogQL,EVALUATION_CATEGORICAL_GRADED_HOGQL,+ EVALUATION_RUNS_QUERY_LIMIT,+ evaluationRunsFilterHogQL,} from './constants'import {evaluationCanResolveModel,@@ -315,6 +317,7 @@ export interface llmEvaluationLogicValues {evaluationRuns: EvaluationRun[]evaluationRunsError: booleanevaluationRunsFilter: EvaluationRunsFilter+ evaluationRunsHasMore: booleanevaluationRunsLoading: booleanfilteredEvaluationRuns: EvaluationRun[]formValid: boolean@@ -386,6 +389,21 @@ export interface llmEvaluationLogicActions {evaluation: EvaluationConfig | nullrequestedTab: string | null}+ loadOlderEvaluationRuns: () => any+ loadOlderEvaluationRunsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOlderEvaluationRunsSuccess: (+ evaluationRuns: EvaluationRun[],+ payload?: any+ ) => {+ evaluationRuns: EvaluationRun[]+ payload?: any+ }loadRunsBackfill: () => anyloadRunsBackfillFailure: (error: string,@@ -469,6 +487,9 @@ export interface llmEvaluationLogicActions {filter: EvaluationRunsFilterpreviousFilter: EvaluationRunsFilter}+ setEvaluationRunsHasMore: (hasMore: boolean) => {+ hasMore: boolean+ }setEvaluationTarget: (target: EvaluationTarget) => {target: EvaluationTarget}@@ -657,6 +678,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([// Evaluation runs actionsrefreshEvaluationRuns: true,+ setEvaluationRunsHasMore: (hasMore: boolean) => ({ hasMore }),// Model selection actionsselectModelFromPicker: (modelId: string, providerKeyId: string) => ({ modelId, providerKeyId }),@@ -748,11 +770,44 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([evaluationId: props.evaluationId,backfillId: values.runsBackfillId ?? undefined,dateRange: values.runsBackfillId ? undefined : values.runsDateRange,+ filterHogQL: evaluationRunsFilterHogQL(values.evaluationRunsFilter, values.originalEvaluation),forceRefresh: values.isForceRefresh,})breakpoint?.()+ actions.setEvaluationRunsHasMore(runs.length >= EVALUATION_RUNS_QUERY_LIMIT)return runs},+ loadOlderEvaluationRuns: async () => {+ const { evaluationRuns: loadedRuns, runsDateRange, runsBackfillId, evaluationRunsFilter } = values+ const oldestTimestamp = loadedRuns[loadedRuns.length - 1]?.timestamp+ if (!oldestTimestamp || !props.evaluationId || props.evaluationId === 'new') {+ return loadedRuns+ }++ const olderRuns = await queryEvaluationRuns({+ evaluationId: props.evaluationId,+ backfillId: runsBackfillId ?? undefined,+ dateRange: runsBackfillId ? undefined : runsDateRange,+ filterHogQL: evaluationRunsFilterHogQL(evaluationRunsFilter, values.originalEvaluation),+ before: {+ timestamp: oldestTimestamp,+ excludeIds: loadedRuns+ .filter((run) => run.timestamp === oldestTimestamp)+ .map((run) => run.id),+ },+ })+ // The selection can change, or a reload can finish, while this page loads. Do not append to rows of a different query.+ if (+ values.evaluationRuns !== loadedRuns ||+ values.runsDateRange !== runsDateRange ||+ values.runsBackfillId !== runsBackfillId ||+ values.evaluationRunsFilter !== evaluationRunsFilter+ ) {+ return values.evaluationRuns+ }+ actions.setEvaluationRunsHasMore(olderRuns.length >= EVALUATION_RUNS_QUERY_LIMIT)+ return [...loadedRuns, ...olderRuns]+ },},],runsBackfill: [@@ -1054,6 +1109,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([resetEvaluation: () => false,},],+ evaluationRunsHasMore: [+ false,+ {+ setEvaluationRunsHasMore: (_, { hasMore }) => hasMore,+ },+ ],evaluationRunsFilter: ['all' as EvaluationRunsFilter,{@@ -1108,6 +1169,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([},loadEvaluationSuccess: () => {actions.loadRunsStats()+ // The filter query reads the evaluation's pass rules, and a sentiment evaluation opens on a non-'all' filter.+ if (values.evaluationRunsFilter !== 'all') {+ actions.loadEvaluationRuns()+ }},loadEvaluationConfigSuccess: () => {// The new-eval draft's enabled default is read before the team's evaluation config has@@ -1209,6 +1274,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([},setEvaluationRunsFilter: ({ filter, previousFilter }) => {+ actions.loadEvaluationRuns()// pinned: analytics event name - renaming it breaks existing dashboardsposthog.capture('llma evaluation summary filter changed', {filter,diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.tsindex 3da84ad4dc19..8946a6761475 100644--- a/products/ai_observability/frontend/utils.ts+++ b/products/ai_observability/frontend/utils.ts@@ -1316,9 +1316,14 @@ export async function queryEvaluationRuns(params: {/** Bounds the scan so it can prune partitions. Omitted for the trace and generation surfaces,* which read a single unit's runs and have always been unbounded. */lookbackDays?: number+ /** Reads the page of runs older than `timestamp`. Runs at exactly `timestamp` are kept unless+ * their id is in `excludeIds`, so runs that share a timestamp across a page edge are not skipped. */+ before?: { timestamp: string; excludeIds: string[] }+ filterHogQL?: string | nullforceRefresh?: boolean}): Promise<EvaluationRun[]> {- const { evaluationId, traceId, sessionId, backfillId, dateRange, lookbackDays, forceRefresh } = params+ const { evaluationId, traceId, sessionId, backfillId, dateRange, lookbackDays, before, filterHogQL, forceRefresh } =+ paramsconst propertyValue = evaluationId || traceId || sessionId@@ -1362,6 +1367,8 @@ export async function queryEvaluationRuns(params: {${backfillId ? hogql.raw(`AND properties.$ai_evaluation_backfill_id = ${escapeHogQLString(backfillId)}`) : hogql.raw('')}${lookbackDays ? hogql.raw(`AND timestamp >= now() - INTERVAL ${Math.floor(lookbackDays)} DAY`) : hogql.raw('')}${dateRange ? hogql.raw('AND {filters}') : hogql.raw('')}+ ${before ? hogql.raw(hogql`AND timestamp <= toDateTime(${before.timestamp}) AND uuid NOT IN ${before.excludeIds}`) : hogql.raw('')}+ ${filterHogQL ? hogql.raw(`AND (${filterHogQL})`) : hogql.raw('')}ORDER BY timestamp DESCLIMIT ${EVALUATION_RUNS_QUERY_LIMIT}`