Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(autoresearch): ingest finished training runs from the tasks signal (10/22) (#89140)

Andrew Maguirebe2851edb55e
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 4625358fb2b8..02c369ef7c9f 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -161,6 +161,7 @@ post_save:products.ai_observability.backend.models.llm_prompt.invalidate_llm_pro
post_save:products.ai_observability.backend.models.provider_keys.provider_key_saved
post_save:products.ai_observability.backend.models.taggers.tagger_saved
post_save:products.annotations.backend.activity_logging.annotation_created
+post_save:products.autoresearch.backend.signals.on_task_run_saved
post_save:products.cdp.backend.models.hog_functions.hog_function.action_saved
post_save:products.cdp.backend.models.hog_functions.hog_function.cohort_saved
post_save:products.cdp.backend.models.hog_functions.hog_function.enabled_default_hog_functions_for_new_team
diff --git a/products/autoresearch/backend/apps.py b/products/autoresearch/backend/apps.py
index a35f0963a4c5..4361a5a1b58f 100644
--- a/products/autoresearch/backend/apps.py
+++ b/products/autoresearch/backend/apps.py
@@ -1,7 +1,16 @@
from django.apps import AppConfig
+from django.db.models.signals import post_save
class AutoresearchConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "products.autoresearch.backend"
label = "autoresearch"
+
+ def ready(self) -> None:
+ # Deferred because the receiver module imports models, which are not usable
+ # at the time this module itself is imported.
+ from products.autoresearch.backend.signals import on_task_run_saved # noqa: PLC0415
+
+ # Lazy "app_label.Model" sender keeps the tasks model off autoresearch's import path.
+ post_save.connect(on_task_run_saved, sender="tasks.TaskRun", dispatch_uid="autoresearch.on_task_run_saved")
diff --git a/products/autoresearch/backend/signals.py b/products/autoresearch/backend/signals.py
new file mode 100644
index 000000000000..ddd30d4ccd12
--- /dev/null
+++ b/products/autoresearch/backend/signals.py
@@ -0,0 +1,63 @@
+"""
+Django signal receivers for the autoresearch product.
+
+Registered in AutoresearchConfig.ready() (apps.py) after the app registry
+is initialised so cross-product model imports are safe.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+import structlog
+
+from posthog.models.scoping import team_scope
+
+if TYPE_CHECKING:
+ from products.autoresearch.backend.training.ingestion import FinishedTaskRun
+
+logger = structlog.get_logger(__name__)
+
+
+def on_task_run_saved(sender: Any, instance: FinishedTaskRun, created: bool, **kwargs: Any) -> None:
+ """
+ Detect autoresearch TaskRun completion and trigger recipe ingestion.
+
+ Fires on every TaskRun post_save. Fast-path: reads instance.state (no I/O)
+ to bail out quickly for non-autoresearch runs.
+ """
+ if created:
+ return
+
+ # Both imports are deferred: this receiver is connected during django.setup(), and
+ # the ingestion path reaches pandas. Importing either at module level puts that cost
+ # on every process boot (see posthog/test/repo_invariants/test_startup_import_budget.py).
+ from products.tasks.backend.facade.api import TaskRunStatus # noqa: PLC0415
+
+ if instance.status not in {
+ TaskRunStatus.COMPLETED,
+ TaskRunStatus.FAILED,
+ TaskRunStatus.CANCELLED,
+ }:
+ return
+
+ # TaskRun.state is client-writable JSON: a non-dict would raise outside the try below,
+ # rolling back the caller's terminal-status transaction.
+ state = instance.state if isinstance(instance.state, dict) else {}
+ training_run_id = state.get("autoresearch_training_run_id")
+ if not training_run_id:
+ return
+
+ try:
+ from products.autoresearch.backend.training.ingestion import handle_task_run_completed # noqa: PLC0415
+
+ # The signal is the entry boundary for this path, so it sets the team scope the
+ # fail-closed managers need.
+ with team_scope(instance.team_id):
+ handle_task_run_completed(instance)
+ except Exception:
+ logger.exception(
+ "autoresearch_signal_handler_failed",
+ task_run_id=str(instance.id),
+ training_run_id=training_run_id,
+ )
diff --git a/products/autoresearch/backend/test_signals.py b/products/autoresearch/backend/test_signals.py
new file mode 100644
index 000000000000..7b1bf7d05fac
--- /dev/null
+++ b/products/autoresearch/backend/test_signals.py
@@ -0,0 +1,25 @@
+from uuid import UUID
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.autoresearch.backend.signals import on_task_run_saved
+from products.tasks.backend.facade.api import TaskRunStatus
+
+
+class TestOnTaskRunSaved(SimpleTestCase):
+ @parameterized.expand([(["autoresearch_training_run_id"],), ("running",), (7,)])
+ def test_non_object_task_run_state_does_not_raise(self, state) -> None:
+ # Raising here would roll back the caller's terminal-status transaction.
+ class FakeTaskRun:
+ id = UUID("00000000-0000-0000-0000-000000000001")
+ team_id = 1
+ status = TaskRunStatus.COMPLETED
+ state: object = None
+ error_message: str | None = None
+
+ instance = FakeTaskRun()
+ instance.state = state
+
+ on_task_run_saved(sender=None, instance=instance, created=False)
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index 2274a9bf6fdc..3c4343443127 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -21,6 +21,7 @@ This package landed ahead of its callers. `../presentation/`, `../temporal/`, `.
- `ingestion.py`
The safety net. `handle_task_run_completed()` is called from the `TaskRun` `post_save` signal registered in `../apps.py`, and runs synchronously in the Temporal worker thread.
If the agent recorded iterations but never called complete, this finalizes through the same promotion path. If it recorded nothing, the run is marked failed — which is what produces `"Agent recorded no iterations before the run ended."`
+ The `autoresearch_training_run_id` marker in `TaskRun.state` is client-writable, so it names a run rather than proving ownership of it. A `TaskRun` may only finalize the run whose server-stamped `task_run_id` is its own id.
- `promotion.py`
Champion selection. `complete_training_run()` is the single entry point, used both by the training-run `complete` API action and by `ingestion.py`.
A challenger must beat the incumbent by `CHAMPION_PROMOTION_MARGIN` (0.005 holdout AUC) to be promoted — near-ties keep the incumbent rather than churning the champion on noise.
diff --git a/products/autoresearch/backend/training/ingestion.py b/products/autoresearch/backend/training/ingestion.py
new file mode 100644
index 000000000000..9b685d33ff87
--- /dev/null
+++ b/products/autoresearch/backend/training/ingestion.py
@@ -0,0 +1,172 @@
+"""
+Training result ingestion: finalize a completed TaskRun for an autoresearch pipeline.
+
+The agent records iterations live (autoresearch-training-runs-iterations-create), uploads
+its model bundle (autoresearch-training-runs-artifacts-upload-create), and finalizes the
+run itself (autoresearch-training-runs-complete-create). This handler is the safety net
+for the case where the TaskRun ends without the agent having called complete: if it
+recorded iterations, we finalize through the same server-side promotion flow; otherwise
+the run produced nothing and is marked failed.
+
+Entry point:
+ - handle_task_run_completed(task_run): called from the TaskRun post_save signal
+ registered in apps.py. Runs synchronously in the Temporal worker thread.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Protocol
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone as django_timezone
+
+import structlog
+
+from products.autoresearch.backend.models import AutoresearchIteration, AutoresearchPipeline, AutoresearchTrainingRun
+from products.autoresearch.backend.training.promotion import PromotionError, complete_training_run
+from products.tasks.backend.facade.api import TaskRunStatus
+
+logger = structlog.get_logger(__name__)
+
+
+class FinishedTaskRun(Protocol):
+ """The fields of a terminal ``TaskRun`` that this product reads, so the tasks model stays off its import path."""
+
+ @property
+ def id(self) -> UUID: ...
+
+ @property
+ def team_id(self) -> int: ...
+
+ @property
+ def status(self) -> str: ...
+
+ @property
+ def state(self) -> object: ...
+
+ @property
+ def error_message(self) -> str | None: ...
+
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
+
+ def _task_run_satisfies_contract(run: TaskRun) -> FinishedTaskRun:
+ # A tasks-side rename or type change of a field read here fails mypy instead of ingestion.
+ # ty has no Django plugin, so it cannot see the team_id attribute the team foreign key adds.
+ return run # ty: ignore[invalid-return-type]
+
+
+def handle_task_run_completed(task_run: FinishedTaskRun) -> None:
+ """
+ Finalize a completed (or failed/cancelled) TaskRun for an autoresearch pipeline.
+
+ Called from the post_save signal in apps.py. Safe to call multiple times — the
+ training_run status check prevents double-finalization. Normally the agent finalizes
+ the run itself via the complete tool, in which case the run is no longer RUNNING by
+ the time this fires and we no-op.
+ """
+ state = task_run.state if isinstance(task_run.state, dict) else {}
+ training_run_id = state.get("autoresearch_training_run_id")
+ if not training_run_id:
+ return
+
+ try:
+ training_run = (
+ AutoresearchTrainingRun.objects.for_team(task_run.team_id)
+ .select_related("pipeline__team")
+ .get(id=training_run_id)
+ )
+ except AutoresearchTrainingRun.DoesNotExist:
+ logger.warning(
+ "autoresearch_training_run_not_found",
+ task_run_id=str(task_run.id),
+ training_run_id=training_run_id,
+ )
+ return
+
+ # The state marker is client-writable; task_run_id is stamped server-side at dispatch.
+ if training_run.task_run_id != task_run.id:
+ logger.warning(
+ "autoresearch_training_run_task_run_mismatch",
+ task_run_id=str(task_run.id),
+ training_run_id=training_run_id,
+ bound_task_run_id=str(training_run.task_run_id),
+ )
+ return
+
+ # Idempotency guard: only act on a still-running run. If the agent already called
+ # complete, the run is COMPLETED/FAILED and there is nothing to do.
+ if training_run.status != AutoresearchTrainingRun.Status.RUNNING:
+ logger.info(
+ "autoresearch_training_run_already_processed",
+ training_run_id=training_run_id,
+ status=training_run.status,
+ )
+ return
+
+ if task_run.status in {TaskRunStatus.FAILED, TaskRunStatus.CANCELLED}:
+ _mark_failed(training_run, error=task_run.error_message or "TaskRun did not complete successfully")
+ return
+
+ # The agent ended without calling complete. If it recorded iterations, finalize through
+ # the promotion flow (which also attaches an uploaded bundle as the champion's artifact).
+ # If it recorded nothing, the run produced no candidate model — fail it.
+ if not AutoresearchIteration.objects.filter(training_run=training_run).exists():
+ _mark_failed(training_run, error="Agent recorded no iterations before the run ended.")
+ return
+
+ try:
+ complete_training_run(training_run)
+ except PromotionError as e:
+ logger.exception(
+ "autoresearch_agent_recorded_complete_failed",
+ training_run_id=training_run_id,
+ task_run_id=str(task_run.id),
+ )
+ _mark_failed(training_run, error=str(e))
+ except Exception:
+ logger.exception(
+ "autoresearch_agent_recorded_complete_failed",
+ training_run_id=training_run_id,
+ task_run_id=str(task_run.id),
+ )
+ _mark_failed(training_run, error="Agent-recorded run completion failed — see server logs")
+
+
+def _mark_failed(training_run: AutoresearchTrainingRun, error: str) -> None:
+ with transaction.atomic():
+ # The status was read before the agent's own complete request may have committed.
+ # Re-read under the same lock completion takes, so a run that promoted a champion in
+ # that window is not flipped to FAILED (which would also revert its pipeline to draft).
+ locked = AutoresearchTrainingRun.objects.select_for_update().get(pk=training_run.pk)
+ if locked.status != AutoresearchTrainingRun.Status.RUNNING:
+ logger.info(
+ "autoresearch_training_failure_skipped_after_completion",
+ training_run_id=str(locked.pk),
+ status=locked.status,
+ )
+ return
+ _apply_failure(locked, error)
+
+
+def _apply_failure(training_run: AutoresearchTrainingRun, error: str) -> None:
+ training_run.status = AutoresearchTrainingRun.Status.FAILED
+ training_run.completed_at = django_timezone.now()
+ training_run.error = error[:2000]
+ training_run.save(update_fields=["status", "completed_at", "error"])
+ # If this was the inaugural run, the pipeline is sitting in BOOTSTRAPPING with no
+ # champion behind it — drop it back to DRAFT so it doesn't look "live" after a failure.
+ # Conditional: a sibling run may have taken the pipeline live since this row was read.
+ AutoresearchPipeline.objects.filter(
+ pk=training_run.pipeline_id,
+ team_id=training_run.team_id,
+ status=AutoresearchPipeline.Status.BOOTSTRAPPING,
+ ).update(status=AutoresearchPipeline.Status.DRAFT, updated_at=django_timezone.now())
+ logger.warning(
+ "autoresearch_training_failed",
+ training_run_id=str(training_run.pk),
+ pipeline_id=str(training_run.pipeline_id),
+ error=error,
+ )
diff --git a/products/autoresearch/backend/training/test_training_ingestion.py b/products/autoresearch/backend/training/test_training_ingestion.py
new file mode 100644
index 000000000000..4e29c274b0a7
--- /dev/null
+++ b/products/autoresearch/backend/training/test_training_ingestion.py
@@ -0,0 +1,186 @@
+from uuid import UUID, uuid4
+
+from posthog.test.base import BaseTest
+
+from django.utils import timezone as django_timezone
+
+from parameterized import parameterized
+
+from products.autoresearch.backend.models import (
+ AutoresearchIteration,
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchTrainingRun,
+)
+from products.autoresearch.backend.testing import TeamScopedTestMixin
+from products.autoresearch.backend.training.ingestion import FinishedTaskRun, handle_task_run_completed
+
+_TASK_RUN_ID = UUID("00000000-0000-0000-0000-000000000001")
+
+
+class TestHandleTaskRunCompleted(TeamScopedTestMixin, BaseTest):
+ def _task_run(self, state: object, status: str = "completed", error_message: str | None = None) -> FinishedTaskRun:
+ class FakeTaskRun:
+ id = _TASK_RUN_ID
+ team_id = 0
+ status = ""
+ state: object = None
+ error_message: str | None = None
+
+ tr = FakeTaskRun()
+ tr.team_id = self.team.id
+ tr.status = status
+ tr.state = state
+ tr.error_message = error_message
+ return tr
+
+ def _make_pipeline(self, **kwargs) -> AutoresearchPipeline:
+ defaults = {
+ "team": self.team,
+ "created_by": self.user,
+ "name": "Test",
+ "target_event": "$pageview",
+ "horizon_days": 7,
+ "iteration_budget": 10,
+ "iteration_budget_remaining": 10,
+ }
+ defaults.update(kwargs)
+ return AutoresearchPipeline.objects.create(**defaults)
+
+ def _make_training_run(self, pipeline: AutoresearchPipeline, **kwargs) -> AutoresearchTrainingRun:
+ defaults = {
+ "pipeline": pipeline,
+ "status": AutoresearchTrainingRun.Status.RUNNING,
+ "iteration_budget": 10,
+ "started_at": django_timezone.now(),
+ "task_run_id": _TASK_RUN_ID,
+ }
+ defaults.update(kwargs)
+ return AutoresearchTrainingRun.objects.create(**defaults)
+
+ def _record_iteration(self, training_run, *, number=0, status="kept", holdout=0.8) -> None:
+ AutoresearchIteration.objects.create(
+ training_run=training_run,
+ pipeline=training_run.pipeline,
+ iteration_number=number,
+ recipe_hash=f"hash{number}",
+ recipe_snapshot={"feature_sql": "SELECT person_id AS distinct_id FROM events"},
+ model_spec={"model_class": "sklearn.linear_model.LogisticRegression", "model_params": {}},
+ holdout_score=holdout,
+ status=status,
+ agent_description="test",
+ )
+
+ @parameterized.expand([({},), ([{"autoresearch_training_run_id": "x"}],), ("running",), (None,)])
+ def test_skips_run_without_a_training_run_marker(self, state) -> None:
+ handle_task_run_completed(self._task_run(state))
+ assert AutoresearchTrainingRun.objects.count() == 0
+
+ def test_skips_unknown_training_run_id(self) -> None:
+ # A stale/unknown id must not raise.
+ handle_task_run_completed(
+ self._task_run(state={"autoresearch_training_run_id": "00000000-0000-0000-0000-0000000000ff"})
+ )
+
+ @parameterized.expand([("unbound", None), ("another_task_run", uuid4())])
+ def test_ignores_a_marker_naming_a_run_this_task_does_not_own(self, _name: str, task_run_id) -> None:
+ pipeline = self._make_pipeline()
+ training_run = self._make_training_run(pipeline, task_run_id=task_run_id)
+ tr = self._task_run(status="failed", state={"autoresearch_training_run_id": str(training_run.id)})
+
+ handle_task_run_completed(tr)
+
+ training_run.refresh_from_db()
+ assert training_run.status == AutoresearchTrainingRun.Status.RUNNING
+
+ def test_marks_failed_on_failed_task_run(self) -> None:
+ pipeline = self._make_pipeline()
+ training_run = self._make_training_run(pipeline)
+ tr = self._task_run(
+ status="failed",
+ state={"autoresearch_training_run_id": str(training_run.id)},
+ error_message="sandbox crashed",
+ )
+
+ handle_task_run_completed(tr)
+
+ training_run.refresh_from_db()
+ assert training_run.status == AutoresearchTrainingRun.Status.FAILED
+ assert "sandbox crashed" in training_run.error
+
+ def test_idempotency_guard_skips_already_completed(self) -> None:
+ pipeline = self._make_pipeline()
+ training_run = self._make_training_run(pipeline, status=AutoresearchTrainingRun.Status.COMPLETED)
+ self._record_iteration(training_run)
+ handle_task_run_completed(self._task_run(state={"autoresearch_training_run_id": str(training_run.id)}))
+ # No new champion materialized — the run was already finalized by the agent.
+ assert AutoresearchModel.objects.filter(pipeline=pipeline).count() == 0
+
+ def test_finalizes_when_agent_recorded_iterations(self) -> None:
+ pipeline = self._make_pipeline()
+ training_run = self._make_training_run(pipeline)
+ self._record_iteration(training_run, number=0, status="discarded", holdout=0.6)
+ self._record_iteration(training_run, number=1, status="kept", holdout=0.82)
+
+ handle_task_run_completed(self._task_run(state={"autoresearch_training_run_id": str(training_run.id)}))
+
+ training_run.refresh_from_db()
+ assert training_run.status == AutoresearchTrainingRun.Status.COMPLETED
+ champion = AutoresearchModel.objects.get(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)
+ assert champion.holdout_score == 0.82
+ assert champion.source_training_run == training_run
+ # First champion takes the pipeline live so the daily coordinator scores it.
+ pipeline.refresh_from_db()
+ assert pipeline.status == AutoresearchPipeline.Status.RUNNING
+
+ def test_promotion_does_not_reactivate_non_draft_pipeline(self) -> None:
+ pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.PAUSED)
+ training_run = self._make_training_run(pipeline)
+ self._record_iteration(training_run, number=0, status="kept", holdout=0.82)
+
+ handle_task_run_completed(self._task_run(state={"autoresearch_training_run_id": str(training_run.id)}))
+
+ AutoresearchModel.objects.get(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)
+ pipeline.refresh_from_db()
+ assert pipeline.status == AutoresearchPipeline.Status.PAUSED
+
+ def test_marks_failed_when_no_iterations(self) -> None:
+ pipeline = self._make_pipeline()
+ training_run = self._make_training_run(pipeline)
+
+ handle_task_run_completed(self._task_run(state={"autoresearch_training_run_id": str(training_run.id)}))
+
+ training_run.refresh_from_db()
+ assert training_run.status == AutoresearchTrainingRun.Status.FAILED
+ assert "no iterations" in training_run.error.lower()
+ assert AutoresearchModel.objects.filter(pipeline=pipeline).count() == 0
+
+ def test_promotion_takes_bootstrapping_pipeline_live(self) -> None:
+ pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.BOOTSTRAPPING)
+ training_run = self._make_training_run(pipeline)
+ self._record_iteration(training_run, number=0, status="kept", holdout=0.82)
+
+ handle_task_run_completed(self._task_run(state={"autoresearch_training_run_id": str(training_run.id)}))
+
+ AutoresearchModel.objects.get(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)
+ pipeline.refresh_from_db()
+ assert pipeline.status == AutoresearchPipeline.Status.RUNNING
+
+ @parameterized.expand(
+ [
+ (AutoresearchPipeline.Status.BOOTSTRAPPING, AutoresearchPipeline.Status.DRAFT),
+ (AutoresearchPipeline.Status.RUNNING, AutoresearchPipeline.Status.RUNNING),
+ (AutoresearchPipeline.Status.PAUSED, AutoresearchPipeline.Status.PAUSED),
+ ]
+ )
+ def test_failed_run_reverts_only_bootstrapping(self, start_status: str, expected_status: str) -> None:
+ pipeline = self._make_pipeline(status=start_status)
+ training_run = self._make_training_run(pipeline)
+ tr = self._task_run(status="failed", state={"autoresearch_training_run_id": str(training_run.id)})
+
+ handle_task_run_completed(tr)
+
+ training_run.refresh_from_db()
+ pipeline.refresh_from_db()
+ assert training_run.status == AutoresearchTrainingRun.Status.FAILED
+ assert pipeline.status == expected_status