: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): validate predictions online once horizons mature (12/22) (#89142)
Andrew Maguire77dd997d0c24
diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.mdnew file mode 100644index 000000000000..5b7777f42671--- /dev/null+++ b/products/autoresearch/backend/evaluation/AGENTS.md@@ -0,0 +1,74 @@+# Evaluation++Did the predictions actually come true?++Training measures a model against a holdout slice of history. This package measures it against reality: once a prediction's horizon has elapsed, it joins the emitted `autoresearch_prediction` events back to what the person actually did and computes realized performance.++It is the only honest number in the product. A holdout AUC of 0.93 says the model separates history well; the realized AUC says whether it predicted the future.++This package landed ahead of its callers. `../presentation/` and `../temporal/` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.++## What lives here++- `online_validation.py`+ `run_online_validation_for_pipeline()` is the entry point, called by the Temporal validation activity and by the `autoresearch_validate_online` command. It takes the acting `user` HogQL applies access control for, defaulting to the pipeline's creator.++ 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)+ - **Brier score** — squared error of the probabilities+ - **expected calibration error** (`_expected_calibration_error`, 10 bins) — whether "0.8" really means 80%+ - **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++ 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.++## Mental model++```text+completed inference run for day D (metrics: prediction_date, horizon_days, rows_scored)+ │+ │ ... wait horizon_days ...+ │+ D + horizon 00:00 UTC + grace <= now → the outcome window has closed and its last events have landed+ │+ find_pending_validation_dates → matured (date, horizon) groups whose validation does not match their inference runs+ │+ _claim_date (RUNNING run, under the pipeline row lock)+ │+ _fetch_predictions × _fetch_realized_labels → metrics per model → one transaction+```++Candidate dates come from Postgres, not from a scan of the events table: the inference runs record the prediction date and the horizon they scored against, so a daily pass costs nothing for the dates it does not validate, and the horizon used is the one the predictions were made under.++`find_pending_validation_dates()` is what keeps this idempotent. A group is done once a `COMPLETED` validation run holds the same per-model counts as the group's inference runs, so the workflow can run daily without recomputing history, and a later rescore or a new model on the date makes the group pending again and replaces its evidence. A `FAILED` run does not count, so its group is retried. A `RUNNING` validation claim, and a `RUNNING` inference run, hold the group only while younger than `STALE_RUN_AFTER`, so a worker killed mid-run cannot block it forever. Models scored on one date under different horizons are separate groups with their own outcome windows. Maturity waits `OUTCOME_INGESTION_GRACE` past the window end so the last outcome events have reached ClickHouse.++Both ClickHouse queries are bounded by what the inference runs say was emitted. The prediction fetch must return exactly `rows_scored` persons per model; fewer means ingestion has not caught up with a backfill, more means events the run did not emit, and either fails the date so it is retried instead of completing with wrong numbers. The realized-label scan is restricted to the predicted persons, and its window is the UTC one scoring bound the run to (`[D 00:00, D + horizon 00:00)`). Before the group is marked complete, its inference runs are read again inside the transaction: a run that finished or started while the queries ran fails the group, and a run that slips in after that check changes the counts and makes the group pending again on the next pass. The model rows are locked for the write, so two validators on different dates cannot race the newest-date guard.++All the heavy work — the HogQL queries and the sklearn metrics — happens inside a single Temporal activity. Nothing large crosses a workflow boundary, which is deliberate: activity payloads are capped, and prediction sets are big.++## Things that bite++- **Nothing to validate on day one.** Predictions written today mature in `horizon_days`. A fresh pipeline returns zero validated dates and that is correct, not a bug.+ To get a populated view locally, backdate: `autoresearch_score --prediction-date <past>` or `--backfill-days N` emits already-matured predictions.+- **A backfill's date fails validation until its events are all in ClickHouse.** The fetch compares against the run's `rows_scored`, so a pass that runs seconds after a backfill records a `FAILED` run and the next pass picks the date up.+- **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.++## Where the rest of the system meets this package++- **Scheduled by** — `AutoresearchValidationWorkflow` / `activity_run_validation` in `../temporal/workflows.py`.+- **Run headlessly by** — `autoresearch_validate_online` (see `../management/AGENTS.md`), which supports `--dry-run` and `--user-id`, and exits non-zero when a date fails.+- **Reads** — `autoresearch_prediction` events emitted by `../inference/`, the `prediction_date` / `horizon_days` keys `scoring.py` records on each inference run, and the target condition from `../dataset/labeling.py` (`build_target_condition`) so "did it happen?" is defined identically to how it was labeled at training time. The product's own prediction event is excluded from the outcome scan, as it is from the labeler's.+- **Writes** — realized metrics onto `AutoresearchModel`, plus an `AutoresearchRun` per validated date.+- **Not to be confused with** `../dataset/validation.py`, which is pre-flight target viability. Same word, opposite ends of the lifecycle.++## When editing this flow++- **Reuse `build_target_condition()` from `../dataset/labeling.py`.** If realized outcomes were defined differently from training labels, every realized metric would be measuring a different question than the model was trained on.+- Keep `find_pending_validation_dates()` the only date selector, and keep the claim under the pipeline row lock, so validation stays idempotent and safe to run from the schedule and the command at once. A validation run's `per_model` entry carries each model's `n_scored`, which is what marks a group validated; keep writing it.+- Keep every query bounded by the inference runs' counts. A bare HogQL SELECT is capped at 100 rows without an error.+- Keep the model updates and the run write in one transaction, so a failure part-way leaves no model with a score its run does not record.+- Keep the heavy work inside one activity. Returning prediction sets through the workflow would hit the Temporal payload limit as soon as a pipeline scores a real population.+- **If you add a metric or change the maturity rule, update this file to match.**diff --git a/products/autoresearch/backend/evaluation/CLAUDE.md b/products/autoresearch/backend/evaluation/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/products/autoresearch/backend/evaluation/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/products/autoresearch/backend/evaluation/__init__.py b/products/autoresearch/backend/evaluation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.pynew file mode 100644index 000000000000..2cb113f9cf23--- /dev/null+++ b/products/autoresearch/backend/evaluation/online_validation.py@@ -0,0 +1,683 @@+"""+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.++Architecture:+- Pure activity functions called by AutoresearchValidationWorkflow (Temporal)+ and the autoresearch_validate_online management command.+- All heavy work (HogQL queries + sklearn metrics) happens inside a single activity;+ nothing large passes through Temporal payloads.+- Candidate dates come from the completed inference runs in Postgres, never from a+ scan of the events table, and every ClickHouse query is bounded by what those runs+ say was emitted.+"""++import math+from datetime import UTC, date, datetime, timedelta+from typing import Any++from django.db import transaction+from django.db.models import Q+from django.utils import timezone as django_timezone++import numpy as np+import structlog++from posthog.schema import HogQLQuery++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.dataclasses import frozen+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models.team.team import Team+from posthog.models.user import User++from products.autoresearch.backend.dataset.labeling import (+ LABELER_QUERY_MODIFIERS,+ PREDICTION_EVENT_NAME,+ _own_events_excluded_clause,+ build_target_condition,+)+from products.autoresearch.backend.inference.sandbox import SandboxInferenceError, _resolve_acting_user+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun+from products.autoresearch.backend.query import HogQLResult, run_hogql++logger = structlog.get_logger(__name__)++# A validation run does two bounded queries and a scoring run is bounded by its sandbox+# timeouts, so a RUNNING row older than this belongs to a worker that died mid-run and the+# exception handler never ran. Neither kind may hold a date forever.+STALE_RUN_AFTER = timedelta(hours=6)++# An outcome event timestamped just before the window closes can still be in the ingestion+# queue when the window closes. Maturity waits this long past the window end so it lands+# first; a completed date is never revisited, so a positive that arrives later than this+# reads as a negative.+OUTCOME_INGESTION_GRACE = timedelta(hours=1)++# A live run stamps its events at emission time, which can cross midnight UTC before the+# batch goes out; a backfill stamps noon UTC of the date. Both fall within this many days+# of the start of the prediction date, so the fetch can bound `timestamp` for pruning.+_EMISSION_WINDOW_DAYS = 2+++class OnlineValidationError(Exception):+ """The date must fail, and be retried on a later pass, instead of completing with metrics from bad data."""+++@frozen+class PendingValidationDate:+ """A matured prediction date with no completed validation, and what its inference runs emitted."""++ prediction_date: date+ horizon_days: int+ # rows_scored of the latest completed inference run per model id. The prediction+ # events for the date must match these counts exactly before metrics are trusted.+ expected_rows_by_model: dict[str, int]++ @property+ def window_start(self) -> datetime:+ # Scoring binds every run to the start of its prediction date in UTC, so the+ # outcome window opens at the same instant whatever the project's timezone.+ return datetime(self.prediction_date.year, self.prediction_date.month, self.prediction_date.day, tzinfo=UTC)++ @property+ def window_end(self) -> datetime:+ return self.window_start + timedelta(days=self.horizon_days)++ @property+ def emitted_before(self) -> datetime:+ return self.window_start + timedelta(days=_EMISSION_WINDOW_DAYS)++ @property+ def expected_rows(self) -> int:+ return sum(self.expected_rows_by_model.values())++ @property+ def key(self) -> tuple[date, int]:+ return (self.prediction_date, self.horizon_days)+++@frozen+class _ModelPredictions:+ emitted_role: str+ p_y_by_person: dict[str, float]+++@frozen+class _ModelValidation:+ emitted_role: str+ metrics: dict[str, Any]+++def run_online_validation_for_pipeline(+ pipeline: AutoresearchPipeline, *, user: User | None = None+) -> list[AutoresearchRun]:+ """+ Validate every matured prediction date that has no completed validation yet.++ A date is matured when its outcome window, ``[prediction_date, prediction_date ++ horizon_days)`` in UTC, has closed. Each date is claimed with an ``AutoresearchRun``+ before any query runs, so two validators cannot score the same date. Returns one run+ per date processed, COMPLETED or FAILED, and updates ``realized_score`` and+ ``calibration_error`` on each model that emitted predictions.++ ``user`` is who HogQL applies access control for; it defaults to the pipeline's creator.+ """+ team = pipeline.team+ acting_user = _acting_user(team=team, pipeline=pipeline, user=user)+ pending = find_pending_validation_dates(pipeline)+ if not pending:+ logger.info("autoresearch_validation_no_mature_dates", pipeline_id=str(pipeline.pk))+ return []++ results: list[AutoresearchRun] = []+ for item in pending:+ run = _claim_date(pipeline, item)+ if run is None:+ continue+ results.append(_validate_claimed_date(team=team, pipeline=pipeline, run=run, pending=item, user=acting_user))+ return results+++def _acting_user(*, team: Team, pipeline: AutoresearchPipeline, user: User | None) -> User:+ try:+ return _resolve_acting_user(team=team, pipeline=pipeline, user=user)+ except SandboxInferenceError as exc:+ raise OnlineValidationError(str(exc)) from exc+++# ── Date selection and claiming ───────────────────────────────────────────────────+++def find_pending_validation_dates(pipeline: AutoresearchPipeline) -> list[PendingValidationDate]:+ """+ Matured (date, horizon) groups whose validation does not match their inference runs, oldest first.++ Candidates come from the completed inference runs, which record the prediction date and+ the horizon they scored against; models scored on one date under different horizons form+ separate groups with their own outcome windows. A group waits while an inference run for+ it is still scoring, and for ``OUTCOME_INGESTION_GRACE`` after its window closes. It is+ done once a COMPLETED validation run holds the same per-model counts as its inference+ runs, so a later rescore or a new model on the date makes it pending again. A FAILED+ validation run does not count; a RUNNING one, like a RUNNING inference run, counts only+ while it is younger than ``STALE_RUN_AFTER``.+ """+ now = django_timezone.now()+ scoring = _groups_still_scoring(pipeline, now=now)+ state = _validation_state(pipeline, now=now)+ return [+ item+ for item in _scored_groups(pipeline)+ if item.key not in scoring and not _is_blocked(item, state) and item.window_end + OUTCOME_INGESTION_GRACE <= now+ ]+++def _scored_groups(pipeline: AutoresearchPipeline) -> list[PendingValidationDate]:+ """Every (date, horizon) with a completed inference run, oldest first, with the rows each model's latest run emitted."""+ runs = (+ AutoresearchRun.objects.filter(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=AutoresearchRun.Status.COMPLETED,+ model__isnull=False,+ rows_scored__gt=0,+ )+ # Ascending, so the latest run for a (group, model) is the one whose counts survive.+ .order_by("completed_at", "created_at")+ .values_list("model_id", "rows_scored", "metrics")+ )+ expected_by_group: dict[tuple[date, int], dict[str, int]] = {}+ for model_id, rows_scored, metrics in runs:+ key = _group_key(metrics)+ if key is None or rows_scored is None:+ continue+ expected_by_group.setdefault(key, {})[str(model_id)] = int(rows_scored)+ return [+ PendingValidationDate(+ prediction_date=prediction_date, horizon_days=horizon_days, expected_rows_by_model=expected+ )+ for (prediction_date, horizon_days), expected in sorted(expected_by_group.items())+ ]+++def _group_key(metrics: dict[str, Any]) -> tuple[date, int] | None:+ stamp = metrics.get("prediction_date")+ horizon_days = metrics.get("horizon_days")+ if not isinstance(stamp, str) or not isinstance(horizon_days, int):+ return None+ return (date.fromisoformat(stamp), horizon_days)+++def _groups_still_scoring(pipeline: AutoresearchPipeline, *, now: datetime) -> set[tuple[date, int]]:+ in_flight = AutoresearchRun.objects.filter(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status__in=(AutoresearchRun.Status.PENDING, AutoresearchRun.Status.RUNNING),+ created_at__gte=now - STALE_RUN_AFTER,+ ).values_list("metrics", flat=True)+ return {key for key in (_group_key(m) for m in in_flight) if key is not None}+++def _validation_state(+ pipeline: AutoresearchPipeline, *, now: datetime+) -> dict[tuple[date, int], list[dict[str, int] | None]]:+ """Per group: the per-model counts each COMPLETED validation run scored, and None for each live claim."""+ runs = (+ AutoresearchRun.objects.filter(pipeline=pipeline, run_type=AutoresearchRun.RunType.VALIDATION)+ .filter(+ Q(status=AutoresearchRun.Status.COMPLETED)+ | Q(status=AutoresearchRun.Status.RUNNING, started_at__gte=now - STALE_RUN_AFTER)+ )+ .values_list("status", "metrics")+ )+ state: dict[tuple[date, int], list[dict[str, int] | None]] = {}+ for status, metrics in runs:+ key = _group_key(metrics)+ if key is None:+ continue+ if status == AutoresearchRun.Status.RUNNING:+ state.setdefault(key, []).append(None)+ continue+ per_model = metrics.get("per_model") or {}+ state.setdefault(key, []).append(+ {+ model_id: int(m["n_scored"])+ for model_id, m in per_model.items()+ if isinstance(m, dict) and "n_scored" in m+ }+ )+ return state+++def _is_blocked(item: PendingValidationDate, state: dict[tuple[date, int], list[dict[str, int] | None]]) -> bool:+ # A completed validation may hold counts for a model deleted since; a deleted model never+ # returns, so only a model the validation has not seen at these counts reopens the group.+ return any(+ counts is None or all(counts.get(model_id) == n for model_id, n in item.expected_rows_by_model.items())+ for counts in state.get(item.key, [])+ )+++def _claim_date(pipeline: AutoresearchPipeline, pending: PendingValidationDate) -> AutoresearchRun | None:+ """+ Record a RUNNING validation run for the group, or return None when another validator+ already holds it or has validated these exact runs. The check and the insert happen+ under the pipeline row's lock, so the scheduled activity and a manual command cannot+ both score the same group. FOR NO KEY UPDATE leaves the KEY SHARE locks an inference+ run's insert takes on the same row unblocked.+ """+ now = django_timezone.now()+ with transaction.atomic():+ AutoresearchPipeline.objects.select_for_update(no_key=True).get(pk=pipeline.pk, team_id=pipeline.team_id)+ if _is_blocked(pending, _validation_state(pipeline, now=now)):+ return None+ return AutoresearchRun.objects.create(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.VALIDATION,+ status=AutoresearchRun.Status.RUNNING,+ started_at=now,+ metrics={"prediction_date": pending.prediction_date.isoformat(), "horizon_days": pending.horizon_days},+ )+++# ── Validating one date ───────────────────────────────────────────────────────────+++def _validate_claimed_date(+ *,+ team: Team,+ pipeline: AutoresearchPipeline,+ run: AutoresearchRun,+ pending: PendingValidationDate,+ user: User,+) -> AutoresearchRun:+ """+ Compute realized metrics for every model that emitted predictions on the date, then+ persist the model updates and the run in one transaction.++ Any failure marks the run FAILED with nothing written to the models, so the date stays+ eligible for the next pass and the other dates in this pass are unaffected.+ """+ try:+ predictions = _fetch_predictions(team=team, pipeline=pipeline, pending=pending, user=user)+ n_predicted = sum(len(model.p_y_by_person) for model in predictions.values())+ realized = _fetch_realized_labels(+ team=team, pipeline=pipeline, pending=pending, n_predicted=n_predicted, user=user+ )+ per_model = {+ model_id: _ModelValidation(+ emitted_role=model.emitted_role,+ metrics=_compute_validation_metrics(model.p_y_by_person, realized),+ )+ for model_id, model in predictions.items()+ }+ _persist_completed(+ pipeline=pipeline, run=run, pending=pending, per_model=per_model, realized_count=len(realized)+ )+ logger.info(+ "autoresearch_validation_complete",+ pipeline_id=str(pipeline.pk),+ prediction_date=pending.prediction_date.isoformat(),+ models_validated=len(per_model),+ total_rows=n_predicted,+ )+ except Exception as exc:+ run.status = AutoresearchRun.Status.FAILED+ run.error = str(exc)[:2000]+ run.completed_at = django_timezone.now()+ run.save(update_fields=["status", "error", "completed_at"])+ logger.exception(+ "autoresearch_validation_failed",+ pipeline_id=str(pipeline.pk),+ prediction_date=pending.prediction_date.isoformat(),+ )+ return run+++def _persist_completed(+ *,+ pipeline: AutoresearchPipeline,+ run: AutoresearchRun,+ pending: PendingValidationDate,+ per_model: dict[str, _ModelValidation],+ realized_count: int,+) -> None:+ run_metrics: dict[str, Any] = {}+ total_rows = 0+ with transaction.atomic():+ # A run that completed or started for this group while the queries ran is missing from+ # the counts the fetch was checked against. A model deleted meanwhile takes its run out+ # of the group; its evidence is still written below, so that alone does not fail it.+ now = django_timezone.now()+ current = {item.key: item.expected_rows_by_model for item in _scored_groups(pipeline)}.get(pending.key, {})+ changed = any(pending.expected_rows_by_model.get(model_id) != n for model_id, n in current.items())+ vanished = set(pending.expected_rows_by_model) - set(current)+ vanished_but_present = (+ AutoresearchModel.objects.filter(pk__in=vanished, pipeline=pipeline, team_id=pipeline.team_id).exists()+ if vanished+ else False+ )+ if changed or vanished_but_present or pending.key in _groups_still_scoring(pipeline, now=now):+ raise OnlineValidationError(+ f"The inference runs for {pending.prediction_date.isoformat()} changed while it was being validated; "+ "retrying on the next pass"+ )+ for model_id, validation in per_model.items():+ # Locked so two validators on different dates cannot race the newest-date guard.+ model = (+ AutoresearchModel.objects.select_for_update()+ .filter(pk=model_id, pipeline=pipeline, team_id=pipeline.team_id)+ .first()+ )+ if model is not None:+ _update_model_realized_metrics(model, validation.metrics, prediction_date=pending.prediction_date)+ run_metrics[model_id] = {+ # Promotion can change the role before the horizon closes, so both are kept.+ "emitted_role": validation.emitted_role,+ "model_role": model.role if model is not None else "deleted",+ **validation.metrics,+ }+ total_rows += int(validation.metrics["n_scored"])+ run.status = AutoresearchRun.Status.COMPLETED+ run.rows_scored = total_rows+ run.completed_at = django_timezone.now()+ run.metrics.update({"realized_labels_count": realized_count, "per_model": run_metrics})+ run.save(update_fields=["status", "rows_scored", "completed_at", "metrics"])+++# ── Queries ────────────────────────────────────────────────────────────────────────+++def _prediction_filter() -> str:+ return (+ " event = {event_name}"+ " AND properties['$autoresearch_pipeline_id'] = {pipeline_id}"+ " AND properties['$autoresearch_prediction_date'] = {prediction_date}"+ " AND properties['$autoresearch_model_id'] IN {model_ids}"+ " AND properties['$autoresearch_horizon_days'] = {horizon_days}"+ " AND properties['$autoresearch_person_id'] != ''"+ " AND timestamp >= {emitted_from} AND timestamp < {emitted_before}"+ )+++def _prediction_values(pipeline: AutoresearchPipeline, pending: PendingValidationDate) -> dict[str, Any]:+ return {+ "event_name": PREDICTION_EVENT_NAME,+ "pipeline_id": str(pipeline.pk),+ "prediction_date": pending.prediction_date.isoformat(),+ "model_ids": tuple(pending.expected_rows_by_model),+ # Property values read back as strings, whatever type scoring emitted.+ "horizon_days": str(pending.horizon_days),+ "emitted_from": pending.window_start,+ "emitted_before": pending.emitted_before,+ }+++def _fetch_predictions(+ *, team: Team, pipeline: AutoresearchPipeline, pending: PendingValidationDate, user: User+) -> dict[str, _ModelPredictions]:+ """+ ``{model_id: predictions}`` for every model the inference runs say scored the date.++ Keyed on ``$autoresearch_person_id``, the person key every scored row carries, so the+ join to realized labels compares the same key space. Only models with a completed+ inference run are fetched, and each model's row count must equal that run's+ ``rows_scored``: fewer means ingestion has not caught up with a backfill yet, more+ means events the run did not emit. Either way the metrics would be wrong, so the date+ fails and is retried.+ """+ # argMax picks the latest emission per (model, person). Backfills stamp every event of+ # a date at the same instant, so the event UUID breaks those ties rather than leaving+ # them to merge order.+ sql = (+ "SELECT"+ " properties['$autoresearch_model_id'] AS model_id,"+ " properties['$autoresearch_person_id'] AS person_id,"+ " argMax(toFloatOrNull(properties['$autoresearch_p_y']), (timestamp, uuid)) AS p_y,"+ " any(properties['$autoresearch_model_role']) AS emitted_role"+ " FROM events"+ f" WHERE{_prediction_filter()}"+ " GROUP BY model_id, person_id"+ )+ result = _query(+ team=team,+ sql=sql,+ values=_prediction_values(pipeline, pending),+ user=user,+ limit=pending.expected_rows + 1,+ what="Predictions",+ )++ roles: dict[str, str] = {}+ scores: dict[str, dict[str, float]] = {}+ for model_id, person_id, p_y, emitted_role in result.rows:+ if p_y is None:+ raise OnlineValidationError(+ f"Prediction for person {person_id} of model {model_id} carries a non-numeric $autoresearch_p_y; "+ "refusing to compute metrics from it"+ )+ scores.setdefault(str(model_id), {})[str(person_id)] = float(p_y)+ roles.setdefault(str(model_id), str(emitted_role or ""))++ for model_id, expected in pending.expected_rows_by_model.items():+ found = len(scores.get(model_id, {}))+ if found < expected:+ raise OnlineValidationError(+ f"Found {found} of the {expected} predictions model {model_id} emitted for "+ f"{pending.prediction_date.isoformat()}; ingestion may not have caught up, retrying on the next pass"+ )+ if found > expected:+ raise OnlineValidationError(+ f"Found {found} predictions for model {model_id} on {pending.prediction_date.isoformat()} but its "+ f"inference run emitted {expected}; refusing to compute metrics from events the run did not emit"+ )+ return {+ model_id: _ModelPredictions(emitted_role=roles[model_id], p_y_by_person=p_y_by_person)+ for model_id, p_y_by_person in scores.items()+ }+++def _fetch_realized_labels(+ *, team: Team, pipeline: AutoresearchPipeline, pending: PendingValidationDate, n_predicted: int, user: User+) -> frozenset[str]:+ """+ The predicted persons who performed the pipeline's target inside the outcome window.++ The target predicate is ``build_target_condition``, the same one that labeled the+ training data, and the window is the UTC one scoring bound the run to. The scan is+ restricted to the persons the prediction events name, so its size is bounded by the+ predictions and not by how many people on the team performed the target. The+ product's own prediction event is excluded, so a target that matches it does not turn+ every scored person into a positive.+ """+ target_cond, target_values = build_target_condition(+ target_event=pipeline.target_event, target_definition=pipeline.target_definition, team=team+ )+ sql = (+ "SELECT DISTINCT toString(person_id) AS person_id"+ " FROM events"+ f" WHERE {target_cond}{_own_events_excluded_clause()}"+ " AND timestamp >= {window_start} AND timestamp < {window_end}"+ " AND toString(person_id) IN ("+ "SELECT DISTINCT properties['$autoresearch_person_id'] FROM events"+ f" WHERE{_prediction_filter()}"+ ")"+ )+ values: dict[str, Any] = {+ **_prediction_values(pipeline, pending),+ **target_values,+ "window_start": pending.window_start,+ "window_end": pending.window_end,+ }+ result = _query(team=team, sql=sql, values=values, user=user, limit=n_predicted + 1, what="Realized labels")+ return frozenset(str(row[0]) for row in result.rows if row[0])+++def _query(*, team: Team, sql: str, values: dict[str, Any], user: User, limit: int, what: str) -> HogQLResult:+ """+ Run a query as the acting user, fresh, with an explicit bound.++ HogQL caps a bare SELECT at 100 rows without an error, so every query here carries a+ LIMIT one above the rows the caller can account for, and a result that reaches it is+ refused. The persons-on-events modifiers keep ``person_id`` resolving the way the+ labeler's queries do, and the always-calculate mode stops a retry reading a cached+ result from before ingestion caught up.+ """+ bounded_sql = sql.rstrip().rstrip(";") + "\nLIMIT {limit}"+ try:+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)+ result = run_hogql(+ team=team,+ query=HogQLQuery(query=bounded_sql, values={**values, "limit": limit}, modifiers=LABELER_QUERY_MODIFIERS),+ user=user,+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ )+ except Exception as exc:+ logger.exception("autoresearch_validation_query_failed", team_id=team.pk, what=what)+ raise OnlineValidationError(f"{what} query failed; failing the date so it is retried") from exc+ if result.has_more or len(result.rows) >= limit:+ raise OnlineValidationError(+ f"{what} query returned more rows than the inference runs account for ({limit - 1}); "+ "refusing to compute metrics from them"+ )+ return result+++# ── Metrics ────────────────────────────────────────────────────────────────────────+++def _compute_validation_metrics(+ predictions: dict[str, float],+ realized_labels: frozenset[str],+) -> dict[str, Any]:+ """+ AUC, Brier score, ECE, 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.+ """+ person_ids = list(predictions.keys())+ y_score = np.array([predictions[pid] for pid in person_ids], dtype=np.float64)+ y_true = np.array([1 if pid in realized_labels else 0 for pid in person_ids], dtype=np.int32)++ n = len(y_true)+ n_pos = int(y_true.sum())+ n_neg = n - n_pos++ metrics: dict[str, Any] = {+ "n_scored": n,+ "n_positive": n_pos,+ "n_negative": n_neg,+ "base_rate": round(n_pos / n, 4) if n > 0 else 0.0,+ }+ if n == 0:+ return metrics++ # Deferred to keep the heavy dependency off the import path.+ from sklearn.metrics import brier_score_loss, roc_auc_score # noqa: PLC0415++ 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)+ 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["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+++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 difference+ between mean predicted probability and actual positive rate within each decile bin.+ """+ n = len(y_true)+ bin_boundaries = np.linspace(0.0, 1.0, n_bins + 1)+ ece = 0.0+ for i in range(n_bins):+ lo, hi = bin_boundaries[i], bin_boundaries[i + 1]+ mask = (y_score >= lo) & (y_score <= hi) if i == n_bins - 1 else (y_score >= lo) & (y_score < hi)+ if not mask.any():+ continue+ bin_n = int(mask.sum())+ avg_pred = float(y_score[mask].mean())+ actual_rate = float(y_true[mask].mean())+ ece += (bin_n / n) * abs(avg_pred - actual_rate)+ return ece+++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.++ A lift of 2.0 at k=10% means the top 10% by score contains twice the positives a+ random 10% sample would. Rows tied at the boundary score are counted fractionally,+ so the number does not depend on the order ClickHouse returned the tied persons in.+ """+ n_pos_total = int(y_true.sum())+ n = len(y_true)+ if n == 0 or n_pos_total == 0 or k <= 0:+ return 0.0+ cutoff = max(1, math.ceil(n * k))+ boundary = float(np.sort(y_score)[::-1][cutoff - 1])+ above = y_score > boundary+ tied = y_score == boundary+ tie_share = (cutoff - int(above.sum())) / int(tied.sum())+ positives_captured = float(y_true[above].sum()) + tie_share * float(y_true[tied].sum())+ # Normalize by the fraction actually selected, not the requested k: rounding up to a+ # whole user would otherwise overstate lift on small validation sets.+ random_expected = (cutoff / n) * n_pos_total+ return positives_captured / random_expected+++def _update_model_realized_metrics(model: AutoresearchModel, metrics: dict[str, Any], *, prediction_date: date) -> None:+ """+ Persist a date's realized metrics onto the model row.++ The first realized AUC clears ``is_preliminary``. Later dates replace the model-level+ numbers only when they are newer than what is stored: a retry of an older date that+ failed earlier must not overwrite the evidence a newer date already left.+ """+ existing = dict(model.metrics or {})+ stored_date = (existing.get("realized") or {}).get("prediction_date")+ if isinstance(stored_date, str) and stored_date > prediction_date.isoformat():+ logger.info(+ "autoresearch_model_realized_metrics_kept_newer",+ model_id=str(model.pk),+ stored_prediction_date=stored_date,+ prediction_date=prediction_date.isoformat(),+ )+ return++ auc = metrics.get("realized_auc")+ cal_error = metrics.get("calibration_error")+ existing["realized"] = {**metrics, "prediction_date": prediction_date.isoformat()}+ model.metrics = existing+ update_fields = ["metrics", "updated_at"]++ if auc is not None:+ model.realized_score = auc+ update_fields.append("realized_score")+ if model.is_preliminary:+ model.is_preliminary = False+ update_fields.append("is_preliminary")++ if cal_error is not None:+ model.calibration_error = cal_error+ update_fields.append("calibration_error")++ model.save(update_fields=update_fields)++ logger.info(+ "autoresearch_model_realized_metrics_updated",+ model_id=str(model.pk),+ role=model.role,+ realized_auc=auc,+ calibration_error=cal_error,+ is_preliminary=model.is_preliminary,+ )diff --git a/products/autoresearch/backend/evaluation/test_online_validation.py b/products/autoresearch/backend/evaluation/test_online_validation.pynew file mode 100644index 000000000000..20f99c6a4815--- /dev/null+++ b/products/autoresearch/backend/evaluation/test_online_validation.py@@ -0,0 +1,476 @@+from datetime import UTC, date, datetime, timedelta++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase+from django.utils import timezone as django_timezone++import numpy as np+from parameterized import parameterized++from posthog.models.user import User++from products.autoresearch.backend.evaluation import online_validation+from products.autoresearch.backend.evaluation.online_validation import (+ OUTCOME_INGESTION_GRACE,+ STALE_RUN_AFTER,+ OnlineValidationError,+ _compute_validation_metrics,+ _expected_calibration_error,+ _lift_at_k,+ _update_model_realized_metrics,+ find_pending_validation_dates,+ run_online_validation_for_pipeline,+)+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRun+from products.autoresearch.backend.query import HogQLResult+from products.autoresearch.backend.testing import TeamScopedTestMixin++FROZEN_NOW = "2026-09-11T12:00:00Z"+++class TestComputeValidationMetrics(SimpleTestCase):+ def _predictions(self) -> dict[str, float]:+ 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"]))+ assert metrics["n_scored"] == 5+ assert metrics["n_positive"] == 2+ assert metrics["n_negative"] == 3+ assert metrics["base_rate"] == 0.4+ assert 0.0 <= metrics["brier_score"] <= 1.0+ assert 0.0 <= metrics["calibration_error"] <= 1.0+ assert metrics["lift_at_10"] > 0.0++ @parameterized.expand(+ [+ ("perfect_separation", {"high-1": 0.95, "high-2": 0.90, "low-1": 0.05, "low-2": 0.10}, 1.0),+ ("reversed_scores", {"high-1": 0.05, "high-2": 0.10, "low-1": 0.95, "low-2": 0.90}, 0.0),+ ]+ )+ def test_realized_auc(self, _name, preds, expected_auc):+ metrics = _compute_validation_metrics(preds, frozenset(["high-1", "high-2"]))+ assert metrics["realized_auc"] == expected_auc++ @parameterized.expand(+ [+ ("no_positives", frozenset()),+ ("no_negatives", frozenset(["user-1", "user-2"])),+ ]+ )+ def test_single_class_skips_only_the_auc(self, _name, labels):+ metrics = _compute_validation_metrics({"user-1": 0.5, "user-2": 0.6}, labels)+ assert metrics["warning"] == "single_class_no_auc"+ assert "realized_auc" not in metrics+ assert 0.0 <= metrics["brier_score"] <= 1.0+ assert 0.0 <= metrics["calibration_error"] <= 1.0+ assert "lift_at_10" in metrics+++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]))+ assert abs(ece) < 1e-6++ def test_overconfident_model_high_ece(self):+ ece = _expected_calibration_error(np.array([0, 0, 0, 0]), np.array([0.9, 0.9, 0.9, 0.9]))+ assert ece > 0.5+++class TestLiftAtK(SimpleTestCase):+ def test_perfect_ranking_lift_at_50_is_2(self):+ lift = _lift_at_k(np.array([1, 1, 0, 0]), np.array([0.9, 0.8, 0.2, 0.1]), k=0.5)+ assert abs(lift - 2.0) < 1e-6++ def test_no_positives_returns_zero(self):+ assert _lift_at_k(np.array([0, 0, 0]), np.array([0.9, 0.5, 0.1]), k=0.5) == 0.0++ def test_lift_normalizes_by_the_rows_actually_selected(self):+ # 11 users at k=0.1 selects 2 rows (ceil), so the random baseline is 2/11 of the+ # positives, not 1.1.+ y_true = np.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0])+ y_score = np.array([0.99, 0.98, 0.5, 0.4, 0.3, 0.2, 0.1, 0.09, 0.08, 0.07, 0.06])+ assert abs(_lift_at_k(y_true, y_score, k=0.1) - 5.5) < 1e-6++ def test_ties_at_the_boundary_are_split_fractionally_whatever_the_row_order(self):+ y_true = np.array([1, 0, 0, 0, 1, 0])+ y_score = np.full(6, 0.5)+ assert abs(_lift_at_k(y_true, y_score, k=0.5) - 1.0) < 1e-6+ assert abs(_lift_at_k(y_true[::-1], y_score, k=0.5) - 1.0) < 1e-6+++def _make_pipeline(team, user: User | None, horizon_days: int = 7) -> AutoresearchPipeline:+ return AutoresearchPipeline.objects.create(+ team=team,+ created_by=user,+ name="Test pipeline",+ target_event="$pageview",+ horizon_days=horizon_days,+ iteration_budget=50,+ iteration_budget_remaining=50,+ )+++def _make_model(pipeline: AutoresearchPipeline) -> AutoresearchModel:+ return AutoresearchModel.objects.create(+ pipeline=pipeline,+ role=AutoresearchModel.Role.CHAMPION,+ model_recipe={"stub": True},+ recipe_hash="abc123",+ holdout_score=0.75,+ )+++def _inference_run(+ pipeline: AutoresearchPipeline,+ model: AutoresearchModel | None,+ prediction_date: date,+ rows_scored: int,+ *,+ horizon_days: int = 7,+ status: str = AutoresearchRun.Status.COMPLETED,+) -> AutoresearchRun:+ return AutoresearchRun.objects.create(+ pipeline=pipeline,+ model=model,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=status,+ rows_scored=rows_scored,+ completed_at=django_timezone.now(),+ metrics={"prediction_date": prediction_date.isoformat(), "horizon_days": horizon_days},+ )+++def _validation_run(+ pipeline: AutoresearchPipeline,+ prediction_date: date,+ status: str,+ *,+ started_at: datetime | None = None,+ horizon_days: int = 7,+ counts: dict[str, int] | None = None,+) -> AutoresearchRun:+ metrics: dict = {"prediction_date": prediction_date.isoformat(), "horizon_days": horizon_days}+ if counts is not None:+ metrics["per_model"] = {model_id: {"n_scored": n} for model_id, n in counts.items()}+ return AutoresearchRun.objects.create(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.VALIDATION,+ status=status,+ started_at=started_at or django_timezone.now(),+ metrics=metrics,+ )+++class TestUpdateModelRealizedMetrics(TeamScopedTestMixin, BaseTest):+ def setUp(self):+ super().setUp()+ self.model = _make_model(_make_pipeline(self.team, self.user))++ def test_clears_preliminary_on_first_validation(self):+ assert self.model.is_preliminary is True+ _update_model_realized_metrics(+ self.model, {"realized_auc": 0.82, "calibration_error": 0.05}, prediction_date=date(2026, 9, 1)+ )+ updated = AutoresearchModel.objects.get(pk=self.model.pk)+ assert updated.is_preliminary is False+ assert updated.realized_score == 0.82+ assert updated.calibration_error == 0.05+ assert updated.metrics["realized"]["prediction_date"] == "2026-09-01"++ @parameterized.expand(+ [+ ("newer_date_replaces", date(2026, 9, 2), 0.85),+ ("older_retry_keeps_the_newer_evidence", date(2026, 8, 30), 0.80),+ ]+ )+ def test_model_level_score_follows_the_newest_date(self, _name, second_date, expected_score):+ _update_model_realized_metrics(self.model, {"realized_auc": 0.80}, prediction_date=date(2026, 9, 1))+ _update_model_realized_metrics(self.model, {"realized_auc": 0.85}, prediction_date=second_date)+ self.model.refresh_from_db()+ assert self.model.realized_score == expected_score+ assert self.model.is_preliminary is False++ def test_no_auc_leaves_preliminary_unchanged(self):+ _update_model_realized_metrics(self.model, {"warning": "single_class_no_auc"}, prediction_date=date(2026, 9, 1))+ self.model.refresh_from_db()+ assert self.model.is_preliminary is True+ assert self.model.realized_score is None+++@time_machine.travel(FROZEN_NOW, tick=False)+class TestFindPendingValidationDates(TeamScopedTestMixin, BaseTest):+ def setUp(self):+ super().setUp()+ self.pipeline = _make_pipeline(self.team, self.user)+ self.model = _make_model(self.pipeline)++ def test_matured_dates_come_from_the_inference_runs(self):+ matured = date(2026, 9, 1)+ _inference_run(self.pipeline, self.model, matured, rows_scored=5)+ _inference_run(self.pipeline, self.model, matured, rows_scored=8)+ # Not matured: 2026-09-05 + 7 days is after the frozen 2026-09-11.+ _inference_run(self.pipeline, self.model, date(2026, 9, 5), rows_scored=3)+ # Matured under the horizon the run recorded, not the pipeline's current 7 days.+ _inference_run(self.pipeline, self.model, date(2026, 9, 6), rows_scored=2, horizon_days=3)+ # Nothing emitted, and a run whose model was deleted: neither can be validated.+ _inference_run(self.pipeline, self.model, date(2026, 8, 20), rows_scored=0)+ _inference_run(self.pipeline, None, date(2026, 8, 21), rows_scored=4)++ pending = find_pending_validation_dates(self.pipeline)++ assert [(p.prediction_date, p.horizon_days, p.expected_rows_by_model) for p in pending] == [+ (matured, 7, {str(self.model.pk): 8}),+ (date(2026, 9, 6), 3, {str(self.model.pk): 2}),+ ]+ assert pending[0].window_start == datetime(2026, 9, 1, tzinfo=UTC)+ assert pending[0].window_end == datetime(2026, 9, 8, tzinfo=UTC)++ def test_maturity_waits_for_the_ingestion_grace(self):+ _inference_run(self.pipeline, self.model, date(2026, 9, 4), rows_scored=5)+ window_end = datetime(2026, 9, 11, tzinfo=UTC)+ with time_machine.travel(window_end + OUTCOME_INGESTION_GRACE - timedelta(minutes=1), tick=False):+ assert find_pending_validation_dates(self.pipeline) == []+ with time_machine.travel(window_end + OUTCOME_INGESTION_GRACE, tick=False):+ assert [p.prediction_date for p in find_pending_validation_dates(self.pipeline)] == [date(2026, 9, 4)]++ @parameterized.expand(+ [+ ("fresh_run_waits", timedelta(hours=1), False),+ ("abandoned_run_is_ignored", STALE_RUN_AFTER + timedelta(minutes=1), True),+ ]+ )+ def test_a_date_still_being_scored_waits(self, _name, age, expect_pending):+ matured = date(2026, 9, 1)+ _inference_run(self.pipeline, self.model, matured, rows_scored=5)+ in_flight = _inference_run(+ self.pipeline, self.model, matured, rows_scored=0, status=AutoresearchRun.Status.RUNNING+ )+ AutoresearchRun.objects.filter(pk=in_flight.pk).update(created_at=django_timezone.now() - age)++ assert [p.prediction_date for p in find_pending_validation_dates(self.pipeline)] == (+ [matured] if expect_pending else []+ )++ def test_models_scored_under_different_horizons_validate_as_separate_groups(self):+ # A 14-day replacement scored the same date as the 7-day champion: only the 7-day+ # window has closed by the frozen 2026-09-11, and each group carries its own models.+ other = AutoresearchModel.objects.create(+ pipeline=self.pipeline, role=AutoresearchModel.Role.CHALLENGER, model_recipe={"stub": True}, recipe_hash="x"+ )+ _inference_run(self.pipeline, self.model, date(2026, 9, 1), rows_scored=5, horizon_days=7)+ _inference_run(self.pipeline, other, date(2026, 9, 1), rows_scored=3, horizon_days=14)++ pending = find_pending_validation_dates(self.pipeline)++ assert [(p.horizon_days, p.expected_rows_by_model) for p in pending] == [(7, {str(self.model.pk): 5})]++ def test_a_deleted_model_does_not_reopen_a_validated_date(self):+ matured = date(2026, 9, 1)+ other = AutoresearchModel.objects.create(+ pipeline=self.pipeline, role=AutoresearchModel.Role.CHALLENGER, model_recipe={"stub": True}, recipe_hash="x"+ )+ _inference_run(self.pipeline, self.model, matured, rows_scored=5)+ _inference_run(self.pipeline, other, matured, rows_scored=3)+ _validation_run(+ self.pipeline, matured, AutoresearchRun.Status.COMPLETED, counts={str(self.model.pk): 5, str(other.pk): 3}+ )++ other.delete()++ assert find_pending_validation_dates(self.pipeline) == []++ def test_a_validated_date_becomes_pending_again_when_its_inference_runs_change(self):+ matured = date(2026, 9, 1)+ _inference_run(self.pipeline, self.model, matured, rows_scored=5)+ _validation_run(self.pipeline, matured, AutoresearchRun.Status.COMPLETED, counts={str(self.model.pk): 5})+ assert find_pending_validation_dates(self.pipeline) == []++ _inference_run(self.pipeline, self.model, matured, rows_scored=6)++ assert [p.expected_rows_by_model for p in find_pending_validation_dates(self.pipeline)] == [+ {str(self.model.pk): 6}+ ]++ @parameterized.expand(+ [+ ("completed_blocks", AutoresearchRun.Status.COMPLETED, timedelta(0), False),+ ("failed_is_retried", AutoresearchRun.Status.FAILED, timedelta(0), True),+ ("fresh_claim_blocks", AutoresearchRun.Status.RUNNING, timedelta(hours=1), False),+ ("stale_claim_is_retried", AutoresearchRun.Status.RUNNING, STALE_RUN_AFTER + timedelta(minutes=1), True),+ ]+ )+ def test_existing_validation_runs(self, _name, status, age, expect_pending):+ matured = date(2026, 9, 1)+ _inference_run(self.pipeline, self.model, matured, rows_scored=5)+ _validation_run(+ self.pipeline, matured, status, started_at=django_timezone.now() - age, counts={str(self.model.pk): 5}+ )++ pending = find_pending_validation_dates(self.pipeline)++ assert [p.prediction_date for p in pending] == ([matured] if expect_pending else [])+++def _fake_hogql(+ *,+ predictions: list[list[object]],+ labels: list[list[object]],+ fail_labels_once: bool = False,+) -> MagicMock:+ """Answer the prediction query with ``predictions`` and the label query with ``labels``, recording each call."""+ state = {"labels_failed": False}++ def side_effect(*, team, query, user, execution_mode):+ if "argMax" in query.query:+ return HogQLResult(columns=["model_id", "person_id", "p_y", "emitted_role"], rows=predictions)+ if fail_labels_once and not state["labels_failed"]:+ state["labels_failed"] = True+ raise RuntimeError("clickhouse unavailable")+ return HogQLResult(columns=["person_id"], rows=labels)++ return MagicMock(side_effect=side_effect)+++@time_machine.travel(FROZEN_NOW, tick=False)+class TestRunOnlineValidationForPipeline(TeamScopedTestMixin, BaseTest):+ def setUp(self):+ super().setUp()+ self.pipeline = _make_pipeline(self.team, self.user)+ self.champion = _make_model(self.pipeline)+ self.prediction_date = date(2026, 9, 1)+ _inference_run(self.pipeline, self.champion, self.prediction_date, rows_scored=4)++ def _prediction_rows(self, n: int) -> list[list[object]]:+ scores = [0.9, 0.8, 0.2, 0.1, 0.5]+ return [[str(self.champion.pk), f"user-{i}", scores[i], "champion"] for i in range(n)]++ def test_validates_a_matured_date_and_records_the_evidence(self):+ hogql = _fake_hogql(predictions=self._prediction_rows(4), labels=[["user-0"], ["user-1"]])++ with patch.object(online_validation, "run_hogql", hogql):+ runs = run_online_validation_for_pipeline(self.pipeline)++ assert [r.status for r in runs] == [AutoresearchRun.Status.COMPLETED]+ run = runs[0]+ assert run.rows_scored == 4+ assert run.metrics["prediction_date"] == "2026-09-01"+ assert run.metrics["realized_labels_count"] == 2+ per_model = run.metrics["per_model"][str(self.champion.pk)]+ assert per_model["emitted_role"] == "champion"+ assert per_model["model_role"] == "champion"+ assert per_model["realized_auc"] == 1.0+ self.champion.refresh_from_db()+ assert self.champion.realized_score == 1.0+ assert self.champion.is_preliminary is False+ assert self.champion.metrics["realized"]["prediction_date"] == "2026-09-01"+ assert find_pending_validation_dates(self.pipeline) == []++ prediction_call, label_call = hogql.call_args_list+ assert prediction_call.kwargs["user"] == self.user+ assert prediction_call.kwargs["query"].values["limit"] == 5+ assert prediction_call.kwargs["query"].values["model_ids"] == (str(self.champion.pk),)+ assert prediction_call.kwargs["query"].values["horizon_days"] == "7"+ assert "$autoresearch_horizon_days'] = {horizon_days}" in prediction_call.kwargs["query"].query+ assert prediction_call.kwargs["query"].values["emitted_from"] == datetime(2026, 9, 1, tzinfo=UTC)+ assert label_call.kwargs["query"].values["window_start"] == datetime(2026, 9, 1, tzinfo=UTC)+ assert label_call.kwargs["query"].values["window_end"] == datetime(2026, 9, 8, tzinfo=UTC)+ assert label_call.kwargs["query"].values["limit"] == 5+ assert "LIMIT {limit}" in label_call.kwargs["query"].query++ @parameterized.expand(+ [+ ("fewer_rows_than_emitted", 3, "Found 3 of the 4 predictions"),+ ("more_rows_than_emitted", 5, "more rows than the inference runs account for (4)"),+ ]+ )+ def test_a_count_mismatch_fails_the_date_and_keeps_it_pending(self, _name, n_rows, error_fragment):+ hogql = _fake_hogql(predictions=self._prediction_rows(n_rows), labels=[["user-0"]])++ with patch.object(online_validation, "run_hogql", hogql):+ runs = run_online_validation_for_pipeline(self.pipeline)++ assert [r.status for r in runs] == [AutoresearchRun.Status.FAILED]+ assert error_fragment in runs[0].error+ assert "per_model" not in runs[0].metrics+ self.champion.refresh_from_db()+ assert self.champion.realized_score is None+ assert [p.prediction_date for p in find_pending_validation_dates(self.pipeline)] == [self.prediction_date]++ def test_a_query_failure_fails_that_date_and_continues_to_the_next(self):+ second_date = date(2026, 9, 2)+ _inference_run(self.pipeline, self.champion, second_date, rows_scored=4)+ hogql = _fake_hogql(predictions=self._prediction_rows(4), labels=[["user-0"]], fail_labels_once=True)++ with patch.object(online_validation, "run_hogql", hogql):+ runs = run_online_validation_for_pipeline(self.pipeline)++ assert [(r.metrics["prediction_date"], r.status) for r in runs] == [+ ("2026-09-01", AutoresearchRun.Status.FAILED),+ ("2026-09-02", AutoresearchRun.Status.COMPLETED),+ ]+ assert "Realized labels query failed" in runs[0].error++ @parameterized.expand(+ [+ ("completed", AutoresearchRun.Status.COMPLETED),+ ("still_running", AutoresearchRun.Status.RUNNING),+ ]+ )+ def test_an_inference_run_appearing_mid_validation_fails_the_date(self, _name, status):+ challenger = AutoresearchModel.objects.create(+ pipeline=self.pipeline,+ role=AutoresearchModel.Role.CHALLENGER,+ model_recipe={"stub": True},+ recipe_hash="def",+ )+ hogql = _fake_hogql(predictions=self._prediction_rows(4), labels=[["user-0"]])+ inner = hogql.side_effect++ def complete_a_rescore_then_answer(**kwargs):+ if "argMax" not in kwargs["query"].query:+ _inference_run(self.pipeline, challenger, self.prediction_date, rows_scored=4, status=status)+ return inner(**kwargs)++ with patch.object(online_validation, "run_hogql", MagicMock(side_effect=complete_a_rescore_then_answer)):+ runs = run_online_validation_for_pipeline(self.pipeline)++ assert [r.status for r in runs] == [AutoresearchRun.Status.FAILED]+ assert "changed while it was being validated" in runs[0].error+ self.champion.refresh_from_db()+ assert self.champion.realized_score is None+ if status == AutoresearchRun.Status.COMPLETED:+ pending = find_pending_validation_dates(self.pipeline)+ assert [set(p.expected_rows_by_model) for p in pending] == [{str(self.champion.pk), str(challenger.pk)}]++ def test_a_model_deleted_mid_validation_keeps_its_evidence_on_the_run(self):+ hogql = _fake_hogql(predictions=self._prediction_rows(4), labels=[["user-0"], ["user-1"]])+ inner = hogql.side_effect++ def delete_the_model_then_answer(**kwargs):+ if "argMax" not in kwargs["query"].query:+ AutoresearchModel.objects.filter(pk=self.champion.pk).delete()+ return inner(**kwargs)++ with patch.object(online_validation, "run_hogql", MagicMock(side_effect=delete_the_model_then_answer)):+ runs = run_online_validation_for_pipeline(self.pipeline)++ assert [r.status for r in runs] == [AutoresearchRun.Status.COMPLETED]+ per_model = runs[0].metrics["per_model"][str(self.champion.pk)]+ assert per_model["model_role"] == "deleted"+ assert per_model["realized_auc"] == 1.0+ assert find_pending_validation_dates(self.pipeline) == []++ def test_a_pipeline_without_a_creator_fails_before_any_query(self):+ self.pipeline.created_by = None+ self.pipeline.save(update_fields=["created_by"])+ hogql = _fake_hogql(predictions=[], labels=[])++ with patch.object(online_validation, "run_hogql", hogql), self.assertRaises(OnlineValidationError):+ run_online_validation_for_pipeline(self.pipeline)++ hogql.assert_not_called()+ assert not AutoresearchRun.objects.filter(run_type=AutoresearchRun.RunType.VALIDATION).exists()diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.pyindex 1ce58adf7a51..d3b0edadf8ff 100644--- a/products/autoresearch/backend/inference/scoring.py+++ b/products/autoresearch/backend/inference/scoring.py@@ -190,6 +190,10 @@ def run_inference_for_pipeline(run_type=AutoresearchRun.RunType.INFERENCE,status=AutoresearchRun.Status.RUNNING,started_at=django_timezone.now(),+ # Online validation discovers matured dates from these two keys instead of scanning+ # the events table, validates against the horizon scored here rather than the+ # pipeline's current one, and waits for a run that is still scoring the date.+ metrics={"prediction_date": window.prediction_date.isoformat(), "horizon_days": pipeline.horizon_days},)try:@@ -202,12 +206,14 @@ def run_inference_for_pipeline(run.status = AutoresearchRun.Status.COMPLETEDrun.rows_scored = emitted.rows_emitted- run.metrics = {- "score_distribution": emitted.score_distribution,- "stub": bool((model.model_recipe or {}).get("stub", False)),- "sandbox": bool(model.artifact_prefix),- "holdout_auc": scored.holdout_auc,- }+ run.metrics.update(+ {+ "score_distribution": emitted.score_distribution,+ "stub": bool((model.model_recipe or {}).get("stub", False)),+ "sandbox": bool(model.artifact_prefix),+ "holdout_auc": scored.holdout_auc,+ }+ )run.completed_at = django_timezone.now()run.save(update_fields=["status", "rows_scored", "metrics", "completed_at"])diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.pyindex d6175d2596ab..d721b393f6cd 100644--- a/products/autoresearch/backend/inference/test_inference.py+++ b/products/autoresearch/backend/inference/test_inference.py@@ -94,6 +94,7 @@ class TestScoreRows(SimpleTestCase):assert _score_rows([]) == []+@time_machine.travel("2026-09-11T12:00:00Z", tick=False)class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):def _make_pipeline_and_model(self, **pipeline_kwargs) -> tuple[AutoresearchPipeline, AutoresearchModel]:pipeline = AutoresearchPipeline.objects.create(@@ -131,6 +132,8 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):assert run.status == AutoresearchRun.Status.COMPLETEDassert run.rows_scored == 2assert run.metrics["holdout_auc"] == 0.7+ assert run.metrics["prediction_date"] == "2026-09-11"+ assert run.metrics["horizon_days"] == 7assert capture.call_count == 1kwargs = capture.call_args.kwargsevents = kwargs["events"]@@ -256,6 +259,7 @@ class TestPredictionDateGuards(TeamScopedTestMixin, BaseTest):score.assert_not_called()run = AutoresearchRun.objects.filter(pipeline=pipeline).latest("created_at")assert run.status == AutoresearchRun.Status.FAILED+ assert run.metrics["prediction_date"] == prediction_date.isoformat()def test_future_prediction_date_is_refused(self):# A future date reads as live: today's features under a future label.diff --git a/products/autoresearch/backend/management/AGENTS.md b/products/autoresearch/backend/management/AGENTS.mdindex a0d6b619ae4f..b02012582197 100644--- a/products/autoresearch/backend/management/AGENTS.md+++ b/products/autoresearch/backend/management/AGENTS.md@@ -2,7 +2,7 @@The headless entrypoints. Four commands cover the whole product lifecycle, and together they are how autoresearch is exercised end to end locally without a browser.-This package landed with `autoresearch_validate` and `autoresearch_score` only. `autoresearch_train` and `autoresearch_validate_online` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.+This package landed with `autoresearch_validate`, `autoresearch_score`, and `autoresearch_validate_online`. `autoresearch_train` arrives in a later piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.Every command calls the same functions the API and the Temporal activities call. They are thin wrappers, not a parallel implementation, and they should stay that way.@@ -22,7 +22,8 @@ Every command calls the same functions the API and the Temporal activities call.`--team-id --target --horizon --user-id``--user-id` is the person HogQL applies access control for; without it the counts run fail-closed. Note there is no `--mode` flag. Note also that `autoresearch_train` does **not** call this, so a target that fails here still trains.- `autoresearch_validate_online` — realized performance for predictions whose horizon has elapsed.- `--pipeline-id --dry-run`+ `--pipeline-id --user-id --dry-run`+ `--dry-run` lists the matured dates waiting for validation and what each inference run emitted. `--user-id` is the person HogQL applies access control for; without it the queries run as the pipeline's creator. The command exits non-zero when any date fails, and the failed date is retried on the next pass.## Running them locallydiff --git a/products/autoresearch/backend/management/commands/autoresearch_validate_online.py b/products/autoresearch/backend/management/commands/autoresearch_validate_online.pynew file mode 100644index 000000000000..dc20feb6b560--- /dev/null+++ b/products/autoresearch/backend/management/commands/autoresearch_validate_online.py@@ -0,0 +1,120 @@+"""+Run online validation for an autoresearch pipeline.++Finds the matured prediction dates that have no completed validation, joins their+predictions to realized target outcomes, and computes realized AUC / Brier / ECE / lift@k+per model. Updates AutoresearchModel.realized_score and calibration_error in Postgres.++Usage:+ python manage.py autoresearch_validate_online --pipeline-id <uuid>+ python manage.py autoresearch_validate_online --pipeline-id <uuid> --dry-run++Requires:+ - PostHog running locally (./bin/start or hogli start)+ - completed inference runs whose predictions are in ClickHouse (run autoresearch_score first)+ - Enough time elapsed for the horizon to close (horizon_days must have passed)+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser++from posthog.models.scoping import team_scope+from posthog.models.user import User++from products.autoresearch.backend.evaluation.online_validation import (+ find_pending_validation_dates,+ run_online_validation_for_pipeline,+)+from products.autoresearch.backend.management.scoping import resolve_pipeline+from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchRun+++class Command(BaseCommand):+ help = "Run online validation for a pipeline: join predictions to realized labels and update model metrics."++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--pipeline-id", type=str, required=True, help="UUID of the pipeline to validate.")+ parser.add_argument(+ "--user-id",+ type=int,+ default=None,+ help="Run the queries as this user. Defaults to the pipeline's creator.",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Show the matured dates waiting for validation and skip DB writes.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ pipeline = resolve_pipeline(options["pipeline_id"])+ user = self._resolve_user(options["user_id"])+ with team_scope(pipeline.team_id):+ self._run(pipeline, user, options)++ @staticmethod+ def _resolve_user(user_id: int | None) -> User | None:+ if user_id is None:+ return None+ try:+ return User.objects.get(pk=user_id)+ except User.DoesNotExist:+ raise CommandError(f"User {user_id} not found.")++ def _run(self, pipeline: AutoresearchPipeline, user: User | None, options: dict[str, Any]) -> None:+ self.stdout.write(f"\nPipeline : {pipeline.name} ({pipeline.pk})")+ self.stdout.write(f"Target : {pipeline.target_event}")+ self.stdout.write(f"Horizon : {pipeline.horizon_days} days")+ self.stdout.write("")++ if options["dry_run"]:+ self.stdout.write(self.style.WARNING("Dry-run mode: showing the pending dates but not validating them.\n"))+ pending = find_pending_validation_dates(pipeline)+ self.stdout.write(f"Pending dates : {len(pending)}")+ for item in pending:+ models = ", ".join(+ f"{model_id[:8]}… ({rows} rows)" for model_id, rows in item.expected_rows_by_model.items()+ )+ self.stdout.write(f" {item.prediction_date.isoformat()} horizon={item.horizon_days}d {models}")+ return++ runs = run_online_validation_for_pipeline(pipeline, user=user)++ if not runs:+ self.stdout.write(self.style.WARNING("No matured prediction dates are waiting for validation."))+ self.stdout.write(+ "Either no completed scoring run has passed its horizon yet, or every matured date is already validated."+ )+ return++ self.stdout.write(f"Validated {len(runs)} prediction date(s):\n")+ for run in runs:+ prediction_date = run.metrics.get("prediction_date", "?")+ n_labels = run.metrics.get("realized_labels_count", "?")+ self.stdout.write(+ f" {prediction_date} status={run.status} rows_scored={run.rows_scored} realized_labels={n_labels}"+ )+ if run.error:+ self.stdout.write(f" error: {run.error}")++ per_model = run.metrics.get("per_model", {})+ for model_id, m in per_model.items():+ auc = m.get("realized_auc")+ brier = m.get("brier_score")+ ece = m.get("calibration_error")+ lift10 = m.get("lift_at_10")+ role = m.get("model_role", "?")+ self.stdout.write(+ f" Model {model_id[:8]}… role={role} AUC={auc} Brier={brier} ECE={ece} lift@10={lift10}"+ )++ completed = [r for r in runs if r.status == AutoresearchRun.Status.COMPLETED]+ if completed:+ self.stdout.write(self.style.SUCCESS(f"\n✓ Completed validation for {len(completed)} date(s)."))+ failed = [r for r in runs if r.status == AutoresearchRun.Status.FAILED]+ if failed:+ raise CommandError(+ f"{len(failed)} validation run(s) failed. Each failed date is retried on the next pass; "+ "the run's error field says why."+ )diff --git a/products/autoresearch/backend/management/test_autoresearch_validate_online.py b/products/autoresearch/backend/management/test_autoresearch_validate_online.pynew file mode 100644index 000000000000..889ac6b576c1--- /dev/null+++ b/products/autoresearch/backend/management/test_autoresearch_validate_online.py@@ -0,0 +1,29 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command+from django.core.management.base import CommandError++from products.autoresearch.backend.management.commands import autoresearch_validate_online+from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchRun+from products.autoresearch.backend.testing import TeamScopedTestMixin+++class TestValidateOnlineCommand(TeamScopedTestMixin, BaseTest):+ def test_a_failed_date_exits_non_zero(self):+ pipeline = AutoresearchPipeline.objects.create(+ team=self.team, created_by=self.user, name="Test", target_event="$pageview", horizon_days=7+ )+ failed = AutoresearchRun(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.VALIDATION,+ status=AutoresearchRun.Status.FAILED,+ error="clickhouse unavailable",+ metrics={"prediction_date": "2026-09-01"},+ )++ with (+ patch.object(autoresearch_validate_online, "run_online_validation_for_pipeline", return_value=[failed]),+ self.assertRaises(CommandError),+ ):+ call_command("autoresearch_validate_online", "--pipeline-id", str(pipeline.pk))