: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(workflows): validate the create AI task action at save time (#88244)
Harley Alexander0657a9e42496
diff --git a/products/tasks/backend/facade/workflow_tasks.py b/products/tasks/backend/facade/workflow_tasks.pyindex 25f3dc012918..26666aed8654 100644--- a/products/tasks/backend/facade/workflow_tasks.py+++ b/products/tasks/backend/facade/workflow_tasks.py@@ -11,6 +11,7 @@ from products.tasks.backend.logic.services.workflow_tasks import (WorkflowTaskOriginKeyConflict,WorkflowTaskOwnerIneligible,create_workflow_task,+ validate_connectors,)__all__ = [@@ -20,4 +21,5 @@ __all__ = ["WorkflowTaskOwnerIneligible","WorkflowTaskSlackContext","create_workflow_task",+ "validate_connectors",]diff --git a/products/tasks/backend/logic/services/workflow_tasks.py b/products/tasks/backend/logic/services/workflow_tasks.pyindex 58a075666feb..278f9894940d 100644--- a/products/tasks/backend/logic/services/workflow_tasks.py+++ b/products/tasks/backend/logic/services/workflow_tasks.py@@ -111,7 +111,7 @@ def create_workflow_task(if replay is not None:return replay- _validate_connectors(team.id, owner_id, mcp_installation_ids)+ validate_connectors(team.id, owner_id, mcp_installation_ids)# Snapshot the connector allowlist onto the run: the sandbox mounts only what's here# (see loop_mcp_installation_allowlist), so a later edit of the workflow can't change@@ -225,7 +225,13 @@ def _find_replayed_task(return _task_dto(existing, created=False)-def _validate_connectors(team_id: int, owner_id: int, mcp_installation_ids: list[str] | None) -> None:+def validate_connectors(team_id: int, owner_id: int, mcp_installation_ids: list[str] | None) -> None:+ """Raise `WorkflowTaskConnectorsInvalid` for any id the owner can't mount.++ Called both when a run actually starts and, from the workflows product, when a+ "Create AI task" action is saved - so a stale or foreign connector id fails at save+ time instead of only on the workflow's next fire.+ """if not mcp_installation_ids:returnvalid_ids = {installation.id for installation in get_active_installations(team_id, owner_id, include_shared=True)}diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 042fa3393748..589ec0d21f89 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -96,6 +96,8 @@ from products.messaging.backend.api.message_templates import DesignOperationSerifrom products.messaging.backend.models import MessageTemplatefrom products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_htmlfrom products.notifications.backend.facade.api import publish_resource_edited+from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choices+from products.tasks.backend.facade.workflow_tasks import WorkflowTaskConnectorsInvalid, validate_connectorsfrom products.workflows.backend.api.action_redirects import compute_action_redirectsfrom products.workflows.backend.api.graph_operations import _deep_merge, apply_graph_operationsfrom products.workflows.backend.api.graph_validation import validate_graph@@ -536,6 +538,16 @@ _FIXED_TEMPLATE_IDS = {"function_push": "template-native-push",}+# The "Create AI task" step. Its inputs name things (connectors, a model, a repository) that+# only make sense checked against live state, so it gets extra save-time checks beyond the+# generic input-shape validation every function step goes through.+_CREATE_TASK_TEMPLATE_ID = "template-posthog-create-task"++_REPOSITORY_SHAPE = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+")++MIN_WORKFLOW_TASK_MAX_PARALLEL_TASKS = 1+MAX_WORKFLOW_TASK_MAX_PARALLEL_TASKS = 100+class _TriggerSourceTemplate(NamedTuple):template_id: str@@ -1215,6 +1227,75 @@ class HogFlowActionSerializer(serializers.Serializer):})+ def _validate_create_task_action(self, inputs: dict) -> None:+ """Save-time checks for the "Create AI task" step beyond input shape: whether the+ chosen connectors, model and repository are actually usable, and the parallel-run+ limit is sane - so a misconfigured step fails here instead of only when it fires."""+ connectors = (inputs.get("connectors") or {}).get("value")+ if connectors:+ get_team = self.context.get("get_team")+ owner_id = self.context.get("workflow_owner_id")+ # No team/owner to check against outside a request (internal re-saves) - nothing+ # new is being authored there, so there is nothing to validate.+ if get_team is not None and owner_id is not None:+ try:+ validate_connectors(get_team().id, owner_id, connectors)+ except WorkflowTaskConnectorsInvalid as e:+ raise serializers.ValidationError(+ {"inputs": {"connectors": f"MCP installation(s) not found or inactive: {e.invalid_ids}"}}+ )++ repository = (inputs.get("repository") or {}).get("value")+ if repository and not _REPOSITORY_SHAPE.fullmatch(repository):+ raise serializers.ValidationError(+ {"inputs": {"repository": "Repository must be an organization/repo name like your-org/your-repo."}}+ )++ model_value = (inputs.get("model") or {}).get("value") or {}+ model = model_value.get("model")+ reasoning_effort = model_value.get("reasoning_effort")+ if model:+ # An empty catalogue means the gateway is unreachable, not that no model is valid -+ # skip rather than block every save during an outage (see available_model_choices).+ available = available_model_choices(TASK_RUN_GATEWAY_PRODUCT)+ if available:+ choice = next((c for c in available if c.model == model), None)+ if choice is None:+ raise serializers.ValidationError({"inputs": {"model": f"'{model}' is not an available model."}})+ if reasoning_effort and reasoning_effort not in choice.supported_efforts:+ raise serializers.ValidationError(+ {+ "inputs": {+ "model": (+ f"Reasoning effort '{reasoning_effort}' is not supported for model "+ f"'{model}'. Supported values: {', '.join(choice.supported_efforts) or 'none'}."+ )+ }+ }+ )++ max_parallel_tasks = (inputs.get("max_parallel_tasks") or {}).get("value")+ if max_parallel_tasks is not None:+ # Matches the runtime IntegerField's own leniency (a "5.0" from an API client+ # coerces to 5 there) while still catching a fractional value or a bool, neither+ # of which the runtime field accepts.+ is_whole_number = (isinstance(max_parallel_tasks, int) and not isinstance(max_parallel_tasks, bool)) or (+ isinstance(max_parallel_tasks, float) and max_parallel_tasks.is_integer()+ )+ if not is_whole_number or not (+ MIN_WORKFLOW_TASK_MAX_PARALLEL_TASKS <= max_parallel_tasks <= MAX_WORKFLOW_TASK_MAX_PARALLEL_TASKS+ ):+ raise serializers.ValidationError(+ {+ "inputs": {+ "max_parallel_tasks": (+ f"Must be a whole number between {MIN_WORKFLOW_TASK_MAX_PARALLEL_TASKS} and "+ f"{MAX_WORKFLOW_TASK_MAX_PARALLEL_TASKS}."+ )+ }+ }+ )+def validate(self, data):is_draft = self.context.get("is_draft")# Drafts from the web builder stay lenient (incomplete graphs save fine); programmatic callers@@ -1431,6 +1512,9 @@ class HogFlowActionSerializer(serializers.Serializer):function_config_serializer.is_valid(raise_exception=True)data["config"]["inputs"] = function_config_serializer.validated_data["inputs"]+ if strict and template_id == _CREATE_TASK_TEMPLATE_ID:+ self._validate_create_task_action(data["config"]["inputs"])+# Branch types fan out via 'branch' edges indexed into these arrays; a node stored without# its array crashes the editor panel and assigns nothing at runtime. Presence is only# enforceable here (the config field is a lenient JSONField), so strict callers fail at@@ -2230,6 +2314,17 @@ class HogFlowSerializer(HogFlowMinimalSerializer):# binds `self.instance`, so fall back to the flow passed in via context so recovery still works.instance = cast(Optional[HogFlow], self.instance) or self.context.get("instance")+ # Who a "Create AI task" step runs as: the existing creator for an update, or the+ # requesting user for a brand-new flow (matches the `created_by` a create() actually+ # writes). None outside a request (internal re-saves), where connector checks are skipped.+ owner = instance.created_by if instance else None+ if owner is None:+ request = self.context.get("request")+ user = getattr(request, "user", None)+ if user is not None and getattr(user, "is_authenticated", False):+ owner = user+ self.context["workflow_owner_id"] = owner.id if owner else None+# Wait conditions the live flow already carries, so per-action validation can tell a newly# introduced clock condition from one we have been storing all along. Seeded here because# nested action validation runs during field processing, before validate() is reached.diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 1e2185f5eb4e..1a6b3b76d141 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -2,6 +2,7 @@ import jsonfrom copy import deepcopyfrom datetime import UTC, datetime, timedeltafrom io import StringIO+from types import SimpleNamespacefrom typing import Any, Optionalfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin@@ -5014,7 +5015,24 @@ def _create_task_template() -> dict:template["id"] = "template-posthog-create-task"template["name"] = "Create AI task"template["inputs_schema"] = [- {"key": "prompt", "type": "string", "label": "Instructions", "secret": False, "required": True}+ {"key": "prompt", "type": "string", "label": "Instructions", "secret": False, "required": True},+ {"key": "model", "type": "task_model", "label": "Model", "secret": False, "required": False},+ {"key": "repository", "type": "task_repository", "label": "Repository", "secret": False, "required": False},+ {+ "key": "connectors",+ "type": "task_mcp_installations",+ "label": "Connectors",+ "secret": False,+ "required": False,+ },+ {+ "key": "max_parallel_tasks",+ "type": "number",+ "label": "Maximum parallel tasks",+ "secret": False,+ "required": False,+ "default": 5,+ },]return template@@ -5170,3 +5188,153 @@ class TestFlagGatedTemplates(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "Template not found" in str(response.json())+++class TestCreateTaskActionValidation(APIBaseTest):+ """Save-time checks specific to the "Create AI task" step: a bad connector, model,+ repository, or limit used to only surface once the workflow fired. These lock in that+ the same misconfiguration is now rejected when the workflow is saved."""++ def setUp(self):+ super().setUp()+ sync_template_to_db(_create_task_template())++ def _post_flow(self, inputs: dict):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ }+ action = {+ "id": "action_1",+ "name": "action_1",+ "type": "function",+ "config": {+ "template_id": "template-posthog-create-task",+ "inputs": {"prompt": {"value": "Investigate"}, **inputs},+ },+ }+ # Strict validation, same as any programmatic caller - the path a misconfigured+ # workflow is actually authored through.+ with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=True):+ return self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Test Flow", "actions": [trigger_action, action], "edges": []},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )++ def test_rejects_a_connector_the_workflow_owner_cannot_mount(self):+ response = self._post_flow({"connectors": {"value": ["nonexistent-installation"]}})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "actions__1__inputs__connectors"+ assert not HogFlow.objects.filter(team=self.team).exists()++ def test_accepts_a_connector_the_workflow_owner_can_mount(self):+ # products.workflows may not depend on products.mcp_store's models directly (tach+ # boundary) - mocking at the same seam the model-catalogue tests below use.+ with patch("products.workflows.backend.api.hog_flow.validate_connectors", return_value=None):+ response = self._post_flow({"connectors": {"value": ["some-installation-id"]}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()++ @parameterized.expand(+ [+ ("no_slash", "just-a-name"),+ ("too_many_slashes", "org/repo/extra"),+ ("whitespace_only", " "),+ ]+ )+ def test_rejects_a_repository_that_is_not_org_slash_repo(self, _name, repository):+ response = self._post_flow({"repository": {"value": repository}})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "actions__1__inputs__repository"++ def test_accepts_an_org_slash_repo_repository(self):+ response = self._post_flow({"repository": {"value": "my-org/my-repo"}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()++ def test_rejects_a_model_outside_the_task_model_catalogue(self):+ with patch(+ "products.workflows.backend.api.hog_flow.available_model_choices",+ return_value=(SimpleNamespace(model="claude-opus"),),+ ):+ response = self._post_flow({"model": {"value": {"model": "not-a-real-model"}}})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "actions__1__inputs__model"++ def test_accepts_a_model_in_the_task_model_catalogue(self):+ with patch(+ "products.workflows.backend.api.hog_flow.available_model_choices",+ return_value=(SimpleNamespace(model="claude-opus"),),+ ):+ response = self._post_flow({"model": {"value": {"model": "claude-opus"}}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()++ def test_does_not_block_saving_while_the_model_catalogue_is_unreachable(self):+ # An empty catalogue means the gateway couldn't be reached, not that no model is+ # valid - a gateway outage must not block every workflow save.+ with patch("products.workflows.backend.api.hog_flow.available_model_choices", return_value=()):+ response = self._post_flow({"model": {"value": {"model": "whatever-model"}}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()++ def test_rejects_a_reasoning_effort_the_selected_model_does_not_support(self):+ # The runtime accepts model/effort pairs uncritically (WorkflowTaskCreateSerializer's+ # reasoning_effort is a plain CharField with no cross-check), so a mismatch saved here+ # would otherwise reach the agent sandbox unvalidated instead of failing anywhere.+ with patch(+ "products.workflows.backend.api.hog_flow.available_model_choices",+ return_value=(SimpleNamespace(model="claude-opus", supported_efforts=("low", "high")),),+ ):+ response = self._post_flow({"model": {"value": {"model": "claude-opus", "reasoning_effort": "ultracode"}}})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "actions__1__inputs__model"++ def test_accepts_a_reasoning_effort_the_selected_model_supports(self):+ with patch(+ "products.workflows.backend.api.hog_flow.available_model_choices",+ return_value=(SimpleNamespace(model="claude-opus", supported_efforts=("low", "high")),),+ ):+ response = self._post_flow({"model": {"value": {"model": "claude-opus", "reasoning_effort": "high"}}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()++ @parameterized.expand(+ [+ ("zero", 0),+ ("negative", -1),+ ("too_high", 101),+ ("fractional_float", 2.5),+ # bool is an int subclass, so the range check alone would let it through.+ ("boolean", True),+ ]+ )+ def test_rejects_max_parallel_tasks_outside_bounds_or_not_a_whole_number(self, _name, value):+ response = self._post_flow({"max_parallel_tasks": {"value": value}})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "actions__1__inputs__max_parallel_tasks"++ @parameterized.expand(+ [+ ("min", 1),+ ("max", 100),+ # DRF's runtime IntegerField coerces a whole-number float like this to 5, so the+ # save-time check must not be stricter than what the field will actually accept.+ ("whole_number_float", 5.0),+ ]+ )+ def test_accepts_max_parallel_tasks_within_bounds(self, _name, value):+ response = self._post_flow({"max_parallel_tasks": {"value": value}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()