: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): add precision, recall and a confusion matrix to accuracy (#114497)
posthog[bot]996ea248b64e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex fd04ba599e31..ca5652db478f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6505,13 +6505,17 @@ snapshots:products-autoresearch-lifecycle-strip--validated-champion--light:hash: v1.k794b7964.131ecc736b38defef5b8ba34fa9836f1d2d5132e1d109e4b995b9591a5d9255c.759giT71A_8sdMCqx-FasPgdZzZWHgRvaoUmqVtYYKwproducts-autoresearch-model-detail-scene--accuracy--narrow--dark:- hash: v1.k794b7964.474afbbef6390672bb4e56fbf5933057946c075c3b0817c3df920ebf4efa6cae.iitmJl1nGiexyocfoVJBleO0jsVpBHPfz9CRRvPwzqo+ hash: v1.k794b7964.3f8217187d3824bf7878aed9060ebd96a4afbbe3bd4dd57d6c50d040ad396780.d5Oe_Z7FJqsHeGA64EyYABDdWkPetbotTiGPnQV6U6kproducts-autoresearch-model-detail-scene--accuracy--narrow--light:- hash: v1.k794b7964.9fdda8cd699a6d2ae9e0c829ee5d4ad380d1ec5664e7793a27ccb85cb4f8416d.B3rYoEpl0eGNDcqdDlGNihDNe30T8Nea9nf0do0Yv_o+ hash: v1.k794b7964.c8eb64cb2728f6ee73094a5d2e5effdbdebb972cbe7a90e5942e153d8f625465.OQRwRbwNqDTXFmqHU6WfPJIsnTR0exRaoSyRf4-HNRwproducts-autoresearch-model-detail-scene--accuracy--wide--dark:- hash: v1.k794b7964.e3e30f0395d8b2531174b4d415fb3ba3789d69d4227eeb31fff97ef7a92fd2c1.JgJ0I_wqdXSubRfU9kIKLCrx2TNIsCO9c_asb6s0YCY+ hash: v1.k794b7964.0fd3e76c74910c5e0017cb1a687bdc23e16807c956eab7c9d38800b588d2dc9c.V7437wGvm0FwZf22kWHip3bJcTzZkedIl7aEz329Hhsproducts-autoresearch-model-detail-scene--accuracy--wide--light:- hash: v1.k794b7964.9df2881fa8b1ad8ae2965e4daf597ef8d2835fdf73ca1c3343f4ae337afeb4d0.-smEXkxUblLfr2j9NSD9vX2BgFpL1qqyogUb_4wlxaE+ hash: v1.k794b7964.937ed09f5202a79d41b2907a114a8d8a5479e9cd50ab992d5e1526244a026716.c8J1y77rve1oe6vz5ZMFqLIXEwMEiXbLMcbP_KoLkt4+ products-autoresearch-model-detail-scene--accuracy-before-precision-recall--wide--dark:+ hash: v1.k794b7964.0b5c8f601ca997bcc047ac9433320f97ded3d77587b5d9a1d17d4efc14fe067a.HmMZQj_A1QVaOYN24p6cCzBTWJ0dxBghBe4vwKTshnE+ products-autoresearch-model-detail-scene--accuracy-before-precision-recall--wide--light:+ hash: v1.k794b7964.cb4b85b471a78a1ad4c359c27692622fbf3bc29d133aa0d9a1c329b7eeba7723.AGhOQQd19cM-yzuU1A6HUYfsGLQf9gpLSuX1Y0OK8Boproducts-autoresearch-model-detail-scene--agent-research-narrow--narrow--dark:hash: v1.k794b7964.052f6d0dba654432d5f12d65bc0f91bc3e2de64334dac07e62d6cf730f154820.7cPMLn00EY67HPH6ikgGBUlULYPQSAMVKLyE_cR3uTsproducts-autoresearch-model-detail-scene--agent-research-narrow--narrow--light:diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.mdindex c7bd2356c752..10c5cbce2a12 100644--- a/products/autoresearch/backend/evaluation/AGENTS.md+++ b/products/autoresearch/backend/evaluation/AGENTS.md@@ -19,6 +19,8 @@ It is the only honest number in the product. A holdout AUC of 0.93 says the mode- **expected calibration error** (`_expected_calibration_error`, 10 equal-width bins) — whether "0.8" really means 80%; kept unchanged so old and new dates compare- **calibration bins** (`_quantile_calibration_bins`) — up to 10 bins cut at score quantiles, each with `n`, `mean_p_y` and `positive_rate`; equal scores share a bin. Equal-width bins put nearly every person in the first bin for a rare target, so read these instead- **lift@k** (`_lift_at_k`) — how much better than random the top slice is; ties at the boundary score are split fractionally so the number does not depend on row order+ - **average precision** — area under the precision-recall curve; null when the date has no positives+ - **confusion counts** (`confusion`, `_confusion_counts`) — `tp`, `fp`, `fn`, `tn`, `n_flagged`, `precision` and `recall` for three cutoffs: `top_10`, `top_20`, and `likely` (score at or above `LIKELY_THRESHOLD`). Top-k cutoffs flag every person tied at the boundary score, so the counts are whole people and `n_flagged` can be a little above k. `LIKELY_THRESHOLD` comes from `frontend/predictionSegmentThresholds.json`, the same file the frontend segments read- **weekday** — the ISO weekday of the prediction dateEvery model that emitted predictions on the date is scored, whatever its role now. Inference shadow-scores every model in the shadow set on the champion's people, and each records its own inference run, so their realized numbers land here. That is what makes challenger promotion decidable on evidence rather than on holdout alone. A shadow model's events carry the emitted role `shadow`.@@ -57,7 +59,7 @@ All the heavy work — the HogQL queries and the sklearn metrics — happens ins- **Backdated events are refused by scoring when the team sets `drop_events_older_than_seconds`**, so no inference run is recorded and validation has nothing to look for.- **A deleted model takes its evidence with it.** Its inference runs lose their model and drop out of the candidates, and its prediction events are not fetched. A model deleted mid-validation is recorded in the run's `per_model` as `deleted` and skipped for the model update, and its absence does not reopen the group.- **A completed date is never revisited.** An outcome event that reaches ClickHouse more than `OUTCOME_INGESTION_GRACE` after the window closed (an offline SDK buffer flushed days late) reads as a negative in the stored metrics.-- **Only the AUC and its interval need both classes.** An all-negative day still records Brier, calibration error, calibration bins, and lift, which is where calibration matters for a rare target.+- **Only the AUC and its interval need both classes.** An all-negative day still records Brier, calibration error, calibration bins, lift, and confusion counts, which is where calibration matters for a rare target.## Where the rest of the system meets this packagediff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.pyindex 9a5e15882452..90252a8730e0 100644--- a/products/autoresearch/backend/evaluation/online_validation.py+++ b/products/autoresearch/backend/evaluation/online_validation.py@@ -3,8 +3,9 @@ Online validation: join autoresearch_prediction events to realized target outcomafter the prediction horizon has elapsed.Computes per model: realized AUC with a 95% interval, Brier score, expected calibration-error (ECE), quantile calibration bins, mean predicted probability, and lift@k, for every-model that emitted predictions on a date.+error (ECE), quantile calibration bins, mean predicted probability, lift@k, average+precision, and confusion counts at three cutoffs, for every model that emitted predictions+on a date.Architecture:- Pure activity functions called by AutoresearchValidationWorkflow (Temporal)@@ -16,8 +17,10 @@ Architecture:say was emitted."""+import jsonimport mathfrom datetime import UTC, date, datetime, timedelta+from pathlib import Pathfrom typing import Anyfrom django.db import transaction@@ -620,6 +623,10 @@ def _query(# ── Metrics ────────────────────────────────────────────────────────────────────────+# The frontend reads the same file for PREDICTION_SEGMENT_THRESHOLDS, so the Likely cutoff cannot drift.+_SEGMENT_THRESHOLDS_PATH = Path(__file__).resolve().parents[2] / "frontend" / "predictionSegmentThresholds.json"+LIKELY_THRESHOLD: float = float(json.loads(_SEGMENT_THRESHOLDS_PATH.read_text())["high"])+def _compute_validation_metrics(predictions: dict[str, float],@@ -628,12 +635,12 @@ def _compute_validation_metrics(prediction_date: date,) -> dict[str, Any]:"""- AUC with its 95% interval, Brier score, ECE, quantile calibration bins, and lift@k- from scored predictions against realized labels.+ AUC with its 95% interval, Brier score, ECE, quantile calibration bins, lift@k,+ average precision, and confusion counts from scored predictions against realized labels.- Only the AUC and its interval need both classes. The other metrics are computed for a- single-class date too, because an all-negative day is exactly where calibration- matters for a rare target.+ Only the AUC and its interval need both classes, and average precision needs a positive.+ The other metrics are computed for a single-class date too, because an all-negative day+ is exactly where calibration matters for a rare target."""person_ids = list(predictions.keys())y_score = np.array([predictions[pid] for pid in person_ids], dtype=np.float64)@@ -655,7 +662,7 @@ def _compute_validation_metrics(metrics["mean_p_y"] = round(float(y_score.mean()), 4)# Deferred to keep the heavy dependency off the import path.- from sklearn.metrics import brier_score_loss, roc_auc_score # noqa: PLC0415+ from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score # noqa: PLC0415if n_pos == 0 or n_neg == 0:metrics["warning"] = "single_class_no_auc"@@ -670,9 +677,46 @@ def _compute_validation_metrics(metrics["calibration_bins"] = _quantile_calibration_bins(y_true, y_score)metrics["lift_at_10"] = round(_lift_at_k(y_true, y_score, k=0.10), 4)metrics["lift_at_20"] = round(_lift_at_k(y_true, y_score, k=0.20), 4)+ metrics["average_precision"] = round(float(average_precision_score(y_true, y_score)), 4) if n_pos > 0 else None+ metrics["confusion"] = {+ "top_10": _confusion_counts(y_true, _top_k_flags(y_score, k=0.10)),+ "top_20": _confusion_counts(y_true, _top_k_flags(y_score, k=0.20)),+ "likely": _confusion_counts(y_true, y_score >= LIKELY_THRESHOLD),+ }return metrics+def _top_k_flags(y_score: np.ndarray, k: float) -> np.ndarray:+ """+ Flag the top-k fraction of scored users, plus every user tied with the last one.++ The counts stay whole people and do not depend on row order, so the flagged count can+ be a little above k. ``_lift_at_k`` splits the tie fractionally instead.+ """+ cutoff = max(1, math.ceil(len(y_score) * k))+ boundary = float(np.sort(y_score)[::-1][cutoff - 1])+ return y_score >= boundary+++def _confusion_counts(y_true: np.ndarray, flagged: np.ndarray) -> dict[str, Any]:+ """Confusion counts for one cutoff. Precision or recall is None when its denominator is 0."""+ positive = y_true == 1+ tp = int((flagged & positive).sum())+ n_flagged = int(flagged.sum())+ n_positive = int(positive.sum())+ fp = n_flagged - tp+ fn = n_positive - tp+ return {+ "tp": tp,+ "fp": fp,+ "fn": fn,+ "tn": len(y_true) - tp - fp - fn,+ "n_flagged": n_flagged,+ "precision": round(tp / n_flagged, 4) if n_flagged else None,+ "recall": round(tp / n_positive, 4) if n_positive else None,+ }++def _expected_calibration_error(y_true: np.ndarray, y_score: np.ndarray, n_bins: int = 10) -> float:"""Expected Calibration Error (ECE): fraction-weighted mean absolute differencediff --git a/products/autoresearch/backend/evaluation/test_online_validation.py b/products/autoresearch/backend/evaluation/test_online_validation.pyindex fa178bd5d07f..f066a25f4aab 100644--- a/products/autoresearch/backend/evaluation/test_online_validation.py+++ b/products/autoresearch/backend/evaluation/test_online_validation.py@@ -81,6 +81,57 @@ class TestComputeValidationMetrics(SimpleTestCase):assert 0.0 <= metrics["brier_score"] <= 1.0assert 0.0 <= metrics["calibration_error"] <= 1.0assert "lift_at_10" in metrics+ for counts in metrics["confusion"].values():+ assert counts["tp"] + counts["fp"] + counts["fn"] + counts["tn"] == 2+ if labels:+ assert metrics["average_precision"] == 1.0+ assert metrics["confusion"]["likely"]["recall"] == 0.5+ else:+ assert metrics["average_precision"] is None+ assert metrics["confusion"]["likely"] == {+ "tp": 0,+ "fp": 1,+ "fn": 0,+ "tn": 1,+ "n_flagged": 1,+ "precision": 0.0,+ "recall": None,+ }++ def test_confusion_counts_flag_every_tie_at_the_top_k_boundary(self):+ scores = [0.9, 0.7, 0.7, 0.7, 0.5, 0.3, 0.2, 0.1, 0.1, 0.05]+ preds = {f"user-{i}": score for i, score in enumerate(scores)}+ positives = frozenset(["user-0", "user-3", "user-5"])++ metrics = _compute_validation_metrics(preds, positives, prediction_date=date(2026, 9, 1))+ reversed_metrics = _compute_validation_metrics(+ dict(reversed(list(preds.items()))), positives, prediction_date=date(2026, 9, 1)+ )++ assert metrics["confusion"] == reversed_metrics["confusion"]+ assert metrics["confusion"]["top_10"] == {+ "tp": 1,+ "fp": 0,+ "fn": 2,+ "tn": 7,+ "n_flagged": 1,+ "precision": 1.0,+ "recall": 0.3333,+ }+ assert metrics["confusion"]["top_20"] == {+ "tp": 2,+ "fp": 2,+ "fn": 1,+ "tn": 5,+ "n_flagged": 4,+ "precision": 0.5,+ "recall": 0.6667,+ }+ assert metrics["confusion"]["likely"] == metrics["confusion"]["top_20"]+ for counts in metrics["confusion"].values():+ assert counts["tp"] + counts["fp"] + counts["fn"] + counts["tn"] == metrics["n_scored"]+ assert counts["tp"] + counts["fn"] == metrics["n_positive"]+ assert 0.0 < metrics["average_precision"] <= 1.0class TestAucConfidenceInterval(SimpleTestCase):diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex 64ed0fe3a971..c00432ee4801 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -40,6 +40,7 @@ from ..dataset.validation import (validate_pipeline_definition as _validate_pipeline_definition,)from ..evaluation.history import latest_validation_runs, realized_auc_trends+from ..evaluation.online_validation import LIKELY_THRESHOLD as LIKELY_THRESHOLDfrom ..models import (AutoresearchIteration,AutoresearchModel,@@ -65,6 +66,8 @@ from .contracts import (ArtifactStorageUnavailable,AutoresearchConflict,CalibrationBin,+ ConfusionByCutoff,+ ConfusionCounts,InvalidArtifactPath as InvalidArtifactPath,InvalidTarget,Iteration,@@ -1033,6 +1036,7 @@ def online_performance(for model_id, m in sorted((run.metrics.get("per_model") or {}).items()):model_uuid = UUID(model_id)bins = m.get("calibration_bins")+ confusion = m.get("confusion")rows.append(OnlinePerformanceRow(validation_run_id=run.id,@@ -1053,6 +1057,12 @@ def online_performance(calibration_error=m.get("calibration_error"),lift_at_10=m.get("lift_at_10"),lift_at_20=m.get("lift_at_20"),+ average_precision=m.get("average_precision"),+ confusion=ConfusionByCutoff(+ **{cutoff: ConfusionCounts(**counts) for cutoff, counts in confusion.items()}+ )+ if confusion is not None+ else None,calibration_bins=[CalibrationBin(**b) for b in bins] if bins is not None else None,warning=m.get("warning"),validated_at=run.completed_at,diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.pyindex 55ab66c3bfec..9814db7bba9b 100644--- a/products/autoresearch/backend/facade/contracts.py+++ b/products/autoresearch/backend/facade/contracts.py@@ -378,6 +378,24 @@ class CalibrationBin:positive_rate: float+@dataclass(frozen=True)+class ConfusionCounts:+ tp: int+ fp: int+ fn: int+ tn: int+ n_flagged: int+ precision: float | None+ recall: float | None+++@dataclass(frozen=True)+class ConfusionByCutoff:+ top_10: ConfusionCounts+ top_20: ConfusionCounts+ likely: ConfusionCounts++@dataclass(frozen=True)class OnlinePerformanceRow:"""One model's realized metrics for one validated prediction date."""@@ -400,6 +418,8 @@ class OnlinePerformanceRow:calibration_error: float | Nonelift_at_10: float | Nonelift_at_20: float | None+ average_precision: float | None+ confusion: ConfusionByCutoff | Nonecalibration_bins: list[CalibrationBin] | Nonewarning: str | Nonevalidated_at: datetime | Nonediff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.pyindex f73d1228c539..8334ed343c6f 100644--- a/products/autoresearch/backend/presentation/views/serializers.py+++ b/products/autoresearch/backend/presentation/views/serializers.py@@ -913,7 +913,11 @@ class AutoresearchModelSerializer(DataclassSerializer):)metrics = MetricsBundleField(required=False,- help_text="Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.",+ help_text=(+ "Extended metrics bundle. Holds the holdout AUC from training, and under 'realized' the newest "+ "validated date's online metrics: realized AUC, Brier score, calibration error and bins, lift@k, "+ "average precision, confusion counts at top 10%, top 20% and Likely, base rate, and row counts."+ ),)source_training_run = serializers.UUIDField(read_only=True,@@ -1269,6 +1273,37 @@ class CalibrationBinSerializer(serializers.Serializer):)+class ConfusionCountsSerializer(serializers.Serializer):+ tp = serializers.IntegerField(help_text="True positives: flagged users who did the target event.")+ fp = serializers.IntegerField(help_text="False positives: flagged users who did not do the target event.")+ fn = serializers.IntegerField(help_text="False negatives: users not flagged who did the target event.")+ tn = serializers.IntegerField(help_text="True negatives: users not flagged who did not do the target event.")+ n_flagged = serializers.IntegerField(+ help_text=(+ "Number of users the cutoff flagged (tp + fp). Top-k cutoffs flag every user tied at the "+ "boundary score, so this can be a little above k."+ )+ )+ precision = serializers.FloatField(+ allow_null=True,+ help_text="tp / n_flagged: share of flagged users who did the target event. Null when no user was flagged.",+ )+ recall = serializers.FloatField(+ allow_null=True,+ help_text=(+ "tp / (tp + fn): share of users who did the target event that the cutoff flagged. Null when no user did it."+ ),+ )+++class ConfusionByCutoffSerializer(serializers.Serializer):+ top_10 = ConfusionCountsSerializer(help_text="Counts when the top 10% of users by score are flagged.")+ top_20 = ConfusionCountsSerializer(help_text="Counts when the top 20% of users by score are flagged.")+ likely = ConfusionCountsSerializer(+ help_text=f"Counts when users with a score of {api.LIKELY_THRESHOLD} or higher (the Likely segment) are flagged."+ )++class OnlinePerformanceRowSerializer(serializers.Serializer):validation_run_id = serializers.UUIDField(help_text="UUID of the validation run that recorded these metrics.")prediction_date = serializers.DateField(help_text="Date the predictions were made for (UTC).")@@ -1319,6 +1354,21 @@ class OnlinePerformanceRowSerializer(serializers.Serializer):lift_at_20 = serializers.FloatField(allow_null=True, help_text="Positives in the top 20% by score, relative to a random 20%.")+ average_precision = serializers.FloatField(+ allow_null=True,+ help_text=(+ "Average precision: area under the precision-recall curve. Higher is better, and a random model "+ "scores about base_rate. Null when no scored user did the target event, or for dates validated "+ "before this metric existed."+ ),+ )+ confusion = ConfusionByCutoffSerializer(+ allow_null=True,+ help_text=(+ "Confusion counts, precision and recall at three cutoffs: top 10%, top 20%, and the Likely segment. "+ "Null for dates validated before this metric existed."+ ),+ )calibration_bins = CalibrationBinSerializer(many=True,allow_null=True,diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pyindex 5440d0143bc2..bb17cbcac99a 100644--- a/products/autoresearch/backend/tests/test_api.py+++ b/products/autoresearch/backend/tests/test_api.py@@ -1072,6 +1072,11 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):"realized_auc_ci_low": 0.65,"realized_auc_ci_high": 0.75,"calibration_bins": [{"n": 10, "mean_p_y": 0.4, "positive_rate": 0.2}],+ "average_precision": 0.5,+ "confusion": {+ cutoff: {"tp": 1, "fp": 0, "fn": 1, "tn": 8, "n_flagged": 1, "precision": 1.0, "recall": 0.5}+ for cutoff in ("top_10", "top_20", "likely")+ },}latest = validation("2026-09-01", {str(former.pk): populated}, completed_minutes_ago=20)validation(@@ -1096,7 +1101,18 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):0.75,)assert rows[1]["calibration_bins"] == [{"n": 10, "mean_p_y": 0.4, "positive_rate": 0.2}]+ assert rows[1]["average_precision"] == 0.5+ assert rows[1]["confusion"]["likely"] == {+ "tp": 1,+ "fp": 0,+ "fn": 1,+ "tn": 8,+ "n_flagged": 1,+ "precision": 1.0,+ "recall": 0.5,+ }assert rows[0]["realized_auc_ci_low"] is None and rows[0]["calibration_bins"] is None+ assert rows[0]["average_precision"] is None and rows[0]["confusion"] is Nonelimited = self.client.get(f"{self.base_url}/{pipeline.id}/online_performance/?limit=1").json()["rows"]assert [r["prediction_date"] for r in limited] == ["2026-09-03"]diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.mdindex ebcf77942e13..32770692077a 100644--- a/products/autoresearch/frontend/AGENTS.md+++ b/products/autoresearch/frontend/AGENTS.md@@ -20,7 +20,7 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st| `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. |+| `predictionSegments.ts` | The likelihood segment thresholds, from `predictionSegmentThresholds.json`. Online validation reads the same file for its Likely cutoff. || `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. |@@ -51,7 +51,7 @@ Follow `frontend/src/AGENTS.md` — it applies to product frontends too.- TypeScript with explicit return types; Tailwind utilities rather than inline styles.- Reuse Lemon / quill components instead of hand-rolling tables, badges, or tags.- Any button that fires a request must guard against double-submission — `loading` / `disabledReason` on `LemonButton`, reset on both success and error paths. The lifecycle actions here (train, score, archive, pause, resume) are all network calls, and several are expensive: firing `train` twice starts two sandbox agent runs and spends the budget twice.-- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, `autoresearch model advanced opened`, `autoresearch model created` (with `action`: `start_training` or `save_draft`), and `autoresearch model training started` / `training start failed`. The detail logic captures `autoresearch model tab changed` (with `tab`) when a person picks a tab, `autoresearch model experiment log filter changed` (with `filter`), `autoresearch model search point clicked` (with `run_id`, `iteration_number`, `status`) and `autoresearch model suggestion sent` (with `priority`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.+- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, `autoresearch model advanced opened`, `autoresearch model created` (with `action`: `start_training` or `save_draft`), and `autoresearch model training started` / `training start failed`. The detail logic captures `autoresearch model tab changed` (with `tab`) when a person picks a tab, `autoresearch model experiment log filter changed` (with `filter`), `autoresearch model accuracy cutoff changed` (with `cutoff`), `autoresearch model search point clicked` (with `run_id`, `iteration_number`, `status`) and `autoresearch model suggestion sent` (with `priority`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.## Copydiff --git a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsxindex 3d4a7d678054..1942a5fc2626 100644--- a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx+++ b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx@@ -141,6 +141,12 @@ const onlinePerformance = {calibration_error: 0.04,lift_at_10: 3.4,lift_at_20: 2.6,+ average_precision: 0.21,+ confusion: {+ top_10: { tp: 480, fp: 4220, fn: 930, tn: 41370, n_flagged: 4700, precision: 0.1021, recall: 0.3404 },+ top_20: { tp: 735, fp: 8665, fn: 675, tn: 36925, n_flagged: 9400, precision: 0.0782, recall: 0.5213 },+ likely: { tp: 0, fp: 0, fn: 1410, tn: 45590, n_flagged: 0, precision: null, recall: 0 },+ },calibration_bins: [{ n: 37600, mean_p_y: 0.01, positive_rate: 0.008 },{ n: 4700, mean_p_y: 0.08, positive_rate: 0.07 },@@ -270,3 +276,19 @@ export const Accuracy: Story = {testOptions: { viewportWidths: ['wide', 'narrow'] },},}++export const AccuracyBeforePrecisionRecall: Story = {+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/autoresearch/${PIPELINE_ID}/online_performance/`]: {+ rows: onlinePerformance.rows.map((row) => ({ ...row, average_precision: null, confusion: null })),+ },+ },+ }),+ ],+ parameters: {+ pageUrl: `${urls.autoresearchPipeline(PIPELINE_ID)}?tab=accuracy`,+ testOptions: { viewportWidths: ['wide'] },+ },+}diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.tsindex d2871f6a5504..09695a4afd21 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts@@ -56,12 +56,16 @@ import {type ModelExplanationFieldApi,type OnlinePerformanceRowApi,} from './generated/api.schemas'+import type { ConfusionByCutoffApi } from './generated/api.schemas'import {+ type AccuracyCutoff,+ type PooledConfusion,RealizedAucPoint,SegmentCalibration,calibrationBySegment,firstCheckDate,latestChampionRow,+ pooledConfusion,realizedAucSeries,validatedPredictionDates,} from './onlinePerformance'@@ -267,6 +271,7 @@ export interface autoresearchPipelineLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogiccurrentProjectId: number | null // projectLogiccurrentTeamId: number | null // teamLogic+ accuracyCutoff: AccuracyCutoffactiveScoreRun: AutoresearchRunApi | nullactiveTab: AutoresearchPipelineTabagentNotes: AgentNotes | null@@ -275,6 +280,7 @@ export interface autoresearchPipelineLogicValues {artifactsByRunLoading: booleanbreadcrumbs: Breadcrumb[]champion: AutoresearchModelApi | null+ championConfusion: PooledConfusion | nulldailyVolume: DailyVolumePoint[] | nulldailyVolumeError: booleandailyVolumeLoading: boolean@@ -630,6 +636,9 @@ export interface autoresearchPipelineLogicActions {searchPointClicked: (point: SearchPoint) => {point: SearchPoint}+ setAccuracyCutoff: (cutoff: AccuracyCutoff) => {+ cutoff: keyof ConfusionByCutoffApi+ }setActiveScoreRun: (run: AutoresearchRunApi | null) => {run: AutoresearchRunApi | null}@@ -743,6 +752,10 @@ export interface autoresearchPipelineLogicMeta {latestChampionPerformance: (onlinePerformance: OnlinePerformanceRowApi[]) => OnlinePerformanceRowApi | nullrealizedAucPoints: (onlinePerformance: OnlinePerformanceRowApi[]) => RealizedAucPoint[]segmentCalibration: (latestChampionPerformance: OnlinePerformanceRowApi | null) => SegmentCalibration[]+ championConfusion: (+ onlinePerformance: OnlinePerformanceRowApi[],+ accuracyCutoff: keyof ConfusionByCutoffApi+ ) => PooledConfusion | nullfirstCheck: (runs: AutoresearchRunApi[], pipeline: AutoresearchPipelineApi | null) => dayjs.Dayjs | nullprobabilityHistogram: (probabilityDistribution: ProbabilityBucket[] | null) => ProbabilityBucket[] | nullhasLiveTrainingRun: (trainingRuns: AutoresearchTrainingRunApi[]) => boolean@@ -786,6 +799,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([actions({setActiveTab: (tab: AutoresearchPipelineTab) => ({ tab }),setPredictionsPeopleView: (view: PredictionsPeopleView) => ({ view }),+ setAccuracyCutoff: (cutoff: AccuracyCutoff) => ({ cutoff }),setTabFromUrl: (tab: AutoresearchPipelineTab | null) => ({ tab }),loadDetail: true,toggleRunArtifacts: (runId: string) => ({ runId }),@@ -825,6 +839,12 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([setPredictionsPeopleView: (_, { view }) => view,},],+ accuracyCutoff: [+ 'top_10' as AccuracyCutoff,+ {+ setAccuracyCutoff: (_, { cutoff }) => cutoff,+ },+ ],activeScoreRun: [null as AutoresearchRunApi | null,{@@ -1296,6 +1316,11 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([(latestChampionPerformance: OnlinePerformanceRowApi | null): SegmentCalibration[] =>calibrationBySegment(latestChampionPerformance?.calibration_bins ?? []),],+ championConfusion: [+ (s) => [s.onlinePerformance, s.accuracyCutoff],+ (onlinePerformance: OnlinePerformanceRowApi[], accuracyCutoff: AccuracyCutoff): PooledConfusion | null =>+ pooledConfusion(onlinePerformance, accuracyCutoff),+ ],firstCheck: [(s) => [s.runs, s.pipeline],(runs: AutoresearchRunApi[], pipeline: AutoresearchPipelineApi | null): dayjs.Dayjs | null =>@@ -1581,6 +1606,9 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([setPredictionsPeopleView: ({ view }) => {posthog.capture('autoresearch model predictions view changed', { pipeline_id: props.id, view })},+ setAccuracyCutoff: ({ cutoff }) => {+ posthog.capture('autoresearch model accuracy cutoff changed', { pipeline_id: props.id, cutoff })+ },saveSegmentCohort: async ({ segment }) => {const { pipeline, currentProjectId } = valuesconst definition = PREDICTION_SEGMENTS.find(({ key }) => key === segment)diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.tsindex 795307688ec1..3711637d7531 100644--- a/products/autoresearch/frontend/generated/api.schemas.ts+++ b/products/autoresearch/frontend/generated/api.schemas.ts@@ -416,7 +416,7 @@ export interface ModelExplanationFieldApi {export type AutoresearchModelApiModelRecipe = { [key: string]: unknown }/**- * Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.+ * Extended metrics bundle. Holds the holdout AUC from training, and under 'realized' the newest validated date's online metrics: realized AUC, Brier score, calibration error and bins, lift@k, average precision, confusion counts at top 10%, top 20% and Likely, base rate, and row counts.*/export type AutoresearchModelApiMetrics = { [key: string]: unknown }@@ -452,7 +452,7 @@ export interface AutoresearchModelApi {* @nullable*/calibration_error?: number | null- /** Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts. */+ /** Extended metrics bundle. Holds the holdout AUC from training, and under 'realized' the newest validated date's online metrics: realized AUC, Brier score, calibration error and bins, lift@k, average precision, confusion counts at top 10%, top 20% and Likely, base rate, and row counts. */metrics?: AutoresearchModelApiMetrics/*** Training run that produced this model. Read that run's artifact bundle to reuse the champion's train.py and features.sql as a starting point. Null for legacy models.@@ -1413,6 +1413,38 @@ export interface PatchedAutoresearchPipelineCreateApi {output_person_property?: string}+export interface ConfusionCountsApi {+ /** True positives: flagged users who did the target event. */+ tp: number+ /** False positives: flagged users who did not do the target event. */+ fp: number+ /** False negatives: users not flagged who did the target event. */+ fn: number+ /** True negatives: users not flagged who did not do the target event. */+ tn: number+ /** Number of users the cutoff flagged (tp + fp). Top-k cutoffs flag every user tied at the boundary score, so this can be a little above k. */+ n_flagged: number+ /**+ * tp / n_flagged: share of flagged users who did the target event. Null when no user was flagged.+ * @nullable+ */+ precision: number | null+ /**+ * tp / (tp + fn): share of users who did the target event that the cutoff flagged. Null when no user did it.+ * @nullable+ */+ recall: number | null+}++export interface ConfusionByCutoffApi {+ /** Counts when the top 10% of users by score are flagged. */+ top_10: ConfusionCountsApi+ /** Counts when the top 20% of users by score are flagged. */+ top_20: ConfusionCountsApi+ /** Counts when users with a score of 0.6 or higher (the Likely segment) are flagged. */+ likely: ConfusionCountsApi+}+export interface CalibrationBinApi {/** Number of scored users in this bin. */n: number@@ -1483,6 +1515,13 @@ export interface OnlinePerformanceRowApi {* @nullable*/lift_at_20: number | null+ /**+ * Average precision: area under the precision-recall curve. Higher is better, and a random model scores about base_rate. Null when no scored user did the target event, or for dates validated before this metric existed.+ * @nullable+ */+ average_precision: number | null+ /** Confusion counts, precision and recall at three cutoffs: top 10%, top 20%, and the Likely segment. Null for dates validated before this metric existed. */+ confusion: ConfusionByCutoffApi | null/*** Calibration table with up to 10 bins cut at score quantiles, lowest scores first. Users with equal scores share a bin, so heavy ties give fewer bins. Null for dates validated before this metric existed.* @nullablediff --git a/products/autoresearch/frontend/onlinePerformance.test.ts b/products/autoresearch/frontend/onlinePerformance.test.tsindex f87544b23e9b..01c33900051d 100644--- a/products/autoresearch/frontend/onlinePerformance.test.ts+++ b/products/autoresearch/frontend/onlinePerformance.test.ts@@ -1,5 +1,5 @@-import { AutoresearchRunApi, OnlinePerformanceRowApi } from './generated/api.schemas'-import { calibrationBySegment, realizedAucSeries, validatedPredictionDates } from './onlinePerformance'+import { AutoresearchRunApi, ConfusionByCutoffApi, OnlinePerformanceRowApi } from './generated/api.schemas'+import { calibrationBySegment, pooledConfusion, realizedAucSeries, validatedPredictionDates } from './onlinePerformance'function row(overrides: Partial<OnlinePerformanceRowApi>): OnlinePerformanceRowApi {return {@@ -12,6 +12,11 @@ function row(overrides: Partial<OnlinePerformanceRowApi>): OnlinePerformanceRowA} as OnlinePerformanceRowApi}+function counts(tp: number, fp: number, fn: number, tn: number): ConfusionByCutoffApi {+ const cutoff = { tp, fp, fn, tn, n_flagged: tp + fp, precision: null, recall: null }+ return { top_10: cutoff, top_20: cutoff, likely: { ...cutoff, tp: 0, fp: 0, n_flagged: 0, tn: tn + tp + fp } }+}+describe('onlinePerformance', () => {test('calibrationBySegment weights each bin by its people and drops empty segments', () => {const segments = calibrationBySegment([@@ -42,6 +47,36 @@ describe('onlinePerformance', () => {])})+ test('pooledConfusion sums the current champion dates and counts pre-change dates apart', () => {+ const rows = [+ row({ prediction_date: '2026-02-13', model_id: 'new', confusion: counts(3, 1, 2, 94) }),+ row({+ prediction_date: '2026-02-13',+ model_id: 'shadow',+ emitted_role: 'shadow',+ confusion: counts(9, 0, 0, 91),+ }),+ row({ prediction_date: '2026-02-12', model_id: 'new', confusion: counts(1, 3, 2, 94) }),+ row({ prediction_date: '2026-02-11', model_id: 'new', confusion: null }),+ row({ prediction_date: '2026-02-10', model_id: 'old', confusion: counts(9, 0, 0, 91) }),+ ]++ expect(pooledConfusion(rows, 'top_10')).toEqual({+ tp: 4,+ fp: 4,+ fn: 4,+ tn: 188,+ flagged: 8,+ precision: 0.5,+ recall: 0.5,+ firstDate: '2026-02-12',+ lastDate: '2026-02-13',+ datesWithoutCounts: 1,+ })+ expect(pooledConfusion(rows, 'likely')).toMatchObject({ flagged: 0, precision: null, recall: 0 })+ expect(pooledConfusion([row({ model_id: 'new', confusion: null })], 'top_10')).toBeNull()+ })+test('validatedPredictionDates counts only completed validation runs that scored a model', () => {const scored = { per_model: { champion: { n_scored: 100 } } }const runs = [diff --git a/products/autoresearch/frontend/onlinePerformance.ts b/products/autoresearch/frontend/onlinePerformance.tsindex 00c79a6b3fd4..392e8195b8e8 100644--- a/products/autoresearch/frontend/onlinePerformance.ts+++ b/products/autoresearch/frontend/onlinePerformance.ts@@ -1,8 +1,18 @@import { dayjs } from 'lib/dayjs'-import { AutoresearchRunApi, CalibrationBinApi, OnlinePerformanceRowApi } from './generated/api.schemas'+import {+ AutoresearchRunApi,+ CalibrationBinApi,+ ConfusionByCutoffApi,+ OnlinePerformanceRowApi,+} from './generated/api.schemas'import { modelQuality } from './modelQuality'-import { PREDICTION_SEGMENTS, PredictionSegmentDefinition, predictionSegmentFor } from './predictionSegments'+import {+ PREDICTION_SEGMENTS,+ PREDICTION_SEGMENT_THRESHOLDS,+ PredictionSegmentDefinition,+ predictionSegmentFor,+} from './predictionSegments'export interface RealizedAucPoint {date: string@@ -20,6 +30,29 @@ export interface SegmentCalibration {actual: number}+export type AccuracyCutoff = keyof ConfusionByCutoffApi++export const ACCURACY_CUTOFFS: { key: AccuracyCutoff; label: string }[] = [+ { key: 'top_10', label: 'Top 10%' },+ { key: 'top_20', label: 'Top 20%' },+ { key: 'likely', label: 'Likely' },+]++/** Confusion counts of one cutoff, summed over the champion's checked dates that have them. */+export interface PooledConfusion {+ tp: number+ fp: number+ fn: number+ tn: number+ flagged: number+ precision: number | null+ recall: number | null+ firstDate: string+ lastDate: string+ /** Champion dates shown on the tab that were checked before confusion counts existed. */+ datesWithoutCounts: number+}+export function percent(value: number): string {return `${(value * 100).toFixed(1)}%`}@@ -95,6 +128,69 @@ export function calibrationBySegment(bins: CalibrationBinApi[]): SegmentCalibrat})}+/**+ * Sum one cutoff's confusion counts over the matured dates of the current champion. Rows checked+ * before confusion counts existed have none, so they are counted apart instead of read as zeros.+ */+export function pooledConfusion(rows: OnlinePerformanceRowApi[], cutoff: AccuracyCutoff): PooledConfusion | null {+ const latest = latestChampionRow(rows)+ if (!latest) {+ return null+ }+ const championRows = rows.filter((row) => row.model_id === latest.model_id && row.emitted_role === 'champion')+ const withCounts = championRows.filter((row) => row.confusion != null)+ if (withCounts.length === 0) {+ return null+ }+ const total = { tp: 0, fp: 0, fn: 0, tn: 0 }+ for (const row of withCounts) {+ const counts = (row.confusion as ConfusionByCutoffApi)[cutoff]+ total.tp += counts.tp+ total.fp += counts.fp+ total.fn += counts.fn+ total.tn += counts.tn+ }+ const flagged = total.tp + total.fp+ const positives = total.tp + total.fn+ const dates = withCounts.map((row) => row.prediction_date).sort()+ return {+ ...total,+ flagged,+ precision: flagged > 0 ? total.tp / flagged : null,+ recall: positives > 0 ? total.tp / positives : null,+ firstDate: dates[0],+ lastDate: dates[dates.length - 1],+ datesWithoutCounts: championRows.length - withCounts.length,+ }+}++/** The group of people a cutoff flags, in words that fit "Of {group}, ...". */+function cutoffGroup(cutoff: AccuracyCutoff): string {+ switch (cutoff) {+ case 'top_10':+ return 'the top 10% the model flagged'+ case 'top_20':+ return 'the top 20% the model flagged'+ case 'likely':+ return `the people the model scored ${PREDICTION_SEGMENT_THRESHOLDS.high * 100}% or higher`+ }+}++/** Precision and recall in plain words. Null when the cutoff flagged nobody. */+export function precisionRecallSentence(+ confusion: PooledConfusion,+ cutoff: AccuracyCutoff,+ target: string+): string | null {+ if (confusion.precision == null) {+ return null+ }+ const precision = `Of ${cutoffGroup(cutoff)}, ${percent(confusion.precision)} did ${target}.`+ return confusion.recall != null+ ? `${precision} They include ${percent(confusion.recall)} of everyone who did.`+ : `${precision} No one did ${target} in this period.`+}+/** 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'>[],diff --git a/products/autoresearch/frontend/pipeline/ConfusionMatrixCard.tsx b/products/autoresearch/frontend/pipeline/ConfusionMatrixCard.tsxnew file mode 100644index 000000000000..2cadbcee35e7--- /dev/null+++ b/products/autoresearch/frontend/pipeline/ConfusionMatrixCard.tsx@@ -0,0 +1,104 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonSegmentedButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { ACCURACY_CUTOFFS, PooledConfusion, percent } from '../onlinePerformance'+import { PREDICTION_SEGMENT_THRESHOLDS } from '../predictionSegments'+import { MetricCard } from './MetricCard'++function dateRange({ firstDate, lastDate }: PooledConfusion): string {+ const last = dayjs(lastDate).format('MMM D, YYYY')+ return firstDate === lastDate ? last : `${dayjs(firstDate).format('MMM D')} to ${last}`+}++function Cell({ count, label }: { count: number; label: string }): JSX.Element {+ return (+ <td className="border p-2 text-right">+ <div className="text-base font-semibold tabular-nums">{count.toLocaleString()}</div>+ <div className="text-xs text-muted">{label}</div>+ </td>+ )+}++/** People the champion flagged at the picked cutoff against what they really did, over the checked dates. */+export function ConfusionMatrixCard(): JSX.Element {+ const { pipeline, accuracyCutoff, championConfusion: confusion } = useValues(autoresearchPipelineLogic)+ const { setAccuracyCutoff } = useActions(autoresearchPipelineLogic)+ const target = pipeline?.target_event ?? 'the target event'++ return (+ <section className="space-y-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-sm font-semibold mb-0">+ Who the model flagged{confusion ? `, ${dateRange(confusion)}` : ''}+ </h3>+ <LemonSegmentedButton+ size="small"+ value={accuracyCutoff}+ onChange={setAccuracyCutoff}+ options={ACCURACY_CUTOFFS.map(({ key, label }) => ({ value: key, label }))}+ data-attr="autoresearch-model-accuracy-cutoff"+ />+ </div>+ {!confusion ? (+ <p className="text-sm text-muted mb-0">+ Precision and recall start from the next checked date. Dates checked before that have no counts.+ </p>+ ) : (+ <>+ {confusion.datesWithoutCounts > 0 && (+ <p className="text-xs text-muted mb-0">+ Precision and recall start from {dayjs(confusion.firstDate).format('MMM D, YYYY')}. Older+ checked dates have no counts.+ </p>+ )}+ {confusion.flagged === 0 ? (+ <LemonBanner type="info">+ No one scored {PREDICTION_SEGMENT_THRESHOLDS.high * 100}% or higher in this period. Pick Top+ 10% to see how the people with the highest scores did.+ </LemonBanner>+ ) : (+ <div className="flex flex-wrap items-start gap-4">+ <table className="text-sm border-collapse">+ <thead>+ <tr>+ <th />+ <th className="p-2 text-right font-semibold">Did {target}</th>+ <th className="p-2 text-right font-semibold">Didn't</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <th className="p-2 text-left font-semibold">Flagged</th>+ <Cell count={confusion.tp} label="Correct" />+ <Cell count={confusion.fp} label="False alarm" />+ </tr>+ <tr>+ <th className="p-2 text-left font-semibold">Not flagged</th>+ <Cell count={confusion.fn} label="Missed" />+ <Cell count={confusion.tn} label="Correct" />+ </tr>+ </tbody>+ </table>+ <div className="grid grid-cols-2 gap-2 min-w-60">+ <MetricCard+ label="Hit rate"+ value={confusion.precision != null ? percent(confusion.precision) : '—'}+ tooltip={`Precision: the share of flagged people who did ${target}.`}+ />+ <MetricCard+ label="Coverage"+ value={confusion.recall != null ? percent(confusion.recall) : '—'}+ tooltip={`Recall: the share of everyone who did ${target} that the model flagged.`}+ />+ </div>+ </div>+ )}+ </>+ )}+ </section>+ )+}diff --git a/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx b/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsxindex 200c22faedc5..954657eb34a8 100644--- a/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx+++ b/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx@@ -7,7 +7,8 @@ import { dayjs } from 'lib/dayjs'import { pluralize } from 'lib/utils/strings'import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'-import { accuracyHeadline, rankingSentence } from '../onlinePerformance'+import { accuracyHeadline, percent, precisionRecallSentence, rankingSentence } from '../onlinePerformance'+import { ConfusionMatrixCard } from './ConfusionMatrixCard'import { EmptyTab } from './EmptyTab'import { RealizedAucChart } from './RealizedAucChart'import { ScoreNowButton } from './ScoreNowButton'@@ -23,6 +24,10 @@ function fmt(value: number | null, decimals = 3): string {return value != null ? value.toFixed(decimals) : '—'}+function fmtPercent(value: number | null | undefined): string {+ return value != null ? percent(value) : '—'+}+function NotCheckedYet(): JSX.Element {const { pipeline, firstCheck } = useValues(autoresearchPipelineLogic)const horizon = pluralize(pipeline?.horizon_days ?? 0, 'day')@@ -48,6 +53,8 @@ export function OnlinePerformanceTab(): JSX.Element {latestChampionPerformance,realizedAucPoints,segmentCalibration,+ accuracyCutoff,+ championConfusion,} = useValues(autoresearchPipelineLogic)const { loadOnlinePerformance } = useActions(autoresearchPipelineLogic)@@ -75,6 +82,9 @@ export function OnlinePerformanceTab(): JSX.Element {}const ranking = rankingSentence(latestChampionPerformance, pipeline.target_event)+ const precisionRecall = championConfusion+ ? precisionRecallSentence(championConfusion, accuracyCutoff, pipeline.target_event)+ : nullconst latestDate = dayjs(latestChampionPerformance.prediction_date).format('MMM D')return (@@ -84,8 +94,11 @@ export function OnlinePerformanceTab(): JSX.Element {{accuracyHeadline(latestChampionPerformance, pipeline.target_event)}</p>{ranking && <p className="text-sm text-muted mb-0">{ranking}</p>}+ {precisionRecall && <p className="text-sm text-muted mb-0">{precisionRecall}</p>}</div>+ <ConfusionMatrixCard />+{segmentCalibration.length > 0 && (<section className="space-y-2"><h3 className="text-sm font-semibold mb-0">Predicted and actual rate by segment, {latestDate}</h3>@@ -142,13 +155,25 @@ export function OnlinePerformanceTab(): JSX.Element {{ 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)}×` },+ {+ title: 'Precision at 10%',+ render: (_, row) => fmtPercent(row.confusion?.top_10.precision),+ },+ {+ title: 'Recall at 10%',+ render: (_, row) => fmtPercent(row.confusion?.top_10.recall),+ },+ { title: 'Average precision', render: (_, row) => fmt(row.average_precision) },]}/><p className="text-xs text-muted mb-0">Realized AUC: higher is better. Brier score and calibration error (ECE): lower isbetter. ECE measures how far predicted probabilities drift from observed rates. Liftat k%: ratio of positives in the top k% vs a random sample, so 2× means twice as- many conversions as random.+ many conversions as random. Precision at 10%: share of the top 10% who did{' '}+ {pipeline.target_event}. Recall at 10%: share of everyone who did it that the top+ 10% includes. Average precision: precision averaged over every cutoff, higher is+ better.</p></div>),diff --git a/products/autoresearch/frontend/predictionSegmentThresholds.json b/products/autoresearch/frontend/predictionSegmentThresholds.jsonnew file mode 100644index 000000000000..486ff20a19d0--- /dev/null+++ b/products/autoresearch/frontend/predictionSegmentThresholds.json@@ -0,0 +1 @@+{ "high": 0.6, "low": 0.2 }diff --git a/products/autoresearch/frontend/predictionSegments.ts b/products/autoresearch/frontend/predictionSegments.tsindex 9aa033b4eb80..73998f8b26c4 100644--- a/products/autoresearch/frontend/predictionSegments.ts+++ b/products/autoresearch/frontend/predictionSegments.ts@@ -11,12 +11,14 @@ import type { CohortFiltersApi, PersonFilterApi } from 'products/cohorts/frontenimport { urlForNewWorkflowWithTrigger } from 'products/workflows/frontend/Workflows/workflowTriggerPrefill'import type { AutoresearchPipelineApi } from './generated/api.schemas'+import thresholds from './predictionSegmentThresholds.json'/*** Probability cut points between the segments. Both sit on a histogram decile boundary,- * so every histogram bar belongs to exactly one segment.+ * so every histogram bar belongs to exactly one segment. Online validation reads the same+ * JSON file for its Likely cutoff.*/-export const PREDICTION_SEGMENT_THRESHOLDS = { high: 0.6, low: 0.2 } as const+export const PREDICTION_SEGMENT_THRESHOLDS: { readonly high: number; readonly low: number } = thresholdsexport type PredictionSegmentKey = 'likely' | 'possible' | 'unlikely'diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3c70a9519b07..084b8b81098d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13650,7 +13650,7 @@ export namespace Schemas {export type AutoresearchModelModelRecipe = { [key: string]: unknown };/**- * Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.+ * Extended metrics bundle. Holds the holdout AUC from training, and under 'realized' the newest validated date's online metrics: realized AUC, Brier score, calibration error and bins, lift@k, average precision, confusion counts at top 10%, top 20% and Likely, base rate, and row counts.*/export type AutoresearchModelMetrics = { [key: string]: unknown };@@ -13751,7 +13751,7 @@ export namespace Schemas {* @nullable*/calibration_error?: number | null;- /** Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts. */+ /** Extended metrics bundle. Holds the holdout AUC from training, and under 'realized' the newest validated date's online metrics: realized AUC, Brier score, calibration error and bins, lift@k, average precision, confusion counts at top 10%, top 20% and Likely, base rate, and row counts. */metrics?: AutoresearchModelMetrics;/*** Training run that produced this model. Read that run's artifact bundle to reuse the champion's train.py and features.sql as a starting point. Null for legacy models.@@ -24318,6 +24318,38 @@ export namespace Schemas {Xaa: 'xaa',} as const;+ export interface ConfusionCounts {+ /** True positives: flagged users who did the target event. */+ tp: number;+ /** False positives: flagged users who did not do the target event. */+ fp: number;+ /** False negatives: users not flagged who did the target event. */+ fn: number;+ /** True negatives: users not flagged who did not do the target event. */+ tn: number;+ /** Number of users the cutoff flagged (tp + fp). Top-k cutoffs flag every user tied at the boundary score, so this can be a little above k. */+ n_flagged: number;+ /**+ * tp / n_flagged: share of flagged users who did the target event. Null when no user was flagged.+ * @nullable+ */+ precision: number | null;+ /**+ * tp / (tp + fn): share of users who did the target event that the cutoff flagged. Null when no user did it.+ * @nullable+ */+ recall: number | null;+ }++ export interface ConfusionByCutoff {+ /** Counts when the top 10% of users by score are flagged. */+ top_10: ConfusionCounts;+ /** Counts when the top 20% of users by score are flagged. */+ top_20: ConfusionCounts;+ /** Counts when users with a score of 0.6 or higher (the Likely segment) are flagged. */+ likely: ConfusionCounts;+ }+/*** * `posthog_code` - posthog_code*/@@ -67405,6 +67437,13 @@ export namespace Schemas {* @nullable*/lift_at_20: number | null;+ /**+ * Average precision: area under the precision-recall curve. Higher is better, and a random model scores about base_rate. Null when no scored user did the target event, or for dates validated before this metric existed.+ * @nullable+ */+ average_precision: number | null;+ /** Confusion counts, precision and recall at three cutoffs: top 10%, top 20%, and the Likely segment. Null for dates validated before this metric existed. */+ confusion: ConfusionByCutoff | null;/*** Calibration table with up to 10 bins cut at score quantiles, lowest scores first. Users with equal scores share a bin, so heavy ties give fewer bins. Null for dates validated before this metric existed.* @nullable