: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.
Training loop
Finding a better model for a pipeline's question.
One run_training() call → one AutoresearchTrainingRun → one sandbox agent session → zero or more AutoresearchIteration rows → at most one new champion AutoresearchModel.
This is the expensive half of the product. A real run costs roughly a dollar in LLM spend on Sonnet, about twice that on the default Opus 5.5, and takes tens of minutes, so almost everything here is built around not wasting a run: the stub path for plumbing tests, the safety net for agents that die mid-flight, and server-side champion selection so a confused agent cannot promote itself.
The other half is ../inference/, which consumes what this package produces and must never re-fit.
What lives here
runner.pyThe real path.run_training()creates theAutoresearchTrainingRun(statusRUNNING) and firesTask.create_and_run()withinternal=Trueand no repository, so the run shows up as an internal Task rather than in the normal Tasks list. The brief carries user-authored text, so the sandbox token holds onlyTRAINING_MCP_SCOPES(theexecute-sqlreads, the autoresearch scopes, anduser:read, which the PostHog MCP server needs to start a session), and an empty connector allowlist keeps the team's shared MCP connectors out of the sandbox.run_training()lowers the requested iterations to the project'smax_iterations_per_run(../limits.py), so scheduled and manual runs share one ceiling. The daily run cap is checked by its callers, inside the pipeline row lock. The task runs on the model and reasoning effort thatagent_run_config_for()inagent_model.pyresolves, and the run records the runtime adapter, model and effort inagent_runtime_adapter,agent_modelandagent_reasoning_effort.build_agent_description()assembles the agent's brief — the target, the horizon, the population, and the contract for the bundle it must author. When theautoresearch-report-notebookflag is on for the launching user, the token also holdsREPORT_NOTEBOOK_MCP_SCOPESand the brief adds two Finalize steps: before complete, the agent creates one report notebook and passes itsshort_idto complete. After complete, it adds the SQL and chart cells, because the run's model row (and so itsmodel_explanation) exists only from then on.report.mdstays required either way. The brief's workedfeatures.sqlreads events through a pre-filtered subquery (the event names the features use, the anchor persons, and the anchors' widest window) before it joins, because ClickHouse builds the hash table from the right side of a join and a direct events join reads the whole team's events. The brief states the two limits of the fit at completion, from the constants: the fittedmodel.pklmust stay underMAX_ARTIFACT_BYTES(the readback cap offit_champion_model()), andfeatures.sqlmust finish insideINTERACTIVE_QUERY_TIME_LIMIT_S(../query.py), because the fit runs it underINTERACTIVE_QUERY. A model that breaks either limit rolls back. The brief also states the inference cutoff: the start of the prediction date in UTC (ScoringWindowin../inference/scoring.py), notnow(). The brief's cost guidance is advice only. Cost does not enter champion selection, so the brief does not tell the agent to trade AUC for a cheaper query. A rescue run is the one exception, see the unscorable champion below. For a person column that events do not carry, the brief recommendsraw_personsin a subquery filtered withid IN (SELECT person_id FROM {anchors}), neverLEFT JOIN persons, because the persons table dedupes every person of the team before any filter applies.feature_sql_hints()inrecipe_validation.pyreturns a non-blocking hint when a query readspersonsorraw_personsin a SELECT whoseWHEREdoes not refer to{anchors}. Thematerialize-featuresresponse carries the hints, with theelapsed_sandrows_readof the materialization. Step 0 of the brief carries the realized results thatrealized_context.pycomputes, wrapped as untrusted data, with guidance on how to read the gap between holdout and realized AUC. The brief presents realized AUC as evidence for a direction, never as a target: the next run's holdout covers the same recent dates, so tuning against realized results tunes against the holdout. A pipeline with no validated dates gets one line instead of tables.report.mdasks for one line on how the run used these results. The agent drives the rest itself through theautoresearch-*MCP tools: it records each iteration, uploads the bundle, and calls complete. Nothing polls it.agent_model.pyWhich model and reasoning effort the training agent runs on. Training is an internal task, and internal tasks skip team and user run preferences, so without an explicit model the run would take the Tasks default and change with it. A pipeline's nullagent_modelresolves toAUTORESEARCH_DEFAULT_MODEL(claude-opus-5-5), and a nullagent_reasoning_efforttoAUTORESEARCH_DEFAULT_REASONING_EFFORT(medium). The runtime adapter comes from the model, so a Codex model runs on the Codex adapter. A stored model the catalogue no longer serves resolves to the default model, and an effort the model does not support resolves to the default effort, so a stale row never fails a paid run at dispatch. The write path is stricter:validate_agent_settings()rejects a model outsideagent_model_choices()and an effort the model does not support. The choices are the offered Tasks catalogue models without an access flag, read through the tasks facade only. Opus 5.5 lists at twice Sonnet 5.5's token price, so a run on the default costs roughly twice what a Sonnet run costs. The brief must read the same under every runtime, so keep harness-specific wording out of it.stub.pyrun_stub_training()— a hand-authored champion recipe with universal engagement features (event counts, distinct event types, days since first seen) that apply to any team and any target. No agent, no LLM spend, deterministic. This is what--stubonautoresearch_trainuses, and it is the right tool for testing anything downstream of training.ingestion.pyThe safety net.handle_task_run_completed()is called from theTaskRunpost_savesignal registered in../apps.py, and runs synchronously in the Temporal worker thread. If the agent recorded iterations but never called complete, this finalizes through the same promotion path. If it recorded nothing, the run is marked failed — which is what produces"Agent recorded no iterations before the run ended."run_training()writes theautoresearch_training_run_idmarker intoTaskRun.statewhen it creates the task, and tasks refuses a patch to it. The marker names a run; ownership is proved by the run's server-stampedtask_run_id, so aTaskRunmay only finalize the run whosetask_run_idis its own id.stale.pyThe backstop for the safety net.fail_stale_training_runs()closes everypendingorrunningrun with atask_run_idthat is older thanSTALE_TRAINING_RUN_AFTER(twice the TasksMAX_SANDBOX_TTL_SECONDS, read through the tasks facade). When theTaskRunis terminal (missed_handoff), it callshandle_task_run_completed(), so the run ends with the outcome the receiver would have given it. When theTaskRunis still live or no longer exists (lost_driver), it fails the run and cancels theTaskRunbest-effort. A cancel failure only logs. Every failure re-reads the run under its row lock and changes only an open run, so a run that completes at the same time keeps its outcome. Each closed run logsautoresearch_stale_training_run_reapedand incrementsautoresearch_stale_training_runs_reaped_total, both with the case. A run with notask_run_id(an external run fromopen_training_run(), or a stub) is not reaped. Coordinator discovery calls it for all teams.activity_kickoff_trainingand the facade'sstart_trainingcall it for their pipeline before the live-run check.promotion.pyChampion selection.complete_training_run()is the single entry point, used both by the training-runcompleteAPI action and byingestion.py. A challenger must beat the incumbent byCHAMPION_PROMOTION_MARGIN(0.005 holdout AUC) to be promoted — near-ties keep the incumbent rather than churning the champion on noise._detect_uploaded_bundle()decides whether the new model gets anartifact_prefix(bundle path) or only a recorded recipe (legacy path). The bundle is written once per run, so a losing iteration can overwrite it: the uploadedfeatures.sqlmust match thefeature_sqlrecorded by the selected iteration, whitespace aside, or promotion raises rather than publishing a champion whose recipe and score describe other code.complete_training_run()reads the bundle and enters the run'steam_scope()before it opens the transaction, because theTaskRunsafety net calls it from a worker thread with no request scope, and object-storage calls must not run under the row lock. The agent'sreport_notebook_short_idgoes into the run summary only if that notebook exists in the run's team. A bad id or a failed check stores an empty value and never fails completion. The run and each iteration carry an optionalheadlinefor the Agent research tab. The write serializers collapse its whitespace and cut it toHEADLINE_MAX_LENGTH(60) characters rather than reject it, so a long or missing headline never fails a run. A promoted bundle-backed model is fitted. A bundle-backed challenger is fitted only when it enters the shadow set (seeshadow_set.py). The fit runs after commit and never changes the completion result. A successful challenger fit setsmetrics.model_fitted, and a failed one only logs. A challenger withoutmodel_fittedstays out of the shadow set. After a champion fit,check_scorability()runs the bundle'sfeatures.sqlagainst today's inference anchors underBATCH_QUERY. A passing check recordsscorability_elapsed_sandscorability_rows_readin the model metrics and setsmodel_fitted. A failed fit, a failed check, or a check aboveSCORABILITY_TIME_BUDGET_S(half the batch query limit) rolls the promotion back under the pipeline lock: the candidate becomes a challenger withnot_promoted_reasonin its metrics, and the champion it archived comes back. A first champion that rolls back puts the pipeline back in the status it had before promotion. The run summary then recordschampion_promoted: false, so the research schedule ends explore for it. Abootstrappingpipeline in this state (awaiting_first_champion()inschedule.py) keeps its research schedule, see../temporal/AGENTS.md, and the pipeline API returns the candidate's reason asnot_promoted_reason. The rolled-back candidate has nomodel_fitted, so it never enters the shadow set. The rollback changes nothing when the candidate is no longer the champion. A scoring run that started with the candidate fails in_require_still_champion()before it emits. A recipe-only champion is not checked. A champion whose scheduled scoring runs failed with a repeatablefailure_kindon the last two prediction dates, with no success after the first of them, is unscorable (find_unscorable_champion()in../inference/failures.py). Any candidate replaces it whatever the margin, withpromotion_reasonreplaced_unscorablein the model metrics, and the fit and the scorability check still roll back a candidate that cannot score either. The brief tells the agent the failure kind and the onset date. A rescue run (see../temporal/AGENTS.md) also tells the agent to prefer a cheap model that scores over a higher holdout score. A champion whose metrics lackanchor_alignment: "utc_day"was trained on T0s at any second (see../dataset/AGENTS.md), so its holdout score is inflated and is no bar. Any candidate replaces it whatever the margin, withpromotion_reasonreplaced_anchor_change. Every new model recordsanchor_alignment.explanation.pyThemodel_explanationcontract:top_features(at mostMAX_TOP_FEATURES, each aname, a non-negativeimportanceand adirectionofpositiveornegative), plus an optionalmethodandnote. Thecompleteserializer enforces it and sorts the features strongest first, and the brief states it. Champions written before the contract stored other shapes (featuresorfeature_importanceslists, afeaturekey,auc_drop_when_shuffledorgainfor the importance, prose directions such ashigher -> less likely). The rows are not backfilled.normalize_model_explanation()maps them on read in the facade and drops entries it cannot read, so the API always returns the typed shape.shadow_set.pyshadow_set(pipeline)computes the models worth scoring side by side. Nothing stores the set. It holds the champion, the previous champion (the newest archived bundle-backed row withpromoted_atset), and up toSHADOW_CHALLENGER_LIMIT(3) fitted bundle-backed challengers. No two members share arecipe_hash. A challenger younger thanhorizon_days + SHADOW_MIN_MATURED_DATESdays keeps its place, so a new challenger cannot displace it. Past that age, a newer challenger displaces it. A challenger that does not enter at completion is never fitted, so it cannot enter later. A model that cannot score never enters the set, and the next eligible model takes its slot. A previous-champion candidate cannot score when promotion archived it withmetrics.archived_reasonunscorable(set on areplaced_unscorablepromotion, and cleared when a rollback restores the champion). Any candidate cannot score whenmodels_failing_repeatably_in_shadow()in../inference/failures.pyfinds repeatable failures onUNSCORABLE_AFTER_FAILED_DAYSscoring days since its last completed run, read over its shadow runs and its scheduled champion runs. Kindothernever counts. Nothing deletes the model row or its artifacts. The models API exposes membership asin_shadow_set. Every live scoring cadence scores the set (see../inference/AGENTS.md). Nothing promotes from the set yet.realized_context.pybuild_realized_context(pipeline)reads the validation history throughlatest_validation_runs()in../evaluation/history.py, the same read as theonline_performanceAPI. For each shadow-set member (champion, previous champion, shadow challengers) it keeps at mostREALIZED_DATES_PER_MODEL(14) dates: realized AUC with its interval, positives, mean score against base rate, and the gap to holdout. It also picks at mostRELATED_PIPELINES_LIMIT(5) pipelines of the same team with a realized result: the same target at another horizon first, then the same training population with another target, nearest horizon first. For those the brief shows only the gap and calibration of the model that served each date, because AUCs at another horizon or for another target do not compare. A population thatever_performed_targetoractive_not_performed_targetdefines resolves against each pipeline's own target, so it never counts as the same population.artifacts.pyObject storage for the bundle:features.sql,train.py,predict.py, plus the fittedmodel.pklwritten at completion. Keys are prefixed by team / pipeline / training-run (bundle_prefix()), so history is preserved naturally and bundles can never collide across tenants.normalize_artifact_path(),MAX_OBJECT_KEY_BYTES(S3's 1024-byte key limit) andMAX_ARTIFACT_BYTES(10 MiB) are the guardrails on agent-supplied paths and sizes — the agent chooses these strings, so treat them as untrusted input.read_bundle()raisesPartialBundlewhen a prefix holds some of the three files but not all, so an interrupted upload cannot read as "no bundle" and fall back to the recipe path. An upload of one of the three bundle files is checked before it is acknowledged: the content must be non-empty UTF-8, andfeatures.sqlmust passvalidate_feature_sql(), because fitting and inference run the uploaded query rather than the recorded snapshot. A write raisesObjectStorageErrorwhen object storage is disabled instead of reporting a success the shared client silently dropped.recipe_validation.pyServer-side validation of whatever an agent records.validate_recipe()first checks the shape of both JSON fields (objects, a stringmodel_class, a stringfeature_sql), so malformed agent input is a validation error rather than a 500.validate_feature_sql()then parses the SQL and enforces the one-row-per-person contract on the AST:{anchors}must be a table in the top-level FROM (a placeholder inside a string literal or a comment does not count, because substitution only replaces it in code position, and behind a CTE the key could be transformed and renamed), the output columns are listed explicitly with exactly onedistinct_idthat is the anchors table's ownperson_idfield, not an expression over it or a joined table's key, and none named__labelor__fold(the training wrapper appends those), no reference to the wrapper's own CTEs (labeled_users,labeled_anchors, ...), which carry the label, and no wall-clock reads (now()in any case, aliases such ascurrent_timestamp()that resolve to it, and bare keywords likeCURRENT_DATE) because a window bound to "now" reads outcome-window events at training time (target leakage). It does not prove every event read is bounded bycutoff_ts; that remains the agent's contract.validate_unique_distinct_ids()re-checks the one-row-per-person contract on actual materialized rows, where duplicates first become visible; passexpected_countto also require one row per anchor, so an inner join cannot silently drop persons.validate_model_class()is deliberately not applied at recording time — in the bundle world the agent's real model is arbitrary sandboxed code, so a recordedmodel_classis informational. The allowlist is enforced only where it is a genuine code-execution surface: the legacy in-process path in../inference/scoring.py, which resolves it throughimportlib, andpromotion.py, which refuses a champion that takes that path with a class the scorer cannot load.
Mental model
The agent proposes, the backend disposes.
run_training()inserts the run row and launches the sandbox. The run's id is handed to the agent so it can address its own run over MCP.- The agent explores with HogQL, tries a feature set plus a model spec, evaluates on holdout, and records the result as an
AutoresearchIterationwithstatuskeptordiscardedand its ownagent_confidence. Recording is live — rows appear during the run, not in a batch at the end. - When it is satisfied it uploads the bundle and calls complete.
complete_training_run()reads the iterations, picks the best by holdout score, applies the promotion margin, and writes theAutoresearchModel.
The agent's status on an iteration and its confidence are evidence, not a decision. _select_best_iteration() is what actually chooses.
Two things routinely surprise people:
AutoresearchTrainingRun.iteration_countis only written at completion. Iteration rows land live, so a run in flight reads0/5with rows already in the table. Poll the rows, not the counter.autoresearch_traindoes not enforce../dataset/validation.py. A target that fails validation on volume will still train. That is deliberate for local dev on thin datasets, but it means a run can "succeed" on far too few rows.
Where the rest of the system meets this package
- Launched by — the
trainAPI action in../presentation/views/views.py, theautoresearch_trainmanagement command, andactivity_kickoff_trainingin../temporal/workflows.py. - Finalized by — the
completeaction on the training-run viewset, oringestion.pyvia theTaskRunpost_savesignal wired in../apps.py, orstale.pywhen neither ran. - Consumed by —
../inference/, which reads the champion'sartifact_prefixand runs its bundle.fit_champion_model()in../inference/sandbox.pyis what actually fits and persistsmodel.pklat completion time, for the champion and for a challenger that enters the shadow set. Shadow scoring loads thatmodel.pklthe same way the champion's scoring does. - Agent-facing surface — the
autoresearch-training-runs-*MCP tools in../../mcp/tools.yaml, backed by the viewsets in../presentation/views/views.py. The sandbox agent has no other way to write. - Labels and features —
../dataset/labeling.pybuilds the training population the bundle is fitted against.
When editing this flow
- Never let agent output select the champion. Everything that decides goes through
complete_training_run(). If you add a new completion path, route it there rather than writing anAutoresearchModeldirectly. - Any new agent-writable field needs validation in
recipe_validation.py. The agent is an untrusted author: SQL it writes is executed, paths it supplies become storage keys. - Keep
stub.pyworking. It is the only way to test the whole downstream chain without spending money, and it is what local E2E leans on. If you change the recipe shape, change the stub too or every plumbing test silently starts covering nothing. - Both model shapes must keep working. A model with an
artifact_prefixruns its bundle; one without carries onlymodel_recipeand takes the legacy in-process path. Do not assumeartifact_prefixis populated. - If you change the bundle file set or layout, update
artifacts.py, the agent brief inrunner.py, and../../backend/test_fixtures/bundle/together — the fixtures are what the tests fit against. - If you change this package's layout or the agent contract, update this file to match.