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): rescue an unscorable champion after the budget runs out (#114570)

posthog[bot]9d46f6b43abd
diff --git a/products/autoresearch/backend/temporal/AGENTS.md b/products/autoresearch/backend/temporal/AGENTS.md
index b1cbe867f9f4..2223235d5db6 100644
--- a/products/autoresearch/backend/temporal/AGENTS.md
+++ b/products/autoresearch/backend/temporal/AGENTS.md
@@ -39,6 +39,7 @@ Validation runs on every daily sweep, because a matured date should not wait for
Scoring and training kickoff run on a cadence day only, compared by calendar day, and kickoff starts after scoring ends.
Discovery pauses a pipeline whose creator has lost access to the team, and skips one outside the flag rollout.
Kickoff applies the Tasks entitlement and usage gates `/train` applies, launches at most one run per UTC day, and holds the pipeline row lock through the launch, as `start_training` does.
+A pipeline with no iteration budget left gets no run, except when `find_unscorable_champion()` finds that its champion cannot score. Then kickoff launches a rescue run of `RESCUE_ITERATION_BUDGET` iterations that does not come out of the budget, at most once in each window of `UNSCORABLE_AFTER_FAILED_DAYS` UTC days, and reports `rescue_unscorable`.
Note that training is launched by an _activity_, not a child workflow, because the actual agent run happens in a Tasks sandbox with its own lifecycle. Autoresearch does not own that workflow; it fires it and the `TaskRun` `post_save` signal (`../training/ingestion.py`) picks the result back up.
diff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.py
index edea5a172e84..964ef80bee2b 100644
--- a/products/autoresearch/backend/temporal/test_workflows.py
+++ b/products/autoresearch/backend/temporal/test_workflows.py
@@ -23,6 +23,7 @@ from products.autoresearch.backend.models import (
from products.autoresearch.backend.query import BATCH_QUERY
from products.autoresearch.backend.temporal.workflows import (
_VALIDATION_ATTEMPT_TIMEOUT,
+ RESCUE_ITERATION_BUDGET,
InferenceWorkflowResult,
KickoffTrainingInput,
KickoffTrainingResult,
@@ -350,6 +351,56 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):
pipeline.refresh_from_db()
assert pipeline.iteration_budget_remaining == 20
+ @parameterized.expand(
+ [
+ ("unscorable_champion_gets_a_rescue", 0, True, None, "rescue_unscorable"),
+ ("scorable_champion_stays_exhausted", 0, False, None, "budget_exhausted"),
+ ("rescue_ran_yesterday", 0, True, datetime(2026, 9, 10, 2, tzinfo=UTC), "rescue_throttled"),
+ ("rescue_ran_two_days_ago", 0, True, datetime(2026, 9, 9, 2, tzinfo=UTC), "rescue_unscorable"),
+ ]
+ )
+ @patch("products.autoresearch.backend.temporal.workflows.run_training")
+ def test_exhausted_budget_rescues_only_an_unscorable_champion(
+ self,
+ _name: str,
+ remaining: int,
+ unscorable: bool,
+ last_run_at: Optional[datetime],
+ expected_reason: str,
+ mock_run_training: MagicMock,
+ ) -> None:
+ pipeline = self._create_pipeline(iteration_budget_remaining=remaining)
+ champion = AutoresearchModel.objects.create(
+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe={"stub": True}, recipe_hash="abc"
+ )
+ for prediction_date in ("2026-09-09", "2026-09-10"):
+ AutoresearchRun.objects.create(
+ pipeline=pipeline,
+ model=champion,
+ run_type=AutoresearchRun.RunType.INFERENCE,
+ scheduled=True,
+ status=AutoresearchRun.Status.FAILED if unscorable else AutoresearchRun.Status.COMPLETED,
+ metrics={"prediction_date": prediction_date, "failure_kind": "limit_exceeded"} if unscorable else {},
+ )
+ if last_run_at is not None:
+ with time_machine.travel(last_run_at, tick=False):
+ AutoresearchTrainingRun.objects.create(
+ pipeline=pipeline, status=AutoresearchTrainingRun.Status.FAILED, iteration_budget=3
+ )
+
+ with time_machine.travel(datetime(2026, 9, 11, 2, tzinfo=UTC), tick=False):
+ result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))
+
+ assert result.reason == expected_reason
+ if expected_reason == "rescue_unscorable":
+ assert result.kicked_off
+ assert mock_run_training.call_args.kwargs["iteration_budget"] == RESCUE_ITERATION_BUDGET
+ assert mock_run_training.call_args.kwargs["rescue"] is True
+ else:
+ mock_run_training.assert_not_called()
+ pipeline.refresh_from_db()
+ assert pipeline.iteration_budget_remaining == remaining
+
@parameterized.expand([("transient_failure_raises", RuntimeError("boom")), ("refused_launch", ValueError("left"))])
@patch("products.autoresearch.backend.temporal.workflows.run_training")
def test_failed_launch_spends_no_budget(self, _name: str, error: Exception, mock_run_training: MagicMock) -> None:
diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.py
index 1c7d1775ca96..a56ef2537d55 100644
--- a/products/autoresearch/backend/temporal/workflows.py
+++ b/products/autoresearch/backend/temporal/workflows.py
@@ -32,6 +32,7 @@ with workflow.unsafe.imports_passed_through():
from products.autoresearch.backend.access import has_autoresearch_access
from products.autoresearch.backend.dataset.labeling import build_target_condition
from products.autoresearch.backend.evaluation.online_validation import run_online_validation_for_pipeline
+ from products.autoresearch.backend.inference.failures import UNSCORABLE_AFTER_FAILED_DAYS, find_unscorable_champion
from products.autoresearch.backend.inference.sandbox import SandboxInferenceError, _resolve_acting_user
from products.autoresearch.backend.inference.scoring import run_inference_for_pipeline
from products.autoresearch.backend.models import (
@@ -461,7 +462,7 @@ def evaluate_pipeline_outcome(
class KickoffTrainingResult:
kicked_off: bool
# "started" | "budget_exhausted" | "already_running" | "already_ran_today" | "not_eligible"
- # | "tasks_gated" | "no_creator" | "not_launchable"
+ # | "tasks_gated" | "no_creator" | "not_launchable" | "rescue_unscorable" | "rescue_throttled"
reason: str
error: Optional[str] = None
# Why an expected skip happened, without counting it as a failure.
@@ -472,6 +473,8 @@ class KickoffTrainingResult:
_COORDINATOR_RETRY = RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=5))
_KICKOFF_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=10))
+# The iterations of a rescue run. It does not come out of the pipeline budget.
+RESCUE_ITERATION_BUDGET = 3
@activity.defn(name="autoresearch-coordinator.load_active_pipelines")
@@ -553,9 +556,14 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResul
# The column is nullable (an admin can clear it); read that as exhausted rather
# than refunding the budget mid-flight.
- remaining = pipeline.iteration_budget_remaining
- if remaining is None or remaining <= 0:
- return KickoffTrainingResult(kicked_off=False, reason="budget_exhausted")
+ remaining = pipeline.iteration_budget_remaining or 0
+ # A champion that cannot score stops all predictions, and only a training run can replace
+ # it. So an exhausted pipeline still gets a small rescue run that spends no budget.
+ rescue = remaining <= 0
+ if rescue:
+ champion = AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION).first()
+ if find_unscorable_champion(champion) is None:
+ return KickoffTrainingResult(kicked_off=False, reason="budget_exhausted")
if AutoresearchTrainingRun.objects.filter(
pipeline=pipeline,
@@ -569,6 +577,15 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResul
if AutoresearchTrainingRun.objects.filter(pipeline=pipeline, created_at__gte=today).exists():
return KickoffTrainingResult(kicked_off=False, reason="already_ran_today")
+ # At most one rescue run in each window of UNSCORABLE_AFTER_FAILED_DAYS UTC days, so a pipeline
+ # that no candidate can fix costs a bounded amount.
+ rescue_window_start = today - timedelta(days=UNSCORABLE_AFTER_FAILED_DAYS - 1)
+ if (
+ rescue
+ and AutoresearchTrainingRun.objects.filter(pipeline=pipeline, created_at__gte=rescue_window_start).exists()
+ ):
+ return KickoffTrainingResult(kicked_off=False, reason="rescue_throttled")
+
# Training runs in a Tasks sandbox that requires a real owning user. CLI-created
# pipelines have no creator, so fail before spending budget rather than launching
# a run that would crash in the tasks facade.
@@ -580,16 +597,27 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResul
)
return KickoffTrainingResult(kicked_off=False, reason="no_creator", error=error)
- daily_budget = min(10, remaining)
try:
with transaction.atomic():
- pipeline.iteration_budget_remaining = remaining - daily_budget
- pipeline.save(update_fields=["iteration_budget_remaining"])
- run_training(pipeline=pipeline, iteration_budget=daily_budget, user_id=pipeline.created_by_id)
+ if rescue:
+ run_training(
+ pipeline=pipeline,
+ iteration_budget=RESCUE_ITERATION_BUDGET,
+ user_id=pipeline.created_by_id,
+ rescue=True,
+ )
+ else:
+ daily_budget = min(10, remaining)
+ pipeline.iteration_budget_remaining = remaining - daily_budget
+ pipeline.save(update_fields=["iteration_budget_remaining"])
+ run_training(pipeline=pipeline, iteration_budget=daily_budget, user_id=pipeline.created_by_id)
except (ValueError, SandboxInferenceError, Action.DoesNotExist) as exc:
# run_training refuses a departed creator or an unresolvable target before it writes
# anything. A retry cannot fix either, so these report instead of raising.
return KickoffTrainingResult(kicked_off=False, reason="not_launchable", error=str(exc))
+ if rescue:
+ logger.info("autoresearch_kickoff_training_rescue", pipeline_id=inp.pipeline_id)
+ return KickoffTrainingResult(kicked_off=True, reason="rescue_unscorable")
return KickoffTrainingResult(kicked_off=True, reason="started")
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index db1a447139e1..e1d0f7b1127b 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -16,7 +16,7 @@ The other half is `../inference/`, which consumes what this package produces and
When the `autoresearch-report-notebook` flag is on for the launching user, the token also holds `REPORT_NOTEBOOK_MCP_SCOPES` and the brief adds two Finalize steps: before complete, the agent creates one report notebook and passes its `short_id` to complete. After complete, it adds the SQL and chart cells, because the run's model row (and so its `model_explanation`) exists only from then on. `report.md` stays required either way.
The brief's worked `features.sql` reads events through a pre-filtered subquery (the event names the features use, the anchor persons, and the anchors' widest window) before it joins, because ClickHouse builds the hash table from the right side of a join and a direct events join reads the whole team's events.
The brief also states the inference cutoff: the start of the prediction date in UTC (`ScoringWindow` in `../inference/scoring.py`), not `now()`.
- The brief's cost guidance is advice only. Cost does not enter champion selection, so the brief does not tell the agent to trade AUC for a cheaper query.
+ The brief's cost guidance is advice only. Cost does not enter champion selection, so the brief does not tell the agent to trade AUC for a cheaper query. A rescue run is the one exception, see the unscorable champion below.
For a person column that events do not carry, the brief recommends `raw_persons` in a subquery filtered with `id IN (SELECT person_id FROM {anchors})`, never `LEFT JOIN persons`, because the persons table dedupes every person of the team before any filter applies.
`feature_sql_hints()` in `recipe_validation.py` returns a non-blocking hint when a query reads `persons` or `raw_persons` in a SELECT whose `WHERE` does not refer to `{anchors}`. The `materialize-features` response carries the hints, with the `elapsed_s` and `rows_read` of the materialization.
Step 0 of the brief carries the realized results that `realized_context.py` computes, wrapped as untrusted data, with guidance on how to read the gap between holdout and realized AUC. The brief presents realized AUC as evidence for a direction, never as a target: the next run's holdout covers the same recent dates, so tuning against realized results tunes against the holdout. A pipeline with no validated dates gets one line instead of tables. `report.md` asks for one line on how the run used these results.
@@ -41,7 +41,7 @@ The other half is `../inference/`, which consumes what this package produces and
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 recipe-only champion is not checked.
- A champion whose scheduled scoring runs failed with a repeatable `failure_kind` on the last two prediction dates, with no success after the first of them, is unscorable (`find_unscorable_champion()` in `../inference/failures.py`). Any candidate replaces it whatever the margin, with `promotion_reason` `replaced_unscorable` in the model metrics, and the fit and the scorability check still roll back a candidate that cannot score either. The brief tells the agent the failure kind and the onset date.
+ A champion whose scheduled scoring runs failed with a repeatable `failure_kind` on the last two prediction dates, with no success after the first of them, is unscorable (`find_unscorable_champion()` in `../inference/failures.py`). Any candidate replaces it whatever the margin, with `promotion_reason` `replaced_unscorable` in the model metrics, and the fit and the scorability check still roll back a candidate that cannot score either. The brief tells the agent the failure kind and the onset date. A rescue run (see `../temporal/AGENTS.md`) also tells the agent to prefer a cheap model that scores over a higher holdout score.
A champion whose metrics lack `anchor_alignment: "utc_day"` was trained on T0s at any second (see `../dataset/AGENTS.md`), so its holdout score is inflated and is no bar. Any candidate replaces it whatever the margin, with `promotion_reason` `replaced_anchor_change`. Every new model records `anchor_alignment`.
- `explanation.py`
The `model_explanation` contract: `top_features` (at most `MAX_TOP_FEATURES`, each a `name`, a non-negative `importance` and a `direction` of `positive` or `negative`), plus an optional `method` and `note`. The `complete` serializer enforces it and sorts the features strongest first, and the brief states it.
diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.py
index 6eb1f1c5347e..6bdf56e9df10 100644
--- a/products/autoresearch/backend/training/runner.py
+++ b/products/autoresearch/backend/training/runner.py
@@ -230,6 +230,7 @@ def build_agent_description(
report_notebook: bool = False,
unscorable_champion: UnscorableChampion | None = None,
realized_context: RealizedContext | None = None,
+ rescue: bool = False,
) -> str:
"""Build the Claude Code agent prompt for the autoresearch training loop."""
pop_clause = ""
@@ -253,7 +254,7 @@ def build_agent_description(
)
sample_clause = _describe_training_sample(training_sample)
- unscorable_clause = _describe_unscorable_champion(unscorable_champion)
+ unscorable_clause = _describe_unscorable_champion(unscorable_champion, rescue=rescue)
realized_clause = _describe_realized_context(realized_context)
today_iso = date.today().isoformat()
@@ -863,9 +864,17 @@ def _realized_context_for_brief(pipeline: AutoresearchPipeline) -> RealizedConte
return None
-def _describe_unscorable_champion(unscorable: UnscorableChampion | None) -> str:
+def _describe_unscorable_champion(unscorable: UnscorableChampion | None, *, rescue: bool = False) -> str:
if unscorable is None:
return ""
+ rescue_text = ""
+ if rescue:
+ rescue_text = """
+
+ **This is a rescue run.** The pipeline has no iteration budget left, so this run gets a
+ small fixed budget only to make scoring work again. Prefer a cheap, simple model whose
+ `features.sql` scores today's inference population well inside the query limits over a
+ model with a higher `holdout_score`."""
# Indented to the brief's level, because the brief is dedented after this text goes in.
return textwrap.indent(
textwrap.dedent(f"""
@@ -876,7 +885,7 @@ def _describe_unscorable_champion(unscorable: UnscorableChampion | None) -> str:
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."""),
+ load or run the fitted model.{rescue_text}"""),
" " * 8,
)
@@ -912,6 +921,7 @@ def run_training(
pipeline: AutoresearchPipeline,
iteration_budget: int,
user_id: int | None,
+ rescue: bool = False,
) -> AutoresearchTrainingRun:
"""
Launch a real agent sandbox training run.
@@ -972,6 +982,7 @@ def run_training(
report_notebook=report_notebook,
unscorable_champion=_unscorable_champion_for_brief(pipeline),
realized_context=_realized_context_for_brief(pipeline),
+ rescue=rescue,
)
title = f"[autoresearch] {pipeline.name}: learn to predict '{pipeline.target_event}'"
diff --git a/products/autoresearch/backend/training/test_training.py b/products/autoresearch/backend/training/test_training.py
index 2864932f7eff..88471237203d 100644
--- a/products/autoresearch/backend/training/test_training.py
+++ b/products/autoresearch/backend/training/test_training.py
@@ -36,6 +36,8 @@ from products.autoresearch.backend.training.runner import (
run_training,
)
+_UNSCORABLE = UnscorableChampion(failure_kind="limit_exceeded", onset=date(2026, 9, 2))
+
class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):
def _make_pipeline(self) -> AutoresearchPipeline:
@@ -52,13 +54,14 @@ class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):
@parameterized.expand(
[
- ("without_notebook", False, None),
- ("with_notebook", True, None),
- ("unscorable_champion", False, UnscorableChampion(failure_kind="limit_exceeded", onset=date(2026, 9, 2))),
+ ("without_notebook", False, None, False),
+ ("with_notebook", True, None, False),
+ ("unscorable_champion", False, _UNSCORABLE, False),
+ ("rescue", False, _UNSCORABLE, True),
]
)
def test_prompt_renders_without_unresolved_placeholders(
- self, _name: str, report_notebook: bool, unscorable: UnscorableChampion | None
+ self, _name: str, report_notebook: bool, unscorable: UnscorableChampion | None, rescue: bool
) -> None:
pipeline = self._make_pipeline()
prompt = build_agent_description(
@@ -67,10 +70,12 @@ class TestBuildAgentDescription(TeamScopedTestMixin, BaseTest):
training_run_id="run-123",
report_notebook=report_notebook,
unscorable_champion=unscorable,
+ rescue=rescue,
)
if unscorable is not None:
assert "**The current champion cannot score.**" in prompt
assert "`limit_exceeded` since 2026-09-02" in prompt
+ assert ("**This is a rescue run.**" in prompt) is rescue
# `{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.