: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
feat(autoresearch): compare each training run's feature importances with the champion (#112656)
posthog[bot]e935978f8c3d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4383b28fd921..d91492a69d19 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6434,6 +6434,22 @@ snapshots:hash: v1.k794b7964.47dc280e27c512035ac74d86134e2b5771f84b1454556c492f6319d9d3ffa29f.l0n9noDhYfjTrpN-tlvi5TJq4RJCDIkUCFKse51o1O4products-autoresearch-probability-histogram--single-bucket--light:hash: v1.k794b7964.492095448990e600a399d4212b8fb96e8f95c2e7bdafb3f84d8bdc10467fbf4e.1OfZFFoGzmeH8sxtbwrD-H9bR_n08l9kV63NB2Sv1jU+ products-autoresearch-training-run-row--compared-with-champion-narrow--dark:+ hash: v1.k794b7964.9830e6048bce43800723ca6bee037bb1a91ec500aec423893be9b3c55659df14.fmdX0m_Qvg0f3TJFplwoR0u44C8RtyPj1NgmVoqP9Fk+ products-autoresearch-training-run-row--compared-with-champion-narrow--light:+ hash: v1.k794b7964.105ee396b96f519507dd4e49a1731864e80370fe5d92081c6480553cfd1eb594.0eAOak4fZGoUCLn2SknMQ6dhtAJ4rJnjDagKbXMVNIk+ products-autoresearch-training-run-row--compared-with-champion-wide--dark:+ hash: v1.k794b7964.54401cab59097a4aa36bdd135c4a3207f42cad57e0cb6ae1be20504c7104623e.lvwUB3xG2CnVO2Voq1d0XuSaKxSI0XPhMkGrlsB4dzo+ products-autoresearch-training-run-row--compared-with-champion-wide--light:+ hash: v1.k794b7964.d076be958a4e3ca0f41838084bc83584a4560ed551a67236b784e31d505b226a.kYRHbvr8-lCpBD4Rn-q6lyaFqbclQsJ8Wz4RG6NGdds+ products-autoresearch-training-run-row--run-model-without-importances--dark:+ hash: v1.k794b7964.cecb833bc7bd8ca42db243e0a6cbf6917167529efff3de02d4976129e31c9d15.NzRkSMaMOSdVxHG39_qyUpjM5mfV7z4xD6NJHWKMgnI+ products-autoresearch-training-run-row--run-model-without-importances--light:+ hash: v1.k794b7964.97de8a577ec7f77873b33b8cf56f7cd13ff7722032a055b0f6cca8f7a788ce7c.5fDSgGcP7hTthZ4U6pihNquI9e5ai8sTN6Dp6zqDDH4+ products-autoresearch-training-run-row--run-produced-the-champion--dark:+ hash: v1.k794b7964.a9de84c1f27dab319f1c8144f25dcb2ee86f24e4a8a81e3e4f1af8772691a853.-8abFqmvKqn68PvlPf_7mXyGfyzzVGlhwqMEIRLT1VQ+ products-autoresearch-training-run-row--run-produced-the-champion--light:+ hash: v1.k794b7964.99a7492e480121211d7b1bdcc80551dd1237c844db39f3e125a3419fcea07392.vVadWxwzVkcx_5Rs8NM_JR-rgQ1Mddc8LADMSDGJ5qAproducts-business-intelligence-comparison-summary--kpi--dark:hash: v1.k794b7964.f57d81874455ecab234e86bea129aa84be0ab55617e1a3f78e4df5ae0b5bef03.0KX9-_jhsiyC9WxFodb_tR84PkA3Sg_F1zEuQGSIPfwproducts-business-intelligence-comparison-summary--kpi--light:diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.mdindex 515082c5b608..db1a447139e1 100644--- a/products/autoresearch/backend/training/AGENTS.md+++ b/products/autoresearch/backend/training/AGENTS.md@@ -13,7 +13,7 @@ The other half is `../inference/`, which consumes what this package produces andThe real path. `run_training()` creates the `AutoresearchTrainingRun` (status `RUNNING`) and fires `Task.create_and_run()` with `internal=True` and no repository, so the run shows up as an internal Task rather than in the normal Tasks list.The brief carries user-authored text, so the sandbox token holds only `TRAINING_MCP_SCOPES` (the `execute-sql` reads, the autoresearch scopes, and `user:read`, which the PostHog MCP server needs to start a session), and an empty connector allowlist keeps the team's shared MCP connectors out of the sandbox.`build_agent_description()` assembles the agent's brief — the target, the horizon, the population, and the contract for the bundle it must author.- When the `autoresearch-report-notebook` flag is on for the launching user, the token also holds `REPORT_NOTEBOOK_MCP_SCOPES` and the brief adds a Finalize step: the agent builds one report notebook from the `system.autoresearch_*` tables and passes its `short_id` to complete. `report.md` stays required either way.+ When the `autoresearch-report-notebook` flag is on for the launching user, the token also holds `REPORT_NOTEBOOK_MCP_SCOPES` and the brief adds two Finalize steps: before complete, the agent creates one report notebook and passes its `short_id` to complete. After complete, it adds the SQL and chart cells, because the run's model row (and so its `model_explanation`) exists only from then on. `report.md` stays required either way.The brief's worked `features.sql` reads events through a pre-filtered subquery (the event names the features use, the anchor persons, and the anchors' widest window) before it joins, because ClickHouse builds the hash table from the right side of a join and a direct events join reads the whole team's events.The brief also states the inference cutoff: the start of the prediction date in UTC (`ScoringWindow` in `../inference/scoring.py`), not `now()`.The brief's cost guidance is advice only. Cost does not enter champion selection, so the brief does not tell the agent to trade AUC for a cheaper query.diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.pyindex 952e86370ddc..6eb1f1c5347e 100644--- a/products/autoresearch/backend/training/runner.py+++ b/products/autoresearch/backend/training/runner.py@@ -161,10 +161,10 @@ def _describe_training_sample(sample: TrainingSample | None) -> str:return clause-def _report_notebook_step(pipeline: AutoresearchPipeline, *, training_run_id: str, today_iso: str) -> str:- """The Finalize step that builds the report notebook, indented to sit inside the brief."""+def _report_notebook_step(pipeline: AutoresearchPipeline, *, today_iso: str) -> str:+ """The Finalize step that creates the report notebook, indented to sit inside the brief."""step = textwrap.dedent(f"""- 3. **Build the report notebook** — a live copy of the report whose numbers come from SQL+ 3. **Create the report notebook** — a live copy of the report whose numbers come from SQLcells, so a reader can check them and re-run them after scoring. `report.md` stays thefallback: write it first, whatever happens in this step.@@ -174,20 +174,32 @@ def _report_notebook_step(pipeline: AutoresearchPipeline, *, training_run_id: stCreate exactly ONE notebook with `notebooks-create-markdown`. Title it`<pipeline name> · model report · {today_iso}`, where the pipeline name is{_wrap_untrusted(pipeline.name)}. Change and run only this notebook. Never update,- delete, or run any other notebook.+ delete, or run any other notebook. Put only the **TL;DR** and **What it predicts**+ sections in it now, with the same content as `report.md`. You add the cells in step 5,+ after the run completes, because this run's model row does not exist until then.- Build it in this order, with markdown prose between the cells:- - **TL;DR** and **What it predicts** — the same content as `report.md`.+ Keep the notebook's `short_id` for the next step.""")+ return textwrap.indent(step, " " * 8)+++def _report_notebook_cells_step(pipeline: AutoresearchPipeline, *, training_run_id: str) -> str:+ """The step after complete that fills the report notebook, indented to sit inside the brief."""+ step = textwrap.dedent(f"""+ 5. **Fill the report notebook** — do this step only if you created the notebook in step 3+ and the complete call succeeded. Complete writes this run's model row, so the cells+ below now read real data.++ Add these cells with `notebooks-add-cell`, in this order, with markdown prose between them:- **How training went** — a SQL cell over `system.autoresearch_iterations` where`training_run_id = '{training_run_id}'`, then a Python cell that plots holdout AUC byiteration and marks kept and discarded iterations.- **How well it works** — a SQL cell over `system.autoresearch_models` where`pipeline_id = '{pipeline.pk}'`: role, holdout AUC, realized AUC, calibration error,and lift@10/@20 from `metrics` when present. Explain them in plain words.- - **What drives it** — a Python cell that charts the feature importances and direction- in `model_explanation` of this run's model row- (`source_training_run_id = '{training_run_id}'`), then prose on the intuition behind- each top feature.+ - **What drives it** — a SQL cell that reads `model_explanation` of this run's model row+ in `system.autoresearch_models` (`source_training_run_id = '{training_run_id}'`), then a+ Python cell that charts the feature importances and direction, then prose on the+ intuition behind each top feature.- **Live performance** — a SQL cell over `events` where`event = 'autoresearch_prediction'` and`properties.$autoresearch_pipeline_id = '{pipeline.pk}'`, then Python cells for the@@ -205,9 +217,7 @@ def _report_notebook_step(pipeline: AutoresearchPipeline, *, training_run_id: st- One figure per Python cell. The kernel keeps at most 8 figures and about 3 MB ofimages per cell.- Do not call `notebooks-configure-compute`. Use the default kernel.- - Run each cell. If a cell fails, fix it or delete it. Never leave a failed cell.-- Keep the notebook's `short_id` for the next step.""")+ - Run each cell. If a cell fails, fix it or delete it. Never leave a failed cell.""")return textwrap.indent(step, " " * 8)@@ -252,9 +262,11 @@ def build_agent_description(complete_step = 3notebook_step = ""notebook_field = ""+ notebook_cells_step = ""if report_notebook:complete_step = 4- notebook_step = _report_notebook_step(pipeline, training_run_id=training_run_id, today_iso=today_iso)+ notebook_step = _report_notebook_step(pipeline, today_iso=today_iso)+ notebook_cells_step = "\n" + _report_notebook_cells_step(pipeline, training_run_id=training_run_id)notebook_field = ("\n - `report_notebook_short_id`: the `short_id` of the notebook from step 3. Omit it\n"" if you skipped step 3 or the notebook does not exist."@@ -673,7 +685,7 @@ def build_agent_description(Also pass `model_explanation`, which the model card charts. Use exactly this shape:`{{"method": "<how you computed importance, one short line>", "top_features": [{{"name": "<feature column>", "importance": <number >= 0>, "direction": "positive" | "negative"}}]}}`.List at most {MAX_TOP_FEATURES} features of the winning iteration, strongest first. `direction` is- "positive" when a higher value raises the predicted probability, else "negative". Other keys are dropped.+ "positive" when a higher value raises the predicted probability, else "negative". Other keys are dropped.{notebook_cells_step}**Honesty note**: holdout_auc is checked against realized outcomes after inference. AnAUC of 0.55 that reflects real data beats a fabricated 0.80 — the realized gate is unfakeable.diff --git a/products/autoresearch/backend/training/test_training.py b/products/autoresearch/backend/training/test_training.pyindex b205e9dbd755..2864932f7eff 100644--- a/products/autoresearch/backend/training/test_training.py+++ b/products/autoresearch/backend/training/test_training.py@@ -145,6 +145,11 @@ class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):assert ("notebooks-create-markdown" in prompt) is report_notebookassert ("report_notebook_short_id" in prompt) is report_notebookassert prompt.index("report.md") < prompt.index("autoresearch-training-runs-complete-create")+ if report_notebook:+ # The model row the "What drives it" cell reads exists only after complete.+ assert prompt.index("autoresearch-training-runs-complete-create") < prompt.index(+ "**What drives it** — a SQL cell"+ )def test_prompt_excludes_autoresearch_feedback_events(self) -> None:pipeline = self._make_pipeline()diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.test.tsindex 704010943010..2a6dc02c5b03 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts@@ -8,6 +8,7 @@ import { initKeaTests } from '~/test/init'import {SCORE_RUN_POLL_INTERVAL_MS,autoresearchPipelineLogic,+ featureChanges,scoringCoverage,trainingRunProgress,} from './autoresearchPipelineLogic'@@ -18,7 +19,13 @@ import {autoresearchRunsRetrieve,autoresearchScoreCreate,} from './generated/api'-import { AutoresearchRunApi, AutoresearchTrainingRunApi, IterationTrailApi } from './generated/api.schemas'+import {+ AutoresearchRunApi,+ AutoresearchTrainingRunApi,+ FeatureDirectionEnumApi,+ IterationTrailApi,+ ModelExplanationFieldApi,+} from './generated/api.schemas'jest.mock('./generated/api', () => ({autoresearchRetrieve: jest.fn(),@@ -271,4 +278,23 @@ describe('autoresearchPipelineLogic', () => {expect(trainingRunProgress(run)).toEqual({ iterationCount: 2, bestHoldoutScore: 0.7 })})})++ describe('featureChanges', () => {+ const explanation = (...names: string[]): ModelExplanationFieldApi => ({+ top_features: names.map((name) => ({+ name,+ importance: 1,+ direction: FeatureDirectionEnumApi.Positive,+ })),+ })++ it.each([+ ['same features', explanation('a', 'b'), explanation('b', 'a'), { added: [], dropped: [] }],+ ['added and dropped', explanation('a', 'c'), explanation('a', 'b'), { added: ['c'], dropped: ['b'] }],+ ['run without importances', {}, explanation('a'), { added: [], dropped: [] }],+ ['champion without importances', explanation('a'), {}, { added: [], dropped: [] }],+ ])('%s', (_name, run, champion, expected) => {+ expect(featureChanges(run, champion)).toEqual(expected)+ })+ })})diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.tsindex 92197ff6fcb1..3013b4ac046d 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts@@ -31,12 +31,14 @@ import {autoresearchTrainCreate,} from './generated/api'import {+ AutoresearchModelRoleEnumApi,type AutoresearchModelApi,type AutoresearchPipelineApi,type AutoresearchRunApi,type AutoresearchSuggestionApi,type AutoresearchTrainingRunApi,CreateSuggestionPriorityEnumApi,+ type ModelExplanationFieldApi,} from './generated/api.schemas'import type { PredictionsPeopleView } from './predictionsPeopleQuery'@@ -175,6 +177,31 @@ export function trainingRunProgress(run: AutoresearchTrainingRunApi): TrainingRu}}+/**+ * Features in the run model's reported top drivers but not the champion's, and the reverse.+ * Each list is capped and can be partial, so a feature missing from a list can still be a model input.+ */+export interface FeatureChanges {+ added: string[]+ dropped: string[]+}++export function featureChanges(+ runExplanation: ModelExplanationFieldApi,+ championExplanation: ModelExplanationFieldApi+): FeatureChanges {+ const runNames = (runExplanation.top_features ?? []).map((f) => f.name)+ const championNames = (championExplanation.top_features ?? []).map((f) => f.name)+ // An empty list means the model recorded no importances, which says nothing about its features.+ if (runNames.length === 0 || championNames.length === 0) {+ return { added: [], dropped: [] }+ }+ return {+ added: runNames.filter((name) => !championNames.includes(name)),+ dropped: championNames.filter((name) => !runNames.includes(name)),+ }+}+/** How much of the inference population the latest scoring run covered, when it scored only part of it. */export interface ScoringCoverage {scored: number@@ -234,12 +261,15 @@ export interface autoresearchPipelineLogicValues {artifactsByRun: Record<string, string[]>artifactsByRunLoading: booleanbreadcrumbs: Breadcrumb[]+ champion: AutoresearchModelApi | nulldailyVolume: DailyVolumePoint[] | nulldailyVolumeError: booleandailyVolumeLoading: booleandetailRequested: booleanexpandedRunId: string | null+ modelByTrainingRun: Record<string, AutoresearchModelApi>models: AutoresearchModelApi[]+ modelsError: booleanmodelsLoading: booleanonlinePerformanceRows: OnlinePerformanceRow[]pipeline: AutoresearchPipelineApi | null@@ -616,6 +646,8 @@ export interface autoresearchPipelineLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {breadcrumbs: (pipeline: AutoresearchPipelineApi | null) => Breadcrumb[]+ champion: (models: AutoresearchModelApi[]) => AutoresearchModelApi | null+ modelByTrainingRun: (models: AutoresearchModelApi[]) => Record<string, AutoresearchModelApi>validationRuns: (runs: AutoresearchRunApi[]) => AutoresearchRunApi[]scoringCoverage: (runs: AutoresearchRunApi[],@@ -716,6 +748,13 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([loadPipelineFailure: () => true,},],+ modelsError: [+ false,+ {+ loadModels: () => false,+ loadModelsFailure: () => true,+ },+ ],trainingRunsError: [false,{@@ -1000,6 +1039,18 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([},],],+ champion: [+ (s) => [s.models],+ (models: AutoresearchModelApi[]): AutoresearchModelApi | null =>+ models.find((m) => m.role === AutoresearchModelRoleEnumApi.Champion) ?? null,+ ],+ modelByTrainingRun: [+ (s) => [s.models],+ (models: AutoresearchModelApi[]): Record<string, AutoresearchModelApi> =>+ Object.fromEntries(+ models.filter((m) => m.source_training_run).map((m) => [m.source_training_run as string, m])+ ),+ ],validationRuns: [(s) => [s.runs],(runs: AutoresearchRunApi[]): AutoresearchRunApi[] =>diff --git a/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx b/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsxindex 0986c3bdc134..28575c47a64c 100644--- a/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx+++ b/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx@@ -1,9 +1,23 @@-import { LemonCollapse, Tooltip } from '@posthog/lemon-ui'+import { ReactNode } from 'react'++import { LemonCollapse, LemonTag, Tooltip } from '@posthog/lemon-ui'import { FeatureDirectionEnumApi, ModelExplanationFieldApi } from '../generated/api.schemas'/** A model's top feature drivers, as importance bars relative to the strongest feature. */-export function FeatureImportanceChart({ explanation }: { explanation: ModelExplanationFieldApi }): JSX.Element {+export function FeatureImportanceChart({+ explanation,+ header = 'Top feature drivers',+ addedFeatures = [],+ droppedFeatures = [],+}: {+ explanation: ModelExplanationFieldApi+ header?: ReactNode+ /** Top drivers to tag as new, because the champion's top drivers do not include them. */+ addedFeatures?: string[]+ /** Champion top drivers that this model's top drivers do not include. */+ droppedFeatures?: string[]+}): JSX.Element {const features = explanation.top_features ?? []// Gain has no fixed scale, so bars are relative to the strongest feature.const maxImportance = Math.max(0, ...features.map((f) => f.importance))@@ -24,9 +38,18 @@ export function FeatureImportanceChart({ explanation }: { explanation: ModelExplconst effect = isNegative ? 'Lowers' : 'Raises'return (<div key={f.name} className="flex items-center gap-2 text-sm">- <div className="w-48 shrink-0 truncate font-mono text-xs" title={f.name}>- <span style={{ color }}>● </span>- {f.name}+ <div className="w-48 shrink-0 flex items-center gap-1 min-w-0">+ <span className="truncate font-mono text-xs" title={f.name}>+ <span style={{ color }}>● </span>+ {f.name}+ </span>+ {addedFeatures.includes(f.name) && (+ <Tooltip title="Not in the champion's top drivers">+ <LemonTag type="highlight" size="small" className="shrink-0">+ New+ </LemonTag>+ </Tooltip>+ )}</div><divclassName="flex-1 rounded h-4 overflow-hidden"@@ -46,15 +69,19 @@ export function FeatureImportanceChart({ explanation }: { explanation: ModelExpl)})}</div>+ {droppedFeatures.length > 0 && (+ <div className="flex flex-wrap items-center gap-1 text-xs text-muted">+ Champion top drivers not in this list:+ {droppedFeatures.map((name) => (+ <LemonTag key={name} type="muted" size="small" className="font-mono">+ {name}+ </LemonTag>+ ))}+ </div>+ )}{explanation.method && <div className="text-xs text-muted">Method: {explanation.method}</div>}{explanation.note && <div className="text-xs text-muted italic">{explanation.note}</div>}</div>)- return (- <LemonCollapse- size="small"- defaultActiveKey="features"- panels={[{ key: 'features', header: 'Top feature drivers', content }]}- />- )+ return <LemonCollapse size="small" defaultActiveKey="features" panels={[{ key: 'features', header, content }]} />}diff --git a/products/autoresearch/frontend/pipeline/RunFeatureComparison.tsx b/products/autoresearch/frontend/pipeline/RunFeatureComparison.tsxnew file mode 100644index 000000000000..e5efb8b5b028--- /dev/null+++ b/products/autoresearch/frontend/pipeline/RunFeatureComparison.tsx@@ -0,0 +1,66 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, Spinner } from '@posthog/lemon-ui'++import { autoresearchPipelineLogic, featureChanges } from '../autoresearchPipelineLogic'+import { AutoresearchModelApi, AutoresearchModelRoleEnumApi } from '../generated/api.schemas'+import { FeatureImportanceChart } from './FeatureImportanceChart'++const ROLE_LABEL: Record<AutoresearchModelRoleEnumApi, string> = {+ champion: 'Champion',+ challenger: 'Challenger',+ archived: 'Archived',+}++function holdoutLabel(model: AutoresearchModelApi): string {+ return model.holdout_score != null ? `holdout AUC ${model.holdout_score.toFixed(3)}` : 'no holdout AUC'+}++/** The feature importances of the model a training run produced, next to the current champion's. */+export function RunFeatureComparison({ runId }: { runId: string }): JSX.Element {+ const { modelByTrainingRun, champion, modelsLoading, modelsError } = useValues(autoresearchPipelineLogic)+ const { loadModels } = useActions(autoresearchPipelineLogic)+ const model = modelByTrainingRun[runId]+ if (!model) {+ return modelsLoading ? (+ <Spinner />+ ) : modelsError ? (+ <LemonBanner+ type="error"+ action={{+ children: 'Retry',+ onClick: () => loadModels(),+ 'data-attr': 'autoresearch-run-model-retry',+ }}+ >+ Couldn't load this run's model. Try again, and if it keeps happening contact support.+ </LemonBanner>+ ) : (+ <div className="text-muted text-sm">+ This run did not produce a model, so it has no feature importances.+ </div>+ )+ }+ const compareWithChampion = champion && champion.id !== model.id+ const changes = compareWithChampion+ ? featureChanges(model.model_explanation, champion.model_explanation)+ : { added: [], dropped: [] }+ return (+ <div className="@container">+ <div className="grid grid-cols-1 gap-3 @2xl:grid-cols-2">+ <FeatureImportanceChart+ explanation={model.model_explanation}+ header={`This run's model · ${ROLE_LABEL[model.role ?? AutoresearchModelRoleEnumApi.Challenger]} · ${holdoutLabel(model)}`}+ addedFeatures={changes.added}+ droppedFeatures={changes.dropped}+ />+ {compareWithChampion && (+ <FeatureImportanceChart+ explanation={champion.model_explanation}+ header={`Current champion · ${holdoutLabel(champion)}`}+ />+ )}+ </div>+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/TrainingRunRow.stories.tsx b/products/autoresearch/frontend/pipeline/TrainingRunRow.stories.tsxnew file mode 100644index 000000000000..bbc5fae5c7d8--- /dev/null+++ b/products/autoresearch/frontend/pipeline/TrainingRunRow.stories.tsx@@ -0,0 +1,151 @@+import { Meta, StoryObj } from '@storybook/react'+import { BindLogic, useMountedLogic } from 'kea'+import { useEffect } from 'react'++import { mswDecorator } from '~/mocks/browser'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import {+ AutoresearchModelApi,+ AutoresearchModelRoleEnumApi,+ AutoresearchTrainingRunApi,+ FeatureDirectionEnumApi,+ FeatureImportanceApi,+} from '../generated/api.schemas'+import { TrainingRunRow } from './TrainingRunRow'++const PIPELINE_ID = 'pipeline-story'+const RUN_ID = '0b5e2f1c-7a1d-4c2e-9f3a-5d6e7f8a9b0c'++const RUN: AutoresearchTrainingRunApi = {+ id: RUN_ID,+ pipeline: PIPELINE_ID,+ task_url: null,+ status: 'completed',+ iteration_count: 4,+ best_holdout_score: 0.812,+ summary: null,+ iterations: [+ { iteration_number: 0, status: 'kept', holdout_score: 0.74 },+ { iteration_number: 1, status: 'discarded', holdout_score: 0.71 },+ { iteration_number: 2, status: 'kept', holdout_score: 0.79 },+ { iteration_number: 3, status: 'kept', holdout_score: 0.812 },+ ],+ error: '',+ started_at: '2026-10-01T09:00:00Z',+ completed_at: '2026-10-01T09:42:00Z',+ created_at: '2026-10-01T09:00:00Z',+} as unknown as AutoresearchTrainingRunApi++function feature(name: string, importance: number, negative = false): FeatureImportanceApi {+ return {+ name,+ importance,+ direction: negative ? FeatureDirectionEnumApi.Negative : FeatureDirectionEnumApi.Positive,+ }+}++function makeModel(overrides: Partial<AutoresearchModelApi>): AutoresearchModelApi {+ return {+ id: 'model-run',+ pipeline: PIPELINE_ID,+ role: AutoresearchModelRoleEnumApi.Challenger,+ holdout_score: 0.812,+ source_training_run: RUN_ID,+ model_explanation: {+ method: 'Permutation importance on holdout',+ top_features: [+ feature('pageviews_last_7d', 0.31),+ feature('files_uploaded_last_30d', 0.22),+ feature('days_since_signup', 0.14, true),+ feature('invited_teammates', 0.09),+ ],+ },+ ...overrides,+ } as AutoresearchModelApi+}++const CHAMPION = makeModel({+ id: 'model-champion',+ role: AutoresearchModelRoleEnumApi.Champion,+ holdout_score: 0.834,+ source_training_run: 'run-older',+ model_explanation: {+ method: 'Permutation importance on holdout',+ top_features: [+ feature('pageviews_last_7d', 0.35),+ feature('files_uploaded_last_30d', 0.2),+ feature('dashboards_viewed_last_30d', 0.12),+ feature('days_since_signup', 0.08, true),+ ],+ },+})++// 520px is about the scene width next to the nav sidebar and an open side panel.+const WIDTH_CLASS = { narrow: 'w-[520px]', wide: 'w-[1100px]' }++function ExpandedRunRow({+ models,+ width,+}: {+ models: AutoresearchModelApi[]+ width: keyof typeof WIDTH_CLASS+}): JSX.Element {+ const logic = autoresearchPipelineLogic({ id: PIPELINE_ID })+ useMountedLogic(logic)+ useEffect(() => {+ logic.actions.loadModelsSuccess(models)+ if (logic.values.expandedRunId !== RUN_ID) {+ logic.actions.toggleRunArtifacts(RUN_ID)+ }+ }, [logic, models])+ return (+ <BindLogic logic={autoresearchPipelineLogic} props={{ id: PIPELINE_ID }}>+ <div className={WIDTH_CLASS[width]}>+ <TrainingRunRow run={RUN} />+ </div>+ </BindLogic>+ )+}++const meta: Meta<typeof ExpandedRunRow> = {+ title: 'Products/Autoresearch/Training run row',+ component: ExpandedRunRow,+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/autoresearch/:pipeline_id/training_runs/:id/artifacts/': {+ paths: ['features.sql', 'train.py', 'predict.py'],+ },+ },+ post: {+ '/api/projects/:team_id/autoresearch/:pipeline_id/training_runs/:id/artifacts/get/': [+ 404,+ { detail: 'Not found.' },+ ],+ },+ }),+ ],+ parameters: { testOptions: { waitForSelector: '.LemonCollapse' } },+}+export default meta+type Story = StoryObj<typeof ExpandedRunRow>++export const ComparedWithChampionWide: Story = {+ args: { models: [makeModel({}), CHAMPION], width: 'wide' },+}++export const ComparedWithChampionNarrow: Story = {+ args: { models: [makeModel({}), CHAMPION], width: 'narrow' },+}++export const RunProducedTheChampion: Story = {+ args: {+ models: [makeModel({ role: AutoresearchModelRoleEnumApi.Champion })],+ width: 'wide',+ },+}++export const RunModelWithoutImportances: Story = {+ args: { models: [makeModel({ model_explanation: {} }), CHAMPION], width: 'wide' },+}diff --git a/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsxindex ea909392bfbc..42205818d470 100644--- a/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx+++ b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx@@ -11,6 +11,7 @@ import { urls } from 'scenes/urls'import { autoresearchPipelineLogic, trainingRunProgress } from '../autoresearchPipelineLogic'import { type AutoresearchRunApi, AutoresearchTrainingRunApi } from '../generated/api.schemas'import { IterationTrail } from './IterationTrail'+import { RunFeatureComparison } from './RunFeatureComparison'// Derived from the field rather than the standalone enum: this pending/running/completed/failed// set is shared with another product, so the generated enum does not carry an autoresearch name.@@ -130,6 +131,14 @@ export function TrainingRunRow({ run }: { run: AutoresearchTrainingRunApi }): JS<div className="text-xs font-semibold text-muted uppercase tracking-wide">Iterations</div><IterationTrail iterations={run.iterations} /></div>+ {run.status === 'completed' && (+ <div className="space-y-2">+ <div className="text-xs font-semibold text-muted uppercase tracking-wide">+ What drives it+ </div>+ <RunFeatureComparison runId={run.id} />+ </div>+ )}{run.summary && (<div className="space-y-1"><div className="text-xs font-semibold text-muted uppercase tracking-wide">