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): schedule training, scoring and validation on Temporal (22/22) (#89156)

Andrew Maguiref4b9fbf67b2f
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 93c8c221cd73..e1791ff4098a 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -440,6 +440,7 @@ jobs:
# check_general_purpose_coverage_added below.
generalPurpose:
- 'products/notebooks/backend/**'
+ - 'products/autoresearch/backend/**'
- 'products/exports/backend/temporal/subscriptions/**'
- 'products/engineering_analytics/backend/**'
- 'products/canvas/backend/**'
@@ -1048,7 +1049,7 @@ jobs:
if [ -z "$BASE" ] || [ "$BASE" = "0000000000000000000000000000000000000000" ] || ! git fetch --depth=1 --no-tags origin "$BASE"; then
BASE="HEAD^"
fi
- if git diff "$BASE" HEAD -- .github/workflows/container-images-cd.yml | grep -qE '^\+.*products/exports/backend/temporal/subscriptions'; then
+ if git diff "$BASE" HEAD -- .github/workflows/container-images-cd.yml | grep -qE '^\+.*(products/exports/backend/temporal/subscriptions|products/autoresearch/backend)'; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 79ebf33a3c38..951ba9f60508 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -160,6 +160,10 @@ from products.alerts.backend.facade.temporal import (
SHARED_ORCHESTRATION_ACTIVITIES as ALERTS_PLATFORM_SHARED_ORCHESTRATION_ACTIVITIES,
SHARED_ORCHESTRATION_WORKFLOWS as ALERTS_PLATFORM_SHARED_ORCHESTRATION_WORKFLOWS,
)
+from products.autoresearch.backend.facade.temporal import (
+ ACTIVITIES as AUTORESEARCH_ACTIVITIES,
+ WORKFLOWS as AUTORESEARCH_WORKFLOWS,
+)
from products.batch_exports.backend.temporal import (
ACTIVITIES as BATCH_EXPORTS_ACTIVITIES,
WORKFLOWS as BATCH_EXPORTS_WORKFLOWS,
@@ -565,6 +569,11 @@ _task_queue_specs = [
LOGS_VOLUME_TICK_WORKFLOWS,
LOGS_VOLUME_TICK_ACTIVITIES,
),
+ (
+ settings.AUTORESEARCH_TASK_QUEUE,
+ AUTORESEARCH_WORKFLOWS,
+ AUTORESEARCH_ACTIVITIES,
+ ),
(
settings.STAMPHOG_TASK_QUEUE,
STAMPHOG_WORKFLOWS,
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index dd43253b32b6..17152d29ecab 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -313,6 +313,9 @@ ERROR_TRACKING_TASK_QUEUE = _set_temporal_task_queue("error-tracking-task-queue"
ERROR_TRACKING_LIFECYCLE_TASK_QUEUE = _set_temporal_task_queue("error-tracking-lifecycle-task-queue")
EVENT_SCREENSHOTS_TASK_QUEUE = _set_temporal_task_queue("event-screenshots-task-queue")
LOGS_ALERTING_TASK_QUEUE = _set_temporal_task_queue("logs-alerting-task-queue")
+# Defaults to the general-purpose fleet so the daily coordinator always has a live worker. Deploy a
+# fleet polling "autoresearch-task-queue" before setting this env, or the schedule strands its runs.
+AUTORESEARCH_TASK_QUEUE = _set_temporal_task_queue(os.getenv("AUTORESEARCH_TASK_QUEUE", "general-purpose-task-queue"))
# Dedicated queue: the tick becomes the scan-heavy rollup writer, and it must not
# share pods with the latency-sensitive alerting workers.
LOGS_VOLUME_TICK_TASK_QUEUE = _set_temporal_task_queue(
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 4571507c4de1..89703ac85cb5 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -79,6 +79,7 @@ from posthog.temporal.warehouse_sources_queue_partition_management.schedule impo
from posthog.temporal.weekly_digest.types import WeeklyDigestInput
from products.alerts.backend.facade.temporal import create_alerts_platform_tick_schedule
+from products.autoresearch.backend.facade.temporal import create_autoresearch_daily_schedule
from products.billing_alerts.backend.temporal.schedule import create_schedule_due_billing_alert_checks_schedule
from products.business_knowledge.backend.temporal.schedule import (
create_business_knowledge_learning_coordinator_schedule,
@@ -950,6 +951,7 @@ schedules = [
create_schedule_due_alert_checks_schedule,
create_run_investigation_safety_net_schedule,
create_cleanup_alert_checks_schedule,
+ create_autoresearch_daily_schedule,
create_signals_scout_coordinator_schedule,
create_inbox_ranking_scoring_schedule,
create_scout_suggestions_coordinator_schedule,
diff --git a/products/autoresearch/backend/dataset/AGENTS.md b/products/autoresearch/backend/dataset/AGENTS.md
index a9dd1ea4beb0..c3a2068fec42 100644
--- a/products/autoresearch/backend/dataset/AGENTS.md
+++ b/products/autoresearch/backend/dataset/AGENTS.md
@@ -2,8 +2,6 @@
What the prediction problem actually _is_: who is in the population, what counts as a positive example, and whether the question is answerable at all.
-This package landed ahead of its callers. `../training/`, `../inference/`, and `../presentation/` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.
-
Nothing here trains or scores anything. It is the shared vocabulary that `../training/` and `../inference/` both compile against — which is the whole point. If the trainer and the scorer disagreed about what a row means, the resulting model would be quietly wrong rather than loudly broken.
## What lives here
diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.md
index 4e9394c2f32c..b7ede1aec54b 100644
--- a/products/autoresearch/backend/evaluation/AGENTS.md
+++ b/products/autoresearch/backend/evaluation/AGENTS.md
@@ -6,8 +6,6 @@ Training measures a model against a holdout slice of history. This package measu
It is the only honest number in the product. A holdout AUC of 0.93 says the model separates history well; the realized AUC says whether it predicted the future.
-This package landed ahead of its scheduler. `../temporal/` arrives in a later piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.
-
## What lives here
- `online_validation.py`
diff --git a/products/autoresearch/backend/facade/temporal.py b/products/autoresearch/backend/facade/temporal.py
new file mode 100644
index 000000000000..4fbab7930c8b
--- /dev/null
+++ b/products/autoresearch/backend/facade/temporal.py
@@ -0,0 +1,8 @@
+"""Temporal wiring re-exports — the only path core may use to register this
+product's workflows, activities, and schedule."""
+
+from ..temporal import (
+ ACTIVITIES as ACTIVITIES,
+ WORKFLOWS as WORKFLOWS,
+)
+from ..temporal.schedule import create_autoresearch_daily_schedule as create_autoresearch_daily_schedule
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index 52ea8c7488fb..5ea837e7e227 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -7,8 +7,6 @@ This is the cheap, boring, high-frequency half of the product — it runs on the
The cardinal rule: **inference never refits a persisted model.** A bundle is fitted once, at training completion, and every cadence loads that `model.pkl`. A recipe-only champion has no persisted model, so it fits its allowlisted sklearn class in process on every cadence; that is the cost of a champion without a bundle, not a refit.
-This package landed ahead of its scheduler. `../temporal/` arrives in a later piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.
-
## What lives here
- `sandbox.py`
diff --git a/products/autoresearch/backend/temporal/AGENTS.md b/products/autoresearch/backend/temporal/AGENTS.md
new file mode 100644
index 000000000000..b925a7e4cca5
--- /dev/null
+++ b/products/autoresearch/backend/temporal/AGENTS.md
@@ -0,0 +1,65 @@
+# Temporal workflows
+
+The scheduled half of autoresearch. Three workflows and four activities, registered on `settings.AUTORESEARCH_TASK_QUEUE` by `start_temporal_worker`, which imports `WORKFLOWS` and `ACTIVITIES` from `__init__.py`.
+
+Scoring, validation and training live in `../inference/`, `../evaluation/`, and `../training/` — the same functions the management commands and the API reach — and the activities call them, so the scheduled path cannot drift from the headless one. What stays here is the sweep's own logic: discovery (cadence, rollout, creator access) and the kickoff's eligibility gates, budget debit and row lock.
+
+## What lives here
+
+- `workflows.py`
+ - `AutoresearchCoordinatorWorkflow` (`autoresearch-coordinator`) — the daily tick. Loads active pipelines (`activity_load_active_pipelines`) and fans out inference, validation, and training kickoff per pipeline.
+ - `AutoresearchInferenceWorkflow` (`autoresearch-inference`) — `activity_run_inference` for one pipeline. The activity reads the current champion itself, so a retry after a mid-scoring promotion scores with the new one.
+ - `AutoresearchValidationWorkflow` (`autoresearch-validation`) — `activity_run_validation` for one pipeline.
+ - `activity_kickoff_training` — launches a training run for a pipeline that is due.
+
+ Each workflow has a typed input/result dataclass pair (`InferenceWorkflowInput` / `InferenceWorkflowResult`, and so on). Activities are named with a `autoresearch-<workflow>.<activity>` convention.
+
+- `schedule.py`
+ `create_autoresearch_daily_schedule()` registers schedule `autoresearch-daily-coordinator` driving workflow id `autoresearch-coordinator`.
+ Overlap policy is **SKIP** — a tick that is still running causes the next one to be dropped rather than queued, so a slow day cannot pile up a backlog of duplicate scoring runs.
+ An update keeps the schedule's live state, so a deploy does not resume a schedule an operator paused.
+ The queue defaults to the general-purpose fleet. Deploy a worker polling `autoresearch-task-queue` before you set `AUTORESEARCH_TASK_QUEUE` to it.
+- `__init__.py`
+ The registration surface. `WORKFLOWS` and `ACTIVITIES` are what the worker reads; a workflow that is not in these lists does not exist as far as production is concerned.
+
+## Mental model
+
+```text
+daily schedule
+ └─ AutoresearchCoordinatorWorkflow
+ ├─ activity_load_active_pipelines
+ └─ per pipeline:
+ ├─ AutoresearchInferenceWorkflow → ../inference/
+ ├─ AutoresearchValidationWorkflow → ../evaluation/
+ └─ activity_kickoff_training → ../training/
+```
+
+The coordinator decides _whether_ each pipeline is due; the child workflows do one pipeline's work. Keep that split — per-pipeline logic in the coordinator is what makes a fan-out impossible to reason about.
+Validation 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.
+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.
+
+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.
+
+## Payload discipline
+
+Temporal activity payloads are capped at roughly 2 MiB, and autoresearch moves genuinely large data — feature matrices, prediction sets, materialized populations.
+
+**Do all heavy work inside a single activity and return only references.** Scoring writes its events and returns counts; validation computes its metrics inside the activity and returns the summary. Never pass a materialized population or a prediction set through a workflow on its way to being persisted — it will work in dev and fail with `PayloadSizeError` the moment a real team runs it.
+
+## Where the rest of the system meets this package
+
+- **Registered by** — `posthog/management/commands/start_temporal_worker.py`, which imports `WORKFLOWS` / `ACTIVITIES` from here.
+- **Scheduled by** — `posthog/temporal/schedule.py`, which calls `create_autoresearch_daily_schedule()`.
+- **Calls into** — `../inference/scoring.py`, `../evaluation/online_validation.py`, `../training/runner.py`.
+- **Result handoff** — training results come back through the `TaskRun` `post_save` signal wired in `../apps.py`, not through this workflow.
+
+## When editing this flow
+
+- **Editing a `@workflow.defn` body breaks in-flight executions.** Adding, removing, or reordering `execute_activity` calls, child-workflow starts, or timers fails replay with a non-determinism error on every running execution.
+ Gate new commands behind `workflow.patched("...")`, or on a new field of an existing activity's output dataclass that defaults to the skip value. Activity _implementations_ and activity _input_ dataclasses are safe to edit; command sequences are not.
+- **Never gate a workflow command on something computed inside the workflow body** — a feature flag, a setting, the clock, a database read. That is itself non-deterministic.
+- Keep scoring, validation and training logic out of the activities. It belongs in the package the activity calls, or the management commands will quietly behave differently from production. Only sweep-specific decisions (what is due, who may launch) stay here.
+- New workflows and activities must be added to `WORKFLOWS` / `ACTIVITIES` in `__init__.py` or they are never registered — this fails silently, since nothing errors when a workflow simply never runs.
+- **If you add or rename a workflow or activity, update this file to match.**
diff --git a/products/autoresearch/backend/temporal/CLAUDE.md b/products/autoresearch/backend/temporal/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/autoresearch/backend/temporal/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/autoresearch/backend/temporal/__init__.py b/products/autoresearch/backend/temporal/__init__.py
new file mode 100644
index 000000000000..d840fb19427c
--- /dev/null
+++ b/products/autoresearch/backend/temporal/__init__.py
@@ -0,0 +1,36 @@
+"""Temporal workflows and activities for autoresearch inference, validation, and training.
+
+`start_temporal_worker` imports WORKFLOWS and ACTIVITIES from here and
+registers them on `settings.AUTORESEARCH_TASK_QUEUE`.
+"""
+
+from .workflows import (
+ AutoresearchCoordinatorWorkflow,
+ AutoresearchInferenceWorkflow,
+ AutoresearchValidationWorkflow,
+ activity_kickoff_training,
+ activity_load_active_pipelines,
+ activity_run_inference,
+ activity_run_validation,
+)
+
+WORKFLOWS = [
+ AutoresearchCoordinatorWorkflow,
+ AutoresearchInferenceWorkflow,
+ AutoresearchValidationWorkflow,
+]
+
+ACTIVITIES = [
+ activity_kickoff_training,
+ activity_load_active_pipelines,
+ activity_run_inference,
+ activity_run_validation,
+]
+
+__all__ = [
+ "ACTIVITIES",
+ "WORKFLOWS",
+ "AutoresearchCoordinatorWorkflow",
+ "AutoresearchInferenceWorkflow",
+ "AutoresearchValidationWorkflow",
+]
diff --git a/products/autoresearch/backend/temporal/schedule.py b/products/autoresearch/backend/temporal/schedule.py
new file mode 100644
index 000000000000..af215bfe50cb
--- /dev/null
+++ b/products/autoresearch/backend/temporal/schedule.py
@@ -0,0 +1,62 @@
+"""Temporal schedule for the daily autoresearch coordinator workflow."""
+
+from __future__ import annotations
+
+from datetime import timedelta
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleCalendarSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleRange,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.autoresearch.backend.temporal.workflows import CoordinatorWorkflowInput
+
+_SCHEDULE_ID = "autoresearch-daily-coordinator"
+_WORKFLOW_ID = "autoresearch-coordinator"
+
+
+async def create_autoresearch_daily_schedule(client: Client) -> None:
+ """Create or update the daily schedule for the autoresearch coordinator workflow.
+
+ Fires once per day at 2 AM UTC. The coordinator fans out inference, validation,
+ and training-kickoff for every active pipeline. SKIP overlap prevents a new run
+ from starting if the previous day's coordinator is still executing.
+ """
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "autoresearch-coordinator",
+ CoordinatorWorkflowInput(),
+ id=_WORKFLOW_ID,
+ task_queue=settings.AUTORESEARCH_TASK_QUEUE,
+ # Longer than one pipeline's children (inference, then kickoff), shorter than a day, so a
+ # stuck coordinator ends before the next tick instead of making SKIP drop every later one.
+ execution_timeout=timedelta(hours=12),
+ ),
+ spec=ScheduleSpec(
+ calendars=[
+ ScheduleCalendarSpec(
+ comment="Daily at 2 AM UTC",
+ hour=[ScheduleRange(start=2, end=2)],
+ )
+ ]
+ ),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, _SCHEDULE_ID):
+ # Keep the live state, so a deploy does not resume a schedule an operator paused to stop spend.
+ description = await client.get_schedule_handle(_SCHEDULE_ID).describe()
+ schedule.state = description.schedule.state
+ await a_update_schedule(client, _SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, _SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.py
new file mode 100644
index 000000000000..0cb055b9f8b6
--- /dev/null
+++ b/products/autoresearch/backend/temporal/test_workflows.py
@@ -0,0 +1,312 @@
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import ActivityEnvironment
+
+from posthog.models import User
+
+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchTrainingRun
+from products.autoresearch.backend.temporal.workflows import (
+ InferenceWorkflowResult,
+ KickoffTrainingInput,
+ KickoffTrainingResult,
+ LoadActivePipelinesInput,
+ RunInferenceInput,
+ RunInferenceResult,
+ RunValidationInput,
+ RunValidationResult,
+ ValidationWorkflowResult,
+ activity_kickoff_training,
+ activity_load_active_pipelines,
+ activity_run_inference,
+ activity_run_validation,
+ evaluate_pipeline_outcome,
+)
+from products.autoresearch.backend.testing import TeamScopedTestMixin
+
+
+def _inference(status: str = "completed", error: Optional[str] = None) -> InferenceWorkflowResult:
+ return InferenceWorkflowResult(run_id="run-1", rows_scored=10, status=status, error=error)
+
+
+def _validation(status: str = "completed", error: Optional[str] = None) -> ValidationWorkflowResult:
+ return ValidationWorkflowResult(dates_validated=1, total_rows=10, status=status, error=error)
+
+
+def _kickoff(reason: str = "started", error: Optional[str] = None) -> KickoffTrainingResult:
+ return KickoffTrainingResult(kicked_off=reason == "started", reason=reason, error=error)
+
+
+class TestEvaluatePipelineOutcome(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("all_steps_succeed", _inference(), _validation(), _kickoff(), True, 0),
+ ("inference_raises", RuntimeError("boom"), _validation(), _kickoff(), False, 1),
+ ("inference_soft_fails", _inference(status="failed", error="oom"), _validation(), _kickoff(), False, 1),
+ ("validation_raises", _inference(), RuntimeError("boom"), _kickoff(), False, 1),
+ ("validation_soft_fails", _inference(), _validation(status="failed", error="boom"), _kickoff(), False, 1),
+ ("kickoff_raises", _inference(), _validation(), RuntimeError("boom"), False, 1),
+ ("kickoff_errors", _inference(), _validation(), _kickoff(reason="error", error="boom"), False, 1),
+ ("kickoff_no_creator", _inference(), _validation(), _kickoff(reason="no_creator", error="boom"), False, 1),
+ ("kickoff_skip_is_not_failure", _inference(), _validation(), _kickoff(reason="budget_exhausted"), True, 0),
+ ("not_due_runs_validation_only", None, _validation(), None, True, 0),
+ (
+ "multiple_failures_all_counted",
+ RuntimeError("boom"),
+ _validation(status="failed", error="boom"),
+ _kickoff(),
+ False,
+ 2,
+ ),
+ ]
+ )
+ def test_outcome_classification(
+ self,
+ _name: str,
+ inference: Any,
+ validation: Any,
+ kickoff: Any,
+ expected_succeeded: bool,
+ expected_error_count: int,
+ ) -> None:
+ outcome = evaluate_pipeline_outcome(
+ pipeline_id="pipeline-1", inference=inference, validation=validation, kickoff=kickoff
+ )
+ assert outcome.succeeded == expected_succeeded
+ assert len(outcome.errors) == expected_error_count
+
+
+@time_machine.travel("2026-09-11T12:00:00Z", tick=False)
+class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ access = patch("products.autoresearch.backend.temporal.workflows.has_autoresearch_access", return_value=True)
+ self.mock_access = access.start()
+ self.addCleanup(access.stop)
+ desktop = patch("products.autoresearch.backend.temporal.workflows.get_desktop_access_decision")
+ desktop.start().return_value.allowed = True
+ self.addCleanup(desktop.stop)
+ usage = patch("products.autoresearch.backend.temporal.workflows.task_run_usage_limited", return_value=False)
+ self.mock_usage_limited = usage.start()
+ self.addCleanup(usage.stop)
+
+ def _create_pipeline(self, **overrides: Any) -> AutoresearchPipeline:
+ params: dict[str, Any] = {
+ "team": self.team,
+ "created_by": self.user,
+ "name": "test pipeline",
+ "target_event": "$pageview",
+ "status": AutoresearchPipeline.Status.RUNNING,
+ "iteration_budget_remaining": 20,
+ **overrides,
+ }
+ return AutoresearchPipeline.objects.create(**params)
+
+ @parameterized.expand(
+ [
+ ("never_scored_is_due", AutoresearchPipeline.Status.RUNNING, 1, None, True),
+ ("overdue_is_due", AutoresearchPipeline.Status.RUNNING, 1, datetime(2026, 9, 9, 3), True),
+ (
+ "scored_yesterday_after_the_tick_is_due",
+ AutoresearchPipeline.Status.RUNNING,
+ 1,
+ datetime(2026, 9, 10, 23),
+ True,
+ ),
+ ("scored_today_validates_only", AutoresearchPipeline.Status.RUNNING, 1, datetime(2026, 9, 11, 11), False),
+ (
+ "within_cadence_window_validates_only",
+ AutoresearchPipeline.Status.RUNNING,
+ 7,
+ datetime(2026, 9, 8, 3),
+ False,
+ ),
+ ("past_cadence_window_is_due", AutoresearchPipeline.Status.RUNNING, 7, datetime(2026, 9, 4, 3), True),
+ ("converged_overdue_is_due", AutoresearchPipeline.Status.CONVERGED, 1, datetime(2026, 9, 9, 3), True),
+ ("paused_is_excluded", AutoresearchPipeline.Status.PAUSED, 1, None, None),
+ ]
+ )
+ def test_load_active_pipelines_honors_cadence(
+ self,
+ _name: str,
+ status: str,
+ cadence_days: int,
+ scored_at: Optional[datetime],
+ expected_score_due: Optional[bool],
+ ) -> None:
+ pipeline = self._create_pipeline(
+ status=status,
+ cadence_days=cadence_days,
+ last_scored_at=scored_at.replace(tzinfo=UTC) if scored_at else None,
+ )
+ result = activity_load_active_pipelines(LoadActivePipelinesInput())
+ score_due = {p.pipeline_id: p.score_due for p in result.pipelines}.get(str(pipeline.id))
+ assert score_due == expected_score_due
+
+ @parameterized.expand(
+ [
+ ("creator_lost_access", True, True, {}),
+ ("outside_the_rollout", False, False, {}),
+ ("organization_deactivated", False, True, {"is_active": False}),
+ ("organization_pending_deletion", False, True, {"is_pending_deletion": True}),
+ ]
+ )
+ def test_load_active_pipelines_excludes_pipelines_it_cannot_run(
+ self, _name: str, creator_lost_access: bool, in_rollout: bool, organization_fields: dict[str, bool]
+ ) -> None:
+ self.mock_access.return_value = in_rollout
+ for field, value in organization_fields.items():
+ setattr(self.organization, field, value)
+ self.organization.save()
+ if creator_lost_access:
+ pipeline = self._create_pipeline(created_by=User.objects.create(email="[email protected]"))
+ else:
+ pipeline = self._create_pipeline()
+
+ result = activity_load_active_pipelines(LoadActivePipelinesInput())
+
+ assert str(pipeline.id) not in [p.pipeline_id for p in result.pipelines]
+ pipeline.refresh_from_db()
+ expected = AutoresearchPipeline.Status.PAUSED if creator_lost_access else AutoresearchPipeline.Status.RUNNING
+ assert pipeline.status == expected
+
+ @parameterized.expand(
+ [
+ ("inference_paused", "inference", AutoresearchPipeline.Status.PAUSED, True),
+ ("validation_paused", "validation", AutoresearchPipeline.Status.PAUSED, True),
+ ("inference_rollout_withdrawn", "inference", AutoresearchPipeline.Status.RUNNING, False),
+ ("validation_rollout_withdrawn", "validation", AutoresearchPipeline.Status.RUNNING, False),
+ ]
+ )
+ @patch("products.autoresearch.backend.temporal.workflows.run_online_validation_for_pipeline")
+ @patch("products.autoresearch.backend.temporal.workflows.run_inference_for_pipeline")
+ def test_activities_skip_a_pipeline_the_sweep_can_no_longer_run(
+ self,
+ _name: str,
+ step: str,
+ status: str,
+ in_rollout: bool,
+ mock_inference: MagicMock,
+ mock_validation: MagicMock,
+ ) -> None:
+ pipeline = self._create_pipeline(status=status)
+ self.mock_access.return_value = in_rollout
+
+ result: RunInferenceResult | RunValidationResult
+ env = ActivityEnvironment()
+ if step == "inference":
+ result = env.run(
+ activity_run_inference,
+ RunInferenceInput(pipeline_id=str(pipeline.id), team_id=self.team.id, prediction_date="2026-09-11"),
+ )
+ else:
+ result = env.run(
+ activity_run_validation, RunValidationInput(pipeline_id=str(pipeline.id), team_id=self.team.id)
+ )
+
+ assert result.status == "skipped"
+ mock_inference.assert_not_called()
+ mock_validation.assert_not_called()
+
+ @patch("products.autoresearch.backend.temporal.workflows.run_inference_for_pipeline")
+ def test_inference_refuses_a_deleted_action_target(self, mock_inference: MagicMock) -> None:
+ pipeline = self._create_pipeline(target_definition={"type": "action", "action_id": 999999})
+ AutoresearchModel.objects.create(
+ pipeline=pipeline,
+ role=AutoresearchModel.Role.CHAMPION,
+ model_recipe={"stub": True},
+ recipe_hash="abc123",
+ holdout_score=0.75,
+ )
+
+ with self.assertRaises(ApplicationError):
+ ActivityEnvironment().run(
+ activity_run_inference,
+ RunInferenceInput(pipeline_id=str(pipeline.id), team_id=self.team.id, prediction_date="2026-09-11"),
+ )
+ mock_inference.assert_not_called()
+
+ @patch("products.autoresearch.backend.temporal.workflows.run_training")
+ def test_kickoff_passes_pipeline_creator_to_training(self, mock_run_training: MagicMock) -> None:
+ pipeline = self._create_pipeline()
+
+ result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))
+
+ assert result.kicked_off
+ assert result.reason == "started"
+ mock_run_training.assert_called_once()
+ assert mock_run_training.call_args.kwargs["user_id"] == self.user.id
+ pipeline.refresh_from_db()
+ assert pipeline.iteration_budget_remaining == 10
+
+ @patch("products.autoresearch.backend.temporal.workflows.run_training")
+ def test_kickoff_without_creator_fails_loudly_and_spends_no_budget(self, mock_run_training: MagicMock) -> None:
+ pipeline = self._create_pipeline(created_by=None)
+
+ result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))
+
+ assert not result.kicked_off
+ assert result.reason == "no_creator"
+ assert result.error
+ mock_run_training.assert_not_called()
+ pipeline.refresh_from_db()
+ assert pipeline.iteration_budget_remaining == 20
+
+ @parameterized.expand(
+ [
+ ("pending_run", AutoresearchTrainingRun.Status.PENDING, False, True, True, "already_running"),
+ ("run_ended_today", AutoresearchTrainingRun.Status.COMPLETED, False, True, True, "already_ran_today"),
+ ("tasks_usage_limited", None, True, True, True, "tasks_gated"),
+ ("rollout_withdrawn_since_discovery", None, False, False, True, "tasks_gated"),
+ ("organization_deactivated_since_discovery", None, False, True, False, "tasks_gated"),
+ ]
+ )
+ @patch("products.autoresearch.backend.temporal.workflows.run_training")
+ def test_kickoff_skips_without_spending_budget(
+ self,
+ _name: str,
+ run_status: Optional[str],
+ usage_limited: bool,
+ in_rollout: bool,
+ organization_active: bool,
+ expected_reason: str,
+ mock_run_training: MagicMock,
+ ) -> None:
+ pipeline = self._create_pipeline()
+ if run_status:
+ AutoresearchTrainingRun.objects.create(pipeline=pipeline, status=run_status, iteration_budget=10)
+ self.mock_usage_limited.return_value = usage_limited
+ self.mock_access.return_value = in_rollout
+ self.organization.is_active = organization_active
+ self.organization.save()
+
+ result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))
+
+ assert result.reason == expected_reason
+ mock_run_training.assert_not_called()
+ pipeline.refresh_from_db()
+ assert pipeline.iteration_budget_remaining == 20
+
+ @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:
+ pipeline = self._create_pipeline()
+ mock_run_training.side_effect = error
+
+ if isinstance(error, RuntimeError):
+ with self.assertRaises(RuntimeError):
+ activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))
+ else:
+ result = activity_kickoff_training(KickoffTrainingInput(pipeline_id=str(pipeline.id), team_id=self.team.id))
+ assert result.reason == "not_launchable"
+
+ pipeline.refresh_from_db()
+ assert pipeline.iteration_budget_remaining == 20
diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.py
new file mode 100644
index 000000000000..38ac88ec4f77
--- /dev/null
+++ b/products/autoresearch/backend/temporal/workflows.py
@@ -0,0 +1,678 @@
+"""
+Temporal workflows for autoresearch inference and online validation.
+
+Both workflows are regular Temporal workflows (not TaskRun/agent sandboxes) because
+scoring and validation are deterministic pipelines. Training runs through Task/TaskRun.
+
+Activities are synchronous — Temporal runs them in a thread pool, which is correct
+for Django ORM + HogQL queries. Workflows are async and only orchestrate activities.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable
+from dataclasses import field
+from datetime import date, timedelta
+from typing import TYPE_CHECKING, Optional, TypeVar, cast
+
+import structlog
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ApplicationError
+
+with workflow.unsafe.imports_passed_through():
+ import asyncio as _asyncio
+
+ from django.db import transaction
+ from django.utils import timezone as django_timezone
+
+ from products.actions.backend.models.action import Action
+ 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.sandbox import SandboxInferenceError, _resolve_acting_user
+ from products.autoresearch.backend.inference.scoring import run_inference_for_pipeline
+ from products.autoresearch.backend.models import (
+ AutoresearchModel,
+ AutoresearchPipeline,
+ AutoresearchRun,
+ AutoresearchTrainingRun,
+ )
+ from products.autoresearch.backend.training.runner import run_training
+ from products.tasks.backend.facade.access import get_desktop_access_decision
+ from products.tasks.backend.facade.usage import task_run_usage_limited
+
+from posthog.dataclasses import frozen
+from posthog.models.scoping import team_scope
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat_sync import HeartbeaterSync
+
+if TYPE_CHECKING:
+ from posthog.models import User
+
+logger = structlog.get_logger(__name__)
+
+_T = TypeVar("_T")
+
+# The statuses the daily sweep scores and validates. Each activity re-reads the status, so a
+# pipeline paused after the sweep loaded it is not scored.
+_LIVE_STATUSES = (AutoresearchPipeline.Status.RUNNING, AutoresearchPipeline.Status.CONVERGED)
+
+
+# ── I/O dataclasses ──────────────────────────────────────────────────────────
+
+
+@frozen
+class InferenceWorkflowInput:
+ pipeline_id: str
+ team_id: int
+ prediction_date: str # ISO date string, e.g. "2026-05-26"
+
+
+@frozen
+class InferenceWorkflowResult:
+ run_id: str
+ rows_scored: int
+ status: str
+ error: Optional[str] = None
+
+
+@frozen
+class RunInferenceInput:
+ pipeline_id: str
+ team_id: int
+ prediction_date: str # ISO date string
+
+
+@frozen
+class RunInferenceResult:
+ run_id: str
+ rows_scored: int
+ status: str
+ error: Optional[str] = None
+
+
+# ── Activities ───────────────────────────────────────────────────────────────
+
+
[email protected](name="autoresearch-inference.run_inference")
+def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:
+ """Score the inference population with the current champion and emit autoresearch_prediction events.
+
+ The champion is read here, not passed in, so a retry after a promotion during scoring scores
+ with the new champion instead of failing again on the archived one.
+ """
+ with HeartbeaterSync(), team_scope(inp.team_id):
+ pipeline = AutoresearchPipeline.objects.select_related("team__organization", "created_by").get(
+ pk=inp.pipeline_id
+ )
+ if pipeline.status not in _LIVE_STATUSES or _sweep_access_block(pipeline):
+ return RunInferenceResult(run_id="", rows_scored=0, status="skipped")
+ try:
+ # A bundle champion never resolves the target, so a deleted or stepless action would
+ # otherwise score and advance last_scored_at. Manual scoring refuses it the same way.
+ build_target_condition(
+ target_event=pipeline.target_event, target_definition=pipeline.target_definition, team=pipeline.team
+ )
+ except (ValueError, Action.DoesNotExist) as exc:
+ raise ApplicationError(f"The pipeline's target cannot be resolved: {exc}", non_retryable=True)
+ model = (
+ AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)
+ .order_by("-created_at")
+ .first()
+ )
+ if model is None:
+ raise ApplicationError(f"No champion model for pipeline {inp.pipeline_id}", non_retryable=True)
+ run = run_inference_for_pipeline(
+ pipeline=pipeline, model=model, prediction_date=date.fromisoformat(inp.prediction_date)
+ )
+ return RunInferenceResult(
+ run_id=str(run.pk),
+ rows_scored=run.rows_scored or 0,
+ status=run.status,
+ error=run.error or None,
+ )
+
+
+# ── Workflow ─────────────────────────────────────────────────────────────────
+
+# Scoring can take minutes for large populations.
+_SCORE_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))
+_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)
+
+
[email protected](name="autoresearch-inference")
+class AutoresearchInferenceWorkflow(PostHogWorkflow):
+ """
+ Temporal workflow that runs daily inference for one autoresearch pipeline.
+
+ One activity scores the inference population with the current champion and emits
+ autoresearch_prediction events. It delegates to products.autoresearch.backend.inference.scoring so the same
+ code is exercised by both the Temporal workflow and the local management
+ command (autoresearch_score).
+ """
+
+ inputs_cls = InferenceWorkflowInput
+
+ @workflow.run
+ async def run(self, inp: InferenceWorkflowInput) -> InferenceWorkflowResult:
+ workflow.logger.info(
+ "autoresearch_inference_workflow_start",
+ extra={"pipeline_id": inp.pipeline_id, "prediction_date": inp.prediction_date},
+ )
+
+ result = await workflow.execute_activity(
+ activity_run_inference,
+ RunInferenceInput(
+ pipeline_id=inp.pipeline_id,
+ team_id=inp.team_id,
+ prediction_date=inp.prediction_date,
+ ),
+ start_to_close_timeout=_SCORE_ATTEMPT_TIMEOUT,
+ heartbeat_timeout=_HEARTBEAT_TIMEOUT,
+ retry_policy=_SCORE_RETRY,
+ )
+
+ workflow.logger.info(
+ "autoresearch_inference_workflow_complete",
+ extra={
+ "pipeline_id": inp.pipeline_id,
+ "run_id": result.run_id,
+ "rows_scored": result.rows_scored,
+ "status": result.status,
+ },
+ )
+
+ return InferenceWorkflowResult(
+ run_id=result.run_id,
+ rows_scored=result.rows_scored,
+ status=result.status,
+ error=result.error,
+ )
+
+
+# ── Validation workflow I/O ───────────────────────────────────────────────────
+
+
+@frozen
+class ValidationWorkflowInput:
+ pipeline_id: str
+ team_id: int
+
+
+@frozen
+class ValidationWorkflowResult:
+ dates_validated: int
+ total_rows: int
+ status: str
+ error: Optional[str] = None
+
+
+@frozen
+class RunValidationInput:
+ pipeline_id: str
+ team_id: int
+
+
+@frozen
+class RunValidationResult:
+ dates_validated: int
+ total_rows: int
+ status: str
+ error: Optional[str] = None
+
+
+# ── Validation activities ─────────────────────────────────────────────────────
+
+# Validation does all its work (HogQL + sklearn) inside a single activity to
+# keep the Temporal payload small — we only return summary counts, not raw data.
+_VALIDATION_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))
+_VALIDATION_ATTEMPT_TIMEOUT = timedelta(hours=1)
+_VALIDATION_WORKFLOW_TIMEOUT = timedelta(hours=3)
+
+
[email protected](name="autoresearch-validation.run_validation")
+def activity_run_validation(inp: RunValidationInput) -> RunValidationResult:
+ """Find all matured unvalidated prediction dates and validate each one."""
+ with HeartbeaterSync(), team_scope(inp.team_id):
+ pipeline = AutoresearchPipeline.objects.select_related("team__organization", "created_by").get(
+ pk=inp.pipeline_id
+ )
+ if pipeline.status not in _LIVE_STATUSES or _sweep_access_block(pipeline):
+ return RunValidationResult(dates_validated=0, total_rows=0, status="skipped")
+ runs = run_online_validation_for_pipeline(pipeline)
+ # A per-date failure is recorded on its own run rather than raised, so inspect the
+ # statuses here. Reporting completed regardless would leave the retry policy unused
+ # even when every matured date failed; the coordinator isolates the failure per
+ # pipeline (it gathers with return_exceptions=True).
+ failed = [r for r in runs if r.status == AutoresearchRun.Status.FAILED]
+ if failed:
+ raise ApplicationError(
+ f"{len(failed)} of {len(runs)} validation dates failed: "
+ + "; ".join(str(r.error or "unknown")[:200] for r in failed[:3])
+ )
+ return RunValidationResult(
+ dates_validated=len(runs),
+ total_rows=sum(r.rows_scored or 0 for r in runs),
+ status="completed",
+ )
+
+
+# ── Validation workflow ───────────────────────────────────────────────────────
+
+
[email protected](name="autoresearch-validation")
+class AutoresearchValidationWorkflow(PostHogWorkflow):
+ """
+ Temporal workflow that runs online validation for one autoresearch pipeline.
+
+ Triggered daily (same cadence as inference) after inference has emitted
+ predictions. Finds all matured, unvalidated prediction dates and computes
+ realized AUC / Brier / ECE / lift@k per model. Updates AutoresearchModel
+ realized_score, calibration_error, and is_preliminary in Postgres.
+ """
+
+ inputs_cls = ValidationWorkflowInput
+
+ @workflow.run
+ async def run(self, inp: ValidationWorkflowInput) -> ValidationWorkflowResult:
+ workflow.logger.info("autoresearch_validation_workflow_start", extra={"pipeline_id": inp.pipeline_id})
+
+ result = await workflow.execute_activity(
+ activity_run_validation,
+ RunValidationInput(pipeline_id=inp.pipeline_id, team_id=inp.team_id),
+ start_to_close_timeout=_VALIDATION_ATTEMPT_TIMEOUT,
+ heartbeat_timeout=_HEARTBEAT_TIMEOUT,
+ retry_policy=_VALIDATION_RETRY,
+ )
+
+ workflow.logger.info(
+ "autoresearch_validation_workflow_complete",
+ extra={
+ "pipeline_id": inp.pipeline_id,
+ "dates_validated": result.dates_validated,
+ "total_rows": result.total_rows,
+ "status": result.status,
+ },
+ )
+
+ return ValidationWorkflowResult(
+ dates_validated=result.dates_validated,
+ total_rows=result.total_rows,
+ status=result.status,
+ error=result.error,
+ )
+
+
+# ── Coordinator workflow I/O ──────────────────────────────────────────────────
+
+
+@frozen
+class CoordinatorWorkflowInput:
+ # ISO date string; if omitted the workflow uses workflow.now()
+ run_date: Optional[str] = None
+
+
+@frozen
+class CoordinatorWorkflowResult:
+ pipelines_processed: int
+ pipelines_errored: int
+ status: str
+
+
+@frozen
+class LoadActivePipelinesInput:
+ pass
+
+
+@frozen
+class ActivePipeline:
+ pipeline_id: str
+ team_id: int
+ # Validation runs on every sweep; scoring and training kickoff only on a cadence day.
+ score_due: bool
+
+
+@frozen
+class LoadActivePipelinesResult:
+ pipelines: list[ActivePipeline]
+
+
+@frozen
+class KickoffTrainingInput:
+ pipeline_id: str
+ team_id: int
+
+
+@frozen
+class PipelineRunOutcome:
+ pipeline_id: str
+ succeeded: bool
+ errors: list[str] = field(default_factory=list)
+
+
+def evaluate_pipeline_outcome(
+ pipeline_id: str,
+ inference: InferenceWorkflowResult | BaseException | None,
+ validation: ValidationWorkflowResult | BaseException,
+ kickoff: KickoffTrainingResult | BaseException | None,
+) -> PipelineRunOutcome:
+ """Classify one pipeline's step results, treating soft-failed activity results as failures too.
+
+ ``None`` is a step the sweep did not start, because the pipeline was not due for scoring.
+ """
+ errors: list[str] = []
+
+ if inference is None:
+ pass
+ elif isinstance(inference, BaseException):
+ errors.append(f"inference: {inference}")
+ elif inference.status == "failed":
+ errors.append(f"inference: {inference.error or 'failed'}")
+
+ if isinstance(validation, BaseException):
+ errors.append(f"validation: {validation}")
+ elif validation.status == "failed":
+ errors.append(f"validation: {validation.error or 'failed'}")
+
+ if kickoff is None:
+ pass
+ elif isinstance(kickoff, BaseException):
+ errors.append(f"training kickoff: {kickoff}")
+ elif kickoff.error:
+ errors.append(f"training kickoff ({kickoff.reason}): {kickoff.error}")
+
+ return PipelineRunOutcome(pipeline_id=pipeline_id, succeeded=not errors, errors=errors)
+
+
+@frozen
+class KickoffTrainingResult:
+ kicked_off: bool
+ # "started" | "budget_exhausted" | "already_running" | "already_ran_today" | "not_eligible"
+ # | "tasks_gated" | "no_creator" | "not_launchable"
+ reason: str
+ error: Optional[str] = None
+ # Why an expected skip happened, without counting it as a failure.
+ detail: Optional[str] = None
+
+
+# ── Coordinator activities ────────────────────────────────────────────────────
+
+_COORDINATOR_RETRY = RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=5))
+_KICKOFF_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=10))
+
+
[email protected](name="autoresearch-coordinator.load_active_pipelines")
+def activity_load_active_pipelines(inp: LoadActivePipelinesInput) -> LoadActivePipelinesResult:
+ """Return every live pipeline the sweep runs, across every team, and whether each is due for scoring.
+
+ A deactivated organization, or one pending deletion, is left out. A pipeline whose creator no
+ longer has access to its team is paused here, before any run is
+ dispatched, because every scheduled query and training run acts as the creator. A pipeline
+ outside the ``autoresearch`` rollout is skipped but stays live, so it resumes when the rollout
+ reaches it again.
+ """
+ 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.
+ candidates = (
+ AutoresearchPipeline.objects.unscoped()
+ .filter(status__in=_LIVE_STATUSES)
+ # A null is_active counts as deactivated, as ActiveOrganizationPermission reads it.
+ .filter(team__organization__is_active=True)
+ .exclude(team__organization__is_pending_deletion=True)
+ .select_related("team", "created_by")
+ .order_by("created_at")
+ )
+ pipelines: list[ActivePipeline] = []
+ for pipeline in candidates:
+ try:
+ creator = _resolve_acting_user(team=pipeline.team, pipeline=pipeline, user=None)
+ except SandboxInferenceError as exc:
+ _pause_orphaned_pipeline(pipeline, reason=str(exc))
+ continue
+ if not has_autoresearch_access(
+ creator, team_id=pipeline.team_id, organization_id=str(pipeline.team.organization_id)
+ ):
+ continue
+ # By calendar day, because a run finishes some time after the 02:00 UTC tick and an
+ # elapsed-time comparison would skip the next day's tick.
+ last_scored = pipeline.last_scored_at.date() if pipeline.last_scored_at else None
+ pipelines.append(
+ ActivePipeline(
+ pipeline_id=str(pipeline.pk),
+ team_id=pipeline.team_id,
+ score_due=last_scored is None or (today - last_scored).days >= pipeline.cadence_days,
+ )
+ )
+ return LoadActivePipelinesResult(pipelines=pipelines)
+
+
+def _pause_orphaned_pipeline(pipeline: AutoresearchPipeline, *, reason: str) -> None:
+ # Conditional on the status read above, so a concurrent archive or pause keeps its outcome.
+ paused = (
+ AutoresearchPipeline.objects.unscoped()
+ .filter(pk=pipeline.pk, status=pipeline.status)
+ .update(status=AutoresearchPipeline.Status.PAUSED, updated_at=django_timezone.now())
+ )
+ if paused:
+ logger.warning("autoresearch_pipeline_paused_creator_lost_access", pipeline_id=str(pipeline.pk), reason=reason)
+
+
[email protected](name="autoresearch-coordinator.kickoff_training")
+def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResult:
+ """Spend part of the iteration budget on a new agent training run, if the pipeline is eligible.
+
+ The deduction, the run row, and its task binding commit together under the pipeline row lock,
+ as in the facade's ``start_training``. A manual start cannot interleave, and a failed launch
+ rolls the deduction back. A launch failure raises, so the activity retry applies.
+ """
+ # The gates can call out to billing and flags, so they run before the row lock is taken.
+ with team_scope(inp.team_id):
+ loaded = AutoresearchPipeline.objects.select_related("created_by", "team__organization").get(pk=inp.pipeline_id)
+ if loaded.created_by is not None and (gate := _tasks_gate(loaded)):
+ return KickoffTrainingResult(kicked_off=False, reason="tasks_gated", detail=gate)
+
+ with team_scope(inp.team_id), transaction.atomic():
+ pipeline = AutoresearchPipeline.objects.select_for_update().get(pk=inp.pipeline_id)
+
+ if pipeline.status != AutoresearchPipeline.Status.RUNNING:
+ return KickoffTrainingResult(kicked_off=False, reason="not_eligible")
+
+ # 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")
+
+ if AutoresearchTrainingRun.objects.filter(
+ pipeline=pipeline,
+ status__in=[AutoresearchTrainingRun.Status.PENDING, AutoresearchTrainingRun.Status.RUNNING],
+ ).exists():
+ return KickoffTrainingResult(kicked_off=False, reason="already_running")
+
+ # At most one scheduled run per UTC day. A retry after a lost activity response must not
+ # launch a second paid run once the first has already ended.
+ today = django_timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
+ if AutoresearchTrainingRun.objects.filter(pipeline=pipeline, created_at__gte=today).exists():
+ return KickoffTrainingResult(kicked_off=False, reason="already_ran_today")
+
+ # 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.
+ if pipeline.created_by_id is None:
+ error = f"Pipeline {inp.pipeline_id} has no creator; training kickoff requires created_by to own the task"
+ logger.error(
+ "autoresearch_kickoff_training_no_creator",
+ pipeline_id=inp.pipeline_id,
+ )
+ 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)
+ 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))
+ return KickoffTrainingResult(kicked_off=True, reason="started")
+
+
+def _sweep_access_block(pipeline: AutoresearchPipeline) -> str | None:
+ """Why the sweep may no longer act on this pipeline, or None.
+
+ Each activity checks again, because a child can start hours after discovery checked. Load the
+ pipeline with ``team__organization`` and ``created_by``.
+ """
+ organization = pipeline.team.organization
+ if not organization.is_active or organization.is_pending_deletion:
+ return "The organization is deactivated or pending deletion"
+ if pipeline.created_by is None or not has_autoresearch_access(
+ pipeline.created_by, team_id=pipeline.team_id, organization_id=str(organization.id)
+ ):
+ return "Outside the autoresearch rollout"
+ return None
+
+
+def _tasks_gate(pipeline: AutoresearchPipeline) -> str | None:
+ """Why the creator may not launch a paid Tasks sandbox now, or None. Mirrors the `/train` gates.
+
+ An unresolvable Desktop access decision raises, so the activity retries instead of launching.
+ """
+ if blocked := _sweep_access_block(pipeline):
+ return blocked
+ creator = cast("User", pipeline.created_by)
+ organization = pipeline.team.organization
+ team_id = pipeline.team_id
+ decision = get_desktop_access_decision(creator, organization)
+ if not decision.allowed:
+ return f"PostHog Desktop access: {decision.value}"
+ if task_run_usage_limited(creator, team_id):
+ return "The Tasks usage limit is reached"
+ return None
+
+
+# ── Coordinator workflow ──────────────────────────────────────────────────────
+
+
[email protected](name="autoresearch-coordinator")
+class AutoresearchCoordinatorWorkflow(PostHogWorkflow):
+ """
+ Daily coordinator that fans out inference, validation, and training kickoff
+ for every active autoresearch pipeline.
+
+ Triggered once per day by a Temporal schedule. For each pipeline whose status
+ is RUNNING or CONVERGED it starts AutoresearchValidationWorkflow, which validates every
+ matured prediction date. When the pipeline's cadence_days have elapsed since the calendar
+ day of last_scored_at it also starts:
+ - AutoresearchInferenceWorkflow — scores users, emits prediction events
+ - activity_kickoff_training — starts a new agent training run if eligible, once
+ inference ends, so a champion promoted mid-scoring cannot fail the scoring run
+
+ Per-pipeline failures — raised exceptions and
+ activity results that report a soft failure — are logged and counted in
+ pipelines_errored, but do not prevent other pipelines from running.
+ """
+
+ inputs_cls = CoordinatorWorkflowInput
+
+ @workflow.run
+ async def run(self, inp: CoordinatorWorkflowInput) -> CoordinatorWorkflowResult:
+ run_date = inp.run_date or workflow.now().strftime("%Y-%m-%d")
+
+ workflow.logger.info("autoresearch_coordinator_start", extra={"run_date": run_date})
+
+ active = await workflow.execute_activity(
+ activity_load_active_pipelines,
+ LoadActivePipelinesInput(),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=_COORDINATOR_RETRY,
+ )
+
+ if not active.pipelines:
+ workflow.logger.info("autoresearch_coordinator_no_active_pipelines")
+ return CoordinatorWorkflowResult(pipelines_processed=0, pipelines_errored=0, status="completed")
+
+ outcomes = await _asyncio.gather(
+ *[self._run_pipeline(pipeline, run_date) for pipeline in active.pipelines],
+ return_exceptions=True,
+ )
+
+ errored = sum(1 for o in outcomes if isinstance(o, BaseException) or not o.succeeded)
+ processed = len(outcomes) - errored
+
+ workflow.logger.info(
+ "autoresearch_coordinator_complete",
+ extra={"run_date": run_date, "pipelines_processed": processed, "pipelines_errored": errored},
+ )
+
+ return CoordinatorWorkflowResult(
+ pipelines_processed=processed,
+ pipelines_errored=errored,
+ status="completed" if errored == 0 else "partial",
+ )
+
+ async def _run_pipeline(self, pipeline: ActivePipeline, run_date: str) -> PipelineRunOutcome:
+ """Run validation, and on a cadence day inference then training kickoff, for one pipeline."""
+ pipeline_id = pipeline.pipeline_id
+ validation = _settle(
+ workflow.execute_child_workflow(
+ AutoresearchValidationWorkflow.run,
+ ValidationWorkflowInput(pipeline_id=pipeline_id, team_id=pipeline.team_id),
+ id=f"autoresearch-validation-{pipeline_id}-{run_date}",
+ execution_timeout=_VALIDATION_WORKFLOW_TIMEOUT,
+ )
+ )
+ inference_result: InferenceWorkflowResult | BaseException | None = None
+ kickoff_result: KickoffTrainingResult | BaseException | None = None
+ if pipeline.score_due:
+ validation_result, inference_result = await _asyncio.gather(
+ validation,
+ _settle(
+ workflow.execute_child_workflow(
+ AutoresearchInferenceWorkflow.run,
+ InferenceWorkflowInput(
+ pipeline_id=pipeline_id, team_id=pipeline.team_id, prediction_date=run_date
+ ),
+ id=f"autoresearch-inference-{pipeline_id}-{run_date}",
+ execution_timeout=_INFERENCE_WORKFLOW_TIMEOUT,
+ )
+ ),
+ )
+ kickoff_result = await _settle(
+ workflow.execute_activity(
+ activity_kickoff_training,
+ KickoffTrainingInput(pipeline_id=pipeline_id, team_id=pipeline.team_id),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=_KICKOFF_RETRY,
+ )
+ )
+ else:
+ validation_result = await validation
+ outcome = evaluate_pipeline_outcome(
+ pipeline_id=pipeline_id,
+ inference=inference_result,
+ validation=validation_result,
+ kickoff=kickoff_result,
+ )
+ for error in outcome.errors:
+ workflow.logger.warning(
+ "autoresearch_pipeline_step_failed",
+ extra={"pipeline_id": pipeline_id, "error": error},
+ )
+ return outcome
+
+
+async def _settle(awaitable: Awaitable[_T]) -> _T | BaseException:
+ """Return a step's exception instead of raising it, so one failed step does not end the others."""
+ try:
+ return await awaitable
+ except Exception as exc:
+ return exc
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index 536d8ee3c74b..9bf9547858e3 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -7,8 +7,6 @@ This is the expensive half of the product. A real run costs roughly a dollar in
The other half is `../inference/`, which consumes what this package produces and must never re-fit.
-This package landed ahead of one caller. `../temporal/` arrives in a later piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to it below describe where it will sit.
-
## What lives here
- `runner.py`