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.

feat(autoresearch): promote the best training run to champion (9/22) (#89135)

Andrew Maguired8a69fc35091
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index 3724dea99471..2274a9bf6fdc 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -25,14 +25,18 @@ This package landed ahead of its callers. `../presentation/`, `../temporal/`, `.
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.
+ Only a promoted model is fitted. A challenger's `model.pkl` would never be read, because inference serves the champion and no path promotes a challenger row later.
- `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`.
+ `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
diff --git a/products/autoresearch/backend/training/artifacts.py b/products/autoresearch/backend/training/artifacts.py
index 6aabf6adc76f..f90d1f1638ef 100644
--- a/products/autoresearch/backend/training/artifacts.py
+++ b/products/autoresearch/backend/training/artifacts.py
@@ -144,6 +144,8 @@ class ArtifactBundle:
@classmethod
def from_files(cls, files: dict[str, bytes]) -> ArtifactBundle:
missing = [name for name in BUNDLE_FILES if name not in files]
+ if missing and files:
+ raise PartialBundle(f"Bundle is missing required files: {', '.join(missing)}")
if missing:
raise BundleNotFound(f"Bundle is missing required files: {', '.join(missing)}")
return cls(
@@ -164,6 +166,16 @@ class BundleNotFound(Exception):
"""Raised when a bundle prefix has no (or an incomplete) set of files."""
+class PartialBundle(BundleNotFound):
+ """
+ Raised when a prefix holds some bundle files but not all three.
+
+ A caller that treats a missing bundle as "the agent did not upload one" must not treat
+ this the same way. An interrupted upload would then take the legacy recipe path and
+ serve an implementation the agent never wrote.
+ """
+
+
def bundle_prefix(*, team_id: int, pipeline_id: str, training_run_id: str) -> str:
"""Object-storage key prefix (no trailing slash) for one training run's bundle."""
folder = settings.OBJECT_STORAGE_TASKS_FOLDER
diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.py
new file mode 100644
index 000000000000..8e22f3de3506
--- /dev/null
+++ b/products/autoresearch/backend/training/promotion.py
@@ -0,0 +1,453 @@
+"""Champion selection and promotion for agent-recorded training runs.
+
+The agent records candidate iterations; the backend alone decides the champion. Used by
+the training-run ``complete`` action and by ``training_ingestion.handle_task_run_completed``
+when a run ends without the agent finalizing. When the agent has uploaded a runnable bundle
+for the run, the champion's ``artifact_prefix`` points at it (inference runs the bundle in a
+sandbox); otherwise the model carries only the recorded recipe (legacy in-process path).
+"""
+
+import json
+import hashlib
+from datetime import date
+from typing import Any
+from uuid import UUID
+
+from django.db import transaction
+from django.db.models import F
+from django.utils import timezone as django_timezone
+
+import structlog
+
+from posthog.hogql.errors import BaseHogQLError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.visitor import clear_locations
+
+from posthog.models.scoping import team_scope
+
+from products.autoresearch.backend.inference.sandbox import fit_champion_model
+from products.autoresearch.backend.models import (
+ AutoresearchIteration,
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchTrainingRun,
+)
+from products.autoresearch.backend.training import artifacts
+from products.autoresearch.backend.training.recipe_validation import (
+ RecipeValidationError,
+ validate_feature_sql,
+ validate_model_class,
+)
+
+logger = structlog.get_logger(__name__)
+
+# A challenger must beat the current champion's holdout score by at least this margin
+# before it is promoted — guards against thrashing on noise-level differences.
+CHAMPION_PROMOTION_MARGIN = 0.005
+
+
+class PromotionError(ValueError):
+ """Raised when completion cannot select a valid champion candidate."""
+
+
+_FINALIZABLE_STATUSES = (AutoresearchTrainingRun.Status.RUNNING, AutoresearchTrainingRun.Status.PENDING)
+
+
+def _already_finalized(training_run: AutoresearchTrainingRun) -> dict[str, Any]:
+ logger.info(
+ "autoresearch_training_run_already_finalized",
+ training_run_id=str(training_run.id),
+ status=training_run.status,
+ )
+ return {
+ "promoted": False,
+ "model_id": None,
+ "role": None,
+ "iteration_count": training_run.iteration_count,
+ "best_holdout_score": training_run.best_holdout_score,
+ }
+
+
+def _select_best_iteration(
+ training_run: AutoresearchTrainingRun, best_iteration_id: UUID | None
+) -> AutoresearchIteration:
+ iterations = AutoresearchIteration.objects.filter(training_run=training_run)
+ if best_iteration_id is not None and not iterations.filter(id=best_iteration_id).exists():
+ raise PromotionError(f"Iteration {best_iteration_id} not found in this training run.")
+
+ # Postgres puts NULLs first on a bare DESC, which would rank an unscored iteration
+ # above every scored one.
+ ranked_by_score = F("holdout_score").desc(nulls_last=True)
+ # The later iteration wins a tie, so the selection is the same on every run. Without the
+ # second key Postgres may return either row, and the bundle check would then reject a run
+ # whose uploaded bundle belongs to the other tied iteration.
+ eligible = iterations.filter(status=AutoresearchIteration.Status.KEPT, holdout_score__isnull=False).order_by(
+ ranked_by_score, "-iteration_number"
+ )
+ best = eligible.first()
+ if best is None:
+ # A run whose iterations all crashed, were discarded, or went unscored is a failed
+ # experiment. Promoting one of them would install it as a live champion at score 0.
+ raise PromotionError("Training run has no kept, scored iteration to select a champion from.")
+
+ if best_iteration_id is not None and best_iteration_id != best.id:
+ nominated = eligible.filter(id=best_iteration_id).first()
+ if nominated is not None and nominated.holdout_score == best.holdout_score:
+ # Tied at the top score, so the nomination breaks the tie rather than overriding
+ # the ranking. The agent knows which of the tied iterations its bundle came from.
+ return nominated
+ # The nomination comes from the untrusted sandbox agent, so it can only confirm the
+ # server-side ranking, never override it.
+ logger.warning(
+ "autoresearch_nominated_iteration_not_best",
+ training_run_id=str(training_run.id),
+ nominated_iteration_id=str(best_iteration_id),
+ selected_iteration_id=str(best.id),
+ )
+ return best
+
+
+def _build_recipe(iteration: AutoresearchIteration, *, trained_on: date) -> dict[str, Any]:
+ snapshot = iteration.recipe_snapshot or {}
+ spec = iteration.model_spec or {}
+ return {
+ "feature_sql": snapshot.get("feature_sql", ""),
+ "feature_transforms": snapshot.get("feature_transforms", []),
+ "model_class": spec.get("model_class", "sklearn.linear_model.LogisticRegression"),
+ "model_params": spec.get("model_params", {}),
+ "fit_signature": (iteration.recipe_hash or "")[:16],
+ "trained_on": trained_on.isoformat(),
+ "holdout_score": iteration.holdout_score or 0.0,
+ "agent_description": iteration.agent_description,
+ }
+
+
+def _beats_incumbent(candidate: float, incumbent: float) -> bool:
+ """Binary floats put ``0.1 + 0.005`` above ``0.105``, so adding the margin to the
+ incumbent would reject a candidate that lands exactly on it. The improvement is rounded
+ first, far below any AUC difference that carries meaning."""
+ return round(candidate - incumbent, 9) >= CHAMPION_PROMOTION_MARGIN
+
+
+def _recipe_hash(recipe: dict[str, Any]) -> str:
+ """
+ The model's ``recipe_hash`` is documented as the digest of its recipe JSON, and
+ deduplication and provenance read it that way. The iteration's own hash is an
+ agent-supplied string over different content, so the digest is computed here.
+ """
+ return hashlib.sha256(json.dumps(recipe, sort_keys=True, default=str).encode("utf-8")).hexdigest()
+
+
+def _summary_item(iteration: AutoresearchIteration) -> dict[str, Any]:
+ spec = iteration.model_spec or {}
+ return {
+ "iteration_number": iteration.iteration_number,
+ "holdout_score": iteration.holdout_score,
+ "model_class": spec.get("model_class", ""),
+ "agent_description": iteration.agent_description or "",
+ }
+
+
+def _serving_model_class(*, promoted: bool, model: AutoresearchModel, incumbent: AutoresearchModel | None) -> str:
+ """The class of the model that serves after this run. A rejected challenger leaves the
+ incumbent in place, and the next run reads this field as the champion it has to beat."""
+ serving = model if promoted else incumbent
+ return str((serving.model_recipe or {}).get("model_class", "")) if serving else ""
+
+
+def _build_run_summary(
+ training_run: AutoresearchTrainingRun,
+ *,
+ best: AutoresearchIteration | None,
+ iterations: list[AutoresearchIteration],
+ promoted: bool,
+ champion_model_class: str,
+ recommended_next: str,
+ distillation: str,
+) -> dict[str, Any]:
+ """Tier-1 cross-run memory: backend derives the structural facts; the agent supplies the two
+ judgment fields (recommended_next, distillation). Read back by a new run before it iterates."""
+ pipeline = training_run.pipeline
+ kept = sorted(
+ (it for it in iterations if it.status == AutoresearchIteration.Status.KEPT),
+ key=lambda it: it.holdout_score if it.holdout_score is not None else -1.0,
+ reverse=True,
+ )
+ dead_ends = [it for it in iterations if it.status != AutoresearchIteration.Status.KEPT]
+ return {
+ "target_event": pipeline.target_event,
+ "horizon_days": pipeline.horizon_days,
+ "best_holdout_score": best.holdout_score if best else None,
+ "champion_promoted": promoted,
+ "champion_model_class": champion_model_class,
+ "kept_ladder": [_summary_item(it) for it in kept],
+ "dead_ends": [_summary_item(it) for it in dead_ends],
+ "recommended_next": recommended_next or "",
+ "distillation": distillation or "",
+ }
+
+
+def _same_query(left: str, right: str) -> bool:
+ """
+ Compare two feature queries by their parsed form, with source positions dropped.
+
+ Reindenting a query between recording and upload is not a different model, but
+ whitespace inside a string literal is: ``'plan upgraded'`` and ``'plan upgraded'``
+ match different events. A text comparison can only have one of those two properties.
+ Unparsable SQL counts as different, because nothing can run it either.
+ """
+ try:
+ return clear_locations(parse_select(left)) == clear_locations(parse_select(right))
+ except BaseHogQLError:
+ return False
+
+
+def _require_bundle_matches_iteration(bundle: artifacts.ArtifactBundle, best: AutoresearchIteration) -> None:
+ """
+ The model row advertises the selected iteration's recipe and holdout score, and inference
+ runs the uploaded bundle. Nothing binds the two: the bundle is written once per run, so a
+ later iteration can overwrite it, and the agent can upload SQL it never recorded. When the
+ two disagree the champion misdescribes the code it executes, so refuse the run.
+ """
+ recorded = str((best.recipe_snapshot or {}).get("feature_sql") or "")
+ if not _same_query(recorded, bundle.features_sql):
+ raise PromotionError(
+ "Uploaded bundle's features.sql does not match the feature_sql recorded by iteration "
+ f"{best.iteration_number}, so the bundle is not the code that produced the selected score."
+ )
+
+
+def _require_legacy_recipe_is_runnable(recipe: dict[str, Any]) -> None:
+ """
+ Without a bundle the model scores in process: it runs the recorded feature_sql and
+ resolves model_class through importlib against the allowlist. Iteration recording
+ accepts any class, because a bundle runs code the allowlist cannot describe, so
+ promotion has to refuse a recipe the legacy scorer could never load.
+ """
+ if not str(recipe["feature_sql"]).strip():
+ raise PromotionError(
+ "Cannot persist a model: no complete bundle was uploaded and the selected "
+ "iteration recorded no feature_sql for the legacy scoring path."
+ )
+ try:
+ validate_model_class(str(recipe["model_class"]))
+ except RecipeValidationError as exc:
+ raise PromotionError(f"Cannot persist a model on the legacy scoring path: {exc}") from exc
+
+
+def _bundle_prefix_for(training_run: AutoresearchTrainingRun) -> str:
+ return artifacts.bundle_prefix(
+ team_id=training_run.pipeline.team_id,
+ pipeline_id=str(training_run.pipeline_id),
+ training_run_id=str(training_run.id),
+ )
+
+
+def _read_uploaded_bundle(training_run: AutoresearchTrainingRun) -> artifacts.ArtifactBundle | None:
+ """
+ Read the complete artifact bundle (train.py, predict.py, features.sql) the agent uploaded
+ for this run. Returns None when no complete bundle is present (the legacy recipe-only path).
+
+ Only ``BundleNotFound`` means "no bundle". A bundle the storage layer refuses is agent
+ input, so it fails the run. Any other storage failure propagates and aborts completion so
+ it can be retried — swallowing it would permanently pin the model to the legacy recipe
+ path on a transient storage blip.
+ """
+ prefix = _bundle_prefix_for(training_run)
+ try:
+ bundle = artifacts.read_bundle(prefix)
+ except artifacts.PartialBundle as exc:
+ # An interrupted upload is not "no bundle": taking the legacy recipe path here would
+ # serve a model the agent never authored, and the run could not be retried.
+ raise PromotionError(f"Uploaded bundle at {prefix} is incomplete: {exc}") from exc
+ except artifacts.BundleNotFound:
+ return None
+ except artifacts.InvalidArtifact as exc:
+ raise PromotionError(f"Uploaded bundle at {prefix} is not usable: {exc}") from exc
+ except Exception:
+ logger.exception("autoresearch_bundle_read_failed", training_run_id=str(training_run.id), prefix=prefix)
+ raise
+ # The uploaded features.sql is what fitting and scoring actually execute, and the agent
+ # can upload SQL that never went through iteration recording — validate the real file.
+ try:
+ validate_feature_sql(bundle.features_sql)
+ except RecipeValidationError as exc:
+ raise PromotionError(f"Uploaded bundle's features.sql failed validation: {exc}") from exc
+ return bundle
+
+
+def complete_training_run(
+ training_run: AutoresearchTrainingRun,
+ *,
+ best_iteration_id: UUID | None = None,
+ model_explanation: dict[str, Any] | None = None,
+ recommended_next: str = "",
+ distillation: str = "",
+) -> dict[str, Any]:
+ """Finalize a run: pick the best iteration, decide champion vs challenger, persist the model."""
+ # The TaskRun safety net calls this from a worker thread, where no request has set a
+ # team scope, and every read below goes through a fail-closed manager. The scope is
+ # entered here so completion does not depend on the caller setting it.
+ with team_scope(training_run.team_id):
+ # A run that is already finished answers with its no-op, and reading its bundle first
+ # would make that answer depend on object storage. The lock and the second status
+ # check below still decide a completion that races the TaskRun signal.
+ current = AutoresearchTrainingRun.objects.select_related("pipeline").get(pk=training_run.pk)
+ if current.status not in _FINALIZABLE_STATUSES:
+ return _already_finalized(current)
+ # Reading the bundle is three object-storage calls. It happens before the transaction
+ # so a slow or unavailable store cannot hold the training run and its pipeline locked.
+ bundle = _read_uploaded_bundle(current)
+ return _finalize_under_lock(
+ current,
+ bundle=bundle,
+ best_iteration_id=best_iteration_id,
+ model_explanation=model_explanation,
+ recommended_next=recommended_next,
+ distillation=distillation,
+ )
+
+
+def _activate_pipeline(pipeline: AutoresearchPipeline) -> None:
+ """A pipeline with its first champion goes live: flip Draft/Bootstrapping -> Running so the
+ daily coordinator starts scoring it. Mirrors the stub path (stub_training); pause/resume
+ handle the rest. Guarded on the pre-live statuses so re-promotions on an already-live
+ (Running/Converged/Paused) pipeline are no-ops."""
+ if pipeline.status not in (AutoresearchPipeline.Status.DRAFT, AutoresearchPipeline.Status.BOOTSTRAPPING):
+ return
+ pipeline.status = AutoresearchPipeline.Status.RUNNING
+ pipeline.save(update_fields=["status", "updated_at"])
+
+
+def _schedule_champion_fit(*, pipeline: AutoresearchPipeline, prefix: str, training_run_id: str) -> None:
+ """The train run produces the serving artifact: fit the champion and persist model.pkl so
+ predict runs are pure inference. Deferred to on_commit, because the sandbox and the
+ object-storage write are side effects that must not run inside the atomic block, and the
+ fit only makes sense once the row is durably committed. A failure leaves the champion
+ without a model.pkl, and every scoring run then fails until a later promotion fits one."""
+
+ def _fit_after_commit() -> None:
+ # Every failure is caught, not only SandboxInferenceError: the run is already
+ # committed, so raising here would report a failed completion for a finished run
+ # that a retry can only answer with its no-op.
+ try:
+ fit_champion_model(team=pipeline.team, pipeline=pipeline, prefix=prefix)
+ except Exception:
+ logger.exception("autoresearch_champion_fit_failed", training_run_id=training_run_id, prefix=prefix)
+
+ transaction.on_commit(_fit_after_commit)
+
+
+def _finalize_under_lock(
+ training_run: AutoresearchTrainingRun,
+ *,
+ bundle: artifacts.ArtifactBundle | None,
+ best_iteration_id: UUID | None,
+ model_explanation: dict[str, Any] | None,
+ recommended_next: str,
+ distillation: str,
+) -> dict[str, Any]:
+ # Re-fetch under lock and re-check status inside the transaction. Both callers (the
+ # complete API action and the TaskRun post_save safety net) guard on status outside
+ # it, so a retry racing the signal could otherwise finalize the same run twice —
+ # duplicate champion/challenger rows and duplicate on_commit fits.
+ training_run = (
+ AutoresearchTrainingRun.objects.select_for_update().select_related("pipeline").get(pk=training_run.pk)
+ )
+ if training_run.status not in _FINALIZABLE_STATUSES:
+ return _already_finalized(training_run)
+
+ pipeline = training_run.pipeline
+ now = django_timezone.now()
+
+ iterations = list(AutoresearchIteration.objects.filter(training_run=training_run))
+ iteration_count = len(iterations)
+ if not iterations:
+ # Mirrors the "Agent recorded no iterations before the run ended." failure the
+ # TaskRun safety net produces — completing here would leave a BOOTSTRAPPING
+ # pipeline with no champion and no retry.
+ raise PromotionError("Agent recorded no iterations, so there is nothing to complete.")
+
+ best = _select_best_iteration(training_run, best_iteration_id)
+
+ # If the agent uploaded a runnable bundle, the champion's artifact is that bundle
+ # (inference runs train.py/predict.py in a sandbox).
+ artifact_prefix = ""
+ if bundle is not None:
+ _require_bundle_matches_iteration(bundle, best)
+ artifact_prefix = _bundle_prefix_for(training_run)
+ # The recipe JSON (derived from the winning iteration's model_spec/snapshot) backs the
+ # legacy in-process path and the model card.
+ model_recipe = _build_recipe(best, trained_on=now.date())
+ if not artifact_prefix:
+ _require_legacy_recipe_is_runnable(model_recipe)
+
+ best_score = best.holdout_score
+ candidate_score = best.holdout_score or 0.0
+ current = AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).first()
+ is_cold_start = current is None
+ beats_champion = current is not None and _beats_incumbent(candidate_score, current.holdout_score or 0.0)
+
+ promoted = False
+ role: str
+ if is_cold_start or beats_champion:
+ if current is not None:
+ AutoresearchModel.objects.filter(pk=current.pk).update(
+ role=AutoresearchModel.Role.ARCHIVED, archived_at=now
+ )
+ role = AutoresearchModel.Role.CHAMPION
+ promoted = True
+ else:
+ role = AutoresearchModel.Role.CHALLENGER
+
+ model = AutoresearchModel.objects.create(
+ pipeline=pipeline,
+ role=role,
+ recipe_hash=_recipe_hash(model_recipe),
+ model_recipe=model_recipe,
+ artifact_prefix=artifact_prefix,
+ model_explanation=model_explanation or {},
+ holdout_score=candidate_score,
+ metrics={
+ "holdout_auc": candidate_score,
+ "source": "agent_recorded",
+ "artifact_bundle": bool(artifact_prefix),
+ },
+ source_training_run=training_run,
+ agent_description=best.agent_description,
+ trained_on_start=now.date(),
+ trained_on_end=now.date(),
+ is_preliminary=True,
+ promoted_at=now if promoted else None,
+ )
+
+ training_run.status = AutoresearchTrainingRun.Status.COMPLETED
+ training_run.iteration_count = iteration_count
+ training_run.best_holdout_score = best_score
+ training_run.completed_at = now
+ training_run.summary = _build_run_summary(
+ training_run,
+ best=best,
+ iterations=iterations,
+ promoted=promoted,
+ champion_model_class=_serving_model_class(promoted=promoted, model=model, incumbent=current),
+ recommended_next=recommended_next,
+ distillation=distillation,
+ )
+ training_run.save(update_fields=["status", "iteration_count", "best_holdout_score", "summary", "completed_at"])
+
+ if promoted:
+ _activate_pipeline(pipeline)
+ # A rejected challenger is not fitted: inference reads the champion only, and no path
+ # promotes a challenger row later, so its fit would cost a sandbox run for nothing.
+ if artifact_prefix:
+ _schedule_champion_fit(pipeline=pipeline, prefix=artifact_prefix, training_run_id=str(training_run.id))
+
+ return {
+ "promoted": promoted,
+ "model_id": str(model.pk),
+ "role": role,
+ "iteration_count": iteration_count,
+ "best_holdout_score": best_score,
+ }
diff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.py
new file mode 100644
index 000000000000..ed41542d0733
--- /dev/null
+++ b/products/autoresearch/backend/training/test_promotion.py
@@ -0,0 +1,352 @@
+import json
+import hashlib
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone as django_timezone
+
+from parameterized import parameterized
+
+from posthog.models.scoping import unscoped
+from posthog.storage.object_storage import ObjectStorageError
+
+from products.autoresearch.backend.models import (
+ AutoresearchIteration,
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchTrainingRun,
+)
+from products.autoresearch.backend.testing import TeamScopedTestMixin
+from products.autoresearch.backend.training.artifacts import ArtifactBundle, InvalidArtifactContent, PartialBundle
+from products.autoresearch.backend.training.promotion import PromotionError, complete_training_run
+
+ANCHORED_FEATURE_SQL = "SELECT a.person_id AS distinct_id, count() AS c FROM {anchors} a GROUP BY a.person_id"
+LITERAL_FEATURE_SQL = (
+ "SELECT a.person_id AS distinct_id, count() AS c, 'plan upgraded' AS marker FROM {anchors} a GROUP BY a.person_id"
+)
+
+
+class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.pipeline = AutoresearchPipeline.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Test",
+ target_event="$pageview",
+ horizon_days=7,
+ iteration_budget=10,
+ iteration_budget_remaining=10,
+ )
+
+ def _run(self) -> AutoresearchTrainingRun:
+ return AutoresearchTrainingRun.objects.create(
+ pipeline=self.pipeline,
+ status=AutoresearchTrainingRun.Status.RUNNING,
+ iteration_budget=10,
+ started_at=django_timezone.now(),
+ )
+
+ def _iteration(
+ self,
+ run: AutoresearchTrainingRun,
+ *,
+ number: int,
+ status: str = AutoresearchIteration.Status.KEPT,
+ holdout: float | None = 0.8,
+ feature_sql: str = ANCHORED_FEATURE_SQL,
+ model_class: str = "sklearn.linear_model.LogisticRegression",
+ ) -> AutoresearchIteration:
+ return AutoresearchIteration.objects.create(
+ pipeline=self.pipeline,
+ training_run=run,
+ iteration_number=number,
+ recipe_hash=f"hash{number}",
+ recipe_snapshot={"feature_sql": feature_sql} if feature_sql else {},
+ model_spec={"model_class": model_class, "model_params": {}},
+ holdout_score=holdout,
+ status=status,
+ agent_description=f"iteration {number}",
+ )
+
+ def _champion(self) -> AutoresearchModel:
+ return AutoresearchModel.objects.get(pipeline=self.pipeline, role=AutoresearchModel.Role.CHAMPION)
+
+ @parameterized.expand(
+ [
+ # A null-score kept iteration must not outrank a scored one (Postgres puts
+ # NULLs first on a bare DESC).
+ ("kept_null_vs_scored", [("kept", None), ("kept", 0.6)], 0.6),
+ # A discarded iteration never wins, however it scored.
+ ("discarded_never_outranks_kept", [("discarded", 0.9), ("kept", 0.4)], 0.4),
+ ]
+ )
+ def test_champion_selection_ranks_kept_scored_iterations(self, _name, iterations, expected_score):
+ run = self._run()
+ for number, (status, holdout) in enumerate(iterations):
+ self._iteration(run, number=number, status=status, holdout=holdout)
+
+ result = complete_training_run(run)
+
+ assert result["best_holdout_score"] == expected_score
+ assert self._champion().holdout_score == expected_score
+
+ def test_completion_without_a_kept_scored_iteration_is_refused(self):
+ # A run whose iterations all crashed or went unscored is a failed experiment, not a
+ # champion at score 0.
+ run = self._run()
+ self._iteration(run, number=0, status=AutoresearchIteration.Status.CRASHED, holdout=None)
+ self._iteration(run, number=1, status=AutoresearchIteration.Status.DISCARDED, holdout=0.9)
+
+ with self.assertRaises(PromotionError):
+ complete_training_run(run)
+ assert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()
+
+ def test_nomination_cannot_beat_the_server_ranking(self):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.9)
+ nominated = self._iteration(run, number=1, holdout=0.7)
+
+ result = complete_training_run(run, best_iteration_id=nominated.id)
+
+ # The nomination comes from the sandbox agent, so a lower-scoring pick never wins.
+ assert result["best_holdout_score"] == 0.9
+
+ @parameterized.expand(
+ [
+ ("discarded", AutoresearchIteration.Status.DISCARDED, 0.95),
+ ("null_score", AutoresearchIteration.Status.KEPT, None),
+ ]
+ )
+ def test_ineligible_nomination_falls_back_to_server_selection(self, _name, status, holdout):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+ ineligible = self._iteration(run, number=1, status=status, holdout=holdout)
+
+ result = complete_training_run(run, best_iteration_id=ineligible.id)
+
+ # The nomination is ignored; the best scored kept iteration wins instead.
+ assert result["best_holdout_score"] == 0.8
+ assert self._champion().holdout_score == 0.8
+
+ def test_nomination_breaks_a_tie_at_the_top_score(self):
+ # Two iterations tie, so ranking alone cannot say which one the uploaded bundle came
+ # from. The agent's nomination decides, and it still cannot lift a lower score.
+ run = self._run()
+ tied = self._iteration(run, number=0, holdout=0.8, model_class="xgboost.XGBClassifier")
+ self._iteration(run, number=1, holdout=0.8)
+
+ # Ranking alone takes the later iteration, so a nomination for the earlier one only
+ # wins if the tie-break honors it.
+ result = complete_training_run(run, best_iteration_id=tied.id)
+
+ assert result["best_holdout_score"] == 0.8
+ assert self._champion().model_recipe["model_class"] == "xgboost.XGBClassifier"
+
+ def test_unknown_nominated_iteration_raises(self):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+ foreign = self._iteration(self._run(), number=0, holdout=0.9)
+
+ with self.assertRaises(PromotionError):
+ complete_training_run(run, best_iteration_id=foreign.id)
+
+ @parameterized.expand(
+ [
+ # The run stays RUNNING so completion can be retried once storage recovers.
+ # Swallowing the error would pin the model to the legacy recipe path forever.
+ ("storage_unavailable", RuntimeError("storage unavailable"), RuntimeError),
+ # A bundle the storage layer refuses is agent input, so it fails the run instead
+ # of reaching the caller as an internal error it would retry.
+ ("unusable_bundle", InvalidArtifactContent("train.py is not valid UTF-8 text."), PromotionError),
+ # An upload that wrote some of the three files is not "no bundle". Falling back to
+ # the recipe path would serve an implementation the agent never authored.
+ ("partial_bundle", PartialBundle("Bundle is missing required files: predict.py"), PromotionError),
+ ]
+ )
+ def test_unreadable_bundle_aborts_completion(self, _name, raised, expected):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", side_effect=raised):
+ with self.assertRaises(expected):
+ complete_training_run(run)
+
+ run.refresh_from_db()
+ assert run.status == AutoresearchTrainingRun.Status.RUNNING
+ assert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()
+
+ @parameterized.expand(
+ [
+ ("no_feature_sql", {"feature_sql": ""}),
+ # Recording accepts any model_class, because a bundle runs its own code. The
+ # in-process scorer resolves the class through importlib and refuses anything
+ # off the allowlist, so this champion could never score.
+ ("bundle_only_model_class", {"model_class": "my_package.MyClassifier"}),
+ ]
+ )
+ def test_recipe_the_legacy_scorer_cannot_run_is_refused(self, _name, iteration_kwargs):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8, **iteration_kwargs)
+
+ with self.assertRaises(PromotionError):
+ complete_training_run(run)
+
+ run.refresh_from_db()
+ assert run.status == AutoresearchTrainingRun.Status.RUNNING
+ assert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()
+
+ def test_bundle_matching_the_selected_iteration_completes(self):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+
+ # Reindented on the way into the file, which is a formatting difference, not a
+ # different model.
+ reformatted = ANCHORED_FEATURE_SQL.replace(" FROM ", "\n FROM ") + "\n"
+ bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=reformatted)
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
+ result = complete_training_run(run)
+
+ assert result["promoted"] is True
+ assert self._champion().artifact_prefix != ""
+
+ @parameterized.expand(
+ [
+ # The bundle is written once per run, so a losing iteration can overwrite it.
+ ("different_query", ANCHORED_FEATURE_SQL.replace("count()", "count(DISTINCT a.person_id)")),
+ # Whitespace inside a literal is content, not formatting: this one matches a
+ # different event.
+ ("whitespace_inside_a_literal", LITERAL_FEATURE_SQL.replace("plan upgraded", "plan upgraded")),
+ ]
+ )
+ def test_bundle_that_is_not_the_selected_query_is_refused(self, _name, uploaded_sql):
+ # Promoting it would advertise the winner's recipe and score against code that never
+ # produced them.
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.9, feature_sql=LITERAL_FEATURE_SQL)
+
+ bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=uploaded_sql)
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
+ with self.assertRaises(PromotionError):
+ complete_training_run(run)
+
+ assert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()
+
+ def test_a_candidate_exactly_on_the_promotion_margin_is_promoted(self):
+ # The margin is documented as inclusive, and 0.1 + 0.005 is above 0.105 in binary
+ # floating point.
+ first = self._run()
+ self._iteration(first, number=0, holdout=0.1)
+ complete_training_run(first)
+
+ second = self._run()
+ self._iteration(second, number=0, holdout=0.105)
+ result = complete_training_run(second)
+
+ assert result["promoted"] is True
+ assert self._champion().holdout_score == 0.105
+
+ def test_bundle_sql_without_anchors_blocks_promotion(self):
+ # The uploaded features.sql is what fitting runs, so SQL without {anchors} reads the
+ # outcome window whatever the iteration recorded.
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+
+ leaky = ArtifactBundle(
+ train_py="pass",
+ predict_py="pass",
+ features_sql="SELECT person_id AS distinct_id, count() AS c FROM events GROUP BY person_id",
+ )
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=leaky):
+ with self.assertRaises(PromotionError):
+ complete_training_run(run)
+
+ assert not AutoresearchModel.objects.filter(pipeline=self.pipeline).exists()
+
+ def test_completion_runs_without_an_ambient_team_scope(self):
+ # The TaskRun safety net finalizes a run from a worker thread, where no request has
+ # set a scope. Every read in promotion goes through a fail-closed manager.
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+
+ with unscoped():
+ result = complete_training_run(run)
+
+ assert result["promoted"] is True
+
+ def test_challenger_below_the_margin_leaves_the_incumbent_serving(self):
+ first = self._run()
+ self._iteration(first, number=0, holdout=0.8, model_class="xgboost.XGBClassifier")
+ complete_training_run(first)
+
+ second = self._run()
+ self._iteration(second, number=0, holdout=0.801)
+ bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=ANCHORED_FEATURE_SQL)
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
+ with patch("products.autoresearch.backend.training.promotion.fit_champion_model") as fit:
+ with self.captureOnCommitCallbacks(execute=True):
+ result = complete_training_run(second)
+
+ assert result["promoted"] is False
+ assert result["role"] == AutoresearchModel.Role.CHALLENGER
+ assert self._champion().holdout_score == 0.8
+ # Inference reads the champion only, so fitting the rejected bundle would spend a
+ # sandbox run on an artifact nothing loads.
+ fit.assert_not_called()
+ second.refresh_from_db()
+ # The next run reads this summary as the champion it has to beat.
+ assert second.summary["champion_model_class"] == "xgboost.XGBClassifier"
+
+ def test_a_failed_champion_fit_does_not_fail_a_committed_completion(self):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+
+ bundle = ArtifactBundle(train_py="pass", predict_py="pass", features_sql=ANCHORED_FEATURE_SQL)
+ with patch("products.autoresearch.backend.training.artifacts.read_bundle", return_value=bundle):
+ with patch(
+ "products.autoresearch.backend.training.promotion.fit_champion_model",
+ # write_model raises this, and it is not a SandboxInferenceError. The run is
+ # already committed, so it must not reach the caller as a failed completion.
+ side_effect=ObjectStorageError("object storage unavailable"),
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ result = complete_training_run(run)
+
+ assert result["promoted"] is True
+ run.refresh_from_db()
+ assert run.status == AutoresearchTrainingRun.Status.COMPLETED
+
+ def test_model_recipe_hash_identifies_the_stored_recipe(self):
+ run = self._run()
+ iteration = self._iteration(run, number=0, holdout=0.8)
+
+ complete_training_run(run)
+
+ champion = self._champion()
+ expected = hashlib.sha256(
+ json.dumps(champion.model_recipe, sort_keys=True, default=str).encode("utf-8")
+ ).hexdigest()
+ assert champion.recipe_hash == expected
+ # The iteration's hash is an agent-supplied string over different content, so copying
+ # it would leave the model row's provenance pointing at a recipe it does not hold.
+ assert champion.recipe_hash != iteration.recipe_hash
+
+ def test_second_completion_is_a_noop(self):
+ run = self._run()
+ self._iteration(run, number=0, holdout=0.8)
+ first = complete_training_run(run)
+
+ # The stale instance simulates the TaskRun signal racing the complete action:
+ # its out-of-transaction status guard saw RUNNING before the first call committed.
+ # The no-op answer must not depend on object storage, which the retry never needs.
+ with patch(
+ "products.autoresearch.backend.training.artifacts.read_bundle",
+ side_effect=RuntimeError("storage unavailable"),
+ ):
+ second = complete_training_run(run)
+
+ assert first["model_id"] is not None
+ assert second["model_id"] is None
+ assert second["promoted"] is False
+ assert AutoresearchModel.objects.filter(pipeline=self.pipeline).count() == 1