: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.
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.
What lives here
online_validation.pyrun_online_validation_for_pipeline()is the entry point, called by the Temporal validation activity and by theautoresearch_validate_onlinecommand. It takes the actinguserHogQL 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_aucinstead) - 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 withbase_rateto see over- or under-prediction - Brier score — squared error of the probabilities
- 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 withn,mean_p_yandpositive_rate; equal scores share a bin. Equal-width bins put nearly every person in the first bin for a rare target, so read these instead - lift@k (
_lift_at_k) — how much better than random the top slice is; ties at the boundary score are split fractionally so the number does not depend on row order - average precision — area under the precision-recall curve; null when the date has no positives
- confusion counts (
confusion,_confusion_counts) —tp,fp,fn,tn,n_flagged,precisionandrecallfor three cutoffs:top_10,top_20, andlikely(score at or abovelikely_threshold, which is stored with them). Top-k cutoffs flag every person tied at the boundary score, so the counts are whole people andn_flaggedcan be a little above k.likely_thresholdis the Likely cut point from the dates checked before this one, so the counts describe the group the Predictions tab showed - weekday — the ISO weekday of the prediction date
Every model that emitted predictions on the date is scored, whatever its role now. Inference shadow-scores every model in the shadow set on the champion's people, and each records its own inference run, so their realized numbers land here. That is what makes challenger promotion decidable on evidence rather than on holdout alone. A shadow model's events carry the emitted role
shadow. Results land onAutoresearchModel.realized_score/.calibration_error/.metrics["realized"]via_update_model_realized_metrics(), and each validated date records anAutoresearchRunwhosemetrics["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:latest_validation_runs()inhistory.pyreads them, foronline_performance()in../facade/api.py(the pipeline'sonline_performanceaction and theautoresearch-online-performance-retrieveMCP 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. The training brief reads the same history (../training/realized_context.py).- realized AUC — ranking quality against actual outcomes (needs both classes; a single-class date records
maturity.pyOUTCOME_INGESTION_GRACEandmatures_at(), the first instant a prediction date can be checked.find_pending_validation_dates()uses it, and the pipeline'sfirst_check_expected_atapplies it to the champion's earliest scored date, so the two cannot disagree. It imports nothing heavy, so the facade reads it without loading this package's sandbox code.segment_thresholds.pyThe cut points between the Likely, Possible and Unlikely segments. Possible starts at the base rate, and Likely starts atLIKELY_LIFTtimes it, capped halfway between the base rate and 1. The base rate pools the emitted champion'sn_positive/n_scoredover the newestBASE_RATE_DATESchecked dates. Until those dates holdMIN_BASE_RATE_POSITIVES, the champion's training base rate applies:fit_champion_model()records the population and positives from before case-control sampling in the model'smetrics(training_population,training_positives), and the same floor applies to them. The training window is in the past, so this rate can differ from the realized rate, which replaces it as soon as it is available. A champion fit before the counts were recorded falls back to the fixed pair.base_rate_sourceon the response tellsrealized,trainingandfixedapart.online_performance()returns the current pair, which every frontend surface reads, andchampion_score_calibration()flags a champion whose mean score is far from the realized rate. Class weighting or resampling intrain.pyleaves scores that are not probabilities, and nothing at scoring time corrects it. A saved cohort, flag or workflow stores the absolute cut point, so it does not follow a later change in the base rate.
Mental model
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.
Every ClickHouse query is bounded by what the inference runs say was emitted. The prediction fetch runs one query per model, because HogQL returns at most 50,000 rows whatever the LIMIT, and the champion and its shadow models together can emit more. Each query must return exactly rows_scored persons for its 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 Nemits 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 aFAILEDrun 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_modelasdeletedand 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_GRACEafter the window closed (an offline SDK buffer flushed days late) reads as a negative in the stored metrics. - Only the AUC and its interval need both classes. An all-negative day still records Brier, calibration error, calibration bins, lift, and confusion counts, which is where calibration matters for a rare target.
Where the rest of the system meets this package
- Scheduled by —
AutoresearchValidationWorkflow/activity_run_validationin../temporal/workflows.py. - Run headlessly by —
autoresearch_validate_online(see../management/AGENTS.md), which supports--dry-runand--user-id, and exits non-zero when a date fails. - Reads —
autoresearch_predictionevents emitted by../inference/, theprediction_date/horizon_dayskeysscoring.pyrecords 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 anAutoresearchRunper 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'sper_modelentry carries each model'sn_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.