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.

33.1 KB
Raw Blame
"""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 posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME

from products.autoresearch.backend.dataset.labeling import ANCHOR_ALIGNMENT
from products.autoresearch.backend.inference.failures import find_unscorable_champion
from products.autoresearch.backend.inference.sandbox import (
    SandboxInferenceError,
    check_scorability,
    fit_champion_model,
    validate_runnable_feature_sql,
)
from products.autoresearch.backend.inference.scoring import check_recipe_estimator
from products.autoresearch.backend.models import (
    AutoresearchIteration,
    AutoresearchModel,
    AutoresearchPipeline,
    AutoresearchTrainingRun,
)
from products.autoresearch.backend.query import QueryCost
from products.autoresearch.backend.training import artifacts
from products.autoresearch.backend.training.recipe_validation import RecipeValidationError, validate_model_class
from products.autoresearch.backend.training.shadow_set import (
    ARCHIVED_REASON_METRIC_KEY,
    ARCHIVED_UNSCORABLE,
    FITTED_METRIC_KEY,
    shadow_set,
)
from products.notebooks.backend.facade import api as notebooks_facade

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

# Scoring runs the same queries under the batch query limit. A champion that needs half of that
# limit today has little room left before population growth makes every cadence fail.
SCORABILITY_TIME_BUDGET_S = HOGQL_INCREASED_MAX_EXECUTION_TIME / 2


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") or [],
        "model_class": spec.get("model_class", "sklearn.linear_model.LogisticRegression"),
        # Recording accepts an absent or null model_params; both mean the constructor defaults.
        "model_params": spec.get("model_params") or {},
        "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,
    report_notebook_short_id: 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 "",
        "report_notebook_short_id": report_notebook_short_id,
    }


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:
        # Scoring runs the feature SQL as the top-level query and refuses a trailing LIMIT,
        # OFFSET or SETTINGS, so a champion that would fail every cadence is refused here.
        validate_runnable_feature_sql(str(recipe["feature_sql"]), source="feature_sql")
    except SandboxInferenceError as exc:
        raise PromotionError(f"Cannot persist a model on the legacy scoring path: {exc}") from exc
    if recipe.get("feature_transforms"):
        # The in-process scorer fits on the raw feature_sql columns and never applies the
        # transforms, so the served model would not be the one the holdout score describes.
        raise PromotionError(
            "Cannot persist a model on the legacy scoring path: it does not apply feature_transforms, "
            "so a recipe that needs them must ship as an uploaded bundle."
        )
    if not isinstance(recipe.get("model_params"), dict):
        raise PromotionError(
            "Cannot persist a model on the legacy scoring path: model_params must be a JSON object, "
            "because the in-process scorer expands it into the estimator's constructor."
        )
    try:
        validate_model_class(str(recipe["model_class"]))
        check_recipe_estimator(recipe)
    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,
    # with the rule inference adds, so a champion is never committed with SQL its fit refuses.
    try:
        validate_runnable_feature_sql(bundle.features_sql, source="features.sql")
    except SandboxInferenceError 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 = "",
    report_notebook_short_id: str = "",
    reader_summary: str | None = None,
    headline: str | None = None,
    next_steps: list[str] | None = None,
) -> 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)
        return _finalize_under_lock(
            current,
            best_iteration_id=best_iteration_id,
            model_explanation=model_explanation,
            recommended_next=recommended_next,
            distillation=distillation,
            report_notebook_short_id=_verified_report_notebook(current, report_notebook_short_id),
            reader_summary=reader_summary,
            headline=headline,
            next_steps=next_steps,
        )


def _verified_report_notebook(training_run: AutoresearchTrainingRun, short_id: str) -> str:
    """
    The agent's notebook short id if that notebook exists in the run's team, else "".
    The model result matters more than the report, so a bad id or a failed check never fails completion.
    """
    short_id = (short_id or "").strip()
    if not short_id:
        return ""
    try:
        if notebooks_facade.notebook_exists(training_run.team_id, short_id, include_deleted=False):
            return short_id
    except Exception:
        logger.exception("autoresearch_report_notebook_check_failed", training_run_id=str(training_run.pk))
        return ""
    logger.warning("autoresearch_report_notebook_not_found", training_run_id=str(training_run.pk))
    return ""


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_model_fit(
    *,
    pipeline: AutoresearchPipeline,
    bundle: artifacts.ArtifactBundle,
    prefix: str,
    training_run: AutoresearchTrainingRun,
    model_id: str,
    promoted: bool,
    previous_champion_id: str | None,
    previous_status: str | None,
) -> None:
    """The train run produces the serving artifact: fit the model 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 failed challenger fit keeps the
    challenger out of the shadow set. The fit labels at the run's anchor instant, so it sees
    the anchor set the agent scored.

    After a champion fit, the bundle's features.sql runs against today's inference anchors under
    the scoring limits. A failed fit, a failed check, or a check over ``SCORABILITY_TIME_BUDGET_S``
    rolls the promotion back, because a champion that cannot score fails every cadence and no
    other path replaces it."""
    training_run_id = str(training_run.id)
    anchor_ts = training_run.anchor_ts

    def roll_back(reason: str, cost: QueryCost | None = None) -> None:
        _roll_back_promotion(
            pipeline=pipeline,
            training_run_id=training_run_id,
            model_id=model_id,
            previous_champion_id=previous_champion_id,
            previous_status=previous_status,
            reason=reason,
            cost=cost,
        )

    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:
            try:
                fit_champion_model(
                    team=pipeline.team,
                    pipeline=pipeline,
                    prefix=prefix,
                    bundle=bundle,
                    anchor_ts=anchor_ts,
                    model_id=model_id,
                )
            except Exception as exc:
                logger.exception("autoresearch_model_fit_failed", training_run_id=training_run_id, prefix=prefix)
                if promoted:
                    roll_back(f"The champion fit failed: {exc}")
                return
            if not promoted:
                _mark_fitted(team_id=pipeline.team_id, model_id=model_id)
                return
            try:
                cost = check_scorability(team=pipeline.team, pipeline=pipeline, feature_sql=bundle.features_sql)
            except Exception as exc:
                logger.exception("autoresearch_champion_unscorable", training_run_id=training_run_id, prefix=prefix)
                roll_back(f"features.sql failed against today's inference anchors: {exc}")
                return
            if cost.elapsed_s > SCORABILITY_TIME_BUDGET_S:
                roll_back(
                    f"features.sql took {cost.elapsed_s:.0f}s against today's inference anchors, "
                    f"above the {SCORABILITY_TIME_BUDGET_S:.0f}s budget for a scoring run",
                    cost,
                )
                return
            _mark_fitted(team_id=pipeline.team_id, model_id=model_id, cost=cost)
        except Exception:
            logger.exception("autoresearch_model_fit_failed", training_run_id=training_run_id, prefix=prefix)

    transaction.on_commit(_fit_after_commit)


def _scorability_metrics(cost: QueryCost) -> dict[str, Any]:
    return {
        "scorability_elapsed_s": cost.elapsed_s,
        "scorability_rows_read": cost.rows_read,
    }


def _mark_fitted(*, team_id: int, model_id: str, cost: QueryCost | None = None) -> None:
    """A rolled-back champion is never marked, so it stays out of the shadow set."""
    with team_scope(team_id), transaction.atomic():
        model = AutoresearchModel.objects.for_team(team_id).select_for_update().filter(pk=model_id).first()
        if model is None:
            return
        model.metrics = {
            **(model.metrics or {}),
            **(_scorability_metrics(cost) if cost else {}),
            FITTED_METRIC_KEY: True,
        }
        model.save(update_fields=["metrics", "updated_at"])
    if cost is not None:
        logger.info("autoresearch_champion_scorable", model_id=model_id, **_scorability_metrics(cost))


def _roll_back_promotion(
    *,
    pipeline: AutoresearchPipeline,
    training_run_id: str,
    model_id: str,
    previous_champion_id: str | None,
    previous_status: str | None,
    reason: str,
    cost: QueryCost | None,
) -> None:
    """
    Demote the candidate to a challenger and bring back the champion it replaced.

    The pipeline row lock serializes this with a promotion of a later run. A candidate that is
    no longer the champion was already replaced, so nothing changes. A scoring run that started
    with the candidate fails in ``_require_still_champion()`` before it emits.
    """
    team_id = pipeline.team_id
    with team_scope(team_id), transaction.atomic():
        locked = AutoresearchPipeline.objects.for_team(team_id).select_for_update(no_key=True).get(pk=pipeline.pk)
        candidate = (
            AutoresearchModel.objects.for_team(team_id)
            .select_for_update()
            .filter(pk=model_id, pipeline=locked, role=AutoresearchModel.Role.CHAMPION)
            .first()
        )
        if candidate is None:
            logger.warning("autoresearch_champion_rollback_superseded", pipeline_id=str(pipeline.pk), model_id=model_id)
            return
        candidate.role = AutoresearchModel.Role.CHALLENGER
        candidate.promoted_at = None
        candidate.metrics = {
            **(candidate.metrics or {}),
            **(_scorability_metrics(cost) if cost else {}),
            "not_promoted_reason": reason,
        }
        candidate.save(update_fields=["role", "promoted_at", "metrics"])

        restored = None
        if previous_champion_id is not None:
            restored = (
                AutoresearchModel.objects.for_team(team_id)
                .select_for_update()
                .filter(pk=previous_champion_id, pipeline=locked, role=AutoresearchModel.Role.ARCHIVED)
                .first()
            )
        if restored is not None:
            restored.role = AutoresearchModel.Role.CHAMPION
            restored.archived_at = None
            restored.metrics = {k: v for k, v in (restored.metrics or {}).items() if k != ARCHIVED_REASON_METRIC_KEY}
            restored.save(update_fields=["role", "archived_at", "metrics"])
        elif previous_status is not None and locked.status == AutoresearchPipeline.Status.RUNNING:
            # The candidate was the first champion and made the pipeline live. With no champion
            # the daily sweep fails every cadence, so the pipeline goes back to waiting for one.
            locked.status = previous_status
            locked.save(update_fields=["status", "updated_at"])

        training_run = (
            AutoresearchTrainingRun.objects.for_team(team_id).select_for_update().filter(pk=training_run_id).first()
        )
        if training_run is not None and training_run.summary:
            # The next run reads this summary as the champion it has to beat.
            training_run.summary = {
                **training_run.summary,
                "champion_promoted": False,
                "champion_model_class": str((restored.model_recipe or {}).get("model_class", "")) if restored else "",
            }
            training_run.save(update_fields=["summary"])
    logger.warning(
        "autoresearch_champion_rolled_back",
        pipeline_id=str(pipeline.pk),
        model_id=model_id,
        restored_model_id=str(restored.pk) if restored else None,
        reason=reason,
    )


@transaction.atomic
def _finalize_under_lock(
    training_run: AutoresearchTrainingRun,
    *,
    best_iteration_id: UUID | None,
    model_explanation: dict[str, Any] | None,
    recommended_next: str,
    distillation: str,
    report_notebook_short_id: str,
    reader_summary: str | None,
    headline: str | None,
    next_steps: list[str] | None,
) -> 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)
    # The artifact endpoints write the bundle under this same row lock, so a bundle read here
    # is the bundle the champion will point at. Read before the lock, an upload landing in
    # between would be fitted without ever being validated. The cost is three object-storage
    # reads of agent-authored text while the row is locked.
    bundle = _read_uploaded_bundle(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 best_iteration_id is not None and best.id != best_iteration_id:
        # The explanation describes the nominated recipe, not the one the ranking selected.
        model_explanation = {}

    # 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
    # The pipeline lock serializes this promotion with the rollback of an unscorable champion.
    AutoresearchPipeline.objects.select_for_update(no_key=True).get(pk=pipeline.pk)
    current = AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).first()
    is_cold_start = current is None
    # A stub champion's score is a fixed placeholder, not a measurement, so any trained candidate replaces it.
    replaces_stub = current is not None and bool((current.metrics or {}).get("stub"))
    # A champion that cannot score serves nothing, so its holdout score is no bar either. The
    # fit and the scorability check still run, and roll the candidate back if it cannot score.
    unscorable = find_unscorable_champion(current)
    # A champion trained on T0s at any second has a holdout score from part-day features that
    # scoring never sees, so the score is inflated and no bar for a model trained on UTC days.
    anchor_changed = current is not None and (current.metrics or {}).get("anchor_alignment") != ANCHOR_ALIGNMENT
    beats_champion = current is not None and _beats_incumbent(candidate_score, current.holdout_score or 0.0)

    promotion_reason = ""
    if is_cold_start:
        promotion_reason = "cold_start"
    elif replaces_stub:
        promotion_reason = "replaced_stub"
    elif unscorable is not None:
        promotion_reason = "replaced_unscorable"
    elif anchor_changed:
        promotion_reason = "replaced_anchor_change"
    elif beats_champion:
        promotion_reason = "beat_champion"

    promoted = False
    role: str
    if promotion_reason:
        if current is not None:
            archived_metrics = {k: v for k, v in (current.metrics or {}).items() if k != ARCHIVED_REASON_METRIC_KEY}
            if promotion_reason == "replaced_unscorable":
                archived_metrics[ARCHIVED_REASON_METRIC_KEY] = ARCHIVED_UNSCORABLE
            AutoresearchModel.objects.filter(pk=current.pk).update(
                role=AutoresearchModel.Role.ARCHIVED, archived_at=now, metrics=archived_metrics
            )
        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),
            "anchor_alignment": ANCHOR_ALIGNMENT,
            **({"promotion_reason": promotion_reason} if promotion_reason else {}),
        },
        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,
        report_notebook_short_id=report_notebook_short_id,
    )
    training_run.reader_summary = reader_summary
    training_run.headline = headline
    training_run.next_steps = next_steps
    training_run.save(
        update_fields=[
            "status",
            "iteration_count",
            "best_holdout_score",
            "summary",
            "reader_summary",
            "headline",
            "next_steps",
            "completed_at",
        ]
    )

    status_before = pipeline.status
    if promoted:
        _activate_pipeline(pipeline)
    # A challenger is fitted only when it enters the shadow set, because nothing else loads
    # its model.pkl.
    if bundle is not None and (
        promoted or any(member.pk == model.pk for member in shadow_set(pipeline, now=now, pending_fit=model.pk))
    ):
        _schedule_model_fit(
            pipeline=pipeline,
            bundle=bundle,
            prefix=artifact_prefix,
            training_run=training_run,
            model_id=str(model.pk),
            promoted=promoted,
            previous_champion_id=str(current.pk) if promoted and current is not None else None,
            previous_status=status_before if status_before != pipeline.status else None,
        )

    return {
        "promoted": promoted,
        "model_id": str(model.pk),
        "role": role,
        "iteration_count": iteration_count,
        "best_holdout_score": best_score,
    }