Skip to content

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

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.py
index 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 PostHogAutoSchema
from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from 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_request
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from 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_facade
from products.tasks.backend.facade.access import code_access_required_response, usage_limit_response
from .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, _FacadePaginationMixin
def 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.py
index 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-ignore
MOCK_VALIDATION_OK = ValidationResult(
can_proceed=True,
@@ -256,6 +257,67 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
assert resp.status_code == status.HTTP_403_FORBIDDEN
assert 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.yaml
index 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-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
+ (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.
feature_flag: autoresearch
autoresearch-training-runs-artifacts-delete-create:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 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.json
index 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",