: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
feat(autoresearch): run score now in the background inference workflow (#110079)
posthog[bot]4b6333b136d1
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex 1201fd3ec249..9305770ec29a 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -11,10 +11,13 @@ filters on it. Business rules live in the modules behind this facade, not in theimport jsonimport base64+import asyncioimport hashlib+from datetime import timedeltafrom typing import Anyfrom uuid import UUID, uuid4+from django.conf import settingsfrom django.db import transactionfrom django.db.models import F, Prefetch, Qfrom django.utils import timezone as django_timezone@@ -704,15 +707,42 @@ 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+++def _running_inference_run(team_id: int, pipeline: AutoresearchPipeline) -> AutoresearchRun | None:+ return (+ AutoresearchRun.objects.for_team(team_id)+ .filter(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=AutoresearchRun.Status.RUNNING,+ started_at__gte=django_timezone.now() - _INFERENCE_RUN_STALE_AFTER,+ )+ .order_by("-started_at")+ .first()+ )++def score_pipeline(team_id: int, pipeline_id: str | UUID, *, user: User, allow_action_target: bool = True) -> Run:- """Score the inference population with the champion model and emit prediction events.+ """Start scoring the inference population with the champion model and return the running run.++ Scoring runs in ``AutoresearchInferenceWorkflow``, so the caller polls the returned run for its+ outcome. When an inference run for the pipeline is already running, this returns that run and+ starts nothing.``allow_action_target=False`` refuses an action target with ``InvalidTarget``: a recipe-onlychampion relabels on the action's steps, and a target-relative population selects on them.The target is frozen once a model exists, so this read needs no lock."""- # Scoring loads the inference sandbox, which imports pandas and pyarrow.- from ..inference.scoring import run_inference_for_pipeline # noqa: PLC0415+ # The scoring module imports pandas and pyarrow.+ from ..inference.scoring import ScoringWindow, create_inference_run # noqa: PLC0415pipeline = _pipeline_row(team_id, pipeline_id, live_only=True)if pipeline.status == AutoresearchPipeline.Status.PAUSED:@@ -728,10 +758,76 @@ def score_pipeline(team_id: int, pipeline_id: str | UUID, *, user: User, allow_a)if not champion:raise AutoresearchConflict("No champion model found. Run training first.")++ window = ScoringWindow.for_date()+ with transaction.atomic():+ # The row lock makes a second click wait for the first one's run row, then return it.+ AutoresearchPipeline.objects.for_team(team_id).select_for_update().get(pk=pipeline.pk)+ running = _running_inference_run(team_id, pipeline)+ if running:+ return _run_to_contract(running)+ run = create_inference_run(pipeline=pipeline, model=champion, window=window)+try:- return _run_to_contract(run_inference_for_pipeline(pipeline=pipeline, model=champion, user=user))- except Action.DoesNotExist:- raise AutoresearchConflict("The pipeline's target action no longer exists.")+ _start_inference_workflow(+ team_id=team_id,+ pipeline_id=str(pipeline.pk),+ prediction_date=window.prediction_date.isoformat(),+ run_id=str(run.pk),+ user_id=user.pk,+ )+ except _InferenceAlreadyStarted:+ # The daily sweep scores this date now, but its activity has not created its row yet.+ run.delete()+ running = _running_inference_run(team_id, pipeline)+ if running:+ return _run_to_contract(running)+ raise AutoresearchConflict("Scoring is already running for this model. Try again in a few minutes.")+ except Exception as exc:+ run.status = AutoresearchRun.Status.FAILED+ run.error = f"Could not start scoring: {exc}"[:2000]+ run.completed_at = django_timezone.now()+ run.save(update_fields=["status", "error", "completed_at"])+ raise+ return _run_to_contract(run)+++def _start_inference_workflow(+ *, team_id: int, pipeline_id: str, prediction_date: str, run_id: str, user_id: int+) -> None:+ # The Temporal client and the workflow module load only when a manual run starts.+ from temporalio.common import WorkflowIDReusePolicy # noqa: PLC0415+ from temporalio.exceptions import WorkflowAlreadyStartedError # noqa: PLC0415++ from posthog.temporal.common.client import sync_connect # noqa: PLC0415++ from ..temporal.workflows import ( # noqa: PLC0415+ _INFERENCE_WORKFLOW_TIMEOUT,+ AutoresearchInferenceWorkflow,+ InferenceWorkflowInput,+ inference_workflow_id,+ )++ client = sync_connect()+ try:+ asyncio.run(+ client.start_workflow(+ AutoresearchInferenceWorkflow.run,+ InferenceWorkflowInput(+ pipeline_id=pipeline_id,+ team_id=team_id,+ prediction_date=prediction_date,+ run_id=run_id,+ user_id=user_id,+ ),+ 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,+ )+ )+ except WorkflowAlreadyStartedError as exc:+ raise _InferenceAlreadyStarted() from excdef validate_pipeline_online(diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.pyindex 2ebb280a0f82..aa9ac74eba51 100644--- a/products/autoresearch/backend/inference/scoring.py+++ b/products/autoresearch/backend/inference/scoring.py@@ -189,11 +189,28 @@ class _EmitResult:score_distribution: dict[str, Any]+def create_inference_run(+ *, pipeline: AutoresearchPipeline, model: AutoresearchModel, window: ScoringWindow+) -> AutoresearchRun:+ return AutoresearchRun.objects.create(+ pipeline=pipeline,+ model=model,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=AutoresearchRun.Status.RUNNING,+ started_at=django_timezone.now(),+ # Online validation discovers matured dates from these two keys instead of scanning+ # the events table, validates against the horizon scored here rather than the+ # pipeline's current one, and waits for a run that is still scoring the date.+ metrics={"prediction_date": window.prediction_date.isoformat(), "horizon_days": pipeline.horizon_days},+ )++def run_inference_for_pipeline(pipeline: AutoresearchPipeline,model: AutoresearchModel,prediction_date: date | None = None,user: User | None = None,+ run: AutoresearchRun | None = None,) -> AutoresearchRun:"""Top-level inference entry point. Creates an AutoresearchRun, scores users,@@ -206,19 +223,19 @@ def run_inference_for_pipeline(``user`` is who HogQL applies access control for; it defaults to thepipeline's creator.++ ``run`` is a row the caller created before it dispatched the scoring, so the caller+ can return it at once. A retry of the same attempt passes the same row again."""window = ScoringWindow.for_date(prediction_date)- run = AutoresearchRun.objects.create(- pipeline=pipeline,- model=model,- run_type=AutoresearchRun.RunType.INFERENCE,- status=AutoresearchRun.Status.RUNNING,- started_at=django_timezone.now(),- # Online validation discovers matured dates from these two keys instead of scanning- # the events table, validates against the horizon scored here rather than the- # pipeline's current one, and waits for a run that is still scoring the date.- metrics={"prediction_date": window.prediction_date.isoformat(), "horizon_days": pipeline.horizon_days},- )+ if run is None:+ run = create_inference_run(pipeline=pipeline, model=model, window=window)+ else:+ run.model = model+ run.status = AutoresearchRun.Status.RUNNING+ run.error = ""+ run.completed_at = None+ run.save(update_fields=["model", "status", "error", "completed_at"])try:team = pipeline.teamdiff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.pyindex adf87de2dbbc..5149ef8bf31a 100644--- a/products/autoresearch/backend/presentation/views/views.py+++ b/products/autoresearch/backend/presentation/views/views.py@@ -495,7 +495,10 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixinresponses={200: OpenApiResponse(response=AutoresearchRunSerializer,- description="The created inference run. Check rows_scored and status.",+ description=(+ "The inference run, with status running. If a run for the pipeline is already running, "+ "this is that run. Poll the run until its status is completed or failed."+ ),),400: OpenApiResponse(description=(@@ -506,9 +509,11 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin},summary="Run inference (score users)",description=(- "Score the inference population using the champion model and emit autoresearch_prediction "- "events for each scored user, and sets the pipeline's output_person_property on each scored person. "- "In production this is triggered by the daily Temporal inference workflow."+ "Start scoring the inference population using the champion model. Scoring runs in the background: "+ "it emits autoresearch_prediction events for each scored user and sets the pipeline's "+ "output_person_property on each scored person. The response returns at once with the running run. "+ "A second request while a run is running returns that run and starts nothing. "+ "The daily Temporal inference workflow also scores each pipeline on its cadence."),)# Scoring sets the pipeline's output property on every scored person, so it needs person:write too.diff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.pyindex 0cb055b9f8b6..fbcc941e742c 100644--- a/products/autoresearch/backend/temporal/test_workflows.py+++ b/products/autoresearch/backend/temporal/test_workflows.py@@ -13,7 +13,12 @@ from temporalio.testing import ActivityEnvironmentfrom posthog.models import User-from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline, AutoresearchTrainingRun+from products.autoresearch.backend.models import (+ AutoresearchModel,+ AutoresearchPipeline,+ AutoresearchRun,+ AutoresearchTrainingRun,+)from products.autoresearch.backend.temporal.workflows import (InferenceWorkflowResult,KickoffTrainingInput,@@ -216,8 +221,11 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):mock_inference.assert_not_called()mock_validation.assert_not_called()+ @parameterized.expand([("scheduled", False), ("manual", True)])@patch("products.autoresearch.backend.temporal.workflows.run_inference_for_pipeline")- def test_inference_refuses_a_deleted_action_target(self, mock_inference: MagicMock) -> None:+ def test_inference_refuses_a_deleted_action_target(+ self, _name: str, manual: bool, mock_inference: MagicMock+ ) -> None:pipeline = self._create_pipeline(target_definition={"type": "action", "action_id": 999999})AutoresearchModel.objects.create(pipeline=pipeline,@@ -226,13 +234,32 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):recipe_hash="abc123",holdout_score=0.75,)+ run = (+ AutoresearchRun.objects.create(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=AutoresearchRun.Status.RUNNING,+ )+ if manual+ else None+ )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"),+ RunInferenceInput(+ pipeline_id=str(pipeline.id),+ team_id=self.team.id,+ prediction_date="2026-09-11",+ run_id=str(run.id) if run else None,+ user_id=self.user.id if run else None,+ ),)mock_inference.assert_not_called()+ if run is not None:+ run.refresh_from_db()+ assert run.status == AutoresearchRun.Status.FAILED+ assert "cannot be resolved" in run.error@patch("products.autoresearch.backend.temporal.workflows.run_training")def test_kickoff_passes_pipeline_creator_to_training(self, mock_run_training: MagicMock) -> None:diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.pyindex 38ac88ec4f77..3a93c0c1b403 100644--- a/products/autoresearch/backend/temporal/workflows.py+++ b/products/autoresearch/backend/temporal/workflows.py@@ -13,7 +13,7 @@ from __future__ import annotationsfrom collections.abc import Awaitablefrom dataclasses import fieldfrom datetime import date, timedelta-from typing import TYPE_CHECKING, Optional, TypeVar, cast+from typing import Optional, TypeVar, castimport structlogfrom temporalio import activity, workflow@@ -26,6 +26,8 @@ with workflow.unsafe.imports_passed_through():from django.db import transactionfrom django.utils import timezone as django_timezone+ from posthog.models.user import User+from products.actions.backend.models.action import Actionfrom products.autoresearch.backend.access import has_autoresearch_accessfrom products.autoresearch.backend.dataset.labeling import build_target_condition@@ -47,9 +49,6 @@ from posthog.models.scoping import team_scopefrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat_sync import HeartbeaterSync-if TYPE_CHECKING:- from posthog.models import User-logger = structlog.get_logger(__name__)_T = TypeVar("_T")@@ -67,6 +66,9 @@ class InferenceWorkflowInput:pipeline_id: strteam_id: intprediction_date: str # ISO date string, e.g. "2026-05-26"+ # Set by a manual "Score now": the run row the API already returned, and the user who asked.+ run_id: Optional[str] = None+ user_id: Optional[int] = None@frozen@@ -82,6 +84,8 @@ class RunInferenceInput:pipeline_id: strteam_id: intprediction_date: str # ISO date string+ run_id: Optional[str] = None+ user_id: Optional[int] = None@frozen@@ -101,30 +105,37 @@ def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:The champion is read here, not passed in, so a retry after a promotion during scoring scoreswith 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."""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):+ manual_run = AutoresearchRun.objects.filter(pk=inp.run_id, pipeline=pipeline).first() if inp.run_id else None+ if inp.run_id and manual_run is None:+ raise ApplicationError(f"Inference run {inp.run_id} does not exist", non_retryable=True)+ if manual_run is not None:+ # The API already applied the manual gates, so only a pause or archive since then stops it.+ if pipeline.status in (AutoresearchPipeline.Status.PAUSED, AutoresearchPipeline.Status.ARCHIVED):+ _fail_run(manual_run, "The pipeline was paused or archived before scoring started.")+ return RunInferenceResult(run_id=str(manual_run.pk), rows_scored=0, status="skipped")+ elif 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)+ user = _manual_run_user(inp.user_id)+ model = _champion_for_inference(pipeline)+ except ApplicationError as exc:+ if manual_run is not None:+ _fail_run(manual_run, str(exc))+ raiserun = run_inference_for_pipeline(- pipeline=pipeline, model=model, prediction_date=date.fromisoformat(inp.prediction_date)+ pipeline=pipeline,+ model=model,+ prediction_date=date.fromisoformat(inp.prediction_date),+ user=user,+ run=manual_run,)return RunInferenceResult(run_id=str(run.pk),@@ -134,6 +145,47 @@ def activity_run_inference(inp: RunInferenceInput) -> RunInferenceResult:)+def _champion_for_inference(pipeline: AutoresearchPipeline) -> AutoresearchModel:+ 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 {pipeline.pk}", non_retryable=True)+ return model+++def _manual_run_user(user_id: int | None) -> User | None:+ """The user who asked for a manual run, so HogQL applies their access and not the creator's."""+ if user_id is None:+ return None+ user = User.objects.filter(pk=user_id, is_active=True).first()+ if user is None:+ raise ApplicationError("The user who started this run no longer exists", non_retryable=True)+ return user+++def _fail_run(run: AutoresearchRun, error: str) -> None:+ run.status = AutoresearchRun.Status.FAILED+ run.error = error[:2000]+ run.completed_at = django_timezone.now()+ run.save(update_fields=["status", "error", "completed_at"])+++def inference_workflow_id(pipeline_id: str, prediction_date: str) -> str:+ """One inference workflow per pipeline and date, shared by the daily sweep and manual scoring."""+ return f"autoresearch-inference-{pipeline_id}-{prediction_date}"++# ── Workflow ─────────────────────────────────────────────────────────────────# Scoring can take minutes for large populations.@@ -171,6 +223,8 @@ class AutoresearchInferenceWorkflow(PostHogWorkflow):pipeline_id=inp.pipeline_id,team_id=inp.team_id,prediction_date=inp.prediction_date,+ run_id=inp.run_id,+ user_id=inp.user_id,),start_to_close_timeout=_SCORE_ATTEMPT_TIMEOUT,heartbeat_timeout=_HEARTBEAT_TIMEOUT,@@ -548,7 +602,7 @@ def _tasks_gate(pipeline: AutoresearchPipeline) -> str | None:"""if blocked := _sweep_access_block(pipeline):return blocked- creator = cast("User", pipeline.created_by)+ creator = cast(User, pipeline.created_by)organization = pipeline.team.organizationteam_id = pipeline.team_iddecision = get_desktop_access_decision(creator, organization)@@ -641,7 +695,7 @@ class AutoresearchCoordinatorWorkflow(PostHogWorkflow):InferenceWorkflowInput(pipeline_id=pipeline_id, team_id=pipeline.team_id, prediction_date=run_date),- id=f"autoresearch-inference-{pipeline_id}-{run_date}",+ id=inference_workflow_id(pipeline_id, run_date),execution_timeout=_INFERENCE_WORKFLOW_TIMEOUT,)),diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pyindex 96050ac0ddde..3f9e3216ed2f 100644--- a/products/autoresearch/backend/tests/test_api.py+++ b/products/autoresearch/backend/tests/test_api.py@@ -1,6 +1,7 @@import uuidimport base64import dataclasses+from datetime import timedeltafrom typing import Anyimport pytest@@ -10,6 +11,7 @@ from unittest.mock import MagicMock, patchfrom django.db import connectionfrom django.test import SimpleTestCasefrom django.test.utils import CaptureQueriesContext+from django.utils import timezone as django_timezonefrom parameterized import parameterizedfrom rest_framework import status@@ -68,6 +70,7 @@ MOCK_VALIDATION_ERROR = ValidationResult(_VIEWS = "products.autoresearch.backend.presentation.views.views"+_FACADE = "products.autoresearch.backend.facade.api"class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):@@ -357,10 +360,51 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):pipeline = self._make_trained_pipeline() if paused else self._make_pipeline()pipeline.status = AutoresearchPipeline.Status.PAUSED if paused else AutoresearchPipeline.Status.RUNNINGpipeline.save(update_fields=["status"])- with patch("products.autoresearch.backend.inference.scoring.run_inference_for_pipeline") as mock_score:+ with patch(f"{_FACADE}._start_inference_workflow") as mock_start:resp = self.client.post(f"{self.base_url}/{pipeline.id}/score/")assert resp.status_code == status.HTTP_400_BAD_REQUEST- mock_score.assert_not_called()+ mock_start.assert_not_called()+ assert not AutoresearchRun.objects.for_team(self.team.pk).filter(pipeline=pipeline).exists()++ @parameterized.expand(+ [+ ("nothing_running_starts_a_run", None, True),+ ("a_running_run_is_returned", timedelta(minutes=1), False),+ ("a_stale_running_run_does_not_block", timedelta(hours=6), True),+ ]+ )+ def test_score_starts_one_background_run(self, _name: str, running_age: timedelta | None, starts: bool):+ pipeline = self._make_trained_pipeline()+ existing = None+ if running_age is not None:+ existing = AutoresearchRun.objects.create(+ pipeline=pipeline,+ run_type=AutoresearchRun.RunType.INFERENCE,+ status=AutoresearchRun.Status.RUNNING,+ started_at=django_timezone.now() - running_age,+ )+ with patch(f"{_FACADE}._start_inference_workflow") as mock_start:+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/score/")+ assert resp.status_code == status.HTTP_200_OK+ assert resp.json()["status"] == "running"+ if not starts:+ assert existing is not None+ assert resp.json()["id"] == str(existing.id)+ mock_start.assert_not_called()+ return+ assert existing is None or resp.json()["id"] != str(existing.id)+ mock_start.assert_called_once()+ assert mock_start.call_args.kwargs["run_id"] == resp.json()["id"]+ assert mock_start.call_args.kwargs["user_id"] == self.user.id++ def test_score_fails_the_run_when_the_workflow_cannot_start(self):+ pipeline = self._make_trained_pipeline()+ with patch(f"{_FACADE}._start_inference_workflow", side_effect=RuntimeError("temporal down")):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/score/")+ assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ run = AutoresearchRun.objects.for_team(self.team.pk).get(pipeline=pipeline)+ assert run.status == AutoresearchRun.Status.FAILED+ assert "temporal down" in run.error# ─────────────────────────────────────── validate action ──────────────────────────────────────@@ -584,19 +628,13 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):assert resp.status_code == gate_statusmock_run_training.assert_not_called()- @parameterized.expand(- [- ("score", "products.autoresearch.backend.inference.scoring.run_inference_for_pipeline"),- (- "validate_online",- "products.autoresearch.backend.evaluation.online_validation.run_online_validation_for_pipeline",- ),- ]- )- def test_scoring_actions_with_a_deleted_target_action_return_400(self, path: str, runner: str):+ def test_validate_online_with_a_deleted_target_action_returns_400(self):pipeline = self._make_trained_pipeline()- with patch(runner, side_effect=Action.DoesNotExist):- resp = self.client.post(f"{self.base_url}/{pipeline.id}/{path}/")+ with patch(+ "products.autoresearch.backend.evaluation.online_validation.run_online_validation_for_pipeline",+ side_effect=Action.DoesNotExist,+ ):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/validate_online/")assert resp.status_code == status.HTTP_400_BAD_REQUEST@parameterized.expand(@@ -618,7 +656,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):action.steps_json = []action.save()with (- patch("products.autoresearch.backend.inference.scoring.run_inference_for_pipeline") as mock_score,+ patch(f"{_FACADE}._start_inference_workflow") as mock_score,patch("products.autoresearch.backend.evaluation.online_validation.run_online_validation_for_pipeline") as mock_validate,diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.test.tsindex d88b53e074c7..e14dde9edadd 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts@@ -5,20 +5,49 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { initKeaTests } from '~/test/init'-import { autoresearchPipelineLogic, trainingRunProgress } from './autoresearchPipelineLogic'-import { autoresearchModelsList, autoresearchRetrieve } from './generated/api'-import { AutoresearchTrainingRunApi, IterationTrailApi } from './generated/api.schemas'+import { SCORE_RUN_POLL_INTERVAL_MS, autoresearchPipelineLogic, trainingRunProgress } from './autoresearchPipelineLogic'+import {+ autoresearchModelsList,+ autoresearchRetrieve,+ autoresearchRunsList,+ autoresearchRunsRetrieve,+ autoresearchScoreCreate,+} from './generated/api'+import { AutoresearchRunApi, AutoresearchTrainingRunApi, IterationTrailApi } from './generated/api.schemas'jest.mock('./generated/api', () => ({autoresearchRetrieve: jest.fn(),autoresearchModelsList: jest.fn(),autoresearchTrainingRunsList: jest.fn(),autoresearchRunsList: jest.fn(),+ autoresearchRunsRetrieve: jest.fn(),+ autoresearchScoreCreate: jest.fn(),autoresearchSuggestionsList: jest.fn(),}))const mockRetrieve = autoresearchRetrieve as jest.Mockconst mockModelsList = autoresearchModelsList as jest.Mock+const mockRunsList = autoresearchRunsList as jest.Mock+const mockRunsRetrieve = autoresearchRunsRetrieve as jest.Mock+const mockScoreCreate = autoresearchScoreCreate as jest.Mock++function makeScoreRun(overrides: Partial<AutoresearchRunApi>): AutoresearchRunApi {+ const now = new Date().toISOString()+ return {+ id: 'score-run-1',+ pipeline: 'pipeline-1',+ model: 'champion',+ run_type: 'inference',+ status: 'running',+ rows_scored: null,+ metrics: {},+ error: '',+ started_at: now,+ completed_at: null,+ created_at: now,+ ...overrides,+ } as AutoresearchRunApi+}function makeRun(overrides: Partial<AutoresearchTrainingRunApi>): AutoresearchTrainingRunApi {return {@@ -82,6 +111,66 @@ describe('autoresearchPipelineLogic', () => {expect(mockRetrieve).toHaveBeenCalledTimes(1)})+ it('follows a background scoring run until it finishes, then stops polling', async () => {+ jest.clearAllMocks()+ jest.useFakeTimers()+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AUTORESEARCH], { [FEATURE_FLAGS.AUTORESEARCH]: true })+ mockRetrieve.mockResolvedValue({ id: 'pipeline-1', name: 'Model' })+ mockModelsList.mockResolvedValue({ results: [], next: null })+ mockRunsList.mockResolvedValue({ results: [], next: null })+ mockScoreCreate.mockResolvedValue(makeScoreRun({}))+ mockRunsRetrieve+ .mockResolvedValueOnce(makeScoreRun({}))+ .mockResolvedValueOnce(makeScoreRun({ status: 'completed', rows_scored: 8000 }))+ const logic = autoresearchPipelineLogic({ id: 'pipeline-1' })+ try {+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRunsSuccess'])++ await expectLogic(logic, () => logic.actions.scoreNow()).toDispatchActions(['scoreNowSuccess'])+ expect(logic.values.activeScoreRun?.id).toEqual('score-run-1')++ await expectLogic(logic, () => jest.advanceTimersByTime(SCORE_RUN_POLL_INTERVAL_MS)).toDispatchActions([+ 'pollScoreRun',+ ])+ expect(logic.values.activeScoreRun?.id).toEqual('score-run-1')++ await expectLogic(logic, () => jest.advanceTimersByTime(SCORE_RUN_POLL_INTERVAL_MS)).toDispatchActions([+ 'scoreRunFinished',+ ])+ expect(logic.values.activeScoreRun).toBeNull()+ expect(logic.cache.disposables.registry.has('scorePoll')).toBe(false)+ } finally {+ logic.unmount()+ jest.useRealTimers()+ }+ })++ it.each([+ ['resumes a run started a minute ago', 60 * 1000, 'score-run-1'],+ ['ignores a run that has been running past the stale cutoff', 6 * 60 * 60 * 1000, null],+ ])('%s when the page loads', async (_name, ageMs, expectedRunId) => {+ jest.clearAllMocks()+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AUTORESEARCH], { [FEATURE_FLAGS.AUTORESEARCH]: true })+ mockRetrieve.mockResolvedValue({ id: 'pipeline-1', name: 'Model' })+ mockModelsList.mockResolvedValue({ results: [], next: null })+ const startedAt = new Date(Date.now() - ageMs).toISOString()+ mockRunsList.mockResolvedValue({+ results: [makeScoreRun({ started_at: startedAt, created_at: startedAt })],+ next: null,+ })+ const logic = autoresearchPipelineLogic({ id: 'pipeline-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRunsSuccess'])+ expect(logic.values.activeScoreRun?.id ?? null).toEqual(expectedRunId)+ expect(logic.cache.disposables.registry.has('scorePoll')).toBe(expectedRunId !== null)+ logic.unmount()+ })+describe('trainingRunProgress', () => {it('derives progress from live iteration rows while the run is in flight', () => {// Persisted fields are only written at completion, so they read 0 / null here.diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.tsindex d21d1d120349..307c768e2a69 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts@@ -21,6 +21,7 @@ import {autoresearchResumeCreate,autoresearchRetrieve,autoresearchRunsList,+ autoresearchRunsRetrieve,autoresearchScoreCreate,autoresearchSuggestionsCreate,autoresearchSuggestionsList,@@ -56,6 +57,29 @@ function isPipelineTab(value: string | undefined): value is AutoresearchPipelinereturn value !== undefined && (AUTORESEARCH_PIPELINE_TABS as string[]).includes(value)}+/** How often the Score now button checks a running scoring run. */+export const SCORE_RUN_POLL_INTERVAL_MS = 5000++/** Matches the backend cutoff: a run still running after the workflow timeout lost its worker. */+export const SCORE_RUN_STALE_AFTER_MS = 5 * 60 * 60 * 1000++function isScoreRunInProgress(run: AutoresearchRunApi): boolean {+ return run.status === 'running' || run.status === 'pending'+}++/** The inference run that is scoring now, if any. Scoring runs in the background, so a reload resumes from it. */+function findRunningScoreRun(runs: AutoresearchRunApi[]): AutoresearchRunApi | null {+ const cutoff = Date.now() - SCORE_RUN_STALE_AFTER_MS+ return (+ runs.find(+ (r) =>+ r.run_type === 'inference' &&+ isScoreRunInProgress(r) &&+ new Date(r.started_at ?? r.created_at).getTime() >= cutoff+ ) ?? null+ )+}+/** One decile of the latest scoring run's predicted probabilities: `lower` ≤ p < `lower` + 0.1. *//** How far back the Predictions tab looks for the latest scoring batch, so it never scans the full history. */export const LATEST_BATCH_LOOKBACK_DAYS = 90@@ -177,6 +201,7 @@ export interface OnlinePerformanceRow {export interface autoresearchPipelineLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogiccurrentTeamId: number | null // teamLogic+ activeScoreRun: AutoresearchRunApi | nullactiveTab: AutoresearchPipelineTabartifactsByRun: Record<string, string[]>artifactsByRunLoading: boolean@@ -430,6 +455,9 @@ export interface autoresearchPipelineLogicActions {pipeline: AutoresearchPipelineApi | nullpayload?: any}+ pollScoreRun: () => {+ value: true+ }resumePipeline: () => anyresumePipelineFailure: (error: string,@@ -460,6 +488,12 @@ export interface autoresearchPipelineLogicActions {scoreResult: AutoresearchRunApi | nullpayload?: any}+ scoreRunFinished: (run: AutoresearchRunApi) => {+ run: AutoresearchRunApi+ }+ setActiveScoreRun: (run: AutoresearchRunApi | null) => {+ run: AutoresearchRunApi | null+ }setActiveTab: (tab: AutoresearchPipelineTab) => {tab: AutoresearchPipelineTab}@@ -469,6 +503,9 @@ export interface autoresearchPipelineLogicActions {setSuggestionPriority: (priority: CreateSuggestionPriorityEnumApi) => {priority: CreateSuggestionPriorityEnumApi}+ startScorePolling: () => {+ value: true+ }startTraining: () => anystartTrainingFailure: (error: string,@@ -570,6 +607,10 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([toggleRunArtifacts: (runId: string) => ({ runId }),setSuggestionDraft: (draft: string) => ({ draft }),setSuggestionPriority: (priority: CreateSuggestionPriorityEnumApi) => ({ priority }),+ setActiveScoreRun: (run: AutoresearchRunApi | null) => ({ run }),+ startScorePolling: true,+ pollScoreRun: true,+ scoreRunFinished: (run: AutoresearchRunApi) => ({ run }),}),reducers({detailRequested: [@@ -584,6 +625,15 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([setActiveTab: (_, { tab }) => tab,},],+ activeScoreRun: [+ null as AutoresearchRunApi | null,+ {+ setActiveScoreRun: (_, { run }) => run,+ scoreNowSuccess: (_, { scoreResult }) => (scoreResult?.status === 'running' ? scoreResult : null),+ loadRunsSuccess: (current, { runs }) => current ?? findRunningScoreRun(runs),+ scoreRunFinished: () => null,+ },+ ],expandedRunId: [null as string | null,{@@ -959,7 +1009,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([},],}),- listeners(({ actions, values, props }) => ({+ listeners(({ actions, values, props, cache }) => ({loadDetail: () => {actions.loadPipeline()actions.loadModels()@@ -1018,17 +1068,81 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([lemonToast.error('Could not resume the model')},scoreNowSuccess: ({ scoreResult }) => {- posthog.capture('autoresearch model scored', { pipeline_id: props.id })- actions.loadRuns()- actions.loadPipeline()- actions.loadProbabilityDistribution()- actions.loadDailyVolume()- const scored = scoreResult?.rows_scored- lemonToast.success(scored != null ? `Scored ${scored.toLocaleString()} users` : 'Scoring run started')+ if (!scoreResult) {+ return+ }+ posthog.capture('autoresearch model score started', { pipeline_id: props.id, run_id: scoreResult.id })+ if (scoreResult.status === 'running') {+ lemonToast.info('Scoring started. Predictions update when it finishes.')+ actions.startScorePolling()+ } else {+ actions.scoreRunFinished(scoreResult)+ }},- scoreNowFailure: () => {+ scoreNowFailure: ({ error }) => {posthog.capture('autoresearch model action failed', { action: 'score', pipeline_id: props.id })- lemonToast.error('Could not score users. Train a champion model first.')+ lemonToast.error(error ? `Could not start scoring. ${error}` : 'Could not start scoring. Try again.')+ },+ loadRunsSuccess: () => {+ // A run started before a reload, or by the daily schedule, is still followed to the end.+ if (values.activeScoreRun) {+ actions.startScorePolling()+ }+ },+ startScorePolling: () => {+ if (cache.disposables.registry.has('scorePoll')) {+ return+ }+ cache.disposables.add(() => {+ const timer = window.setInterval(() => actions.pollScoreRun(), SCORE_RUN_POLL_INTERVAL_MS)+ return () => clearInterval(timer)+ }, 'scorePoll')+ },+ pollScoreRun: async () => {+ const active = values.activeScoreRun+ if (!values.currentTeamId || !active) {+ cache.disposables.dispose('scorePoll')+ return+ }+ let run: AutoresearchRunApi+ try {+ run = await autoresearchRunsRetrieve(String(values.currentTeamId), props.id, active.id)+ } catch {+ // A failed check is retried on the next interval.+ return+ }+ if (isScoreRunInProgress(run)) {+ return+ }+ actions.scoreRunFinished(run)+ },+ scoreRunFinished: ({ run }) => {+ cache.disposables.dispose('scorePoll')+ actions.loadRuns()+ actions.loadPipeline()+ if (run.status === 'completed') {+ posthog.capture('autoresearch model scored', {+ pipeline_id: props.id,+ run_id: run.id,+ rows_scored: run.rows_scored,+ })+ actions.loadProbabilityDistribution()+ actions.loadDailyVolume()+ const scored = run.rows_scored ?? 0+ lemonToast.success(`Scored ${scored.toLocaleString()} users`)+ } else {+ posthog.capture('autoresearch model action failed', {+ action: 'score',+ stage: 'run',+ pipeline_id: props.id,+ run_id: run.id,+ })+ lemonToast.error(+ run.error+ ? `Scoring failed. ${run.error}`+ : 'Scoring failed. Try again, and contact support if it keeps happening.'+ )+ }},submitSuggestionSuccess: () => {posthog.capture('autoresearch model suggestion sent', { pipeline_id: props.id })diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.tsindex a9f4d838f8ad..0b0ba740b5c4 100644--- a/products/autoresearch/frontend/generated/api.ts+++ b/products/autoresearch/frontend/generated/api.ts@@ -792,7 +792,7 @@ export const getAutoresearchScoreCreateUrl = (projectId: string, id: string) =>}/**- * Score the inference population using the champion model and emit autoresearch_prediction events for each scored user, and sets the pipeline's output_person_property on each scored person. In production this is triggered by the daily Temporal inference workflow.+ * Start scoring the inference population using the champion model. Scoring runs in the background: it emits autoresearch_prediction events for each scored user and sets the pipeline's output_person_property on each scored person. The response returns at once with the running run. A second request while a run is running returns that run and starts nothing. The daily Temporal inference workflow also scores each pipeline on its cadence.* @summary Run inference (score users)*/export const autoresearchScoreCreate = async (diff --git a/products/autoresearch/frontend/pipeline/ScoreNowButton.tsx b/products/autoresearch/frontend/pipeline/ScoreNowButton.tsxindex 2dd98818d9ed..63b209534389 100644--- a/products/autoresearch/frontend/pipeline/ScoreNowButton.tsx+++ b/products/autoresearch/frontend/pipeline/ScoreNowButton.tsx@@ -3,12 +3,14 @@ import { useActions, useValues } from 'kea'import { IconRefresh } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'+import { dayjs } from 'lib/dayjs'+import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'import { AutoresearchModelRoleEnumApi } from '../generated/api.schemas'/** Score-now action, gated on a champion existing. Reused in the title bar and empty states. */export function ScoreNowButton(): JSX.Element | null {- const { pipeline, models, scoreResultLoading } = useValues(autoresearchPipelineLogic)+ const { pipeline, models, scoreResultLoading, activeScoreRun } = useValues(autoresearchPipelineLogic)const { scoreNow } = useActions(autoresearchPipelineLogic)const hasChampion = models.some((m) => m.role === AutoresearchModelRoleEnumApi.Champion)if (!pipeline || pipeline.status === 'archived') {@@ -21,7 +23,7 @@ export function ScoreNowButton(): JSX.Element | null {icon={<IconRefresh />}onClick={() => scoreNow()}data-attr="autoresearch-model-score"- loading={scoreResultLoading}+ loading={scoreResultLoading || !!activeScoreRun}disabledReason={pipeline.status === 'paused'? 'Resume the model to score it'@@ -30,7 +32,9 @@ export function ScoreNowButton(): JSX.Element | null {: 'Train a champion model first'}>- Score now+ {activeScoreRun+ ? `Scoring… started ${dayjs(activeScoreRun.started_at ?? activeScoreRun.created_at).format('HH:mm')}`+ : 'Score now'}</LemonButton>)}diff --git a/products/autoresearch/mcp/AGENTS.md b/products/autoresearch/mcp/AGENTS.mdindex 50187e2ad782..0c5c11300a64 100644--- a/products/autoresearch/mcp/AGENTS.md+++ b/products/autoresearch/mcp/AGENTS.md@@ -7,7 +7,7 @@ During a run, the sandbox agent has no other write path. It records iterations,## What lives here- `tools.yaml`- The whole surface: 21 enabled tools, `category: Autoresearch`, `feature: autoresearch`, `url_prefix: /autoresearch`. The family must stay at or below 25 tools: above that the exec tool's compact domain index splits it into sub-domains, and the serialized exec schema crosses the claude.ai registry cap (see `services/mcp/tests/unit/instructions-formatter-snapshot.test.ts`). Duplicative tools (`suggestions-retrieve`, `templates-list`, `validate-online-create`, `artifacts-delete-create`) are disabled rather than removed. `resolve-template-create` names every template key, so it replaces `templates-list` as the template entry point.+ The whole surface: 22 enabled tools, `category: Autoresearch`, `feature: autoresearch`, `url_prefix: /autoresearch`. The family must stay at or below 25 tools: above that the exec tool's compact domain index splits it into sub-domains, and the serialized exec schema crosses the claude.ai registry cap (see `services/mcp/tests/unit/instructions-formatter-snapshot.test.ts`). Duplicative tools (`suggestions-retrieve`, `templates-list`, `validate-online-create`, `artifacts-delete-create`) are disabled rather than removed. `resolve-template-create` names every template key, so it replaces `templates-list` as the template entry point.Each entry names an `operation` (an operation id from the OpenAPI spec), an `enabled` flag, required `scopes` (`autoresearch:read` / `autoresearch:write`, plus every extra scope the endpoint's `required_scopes` names, such as `query:read`: MCP hides a tool whose scopes the key lacks), `annotations` (`readOnly`, `destructive`, `idempotent`), and a `title` + `description`.Tool entries are scaffolded from the OpenAPI schema — `pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all` keeps the tool list and operation ids in sync. Everything editorial (description, title, `enrich_url`, `exclude_params`) is yours to write.@@ -24,7 +24,7 @@ Tool entries are scaffolded from the OpenAPI schema — `pnpm --filter=@posthog/`autoresearch-score-create` scores today's prediction date on demand, so an MCP caller does not have to wait for the daily run after a champion is promoted. The training sandbox never sees it, because `TRAINING_MCP_SCOPES` has no `person:write`.-Pipeline lifecycle (`archive`, `pause`, `resume`) and the inference-run list stay disabled: the UI covers the lifecycle, and nothing agent-driven needs the rest yet. Enabling one is a one-line change here.+Pipeline lifecycle (`archive`, `pause`, `resume`) stays disabled. The inference-run list is enabled so callers can check the status of background scoring.The split matters when you change a description. An agent-facing description is a **contract**: `autoresearch-training-runs-iterations-create` has to tell the agent what a valid `feature_sql` looks like, because the server will reject anything that is not a read-only `SELECT` keyed on `person_id` and the agent has no other way to learn that.diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yamlindex 4f3b01f1a601..21a898760612 100644--- a/products/autoresearch/mcp/tools.yaml+++ b/products/autoresearch/mcp/tools.yaml@@ -231,7 +231,7 @@ tools:- created_byautoresearch-runs-list:operation: autoresearch_runs_list- enabled: false+ enabled: truescopes:- autoresearch:readannotations:@@ -272,16 +272,16 @@ tools:idempotent: falsetitle: Run inference (score users)description: >- Score today's prediction date now with the pipeline's champion model, instead of waiting for the daily 02:00- UTC scoring run. Use it after autoresearch-train-create completes and promotes a champion. The call is- synchronous and returns the inference run with status and rows_scored. It emits one- 'autoresearch_prediction' event per scored user, with the score in '$autoresearch_p_y', and sets the- pipeline's output_person_property on each scored person. A manual score counts as that day's scoring, so the- daily run skips the pipeline until its next cadence date. Call it once per prediction date: a repeat call- scores the population again and can duplicate predictions. Returns 400 if the pipeline has no champion (run- autoresearch-train-create first), is paused, or its target cannot be resolved. A pipeline with an action- target also needs the action:read scope. After scoring, query predictions with execute-sql: SELECT- distinct_id, properties.$autoresearch_p_y FROM events WHERE event = 'autoresearch_prediction' AND+ Score today's prediction date with the champion model instead of waiting for the daily scoring run. Use+ autoresearch-train-create first if the pipeline has no champion. Scoring runs in the background and returns+ an inference run with status 'running'. If one is already running, returns that run without starting+ another. Poll autoresearch-runs-list for this run's ID until its status is 'completed' (rows_scored is then+ set) or 'failed' (error is then set). A manual score counts as today's scoring; the daily run skips the+ pipeline until its next cadence date. Do not start another run for the same prediction date: it can+ duplicate predictions. The pipeline must not be paused; an action target also needs the action:read scope.+ Each scored user gets an 'autoresearch_prediction' event with '$autoresearch_p_y' and a person property+ update. After the run completes, query predictions with execute-sql: SELECT distinct_id,+ properties.$autoresearch_p_y FROM events WHERE event = 'autoresearch_prediction' ANDproperties.$autoresearch_pipeline_id = '<pipeline_id>' ORDER BY properties.$autoresearch_p_y DESC LIMIT 50.feature_flag: autoresearchautoresearch-suggestions-create:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 388883bf52b2..a4cbf0722b67 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1194,8 +1194,23 @@},"feature_flag": "autoresearch"},+ "autoresearch-runs-list": {+ "description": "List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status to understand scoring history. run_type is 'inference' for daily scoring runs.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List inference runs",+ "title": "List inference runs",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },"autoresearch-score-create": {- "description": "Score today's prediction date now with the pipeline's champion model, instead of waiting for the daily 02:00 UTC scoring run. Use it after autoresearch-train-create completes and promotes a champion. The call is synchronous and returns the inference run with status and rows_scored. It emits one 'autoresearch_prediction' event per scored user, with the score in '$autoresearch_p_y', and sets the pipeline's output_person_property on each scored person. A manual score counts as that day's scoring, so the daily run skips the pipeline until its next cadence date. Call it once per prediction date: a repeat call scores the population again and can duplicate predictions. Returns 400 if the pipeline has no champion (run autoresearch-train-create first), is paused, or its target cannot be resolved. A pipeline with an action target also needs the action:read scope. After scoring, query predictions with execute-sql: SELECT distinct_id, properties.$autoresearch_p_y FROM events WHERE event = 'autoresearch_prediction' AND properties.$autoresearch_pipeline_id = '<pipeline_id>' ORDER BY properties.$autoresearch_p_y DESC LIMIT 50.",+ "description": "Score today's prediction date with the champion model instead of waiting for the daily scoring run. Use autoresearch-train-create first if the pipeline has no champion. Scoring runs in the background and returns an inference run with status 'running'. If one is already running, returns that run without starting another. Poll autoresearch-runs-list for this run's ID until its status is 'completed' (rows_scored is then set) or 'failed' (error is then set). A manual score counts as today's scoring; the daily run skips the pipeline until its next cadence date. Do not start another run for the same prediction date: it can duplicate predictions. The pipeline must not be paused; an action target also needs the action:read scope. Each scored user gets an 'autoresearch_prediction' event with '$autoresearch_p_y' and a person property update. After the run completes, query predictions with execute-sql: SELECT distinct_id, properties.$autoresearch_p_y FROM events WHERE event = 'autoresearch_prediction' AND properties.$autoresearch_pipeline_id = '<pipeline_id>' ORDER BY properties.$autoresearch_p_y DESC LIMIT 50.","category": "Autoresearch","feature": "autoresearch","summary": "Run inference (score users)",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 414aadd1a875..324236a35d3f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1209,8 +1209,23 @@},"feature_flag": "autoresearch"},+ "autoresearch-runs-list": {+ "description": "List inference and validation runs for a pipeline, ordered most recent first. Check rows_scored and status to understand scoring history. run_type is 'inference' for daily scoring runs.",+ "category": "Autoresearch",+ "feature": "autoresearch",+ "summary": "List inference runs",+ "title": "List inference runs",+ "required_scopes": ["autoresearch:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "autoresearch"+ },"autoresearch-score-create": {- "description": "Score today's prediction date now with the pipeline's champion model, instead of waiting for the daily 02:00 UTC scoring run. Use it after autoresearch-train-create completes and promotes a champion. The call is synchronous and returns the inference run with status and rows_scored. It emits one 'autoresearch_prediction' event per scored user, with the score in '$autoresearch_p_y', and sets the pipeline's output_person_property on each scored person. A manual score counts as that day's scoring, so the daily run skips the pipeline until its next cadence date. Call it once per prediction date: a repeat call scores the population again and can duplicate predictions. Returns 400 if the pipeline has no champion (run autoresearch-train-create first), is paused, or its target cannot be resolved. A pipeline with an action target also needs the action:read scope. After scoring, query predictions with execute-sql: SELECT distinct_id, properties.$autoresearch_p_y FROM events WHERE event = 'autoresearch_prediction' AND properties.$autoresearch_pipeline_id = '<pipeline_id>' ORDER BY properties.$autoresearch_p_y DESC LIMIT 50.",+ "description": "Score today's prediction date with the champion model instead of waiting for the daily scoring run. Use autoresearch-train-create first if the pipeline has no champion. Scoring runs in the background and returns an inference run with status 'running'. If one is already running, returns that run without starting another. Poll autoresearch-runs-list for this run's ID until its status is 'completed' (rows_scored is then set) or 'failed' (error is then set). A manual score counts as today's scoring; the daily run skips the pipeline until its next cadence date. Do not start another run for the same prediction date: it can duplicate predictions. The pipeline must not be paused; an action target also needs the action:read scope. Each scored user gets an 'autoresearch_prediction' event with '$autoresearch_p_y' and a person property update. After the run completes, query predictions with execute-sql: SELECT distinct_id, properties.$autoresearch_p_y FROM events WHERE event = 'autoresearch_prediction' AND properties.$autoresearch_pipeline_id = '<pipeline_id>' ORDER BY properties.$autoresearch_p_y DESC LIMIT 50.","category": "Autoresearch","feature": "autoresearch","summary": "Run inference (score users)",diff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.tsindex 87ab4f67c46f..4a88cc4ce81c 100644--- a/services/mcp/src/generated/autoresearch/api.ts+++ b/services/mcp/src/generated/autoresearch/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 21 enabled ops+ * PostHog API - MCP 22 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -186,6 +186,23 @@ export const AutoresearchModelsRetrieveParams = () => zod.object({),})+/**+ * List and retrieve inference and validation runs for a pipeline.+ */+export const AutoresearchRunsListParams = () => zod.object({+ pipeline_id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const AutoresearchRunsListQueryParams = () => zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})+/*** List steering suggestions for a pipeline, ordered most recent first. Check 'status' to see which have been picked up or acted on by the agent.* @summary List suggestions@@ -605,7 +622,7 @@ export const AutoresearchRetrieveParams = () => zod.object({})/**- * Score the inference population using the champion model and emit autoresearch_prediction events for each scored user, and sets the pipeline's output_person_property on each scored person. In production this is triggered by the daily Temporal inference workflow.+ * Start scoring the inference population using the champion model. Scoring runs in the background: it emits autoresearch_prediction events for each scored user and sets the pipeline's output_person_property on each scored person. The response returns at once with the running run. A second request while a run is running returns that run and starts nothing. The daily Temporal inference workflow also scores each pipeline on its cadence.* @summary Run inference (score users)*/export const AutoresearchScoreCreateParams = () => zod.object({diff --git a/services/mcp/src/tools/generated/autoresearch.ts b/services/mcp/src/tools/generated/autoresearch.tsindex 6a0d4628b2c6..ec707d4725a6 100644--- a/services/mcp/src/tools/generated/autoresearch.ts+++ b/services/mcp/src/tools/generated/autoresearch.ts@@ -262,6 +262,49 @@ const autoresearchRetrieve = (): ToolBase<},})+const AutoresearchRunsListSchema = () => {+ const AutoresearchRunsListParams = orvalSchemas.AutoresearchRunsListParams()+ const AutoresearchRunsListQueryParams = orvalSchemas.AutoresearchRunsListQueryParams()+ return AutoresearchRunsListParams.omit({ project_id: true }).extend(AutoresearchRunsListQueryParams.shape)+}++const autoresearchRunsList = (): ToolBase<+ ReturnType<typeof AutoresearchRunsListSchema>,+ WithPostHogUrl<Schemas.PaginatedAutoresearchRunList>+> => ({+ name: 'autoresearch-runs-list',+ schema: AutoresearchRunsListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchRunsListSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedAutoresearchRunList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.pipeline_id))}/runs/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'pipeline',+ 'model',+ 'run_type',+ 'status',+ 'rows_scored',+ 'error',+ 'started_at',+ 'completed_at',+ 'created_at',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(context, filtered, '/autoresearch')+ },+})+const AutoresearchScoreCreateSchema = () => {const AutoresearchScoreCreateParams = orvalSchemas.AutoresearchScoreCreateParams()return AutoresearchScoreCreateParams.omit({ project_id: true })@@ -788,6 +831,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'autoresearch-models-retrieve': autoresearchModelsRetrieve,'autoresearch-resolve-template-create': autoresearchResolveTemplateCreate,'autoresearch-retrieve': autoresearchRetrieve,+ 'autoresearch-runs-list': autoresearchRunsList,'autoresearch-score-create': autoresearchScoreCreate,'autoresearch-suggestions-create': autoresearchSuggestionsCreate,'autoresearch-suggestions-list': autoresearchSuggestionsList,