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.

feat(autoresearch): show predicted vs actual and realized AUC on accuracy (#113158)

posthog[bot]20cebce7614d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c6775017c710..d12ded99ef89 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6504,6 +6504,14 @@ snapshots:
hash: v1.k794b7964.ec5636bb061b046741a42c6ce3faa30704b2b4203947e956c5d7966bada33fd5.pMIwCFfVjMdfrr_RckXkoewH1hbCy3Veditgtv4hx_k
products-autoresearch-lifecycle-strip--validated-champion--light:
hash: v1.k794b7964.131ecc736b38defef5b8ba34fa9836f1d2d5132e1d109e4b995b9591a5d9255c.759giT71A_8sdMCqx-FasPgdZzZWHgRvaoUmqVtYYKw
+ products-autoresearch-model-detail-scene--accuracy--narrow--dark:
+ hash: v1.k794b7964.474afbbef6390672bb4e56fbf5933057946c075c3b0817c3df920ebf4efa6cae.iitmJl1nGiexyocfoVJBleO0jsVpBHPfz9CRRvPwzqo
+ products-autoresearch-model-detail-scene--accuracy--narrow--light:
+ hash: v1.k794b7964.9fdda8cd699a6d2ae9e0c829ee5d4ad380d1ec5664e7793a27ccb85cb4f8416d.B3rYoEpl0eGNDcqdDlGNihDNe30T8Nea9nf0do0Yv_o
+ products-autoresearch-model-detail-scene--accuracy--wide--dark:
+ hash: v1.k794b7964.e3e30f0395d8b2531174b4d415fb3ba3789d69d4227eeb31fff97ef7a92fd2c1.JgJ0I_wqdXSubRfU9kIKLCrx2TNIsCO9c_asb6s0YCY
+ products-autoresearch-model-detail-scene--accuracy--wide--light:
+ hash: v1.k794b7964.9df2881fa8b1ad8ae2965e4daf597ef8d2835fdf73ca1c3343f4ae337afeb4d0.-smEXkxUblLfr2j9NSD9vX2BgFpL1qqyogUb_4wlxaE
products-autoresearch-model-detail-scene--agent-research-narrow--narrow--dark:
hash: v1.k794b7964.052f6d0dba654432d5f12d65bc0f91bc3e2de64334dac07e62d6cf730f154820.7cPMLn00EY67HPH6ikgGBUlULYPQSAMVKLyE_cR3uTs
products-autoresearch-model-detail-scene--agent-research-narrow--narrow--light:
diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.md
index 1a5189781d1d..ebcf77942e13 100644
--- a/products/autoresearch/frontend/AGENTS.md
+++ b/products/autoresearch/frontend/AGENTS.md
@@ -19,6 +19,8 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st
| `autoresearchPipelineLogic.ts` | Detail logic. Also maps the old `?tab=` keys to the four tabs, so saved links still open. |
| `pipelineLifecycle.ts` | The five lifecycle steps (question set to checked against reality) and which one is current. |
| `agentSearch.ts` | The agent's search across training runs: chart points, best score so far, AUC change per experiment, log groups and the latest agent notes. |
+| `onlinePerformance.ts` | Accuracy tab helpers over the `online_performance` endpoint: the headline, the realized AUC series, predicted against actual by segment. |
+| `predictionSegments.ts` | The likelihood segment thresholds (Likely, Possible, Unlikely). The Predictions and Accuracy tabs share them. |
| `PipelineStatusTag.tsx` | Status tag + tooltip shared by the list and detail scenes. |
| `ProbabilityHistogram.tsx` | Decile histogram of the latest scoring run's probabilities. |
| `DailyVolumeChart.tsx` | Bar-per-day chart of scoring volume. |
diff --git a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
index 5d530d0b4487..3d4a7d678054 100644
--- a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
+++ b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
@@ -120,6 +120,39 @@ function iteration(
}
}
+const onlinePerformance = {
+ rows: ['2026-02-10', '2026-02-11', '2026-02-12', '2026-02-13', '2026-02-14']
+ .map((prediction_date, index) => ({
+ validation_run_id: `validate-${index}`,
+ prediction_date,
+ horizon_days: 7,
+ weekday: 1,
+ model_id: champion.id,
+ emitted_role: 'champion',
+ current_role: 'champion',
+ n_scored: 47000,
+ n_positive: 1410,
+ base_rate: 0.03,
+ mean_p_y: 0.033,
+ realized_auc: [0.78, 0.8, 0.79, 0.82, 0.81][index],
+ realized_auc_ci_low: [0.76, 0.78, 0.77, 0.8, 0.79][index],
+ realized_auc_ci_high: [0.8, 0.82, 0.81, 0.84, 0.83][index],
+ brier_score: 0.06,
+ calibration_error: 0.04,
+ lift_at_10: 3.4,
+ lift_at_20: 2.6,
+ calibration_bins: [
+ { n: 37600, mean_p_y: 0.01, positive_rate: 0.008 },
+ { n: 4700, mean_p_y: 0.08, positive_rate: 0.07 },
+ { n: 2350, mean_p_y: 0.3, positive_rate: 0.27 },
+ { n: 2350, mean_p_y: 0.68, positive_rate: 0.6 },
+ ],
+ warning: null,
+ validated_at: '2026-02-21T03:00:00Z',
+ }))
+ .reverse(),
+}
+
const trainingRuns = [
{
id: 'training-3',
@@ -201,6 +234,7 @@ const meta: Meta = {
[`/api/projects/:team_id/autoresearch/${PIPELINE_ID}/training_runs/`]:
toPaginatedResponse(trainingRuns),
[`/api/projects/:team_id/autoresearch/${PIPELINE_ID}/suggestions/`]: toPaginatedResponse([]),
+ [`/api/projects/:team_id/autoresearch/${PIPELINE_ID}/online_performance/`]: onlinePerformance,
},
}),
],
@@ -229,3 +263,10 @@ export const AgentResearchNarrow: Story = {
testOptions: { viewportWidths: ['narrow'] },
},
}
+
+export const Accuracy: Story = {
+ parameters: {
+ pageUrl: `${urls.autoresearchPipeline(PIPELINE_ID)}?tab=accuracy`,
+ testOptions: { viewportWidths: ['wide', 'narrow'] },
+ },
+}
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
index c490ba616a4e..d2871f6a5504 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
@@ -31,6 +31,7 @@ import {
} from './agentSearch'
import {
autoresearchModelsList,
+ autoresearchOnlinePerformanceRetrieve,
autoresearchPauseCreate,
autoresearchResumeCreate,
autoresearchRetrieve,
@@ -53,7 +54,17 @@ import {
type AutoresearchTrainingRunApi,
CreateSuggestionPriorityEnumApi,
type ModelExplanationFieldApi,
+ type OnlinePerformanceRowApi,
} from './generated/api.schemas'
+import {
+ RealizedAucPoint,
+ SegmentCalibration,
+ calibrationBySegment,
+ firstCheckDate,
+ latestChampionRow,
+ realizedAucSeries,
+ validatedPredictionDates,
+} from './onlinePerformance'
import { LifecycleStep, pipelineLifecycle } from './pipelineLifecycle'
import {
PREDICTION_SEGMENTS,
@@ -131,30 +142,6 @@ export interface ProbabilityBucket {
users: number
}
-/** Metrics stored in AutoresearchRun.metrics for validation runs. */
-interface ValidationRunMetrics {
- prediction_date: string
- realized_labels_count?: number
- warning?: string
- per_model?: Record<
- string,
- {
- emitted_role?: string
- model_role: string
- n_scored: number
- n_positive?: number
- n_negative?: number
- base_rate?: number
- realized_auc?: number
- brier_score?: number
- calibration_error?: number
- lift_at_10?: number
- lift_at_20?: number
- warning?: string
- }
- >
-}
-
/** The list endpoints page at 100 rows. Follow every page so a long-lived model shows its whole history. */
async function fetchAllPages<T>(
fetchPage: (offset: number) => Promise<{ results: T[]; next?: string | null }>
@@ -275,22 +262,6 @@ export interface DailyVolumePoint {
avgProbabilityPct: number
}
-/** Flattened row for the online performance table. */
-export interface OnlinePerformanceRow {
- run_id: string
- model_id: string
- prediction_date: string
- /** The role the model held when it emitted these predictions; `model_role` is its role now. */
- emitted_role: string
- model_role: string
- n_scored: number
- realized_auc: number | null
- brier_score: number | null
- calibration_error: number | null
- lift_at_10: number | null
- lift_at_20: number | null
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface autoresearchPipelineLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
@@ -313,14 +284,18 @@ export interface autoresearchPipelineLogicValues {
expandedRunId: string | null
experimentLogFilter: ExperimentLogFilter
experimentLogGroups: ExperimentLogGroup[]
+ firstCheck: dayjs.Dayjs | null
hasLiveTrainingRun: boolean
+ latestChampionPerformance: OnlinePerformanceRowApi | null
lifecycleSteps: LifecycleStep[] | null
modelByTrainingRun: Record<string, AutoresearchModelApi>
models: AutoresearchModelApi[]
modelsError: boolean
modelsLoaded: boolean
modelsLoading: boolean
- onlinePerformanceRows: OnlinePerformanceRow[]
+ onlinePerformance: OnlinePerformanceRowApi[]
+ onlinePerformanceError: boolean
+ onlinePerformanceLoading: boolean
pipeline: AutoresearchPipelineApi | null
pipelineError: boolean
pipelineLoading: boolean
@@ -332,6 +307,7 @@ export interface autoresearchPipelineLogicValues {
probabilityDistributionError: boolean
probabilityDistributionLoading: boolean
probabilityHistogram: ProbabilityBucket[] | null
+ realizedAucPoints: RealizedAucPoint[]
reportByRun: Record<string, string | null>
reportByRunLoading: boolean
runs: AutoresearchRunApi[]
@@ -342,6 +318,7 @@ export interface autoresearchPipelineLogicValues {
scoreResult: AutoresearchRunApi | null
scoreResultLoading: boolean
scoringCoverage: ScoringCoverage | null
+ segmentCalibration: SegmentCalibration[]
selectedTab: AutoresearchPipelineTab | null
startTrainingResult: AutoresearchTrainingRunApi | null
startTrainingResultLoading: boolean
@@ -355,7 +332,6 @@ export interface autoresearchPipelineLogicValues {
trainingRuns: AutoresearchTrainingRunApi[]
trainingRunsError: boolean
trainingRunsLoading: boolean
- validationRuns: AutoresearchRunApi[]
viewedArtifact: ViewedArtifact | null
viewedArtifactLoading: boolean
}
@@ -432,6 +408,21 @@ export interface autoresearchPipelineLogicActions {
models: AutoresearchModelApi[]
payload?: any
}
+ loadOnlinePerformance: () => any
+ loadOnlinePerformanceFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOnlinePerformanceSuccess: (
+ onlinePerformance: OnlinePerformanceRowApi[],
+ payload?: any
+ ) => {
+ onlinePerformance: OnlinePerformanceRowApi[]
+ payload?: any
+ }
loadPipeline: () => any
loadPipelineFailure: (
error: string,
@@ -745,12 +736,14 @@ export interface autoresearchPipelineLogicMeta {
breadcrumbs: (pipeline: AutoresearchPipelineApi | null) => Breadcrumb[]
champion: (models: AutoresearchModelApi[]) => AutoresearchModelApi | null
modelByTrainingRun: (models: AutoresearchModelApi[]) => Record<string, AutoresearchModelApi>
- validationRuns: (runs: AutoresearchRunApi[]) => AutoresearchRunApi[]
scoringCoverage: (
runs: AutoresearchRunApi[],
pipeline: AutoresearchPipelineApi | null
) => ScoringCoverage | null
- onlinePerformanceRows: (validationRuns: AutoresearchRunApi[]) => OnlinePerformanceRow[]
+ latestChampionPerformance: (onlinePerformance: OnlinePerformanceRowApi[]) => OnlinePerformanceRowApi | null
+ realizedAucPoints: (onlinePerformance: OnlinePerformanceRowApi[]) => RealizedAucPoint[]
+ segmentCalibration: (latestChampionPerformance: OnlinePerformanceRowApi | null) => SegmentCalibration[]
+ firstCheck: (runs: AutoresearchRunApi[], pipeline: AutoresearchPipelineApi | null) => dayjs.Dayjs | null
probabilityHistogram: (probabilityDistribution: ProbabilityBucket[] | null) => ProbabilityBucket[] | null
hasLiveTrainingRun: (trainingRuns: AutoresearchTrainingRunApi[]) => boolean
agentSearch: (trainingRuns: AutoresearchTrainingRunApi[], champion: AutoresearchModelApi | null) => AgentSearch
@@ -769,7 +762,6 @@ export interface autoresearchPipelineLogicMeta {
pipeline: AutoresearchPipelineApi | null,
champion: AutoresearchModelApi | null,
runs: AutoresearchRunApi[],
- onlinePerformanceRows: OnlinePerformanceRow[],
modelsLoaded: boolean,
runsLoaded: boolean
) => LifecycleStep[] | null
@@ -938,6 +930,13 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
loadRunsFailure: () => true,
},
],
+ onlinePerformanceError: [
+ false,
+ {
+ loadOnlinePerformance: () => false,
+ loadOnlinePerformanceFailure: () => true,
+ },
+ ],
suggestionsError: [
false,
{
@@ -1015,6 +1014,18 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
},
},
],
+ onlinePerformance: [
+ [] as OnlinePerformanceRowApi[],
+ {
+ loadOnlinePerformance: async () => {
+ if (!values.currentTeamId) {
+ return []
+ }
+ const { rows } = await autoresearchOnlinePerformanceRetrieve(String(values.currentTeamId), props.id)
+ return rows
+ },
+ },
+ ],
suggestions: [
[] as AutoresearchSuggestionApi[],
{
@@ -1266,53 +1277,29 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
models.filter((m) => m.source_training_run).map((m) => [m.source_training_run as string, m])
),
],
- validationRuns: [
- (s) => [s.runs],
- (runs: AutoresearchRunApi[]): AutoresearchRunApi[] =>
- runs.filter((r) => r.run_type === 'validation' && r.status === 'completed'),
- ],
scoringCoverage: [
(s) => [s.runs, s.pipeline],
(runs: AutoresearchRunApi[], pipeline: AutoresearchPipelineApi | null): ScoringCoverage | null =>
scoringCoverage(runs, pipeline?.cadence_days ?? 1),
],
- onlinePerformanceRows: [
- (s) => [s.validationRuns],
- (validationRuns: AutoresearchRunApi[]): OnlinePerformanceRow[] => {
- const rows: OnlinePerformanceRow[] = []
- for (const run of validationRuns) {
- const m = run.metrics as Partial<ValidationRunMetrics> | null
- if (!m?.prediction_date) {
- continue
- }
- if (!m.per_model || Object.keys(m.per_model).length === 0) {
- continue
- }
- for (const [modelId, model] of Object.entries(m.per_model)) {
- rows.push({
- run_id: run.id,
- model_id: modelId,
- prediction_date: m.prediction_date,
- emitted_role: model.emitted_role ?? model.model_role,
- model_role: model.model_role,
- n_scored: model.n_scored,
- realized_auc: model.realized_auc ?? null,
- brier_score: model.brier_score ?? null,
- calibration_error: model.calibration_error ?? null,
- lift_at_10: model.lift_at_10 ?? null,
- lift_at_20: model.lift_at_20 ?? null,
- })
- }
- }
- // Sort by date descending, champion before challenger within same date
- rows.sort((a, b) => {
- if (b.prediction_date !== a.prediction_date) {
- return b.prediction_date.localeCompare(a.prediction_date)
- }
- return a.emitted_role === 'champion' ? -1 : 1
- })
- return rows
- },
+ latestChampionPerformance: [
+ (s) => [s.onlinePerformance],
+ (onlinePerformance: OnlinePerformanceRowApi[]): OnlinePerformanceRowApi | null =>
+ latestChampionRow(onlinePerformance),
+ ],
+ realizedAucPoints: [
+ (s) => [s.onlinePerformance],
+ (onlinePerformance: OnlinePerformanceRowApi[]): RealizedAucPoint[] => realizedAucSeries(onlinePerformance),
+ ],
+ segmentCalibration: [
+ (s) => [s.latestChampionPerformance],
+ (latestChampionPerformance: OnlinePerformanceRowApi | null): SegmentCalibration[] =>
+ calibrationBySegment(latestChampionPerformance?.calibration_bins ?? []),
+ ],
+ firstCheck: [
+ (s) => [s.runs, s.pipeline],
+ (runs: AutoresearchRunApi[], pipeline: AutoresearchPipelineApi | null): dayjs.Dayjs | null =>
+ firstCheckDate(runs, pipeline?.horizon_days),
],
probabilityHistogram: [
(s) => [s.probabilityDistribution],
@@ -1361,12 +1348,11 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
): AutoresearchPipelineTab => selectedTab ?? defaultTab,
],
lifecycleSteps: [
- (s) => [s.pipeline, s.champion, s.runs, s.onlinePerformanceRows, s.modelsLoaded, s.runsLoaded],
+ (s) => [s.pipeline, s.champion, s.runs, s.modelsLoaded, s.runsLoaded],
(
pipeline: AutoresearchPipelineApi | null,
champion: AutoresearchModelApi | null,
runs: AutoresearchRunApi[],
- onlinePerformanceRows: OnlinePerformanceRow[],
modelsLoaded: boolean,
runsLoaded: boolean
): LifecycleStep[] | null =>
@@ -1376,7 +1362,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
pipeline,
champion,
runs,
- validatedDates: onlinePerformanceRows.map((row) => row.prediction_date),
+ validatedDates: validatedPredictionDates(runs),
now: dayjs(),
})
: null,
@@ -1388,6 +1374,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
actions.loadModels()
actions.loadTrainingRuns()
actions.loadRuns()
+ actions.loadOnlinePerformance()
actions.loadSuggestions()
},
loadCurrentTeamSuccess: () => {
diff --git a/products/autoresearch/frontend/onlinePerformance.test.ts b/products/autoresearch/frontend/onlinePerformance.test.ts
new file mode 100644
index 000000000000..f87544b23e9b
--- /dev/null
+++ b/products/autoresearch/frontend/onlinePerformance.test.ts
@@ -0,0 +1,56 @@
+import { AutoresearchRunApi, OnlinePerformanceRowApi } from './generated/api.schemas'
+import { calibrationBySegment, realizedAucSeries, validatedPredictionDates } from './onlinePerformance'
+
+function row(overrides: Partial<OnlinePerformanceRowApi>): OnlinePerformanceRowApi {
+ return {
+ prediction_date: '2026-02-10',
+ emitted_role: 'champion',
+ realized_auc: 0.8,
+ realized_auc_ci_low: 0.75,
+ realized_auc_ci_high: 0.85,
+ ...overrides,
+ } as OnlinePerformanceRowApi
+}
+
+describe('onlinePerformance', () => {
+ test('calibrationBySegment weights each bin by its people and drops empty segments', () => {
+ const segments = calibrationBySegment([
+ { n: 300, mean_p_y: 0.05, positive_rate: 0.04 },
+ { n: 100, mean_p_y: 0.15, positive_rate: 0.2 },
+ { n: 50, mean_p_y: 0.7, positive_rate: 0.6 },
+ ])
+
+ expect(
+ segments.map(({ segment, people, predicted, actual }) => [segment.key, people, predicted, actual])
+ ).toEqual([
+ ['likely', 50, 0.7, 0.6],
+ ['unlikely', 400, expect.closeTo(0.075), expect.closeTo(0.08)],
+ ])
+ })
+
+ test('realizedAucSeries keeps the champion rows with an AUC, oldest date first', () => {
+ const points = realizedAucSeries([
+ row({ prediction_date: '2026-02-12', realized_auc: 0.82 }),
+ row({ prediction_date: '2026-02-12', emitted_role: 'challenger', realized_auc: 0.7 }),
+ row({ prediction_date: '2026-02-11', realized_auc: null }),
+ row({ prediction_date: '2026-02-10', realized_auc: 0.79 }),
+ ])
+
+ expect(points.map((p) => [p.date, p.auc])).toEqual([
+ ['2026-02-10', 0.79],
+ ['2026-02-12', 0.82],
+ ])
+ })
+
+ test('validatedPredictionDates counts only completed validation runs that scored a model', () => {
+ const scored = { per_model: { champion: { n_scored: 100 } } }
+ const runs = [
+ { run_type: 'validation', status: 'completed', metrics: { prediction_date: '2026-02-10', ...scored } },
+ { run_type: 'validation', status: 'failed', metrics: { prediction_date: '2026-02-11', ...scored } },
+ { run_type: 'validation', status: 'completed', metrics: { prediction_date: '2026-02-12', per_model: {} } },
+ { run_type: 'inference', status: 'completed', metrics: { prediction_date: '2026-02-13', ...scored } },
+ ] as Pick<AutoresearchRunApi, 'run_type' | 'status' | 'metrics'>[]
+
+ expect(validatedPredictionDates(runs)).toEqual(['2026-02-10'])
+ })
+})
diff --git a/products/autoresearch/frontend/onlinePerformance.ts b/products/autoresearch/frontend/onlinePerformance.ts
new file mode 100644
index 000000000000..00c79a6b3fd4
--- /dev/null
+++ b/products/autoresearch/frontend/onlinePerformance.ts
@@ -0,0 +1,126 @@
+import { dayjs } from 'lib/dayjs'
+
+import { AutoresearchRunApi, CalibrationBinApi, OnlinePerformanceRowApi } from './generated/api.schemas'
+import { modelQuality } from './modelQuality'
+import { PREDICTION_SEGMENTS, PredictionSegmentDefinition, predictionSegmentFor } from './predictionSegments'
+
+export interface RealizedAucPoint {
+ date: string
+ auc: number
+ low: number | null
+ high: number | null
+}
+
+export interface SegmentCalibration {
+ segment: PredictionSegmentDefinition
+ people: number
+ /** Mean predicted probability of the segment's people. */
+ predicted: number
+ /** Fraction of the segment's people who did the target event. */
+ actual: number
+}
+
+export function percent(value: number): string {
+ return `${(value * 100).toFixed(1)}%`
+}
+
+/** The champion's row for the newest validated date. Rows come newest date first. */
+export function latestChampionRow(rows: OnlinePerformanceRowApi[]): OnlinePerformanceRowApi | null {
+ return rows.find((row) => row.emitted_role === 'champion') ?? null
+}
+
+/** One sentence on what the model predicted for its newest matured date and what really happened. */
+export function accuracyHeadline(row: OnlinePerformanceRowApi, target: string): string {
+ const date = dayjs(row.prediction_date).format('MMM D')
+ const outcome = `${row.n_positive.toLocaleString()} of ${row.n_scored.toLocaleString()} people scored on ${date} did ${target} (${percent(row.base_rate)})`
+ return row.mean_p_y != null ? `${outcome}. The model predicted ${percent(row.mean_p_y)}.` : `${outcome}.`
+}
+
+/** How well the model ranked people on that date, in the same words as the model list. */
+export function rankingSentence(row: OnlinePerformanceRowApi, target: string): string | null {
+ const quality = modelQuality({
+ holdoutAuc: null,
+ realizedAuc: row.realized_auc,
+ liftAt10: null,
+ isPreliminary: false,
+ target: '',
+ })
+ if (!quality) {
+ return null
+ }
+ const lift =
+ row.lift_at_10 != null ? ` The top 10% were ${row.lift_at_10.toFixed(1)}× more likely to do ${target}.` : ''
+ return `Ranking quality is ${quality.verdict.toLowerCase()} (realized AUC ${quality.auc.toFixed(2)}).${lift}`
+}
+
+/** The champion's realized AUC per date, oldest first, for the trend chart. */
+export function realizedAucSeries(rows: OnlinePerformanceRowApi[]): RealizedAucPoint[] {
+ return rows
+ .filter((row) => row.emitted_role === 'champion' && row.realized_auc != null)
+ .map((row) => ({
+ date: row.prediction_date,
+ auc: row.realized_auc as number,
+ low: row.realized_auc_ci_low,
+ high: row.realized_auc_ci_high,
+ }))
+ .sort((a, b) => a.date.localeCompare(b.date))
+}
+
+/**
+ * Predicted against actual rate per likelihood segment. The quantile bins do not align with the
+ * segment cut points, so each bin goes to the segment of its mean predicted probability.
+ */
+export function calibrationBySegment(bins: CalibrationBinApi[]): SegmentCalibration[] {
+ const totals = new Map<string, { people: number; predicted: number; actual: number }>()
+ for (const bin of bins) {
+ const key = predictionSegmentFor(bin.mean_p_y).key
+ const total = totals.get(key) ?? { people: 0, predicted: 0, actual: 0 }
+ total.people += bin.n
+ total.predicted += bin.n * bin.mean_p_y
+ total.actual += bin.n * bin.positive_rate
+ totals.set(key, total)
+ }
+ return PREDICTION_SEGMENTS.flatMap((segment) => {
+ const total = totals.get(segment.key)
+ return total && total.people > 0
+ ? [
+ {
+ segment,
+ people: total.people,
+ predicted: total.predicted / total.people,
+ actual: total.actual / total.people,
+ },
+ ]
+ : []
+ })
+}
+
+/** When the first scored date matures: the earliest completed scoring run plus the horizon. */
+export function firstCheckDate(
+ runs: Pick<AutoresearchRunApi, 'run_type' | 'status' | 'created_at'>[],
+ horizonDays: number | undefined
+): dayjs.Dayjs | null {
+ const firstScored = runs
+ .filter((run) => run.run_type === 'inference' && run.status === 'completed')
+ .map((run) => dayjs(run.created_at))
+ .sort((a, b) => a.valueOf() - b.valueOf())[0]
+ return firstScored ? firstScored.add(horizonDays ?? 0, 'day') : null
+}
+
+/**
+ * Prediction dates that a completed validation run checked. Reads the full run history, because the
+ * online_performance endpoint returns only the newest dates.
+ */
+export function validatedPredictionDates(
+ runs: Pick<AutoresearchRunApi, 'run_type' | 'status' | 'metrics'>[]
+): string[] {
+ return runs.flatMap((run) => {
+ const metrics = run.metrics as { prediction_date?: string; per_model?: Record<string, unknown> } | null
+ return run.run_type === 'validation' &&
+ run.status === 'completed' &&
+ metrics?.prediction_date &&
+ Object.keys(metrics.per_model ?? {}).length > 0
+ ? [metrics.prediction_date]
+ : []
+ })
+}
diff --git a/products/autoresearch/frontend/pipeline/MetricTrendCard.tsx b/products/autoresearch/frontend/pipeline/MetricTrendCard.tsx
deleted file mode 100644
index d2ada26b9df1..000000000000
--- a/products/autoresearch/frontend/pipeline/MetricTrendCard.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { dayjs } from 'lib/dayjs'
-
-import { MetricSparkline } from './MetricSparkline'
-
-/** A labelled sparkline card showing one realized metric's trend over prediction dates. */
-export function MetricTrendCard({
- title,
- points,
- color,
- floor,
- ceil,
-}: {
- title: string
- points: { date: string; value: number }[]
- color?: string
- floor?: number
- ceil?: number
-}): JSX.Element | null {
- if (points.length < 2) {
- return null
- }
- const latest = points[points.length - 1]
- return (
- <div className="border rounded p-3 space-y-1 inline-block">
- <div className="text-xs font-semibold text-muted uppercase tracking-wide">{title}</div>
- <div className="text-lg font-bold">{latest.value.toFixed(3)}</div>
- <MetricSparkline points={points} color={color} floor={floor} ceil={ceil} />
- <div className="text-xs text-muted">
- {dayjs(points[0].date).format('MMM D')} to {dayjs(latest.date).format('MMM D')}
- </div>
- </div>
- )
-}
diff --git a/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx b/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx
index 2441968653e2..200c22faedc5 100644
--- a/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx
+++ b/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx
@@ -1,11 +1,17 @@
import { useActions, useValues } from 'kea'
import { IconGraph } from '@posthog/icons'
-import { LemonBanner, LemonTable, LemonTag, Spinner } from '@posthog/lemon-ui'
+import { LemonBanner, LemonCollapse, LemonTable, LemonTag, Spinner } from '@posthog/lemon-ui'
-import { OnlinePerformanceRow, autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
+import { dayjs } from 'lib/dayjs'
+import { pluralize } from 'lib/utils/strings'
+
+import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
+import { accuracyHeadline, rankingSentence } from '../onlinePerformance'
import { EmptyTab } from './EmptyTab'
-import { MetricTrendCard } from './MetricTrendCard'
+import { RealizedAucChart } from './RealizedAucChart'
+import { ScoreNowButton } from './ScoreNowButton'
+import { SegmentCalibrationBars } from './SegmentCalibrationBars'
const MODEL_ROLE: Record<string, { type: 'success' | 'default' | 'highlight'; label: string }> = {
champion: { type: 'success', label: 'Champion' },
@@ -17,101 +23,138 @@ function fmt(value: number | null, decimals = 3): string {
return value != null ? value.toFixed(decimals) : '—'
}
+function NotCheckedYet(): JSX.Element {
+ const { pipeline, firstCheck } = useValues(autoresearchPipelineLogic)
+ const horizon = pluralize(pipeline?.horizon_days ?? 0, 'day')
+ return (
+ <EmptyTab icon={<IconGraph />} title="Not checked against real outcomes yet" cta={<ScoreNowButton />}>
+ PostHog checks each prediction against what people really did, {horizon} after the prediction.{' '}
+ {!firstCheck
+ ? `Score the model to start. The first check comes ${horizon} after the first scoring run.`
+ : firstCheck.isAfter(dayjs())
+ ? `The first check is due on ${firstCheck.format('MMM D, YYYY')}.`
+ : `The first scored date matured on ${firstCheck.format('MMM D, YYYY')}. The first check runs on the next daily schedule.`}
+ </EmptyTab>
+ )
+}
+
export function OnlinePerformanceTab(): JSX.Element {
- const { onlinePerformanceRows, runsLoading, runsError } = useValues(autoresearchPipelineLogic)
- const { loadRuns } = useActions(autoresearchPipelineLogic)
+ const {
+ pipeline,
+ champion,
+ onlinePerformance,
+ onlinePerformanceLoading,
+ onlinePerformanceError,
+ latestChampionPerformance,
+ realizedAucPoints,
+ segmentCalibration,
+ } = useValues(autoresearchPipelineLogic)
+ const { loadOnlinePerformance } = useActions(autoresearchPipelineLogic)
- if (runsLoading) {
+ if (onlinePerformanceLoading && onlinePerformance.length === 0) {
return <Spinner />
}
- if (runsError) {
+ if (onlinePerformanceError) {
return (
<LemonBanner
type="error"
- action={{ children: 'Retry', onClick: () => loadRuns(), 'data-attr': 'autoresearch-model-runs-retry' }}
+ action={{
+ children: 'Retry',
+ onClick: () => loadOnlinePerformance(),
+ 'data-attr': 'autoresearch-model-accuracy-retry',
+ }}
>
- Couldn't load this model's scoring runs. Try again, and if it keeps happening contact support.
+ Couldn't load this model's accuracy. Try again, and if it keeps happening contact support.
</LemonBanner>
)
}
- if (onlinePerformanceRows.length === 0) {
- return (
- <EmptyTab icon={<IconGraph />} title="No realized performance yet">
- Realized metrics appear once prediction horizons elapse. For each prediction date, PostHog joins your{' '}
- <code>autoresearch_prediction</code> events to actual outcomes and computes AUC, Brier score, and lift.
- Trigger evaluation with the <code>autoresearch-validate-online</code> MCP tool or the{' '}
- <code>autoresearch_validate_online</code> management command.
- </EmptyTab>
- )
+ if (!latestChampionPerformance || !pipeline) {
+ return <NotCheckedYet />
}
- // Champion metric trends over time, oldest → newest, for the sparklines.
- const championRows = onlinePerformanceRows
- .filter((r) => r.emitted_role === 'champion')
- .sort((a, b) => a.prediction_date.localeCompare(b.prediction_date))
- const trend = (pick: (r: OnlinePerformanceRow) => number | null): { date: string; value: number }[] =>
- championRows.filter((r) => pick(r) != null).map((r) => ({ date: r.prediction_date, value: pick(r) as number }))
- const aucTrend = trend((r) => r.realized_auc)
- const brierTrend = trend((r) => r.brier_score)
- const eceTrend = trend((r) => r.calibration_error)
+ const ranking = rankingSentence(latestChampionPerformance, pipeline.target_event)
+ const latestDate = dayjs(latestChampionPerformance.prediction_date).format('MMM D')
return (
- <div className="space-y-4">
- <p className="text-sm text-muted">
- Realized performance measured after each prediction horizon elapses. AUC and lift here reflect actual
- user outcomes rather than holdout estimates.
- </p>
- <div className="flex flex-wrap gap-3">
- <MetricTrendCard
- title="Champion realized AUC"
- points={aucTrend}
- color="var(--success)"
- floor={0.5}
- ceil={1}
- />
- <MetricTrendCard title="Champion Brier score" points={brierTrend} color="var(--warning)" floor={0} />
- <MetricTrendCard
- title="Champion calibration error (ECE)"
- points={eceTrend}
- color="var(--warning)"
- floor={0}
- />
+ <div className="space-y-6">
+ <div className="space-y-1">
+ <p className="text-base font-semibold mb-0">
+ {accuracyHeadline(latestChampionPerformance, pipeline.target_event)}
+ </p>
+ {ranking && <p className="text-sm text-muted mb-0">{ranking}</p>}
</div>
- <LemonTable
- dataSource={onlinePerformanceRows}
- rowKey={(row) => `${row.run_id}-${row.model_id}`}
- columns={[
- {
- title: 'Prediction date',
- render: (_, row) => <span className="font-mono">{row.prediction_date}</span>,
- },
+
+ {segmentCalibration.length > 0 && (
+ <section className="space-y-2">
+ <h3 className="text-sm font-semibold mb-0">Predicted and actual rate by segment, {latestDate}</h3>
+ <SegmentCalibrationBars segments={segmentCalibration} />
+ </section>
+ )}
+
+ {realizedAucPoints.length > 0 && (
+ <section className="space-y-2">
+ <h3 className="text-sm font-semibold mb-0">Realized AUC over time</h3>
+ <p className="text-xs text-muted mb-0">
+ Realized AUC measures how well the model ranked people who did {pipeline.target_event} above
+ people who did not. 0.5 is a coin flip and 1 is a perfect ranking. The holdout line is the score
+ the model got in training.
+ </p>
+ <RealizedAucChart points={realizedAucPoints} holdoutAuc={champion?.holdout_score ?? null} />
+ </section>
+ )}
+
+ <LemonCollapse
+ panels={[
{
- title: 'Model',
- tooltip: 'The role the model held when it made these predictions.',
- render: (_, row) => (
- <LemonTag type={MODEL_ROLE[row.emitted_role]?.type ?? 'default'}>
- {MODEL_ROLE[row.emitted_role]?.label ?? row.emitted_role}
- </LemonTag>
+ key: 'history',
+ header: `All checked dates (${onlinePerformance.length})`,
+ content: (
+ <div className="space-y-2">
+ <LemonTable
+ dataSource={onlinePerformance}
+ rowKey={(row) => `${row.validation_run_id}-${row.model_id}`}
+ columns={[
+ {
+ title: 'Prediction date',
+ render: (_, row) => (
+ <span className="font-mono">{row.prediction_date}</span>
+ ),
+ },
+ {
+ title: 'Model',
+ tooltip: 'The role the model held when it made these predictions.',
+ render: (_, row) => (
+ <LemonTag type={MODEL_ROLE[row.emitted_role]?.type ?? 'default'}>
+ {MODEL_ROLE[row.emitted_role]?.label ?? row.emitted_role}
+ </LemonTag>
+ ),
+ },
+ { title: 'Users scored', render: (_, row) => row.n_scored.toLocaleString() },
+ {
+ title: 'Realized AUC',
+ render: (_, row) => (
+ <span className="font-semibold">{fmt(row.realized_auc)}</span>
+ ),
+ },
+ { title: 'Brier score', render: (_, row) => fmt(row.brier_score) },
+ { title: 'Calibration error', render: (_, row) => fmt(row.calibration_error) },
+ { title: 'Lift at 10%', render: (_, row) => `${fmt(row.lift_at_10, 2)}×` },
+ { title: 'Lift at 20%', render: (_, row) => `${fmt(row.lift_at_20, 2)}×` },
+ ]}
+ />
+ <p className="text-xs text-muted mb-0">
+ Realized AUC: higher is better. Brier score and calibration error (ECE): lower is
+ better. ECE measures how far predicted probabilities drift from observed rates. Lift
+ at k%: ratio of positives in the top k% vs a random sample, so 2× means twice as
+ many conversions as random.
+ </p>
+ </div>
),
},
- { title: 'Users scored', render: (_, row) => row.n_scored.toLocaleString() },
- {
- title: 'Realized AUC',
- render: (_, row) => <span className="font-semibold">{fmt(row.realized_auc)}</span>,
- },
- { title: 'Brier score', render: (_, row) => fmt(row.brier_score) },
- { title: 'Calibration error', render: (_, row) => fmt(row.calibration_error) },
- { title: 'Lift at 10%', render: (_, row) => `${fmt(row.lift_at_10, 2)}×` },
- { title: 'Lift at 20%', render: (_, row) => `${fmt(row.lift_at_20, 2)}×` },
]}
/>
- <p className="text-xs text-muted">
- Realized AUC: higher is better. Brier score and calibration error (ECE): lower is better. ECE measures
- how far predicted probabilities drift from observed rates. Lift at k%: ratio of positives in the top k%
- vs a random sample, so 2× means twice as many conversions as random.
- </p>
</div>
)
}
diff --git a/products/autoresearch/frontend/pipeline/RealizedAucChart.tsx b/products/autoresearch/frontend/pipeline/RealizedAucChart.tsx
new file mode 100644
index 000000000000..c443567659f3
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/RealizedAucChart.tsx
@@ -0,0 +1,107 @@
+import { dayjs } from 'lib/dayjs'
+
+import { RealizedAucPoint } from '../onlinePerformance'
+
+const WIDTH = 600
+const HEIGHT = 160
+const Y_MIN = 0.5
+const Y_MAX = 1
+
+/** Champion realized AUC per prediction date, with its 95% interval and the holdout AUC for reference. No chart deps, like MetricSparkline. */
+export function RealizedAucChart({
+ points,
+ holdoutAuc,
+}: {
+ points: RealizedAucPoint[]
+ holdoutAuc: number | null
+}): JSX.Element {
+ const x = (index: number): number => (points.length === 1 ? WIDTH / 2 : (index * WIDTH) / (points.length - 1))
+ const y = (value: number): number =>
+ HEIGHT - ((Math.min(Math.max(value, Y_MIN), Y_MAX) - Y_MIN) / (Y_MAX - Y_MIN)) * HEIGHT
+ const banded = points.map((point, index) => ({ ...point, index })).filter((p) => p.low != null && p.high != null)
+ const band = [
+ ...banded.map((p) => `${x(p.index)},${y(p.high as number)}`),
+ ...[...banded].reverse().map((p) => `${x(p.index)},${y(p.low as number)}`),
+ ].join(' ')
+ const line = points.map((p, index) => `${x(index)},${y(p.auc)}`).join(' ')
+ const latest = points[points.length - 1]
+
+ return (
+ <div className="space-y-1 max-w-4xl">
+ <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 text-xs text-muted">
+ <span>
+ <span className="inline-block w-3 h-0.5 align-middle mr-1 bg-[var(--data-color-1)]" />
+ Realized AUC, latest {latest.auc.toFixed(2)}
+ </span>
+ <span>
+ <span className="inline-block w-3 h-2 align-middle mr-1 bg-[var(--data-color-1)] opacity-20" />
+ 95% interval
+ </span>
+ {holdoutAuc != null && (
+ <span>
+ <span className="inline-block w-3 align-middle mr-1 border-t border-dashed border-current" />
+ Holdout AUC {holdoutAuc.toFixed(2)}
+ </span>
+ )}
+ </div>
+ <div className="flex gap-2">
+ <div className="flex flex-col justify-between text-xs text-muted tabular-nums h-40">
+ <span>{Y_MAX.toFixed(1)}</span>
+ <span>{Y_MIN.toFixed(1)}</span>
+ </div>
+ <svg
+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
+ preserveAspectRatio="none"
+ className="flex-1 min-w-0 h-40 overflow-visible border-b border-l"
+ role="img"
+ aria-label="Realized AUC over prediction dates"
+ >
+ {banded.length > 0 && <polygon points={band} className="fill-[var(--data-color-1)] opacity-20" />}
+ {holdoutAuc != null && (
+ <line
+ x1={0}
+ x2={WIDTH}
+ y1={y(holdoutAuc)}
+ y2={y(holdoutAuc)}
+ className="stroke-current text-secondary"
+ strokeDasharray="6 4"
+ vectorEffect="non-scaling-stroke"
+ />
+ )}
+ <polyline
+ points={line}
+ fill="none"
+ className="stroke-[var(--data-color-1)]"
+ strokeWidth={2}
+ vectorEffect="non-scaling-stroke"
+ />
+ {points.map((p, index) => (
+ // A zero-length line with round caps stays a round dot when the SVG stretches.
+ <line
+ key={p.date}
+ x1={x(index)}
+ x2={x(index)}
+ y1={y(p.auc)}
+ y2={y(p.auc)}
+ className="stroke-[var(--data-color-1)]"
+ strokeWidth={6}
+ strokeLinecap="round"
+ vectorEffect="non-scaling-stroke"
+ >
+ <title>
+ {dayjs(p.date).format('MMM D, YYYY')}: AUC {p.auc.toFixed(3)}
+ {p.low != null && p.high != null
+ ? ` (95% interval ${p.low.toFixed(3)} to ${p.high.toFixed(3)})`
+ : ''}
+ </title>
+ </line>
+ ))}
+ </svg>
+ </div>
+ <div className="flex justify-between text-xs text-muted pl-6">
+ <span>{dayjs(points[0].date).format('MMM D')}</span>
+ {points.length > 1 && <span>{dayjs(latest.date).format('MMM D')}</span>}
+ </div>
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/pipeline/SegmentCalibrationBars.tsx b/products/autoresearch/frontend/pipeline/SegmentCalibrationBars.tsx
new file mode 100644
index 000000000000..5238cb9c6a2d
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/SegmentCalibrationBars.tsx
@@ -0,0 +1,50 @@
+import { SegmentCalibration, percent } from '../onlinePerformance'
+
+function Bar({
+ label,
+ value,
+ max,
+ className,
+}: {
+ label: string
+ value: number
+ max: number
+ className: string
+}): JSX.Element {
+ return (
+ <div className="flex items-center gap-2 text-xs">
+ <span className="w-16 shrink-0 text-muted">{label}</span>
+ <div className="flex-1 min-w-0 h-3 rounded bg-surface-secondary">
+ <div className={`h-full rounded ${className}`} style={{ width: `${(100 * value) / max}%` }} />
+ </div>
+ <span className="w-12 shrink-0 text-right tabular-nums">{percent(value)}</span>
+ </div>
+ )
+}
+
+/** Predicted against actual rate for each likelihood segment on one matured date. */
+export function SegmentCalibrationBars({ segments }: { segments: SegmentCalibration[] }): JSX.Element {
+ const max = Math.max(...segments.flatMap((s) => [s.predicted, s.actual]), 0.01)
+ return (
+ <div className="space-y-3 max-w-2xl">
+ {segments.map(({ segment, people, predicted, actual }) => (
+ <div key={segment.key} className="space-y-1">
+ <div className="flex flex-wrap items-baseline gap-x-2 text-sm">
+ <span className={`inline-block w-2 h-2 rounded-full ${segment.colorClassName}`} />
+ <span className="font-semibold">{segment.label}</span>
+ <span className="text-xs text-muted">
+ {segment.range} · {people.toLocaleString()} people
+ </span>
+ </div>
+ <Bar
+ label="Predicted"
+ value={predicted}
+ max={max}
+ className={`${segment.colorClassName} opacity-50`}
+ />
+ <Bar label="Actual" value={actual} max={max} className={segment.colorClassName} />
+ </div>
+ ))}
+ </div>
+ )
+}