:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(autoresearch): allow pipeline writes from user-driven sandboxes (#109485)
posthog[bot]db7ce00e5d75
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.pyindex 94d1ca67950e..5fd9fe913c6f 100644--- a/products/autoresearch/backend/presentation/views/views.py+++ b/products/autoresearch/backend/presentation/views/views.py@@ -31,7 +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_request+from posthog.oauth_provenance import get_oauth_access_token, is_sandbox_origin_requestfrom posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom products.autoresearch.backend.facade import api@@ -46,6 +46,7 @@ from products.autoresearch.backend.facade.contracts import (SuggestionNotFound,TrainingRunNotFound,)+from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.access import code_access_required_response, usage_limit_responsefrom .serializers import (@@ -166,6 +167,19 @@ def _require_parent_pipeline_id(view: Any) -> str:return pipeline_id+def _is_training_agent_sandbox(request: Request, team_id: int) -> bool:+ """Whether to treat a sandbox request as the autoresearch training agent.++ A request without a task-bound sandbox token counts as the training agent, so the check+ fails closed when the header alone marks the request.+ """+ task_id = getattr(get_oauth_access_token(request), "sandbox_task_id", None)+ if task_id is None:+ return True+ tasks = tasks_facade.get_tasks_by_ids([task_id], [team_id])+ return not tasks or tasks[0].origin_product == tasks_facade.TaskOriginProduct.AUTORESEARCH++def _pipeline_write_fields(validated: Any) -> dict[str, Any]:"""The fields to persist.@@ -217,10 +231,18 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixindef initial(self, request: Request, *args: Any, **kwargs: Any) -> None:super().initial(request, *args, **kwargs)+ if self.action not in self.scope_object_write_actions or not is_sandbox_origin_request(request):+ return+ # A training run is a paid Tasks sandbox, so a person starts it. Tasks applies the same+ # rule to its own launches.+ if self.action == "start_training":+ raise PermissionDenied(+ "Training cannot be started from inside a sandbox. Start training from the pipeline's page in PostHog."+ )# 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):+ # through its run, so a confused or injected agent must not reach pipeline writes. A+ # user-driven sandbox, such as a PostHog AI task, can do what its user can do.+ if _is_training_agent_sandbox(request, self.team_id):raise PermissionDenied("Pipelines cannot be changed from inside a sandbox.")def get_throttles(self) -> list[BaseThrottle]:diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pyindex 01a2c7c7305d..96050ac0ddde 100644--- a/products/autoresearch/backend/tests/test_api.py+++ b/products/autoresearch/backend/tests/test_api.py@@ -39,6 +39,7 @@ from products.autoresearch.backend.presentation.views.serializers import (ValidationWarningSerializer,)from products.autoresearch.backend.testing import TeamScopedTestMixin+from products.tasks.backend.models import Task # tach-ignoreMOCK_VALIDATION_OK = ValidationResult(can_proceed=True,@@ -256,6 +257,67 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):assert resp.status_code == status.HTTP_403_FORBIDDENassert not AutoresearchTrainingRun.objects.for_team(self.team.pk).filter(pipeline=pipeline).exists()+ def _sandbox_task_id(self, origin_product: str, team: Team | None = None) -> uuid.UUID:+ return Task.objects.create(+ team=team or self.team,+ title="t",+ description="d",+ origin_product=origin_product,+ created_by=self.user,+ ).id++ def _as_sandbox_task(self, task_id: uuid.UUID | None):+ token = MagicMock(sandbox_task_id=task_id)+ return (+ patch(f"{_VIEWS}.is_sandbox_origin_request", return_value=True),+ patch(f"{_VIEWS}.get_oauth_access_token", return_value=token),+ )++ @parameterized.expand(+ [+ ("create", "post", "", {"name": "New", "target_event": "$signup"}, status.HTTP_201_CREATED),+ ("patch", "patch", "{id}/", {"name": "Renamed"}, status.HTTP_200_OK),+ ("archive", "post", "{id}/archive/", {}, status.HTTP_200_OK),+ ]+ )+ def test_user_driven_sandbox_can_change_a_pipeline(+ self, _name: str, method: str, suffix: str, body: dict, expected: int+ ):+ pipeline = self._make_pipeline()+ sandbox, token = self._as_sandbox_task(self._sandbox_task_id(Task.OriginProduct.POSTHOG_AI))+ with sandbox, token:+ resp = getattr(self.client, method)(f"{self.base_url}/{suffix.format(id=pipeline.id)}", body, format="json")+ assert resp.status_code == expected, resp.json()++ @parameterized.expand(+ [+ ("training_agent", Task.OriginProduct.AUTORESEARCH, False),+ ("task_in_another_team", Task.OriginProduct.POSTHOG_AI, True),+ ("no_task_on_token", None, False),+ ]+ )+ def test_training_agent_or_unresolved_sandbox_cannot_create_a_pipeline(+ self, _name: str, origin_product: str | None, other_team: bool+ ):+ task_id = None+ if origin_product is not None:+ team = Team.objects.create(organization=self.organization) if other_team else None+ task_id = self._sandbox_task_id(origin_product, team=team)+ sandbox, token = self._as_sandbox_task(task_id)+ with sandbox, token:+ resp = self.client.post(f"{self.base_url}/", {"name": "New", "target_event": "$signup"}, format="json")+ assert resp.status_code == status.HTTP_403_FORBIDDEN+ assert not AutoresearchPipeline.objects.for_team(self.team.pk).filter(name="New").exists()++ def test_user_driven_sandbox_cannot_start_training(self):+ pipeline = self._make_pipeline()+ sandbox, token = self._as_sandbox_task(self._sandbox_task_id(Task.OriginProduct.POSTHOG_AI))+ with sandbox, token, 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_403_FORBIDDEN+ assert "Start training from the pipeline's page" in resp.json()["detail"]+ mock_run_training.assert_not_called()+def test_sandbox_origin_can_still_read_pipelines(self):pipeline = self._make_pipeline()with patch(f"{_VIEWS}.is_sandbox_origin_request", return_value=True):diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yamlindex 89556b66754e..cb20190330c9 100644--- a/products/autoresearch/mcp/tools.yaml+++ b/products/autoresearch/mcp/tools.yaml@@ -408,9 +408,10 @@ tools:reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-sidepromotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 ifa training run is already in progress, the pipeline is paused, or its creator or target is no longer valid- (recreate the pipeline). Returns 403 from inside a sandbox, where pipeline writes are refused. Needs PostHog- Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job- scores the inference population and emits autoresearch_prediction events. You can optionally override the+ (recreate the pipeline). Returns 403 from inside a sandbox, such as a PostHog AI cloud task: do not retry,+ and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access,+ because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job scores the+ inference population and emits autoresearch_prediction events. You can optionally override theiteration_budget for this run. A pipeline with an action target also needs the action:read scope.feature_flag: autoresearchautoresearch-training-runs-artifacts-delete-create:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 2d2035313d9d..cfe3e3ce5f3e 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1240,7 +1240,7 @@"feature_flag": "autoresearch"},"autoresearch-train-create": {- "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, where pipeline writes are refused. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job scores the inference population and emits autoresearch_prediction events. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.",+ "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, such as a PostHog AI cloud task: do not retry, and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job scores the inference population and emits autoresearch_prediction events. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.","category": "Autoresearch","feature": "autoresearch","summary": "Start training",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 174eeb4289b1..4d720f537e83 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1255,7 +1255,7 @@"feature_flag": "autoresearch"},"autoresearch-train-create": {- "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, where pipeline writes are refused. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job scores the inference population and emits autoresearch_prediction events. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.",+ "description": "Start an asynchronous training run for a pipeline. Launches the autoresearch agent in a sandbox and returns the training run immediately with status 'running'. Poll autoresearch-training-runs-list until the run reaches 'completed' or 'failed'. A pipeline's first run has no champion until it completes and server-side promotion runs; on a retrain the existing champion keeps scoring until a new one is promoted. Returns 400 if a training run is already in progress, the pipeline is paused, or its creator or target is no longer valid (recreate the pipeline). Returns 403 from inside a sandbox, such as a PostHog AI cloud task: do not retry, and ask the user to start training from the pipeline's page in PostHog. Needs PostHog Desktop access, because the run is a cloud sandbox. After a run promotes a champion, the daily scoring job scores the inference population and emits autoresearch_prediction events. You can optionally override the iteration_budget for this run. A pipeline with an action target also needs the action:read scope.","category": "Autoresearch","feature": "autoresearch","summary": "Start training",