: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(autoresearch): close inference runs a lost scoring attempt leaves running (#114569)
posthog[bot]537e0ec518c7
diff --git a/products/autoresearch/backend/evaluation/online_validation.py b/products/autoresearch/backend/evaluation/online_validation.pyindex d2470c58d358..83a1157460a1 100644--- a/products/autoresearch/backend/evaluation/online_validation.py+++ b/products/autoresearch/backend/evaluation/online_validation.py@@ -45,16 +45,17 @@ from products.autoresearch.backend.dataset.labeling import (from products.autoresearch.backend.evaluation.history import latest_validation_runsfrom products.autoresearch.backend.evaluation.maturity import matures_atfrom products.autoresearch.backend.evaluation.segment_thresholds import BASE_RATE_DATES, segment_thresholds+from products.autoresearch.backend.inference.failures import INFERENCE_WORKFLOW_TIMEOUTfrom products.autoresearch.backend.inference.sandbox import SandboxInferenceError, _resolve_acting_userfrom products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchRunfrom products.autoresearch.backend.query import INTERACTIVE_QUERY, HogQLResult, QueryContext, run_hogqllogger = structlog.get_logger(__name__)-# A validation run does one bounded query per model plus the labels query, and a scoring run-# is bounded by its sandbox timeouts, so a RUNNING row older than this belongs to a worker that-# died mid-run and the exception handler never ran. Neither kind may hold a date forever.-STALE_RUN_AFTER = timedelta(hours=6)+# The inference and validation workflows both end by this timeout, so a RUNNING row older than+# this belongs to a worker that died mid-run and the exception handler never ran. Neither kind+# may hold a date forever.+STALE_RUN_AFTER = INFERENCE_WORKFLOW_TIMEOUT# A live run stamps its events at emission time, which can cross midnight UTC before the# batch goes out; a backfill stamps noon UTC of the date. Both fall within this many daysdiff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex 757fd9d288fe..ece1d3a4a33c 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -13,7 +13,7 @@ import jsonimport base64import asyncioimport hashlib-from datetime import date, datetime, timedelta+from datetime import date, datetimefrom typing import Anyfrom uuid import UUID, uuid4@@ -48,6 +48,7 @@ from ..evaluation.segment_thresholds import (champion_score_calibration,segment_thresholds,)+from ..inference.failures import INFERENCE_WORKFLOW_TIMEOUTfrom ..models import (AutoresearchIteration,AutoresearchModel,@@ -971,11 +972,6 @@ def _require_resolvable_target(pipeline: AutoresearchPipeline) -> None:raise AutoresearchConflict("The pipeline's target action no longer exists or has no steps.")-# A run still marked running after the inference workflow's own timeout lost its worker, so it-# must not block a new run forever.-_INFERENCE_RUN_STALE_AFTER = timedelta(hours=5)--class _InferenceAlreadyStarted(Exception):pass@@ -987,7 +983,8 @@ def _running_inference_run(team_id: int, pipeline: AutoresearchPipeline) -> Autopipeline=pipeline,run_type=AutoresearchRun.RunType.INFERENCE,status=AutoresearchRun.Status.RUNNING,- started_at__gte=django_timezone.now() - _INFERENCE_RUN_STALE_AFTER,+ # A run older than the workflow timeout lost its worker, so it must not block a new run.+ started_at__gte=django_timezone.now() - INFERENCE_WORKFLOW_TIMEOUT,)# A shadow model's run belongs to the champion's cadence, not to a scoring the caller can poll..exclude(metrics__has_key="shadow")@@ -1068,7 +1065,6 @@ def _start_inference_workflow(from posthog.temporal.common.client import sync_connect # noqa: PLC0415from ..temporal.workflows import ( # noqa: PLC0415- _INFERENCE_WORKFLOW_TIMEOUT,AutoresearchInferenceWorkflow,InferenceWorkflowInput,inference_workflow_id,@@ -1089,7 +1085,7 @@ def _start_inference_workflow(id=inference_workflow_id(pipeline_id, prediction_date),task_queue=settings.AUTORESEARCH_TASK_QUEUE,id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,- execution_timeout=_INFERENCE_WORKFLOW_TIMEOUT,+ execution_timeout=INFERENCE_WORKFLOW_TIMEOUT,))except WorkflowAlreadyStartedError as exc:diff --git a/products/autoresearch/backend/inference/failures.py b/products/autoresearch/backend/inference/failures.pyindex ad8c84bc55da..ce68a9ec8777 100644--- a/products/autoresearch/backend/inference/failures.py+++ b/products/autoresearch/backend/inference/failures.py@@ -1,15 +1,25 @@"""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 datetime import date, timedeltafrom enum import StrEnum+from django.utils import timezone as django_timezone++import structlog+from posthog.dataclasses import frozenfrom posthog.errors import QueryErrorCategory, classify_query_errorfrom products.autoresearch.backend.inference.sandbox import ModelLoadErrorfrom products.autoresearch.backend.models import AutoresearchModel, AutoresearchRun+logger = structlog.get_logger(__name__)++# The inference workflow's execution timeout. It covers both activity attempts plus their backoff,+# so an inference run still RUNNING after this long lost its worker and no attempt can close it.+INFERENCE_WORKFLOW_TIMEOUT = timedelta(hours=5)+class FailureKind(StrEnum):LIMIT_EXCEEDED = "limit_exceeded"@@ -102,3 +112,29 @@ def find_unscorable_champion(champion: AutoresearchModel | None) -> UnscorableChreturn Nonenewest_day = max(failed_days)return UnscorableChampion(failure_kind=failed_days[newest_day], onset=min(failed_days))+++def fail_stale_inference_runs() -> int:+ """+ Fail every inference run, across all teams, that is still RUNNING after ``INFERENCE_WORKFLOW_TIMEOUT``.++ A lost worker, a heartbeat timeout, or a cancellation ends the attempt before the scoring code+ records an outcome. The kind is ``other``, so ``find_unscorable_champion`` does not count the run.+ """+ now = django_timezone.now()+ stale = AutoresearchRun.objects.unscoped().filter(+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=AutoresearchRun.Status.RUNNING,+ started_at__lt=now - INFERENCE_WORKFLOW_TIMEOUT,+ )+ failed = 0+ for run in stale:+ run.status = AutoresearchRun.Status.FAILED+ run.error = "Scoring stopped without a result. The worker was lost or the attempt timed out."+ run.metrics["failure_kind"] = FailureKind.OTHER+ run.completed_at = now+ run.save(update_fields=["status", "error", "metrics", "completed_at"])+ failed += 1+ if failed:+ logger.warning("autoresearch_stale_inference_runs_failed", count=failed)+ return faileddiff --git a/products/autoresearch/backend/temporal/AGENTS.md b/products/autoresearch/backend/temporal/AGENTS.mdindex 2223235d5db6..e2619a7e2e67 100644--- a/products/autoresearch/backend/temporal/AGENTS.md+++ b/products/autoresearch/backend/temporal/AGENTS.md@@ -38,6 +38,8 @@ The coordinator decides _whether_ each pipeline is due; the child workflows do oValidation runs on every daily sweep, because a matured date should not wait for the next scoring day.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.+Discovery also fails every inference run still RUNNING after `INFERENCE_WORKFLOW_TIMEOUT` (`fail_stale_inference_runs()` in `../inference/failures.py`), with `failure_kind` `other`, because a lost worker never records an outcome.+A retry of a scheduled scoring attempt fills the RUNNING row of the attempt before it, so one date keeps one row.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`.diff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.pyindex 964ef80bee2b..4c636db44a4f 100644--- a/products/autoresearch/backend/temporal/test_workflows.py+++ b/products/autoresearch/backend/temporal/test_workflows.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, Optionalimport time_machine@@ -250,6 +250,65 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):claim_deadline = mock_validation.call_args.kwargs["claim_deadline"]assert django_timezone.now() < claim_deadline < django_timezone.now() + _VALIDATION_ATTEMPT_TIMEOUT+ @parameterized.expand(+ [+ ("open_scheduled_row_is_reused", {}, True),+ ("other_date_is_not_reused", {"prediction_date": "2026-09-10"}, False),+ ("manual_row_is_not_reused", {"scheduled": False}, False),+ ("finished_row_is_not_reused", {"status": AutoresearchRun.Status.FAILED}, False),+ ("row_past_the_workflow_timeout_is_not_reused", {"age": timedelta(hours=6)}, False),+ ]+ )+ @patch("products.autoresearch.backend.temporal.workflows.run_inference_for_pipeline")+ def test_scheduled_retry_reuses_the_row_of_the_lost_attempt(+ self, _name: str, row: dict[str, Any], reused: bool, mock_inference: MagicMock+ ) -> None:+ pipeline = self._create_pipeline()+ AutoresearchModel.objects.create(+ pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION, model_recipe={"stub": True}, recipe_hash="abc"+ )+ earlier = AutoresearchRun.objects.create(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ scheduled=row.get("scheduled", True),+ status=row.get("status", AutoresearchRun.Status.RUNNING),+ started_at=django_timezone.now() - row.get("age", timedelta(minutes=10)),+ metrics={"prediction_date": row.get("prediction_date", "2026-09-11"), "horizon_days": 30},+ )+ mock_inference.return_value = MagicMock(pk="run-1", rows_scored=0, status="completed", error="")++ ActivityEnvironment().run(+ activity_run_inference,+ RunInferenceInput(pipeline_id=str(pipeline.id), team_id=self.team.id, prediction_date="2026-09-11"),+ )++ assert mock_inference.call_args.kwargs["run"] == (earlier if reused else None)++ def test_load_active_pipelines_fails_inference_runs_left_running(self) -> None:+ pipeline = self._create_pipeline()++ def _running(age: timedelta) -> AutoresearchRun:+ return AutoresearchRun.objects.create(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ scheduled=True,+ status=AutoresearchRun.Status.RUNNING,+ started_at=django_timezone.now() - age,+ metrics={"prediction_date": "2026-09-10", "horizon_days": 30},+ )++ lost = _running(timedelta(hours=6))+ live = _running(timedelta(hours=1))++ activity_load_active_pipelines(LoadActivePipelinesInput())++ lost.refresh_from_db()+ live.refresh_from_db()+ assert lost.status == AutoresearchRun.Status.FAILED+ assert lost.completed_at is not None+ assert lost.metrics["failure_kind"] == "other"+ assert live.status == AutoresearchRun.Status.RUNNING+@parameterized.expand([("scheduled", False), ("manual", True)])@patch("products.autoresearch.backend.temporal.workflows.run_inference_for_pipeline")def test_inference_refuses_a_deleted_action_target(diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.pyindex a56ef2537d55..57fb143f6a77 100644--- a/products/autoresearch/backend/temporal/workflows.py+++ b/products/autoresearch/backend/temporal/workflows.py@@ -32,7 +32,12 @@ with workflow.unsafe.imports_passed_through():from products.autoresearch.backend.access import has_autoresearch_accessfrom products.autoresearch.backend.dataset.labeling import build_target_conditionfrom 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.failures import (+ INFERENCE_WORKFLOW_TIMEOUT,+ UNSCORABLE_AFTER_FAILED_DAYS,+ fail_stale_inference_runs,+ find_unscorable_champion,+ )from products.autoresearch.backend.inference.sandbox import SandboxInferenceError, _resolve_acting_userfrom products.autoresearch.backend.inference.scoring import run_inference_for_pipelinefrom products.autoresearch.backend.models import (@@ -109,7 +114,8 @@ def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:with the new champion instead of failing again on the archived one.A manual run (``run_id`` set) fills the row the API created, and a refusal fails that row,- so the caller that polls it sees the outcome.+ so the caller that polls it sees the outcome. A retry of a scheduled run fills the row the+ first attempt created, so a lost attempt does not leave a second row for the same date."""with HeartbeaterSync(), team_scope(inp.team_id):pipeline = AutoresearchPipeline.objects.select_related("team__organization", "created_by").get(@@ -137,7 +143,7 @@ def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:model=model,prediction_date=date.fromisoformat(inp.prediction_date),user=user,- run=manual_run,+ run=manual_run or _open_scheduled_run(pipeline, inp.prediction_date),query_context=BATCH_QUERY,scheduled=manual_run is None,)@@ -149,6 +155,22 @@ def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:)+def _open_scheduled_run(pipeline: AutoresearchPipeline, prediction_date: str) -> AutoresearchRun | None:+ """The RUNNING row an earlier attempt of this scheduled run created, or None on the first attempt."""+ return (+ AutoresearchRun.objects.filter(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ scheduled=True,+ status=AutoresearchRun.Status.RUNNING,+ started_at__gte=django_timezone.now() - INFERENCE_WORKFLOW_TIMEOUT,+ metrics__prediction_date=prediction_date,+ )+ .order_by("-started_at")+ .first()+ )++def _champion_for_inference(pipeline: AutoresearchPipeline) -> AutoresearchModel:try:# A bundle champion never resolves the target, so a deleted or stepless action would@@ -200,8 +222,7 @@ _SCORE_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(second_SCORE_ATTEMPT_TIMEOUT = timedelta(hours=2)# A lost worker is detected in minutes rather than at the end of a multi-hour attempt._HEARTBEAT_TIMEOUT = timedelta(minutes=2)-# Covers both attempts plus their backoff, so the child never cuts off a retry.-_INFERENCE_WORKFLOW_TIMEOUT = timedelta(hours=5)+# INFERENCE_WORKFLOW_TIMEOUT covers both attempts plus their backoff, so the child never cuts off a retry.@workflow.defn(name="autoresearch-inference")@@ -299,7 +320,8 @@ _VALIDATION_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(s# sweep, so the attempt completes instead of timing out part-way._VALIDATION_ATTEMPT_TIMEOUT = timedelta(hours=2)_VALIDATION_DATE_RESERVE = timedelta(minutes=70)-# Covers both attempts plus their backoff, as for inference.+# Covers both attempts plus their backoff, as for inference. Online validation treats a RUNNING+# row older than INFERENCE_WORKFLOW_TIMEOUT as dead, so keep this no longer than that._VALIDATION_WORKFLOW_TIMEOUT = timedelta(hours=5)@@ -486,7 +508,10 @@ def activity_load_active_pipelines(inp: LoadActivePipelinesInput) -> LoadActivePdispatched, because every scheduled query and training run acts as the creator. A pipelineoutside the ``autoresearch`` rollout is skipped but stays live, so it resumes when the rolloutreaches it again.++ It also fails every inference run that its lost worker left RUNNING."""+ fail_stale_inference_runs()today = django_timezone.now().date()# unscoped() because the coordinator's job is exactly to sweep every team. The# pipelines it returns carry their team so the downstream activities can scope.@@ -738,7 +763,7 @@ class AutoresearchCoordinatorWorkflow(PostHogWorkflow):pipeline_id=pipeline_id, team_id=pipeline.team_id, prediction_date=run_date),id=inference_workflow_id(pipeline_id, run_date),- execution_timeout=_INFERENCE_WORKFLOW_TIMEOUT,+ execution_timeout=INFERENCE_WORKFLOW_TIMEOUT,)),)