: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): add the pipeline lifecycle actions (21/22) (#89155)
Andrew Maguire236103991a50
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.pyindex 27f60e23e70d..18952875d42d 100644--- a/products/autoresearch/backend/dataset/labeling.py+++ b/products/autoresearch/backend/dataset/labeling.py@@ -540,7 +540,7 @@ def build_target_condition(# Scope the lookup to the pipeline's project so a foreign action id can't leak across# tenants. Actions live on the project's root team, so a team match would miss them# from any other environment of the same project.- action = Action.objects.get(id=action_id, team__project_id=team.project_id)+ action = Action.objects.get(id=action_id, team__project_id=team.project_id, deleted=False)if not action.steps:# action_to_expr compiles an empty step list to a constant true, which would label# every event in the horizon a positive.diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex e13f85ea2f58..f8278411eed7 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -342,16 +342,139 @@ def create_pipeline(team_id: int, *, fields: dict[str, Any], created_by: Any) ->return _pipeline_with_champion(row)+# Fields a trained model was fit against. The serializer freezes them once a model exists, and+# `update_pipeline` freezes them while a run is live, before the first model exists.+MODEL_DEFINING_FIELDS = (+ "target_event",+ "target_definition",+ "horizon_days",+ "training_lookback_days",+ "training_population",+ "inference_population",+)+++def _changes_model_definition(row: AutoresearchPipeline, fields: dict[str, Any]) -> bool:+ for name in MODEL_DEFINING_FIELDS:+ if name not in fields:+ continue+ current, new = getattr(row, name), fields[name]+ if name == "target_definition":+ # An empty stored definition and the normalized {"type": "event"} mean the same thing.+ current, new = current or {"type": "event"}, new or {"type": "event"}+ if current != new:+ return True+ return False++def update_pipeline(team_id: int, pipeline_id: str | UUID, *, fields: dict[str, Any]) -> Pipeline:- row = _pipeline_row(team_id, pipeline_id, live_only=True)- for key, value in fields.items():- setattr(row, key, value)- row.save()+ """Update a pipeline. Refuses a change to what it predicts while a run is live or once a model exists.++ The row lock serializes this with ``start_training``, so a run cannot start between the+ live-run check and the write, and a concurrent delete waits instead of racing the save.+ """+ pipeline_uuid = _as_uuid(pipeline_id)+ if pipeline_uuid is None:+ raise PipelineNotFound("Pipeline not found.")+ with transaction.atomic():+ try:+ row = (+ AutoresearchPipeline.objects.for_team(team_id)+ .exclude(status=AutoresearchPipeline.Status.ARCHIVED)+ .select_for_update()+ .get(pk=pipeline_uuid)+ )+ except AutoresearchPipeline.DoesNotExist:+ raise PipelineNotFound("Pipeline not found.")+ if _changes_model_definition(row, fields):+ if _has_live_training_run(team_id, row):+ raise AutoresearchConflict(+ "A training run is in progress. Wait for it to finish before changing what the pipeline predicts."+ )+ # Rechecked under the lock: a run can complete and create a model after the serializer's check.+ if AutoresearchModel.objects.for_team(team_id).filter(pipeline=row).exists():+ raise AutoresearchConflict(+ "What the pipeline predicts cannot change after a model has been trained. "+ "Create a new pipeline to predict a different target."+ )+ for key, value in fields.items():+ setattr(row, key, value)+ # Only the request's fields, so the write never touches a column the request did not set.+ row.save(update_fields=[*fields, "updated_at"])return _pipeline_with_champion(row)def delete_pipeline(team_id: int, pipeline_id: str | UUID) -> None:- _pipeline_row(team_id, pipeline_id, live_only=True).delete()+ """Delete a pipeline and its rows. Refused while a training run is live.++ The TaskRun is linked only by id, so a cascade would leave its paid sandbox running with+ nothing to report to.+ """+ pipeline_uuid = _as_uuid(pipeline_id)+ if pipeline_uuid is None:+ raise PipelineNotFound("Pipeline not found.")+ with transaction.atomic():+ try:+ row = (+ AutoresearchPipeline.objects.for_team(team_id)+ .exclude(status=AutoresearchPipeline.Status.ARCHIVED)+ .select_for_update()+ .get(pk=pipeline_uuid)+ )+ except AutoresearchPipeline.DoesNotExist:+ raise PipelineNotFound("Pipeline not found.")+ if _has_live_training_run(team_id, row):+ raise AutoresearchConflict("A training run is in progress. Wait for it to finish before deleting.")+ row.delete()+++# Pause and resume only toggle a live pipeline. A pipeline that has no champion yet (draft,+# bootstrapping) cannot pause, so resume can never mark an untrained pipeline live.+_STATUS_TRANSITION_SOURCES: dict[str, frozenset[str]] = {+ AutoresearchPipeline.Status.PAUSED: frozenset({AutoresearchPipeline.Status.RUNNING}),+ AutoresearchPipeline.Status.RUNNING: frozenset({AutoresearchPipeline.Status.PAUSED}),+}+++def set_pipeline_status(team_id: int, pipeline_id: str | UUID, *, status: str) -> Pipeline:+ """Archive, pause, or resume a pipeline.++ The row lock serializes this with a concurrent lifecycle change and with ``start_training``,+ so a stale read cannot revive an archived pipeline, and archival cannot race a new run.+ """+ pipeline_uuid = _as_uuid(pipeline_id)+ if pipeline_uuid is None:+ raise PipelineNotFound("Pipeline not found.")+ with transaction.atomic():+ try:+ row = (+ AutoresearchPipeline.objects.for_team(team_id)+ .exclude(status=AutoresearchPipeline.Status.ARCHIVED)+ .select_for_update()+ .get(pk=pipeline_uuid)+ )+ except AutoresearchPipeline.DoesNotExist:+ raise PipelineNotFound("Pipeline not found.")+ sources = _STATUS_TRANSITION_SOURCES.get(status)+ if sources is not None and row.status not in sources:+ raise AutoresearchConflict(f"Cannot change a {row.status} pipeline to {status}.")+ if status == AutoresearchPipeline.Status.ARCHIVED and _has_live_training_run(team_id, row):+ # Archival would leave the sandbox writing to, and promoting on, a pipeline nobody sees.+ raise AutoresearchConflict("A training run is in progress. Wait for it to finish before archiving.")+ row.status = status+ row.save(update_fields=["status", "updated_at"])+ return _pipeline_with_champion(row)+++def _has_live_training_run(team_id: int, pipeline: AutoresearchPipeline) -> bool:+ return (+ AutoresearchTrainingRun.objects.for_team(team_id)+ .filter(+ pipeline=pipeline,+ status__in=[AutoresearchTrainingRun.Status.PENDING, AutoresearchTrainingRun.Status.RUNNING],+ )+ .exists()+ )def pipeline_has_models(team_id: int, pipeline_id: str | UUID) -> bool:@@ -562,6 +685,78 @@ def get_run(team_id: int, run_id: str | UUID, *, pipeline_id: str | UUID | Nonereturn _run_to_contract(row) if row else None+def _require_resolvable_target(pipeline: AutoresearchPipeline) -> None:+ """Refuse an action target whose action was deleted or lost its steps since training.++ Not every scoring path resolves the action, so a stale one must be caught here rather than+ left to whichever runner happens to read it.+ """+ definition = pipeline.target_definition or {}+ if definition.get("type") != "action":+ return+ action_id = definition.get("action_id")+ action = (+ Action.objects.filter(id=action_id, team__project_id=pipeline.team.project_id, deleted=False).first()+ if isinstance(action_id, int)+ else None+ )+ if action is None or not action.get_step_events():+ raise AutoresearchConflict("The pipeline's target action no longer exists or has no steps.")+++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.++ ``allow_action_target=False`` refuses an action target with ``InvalidTarget``: a recipe-only+ champion 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++ pipeline = _pipeline_row(team_id, pipeline_id, live_only=True)+ if pipeline.status == AutoresearchPipeline.Status.PAUSED:+ raise AutoresearchConflict("The pipeline is paused. Resume it before scoring.")+ if not allow_action_target and pipeline.target_definition.get("type") == "action":+ raise InvalidTarget("An action target needs the action:read scope.")+ _require_resolvable_target(pipeline)+ champion = (+ AutoresearchModel.objects.for_team(team_id)+ .filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)+ .order_by("-created_at")+ .first()+ )+ if not champion:+ raise AutoresearchConflict("No champion model found. Run training first.")+ 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.")+++def validate_pipeline_online(+ team_id: int, pipeline_id: str | UUID, *, user: User, allow_action_target: bool = True+) -> list[Run]:+ """Score matured prediction dates against realized outcomes.++ ``allow_action_target=False`` refuses an action target with ``InvalidTarget``, because the+ realized labels come from the action's steps. The target is frozen once a model exists, so+ this read needs no lock.+ """+ # Online validation loads the inference sandbox, which imports pandas and pyarrow.+ from ..evaluation.online_validation import run_online_validation_for_pipeline # noqa: PLC0415++ pipeline = _pipeline_row(team_id, pipeline_id, live_only=True)+ if not allow_action_target and pipeline.target_definition.get("type") == "action":+ raise InvalidTarget("An action target needs the action:read scope.")+ _require_resolvable_target(pipeline)+ try:+ runs = run_online_validation_for_pipeline(pipeline=pipeline, user=user)+ except Action.DoesNotExist:+ raise AutoresearchConflict("The pipeline's target action no longer exists.")+ return [_run_to_contract(run) for run in runs]++# ── Training runs ──────────────────────────────────────────────────────────@@ -584,17 +779,91 @@ def get_training_run(return None-def open_training_run(team_id: int, pipeline_id: str | UUID, *, iteration_budget: int | None) -> TrainingRun:- """Open a run an external agent will record iterations against."""+def _claim_pipeline_for_training(team_id: int, pipeline_id: str | UUID) -> AutoresearchPipeline:+ """Lock a live pipeline that has no running training run. Call inside ``transaction.atomic()``.++ Every path that opens a run takes this lock, so two starts cannot both see no live run.+ """+ pipeline_uuid = _as_uuid(pipeline_id)+ if pipeline_uuid is None:+ raise PipelineNotFound("Pipeline not found.")+ try:+ pipeline = (+ AutoresearchPipeline.objects.for_team(team_id)+ .exclude(status=AutoresearchPipeline.Status.ARCHIVED)+ .select_for_update()+ .get(pk=pipeline_uuid)+ )+ except AutoresearchPipeline.DoesNotExist:+ raise PipelineNotFound("Pipeline not found.")+ if pipeline.status == AutoresearchPipeline.Status.PAUSED:+ raise AutoresearchConflict("The pipeline is paused. Resume it before training.")+ if _has_live_training_run(team_id, pipeline):+ raise AutoresearchConflict(+ "A training run is already in progress for this pipeline. "+ "Wait for it to finish, or check its status in the training runs list."+ )+ return pipeline+++def start_training(+ team_id: int,+ pipeline_id: str | UUID,+ *,+ iteration_budget: int | None,+ user_id: int,+ allow_action_target: bool = True,+) -> TrainingRun:+ """Start an asynchronous training run in a sandbox.++ Mirrors the scheduled coordinator's kickoff guard: the pipeline row is locked so a+ concurrent manual and scheduled start serialize, and a second live run is refused.+ ``run_training`` stays inside the lock so the new run row commits before a waiting+ request re-checks.++ ``allow_action_target=False`` refuses an action target with ``InvalidTarget``. The check+ reads the locked row, so a concurrent edit of the target cannot slip past it.+ """+ # The runner and the sandbox import pandas and pyarrow, so the router path loads them only here.+ from ..inference.sandbox import SandboxInferenceError # noqa: PLC0415+ from ..training.runner import run_training # noqa: PLC0415++ with transaction.atomic():+ pipeline = _claim_pipeline_for_training(team_id, pipeline_id)+ if not allow_action_target and pipeline.target_definition.get("type") == "action":+ raise InvalidTarget("An action target needs the action:read scope.")+ budget = iteration_budget or pipeline.iteration_budget+ try:+ training_run = run_training(pipeline=pipeline, iteration_budget=budget, user_id=user_id)+ except Action.DoesNotExist:+ raise AutoresearchConflict("The pipeline's target action no longer exists.")+ except (ValueError, SandboxInferenceError) as exc:+ # run_training refuses an unresolvable target or a departed creator before any write.+ raise AutoresearchConflict(str(exc)) from exc+ return _training_run_to_contract(training_run)+++def open_training_run(+ team_id: int, pipeline_id: str | UUID, *, iteration_budget: int | None, allow_action_target: bool = True+) -> TrainingRun:+ """Open a run an external agent will record iterations against.++ ``allow_action_target`` works as in ``start_training``: materializing features on the run+ labels on the action's steps, so the scope check reads the locked row.+ """pipeline = _pipeline_row(team_id, pipeline_id)if pipeline.status == AutoresearchPipeline.Status.ARCHIVED:raise AutoresearchConflict("Cannot open a training run on an archived pipeline.")- row = AutoresearchTrainingRun.objects.create(- pipeline=pipeline,- status=AutoresearchTrainingRun.Status.RUNNING,- iteration_budget=iteration_budget or pipeline.iteration_budget,- started_at=django_timezone.now(),- )+ with transaction.atomic():+ pipeline = _claim_pipeline_for_training(team_id, pipeline.pk)+ if not allow_action_target and pipeline.target_definition.get("type") == "action":+ raise InvalidTarget("An action target needs the action:read scope.")+ row = AutoresearchTrainingRun.objects.create(+ pipeline=pipeline,+ status=AutoresearchTrainingRun.Status.RUNNING,+ iteration_budget=iteration_budget or pipeline.iteration_budget,+ started_at=django_timezone.now(),+ )return _training_run_to_contract(row)diff --git a/products/autoresearch/backend/management/commands/autoresearch_train.py b/products/autoresearch/backend/management/commands/autoresearch_train.pyindex c867a63d6c1e..9f8a54548588 100644--- a/products/autoresearch/backend/management/commands/autoresearch_train.py+++ b/products/autoresearch/backend/management/commands/autoresearch_train.py@@ -32,11 +32,11 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.autoresearch.backend.access import has_autoresearch_access-from products.autoresearch.backend.facade.api import output_person_property_taken+from products.autoresearch.backend.facade.api import output_person_property_taken, start_training+from products.autoresearch.backend.facade.contracts import AutoresearchConflict, PipelineNotFoundfrom products.autoresearch.backend.management.scoping import resolve_pipelinefrom products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipelinefrom products.autoresearch.backend.presentation.views.serializers import validate_event_target-from products.autoresearch.backend.training.runner import run_trainingfrom products.autoresearch.backend.training.stub import run_stub_training# The bounds the API applies to the same fields.@@ -170,6 +170,7 @@ class Command(BaseCommand):self.stdout.write("")training_run = run_stub_training(pipeline=pipeline)+ run_id, run_status = training_run.pk, training_run.statuselse:user = self._team_user(pipeline.team, options["user_id"])user_id = user.pk@@ -183,10 +184,19 @@ class Command(BaseCommand):self.stdout.write(f" User ID : {user_id}")self.stdout.write("")- training_run = run_training(pipeline=pipeline, iteration_budget=iteration_budget, user_id=user_id)+ # The facade takes the same pipeline lock as the API, so a concurrent start cannot add a second live run.+ try:+ launched = start_training(+ pipeline.team_id, pipeline.pk, iteration_budget=iteration_budget, user_id=user_id+ )+ except (AutoresearchConflict, PipelineNotFound) as exc:+ # PipelineNotFound: a delete landed between resolving the pipeline and claiming it.+ raise CommandError(str(exc)) from exc++ run_id, run_status = launched.id, launched.status- self.stdout.write(f"Training run : {training_run.pk}")- self.stdout.write(f"Status : {training_run.status}")+ self.stdout.write(f"Training run : {run_id}")+ self.stdout.write(f"Status : {run_status}")if options["stub"]:self.stdout.write(f"Iterations : {training_run.iteration_count}")@@ -203,15 +213,15 @@ class Command(BaseCommand):self.stdout.write(f" Holdout AUC : {champion.holdout_score}")self.stdout.write(f" Preliminary : {champion.is_preliminary}")else:- task_run_id = training_run.task_run_id+ task_run_id = launched.task_run_idself.stdout.write(f"Task run : {task_run_id}")self.stdout.write("")self.stdout.write("Agent is running in the background. Monitor progress:")- self.stdout.write(f" tail -f /tmp/temporal-worker2.log | grep {str(training_run.pk)[:8]}")+ self.stdout.write(f" tail -f /tmp/temporal-worker2.log | grep {str(run_id)[:8]}")self.stdout.write("")self.stdout.write("Check training run status:")self.stdout.write(- f" python manage.py shell -c \"from products.autoresearch.backend.models import AutoresearchTrainingRun; r = AutoresearchTrainingRun.objects.get(pk='{training_run.pk}'); print(r.status, r.error)\""+ f" python manage.py shell -c \"from products.autoresearch.backend.models import AutoresearchTrainingRun; r = AutoresearchTrainingRun.objects.get(pk='{run_id}'); print(r.status, r.error)\"")self.stdout.write(f"\nNext step: python manage.py autoresearch_score --pipeline-id {pipeline.pk}")diff --git a/products/autoresearch/backend/management/test_autoresearch_train.py b/products/autoresearch/backend/management/test_autoresearch_train.pyindex 3bf64c5320e6..720ada06f9a9 100644--- a/products/autoresearch/backend/management/test_autoresearch_train.py+++ b/products/autoresearch/backend/management/test_autoresearch_train.py@@ -1,3 +1,5 @@+from contextlib import nullcontext+from posthog.test.base import BaseTestfrom unittest.mock import patch@@ -10,7 +12,8 @@ from posthog.models.organization import Organizationfrom posthog.models.scoping import team_scopefrom posthog.models.user import User-from products.autoresearch.backend.models import AutoresearchPipeline+from products.autoresearch.backend.facade.contracts import PipelineNotFound+from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchTrainingRunCOMMAND = "products.autoresearch.backend.management.commands.autoresearch_train"@@ -30,6 +33,8 @@ class TestAutoresearchTrainCommand(BaseTest):("zero_iterations", {"iterations": 0}),("flag_off", {"flag": False}),("malformed_pipeline_id", {"pipeline_id": "not-a-uuid"}),+ ("live_training_run", {"live_run": True}),+ ("deleted_during_launch", {"deleted_during_launch": True}),])def test_real_training_is_refused_before_launch(self, _name, case) -> None:@@ -42,10 +47,22 @@ class TestAutoresearchTrainCommand(BaseTest):with team_scope(self.team.id):self.pipeline.status = case["status"]self.pipeline.save()+ if case.get("live_run"):+ with team_scope(self.team.id):+ AutoresearchTrainingRun.objects.create(+ pipeline=self.pipeline, status=AutoresearchTrainingRun.Status.RUNNING, iteration_budget=5+ )with (patch(f"{COMMAND}.has_autoresearch_access", return_value=case.get("flag", True)),- patch(f"{COMMAND}.run_training") as run_training,+ patch("products.autoresearch.backend.training.runner.run_training") as run_training,+ # A delete that lands after the command resolved the pipeline, before the facade claims it.+ patch(+ "products.autoresearch.backend.facade.api._claim_pipeline_for_training",+ side_effect=PipelineNotFound("Pipeline not found."),+ )+ if case.get("deleted_during_launch")+ else nullcontext(),self.assertRaises(CommandError),):call_command(@@ -73,7 +90,7 @@ class TestAutoresearchTrainCommand(BaseTest):case = {"stub": True, **case}with (patch(f"{COMMAND}.has_autoresearch_access", return_value=False),- patch(f"{COMMAND}.run_training"),+ patch("products.autoresearch.backend.training.runner.run_training"),self.assertRaises(CommandError),):call_command("autoresearch_train", create=True, team_id=self.team.pk, **case)diff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.mdindex 8994e6e9e746..a5ba64c171ea 100644--- a/products/autoresearch/backend/presentation/AGENTS.md+++ b/products/autoresearch/backend/presentation/AGENTS.md@@ -5,13 +5,13 @@ The HTTP surface — and, because of how PostHog's codegen works, considerably mThese serializers are the source of truth for three downstream artifacts: the REST API itself, the generated frontend TypeScript types, and the 29 `autoresearch-*` MCP tools that the sandbox agent uses to drive its own training run.A vague `help_text` here becomes a vague tool description that a model has to guess at. Treat serializer annotations as agent-facing documentation, because they are.-The pipeline lifecycle actions (`train`, `score`, `validate-online`, `archive`, `pause`, `resume`) arrive with the last API piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), and the MCP tools at its end.+The `autoresearch-*` MCP tools that expose this API to the sandbox agent arrive at the end of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464).## What lives here- `views/views.py`Five viewsets, registered in `../routes.py` under `project_autoresearch_*` basenames and nested pipeline-first.- - `AutoresearchPipelineViewSet` — full CRUD plus the pre-create helpers `templates`, `resolve-template`, `validate`.+ - `AutoresearchPipelineViewSet` — full CRUD plus the lifecycle actions: `train`, `score`, `validate_online`, `archive`, `pause`, `resume`, and the pre-create helpers `templates`, `resolve-template`, `validate`.- `AutoresearchTrainingRunViewSet` — read plus create, and **the agent's entire write surface**: `iterations`, `materialize-features`, `complete`, `artifacts`, `artifacts/upload`, `artifacts/get`, `artifacts/delete`, plus `history`.- `AutoresearchModelViewSet`, `AutoresearchRunViewSet` — read-only.- `AutoresearchSuggestionViewSet` — human or agent hypotheses, plus `respond`.@@ -52,7 +52,7 @@ Consequences worth internalizing:- **Routing** — `../routes.py` (`register_routes`), nested pipeline → models / runs / training_runs / suggestions.- **Frontend types** — generated into `../../frontend/generated/` via drf-spectacular + Orval. Never hand-edit those; change the serializer and regenerate with `hogli build:openapi`.-- **Calls into** — `../training/` (complete), `../dataset/` (validate, templates, `resolve_target`).+- **Calls into** — `../training/` (train, complete), `../inference/` (score), `../evaluation/` (validate_online), `../dataset/` (validate, templates, `resolve_target`).## Declare the response when it differs from the requestdiff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.pyindex 13efa79cdb64..9896456fb4a0 100644--- a/products/autoresearch/backend/presentation/views/serializers.py+++ b/products/autoresearch/backend/presentation/views/serializers.py@@ -80,9 +80,13 @@ def validate_event_target(target_event: str, *, error_key: str) -> None:_validate_target_event_value(target_event, error_key=error_key)-def _require_action_scope(request: Request | None) -> None:+def has_action_scope(request: Request | None) -> bool:scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))- if scopes is not None and not any(scope in scopes for scope in _ACTION_READ_SCOPES):+ return scopes is None or any(scope in scopes for scope in _ACTION_READ_SCOPES)+++def require_action_scope(request: Request | None) -> None:+ if not has_action_scope(request):raise serializers.ValidationError({"target_definition": "An action target needs the action:read scope."})@@ -124,7 +128,7 @@ def resolve_target(raise serializers.ValidationError({"target_definition": "Action target requires a positive integer 'action_id'."})- _require_action_scope(request)+ require_action_scope(request)try:action_name, action_id = api.resolve_action_target(team.project_id, action_id)except (api.PipelineNotFound, api.InvalidTarget) as exc:@@ -650,14 +654,7 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):# Fields a trained model was fit against. Once any model exists they are frozen: scoring keeps# loading the trained artifact, so changing them would silently answer a different question.- MODEL_DEFINING_FIELDS = (- "target_event",- "target_definition",- "horizon_days",- "training_lookback_days",- "training_population",- "inference_population",- )+ MODEL_DEFINING_FIELDS = api.MODEL_DEFINING_FIELDS@propertydef _pipeline_id(self) -> Any:@@ -1276,6 +1273,15 @@ class ValidatePipelineResponseSerializer(serializers.Serializer):)+class StartTrainingRequestSerializer(serializers.Serializer):+ iteration_budget = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=500,+ help_text="Override the pipeline iteration budget for this training run.",+ )++# ── Agent-recorded training serializers ────────────────────────────────────diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.pyindex ab7d976d7800..94d1ca67950e 100644--- a/products/autoresearch/backend/presentation/views/views.py+++ b/products/autoresearch/backend/presentation/views/views.py@@ -14,9 +14,12 @@ from typing import Any, castimport structlogfrom drf_spectacular.utils import OpenApiResponse, extend_schema-from rest_framework import viewsets+from rest_framework import (+ serializers as drf_serializers,+ viewsets,+)from rest_framework.decorators import action-from rest_framework.exceptions import APIException, NotFound, ValidationError+from rest_framework.exceptions import APIException, NotFound, PermissionDenied, ValidationErrorfrom rest_framework.fields import emptyfrom rest_framework.permissions import BasePermissionfrom rest_framework.request import Request@@ -28,6 +31,7 @@ from posthog.api.documentation import PostHogAutoSchemafrom posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models.user import User+from posthog.oauth_provenance import is_sandbox_origin_requestfrom posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom products.autoresearch.backend.facade import api@@ -37,10 +41,12 @@ from products.autoresearch.backend.facade.contracts import (ArtifactStorageUnavailable,AutoresearchConflict,InvalidArtifactPath,+ InvalidTarget,PipelineNotFound,SuggestionNotFound,TrainingRunNotFound,)+from products.tasks.backend.facade.access import code_access_required_response, usage_limit_responsefrom .serializers import (ArtifactContentSerializer,@@ -64,12 +70,14 @@ from .serializers import (ResolvedTemplateSerializer,ResolveTemplateRequestSerializer,RespondToSuggestionSerializer,+ StartTrainingRequestSerializer,StoredArtifactSerializer,TemplateInfoSerializer,TrainingRunHistoryQuerySerializer,TrainingRunHistorySerializer,ValidatePipelineRequestSerializer,ValidatePipelineResponseSerializer,+ has_action_scope,resolve_target,validate_event_target,)@@ -170,6 +178,12 @@ def _pipeline_write_fields(validated: Any) -> dict[str, Any]:}+def _validated_with_sentinels(serializer: drf_serializers.BaseSerializer) -> Any:+ # On a partial update `DataclassSerializer.validated_data` swaps each `empty` sentinel for the+ # dataclass default, so reading it would write defaults over every field the PATCH left out.+ return drf_serializers.BaseSerializer.validated_data.fget(serializer) # type: ignore[attr-defined]++@extend_schema(tags=["autoresearch"])class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ModelViewSet):"""@@ -183,16 +197,35 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixinschema = FacadePathParamSchema()uuid_path_parameters = {"id": "A UUID string identifying this autoresearch pipeline."}scope_object = "autoresearch"- # Both HogQL actions also carry their own `required_scopes`, so a scoped token needs `query:read` too.+ # The HogQL actions also carry their own `required_scopes`, so a scoped token needs `query:read` too.scope_object_read_actions = ["list", "retrieve", "validate_definition", "list_templates", "resolve_template"]- scope_object_write_actions = ["create", "update", "partial_update", "destroy"]+ scope_object_write_actions = [+ "create",+ "update",+ "partial_update",+ "destroy",+ "start_training",+ "run_inference",+ "run_validation",+ "archive",+ "pause",+ "resume",+ ]permission_classes = [AutoresearchAccessPermission]serializer_class = AutoresearchPipelineSerializerqueryset = None # data is reached through the facade; declared for router/schema only+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:+ super().initial(request, *args, **kwargs)+ # A sandbox token carries team-wide autoresearch:write, and the training agent writes only+ # through its run, so a confused or injected agent must not reach pipeline writes. Tasks+ # applies the same rule to its own launches.+ if self.action in self.scope_object_write_actions and is_sandbox_origin_request(request):+ raise PermissionDenied("Pipelines cannot be changed from inside a sandbox.")+def get_throttles(self) -> list[BaseThrottle]:# Several unsampled ClickHouse scans per call, so a personal API key gets the ClickHouse budget.- if self.action in ("resolve_template", "validate_definition"):+ if self.action in ("resolve_template", "validate_definition", "run_inference", "run_validation"):return [ClickHouseBurstRateThrottle(), ClickHouseSustainedRateThrottle()]return super().get_throttles()@@ -245,21 +278,32 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixinpipeline = api.update_pipeline(self.team_id,self.kwargs["pk"],- fields=_pipeline_write_fields(serializer.validated_data),+ fields=_pipeline_write_fields(_validated_with_sentinels(serializer)),)except PipelineNotFound:raise NotFound("Pipeline not found.")+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from excreturn Response(AutoresearchPipelineSerializer(instance=pipeline).data)def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:kwargs["partial"] = Truereturn self.update(request, *args, **kwargs)+ @extend_schema(+ responses={+ 204: OpenApiResponse(description="The pipeline and its rows were deleted."),+ 400: OpenApiResponse(description="A training run is in progress for this pipeline."),+ 404: OpenApiResponse(description="The pipeline does not exist or is archived."),+ }+ )def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:try:api.delete_pipeline(self.team_id, self.kwargs["pk"])except PipelineNotFound:raise NotFound("Pipeline not found.")+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from excreturn Response(status=204)@extend_schema(@@ -363,6 +407,228 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin)return Response(ValidatePipelineResponseSerializer(instance=result).data)+ @validated_request(+ request_serializer=StartTrainingRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=AutoresearchTrainingRunSerializer,+ description="The created training run. Poll it through the training runs endpoint.",+ ),+ 400: OpenApiResponse(+ description=(+ "A training run is already in progress, the pipeline is paused, "+ "or the pipeline's target or creator is no longer valid."+ )+ ),+ 403: OpenApiResponse(+ description=(+ "The caller has no PostHog Desktop access, which cloud runs need, "+ "or the request comes from inside a sandbox."+ )+ ),+ 404: OpenApiResponse(description="The pipeline does not exist or is archived."),+ 429: OpenApiResponse(description="The team is over its PostHog Desktop usage limit."),+ 503: OpenApiResponse(description="PostHog Desktop access could not be checked. Try again."),+ },+ summary="Start a training run",+ description=(+ "Start an asynchronous training run for this pipeline. Creates a Task/TaskRun sandbox where "+ "the autoresearch agent iterates on features and models, and returns the run immediately with "+ "status 'running'. Poll the training run until it reaches a terminal status (completed or "+ "failed). A pipeline's first run has no champion until it completes and promotion runs; on a "+ "retrain the existing champion stays live and keeps scoring until a new one is promoted."+ ),+ )+ # The sandbox agent gets a token with these read scopes, so the caller must already hold them.+ @action(+ detail=True,+ methods=["post"],+ url_path="train",+ required_scopes=["autoresearch:write", "query:read", "insight:read"],+ )+ def start_training(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ # The run is a paid Tasks sandbox, so it takes the same entitlement and usage gates as a Task launch.+ if access_response := code_access_required_response(request, self.organization):+ return access_response+ if limit_response := usage_limit_response(request.user, self.team_id):+ return limit_response+ try:+ training_run = api.start_training(+ self.team_id,+ self.kwargs["pk"],+ iteration_budget=request.validated_data.get("iteration_budget"),+ user_id=cast(User, request.user).id,+ # Training labels on the action's steps, so an action target needs the same scope it took to set.+ allow_action_target=has_action_scope(request),+ )+ except PipelineNotFound:+ raise NotFound("Pipeline not found.")+ except InvalidTarget as exc:+ raise ValidationError({"target_definition": str(exc)}) from exc+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from exc+ return Response(AutoresearchTrainingRunSerializer(instance=training_run).data)++ @validated_request(+ responses={+ 200: OpenApiResponse(+ response=AutoresearchRunSerializer,+ description="The created inference run. Check rows_scored and status.",+ ),+ 400: OpenApiResponse(+ description=(+ "The pipeline has no champion model or is paused, or an action target needs the action:read scope."+ )+ ),+ 404: OpenApiResponse(description="The pipeline does not exist or is archived."),+ },+ 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."+ ),+ )+ # Scoring sets the pipeline's output property on every scored person, so it needs person:write too.+ @action(+ detail=True,+ methods=["post"],+ url_path="score",+ required_scopes=["autoresearch:write", "query:read", "person:write"],+ )+ def run_inference(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ try:+ run = api.score_pipeline(+ self.team_id,+ self.kwargs["pk"],+ user=cast(User, request.user),+ # Scoring can label or select on the action's steps, so an action target needs the action scope.+ allow_action_target=has_action_scope(request),+ )+ except PipelineNotFound:+ raise NotFound("Pipeline not found.")+ except InvalidTarget as exc:+ raise ValidationError({"target_definition": str(exc)}) from exc+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from exc+ return Response(AutoresearchRunSerializer(instance=run).data)++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response=AutoresearchRunSerializer(many=True),+ description=(+ "One AutoresearchRun per matured prediction date that was validated. "+ "Empty list when no prediction dates have matured yet."+ ),+ ),+ 400: OpenApiResponse(description="An action target needs the action:read scope."),+ 404: OpenApiResponse(description="The pipeline does not exist or is archived."),+ },+ summary="Run online validation",+ description=(+ "Validate predictions against realized outcomes for all matured prediction dates. "+ "A prediction date is matured when today >= prediction_date + horizon_days. "+ "Computes realized AUC, Brier score, calibration error (ECE), and lift@10/20 per model. "+ "Updates the model's realized_score, calibration_error, and clears the is_preliminary flag. "+ "Already-validated dates are skipped. In production this is triggered by the daily "+ "Temporal validation workflow after inference runs."+ ),+ )+ # pagination_class=None so the generated client types the response as a bare array of runs+ # (matching what this returns) rather than a paginated envelope.+ @action(+ detail=True,+ methods=["post"],+ url_path="validate_online",+ pagination_class=None,+ required_scopes=["autoresearch:write", "query:read"],+ )+ def run_validation(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ try:+ runs = api.validate_pipeline_online(+ self.team_id,+ self.kwargs["pk"],+ user=cast(User, request.user),+ # Realized labels come from the action's steps, so an action target needs the action scope.+ allow_action_target=has_action_scope(request),+ )+ except PipelineNotFound:+ raise NotFound("Pipeline not found.")+ except InvalidTarget as exc:+ raise ValidationError({"target_definition": str(exc)}) from exc+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from exc+ return Response(AutoresearchRunSerializer(instance=runs, many=True).data)++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response=AutoresearchPipelineSerializer,+ description="The pipeline after archiving.",+ ),+ 400: OpenApiResponse(description="A training run is in progress for this pipeline."),+ 404: OpenApiResponse(description="The pipeline does not exist or is archived."),+ },+ summary="Archive a pipeline",+ description=(+ "Soft-delete a pipeline. Stops daily scoring and training. Predictions and metrics are preserved. "+ "Refused while a training run is in progress."+ ),+ )+ @action(detail=True, methods=["post"], url_path="archive")+ def archive(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return self._set_status("archived")++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response=AutoresearchPipelineSerializer,+ description="The pipeline after pausing.",+ ),+ 400: OpenApiResponse(description="The pipeline is not running."),+ 404: OpenApiResponse(description="The pipeline does not exist or is archived."),+ },+ summary="Pause a pipeline",+ description=(+ "Pause daily scoring and training on a running pipeline. The pipeline can be resumed later. "+ "A training run already in progress finishes and can promote a new champion, "+ "but the pipeline stays paused and scores nobody until it is resumed."+ ),+ )+ @action(detail=True, methods=["post"], url_path="pause")+ def pause(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return self._set_status("paused")++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response=AutoresearchPipelineSerializer,+ description="The pipeline after resuming.",+ ),+ 400: OpenApiResponse(description="The pipeline is not paused."),+ 404: OpenApiResponse(description="The pipeline does not exist or is archived."),+ },+ summary="Resume a pipeline",+ description="Resume a paused pipeline. Daily scoring and training will restart on the next cadence tick.",+ )+ @action(detail=True, methods=["post"], url_path="resume")+ def resume(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return self._set_status("running")++ def _set_status(self, status: str) -> Response:+ try:+ pipeline = api.set_pipeline_status(self.team_id, self.kwargs["pk"], status=status)+ except PipelineNotFound:+ raise NotFound("Pipeline not found.")+ except AutoresearchConflict as exc:+ raise ValidationError(str(exc)) from exc+ return Response(AutoresearchPipelineSerializer(instance=pipeline).data)+@extend_schema(tags=["autoresearch"])class AutoresearchModelViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ReadOnlyModelViewSet):@@ -496,7 +762,12 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMiresponse=AutoresearchTrainingRunSerializer,description="The opened training run. Record iterations against its id, then call complete.",),- 400: OpenApiResponse(description="Pipeline is archived."),+ 400: OpenApiResponse(+ description=(+ "The pipeline is archived or paused, a run is already in progress, "+ "or an action target needs the action:read scope."+ )+ ),},summary="Open a training run",description=(@@ -506,14 +777,20 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMi),)def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ # The training agent works inside the run /train opened for it, so it never opens one itself.+ if is_sandbox_origin_request(request):+ raise PermissionDenied("Training runs cannot be opened from inside a sandbox.")try:training_run = api.open_training_run(self.team_id,_require_parent_pipeline_id(self),iteration_budget=request.validated_data.get("iteration_budget"),+ allow_action_target=has_action_scope(request),)except PipelineNotFound as exc:raise NotFound(str(exc)) from exc+ except InvalidTarget as exc:+ raise ValidationError({"target_definition": str(exc)}) from excexcept AutoresearchConflict as exc:raise ValidationError(str(exc)) from excreturn Response(AutoresearchTrainingRunSerializer(instance=training_run).data, status=201)diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pyindex f4b0ec05c92e..01a2c7c7305d 100644--- a/products/autoresearch/backend/tests/test_api.py+++ b/products/autoresearch/backend/tests/test_api.py@@ -1,5 +1,6 @@import uuidimport base64+import dataclassesfrom typing import Anyimport pytest@@ -12,6 +13,7 @@ from django.test.utils import CaptureQueriesContextfrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.response import Responsefrom posthog.models import Organization, Teamfrom posthog.storage.object_storage import ObjectStorageError@@ -19,6 +21,7 @@ from posthog.storage.object_storage import ObjectStorageErrorfrom products.actions.backend.models.action import Actionfrom products.autoresearch.backend.dataset.templates import TEMPLATESfrom products.autoresearch.backend.dataset.validation import ValidationResult, ValidationWarning+from products.autoresearch.backend.facade import apifrom products.autoresearch.backend.models import (AutoresearchIteration,AutoresearchModel,@@ -63,6 +66,9 @@ MOCK_VALIDATION_ERROR = ValidationResult()+_VIEWS = "products.autoresearch.backend.presentation.views.views"++class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):def setUp(self):super().setUp()@@ -73,6 +79,10 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):)self._flag_patcher.start()self.addCleanup(self._flag_patcher.stop)+ for gate in ("code_access_required_response", "usage_limit_response"):+ gate_patcher = patch(f"{_VIEWS}.{gate}", return_value=None)+ gate_patcher.start()+ self.addCleanup(gate_patcher.stop)def _make_pipeline(self, **kwargs) -> AutoresearchPipeline:defaults = {@@ -189,6 +199,107 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):# ──────────────────────────────────────── lifecycle actions ────────────────────────────────────+ def test_pause_and_resume_pipeline(self):+ pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.RUNNING)+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/pause/")+ assert resp.status_code == status.HTTP_200_OK+ assert resp.json()["status"] == "paused"++ resp2 = self.client.post(f"{self.base_url}/{pipeline.id}/resume/")+ assert resp2.status_code == status.HTTP_200_OK+ assert resp2.json()["status"] == "running"++ @parameterized.expand(+ [+ ("resume_running", "resume", AutoresearchPipeline.Status.RUNNING, None),+ ("pause_draft", "pause", AutoresearchPipeline.Status.DRAFT, None),+ ("pause_bootstrapping", "pause", AutoresearchPipeline.Status.BOOTSTRAPPING, None),+ ("archive_while_training", "archive", AutoresearchPipeline.Status.RUNNING, "running"),+ ("archive_while_pending", "archive", AutoresearchPipeline.Status.RUNNING, "pending"),+ ]+ )+ def test_refused_lifecycle_transition_returns_400(+ self, _name: str, verb: str, start: AutoresearchPipeline.Status, run_status: str | None+ ):+ pipeline = self._make_pipeline(status=start)+ if run_status:+ AutoresearchTrainingRun.objects.create(pipeline=pipeline, status=run_status, iteration_budget=50)+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/{verb}/")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ pipeline.refresh_from_db()+ assert pipeline.status == start++ @parameterized.expand(+ [+ ("pause", "post", "pause/"),+ ("resume", "post", "resume/"),+ ("archive", "post", "archive/"),+ ("score", "post", "score/"),+ ("validate_online", "post", "validate_online/"),+ ("patch", "patch", ""),+ ("delete", "delete", ""),+ ]+ )+ def test_sandbox_origin_cannot_change_a_pipeline(self, verb: str, method: str, suffix: str):+ start = AutoresearchPipeline.Status.PAUSED if verb == "resume" else AutoresearchPipeline.Status.RUNNING+ pipeline = self._make_pipeline(status=start)+ with patch(f"{_VIEWS}.is_sandbox_origin_request", return_value=True):+ resp = getattr(self.client, method)(f"{self.base_url}/{pipeline.id}/{suffix}", {"name": "x"}, format="json")+ assert resp.status_code == status.HTTP_403_FORBIDDEN+ pipeline.refresh_from_db()+ assert (pipeline.status, pipeline.name) == (start, "Test Pipeline")++ def test_sandbox_origin_cannot_open_a_training_run(self):+ pipeline = self._make_pipeline()+ with patch(f"{_VIEWS}.is_sandbox_origin_request", return_value=True):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/training_runs/", {}, format="json")+ assert resp.status_code == status.HTTP_403_FORBIDDEN+ assert not AutoresearchTrainingRun.objects.for_team(self.team.pk).filter(pipeline=pipeline).exists()++ def test_sandbox_origin_can_still_read_pipelines(self):+ pipeline = self._make_pipeline()+ with patch(f"{_VIEWS}.is_sandbox_origin_request", return_value=True):+ assert self.client.get(f"{self.base_url}/{pipeline.id}/").status_code == status.HTTP_200_OK++ @parameterized.expand([("idle", None, 204), ("training", "running", 400), ("pending", "pending", 400)])+ def test_delete_pipeline_is_refused_while_training(self, _name: str, run_status: str | None, expected: int):+ pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.RUNNING)+ if run_status:+ AutoresearchTrainingRun.objects.create(pipeline=pipeline, status=run_status, iteration_budget=50)+ resp = self.client.delete(f"{self.base_url}/{pipeline.id}/")+ assert resp.status_code == expected+ still_there = AutoresearchPipeline.objects.for_team(self.team.pk).filter(pk=pipeline.pk).exists()+ assert still_there == (expected != 204)++ def test_archive_pipeline(self):+ pipeline = self._make_pipeline()+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/archive/")+ assert resp.status_code == status.HTTP_200_OK+ assert resp.json()["status"] == "archived"+ pipeline.refresh_from_db()+ assert pipeline.status == AutoresearchPipeline.Status.ARCHIVED++ def test_train_archived_pipeline_returns_404(self):+ pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.ARCHIVED)+ # Archived pipelines are excluded from the queryset so the endpoint returns 404+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/train/")+ assert resp.status_code == status.HTTP_404_NOT_FOUND++ def test_score_archived_pipeline_returns_404(self):+ pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.ARCHIVED)+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/score/")+ assert resp.status_code == status.HTTP_404_NOT_FOUND++ @parameterized.expand([("no_champion", False), ("paused", True)])+ def test_score_refused_returns_400(self, _name: str, paused: bool):+ pipeline = self._make_trained_pipeline() if paused else self._make_pipeline()+ pipeline.status = AutoresearchPipeline.Status.PAUSED if paused else AutoresearchPipeline.Status.RUNNING+ pipeline.save(update_fields=["status"])+ with patch("products.autoresearch.backend.inference.scoring.run_inference_for_pipeline") as mock_score:+ 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()+# ─────────────────────────────────────── validate action ──────────────────────────────────────@patch(@@ -308,8 +419,200 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {with_action}")assert self.client.post(f"{self.base_url}/{path}", body, format="json").status_code == ok_status+ @parameterized.expand(+ [+ ("score_query", "score", ["autoresearch:write", "person:write"], ["query:read"]),+ ("score_person", "score", ["autoresearch:write", "query:read"], ["person:write"]),+ ("validate_online", "validate_online", ["autoresearch:write"], ["query:read"]),+ ("train", "train", ["autoresearch:write", "query:read"], ["insight:read"]),+ ]+ )+ def test_data_reading_actions_need_the_read_scopes(+ self, _name: str, path: str, partial: list[str], rest: list[str]+ ):+ missing = f"{self.base_url}/{uuid.uuid4()}/{path}/"+ self.client.logout()+ without = self.create_personal_api_key_with_scopes(partial)+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {without}")+ assert self.client.post(missing).status_code == status.HTTP_403_FORBIDDEN+ with_all = self.create_personal_api_key_with_scopes([*partial, *rest])+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {with_all}")+ assert self.client.post(missing).status_code == status.HTTP_404_NOT_FOUND+# ──────────────────────────────────────── train action ────────────────────────────────────────+ def test_start_training(self):+ pipeline = self._make_pipeline()++ # The run must not exist before the call: the endpoint rejects pipelines that+ # already have a live run, so the mock creates it the way run_training would.+ def _fake_run_training(*, pipeline: AutoresearchPipeline, iteration_budget: int, user_id: Any):+ return AutoresearchTrainingRun.objects.create(+ pipeline=pipeline,+ status=AutoresearchTrainingRun.Status.RUNNING,+ iteration_budget=iteration_budget,+ )++ with patch("products.autoresearch.backend.training.runner.run_training", side_effect=_fake_run_training):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/train/")++ assert resp.status_code == status.HTTP_200_OK+ data = resp.json()+ assert data["status"] == "running"++ @parameterized.expand(+ [+ ("train", status.HTTP_200_OK),+ ("training_runs", status.HTTP_201_CREATED),+ ("validate_online", status.HTTP_200_OK),+ # No champion, so the scoped caller gets past the scope check to the champion refusal.+ ("score", status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_action_target_actions_need_the_action_scope(self, path: str, ok_status: int):+ action = Action.objects.create(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])+ pipeline = self._make_pipeline(+ target_event="Uploaded", target_definition={"type": "action", "action_id": action.id}+ )+ scopes = ["autoresearch:write", "query:read", "insight:read", "person:write"]+ self.client.logout()+ without = self.create_personal_api_key_with_scopes(scopes)+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {without}")+ real_get_pipeline = api.get_pipeline+ # An unlocked read that still sees the old event target must not decide the scope check.+ with (+ patch(+ "products.autoresearch.backend.facade.api.get_pipeline",+ side_effect=lambda *a, **kw: dataclasses.replace(+ real_get_pipeline(*a, **kw), target_definition={"type": "event"}+ ),+ ),+ patch("products.autoresearch.backend.training.runner.run_training") as mock_run_training,+ ):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/{path}/")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ assert resp.json()["attr"] == "target_definition"+ mock_run_training.assert_not_called()+ assert not AutoresearchTrainingRun.objects.for_team(self.team.pk).filter(pipeline=pipeline).exists()++ with_action = self.create_personal_api_key_with_scopes([*scopes, "action:read"])+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {with_action}")+ with patch(+ "products.autoresearch.backend.training.runner.run_training",+ side_effect=lambda **kw: AutoresearchTrainingRun.objects.create(+ pipeline=kw["pipeline"], status=AutoresearchTrainingRun.Status.RUNNING, iteration_budget=5+ ),+ ):+ assert self.client.post(f"{self.base_url}/{pipeline.id}/{path}/").status_code == ok_status++ @parameterized.expand(+ [+ ("code_access_required_response", Response(status=403), status.HTTP_403_FORBIDDEN),+ ("usage_limit_response", Response(status=429), status.HTTP_429_TOO_MANY_REQUESTS),+ ("is_sandbox_origin_request", True, status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_start_training_is_refused_by_the_launch_gates(self, gate: str, gate_result: Any, gate_status: int):+ pipeline = self._make_pipeline()+ with (+ patch(f"{_VIEWS}.{gate}", return_value=gate_result),+ patch("products.autoresearch.backend.training.runner.run_training") as mock_run_training,+ ):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/train/")+ assert resp.status_code == gate_status+ mock_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):+ pipeline = self._make_trained_pipeline()+ with patch(runner, side_effect=Action.DoesNotExist):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/{path}/")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ @parameterized.expand(+ [+ ("score_deleted", "score", "deleted"),+ ("score_no_steps", "score", "no_steps"),+ ("validate_deleted", "validate_online", "deleted"),+ ("validate_no_steps", "validate_online", "no_steps"),+ ]+ )+ def test_scoring_actions_refuse_a_stale_target_action(self, _name: str, path: str, staleness: str):+ action = Action.objects.create(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])+ pipeline = self._make_trained_pipeline()+ pipeline.target_definition = {"type": "action", "action_id": action.id}+ pipeline.save(update_fields=["target_definition"])+ if staleness == "deleted":+ action.deleted = True+ else:+ action.steps_json = []+ action.save()+ with (+ patch("products.autoresearch.backend.inference.scoring.run_inference_for_pipeline") as mock_score,+ patch(+ "products.autoresearch.backend.evaluation.online_validation.run_online_validation_for_pipeline"+ ) as mock_validate,+ ):+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/{path}/")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ mock_score.assert_not_called()+ mock_validate.assert_not_called()++ def test_start_training_with_a_deleted_target_action_returns_400(self):+ action = Action.objects.create(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])+ pipeline = self._make_pipeline(+ target_event="Uploaded", target_definition={"type": "action", "action_id": action.id}+ )+ # The Action API soft-deletes, so the row stays behind.+ action.deleted = True+ action.save(update_fields=["deleted"])+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/train/")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ assert not AutoresearchTrainingRun.objects.for_team(self.team.pk).filter(pipeline=pipeline).exists()++ def test_patch_writes_only_the_fields_it_carries(self):+ pipeline = self._make_pipeline(+ status=AutoresearchPipeline.Status.RUNNING, target_event="uploaded_file", horizon_days=30+ )+ with CaptureQueriesContext(connection) as queries:+ resp = self.client.patch(f"{self.base_url}/{pipeline.id}/", {"name": "Renamed"}, format="json")+ assert resp.status_code == status.HTTP_200_OK+ updates = [+ q["sql"]+ for q in queries.captured_queries+ if q["sql"].startswith('UPDATE "autoresearch_autoresearchpipeline"')+ ]+ assert len(updates) == 1+ assert '"status"' not in updates[0].split(" WHERE ")[0]+ pipeline.refresh_from_db()+ assert (pipeline.name, pipeline.target_event, pipeline.horizon_days) == ("Renamed", "uploaded_file", 30)++ @parameterized.expand(+ [+ ("live_run", AutoresearchPipeline.Status.RUNNING, True),+ ("paused", AutoresearchPipeline.Status.PAUSED, False),+ ]+ )+ def test_start_training_refused_returns_400(self, _name: str, start: AutoresearchPipeline.Status, live_run: bool):+ pipeline = self._make_pipeline(status=start)+ if live_run:+ AutoresearchTrainingRun.objects.create(+ pipeline=pipeline, status=AutoresearchTrainingRun.Status.RUNNING, iteration_budget=50+ )+ with patch("products.autoresearch.backend.training.runner.run_training") as mock_run_training:+ resp = self.client.post(f"{self.base_url}/{pipeline.id}/train/")++ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ mock_run_training.assert_not_called()+# ──────────────────────────────────── update restrictions ─────────────────────────────────────def _make_trained_pipeline(self) -> AutoresearchPipeline:@@ -364,6 +667,34 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):resp = self.client.patch(f"{self.base_url}/{pipeline_id}/", {"name": "Renamed"}, format="json")assert resp.status_code == status.HTTP_404_NOT_FOUND+ def test_model_defining_fields_are_rechecked_against_models_under_the_lock(self):+ pipeline = self._make_trained_pipeline()+ # The serializer read happened before the first run finished and created the model.+ with patch(+ "products.autoresearch.backend.presentation.views.serializers.api.pipeline_has_models", return_value=False+ ):+ resp = self.client.patch(f"{self.base_url}/{pipeline.id}/", {"horizon_days": 30}, format="json")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ pipeline.refresh_from_db()+ assert pipeline.horizon_days == 7++ @parameterized.expand(+ [+ ("target_changed", {"horizon_days": 30}, status.HTTP_400_BAD_REQUEST),+ ("target_resubmitted", {"target_event": "$pageview"}, status.HTTP_200_OK),+ ("metadata", {"name": "Renamed"}, status.HTTP_200_OK),+ ]+ )+ def test_model_defining_fields_frozen_while_the_first_run_is_live(self, _name: str, payload: dict, expected: int):+ pipeline = self._make_pipeline()+ AutoresearchTrainingRun.objects.create(+ pipeline=pipeline, status=AutoresearchTrainingRun.Status.RUNNING, iteration_budget=50+ )+ resp = self.client.patch(f"{self.base_url}/{pipeline.id}/", payload, format="json")+ assert resp.status_code == expected+ pipeline.refresh_from_db()+ assert pipeline.horizon_days == 7+def test_target_editable_before_any_model_is_trained(self):pipeline = self._make_pipeline()resp = self.client.patch(f"{self.base_url}/{pipeline.id}/", {"horizon_days": 30}, format="json")diff --git a/products/autoresearch/backend/training/test_agent_recorded_training.py b/products/autoresearch/backend/training/test_agent_recorded_training.pyindex d97a550cf4f6..24ff54fe2be4 100644--- a/products/autoresearch/backend/training/test_agent_recorded_training.py+++ b/products/autoresearch/backend/training/test_agent_recorded_training.py@@ -99,6 +99,8 @@ class TestAgentRecordedTraining(TeamScopedTestMixin, APIBaseTest):run = AutoresearchTrainingRun.objects.get(pk=data["id"], team_id=self.team.pk)assert run.pipeline.pk == self.pipeline.pkassert run.started_at is not None+ second = self.client.post(f"{self.runs_url}/", {}, format="json")+ assert second.status_code == status.HTTP_400_BAD_REQUESTdef test_record_iteration_creates_row(self):run_id = self._open_run()diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.tsindex 3a2040ec2c98..2a5f531d1f81 100644--- a/products/autoresearch/frontend/generated/api.schemas.ts+++ b/products/autoresearch/frontend/generated/api.schemas.ts@@ -1315,6 +1315,15 @@ export interface PatchedAutoresearchPipelineCreateApi {output_person_property?: string}+export interface StartTrainingRequestApi {+ /**+ * Override the pipeline iteration budget for this training run.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number+}+/*** * `likely_active_soon` - Likely Active Soon* * `at_risk_of_inactivity` - At Risk Of Inactivitydiff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.tsindex 1882febde97b..a9b28472b93b 100644--- a/products/autoresearch/frontend/generated/api.ts+++ b/products/autoresearch/frontend/generated/api.ts@@ -42,6 +42,7 @@ import type {ResolveTemplateRequestApi,ResolvedTemplateApi,RespondToSuggestionApi,+ StartTrainingRequestApi,StoredArtifactApi,TemplateInfoApi,TrainingRunHistoryApi,@@ -729,6 +730,123 @@ export const autoresearchDestroy = async (projectId: string, id: string, options})}+export const getAutoresearchArchiveCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/archive/`+}++/**+ * Soft-delete a pipeline. Stops daily scoring and training. Predictions and metrics are preserved. Refused while a training run is in progress.+ * @summary Archive a pipeline+ */+export const autoresearchArchiveCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AutoresearchPipelineApi> => {+ return apiMutator<AutoresearchPipelineApi>(getAutoresearchArchiveCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getAutoresearchPauseCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/pause/`+}++/**+ * Pause daily scoring and training on a running pipeline. The pipeline can be resumed later. A training run already in progress finishes and can promote a new champion, but the pipeline stays paused and scores nobody until it is resumed.+ * @summary Pause a pipeline+ */+export const autoresearchPauseCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AutoresearchPipelineApi> => {+ return apiMutator<AutoresearchPipelineApi>(getAutoresearchPauseCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getAutoresearchResumeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/resume/`+}++/**+ * Resume a paused pipeline. Daily scoring and training will restart on the next cadence tick.+ * @summary Resume a pipeline+ */+export const autoresearchResumeCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AutoresearchPipelineApi> => {+ return apiMutator<AutoresearchPipelineApi>(getAutoresearchResumeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getAutoresearchScoreCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/score/`+}++/**+ * 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.+ * @summary Run inference (score users)+ */+export const autoresearchScoreCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AutoresearchRunApi> => {+ return apiMutator<AutoresearchRunApi>(getAutoresearchScoreCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getAutoresearchTrainCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/train/`+}++/**+ * Start an asynchronous training run for this pipeline. Creates a Task/TaskRun sandbox where the autoresearch agent iterates on features and models, and returns the run immediately with status 'running'. Poll the training run until it reaches a terminal status (completed or failed). A pipeline's first run has no champion until it completes and promotion runs; on a retrain the existing champion stays live and keeps scoring until a new one is promoted.+ * @summary Start a training run+ */+export const autoresearchTrainCreate = async (+ projectId: string,+ id: string,+ startTrainingRequestApi?: StartTrainingRequestApi,+ options?: RequestInit+): Promise<AutoresearchTrainingRunApi> => {+ return apiMutator<AutoresearchTrainingRunApi>(getAutoresearchTrainCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(startTrainingRequestApi),+ })+}++export const getAutoresearchValidateOnlineCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/validate_online/`+}++/**+ * Validate predictions against realized outcomes for all matured prediction dates. A prediction date is matured when today >= prediction_date + horizon_days. Computes realized AUC, Brier score, calibration error (ECE), and lift@10/20 per model. Updates the model's realized_score, calibration_error, and clears the is_preliminary flag. Already-validated dates are skipped. In production this is triggered by the daily Temporal validation workflow after inference runs.+ * @summary Run online validation+ */+export const autoresearchValidateOnlineCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AutoresearchRunApi[]> => {+ return apiMutator<AutoresearchRunApi[]>(getAutoresearchValidateOnlineCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getAutoresearchResolveTemplateCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/autoresearch/resolve-template/`}diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.tsindex 10cd271427bb..0ac7f62e138a 100644--- a/products/autoresearch/frontend/generated/api.zod.ts+++ b/products/autoresearch/frontend/generated/api.zod.ts@@ -607,6 +607,21 @@ export const AutoresearchPartialUpdateBody = /* @__PURE__ */ zod.object({),})+/**+ * Start an asynchronous training run for this pipeline. Creates a Task/TaskRun sandbox where the autoresearch agent iterates on features and models, and returns the run immediately with status 'running'. Poll the training run until it reaches a terminal status (completed or failed). A pipeline's first run has no champion until it completes and promotion runs; on a retrain the existing champion stays live and keeps scoring until a new one is promoted.+ * @summary Start a training run+ */+export const autoresearchTrainCreateBodyIterationBudgetMax = 500++export const AutoresearchTrainCreateBody = /* @__PURE__ */ zod.object({+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchTrainCreateBodyIterationBudgetMax)+ .optional()+ .describe('Override the pipeline iteration budget for this training run.'),+})+/*** Resolve a template key and optional overrides into a concrete pipeline config. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target event is auto-resolved from your event schema — check resolved_activity_event and activity_event_alternatives, then override if needed. For 'feature_adoption' and 'repeat_key_behavior', supply target_event. After resolving, call autoresearch-validate-create to check volume and warnings, then autoresearch-create to create the pipeline.* @summary Resolve a templatediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 354c8514b3b9..93ef22b4b2c7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -95874,6 +95874,15 @@ export namespace Schemas {readonly installations: readonly StamphogDiscoveredInstallation[];}+ export interface StartTrainingRequest {+ /**+ * Override the pipeline iteration budget for this training run.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number;+ }+/*** Result of an upload: where the file landed and its content hash.*/