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.

fix(autoresearch): replace a champion that cannot score (#111608)

posthog[bot]9d539315d39e
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index b715312c58d6..758d02ac76bf 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -74,7 +74,7 @@ The prediction event is itself an event on the person, so every live cadence add
2. Resolve the inference population and build anchors at the cutoff, the start of the prediction date in UTC (`../dataset/labeling.py`).
3. If the champion has an `artifact_prefix`, materialize features into a sandbox and run `predict.py`. Otherwise compile the recorded recipe and score in-process.
4. Map `person_id` → `distinct_id` and emit one event each.
-5. Record an `AutoresearchRun` for the execution.
+5. Record an `AutoresearchRun` for the execution. A run the daily sweep starts has `scheduled` set. A failed run records `metrics["failure_kind"]` from `classify_failure()` in `failures.py`: `limit_exceeded`, `query_failed` and `model_load_failed` fail again with the same champion, and `other` (transport, capture, cluster capacity, anything unknown) can pass on a retry. Promotion reads the scheduled runs to decide that a champion cannot score.
Both model shapes are live and must stay that way: bundle-backed champions take the sandbox path, older recipe-only champions take the in-process path.
diff --git a/products/autoresearch/backend/inference/failures.py b/products/autoresearch/backend/inference/failures.py
new file mode 100644
index 000000000000..ad8c84bc55da
--- /dev/null
+++ b/products/autoresearch/backend/inference/failures.py
@@ -0,0 +1,104 @@
+"""Classify a failed scoring run, and tell when the champion's scheduled runs show it cannot score."""
+
+from collections.abc import Iterator
+from datetime import date
+from enum import StrEnum
+
+from posthog.dataclasses import frozen
+from posthog.errors import QueryErrorCategory, classify_query_error
+
+from products.autoresearch.backend.inference.sandbox import ModelLoadError
+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchRun
+
+
+class FailureKind(StrEnum):
+ LIMIT_EXCEEDED = "limit_exceeded"
+ QUERY_FAILED = "query_failed"
+ MODEL_LOAD_FAILED = "model_load_failed"
+ # Transport, capture, cluster capacity, and every error this module does not recognize.
+ OTHER = "other"
+
+
+# These kinds fail again on the next run with the same champion. The other kinds can pass on a retry.
+REPEATABLE_FAILURE_KINDS = frozenset(
+ {FailureKind.LIMIT_EXCEEDED, FailureKind.QUERY_FAILED, FailureKind.MODEL_LOAD_FAILED}
+)
+
+# The number of consecutive scheduled scoring days with a repeatable failure that make a champion unscorable.
+UNSCORABLE_AFTER_FAILED_DAYS = 2
+# The scheduled runs one check reads. An activity retry adds a second run for the same day.
+_RUNS_TO_SCAN = 20
+
+
+def _exception_chain(exc: BaseException) -> Iterator[BaseException]:
+ seen: set[int] = set()
+ current: BaseException | None = exc
+ while current is not None and id(current) not in seen:
+ seen.add(id(current))
+ yield current
+ current = current.__cause__
+
+
+def classify_failure(exc: BaseException) -> FailureKind:
+ """The kind of a scoring failure. The scoring code wraps query errors, so this reads the whole cause chain."""
+ for error in _exception_chain(exc):
+ if isinstance(error, ModelLoadError):
+ return FailureKind.MODEL_LOAD_FAILED
+ if not isinstance(error, Exception):
+ continue
+ category = classify_query_error(error)
+ if category == QueryErrorCategory.QUERY_PERFORMANCE_ERROR:
+ return FailureKind.LIMIT_EXCEEDED
+ if category == QueryErrorCategory.USER_ERROR:
+ return FailureKind.QUERY_FAILED
+ if category != QueryErrorCategory.ERROR:
+ # The wrapper decided first: cluster memory pressure keeps a raw MEMORY_LIMIT_EXCEEDED as its cause.
+ return FailureKind.OTHER
+ return FailureKind.OTHER
+
+
+@frozen
+class UnscorableChampion:
+ failure_kind: str
+ onset: date
+
+
+def _run_date(run: AutoresearchRun) -> date:
+ prediction_date = (run.metrics or {}).get("prediction_date")
+ return date.fromisoformat(prediction_date) if prediction_date else run.created_at.date()
+
+
+def find_unscorable_champion(champion: AutoresearchModel | None) -> UnscorableChampion | None:
+ """
+ Return the failure when the champion's scheduled runs failed with a repeatable kind on the
+ last ``UNSCORABLE_AFTER_FAILED_DAYS`` scoring days, with no success after the first of them.
+
+ Manual runs do not count, because a person can start them many times in one day. Failures of
+ other kinds do not count, and do not break the streak either. The onset is the prediction date
+ of the oldest repeatable failure after the last success.
+ """
+ if champion is None:
+ return None
+ runs = (
+ AutoresearchRun.objects.for_team(champion.team_id)
+ .filter(
+ pipeline_id=champion.pipeline_id,
+ model=champion,
+ run_type=AutoresearchRun.RunType.INFERENCE,
+ scheduled=True,
+ status__in=(AutoresearchRun.Status.COMPLETED, AutoresearchRun.Status.FAILED),
+ )
+ .order_by("-created_at")[:_RUNS_TO_SCAN]
+ )
+ failed_days: dict[date, str] = {}
+ for run in runs:
+ if run.status == AutoresearchRun.Status.COMPLETED:
+ break
+ kind = (run.metrics or {}).get("failure_kind")
+ if kind in REPEATABLE_FAILURE_KINDS:
+ # The newest failure of a day wins, so the kind reported is the latest one.
+ failed_days.setdefault(_run_date(run), kind)
+ if len(failed_days) < UNSCORABLE_AFTER_FAILED_DAYS:
+ return None
+ newest_day = max(failed_days)
+ return UnscorableChampion(failure_kind=failed_days[newest_day], onset=min(failed_days))
diff --git a/products/autoresearch/backend/inference/sandbox.py b/products/autoresearch/backend/inference/sandbox.py
index 5e6298fedee1..6aec485d7e7e 100644
--- a/products/autoresearch/backend/inference/sandbox.py
+++ b/products/autoresearch/backend/inference/sandbox.py
@@ -157,6 +157,10 @@ class SandboxInferenceError(Exception):
"""Raised when materialization or the sandbox run fails. The caller fails the run."""
+class ModelLoadError(SandboxInferenceError):
+ """Raised when a scoring run cannot load the champion's persisted model. A retry fails the same way."""
+
+
@frozen
class MaterializedData:
"""Labeled training matrix for a train run: train + holdout folds. Predict runs return a plain row list."""
@@ -281,9 +285,7 @@ def score_via_sandbox(
model_bytes = read_model(prefix)
if not model_bytes:
- raise SandboxInferenceError(
- f"Champion model.pkl is missing at {prefix}; the completion-time fit has not produced it"
- )
+ raise ModelLoadError(f"Champion model.pkl is missing at {prefix}; the completion-time fit has not produced it")
score_data = _materialize_score_data(
team=team,
@@ -857,12 +859,16 @@ def _run_predict_in_sandbox(
_write_file(sandbox, f"{_WORKDIR}/{_MODEL_PKL}", model_bytes)
_write_file(sandbox, f"{_WORKDIR}/data/score_features.parquet", features_parquet(score_rows, feature_cols))
- _run_script(
- sandbox,
- script="predict.py",
- args=f"data/score_features.parquet {_MODEL_PKL} {_SCORES_PARQUET}",
- timeout_seconds=_PREDICT_TIMEOUT_S,
- )
+ try:
+ _run_script(
+ sandbox,
+ script="predict.py",
+ args=f"data/score_features.parquet {_MODEL_PKL} {_SCORES_PARQUET}",
+ timeout_seconds=_PREDICT_TIMEOUT_S,
+ )
+ except SandboxInferenceError as exc:
+ # predict.py loads model.pkl first, and the fit already ran it once against the same files.
+ raise ModelLoadError(str(exc)) from exc
scores = _read_scores(sandbox, expected_rows=len(score_rows))
return _join_scores(score_rows=score_rows, scores=scores)
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index f78153827ef3..f06a433a66f5 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -61,6 +61,7 @@ from products.autoresearch.backend.dataset.labeling import (
build_training_features_sql,
rolling_selection,
)
+from products.autoresearch.backend.inference.failures import classify_failure
from products.autoresearch.backend.inference.sandbox import (
_FOLD_COL,
_HOLDOUT_FOLD,
@@ -215,12 +216,13 @@ class _EmitResult:
def create_inference_run(
- *, pipeline: AutoresearchPipeline, model: AutoresearchModel, window: ScoringWindow
+ *, pipeline: AutoresearchPipeline, model: AutoresearchModel, window: ScoringWindow, scheduled: bool = False
) -> AutoresearchRun:
return AutoresearchRun.objects.create(
pipeline=pipeline,
model=model,
run_type=AutoresearchRun.RunType.INFERENCE,
+ scheduled=scheduled,
status=AutoresearchRun.Status.RUNNING,
started_at=django_timezone.now(),
# Online validation discovers matured dates from these two keys instead of scanning
@@ -237,6 +239,7 @@ def run_inference_for_pipeline(
user: User | None = None,
run: AutoresearchRun | None = None,
query_context: QueryContext = INTERACTIVE_QUERY,
+ scheduled: bool = False,
) -> AutoresearchRun:
"""
Top-level inference entry point. Creates an AutoresearchRun, scores users,
@@ -255,16 +258,20 @@ def run_inference_for_pipeline(
``query_context`` is the ClickHouse budget of every scoring query. The Temporal
activity passes ``BATCH_QUERY``.
+
+ ``scheduled`` marks a run the daily sweep started. Promotion counts only those runs when
+ it decides that the champion cannot score.
"""
window = ScoringWindow.for_date(prediction_date)
if run is None:
- run = create_inference_run(pipeline=pipeline, model=model, window=window)
+ run = create_inference_run(pipeline=pipeline, model=model, window=window, scheduled=scheduled)
else:
run.model = model
run.status = AutoresearchRun.Status.RUNNING
run.error = ""
+ run.metrics.pop("failure_kind", None)
run.completed_at = None
- run.save(update_fields=["model", "status", "error", "completed_at"])
+ run.save(update_fields=["model", "status", "error", "metrics", "completed_at"])
try:
team = pipeline.team
@@ -310,9 +317,12 @@ def run_inference_for_pipeline(
except Exception as exc:
run.status = AutoresearchRun.Status.FAILED
run.error = str(exc)[:2000]
+ run.metrics["failure_kind"] = classify_failure(exc)
run.completed_at = django_timezone.now()
- run.save(update_fields=["status", "error", "completed_at"])
- logger.exception("autoresearch_inference_failed", pipeline_id=str(pipeline.pk))
+ run.save(update_fields=["status", "error", "metrics", "completed_at"])
+ logger.exception(
+ "autoresearch_inference_failed", pipeline_id=str(pipeline.pk), failure_kind=run.metrics["failure_kind"]
+ )
raise
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index cb987ea60118..bcfb966a1cd7 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -7,9 +7,17 @@ from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
+from clickhouse_driver.errors import ServerException
from parameterized import parameterized
+from posthog.hogql.errors import QueryError
+
from posthog.api.capture import CaptureInternalResult
+from posthog.exceptions import (
+ ClickHouseClusterMemoryLimitExceeded,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME, ROLLING_SCORE_LIMIT
from products.autoresearch.backend.inference import (
@@ -518,12 +526,34 @@ class TestRecipeRouting(TeamScopedTestMixin, BaseTest):
assert dist["max"] > dist["min"]
+def _per_query_memory_limit() -> Exception:
+ exc = ClickHouseQueryMemoryLimitExceeded()
+ exc.__cause__ = ServerException("Query memory limit exceeded", code=241)
+ return exc
+
+
+def _cluster_memory_pressure() -> Exception:
+ exc = ClickHouseClusterMemoryLimitExceeded()
+ exc.__cause__ = ServerException("Memory limit (total) exceeded", code=241)
+ return exc
+
+
class TestQueryFailuresFailTheRun(TeamScopedTestMixin, BaseTest):
+ @parameterized.expand(
+ [
+ ("unknown_error", lambda: Exception("connection reset"), "other"),
+ ("per_query_memory_limit", _per_query_memory_limit, "limit_exceeded"),
+ ("timeout", ClickHouseQueryTimeOut, "limit_exceeded"),
+ # The raw cause carries the same code as a per-query limit, but the next run can pass.
+ ("cluster_memory_pressure", _cluster_memory_pressure, "other"),
+ ("invalid_query", lambda: QueryError("Unknown table"), "query_failed"),
+ ]
+ )
@patch("products.autoresearch.backend.inference.scoring.run_hogql")
- def test_feature_query_failure_fails_the_run(self, mock_run_hogql: MagicMock):
+ def test_feature_query_failure_fails_the_run(self, _name, make_error, failure_kind, mock_run_hogql: MagicMock):
# Returning no rows on a transient failure completed the run as an empty population
# and advanced the cadence, so the day's scoring was skipped with nothing retried.
- mock_run_hogql.side_effect = Exception("clickhouse timeout")
+ mock_run_hogql.side_effect = make_error()
pipeline = AutoresearchPipeline.objects.create(
team=self.team, created_by=self.user, name="Failing", target_event="$pageview", horizon_days=7
)
@@ -536,6 +566,7 @@ class TestQueryFailuresFailTheRun(TeamScopedTestMixin, BaseTest):
run = AutoresearchRun.objects.filter(pipeline=pipeline).latest("created_at")
assert run.status == AutoresearchRun.Status.FAILED
+ assert run.metrics["failure_kind"] == failure_kind
pipeline.refresh_from_db()
assert pipeline.last_scored_at is None
diff --git a/products/autoresearch/backend/migrations/0003_scheduled_inference_run.py b/products/autoresearch/backend/migrations/0003_scheduled_inference_run.py
new file mode 100644
index 000000000000..02d47133e250
--- /dev/null
+++ b/products/autoresearch/backend/migrations/0003_scheduled_inference_run.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.17 on 2026-10-04 18:01
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("autoresearch", "0002_negative_sample_rate"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="autoresearchrun",
+ name="scheduled",
+ field=models.BooleanField(
+ db_default=False,
+ default=False,
+ help_text="True when the daily sweep started this run. False for a manual run or a command.",
+ ),
+ ),
+ ]
diff --git a/products/autoresearch/backend/migrations/max_migration.txt b/products/autoresearch/backend/migrations/max_migration.txt
index 6b29d5fe0b3d..6c7e83b38dba 100644
--- a/products/autoresearch/backend/migrations/max_migration.txt
+++ b/products/autoresearch/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0002_negative_sample_rate
+0003_scheduled_inference_run
diff --git a/products/autoresearch/backend/models.py b/products/autoresearch/backend/models.py
index daf3713e90fb..eafe67cc32e3 100644
--- a/products/autoresearch/backend/models.py
+++ b/products/autoresearch/backend/models.py
@@ -470,6 +470,11 @@ class AutoresearchRun(PipelineScopedModel):
)
run_type = models.CharField(max_length=20, choices=RunType.choices)
status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
+ scheduled = models.BooleanField(
+ default=False,
+ db_default=False,
+ help_text="True when the daily sweep started this run. False for a manual run or a command.",
+ )
rows_scored = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(0)])
metrics = models.JSONField(default=dict)
diff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.py
index 582a8f8f57a8..edea5a172e84 100644
--- a/products/autoresearch/backend/temporal/test_workflows.py
+++ b/products/autoresearch/backend/temporal/test_workflows.py
@@ -242,6 +242,7 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):
RunInferenceInput(pipeline_id=str(pipeline.id), team_id=self.team.id, prediction_date="2026-09-11"),
)
assert mock_inference.call_args.kwargs["query_context"] == BATCH_QUERY
+ assert mock_inference.call_args.kwargs["scheduled"] is True
else:
env.run(activity_run_validation, RunValidationInput(pipeline_id=str(pipeline.id), team_id=self.team.id))
assert mock_validation.call_args.kwargs["query_context"] == BATCH_QUERY
diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.py
index 06fcbbe4077d..12c5d35cd6a8 100644
--- a/products/autoresearch/backend/temporal/workflows.py
+++ b/products/autoresearch/backend/temporal/workflows.py
@@ -138,6 +138,7 @@ def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:
user=user,
run=manual_run,
query_context=BATCH_QUERY,
+ scheduled=manual_run is None,
)
return RunInferenceResult(
run_id=str(run.pk),
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index 05d8ea217906..437a64f2ca63 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -39,7 +39,8 @@ The other half is `../inference/`, which consumes what this package produces and
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 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 champion that is already unscorable is not repaired here, and a recipe-only champion is not checked.
+ 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.
- `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`.
diff --git a/products/autoresearch/backend/training/promotion.py b/products/autoresearch/backend/training/promotion.py
index 8ccd807bfafc..0b366531ac60 100644
--- a/products/autoresearch/backend/training/promotion.py
+++ b/products/autoresearch/backend/training/promotion.py
@@ -26,6 +26,7 @@ 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.inference.failures import find_unscorable_champion
from products.autoresearch.backend.inference.sandbox import (
SandboxInferenceError,
check_scorability,
@@ -606,11 +607,24 @@ def _finalize_under_lock(
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)
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 beats_champion:
+ promotion_reason = "beat_champion"
+
promoted = False
role: str
- if is_cold_start or replaces_stub or beats_champion:
+ if promotion_reason:
if current is not None:
AutoresearchModel.objects.filter(pk=current.pk).update(
role=AutoresearchModel.Role.ARCHIVED, archived_at=now
@@ -632,6 +646,7 @@ def _finalize_under_lock(
"holdout_auc": candidate_score,
"source": "agent_recorded",
"artifact_bundle": bool(artifact_prefix),
+ **({"promotion_reason": promotion_reason} if promotion_reason else {}),
},
source_training_run=training_run,
agent_description=best.agent_description,
diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.py
index a3678c18b4c2..715a9d270746 100644
--- a/products/autoresearch/backend/training/runner.py
+++ b/products/autoresearch/backend/training/runner.py
@@ -38,8 +38,14 @@ from posthog.models.user import User
from products.actions.backend.models.action import Action
from products.autoresearch.backend.access import has_report_notebook_access
from products.autoresearch.backend.dataset.labeling import TrainingSample, build_target_condition
+from products.autoresearch.backend.inference.failures import UnscorableChampion, find_unscorable_champion
from products.autoresearch.backend.inference.sandbox import _resolve_acting_user, measure_training_sample
-from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchSuggestion, AutoresearchTrainingRun
+from products.autoresearch.backend.models import (
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchSuggestion,
+ AutoresearchTrainingRun,
+)
from products.tasks.backend.facade import (
api as tasks_facade,
cancellation as tasks_cancellation,
@@ -204,6 +210,7 @@ def build_agent_description(
pending_suggestions: list[AutoresearchSuggestion] | None = None,
training_sample: TrainingSample | None = None,
report_notebook: bool = False,
+ unscorable_champion: UnscorableChampion | None = None,
) -> str:
"""Build the Claude Code agent prompt for the autoresearch training loop."""
pop_clause = ""
@@ -227,6 +234,7 @@ def build_agent_description(
)
sample_clause = _describe_training_sample(training_sample)
+ unscorable_clause = _describe_unscorable_champion(unscorable_champion)
today_iso = date.today().isoformat()
min_iters = min(3, iteration_budget)
@@ -302,7 +310,7 @@ def build_agent_description(
in `dead_ends`. In each iteration's `agent_description`, cite which prior learning you are
building on or deliberately avoiding.
- If no champion exists you are establishing the baseline — aim for AUC > 0.6.
+ If no champion exists you are establishing the baseline — aim for AUC > 0.6.{unscorable_clause}
## How labeling works (read this carefully — it shapes everything below)
@@ -704,6 +712,29 @@ def _cancel_dispatched_task_run(task_run_id: UUID, task_id: UUID, *, team_id: in
# ── Main entry point ──────────────────────────────────────────────────────────
+def _describe_unscorable_champion(unscorable: UnscorableChampion | None) -> str:
+ if unscorable is None:
+ return ""
+ # Indented to the brief's level, because the brief is dedented after this text goes in.
+ return textwrap.indent(
+ textwrap.dedent(f"""
+
+ **The current champion cannot score.** Its scheduled scoring runs fail with
+ `{unscorable.failure_kind}` since {unscorable.onset.isoformat()}. Its `holdout_score` is not
+ the bar for this run: any candidate whose `features.sql` scores today's inference population
+ replaces it. Do not reuse its `features.sql` as it is. Find what makes it fail first.
+ `limit_exceeded` means a query hit a memory, time, rows or bytes limit. `query_failed` means
+ the query is not valid for today's data. `model_load_failed` means `predict.py` could not
+ load or run the fitted model."""),
+ " " * 8,
+ )
+
+
+def _unscorable_champion_for_brief(pipeline: AutoresearchPipeline) -> UnscorableChampion | None:
+ champion = AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).first()
+ return find_unscorable_champion(champion)
+
+
def _training_sample_for_brief(pipeline: AutoresearchPipeline) -> TrainingSample | None:
"""
The training sample, for the brief only. Materialization measures it again, so a count that
@@ -788,6 +819,7 @@ def run_training(
pending_suggestions=pending_suggestions or None,
training_sample=_training_sample_for_brief(pipeline),
report_notebook=report_notebook,
+ unscorable_champion=_unscorable_champion_for_brief(pipeline),
)
title = f"[autoresearch] {pipeline.name}: learn to predict '{pipeline.target_event}'"
diff --git a/products/autoresearch/backend/training/test_promotion.py b/products/autoresearch/backend/training/test_promotion.py
index 44dccd192d20..65536150d932 100644
--- a/products/autoresearch/backend/training/test_promotion.py
+++ b/products/autoresearch/backend/training/test_promotion.py
@@ -19,6 +19,7 @@ from products.autoresearch.backend.models import (
AutoresearchIteration,
AutoresearchModel,
AutoresearchPipeline,
+ AutoresearchRun,
AutoresearchTrainingRun,
)
from products.autoresearch.backend.query import QueryCost
@@ -316,6 +317,47 @@ class TestCompleteTrainingRun(TeamScopedTestMixin, BaseTest):
assert result["promoted"] is True
assert self._champion().holdout_score == 0.6
+ @parameterized.expand(
+ [
+ ("two_repeatable_failures", [("2026-09-02", "limit_exceeded"), ("2026-09-03", "query_failed")], True),
+ ("a_single_failure", [("2026-09-03", "limit_exceeded")], False),
+ (
+ "a_success_in_between",
+ [("2026-09-01", "limit_exceeded"), ("2026-09-02", None), ("2026-09-03", "limit_exceeded")],
+ False,
+ ),
+ ("transport_failures", [("2026-09-02", "other"), ("2026-09-03", "other")], False),
+ # An activity retry adds a second failed run for the same prediction date.
+ ("one_day_retried", [("2026-09-03", "limit_exceeded"), ("2026-09-03", "limit_exceeded")], False),
+ ]
+ )
+ def test_a_champion_that_cannot_score_is_replaced_below_the_margin(self, _name, scheduled_runs, replaced):
+ first = self._run()
+ self._iteration(first, number=0, holdout=0.8)
+ complete_training_run(first)
+ champion = self._champion()
+ for prediction_date, failure_kind in scheduled_runs:
+ AutoresearchRun.objects.create(
+ pipeline=self.pipeline,
+ model=champion,
+ run_type=AutoresearchRun.RunType.INFERENCE,
+ scheduled=True,
+ status=AutoresearchRun.Status.COMPLETED if failure_kind is None else AutoresearchRun.Status.FAILED,
+ metrics={
+ "prediction_date": prediction_date,
+ **({"failure_kind": failure_kind} if failure_kind else {}),
+ },
+ )
+
+ second = self._run()
+ self._iteration(second, number=0, holdout=0.7)
+ result = complete_training_run(second)
+
+ assert result["promoted"] is replaced
+ assert self._champion().holdout_score == (0.7 if replaced else 0.8)
+ if replaced:
+ assert self._champion().metrics["promotion_reason"] == "replaced_unscorable"
+
@parameterized.expand(
[
# SQL without {anchors} reads the outcome window whatever the iteration recorded.
diff --git a/products/autoresearch/backend/training/test_training.py b/products/autoresearch/backend/training/test_training.py
index 9e19ab886052..11c619e2db69 100644
--- a/products/autoresearch/backend/training/test_training.py
+++ b/products/autoresearch/backend/training/test_training.py
@@ -1,5 +1,6 @@
import re
import uuid
+from datetime import date
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -11,6 +12,7 @@ from posthog.models.user import User
from products.actions.backend.models.action import Action
from products.autoresearch.backend.dataset.labeling import TrainingSample
+from products.autoresearch.backend.inference.failures import UnscorableChampion
from products.autoresearch.backend.inference.sandbox import SandboxInferenceError
from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchSuggestion, AutoresearchTrainingRun
from products.autoresearch.backend.testing import TeamScopedTestMixin
@@ -36,12 +38,27 @@ class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):
iteration_budget_remaining=10,
)
- @parameterized.expand([("without_notebook", False), ("with_notebook", True)])
- def test_prompt_renders_without_unresolved_placeholders(self, _name: str, report_notebook: bool) -> None:
+ @parameterized.expand(
+ [
+ ("without_notebook", False, None),
+ ("with_notebook", True, None),
+ ("unscorable_champion", False, UnscorableChampion(failure_kind="limit_exceeded", onset=date(2026, 9, 2))),
+ ]
+ )
+ def test_prompt_renders_without_unresolved_placeholders(
+ self, _name: str, report_notebook: bool, unscorable: UnscorableChampion | None
+ ) -> None:
pipeline = self._make_pipeline()
prompt = build_agent_description(
- pipeline=pipeline, iteration_budget=5, training_run_id="run-123", report_notebook=report_notebook
+ pipeline=pipeline,
+ iteration_budget=5,
+ training_run_id="run-123",
+ report_notebook=report_notebook,
+ unscorable_champion=unscorable,
)
+ if unscorable is not None:
+ assert "**The current champion cannot score.**" in prompt
+ assert "`limit_exceeded` since 2026-09-02" in prompt
# `{anchors}` and `{lookback_days}` are intentional — they are documented
# placeholders the agent is taught to use inside its own SQL, and `{init}`
# is the literal mermaid `%%{init}%%` directive the report section forbids.