Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

21.6 KB
Raw Blame

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.py The real path. run_training() creates the AutoresearchTrainingRun (status RUNNING) and fires Task.create_and_run() with internal=True and 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 only TRAINING_MCP_SCOPES (the execute-sql reads, the autoresearch scopes, and user: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's max_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 that agent_run_config_for() in agent_model.py resolves, and the run records the runtime adapter, model and effort in agent_runtime_adapter, agent_model and agent_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 the autoresearch-report-notebook flag is on for the launching user, the token also holds REPORT_NOTEBOOK_MCP_SCOPES and the brief adds two Finalize steps: before complete, the agent creates one report notebook and passes its short_id to complete. After complete, it adds the SQL and chart cells, because the run's model row (and so its model_explanation) exists only from then on. report.md stays required either way. The brief's worked features.sql reads 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 fitted model.pkl must stay under MAX_ARTIFACT_BYTES (the readback cap of fit_champion_model()), and features.sql must finish inside INTERACTIVE_QUERY_TIME_LIMIT_S (../query.py), because the fit runs it under INTERACTIVE_QUERY. A model that breaks either limit rolls back. The brief also states the inference cutoff: the start of the prediction date in UTC (ScoringWindow in ../inference/scoring.py), not now(). 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 recommends raw_persons in a subquery filtered with id IN (SELECT person_id FROM {anchors}), never LEFT JOIN persons, because the persons table dedupes every person of the team before any filter applies. feature_sql_hints() in recipe_validation.py returns a non-blocking hint when a query reads persons or raw_persons in a SELECT whose WHERE does not refer to {anchors}. The materialize-features response carries the hints, with the elapsed_s and rows_read of the materialization. Step 0 of the brief carries the realized results that realized_context.py computes, 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.md asks for one line on how the run used these results. The agent drives the rest itself through the autoresearch-* MCP tools: it records each iteration, uploads the bundle, and calls complete. Nothing polls it.
  • agent_model.py Which 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 null agent_model resolves to AUTORESEARCH_DEFAULT_MODEL (claude-opus-5-5), and a null agent_reasoning_effort to AUTORESEARCH_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 outside agent_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.py run_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 --stub on autoresearch_train uses, and it is the right tool for testing anything downstream of training.
  • ingestion.py The safety net. handle_task_run_completed() is called from the TaskRun post_save signal 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 the autoresearch_training_run_id marker into TaskRun.state when it creates the task, and tasks refuses a patch to it. The marker names a run; ownership is proved by the run's server-stamped task_run_id, so a TaskRun may only finalize the run whose task_run_id is its own id.
  • stale.py The backstop for the safety net. fail_stale_training_runs() closes every pending or running run with a task_run_id that is older than STALE_TRAINING_RUN_AFTER (twice the Tasks MAX_SANDBOX_TTL_SECONDS, read through the tasks facade). When the TaskRun is terminal (missed_handoff), it calls handle_task_run_completed(), so the run ends with the outcome the receiver would have given it. When the TaskRun is still live or no longer exists (lost_driver), it fails the run and cancels the TaskRun best-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 logs autoresearch_stale_training_run_reaped and increments autoresearch_stale_training_runs_reaped_total, both with the case. A run with no task_run_id (an external run from open_training_run(), or a stub) is not reaped. Coordinator discovery calls it for all teams. activity_kickoff_training and the facade's start_training call it for their pipeline before the live-run check.
  • promotion.py Champion selection. complete_training_run() is the single entry point, used both by the training-run complete API action and by ingestion.py. A challenger must beat the incumbent by CHAMPION_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 an artifact_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 uploaded features.sql must match the feature_sql recorded 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's team_scope() before it opens the transaction, because the TaskRun safety net calls it from a worker thread with no request scope, and object-storage calls must not run under the row lock. The agent's report_notebook_short_id goes 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 optional headline for the Agent research tab. The write serializers collapse its whitespace and cut it to HEADLINE_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 (see shadow_set.py). The fit runs after commit and never changes the completion result. A successful challenger fit sets metrics.model_fitted, and a failed one only logs. A challenger without model_fitted stays out of the shadow set. After a champion fit, check_scorability() runs the bundle's features.sql against today's inference anchors under BATCH_QUERY. A passing check records scorability_elapsed_s and scorability_rows_read in the model metrics and sets model_fitted. A failed fit, a failed check, or a check above SCORABILITY_TIME_BUDGET_S (half the batch query limit) rolls the promotion back under the pipeline lock: the candidate becomes a challenger with not_promoted_reason in 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 records champion_promoted: false, so the research schedule ends explore for it. A bootstrapping pipeline in this state (awaiting_first_champion() in schedule.py) keeps its research schedule, see ../temporal/AGENTS.md, and the pipeline API returns the candidate's reason as not_promoted_reason. The rolled-back candidate has no model_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 repeatable failure_kind on 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, with promotion_reason replaced_unscorable in 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 lack anchor_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, with promotion_reason replaced_anchor_change. Every new model records anchor_alignment.
  • explanation.py The model_explanation contract: top_features (at most MAX_TOP_FEATURES, each a name, a non-negative importance and a direction of positive or negative), plus an optional method and note. The complete serializer enforces it and sorts the features strongest first, and the brief states it. Champions written before the contract stored other shapes (features or feature_importances lists, a feature key, auc_drop_when_shuffled or gain for the importance, prose directions such as higher -> 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.py shadow_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 with promoted_at set), and up to SHADOW_CHALLENGER_LIMIT (3) fitted bundle-backed challengers. No two members share a recipe_hash. A challenger younger than horizon_days + SHADOW_MIN_MATURED_DATES days 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 with metrics.archived_reason unscorable (set on a replaced_unscorable promotion, and cleared when a rollback restores the champion). Any candidate cannot score when models_failing_repeatably_in_shadow() in ../inference/failures.py finds repeatable failures on UNSCORABLE_AFTER_FAILED_DAYS scoring days since its last completed run, read over its shadow runs and its scheduled champion runs. Kind other never counts. Nothing deletes the model row or its artifacts. The models API exposes membership as in_shadow_set. Every live scoring cadence scores the set (see ../inference/AGENTS.md). Nothing promotes from the set yet.
  • realized_context.py build_realized_context(pipeline) reads the validation history through latest_validation_runs() in ../evaluation/history.py, the same read as the online_performance API. For each shadow-set member (champion, previous champion, shadow challengers) it keeps at most REALIZED_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 most RELATED_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 that ever_performed_target or active_not_performed_target defines resolves against each pipeline's own target, so it never counts as the same population.
  • artifacts.py Object storage for the bundle: features.sql, train.py, predict.py, plus the fitted model.pkl written 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) and MAX_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() raises PartialBundle when 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, and features.sql must pass validate_feature_sql(), because fitting and inference run the uploaded query rather than the recorded snapshot. A write raises ObjectStorageError when object storage is disabled instead of reporting a success the shared client silently dropped.
  • recipe_validation.py Server-side validation of whatever an agent records. validate_recipe() first checks the shape of both JSON fields (objects, a string model_class, a string feature_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 one distinct_id that is the anchors table's own person_id field, not an expression over it or a joined table's key, and none named __label or __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 as current_timestamp() that resolve to it, and bare keywords like CURRENT_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 by cutoff_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; pass expected_count to 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 recorded model_class is 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 through importlib, and promotion.py, which refuses a champion that takes that path with a class the scorer cannot load.

Mental model

The agent proposes, the backend disposes.

  1. 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.
  2. The agent explores with HogQL, tries a feature set plus a model spec, evaluates on holdout, and records the result as an AutoresearchIteration with status kept or discarded and its own agent_confidence. Recording is live — rows appear during the run, not in a batch at the end.
  3. When it is satisfied it uploads the bundle and calls complete.
  4. complete_training_run() reads the iterations, picks the best by holdout score, applies the promotion margin, and writes the AutoresearchModel.

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_count is only written at completion. Iteration rows land live, so a run in flight reads 0/5 with rows already in the table. Poll the rows, not the counter.
  • autoresearch_train does 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 train API action in ../presentation/views/views.py, the autoresearch_train management command, and activity_kickoff_training in ../temporal/workflows.py.
  • Finalized by — the complete action on the training-run viewset, or ingestion.py via the TaskRun post_save signal wired in ../apps.py, or stale.py when neither ran.
  • Consumed by — ../inference/, which reads the champion's artifact_prefix and runs its bundle. fit_champion_model() in ../inference/sandbox.py is what actually fits and persists model.pkl at completion time, for the champion and for a challenger that enters the shadow set. Shadow scoring loads that model.pkl the 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.py builds 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 an AutoresearchModel directly.
  • 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.py working. 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_prefix runs its bundle; one without carries only model_recipe and takes the legacy in-process path. Do not assume artifact_prefix is populated.
  • If you change the bundle file set or layout, update artifacts.py, the agent brief in runner.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.