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): keep and expose realized history per model and date (#111604)

posthog[bot]0bafec2fc57f
diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.md
index b7ede1aec54b..ae9862fd7afe 100644
--- a/products/autoresearch/backend/evaluation/AGENTS.md
+++ b/products/autoresearch/backend/evaluation/AGENTS.md
@@ -13,12 +13,17 @@ It is the only honest number in the product. A holdout AUC of 0.93 says the mode
Per matured prediction date, per model that emitted predictions, it computes:
- **realized AUC** — ranking quality against actual outcomes (needs both classes; a single-class date records `single_class_no_auc` instead)
+ - **AUC interval** (`realized_auc_ci_low` / `realized_auc_ci_high`, `_auc_confidence_interval`) — a 95% Hanley-McNeil interval, so a date with few positives shows as uncertain; omitted with the AUC
+ - **mean predicted probability** (`mean_p_y`) — compare it with `base_rate` to see over- or under-prediction
- **Brier score** — squared error of the probabilities
- - **expected calibration error** (`_expected_calibration_error`, 10 bins) — whether "0.8" really means 80%
+ - **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
+ - **weekday** — the ISO weekday of the prediction date
Every model that emitted predictions on the date is scored, whatever its role now. Inference emits the champion only today; when challenger shadow scoring ships, their realized numbers land here without a change, which is what makes challenger promotion decidable on evidence rather than on holdout alone.
Results land on `AutoresearchModel.realized_score` / `.calibration_error` / `.metrics["realized"]` via `_update_model_realized_metrics()`, and each validated date records an `AutoresearchRun` whose `metrics["per_model"]` keeps the emitted role next to the current one.
+ The model row keeps only the newest date. The history is on the runs: `online_performance()` in `../facade/api.py` (the pipeline's `online_performance` action and the `autoresearch-online-performance-retrieve` MCP tool) reads the newest completed run per (date, horizon) and returns one row per model per date, so an archived former champion keeps its evidence after a promotion.
## Mental model
@@ -52,7 +57,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 needs both classes.** An all-negative day still records Brier, calibration error, 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, and lift, which is where calibration matters for a rare target.
## Where the rest of the system meets this package
diff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.py
index 135210cfd063..00aa6f4ee4c4 100644
--- a/products/autoresearch/backend/evaluation/online_validation.py
+++ b/products/autoresearch/backend/evaluation/online_validation.py
@@ -2,8 +2,9 @@
Online validation: join autoresearch_prediction events to realized target outcomes
after the prediction horizon has elapsed.
-Computes per model: realized AUC, Brier score, expected calibration error (ECE),
-and lift@k, for every model that emitted predictions on a date.
+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.
Architecture:
- Pure activity functions called by AutoresearchValidationWorkflow (Temporal)
@@ -106,6 +107,12 @@ class _ModelPredictions:
p_y_by_person: dict[str, float]
+@frozen
+class _AucInterval:
+ low: float
+ high: float
+
+
@frozen
class _ModelValidation:
emitted_role: str
@@ -340,7 +347,9 @@ def _validate_claimed_date(
per_model = {
model_id: _ModelValidation(
emitted_role=model.emitted_role,
- metrics=_compute_validation_metrics(model.p_y_by_person, realized),
+ metrics=_compute_validation_metrics(
+ model.p_y_by_person, realized, prediction_date=pending.prediction_date
+ ),
)
for model_id, model in predictions.items()
}
@@ -612,13 +621,16 @@ def _query(
def _compute_validation_metrics(
predictions: dict[str, float],
realized_labels: frozenset[str],
+ *,
+ prediction_date: date,
) -> dict[str, Any]:
"""
- AUC, Brier score, ECE, and lift@k from scored predictions against realized labels.
+ AUC with its 95% interval, Brier score, ECE, quantile calibration bins, and lift@k
+ from scored predictions against realized labels.
- Only the AUC needs 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. 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)
@@ -633,9 +645,11 @@ def _compute_validation_metrics(
"n_positive": n_pos,
"n_negative": n_neg,
"base_rate": round(n_pos / n, 4) if n > 0 else 0.0,
+ "weekday": prediction_date.isoweekday(),
}
if n == 0:
return 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
@@ -643,9 +657,14 @@ def _compute_validation_metrics(
if n_pos == 0 or n_neg == 0:
metrics["warning"] = "single_class_no_auc"
else:
- metrics["realized_auc"] = round(float(roc_auc_score(y_true, y_score)), 4)
+ auc = float(roc_auc_score(y_true, y_score))
+ interval = _auc_confidence_interval(auc, n_pos=n_pos, n_neg=n_neg)
+ metrics["realized_auc"] = round(auc, 4)
+ metrics["realized_auc_ci_low"] = round(interval.low, 4)
+ metrics["realized_auc_ci_high"] = round(interval.high, 4)
metrics["brier_score"] = round(float(brier_score_loss(y_true, y_score)), 4)
metrics["calibration_error"] = round(_expected_calibration_error(y_true, y_score), 4)
+ 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)
return metrics
@@ -671,6 +690,44 @@ def _expected_calibration_error(y_true: np.ndarray, y_score: np.ndarray, n_bins:
return ece
+def _auc_confidence_interval(auc: float, *, n_pos: int, n_neg: int, z: float = 1.96) -> _AucInterval:
+ """
+ 95% interval for an AUC from the Hanley-McNeil (1982) standard error.
+
+ The width depends on the class counts, so a date with a few dozen positives gets a
+ wide interval and a date with thousands gets a narrow one.
+ """
+ q1 = auc / (2 - auc)
+ q2 = 2 * auc**2 / (1 + auc)
+ variance = (auc * (1 - auc) + (n_pos - 1) * (q1 - auc**2) + (n_neg - 1) * (q2 - auc**2)) / (n_pos * n_neg)
+ se = math.sqrt(max(variance, 0.0))
+ return _AucInterval(low=max(0.0, auc - z * se), high=min(1.0, auc + z * se))
+
+
+def _quantile_calibration_bins(y_true: np.ndarray, y_score: np.ndarray, n_bins: int = 10) -> list[dict[str, Any]]:
+ """
+ Calibration table with up to ``n_bins`` bins cut at score quantiles, lowest scores first.
+
+ Equal-width bins put almost every person in the first bin for a rare target; quantile
+ bins hold roughly equal counts. Equal scores always share a bin, so heavy ties give
+ fewer bins rather than a split that depends on row order.
+ """
+ # A score's bin comes from how many scores sit below it, so every user with that score shares it.
+ rank = np.searchsorted(np.sort(y_score), y_score, side="left")
+ bin_index = rank * n_bins // len(y_score)
+ bins: list[dict[str, Any]] = []
+ for i in np.unique(bin_index):
+ mask = bin_index == i
+ bins.append(
+ {
+ "n": int(mask.sum()),
+ "mean_p_y": round(float(y_score[mask].mean()), 4),
+ "positive_rate": round(float(y_true[mask].mean()), 4),
+ }
+ )
+ return bins
+
+
def _lift_at_k(y_true: np.ndarray, y_score: np.ndarray, k: float) -> float:
"""
Lift@k: positives captured in the top-k fraction of scored users, relative to random.
diff --git a/products/autoresearch/backend/evaluation/test_online_validation.py b/products/autoresearch/backend/evaluation/test_online_validation.py
index 2d47ded6b7e7..44bcf70cfd80 100644
--- a/products/autoresearch/backend/evaluation/test_online_validation.py
+++ b/products/autoresearch/backend/evaluation/test_online_validation.py
@@ -17,9 +17,11 @@ from products.autoresearch.backend.evaluation.online_validation import (
OUTCOME_INGESTION_GRACE,
STALE_RUN_AFTER,
OnlineValidationError,
+ _auc_confidence_interval,
_compute_validation_metrics,
_expected_calibration_error,
_lift_at_k,
+ _quantile_calibration_bins,
_update_model_realized_metrics,
find_pending_validation_dates,
run_online_validation_for_pipeline,
@@ -36,11 +38,17 @@ class TestComputeValidationMetrics(SimpleTestCase):
return {"user-1": 0.9, "user-2": 0.8, "user-3": 0.4, "user-4": 0.3, "user-5": 0.1}
def test_returns_base_counts(self):
- metrics = _compute_validation_metrics(self._predictions(), frozenset(["user-1", "user-2"]))
+ metrics = _compute_validation_metrics(
+ self._predictions(), frozenset(["user-1", "user-2"]), prediction_date=date(2026, 9, 6)
+ )
assert metrics["n_scored"] == 5
assert metrics["n_positive"] == 2
assert metrics["n_negative"] == 3
assert metrics["base_rate"] == 0.4
+ assert metrics["mean_p_y"] == 0.5
+ assert metrics["weekday"] == 7
+ assert metrics["realized_auc_ci_low"] <= metrics["realized_auc"] <= metrics["realized_auc_ci_high"]
+ assert sum(b["n"] for b in metrics["calibration_bins"]) == 5
assert 0.0 <= metrics["brier_score"] <= 1.0
assert 0.0 <= metrics["calibration_error"] <= 1.0
assert metrics["lift_at_10"] > 0.0
@@ -52,7 +60,7 @@ class TestComputeValidationMetrics(SimpleTestCase):
]
)
def test_realized_auc(self, _name, preds, expected_auc):
- metrics = _compute_validation_metrics(preds, frozenset(["high-1", "high-2"]))
+ metrics = _compute_validation_metrics(preds, frozenset(["high-1", "high-2"]), prediction_date=date(2026, 9, 1))
assert metrics["realized_auc"] == expected_auc
@parameterized.expand(
@@ -62,14 +70,57 @@ class TestComputeValidationMetrics(SimpleTestCase):
]
)
def test_single_class_skips_only_the_auc(self, _name, labels):
- metrics = _compute_validation_metrics({"user-1": 0.5, "user-2": 0.6}, labels)
+ metrics = _compute_validation_metrics({"user-1": 0.5, "user-2": 0.6}, labels, prediction_date=date(2026, 9, 1))
assert metrics["warning"] == "single_class_no_auc"
assert "realized_auc" not in metrics
+ assert "realized_auc_ci_low" not in metrics
+ assert "realized_auc_ci_high" not in metrics
+ assert metrics["mean_p_y"] == 0.55
+ assert sum(b["n"] for b in metrics["calibration_bins"]) == 2
assert 0.0 <= metrics["brier_score"] <= 1.0
assert 0.0 <= metrics["calibration_error"] <= 1.0
assert "lift_at_10" in metrics
+class TestAucConfidenceInterval(SimpleTestCase):
+ def test_interval_narrows_as_the_classes_grow(self):
+ few = _auc_confidence_interval(0.75, n_pos=20, n_neg=200)
+ many = _auc_confidence_interval(0.75, n_pos=2000, n_neg=20000)
+ assert few.low < many.low < 0.75 < many.high < few.high
+ # Hanley-McNeil standard error for these counts is about 0.065.
+ assert abs((few.high - few.low) / 2 - 1.96 * 0.065) < 0.002
+
+ def test_interval_is_clipped_to_one(self):
+ interval = _auc_confidence_interval(0.99, n_pos=3, n_neg=3)
+ assert 0.0 <= interval.low < 0.99
+ assert interval.high == 1.0
+
+
+class TestQuantileCalibrationBins(SimpleTestCase):
+ def test_rare_target_scores_spread_over_ten_equal_bins(self):
+ # Every score is below 0.1, so equal-width bins would put all users in one bin.
+ y_score = np.linspace(0.001, 0.05, 100)
+ y_true = np.zeros(100, dtype=np.int32)
+ y_true[-5:] = 1
+ bins = _quantile_calibration_bins(y_true, y_score)
+ assert [b["n"] for b in bins] == [10] * 10
+ assert [b["mean_p_y"] for b in bins] == sorted(b["mean_p_y"] for b in bins)
+ assert bins[-1]["positive_rate"] == 0.5
+ assert all(b["positive_rate"] == 0.0 for b in bins[:-1])
+
+ @parameterized.expand(
+ [
+ ("all_scores_equal", [0.2] * 6, [6]),
+ ("ties_never_split", [0.1] * 5 + [0.9] * 5, [5, 5]),
+ ("tie_group_past_the_median_keeps_its_own_bin", [0.1] * 51 + [0.9] * 49, [51, 49]),
+ ]
+ )
+ def test_equal_scores_share_a_bin(self, _name, scores, expected_counts):
+ y_score = np.array(scores)
+ bins = _quantile_calibration_bins(np.zeros(len(scores), dtype=np.int32), y_score)
+ assert [b["n"] for b in bins] == expected_counts
+
+
class TestExpectedCalibrationError(SimpleTestCase):
def test_perfect_calibration_zero_ece(self):
ece = _expected_calibration_error(np.array([1, 0, 1, 0]), np.array([0.5, 0.5, 0.5, 0.5]))
@@ -363,6 +414,7 @@ class TestRunOnlineValidationForPipeline(TeamScopedTestMixin, BaseTest):
assert per_model["emitted_role"] == "champion"
assert per_model["model_role"] == "champion"
assert per_model["realized_auc"] == 1.0
+ assert per_model["weekday"] == 2
self.champion.refresh_from_db()
assert self.champion.realized_score == 1.0
assert self.champion.is_preliminary is False
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index d6d824308a8e..9a7132390a3f 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -13,13 +13,14 @@ import json
import base64
import asyncio
import hashlib
-from datetime import timedelta
+from datetime import date, timedelta
from typing import Any
from uuid import UUID, uuid4
from django.conf import settings
from django.db import transaction
from django.db.models import F, Prefetch, Q
+from django.db.models.fields.json import KT
from django.utils import timezone as django_timezone
from posthog.models.team import Team
@@ -56,12 +57,15 @@ from .contracts import (
ArtifactNotFound,
ArtifactStorageUnavailable,
AutoresearchConflict,
+ CalibrationBin,
InvalidArtifactPath as InvalidArtifactPath,
InvalidTarget,
Iteration,
IterationTrailEntry,
MaterializedFeatures,
Model,
+ OnlinePerformance,
+ OnlinePerformanceRow,
Pipeline,
PipelineNotFound,
PipelineValidation,
@@ -96,6 +100,9 @@ MAX_BUNDLE_FILES = 32
HISTORY_LIMIT_MAX = 20
+ONLINE_PERFORMANCE_DATES_DEFAULT = 60
+ONLINE_PERFORMANCE_DATES_MAX = 180
+
def _as_uuid(value: str | UUID | None) -> UUID | None:
"""A pk from a URL as a UUID, or None when it cannot be one.
@@ -859,6 +866,70 @@ def validate_pipeline_online(
return [_run_to_contract(run) for run in runs]
+def online_performance(
+ team_id: int, pipeline_id: str | UUID, *, limit: int = ONLINE_PERFORMANCE_DATES_DEFAULT
+) -> OnlinePerformance:
+ """Realized metrics per model per validated prediction date, newest date first.
+
+ Reads the completed validation runs, not the model rows: a model row keeps only its newest
+ date, and promotion archives the former champion, but each run keeps every model it scored.
+ ``limit`` bounds the number of (prediction date, horizon) groups. When a group was validated
+ more than once, its newest completed run holds the current evidence.
+ """
+ pipeline = _pipeline_row(team_id, pipeline_id)
+ limit = max(1, min(limit, ONLINE_PERFORMANCE_DATES_MAX))
+ runs = list(
+ AutoresearchRun.objects.for_team(team_id)
+ .filter(
+ pipeline=pipeline,
+ run_type=AutoresearchRun.RunType.VALIDATION,
+ status=AutoresearchRun.Status.COMPLETED,
+ metrics__has_key="prediction_date",
+ )
+ .annotate(prediction_date=KT("metrics__prediction_date"), horizon=KT("metrics__horizon_days"))
+ .order_by("-prediction_date", "horizon", F("completed_at").desc(nulls_last=True), "-id")
+ .distinct("prediction_date", "horizon")[:limit]
+ )
+ model_ids = {model_id for run in runs for model_id in (run.metrics.get("per_model") or {})}
+ current_roles = dict(
+ AutoresearchModel.objects.for_team(team_id)
+ .filter(pipeline=pipeline, pk__in=[_as_uuid(model_id) for model_id in model_ids])
+ .values_list("id", "role")
+ )
+ rows: list[OnlinePerformanceRow] = []
+ for run in runs:
+ prediction_date = date.fromisoformat(run.metrics["prediction_date"])
+ for model_id, m in sorted((run.metrics.get("per_model") or {}).items()):
+ model_uuid = UUID(model_id)
+ bins = m.get("calibration_bins")
+ rows.append(
+ OnlinePerformanceRow(
+ validation_run_id=run.id,
+ prediction_date=prediction_date,
+ horizon_days=int(run.metrics.get("horizon_days") or pipeline.horizon_days),
+ weekday=prediction_date.isoweekday(),
+ model_id=model_uuid,
+ emitted_role=m.get("emitted_role") or "",
+ current_role=current_roles.get(model_uuid, "deleted"),
+ n_scored=int(m.get("n_scored") or 0),
+ n_positive=int(m.get("n_positive") or 0),
+ base_rate=float(m.get("base_rate") or 0.0),
+ mean_p_y=m.get("mean_p_y"),
+ realized_auc=m.get("realized_auc"),
+ realized_auc_ci_low=m.get("realized_auc_ci_low"),
+ realized_auc_ci_high=m.get("realized_auc_ci_high"),
+ brier_score=m.get("brier_score"),
+ calibration_error=m.get("calibration_error"),
+ lift_at_10=m.get("lift_at_10"),
+ lift_at_20=m.get("lift_at_20"),
+ calibration_bins=[CalibrationBin(**b) for b in bins] if bins is not None else None,
+ warning=m.get("warning"),
+ validated_at=run.completed_at,
+ )
+ )
+ return OnlinePerformance(rows=rows)
+
+
# ── Training runs ──────────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 5accdca3d245..2a7897cc2423 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -344,6 +344,48 @@ class TrainingRunHistory:
runs: list[TrainingRunHistoryEntry]
+# ── Online performance ─────────────────────────────────────────────────────
+
+
+@dataclass(frozen=True)
+class CalibrationBin:
+ n: int
+ mean_p_y: float
+ positive_rate: float
+
+
+@dataclass(frozen=True)
+class OnlinePerformanceRow:
+ """One model's realized metrics for one validated prediction date."""
+
+ validation_run_id: UUID
+ prediction_date: date
+ horizon_days: int
+ weekday: int
+ model_id: UUID
+ emitted_role: str
+ current_role: str
+ n_scored: int
+ n_positive: int
+ base_rate: float
+ mean_p_y: float | None
+ realized_auc: float | None
+ realized_auc_ci_low: float | None
+ realized_auc_ci_high: float | None
+ brier_score: float | None
+ calibration_error: float | None
+ lift_at_10: float | None
+ lift_at_20: float | None
+ calibration_bins: list[CalibrationBin] | None
+ warning: str | None
+ validated_at: datetime | None
+
+
+@dataclass(frozen=True)
+class OnlinePerformance:
+ rows: list[OnlinePerformanceRow]
+
+
# ── Artifact bundle ────────────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.md
index 2b0315a12726..982c6941b0ae 100644
--- a/products/autoresearch/backend/presentation/AGENTS.md
+++ b/products/autoresearch/backend/presentation/AGENTS.md
@@ -11,7 +11,7 @@ The `autoresearch-*` MCP tools that expose this API to the sandbox agent are dec
- `views/views.py`
Five viewsets, registered in `../routes.py` under `project_autoresearch_*` basenames and nested pipeline-first.
- - `AutoresearchPipelineViewSet` — full CRUD plus the lifecycle actions: `train`, `score`, `validate_online`, `archive`, `pause`, `resume`, and the pre-create helpers `templates`, `resolve-template`, `validate`.
+ - `AutoresearchPipelineViewSet` — full CRUD plus the lifecycle actions: `train`, `score`, `validate_online`, `archive`, `pause`, `resume`, the pre-create helpers `templates`, `resolve-template`, `validate`, and the read-only `online_performance`, which returns realized metrics per model per validated date from the validation runs.
- `AutoresearchTrainingRunViewSet` — read plus create, and **the agent's entire write surface**: `iterations`, `materialize-features`, `complete`, `artifacts`, `artifacts/upload`, `artifacts/get`, `artifacts/delete`, plus `history`.
- `AutoresearchModelViewSet`, `AutoresearchRunViewSet` — read-only.
- `AutoresearchSuggestionViewSet` — human or agent hypotheses, plus `respond`.
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index bbfbb0f4ccdc..acc892ddf2b8 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -1133,6 +1133,104 @@ class TrainingRunHistorySerializer(serializers.Serializer):
)
+class OnlinePerformanceQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(
+ required=False,
+ default=api.ONLINE_PERFORMANCE_DATES_DEFAULT,
+ min_value=1,
+ max_value=api.ONLINE_PERFORMANCE_DATES_MAX,
+ help_text=(
+ f"Maximum number of validated prediction dates to return, newest first "
+ f"(default {api.ONLINE_PERFORMANCE_DATES_DEFAULT}, at most {api.ONLINE_PERFORMANCE_DATES_MAX}). "
+ "Each date returns one row per model that emitted predictions on it."
+ ),
+ )
+
+
+class CalibrationBinSerializer(serializers.Serializer):
+ n = serializers.IntegerField(help_text="Number of scored users in this bin.")
+ mean_p_y = serializers.FloatField(help_text="Mean predicted probability of the users in this bin.")
+ positive_rate = serializers.FloatField(
+ help_text="Fraction of the users in this bin who did the target event within the horizon."
+ )
+
+
+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).")
+ horizon_days = serializers.IntegerField(help_text="Prediction horizon, in days, the predictions were made under.")
+ weekday = serializers.IntegerField(
+ help_text="ISO weekday of the prediction date: 1 is Monday and 7 is Sunday. Use it to find weekday effects."
+ )
+ model_id = serializers.UUIDField(help_text="UUID of the model that emitted the predictions.")
+ emitted_role = serializers.CharField(
+ help_text="Role the model had when it emitted the predictions: 'champion' or 'challenger'."
+ )
+ current_role = serializers.CharField(
+ help_text=(
+ "Role the model has now: 'champion', 'challenger', 'archived', or 'deleted'. "
+ "A former champion that a promotion archived keeps its rows."
+ )
+ )
+ n_scored = serializers.IntegerField(help_text="Number of users the model scored on this date.")
+ n_positive = serializers.IntegerField(help_text="Number of scored users who did the target event in the horizon.")
+ base_rate = serializers.FloatField(
+ help_text="Fraction of scored users who did the target event (n_positive / n_scored)."
+ )
+ mean_p_y = serializers.FloatField(
+ allow_null=True,
+ help_text=(
+ "Mean predicted probability. Compare it with base_rate: a higher value means the model "
+ "over-predicts. Null for dates validated before this metric existed."
+ ),
+ )
+ realized_auc = serializers.FloatField(
+ allow_null=True, help_text="Realized ROC AUC against actual outcomes. Null when the date has one class only."
+ )
+ realized_auc_ci_low = serializers.FloatField(
+ allow_null=True,
+ help_text="Lower bound of the 95% AUC interval (Hanley-McNeil). Null when realized_auc is null.",
+ )
+ realized_auc_ci_high = serializers.FloatField(
+ allow_null=True,
+ help_text="Upper bound of the 95% AUC interval (Hanley-McNeil). Null when realized_auc is null.",
+ )
+ brier_score = serializers.FloatField(allow_null=True, help_text="Brier score. Lower is better.")
+ calibration_error = serializers.FloatField(
+ allow_null=True, help_text="Expected calibration error over 10 equal-width bins. Lower is better."
+ )
+ lift_at_10 = serializers.FloatField(
+ allow_null=True, help_text="Positives in the top 10% by score, relative to a random 10%."
+ )
+ lift_at_20 = serializers.FloatField(
+ allow_null=True, help_text="Positives in the top 20% by score, relative to a random 20%."
+ )
+ calibration_bins = CalibrationBinSerializer(
+ many=True,
+ allow_null=True,
+ help_text=(
+ "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."
+ ),
+ )
+ warning = serializers.CharField(
+ allow_null=True,
+ help_text="'single_class_no_auc' when every scored user had the same outcome, otherwise null.",
+ )
+ validated_at = serializers.DateTimeField(allow_null=True, help_text="When the validation run completed.")
+
+
+class OnlinePerformanceSerializer(serializers.Serializer):
+ rows = OnlinePerformanceRowSerializer(
+ many=True,
+ help_text=(
+ "One row per model per validated prediction date, newest date first. "
+ "Empty until a prediction horizon has elapsed and online validation has run."
+ ),
+ )
+
+
@extend_schema_serializer(component_name="AutoresearchRun")
class AutoresearchRunSerializer(DataclassSerializer):
id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this run.")
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index d70ba38d9a58..53f883b3d0d0 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -66,6 +66,8 @@ from .serializers import (
CreateSuggestionSerializer,
MaterializeFeaturesRequestSerializer,
MaterializeFeaturesResponseSerializer,
+ OnlinePerformanceQuerySerializer,
+ OnlinePerformanceSerializer,
OpenTrainingRunSerializer,
RecordIterationSerializer,
ResolvedTemplateSerializer,
@@ -212,7 +214,14 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
uuid_path_parameters = {"id": "A UUID string identifying this autoresearch pipeline."}
scope_object = "autoresearch"
# The HogQL actions also carry their own `required_scopes`, so a scoped token needs `query:read` too.
- scope_object_read_actions = ["list", "retrieve", "validate_definition", "list_templates", "resolve_template"]
+ scope_object_read_actions = [
+ "list",
+ "retrieve",
+ "validate_definition",
+ "list_templates",
+ "resolve_template",
+ "online_performance",
+ ]
scope_object_write_actions = [
"create",
"update",
@@ -589,6 +598,34 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
raise ValidationError(str(exc)) from exc
return Response(AutoresearchRunSerializer(instance=runs, many=True).data)
+ @validated_request(
+ query_serializer=OnlinePerformanceQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=OnlinePerformanceSerializer,
+ description="Realized metrics per model per validated prediction date, newest date first.",
+ ),
+ 404: OpenApiResponse(description="The pipeline does not exist."),
+ },
+ summary="Read realized performance history",
+ description=(
+ "Return the realized metrics online validation recorded for each model on each validated "
+ "prediction date, newest date first. Each row has realized AUC with a 95% interval, Brier score, "
+ "calibration error, quantile calibration bins, mean predicted probability against the base rate, "
+ "lift, and the model's role when it emitted and now. The rows come from the validation runs, so a "
+ "former champion that a promotion archived keeps its history. Read-only; it runs no queries."
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="online_performance", pagination_class=None)
+ def online_performance(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ try:
+ performance = api.online_performance(
+ self.team_id, self.kwargs["pk"], limit=request.validated_query_data["limit"]
+ )
+ except PipelineNotFound:
+ raise NotFound("Pipeline not found.")
+ return Response(OnlinePerformanceSerializer(instance=performance).data)
+
@extend_schema(
request=None,
responses={
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index 154f0aab0a61..820ec1e053c2 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -888,6 +888,64 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
assert resp.status_code == status.HTTP_200_OK
assert resp.json()["count"] == 1
+ def test_online_performance_keeps_an_archived_former_champion(self):
+ pipeline = self._make_pipeline()
+ former = AutoresearchModel.objects.create(
+ pipeline=pipeline, role=AutoresearchModel.Role.ARCHIVED, model_recipe={}, recipe_hash="old"
+ )
+ champion = AutoresearchModel.objects.create(
+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe={}, recipe_hash="new"
+ )
+ now = django_timezone.now()
+
+ def validation(prediction_date: str, per_model: dict, *, completed_minutes_ago: int, run_status="completed"):
+ return AutoresearchRun.objects.create(
+ pipeline=pipeline,
+ run_type=AutoresearchRun.RunType.VALIDATION,
+ status=run_status,
+ completed_at=now - timedelta(minutes=completed_minutes_ago),
+ metrics={"prediction_date": prediction_date, "horizon_days": 7, "per_model": per_model},
+ )
+
+ def metrics(role: str, auc: float) -> dict:
+ return {"emitted_role": role, "model_role": role, "n_scored": 10, "n_positive": 2, "realized_auc": auc}
+
+ validation("2026-09-01", {str(former.pk): metrics("champion", 0.6)}, completed_minutes_ago=30)
+ populated = {
+ **metrics("champion", 0.7),
+ "mean_p_y": 0.4,
+ "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}],
+ }
+ latest = validation("2026-09-01", {str(former.pk): populated}, completed_minutes_ago=20)
+ validation(
+ "2026-09-02", {str(champion.pk): metrics("champion", 0.9)}, completed_minutes_ago=5, run_status="failed"
+ )
+ validation("2026-09-03", {str(champion.pk): metrics("champion", 0.8)}, completed_minutes_ago=10)
+
+ resp = self.client.get(f"{self.base_url}/{pipeline.id}/online_performance/")
+
+ assert resp.status_code == status.HTTP_200_OK
+ rows = resp.json()["rows"]
+ assert [(r["prediction_date"], r["model_id"], r["realized_auc"]) for r in rows] == [
+ ("2026-09-03", str(champion.pk), 0.8),
+ ("2026-09-01", str(former.pk), 0.7),
+ ]
+ assert rows[1]["validation_run_id"] == str(latest.pk)
+ assert (rows[1]["emitted_role"], rows[1]["current_role"]) == ("champion", "archived")
+ assert rows[1]["weekday"] == 2
+ assert (rows[1]["mean_p_y"], rows[1]["realized_auc_ci_low"], rows[1]["realized_auc_ci_high"]) == (
+ 0.4,
+ 0.65,
+ 0.75,
+ )
+ assert rows[1]["calibration_bins"] == [{"n": 10, "mean_p_y": 0.4, "positive_rate": 0.2}]
+ assert rows[0]["realized_auc_ci_low"] is None and rows[0]["calibration_bins"] is None
+
+ limited = 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"]
+
def test_models_not_leaked_across_pipelines(self):
pipeline_a = self._make_pipeline(name="Pipeline A")
pipeline_b = self._make_pipeline(name="Pipeline B")
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 4f592b795c3c..2b981b253e30 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -1321,6 +1321,98 @@ export interface PatchedAutoresearchPipelineCreateApi {
output_person_property?: string
}
+export interface CalibrationBinApi {
+ /** Number of scored users in this bin. */
+ n: number
+ /** Mean predicted probability of the users in this bin. */
+ mean_p_y: number
+ /** Fraction of the users in this bin who did the target event within the horizon. */
+ positive_rate: number
+}
+
+export interface OnlinePerformanceRowApi {
+ /** UUID of the validation run that recorded these metrics. */
+ validation_run_id: string
+ /** Date the predictions were made for (UTC). */
+ prediction_date: string
+ /** Prediction horizon, in days, the predictions were made under. */
+ horizon_days: number
+ /** ISO weekday of the prediction date: 1 is Monday and 7 is Sunday. Use it to find weekday effects. */
+ weekday: number
+ /** UUID of the model that emitted the predictions. */
+ model_id: string
+ /** Role the model had when it emitted the predictions: 'champion' or 'challenger'. */
+ emitted_role: string
+ /** Role the model has now: 'champion', 'challenger', 'archived', or 'deleted'. A former champion that a promotion archived keeps its rows. */
+ current_role: string
+ /** Number of users the model scored on this date. */
+ n_scored: number
+ /** Number of scored users who did the target event in the horizon. */
+ n_positive: number
+ /** Fraction of scored users who did the target event (n_positive / n_scored). */
+ base_rate: number
+ /**
+ * Mean predicted probability. Compare it with base_rate: a higher value means the model over-predicts. Null for dates validated before this metric existed.
+ * @nullable
+ */
+ mean_p_y: number | null
+ /**
+ * Realized ROC AUC against actual outcomes. Null when the date has one class only.
+ * @nullable
+ */
+ realized_auc: number | null
+ /**
+ * Lower bound of the 95% AUC interval (Hanley-McNeil). Null when realized_auc is null.
+ * @nullable
+ */
+ realized_auc_ci_low: number | null
+ /**
+ * Upper bound of the 95% AUC interval (Hanley-McNeil). Null when realized_auc is null.
+ * @nullable
+ */
+ realized_auc_ci_high: number | null
+ /**
+ * Brier score. Lower is better.
+ * @nullable
+ */
+ brier_score: number | null
+ /**
+ * Expected calibration error over 10 equal-width bins. Lower is better.
+ * @nullable
+ */
+ calibration_error: number | null
+ /**
+ * Positives in the top 10% by score, relative to a random 10%.
+ * @nullable
+ */
+ lift_at_10: number | null
+ /**
+ * Positives in the top 20% by score, relative to a random 20%.
+ * @nullable
+ */
+ lift_at_20: number | 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
+ */
+ calibration_bins: CalibrationBinApi[] | null
+ /**
+ * 'single_class_no_auc' when every scored user had the same outcome, otherwise null.
+ * @nullable
+ */
+ warning: string | null
+ /**
+ * When the validation run completed.
+ * @nullable
+ */
+ validated_at: string | null
+}
+
+export interface OnlinePerformanceApi {
+ /** One row per model per validated prediction date, newest date first. Empty until a prediction horizon has elapsed and online validation has run. */
+ rows: OnlinePerformanceRowApi[]
+}
+
export interface StartTrainingRequestApi {
/**
* Override the pipeline iteration budget for this training run.
@@ -1615,3 +1707,12 @@ export type AutoresearchTrainingRunsHistoryRetrieveParams = {
*/
limit?: number
}
+
+export type AutoresearchOnlinePerformanceRetrieveParams = {
+ /**
+ * Maximum number of validated prediction dates to return, newest first (default 60, at most 180). Each date returns one row per model that emitted predictions on it.
+ * @minimum 1
+ * @maximum 180
+ */
+ limit?: number
+}
diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.ts
index 0b0ba740b5c4..1f41959b799f 100644
--- a/products/autoresearch/frontend/generated/api.ts
+++ b/products/autoresearch/frontend/generated/api.ts
@@ -18,6 +18,7 @@ import type {
AutoresearchListParams,
AutoresearchModelApi,
AutoresearchModelsListParams,
+ AutoresearchOnlinePerformanceRetrieveParams,
AutoresearchPipelineApi,
AutoresearchPipelineCreateApi,
AutoresearchRunApi,
@@ -31,6 +32,7 @@ import type {
CreateSuggestionApi,
MaterializeFeaturesRequestApi,
MaterializeFeaturesResponseApi,
+ OnlinePerformanceApi,
OpenTrainingRunApi,
PaginatedAutoresearchModelListApi,
PaginatedAutoresearchPipelineListApi,
@@ -749,6 +751,42 @@ export const autoresearchArchiveCreate = async (
})
}
+export const getAutoresearchOnlinePerformanceRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: AutoresearchOnlinePerformanceRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/autoresearch/${id}/online_performance/?${stringifiedParams}`
+ : `/api/projects/${projectId}/autoresearch/${id}/online_performance/`
+}
+
+/**
+ * Return the realized metrics online validation recorded for each model on each validated prediction date, newest date first. Each row has realized AUC with a 95% interval, Brier score, calibration error, quantile calibration bins, mean predicted probability against the base rate, lift, and the model's role when it emitted and now. The rows come from the validation runs, so a former champion that a promotion archived keeps its history. Read-only; it runs no queries.
+ * @summary Read realized performance history
+ */
+export const autoresearchOnlinePerformanceRetrieve = async (
+ projectId: string,
+ id: string,
+ params?: AutoresearchOnlinePerformanceRetrieveParams,
+ options?: RequestInit
+): Promise<OnlinePerformanceApi> => {
+ return apiMutator<OnlinePerformanceApi>(getAutoresearchOnlinePerformanceRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getAutoresearchPauseCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/autoresearch/${id}/pause/`
}
diff --git a/products/autoresearch/mcp/AGENTS.md b/products/autoresearch/mcp/AGENTS.md
index 0c5c11300a64..fad8b7017512 100644
--- a/products/autoresearch/mcp/AGENTS.md
+++ b/products/autoresearch/mcp/AGENTS.md
@@ -7,7 +7,7 @@ During a run, the sandbox agent has no other write path. It records iterations,
## What lives here
- `tools.yaml`
- The whole surface: 22 enabled tools, `category: Autoresearch`, `feature: autoresearch`, `url_prefix: /autoresearch`. The family must stay at or below 25 tools: above that the exec tool's compact domain index splits it into sub-domains, and the serialized exec schema crosses the claude.ai registry cap (see `services/mcp/tests/unit/instructions-formatter-snapshot.test.ts`). Duplicative tools (`suggestions-retrieve`, `templates-list`, `validate-online-create`, `artifacts-delete-create`) are disabled rather than removed. `resolve-template-create` names every template key, so it replaces `templates-list` as the template entry point.
+ The whole surface: 24 enabled tools, `category: Autoresearch`, `feature: autoresearch`, `url_prefix: /autoresearch`. The family must stay at or below 25 tools: above that the exec tool's compact domain index splits it into sub-domains, and the serialized exec schema crosses the claude.ai registry cap (see `services/mcp/tests/unit/instructions-formatter-snapshot.test.ts`). Duplicative tools (`suggestions-retrieve`, `templates-list`, `validate-online-create`, `artifacts-delete-create`) are disabled rather than removed. `resolve-template-create` names every template key, so it replaces `templates-list` as the template entry point.
Each entry names an `operation` (an operation id from the OpenAPI spec), an `enabled` flag, required `scopes` (`autoresearch:read` / `autoresearch:write`, plus every extra scope the endpoint's `required_scopes` names, such as `query:read`: MCP hides a tool whose scopes the key lacks), `annotations` (`readOnly`, `destructive`, `idempotent`), and a `title` + `description`.
Tool entries are scaffolded from the OpenAPI schema — `pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all` keeps the tool list and operation ids in sync. Everything editorial (description, title, `enrich_url`, `exclude_params`) is yours to write.
@@ -20,7 +20,7 @@ Tool entries are scaffolded from the OpenAPI schema — `pnpm --filter=@posthog/
**Bring-your-own agents** — an agent that trains outside PostHog (for example on a laptop) calls `autoresearch-training-runs-create` to open a run, then the agent-facing tools above except `-materialize-features`, which writes into a PostHog sandbox; it pulls data with `execute-sql` instead. A sandbox request to open a run is refused.
-**User-facing** — creating and inspecting pipelines: `autoresearch-resolve-template-create`, `-validate-create`, `-create`, `-train-create`, `-score-create`, `-list`, `-retrieve`, `-training-runs-list`, `-suggestions-create`, `-suggestions-list` (to read the agent's response).
+**User-facing** — creating and inspecting pipelines: `autoresearch-resolve-template-create`, `-validate-create`, `-create`, `-train-create`, `-score-create`, `-list`, `-retrieve`, `-training-runs-list`, `-online-performance-retrieve` (realized metrics per model per validated date), `-suggestions-create`, `-suggestions-list` (to read the agent's response).
`autoresearch-score-create` scores today's prediction date on demand, so an MCP caller does not have to wait for the daily run after a champion is promoted. The training sandbox never sees it, because `TRAINING_MCP_SCOPES` has no `person:write`.
diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yaml
index 3f8b554c8621..125b023a7ec9 100644
--- a/products/autoresearch/mcp/tools.yaml
+++ b/products/autoresearch/mcp/tools.yaml
@@ -150,6 +150,26 @@ tools:
Get full details for a specific model version, including the portable model recipe (feature SQL, transforms,
model class, params) and feature importance explanation.
feature_flag: autoresearch
+ autoresearch-online-performance-retrieve:
+ operation: autoresearch_online_performance_retrieve
+ enabled: true
+ scopes:
+ - autoresearch:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Read realized performance history
+ description: >
+ Read how a pipeline's models performed against real outcomes, one row per model per validated prediction
+ date, newest date first. Each row has realized AUC with a 95% interval, Brier score, calibration error,
+ quantile calibration bins, mean_p_y against base_rate (mean_p_y above base_rate means the model
+ over-predicts), lift at 10% and 20%, the ISO weekday, and the model's role when it emitted and now. Use it
+ to see trends across dates and to judge a champion right after a promotion: the archived former champion
+ keeps its rows, while the new champion has none until its first horizon elapses. A wide AUC interval means
+ the date had few positives. Rows exist only after a prediction horizon has elapsed and online validation has
+ run. Use limit to bound the number of dates (default 60).
+ feature_flag: autoresearch
autoresearch-partial-update:
operation: autoresearch_partial_update
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 252f2e1c2f57..d6ca20f80e4a 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1164,6 +1164,21 @@
},
"feature_flag": "autoresearch"
},
+ "autoresearch-online-performance-retrieve": {
+ "description": "Read how a pipeline's models performed against real outcomes, one row per model per validated prediction date, newest date first. Each row has realized AUC with a 95% interval, Brier score, calibration error, quantile calibration bins, mean_p_y against base_rate (mean_p_y above base_rate means the model over-predicts), lift at 10% and 20%, the ISO weekday, and the model's role when it emitted and now. Use it to see trends across dates and to judge a champion right after a promotion: the archived former champion keeps its rows, while the new champion has none until its first horizon elapses. A wide AUC interval means the date had few positives. Rows exist only after a prediction horizon has elapsed and online validation has run. Use limit to bound the number of dates (default 60).",
+ "category": "Autoresearch",
+ "feature": "autoresearch",
+ "summary": "Read realized performance history",
+ "title": "Read realized performance history",
+ "required_scopes": ["autoresearch:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "autoresearch"
+ },
"autoresearch-resolve-template-create": {
"description": "Start here to create a pipeline from a template. Resolve a template key and optional overrides into a ready-to-use pipeline config. An unknown key returns 400. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target_event is auto-resolved from your event schema — review resolved_activity_event and activity_event_alternatives, then re-resolve with a target_event override if the chosen event is wrong. For 'feature_adoption' and 'repeat_key_behavior', supply target_event (required). After resolving: (1) call autoresearch-validate-create with the resolved target_event, horizon_days, training_lookback_days, training_population and inference_population, so validation counts the same window the pipeline will use; (2) if can_proceed is true, call autoresearch-create with name set to suggested_name and the same five fields plus output_person_property. For an action target, pass the same target_definition to both calls; target_event then only labels it, and both calls need the action:read scope.",
"category": "Autoresearch",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index bb7c464d40f2..42c9a6ea0042 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1179,6 +1179,21 @@
},
"feature_flag": "autoresearch"
},
+ "autoresearch-online-performance-retrieve": {
+ "description": "Read how a pipeline's models performed against real outcomes, one row per model per validated prediction date, newest date first. Each row has realized AUC with a 95% interval, Brier score, calibration error, quantile calibration bins, mean_p_y against base_rate (mean_p_y above base_rate means the model over-predicts), lift at 10% and 20%, the ISO weekday, and the model's role when it emitted and now. Use it to see trends across dates and to judge a champion right after a promotion: the archived former champion keeps its rows, while the new champion has none until its first horizon elapses. A wide AUC interval means the date had few positives. Rows exist only after a prediction horizon has elapsed and online validation has run. Use limit to bound the number of dates (default 60).",
+ "category": "Autoresearch",
+ "feature": "autoresearch",
+ "summary": "Read realized performance history",
+ "title": "Read realized performance history",
+ "required_scopes": ["autoresearch:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "autoresearch"
+ },
"autoresearch-resolve-template-create": {
"description": "Start here to create a pipeline from a template. Resolve a template key and optional overrides into a ready-to-use pipeline config. An unknown key returns 400. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target_event is auto-resolved from your event schema — review resolved_activity_event and activity_event_alternatives, then re-resolve with a target_event override if the chosen event is wrong. For 'feature_adoption' and 'repeat_key_behavior', supply target_event (required). After resolving: (1) call autoresearch-validate-create with the resolved target_event, horizon_days, training_lookback_days, training_population and inference_population, so validation counts the same window the pipeline will use; (2) if can_proceed is true, call autoresearch-create with name set to suggested_name and the same five fields plus output_person_property. For an action target, pass the same target_definition to both calls; target_event then only labels it, and both calls need the action:read scope.",
"category": "Autoresearch",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3afccc7af4cd..50b5dd930157 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19198,6 +19198,15 @@ export namespace Schemas {
Month: 'month',
} as const;
+ export interface CalibrationBin {
+ /** Number of scored users in this bin. */
+ n: number;
+ /** Mean predicted probability of the users in this bin. */
+ mean_p_y: number;
+ /** Fraction of the users in this bin who did the target event within the horizon. */
+ positive_rate: number;
+ }
+
/**
* * `needs_approval` - needs_approval
* * `disabled` - disabled
@@ -65451,6 +65460,89 @@ export namespace Schemas {
Provisioned: 'provisioned',
} as const;
+ export interface OnlinePerformanceRow {
+ /** UUID of the validation run that recorded these metrics. */
+ validation_run_id: string;
+ /** Date the predictions were made for (UTC). */
+ prediction_date: string;
+ /** Prediction horizon, in days, the predictions were made under. */
+ horizon_days: number;
+ /** ISO weekday of the prediction date: 1 is Monday and 7 is Sunday. Use it to find weekday effects. */
+ weekday: number;
+ /** UUID of the model that emitted the predictions. */
+ model_id: string;
+ /** Role the model had when it emitted the predictions: 'champion' or 'challenger'. */
+ emitted_role: string;
+ /** Role the model has now: 'champion', 'challenger', 'archived', or 'deleted'. A former champion that a promotion archived keeps its rows. */
+ current_role: string;
+ /** Number of users the model scored on this date. */
+ n_scored: number;
+ /** Number of scored users who did the target event in the horizon. */
+ n_positive: number;
+ /** Fraction of scored users who did the target event (n_positive / n_scored). */
+ base_rate: number;
+ /**
+ * Mean predicted probability. Compare it with base_rate: a higher value means the model over-predicts. Null for dates validated before this metric existed.
+ * @nullable
+ */
+ mean_p_y: number | null;
+ /**
+ * Realized ROC AUC against actual outcomes. Null when the date has one class only.
+ * @nullable
+ */
+ realized_auc: number | null;
+ /**
+ * Lower bound of the 95% AUC interval (Hanley-McNeil). Null when realized_auc is null.
+ * @nullable
+ */
+ realized_auc_ci_low: number | null;
+ /**
+ * Upper bound of the 95% AUC interval (Hanley-McNeil). Null when realized_auc is null.
+ * @nullable
+ */
+ realized_auc_ci_high: number | null;
+ /**
+ * Brier score. Lower is better.
+ * @nullable
+ */
+ brier_score: number | null;
+ /**
+ * Expected calibration error over 10 equal-width bins. Lower is better.
+ * @nullable
+ */
+ calibration_error: number | null;
+ /**
+ * Positives in the top 10% by score, relative to a random 10%.
+ * @nullable
+ */
+ lift_at_10: number | null;
+ /**
+ * Positives in the top 20% by score, relative to a random 20%.
+ * @nullable
+ */
+ lift_at_20: number | 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
+ */
+ calibration_bins: CalibrationBin[] | null;
+ /**
+ * 'single_class_no_auc' when every scored user had the same outcome, otherwise null.
+ * @nullable
+ */
+ warning: string | null;
+ /**
+ * When the validation run completed.
+ * @nullable
+ */
+ validated_at: string | null;
+ }
+
+ export interface OnlinePerformance {
+ /** One row per model per validated prediction date, newest date first. Empty until a prediction horizon has elapsed and online validation has run. */
+ rows: OnlinePerformanceRow[];
+ }
+
/**
* * `eq` - eq
* * `neq` - neq
@@ -113561,6 +113653,15 @@ export namespace Schemas {
limit?: number;
};
+ export type AutoresearchOnlinePerformanceRetrieveParams = {
+ /**
+ * Maximum number of validated prediction dates to return, newest first (default 60, at most 180). Each date returns one row per model that emitted predictions on it.
+ * @minimum 1
+ * @maximum 180
+ */
+ limit?: number;
+ };
+
export type BatchExportsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.ts
index 9b46d1673d11..f36ca37434be 100644
--- a/services/mcp/src/generated/autoresearch/api.ts
+++ b/services/mcp/src/generated/autoresearch/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 22 enabled ops
+ * PostHog API - MCP 23 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -629,6 +629,33 @@ export const AutoresearchRetrieveParams = () => zod.object({
),
})
+/**
+ * Return the realized metrics online validation recorded for each model on each validated prediction date, newest date first. Each row has realized AUC with a 95% interval, Brier score, calibration error, quantile calibration bins, mean predicted probability against the base rate, lift, and the model's role when it emitted and now. The rows come from the validation runs, so a former champion that a promotion archived keeps its history. Read-only; it runs no queries.
+ * @summary Read realized performance history
+ */
+export const AutoresearchOnlinePerformanceRetrieveParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this autoresearch pipeline.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const autoresearchOnlinePerformanceRetrieveQueryLimitDefault = 60
+export const autoresearchOnlinePerformanceRetrieveQueryLimitMax = 180
+
+export const AutoresearchOnlinePerformanceRetrieveQueryParams = () => zod.object({
+ limit: zod
+ .number()
+ .min(1)
+ .max(autoresearchOnlinePerformanceRetrieveQueryLimitMax)
+ .default(autoresearchOnlinePerformanceRetrieveQueryLimitDefault)
+ .describe(
+ 'Maximum number of validated prediction dates to return, newest first (default 60, at most 180). Each date returns one row per model that emitted predictions on it.'
+ ),
+})
+
/**
* Start scoring the inference population using the champion model. Scoring runs in the background: it emits autoresearch_prediction events for each scored user and sets the pipeline's output_person_property on each scored person. The response returns at once with the running run. A second request while a run is running returns that run and starts nothing. The daily Temporal inference workflow also scores each pipeline on its cadence.
* @summary Run inference (score users)
diff --git a/services/mcp/src/tools/generated/autoresearch.ts b/services/mcp/src/tools/generated/autoresearch.ts
index 8b6198728d1c..be0e2335125e 100644
--- a/services/mcp/src/tools/generated/autoresearch.ts
+++ b/services/mcp/src/tools/generated/autoresearch.ts
@@ -208,6 +208,37 @@ const autoresearchModelsRetrieve = (): ToolBase<
},
})
+const AutoresearchOnlinePerformanceRetrieveSchema = () => {
+ const AutoresearchOnlinePerformanceRetrieveParams = orvalSchemas.AutoresearchOnlinePerformanceRetrieveParams()
+ const AutoresearchOnlinePerformanceRetrieveQueryParams =
+ orvalSchemas.AutoresearchOnlinePerformanceRetrieveQueryParams()
+ return AutoresearchOnlinePerformanceRetrieveParams.omit({ project_id: true }).extend(
+ AutoresearchOnlinePerformanceRetrieveQueryParams.shape
+ )
+}
+
+const autoresearchOnlinePerformanceRetrieve = (): ToolBase<
+ ReturnType<typeof AutoresearchOnlinePerformanceRetrieveSchema>,
+ Schemas.OnlinePerformance
+> => ({
+ name: 'autoresearch-online-performance-retrieve',
+ schema: AutoresearchOnlinePerformanceRetrieveSchema(),
+ handler: async (
+ context: Context,
+ params: z.infer<ReturnType<typeof AutoresearchOnlinePerformanceRetrieveSchema>>
+ ) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.OnlinePerformance>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.id))}/online_performance/`,
+ query: {
+ limit: params.limit,
+ },
+ })
+ return result
+ },
+})
+
const AutoresearchResolveTemplateCreateSchema = () => {
const AutoresearchResolveTemplateCreateBody = orvalSchemas.AutoresearchResolveTemplateCreateBody()
return AutoresearchResolveTemplateCreateBody
@@ -832,6 +863,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'autoresearch-materialize-features': autoresearchMaterializeFeatures,
'autoresearch-models-list': autoresearchModelsList,
'autoresearch-models-retrieve': autoresearchModelsRetrieve,
+ 'autoresearch-online-performance-retrieve': autoresearchOnlinePerformanceRetrieve,
'autoresearch-resolve-template-create': autoresearchResolveTemplateCreate,
'autoresearch-retrieve': autoresearchRetrieve,
'autoresearch-runs-list': autoresearchRunsList,