: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.
Inference
Scoring a population with the champion model and writing the result back into PostHog as autoresearch_prediction events, then scoring the same people with every other model in the shadow set.
This is the cheap, boring, high-frequency half of the product — it runs on the pipeline's cadence (default daily) for every active pipeline, forever.
../training/ is the expensive half that produces what this package consumes.
The cardinal rule: inference never refits a persisted model. A bundle is fitted once, at training completion, and every cadence loads that model.pkl. A recipe-only champion has no persisted model, so it fits its allowlisted sklearn class in process on every cadence; that is the cost of a champion without a bundle, not a refit.
What lives here
sandbox.pyThe current path. Runs the agent-authored bundle in a Tasks sandbox, split by run type because train and predict have genuinely different data contracts:fit_champion_model()— train run, called once at training completion. Materializes the labeled training population, runs the bundle'strain.py, runspredict.pyonce against the holdout features as a smoke test, and only then persists the fittedmodel.pklnext to the bundle. A bundle whose two scripts disagree fails here, not on the first cadence.check_scorability()— called once after the champion fit. Runs the anchor count and the feature query of a scoring run against today's inference anchors underBATCH_QUERY, with no sandbox, and returns theirQueryCost(measure_queries()in../query.py). Promotion rolls back a champion that fails it or runs over its time budget.score_via_sandbox()— predict run, called every cadence. Loads the persistedmodel.pkl, materializes only the inference population (cutoff at the start of the prediction date, no labels, no holdout, no fold), runspredict.py, and hands scores to the emitter. A missingmodel.pklfails the run.
Both entry points validate the bundle's
features.sqlwithvalidate_feature_sql()(plus no trailingLIMIT/OFFSET/SETTINGS) before any query runs, and run every HogQL query as the pipeline's creator (_resolve_acting_user(), or the explicitusera management command passes), withCALCULATE_BLOCKING_ALWAYSso a cadence never reuses a cached population, and withLABELER_QUERY_MODIFIERS, soperson_idresolves the same way in the anchors and the feature SQL, and aperson.*column in feature SQL resolves through the persons table. The anchor SQL itself reads identity fromraw_persons, not fromperson.*. The train run persistsfeature_columns.jsonnext tomodel.pkl; every predict run sends exactly those columns, in that order, filling an absent or null one with zeros, so the fitted model never sees a column set that depends on today's population. A champion fitted before the file existed falls back to deriving the columns from the scoring rows. A fitted column that holds a present non-numeric value fails the run, because the persisted list bypasses_numeric_feature_cols()and zero-filling schema drift would emit a plausible wrong prediction.materialize_training_data()writes feature and label parquet files into the sandbox;MaterializedDatacarries the paths and row counts back. Materialized rows must key exactly one person each (validate_unique_distinct_ids()), and a training row whose label failed to join fails the run. Feature SQL that returns two columns of the same name fails the run, becauseHogQLResult.as_dicts()keeps only the last value of a repeated name. Every upload goes through_write_file(), which fails the run on a non-zero result: the providers report a failed write through the exit code rather than an exception, and a discarded result would let a script run against a missing input. The train run's smoke test loads the model bytes read back from the sandbox, written to_SMOKE_MODEL_PKL, so the bytes the caller persists are the bytespredict.pyproved it can load. Everything a script produces is untrusted: script output goes todata/script.logand only a bounded tail comes back on failure; every file readback is size-gated inside the sandbox (_MAX_READBACK_BYTES, the artifact cap), emits at most cap-plus-one bytes throughhead -chowever the file grows, and fails on a missing, empty, or oversized file;output.jsonvalues are typed and ranged;scores.parquetis checked from its footer before it is decoded (column types, row count against the input, decoded byte size of the two contract columns against the cap), only those two columns are read, and a person scored twice fails the run. Timeouts are asymmetric on purpose —_TRAIN_TIMEOUT_S300s versus_PREDICT_TIMEOUT_S120s — with_SANDBOX_TTL_Sas the backstop for a worker that dies mid-run._MATERIALIZE_ROW_LIMIT(with the rolling selection below it for scoring) and_MAX_FEATURE_COLStogether cap what crosses into the sandbox: the row cap alone does not bound the matrix the worker expands, because the agent's SQL chooses the column count.scoring.pyThe recipe-only in-process path plus the event emission that both paths share.run_inference_for_pipeline()is the entry point called by the Temporal activity and byautoresearch_score;score_population()is the scoring half alone, which the command's dry run calls so it exercises the same route as a real run; the prediction-date guards run inside it, so the dry run refuses exactly the dates the live run refuses. A recipe-only champion routes on its recipe: a stub recipe (stub: true, SQL evaluated atnow()) scores by the fixed engagement formula, with the inference population applied inside its query so the row bound measures the population and not the team, and its rows checked against the population count; an agent recipe goes throughvalidate_runnable_feature_sql()like a bundle (so a trailingLIMITor an{anchors}that sits only in a comment fails the run rather than running without a cutoff) and then fits on the anchored training rows and predicts on the inference anchors. Neither can be backfilled: the fit happens at scoring time on labels decided as ofnow(), so a fit for a past date would learn from outcomes after it. Only a bundle, whosemodel.pklalready exists, is re-scored in the past. The recipe fit validates its training rows the way the sandbox does (one row per person, every row labeled, at most_MAX_FEATURE_COLSnumeric columns, no duplicate column names), sorts them by person before fitting, because an estimator that samples row indices fits a different model on a different row order despite its seed, seeds a stochastic estimator from the pipeline id unless the recipe setsrandom_state, so a retry refits the same model under the same event UUIDs, and pinsn_jobs=1, because the fit runs in the worker process. Its probabilities keep full precision, as the bundle path's do. This is the only place that resolvesmodel_classthroughimportlib, so it is the one genuine code-execution surface — it callsvalidate_model_class()from../training/recipe_validation.pybefore importing. Do not weaken that. Every query runs as the acting user (the pipeline's creator, or the--user-ida command passes), with an explicit bound and a truncation check, including the identity lookup: a bareSELECTthat HogQL caps at 100 rows would emit most of the population person-less. Every result is refused above_MAX_FEATURE_COLSoutput columns as it is read, before any column is typed, because the numeric filter would otherwise discard the excess only after it was materialized. A run decides its dates once, inScoringWindow: live or backfill, the cutoff every query binds to, and the emit timestamp. The cutoff is the start of the prediction date in UTC for every run, live included, so a retry recomputes the population the failed attempt had (the event UUIDs are the same either way), the feature query and the anchor count agree, and a backfill of a date gets the anchors a live run on that date got. A run that crosses midnight keeps the mode it started in. Inference rows are checked against the anchor count on both paths (count_inference_anchors()), and training rows against the labeled anchor count (count_training_anchors(), at the negative sample rate the rows were drawn at), because feature SQL that inner joins or filters a joined table inWHEREdrops people without any row looking wrong. Scoring above the cap is rolling. Every path (bundle, agent recipe, stub) counts the whole inference population first. When the count reachesMATERIALIZE_ROW_LIMIT,rolling_selection()returns aRollingSelectionofROLLING_SCORE_LIMITpersons, and the feature query takes that many anchors, ranked bybuild_inference_anchors_sql(): never scored by this pipeline, then the oldest last score, then the most recent activity. The row check then expects exactly that many rows. The run records the whole count asmetrics["rows_eligible"]next torows_scored, so a run that scored part of its population completes, and consecutive runs cover everyone inceil(eligible / scored)runs, which is that many timescadence_daysin days. Below the cap the selection is unchanged. The stub path's population and ranking bind the run's cutoff at every size, so a retry selects the same people, though its feature SQL still reads atnow(). The truncation check stays as the backstop for a query that misbehaves. A completed live run also recordsmetrics["coverage"]: the population, how many people have a non-shadow score, how many have none, and the age of the newest score per person (avg, p50, p90, max, in days before the cutoff).build_prediction_coverage_sql()reads the same last-score subquery as the ranking, over the samescored_lookback_days()window, sonever_scoredis the set the ranking puts first. The query runs underBATCH_QUERY. A failed coverage query only logs, and backfill and shadow runs do not record coverage. A completed live run also recordsmetrics["likely_count"], the people it scored at or above the current Likely cut point from../evaluation/segment_thresholds.py, and that cut point asmetrics["likely_threshold"]. The score distribution keeps only quantiles, so the model list reads the count from here instead of querying the prediction events. Backfill and shadow runs do not record it._resolve_distinct_ids()maps theperson_ideverything is keyed on back to one currentdistinct_idthrough personhog (get_persons_by_uuids), never from event history, because an id read off old events can belong to someone else after a merge or split.person_property.pyA live champion event carries$setofoutput_person_propertyonly while the pipeline'swrite_person_propertyis on. New pipelines start with it off; pipelines created before the setting existed were migrated to on. Scoring re-reads the setting right before its batch goes out (_still_writes_person_property(), which also treats an archived pipeline as off), next to_require_still_champion().remove_output_person_property()removes the property again. It reads the currentperson_idof every championautoresearch_predictionfrom this pipeline since it was created that carries$setof the property (so a merge survivor counts, and a prediction made while writing was off does not), in pages of 50,000, and checks them againstpersonsthat still hold the property 1,000 at a time. A person who got the same property name from somewhere else keeps it. It resolves each to a current distinct id with_resolve_distinct_ids(), and sends$unsetthroughcapture_batch_internal(). Before each page it callscleanup_stop_reason(), so the cleanup stops when someone turns the setting back on for the same property name, or when another live pipeline writes the same property name. The facade starts it (AutoresearchPropertyCleanupWorkflow) when the setting goes from on to off, or when a pipeline with it on is archived or deleted. A cleanup records anAutoresearchRunwithrun_typeproperty_cleanup, except after a delete.
Query budget
Every HogQL query goes through run_hogql() in ../query.py with a QueryContext: a limit context, which sets max_execution_time, and a ClickHouse workload. The entry point chooses it and passes it down explicitly. No code decides it from where it runs.
| Path | Context | Limit and workload |
|---|---|---|
Scoring from activity_run_inference (sweep and manual /score) and activity_run_shadow_scoring, both routes, with their anchor and population counts |
SCORING_QUERY |
QUERY_ASYNC (HOGQL_INCREASED_MAX_EXECUTION_TIME, 600 s), OFFLINE, capacity backoff |
Online validation from activity_run_validation |
BATCH_QUERY |
QUERY_ASYNC, OFFLINE |
check_scorability() after the champion fit at training completion |
BATCH_QUERY |
QUERY_ASYNC, OFFLINE |
fit_champion_model() at training completion, materialize-features, /validate, /validate_online |
INTERACTIVE_QUERY (the default) |
QUERY (60 s), DEFAULT |
| Management commands | INTERACTIVE_QUERY (the default) |
QUERY, DEFAULT |
Scoring and validation are batch work that nobody waits on, so they get the batch limit.
SCORING_QUERY is BATCH_QUERY plus a capacity backoff: run_hogql() runs a query that ClickHouse refuses as RATE_LIMITED (ClickHouseAtCapacity, ConcurrencyLimitExceeded, ClickHouseClusterMemoryLimitExceeded) again after about 30 s, 60 s, and 120 s, with jitter and with ClickHouseAtCapacity.wait as the floor, and then raises. The activity's HeartbeaterSync heartbeats during the waits. The other contexts do not retry, because a request path must not wait minutes. A path inside a web request keeps the interactive limit, because a 600 s query would outlive the request.
Training stays interactive on purpose: feature SQL that materializes within 60 s at training has ten times that budget at scoring, so the stricter bar is at the gate. When a request path moves to Temporal, give it BATCH_QUERY.
The activity timeouts in ../temporal/workflows.py cover several batch queries in sequence at the full limit. Keep them that way when you add a query to either path.
The emitted event
event: autoresearch_prediction
distinct_id: <person distinct_id>
properties: $autoresearch_pipeline_id, $autoresearch_p_y, $autoresearch_p_y_raw,
$autoresearch_negative_sample_rate, ...
Shadow scoring
After a live champion run completes, _score_shadow_set() in scoring.py scores every other model in shadow_set() (../training/shadow_set.py). A backfill does not shadow-score.
- Same people. Each shadow model scores exactly the persons the champion's run scored, including a rolling subset. Its anchors bind the same cutoff, and a feature result that keys a different set of persons fails that model, because unpaired scores do not compare.
- One feature query per distinct
features.sql. The digest of the bundle's SQL (features_sql_digest()) keys the materialized rows. The champion's rows serve a shadow model with the same SQL, and each other SQL runs once. A failed materialization is cached too. A result is released after the last model that uses it, so the phase does not hold one result per distinct SQL. - Person-less events. A shadow event has
$autoresearch_model_roleshadow, no$set, and no person processing, and itsdistinct_idis unique per model and person (_shadow_distinct_id()), because ingestion deduplicates on timestamp, distinct_id, token, and event name, not on the UUID. Validation keys on$autoresearch_person_id. A shadow score never reaches the output person property. Right before its batch goes out, a shadow model checks that it is still in the set (_require_still_in_shadow_set()), in place of_require_still_champion(). - Isolated runs. Each shadow model records its own inference run, with
metrics["shadow"]set andscheduledfalse, sofind_unscorable_champion()never reads it, even after the model becomes the champion. A shadow failure fails only that run. Repeatable shadow failures onUNSCORABLE_AFTER_FAILED_DAYSscoring days remove the model from the shadow set (models_failing_repeatably_in_shadow()). The champion's run recordsmetrics["shadow_models"]: the models that completed, failed, or were skipped. - Deferred in the daily sweep. The sweep scores the champion with
defer_shadows, and scores the shadow set later in its own activity, throughscore_shadow_set_for_run(), after every champion of the sweep has finished. A live run recordsmetrics["scored_persons_digest"](persons_digest()of the people it scored), and the deferred phase pairs each feature result against that digest, so the person list never crosses the Temporal payload. The champion's run also stores the person ids it scored in object storage (metrics["scored_persons_key"],scored_persons_key()in../training/artifacts.py). The deferred phase binds its anchors to those people (anchor_person_ids,build_fixed_anchors_sql()), so a population-property change during the sweep does not change who the shadows score. The fixed anchors keep only persons who are still live, through the same_person_rows_sql()filter every population uses, so a person deleted or merged away since the champion's run is neither scored nor emitted. The shadows then pair on the champion's people who are still live: their rows must key only stored people, and the live count is the expected row count. A shadow run records the champion'srows_eligible, so coverage stays true for a rolling champion. The deferred phase deletes the stored list when it ends, including when the activity skips the run or the run is gone with a deleted pipeline. Without a stored list it selects the population again. The deferred phase queries the champion's SQL again, because the champion's rows are gone with its activity. It scores nothing when the prediction date has passed. A model promoted since the champion's run does not score as a shadow. Manual scoring andautoresearch_scorestill score the shadow set in the same call. - The rolling ranking ignores shadow events.
build_inference_anchors_sql()counts only non-shadow predictions as scores, so shadow scoring does not change who the champion scores next. - Cost bound. No new shadow model starts after
SHADOW_TIME_BUDGET_S(20 minutes). The rest are skipped for that cadence. The inference activity timeout covers the champion's worst case, the budget, and one more model. The shadow activity timeout covers the budget and one more model. - Timing. A live champion run records
metrics["scoring_seconds"], completed or failed. The deferred phase recordsmetrics["shadow_seconds"]on the champion's run. A sweep run also recordsmetrics["coordinator_concurrency"].
Scores are prior-corrected once, in score_population(). A model fitted on a case-control sample (see ../dataset/AGENTS.md) overstates the odds by 1 / r, so corrected_probability() applies logit(p) + log(r). $autoresearch_p_y and the output person property carry the corrected value, $autoresearch_p_y_raw the model's own score, and the run records r in AutoresearchRun.negative_sample_rate.
A bundle's r is AutoresearchModel.negative_sample_rate, which fit_champion_model() saves before it writes model.pkl. A recipe-only champion measures its sample at each fit and uses that rate. The stub formula never saw a sample, so its r is 1.0. Never correct in a scoring route; a second correction would shrink every probability again.
One event per scored person per run, sent as one capture_batch_internal() batch. This is the product's actual output — the person property on the pipeline (output_person_property, e.g. predicted_p_downloaded_file_30d) is derived from these.
Any event the batch does not accept, or accepts with a warning (capture stores the event but has switched something off, such as person processing for a rate-limited distinct id, so the $set never lands), fails the run: the event UUIDs are deterministic per (pipeline, model, date, person), so the retry re-sends every row and ingestion keeps one copy, whereas completing with a partial batch would advance the cadence past the people who never received their prediction.
Right before the batch goes out the run re-reads the model's role and fails if promotion has replaced the champion meanwhile, so a superseded model does not write its $set over the new champion's. The window between that read and capture is what remains of the race.
Because emission goes through normal ingestion, a backdated event older than the team's drop_events_older_than is accepted by capture and then dropped, so a run refuses a backfill past that threshold instead of recording rows nobody can read. A run also refuses a future prediction date, and a backfill of a population filtered on person properties, because those properties are evaluated as they are today.
The prediction event is itself an event on the person, so every live cadence adds one. The population and anchor scans in ../dataset/labeling.py exclude it; feature SQL is the agent's, so the fixture's features.sql excludes it explicitly and the agent brief says to.
Mental model
- Load the champion for the pipeline.
- Resolve the inference population and build anchors at the cutoff, the start of the prediction date in UTC (
../dataset/labeling.py). - If the champion has an
artifact_prefix, materialize features into a sandbox and runpredict.py. Otherwise compile the recorded recipe and score in-process. - Map
person_id→distinct_idand emit one event each. - Record an
AutoresearchRunfor the execution. A run the daily sweep starts hasscheduledset. A failed run recordsmetrics["failure_kind"]fromclassify_failure()infailures.py:limit_exceeded,query_failedandmodel_load_failedfail again with the same champion, andother(transport, capture, cluster capacity, anything unknown) can pass on a retry. Promotion reads the scheduled runs to decide that a champion cannot score. - On a live run that completed, score the other shadow-set models on the same people, each with its own run (see Shadow scoring above). The daily sweep does this in a later activity.
Both model shapes are live and must stay that way: bundle-backed champions take the sandbox path, older recipe-only champions take the in-process path.
The failure mode that will cost you a day
A uniform or constant score distribution is an identifier mismatch, not a bad model.
Everything is keyed on person_id, one row per person — the agent's feature_sql, the label query, and the population query all have to agree.
When they don't, nothing raises: labels fail to join, come back all-zero, the model degenerates, and every person gets the same score. A raw UUID leaking into the event path also breaks JSON serialization and emits zero events.
Before suspecting the model, check that features, labels, and population all key on person_id and coerce to str.
Where the rest of the system meets this package
- Scheduled by —
AutoresearchInferenceWorkflowandactivity_run_inferencein../temporal/workflows.py. - Run headlessly by —
autoresearch_score(see../management/AGENTS.md), which calls the same functions directly. - Called by training —
fit_champion_model()is invoked from the completion path in../training/promotion.py, for a promoted champion and for a challenger that enters the shadow set (../training/shadow_set.py). Scoring then loads the fitted challengers for shadow scoring. It lives here because it shares the materialization and sandbox machinery with scoring, not because it is part of the inference loop. - Reads —
AutoresearchModel(champion role) and the bundle in object storage via../training/artifacts.py. - Feeds —
../evaluation/online_validation.py, which reads the emitted events back once their horizon has elapsed. - Population and anchors —
../dataset/labeling.py, shared with training so the cutoff contract cannot drift.
When editing this flow
- Never re-fit a persisted model on the scoring path.
score_via_sandbox()loadsmodel.pkland runspredict.pyonly. A fallback that quietly re-fits would make every scoring run expensive and non-deterministic, and concurrent cadences would race to overwrite the pickle. A missing model is a failed run. The in-process fit inscoring.pyis the recipe-only shape's contract, not a fallback, and it must not be reached for a model that has anartifact_prefix. - Keep both champion shapes working — bundle-backed and recipe-only. Guard on
artifact_prefixrather than assuming. validate_model_class()must stay on the in-process path. It is not defense in depth there, it is the only defense.- Anything that changes the cutoff, the population, or the anchor SQL belongs in
../dataset/labeling.py, not here — training and inference share it precisely so they cannot disagree. - Nothing a script writes reaches the worker unbounded. Keep the size gate in
_readback_command()and the log redirect in_script_command()when you add a new file to the contract. - The sandbox providers differ: Modal honors
block_network; the Docker provider (local dev) does not, and mountsSANDBOX_REPO_MOUNT_MAPcheckouts read-write. The no-egress guarantee holds in production only. Hogland maps onlyDEFAULT_BASE, so this workload does not run there. - A large
--backfill-daysrun emits N × population events into Kafka in a tight loop and can overwhelm a local ingestion consumer. Prefer smaller backfills; a contiguous gap in prediction dates is the symptom. - If you change the run-type split or the event shape, update this file to match.