: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
chore(workflows): route the step validation checks through the facade (#109047)
Harley Alexander647875c473cf
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 4865ad539b6a..955f2dddc95f 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -181,6 +181,14 @@ class WorkflowTemplate:variables: list[dict[str, Any]] | None+@frozen+class FunctionTemplateSchema:+ """The parts of a cdp function template that a workflow step validates its inputs against."""++ type: str+ inputs_schema: list[dict[str, Any]] | None++# The provider payloads below are TypedDicts, not frozen dataclasses: the email-verify endpoint# returns them as JSON without a serializer, so the keys are the API response keys.diff --git a/products/workflows/backend/facade/templates.py b/products/workflows/backend/facade/templates.pyindex a2f90148de37..d5333a1ac112 100644--- a/products/workflows/backend/facade/templates.py+++ b/products/workflows/backend/facade/templates.py@@ -6,6 +6,7 @@ from products.workflows.backend.services.hog_flow_templates import (create_template,delete_template,function_template_exists,+ get_function_template_schema,get_global_template,get_template,list_global_templates,@@ -18,6 +19,7 @@ __all__ = ["create_template","delete_template","function_template_exists",+ "get_function_template_schema","get_global_template","get_template","list_global_templates",diff --git a/products/workflows/backend/facade/validation.py b/products/workflows/backend/facade/validation.pynew file mode 100644index 000000000000..536056d1cb52--- /dev/null+++ b/products/workflows/backend/facade/validation.py@@ -0,0 +1,21 @@+"""Save-time checks on a workflow's steps that need the database or shared parsing rules."""++from products.workflows.backend.services.batch_audience_cohorts import find_behavioral_cohort_name+from products.workflows.backend.services.wait_clock_conditions import find_clock_function+from products.workflows.backend.utils.durations import (+ DURATION_PATTERN,+ duration_error,+ duration_minutes,+ is_duration,+ is_signed_duration,+)++__all__ = [+ "DURATION_PATTERN",+ "duration_error",+ "duration_minutes",+ "find_behavioral_cohort_name",+ "find_clock_function",+ "is_duration",+ "is_signed_duration",+]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex af8810ac6b84..dace48c2e4ea 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -103,9 +103,6 @@ from products.access_control.backend.presentation.access_control import (AccessControlViewSetMixin,UserAccessControlSerializerMixin,)-from products.cdp.backend.models.hog_function_template import HogFunctionTemplate-from products.cohorts.backend.models.cohort import Cohort-from products.cohorts.backend.models.util import get_all_cohort_dependenciesfrom products.feature_flags.backend.person_sampling import bounded_memory_settingsfrom products.feature_flags.backend.user_blast_radius import BlastRadiusResult, get_user_blast_radiusfrom products.messaging.backend.api.design_operations import apply_design_operations@@ -136,6 +133,16 @@ from products.workflows.backend.facade.secrets import (strip_content_secrets,strip_secrets_from_content,)+from products.workflows.backend.facade.templates import get_function_template_schema+from products.workflows.backend.facade.validation import (+ DURATION_PATTERN,+ duration_error,+ duration_minutes,+ find_behavioral_cohort_name,+ find_clock_function,+ is_duration,+ is_signed_duration,+)from products.workflows.backend.metrics import (GUARDRAIL_LABELS,GUARDRAIL_METRICS,@@ -211,7 +218,6 @@ from products.workflows.backend.services.timing_reschedule import (get_all_timing_action_ids,get_timing_reschedule_action_ids,)-from products.workflows.backend.services.wait_clock_conditions import find_clock_functionfrom products.workflows.backend.services.workflow_email_health import (StaffPausedError,pause_requires_staff,@@ -219,13 +225,6 @@ from products.workflows.backend.services.workflow_email_health import ()from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timingfrom products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit-from products.workflows.backend.utils.durations import (- DURATION_PATTERN,- duration_error,- duration_minutes,- is_duration,- is_signed_duration,-)from products.workflows.backend.utils.email_sending_tiers import max_email_sending_tier, resolve_team_email_sending_tierfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule@@ -1265,27 +1264,17 @@ class HogFlowActionSerializer(serializers.Serializer):]if not cohort_ids:return- project_id = self.context["get_team"]().project_id- for cohort_id in cohort_ids:- try:- cohort = Cohort.objects.get(pk=cohort_id, team__project_id=project_id, deleted=False)- except (Cohort.DoesNotExist, ValueError, TypeError):- continue # missing/invalid cohort surfaces during audience resolution, not here- if cohort.is_static:- continue- for dep in [cohort, *get_all_cohort_dependencies(cohort)]:- if dep.is_static:- continue- if any(p.type == "behavioral" for p in dep.properties.flat):- raise serializers.ValidationError(- {- "filters": (- f"Cohort '{dep.name}' targets event behavior, which batch/schedule audiences "- "can't evaluate. Use a static or property-based cohort, or an event trigger "- "for behavioral targeting."- )- }+ cohort_name = find_behavioral_cohort_name(self.context["get_team"]().project_id, cohort_ids)+ if cohort_name is not None:+ raise serializers.ValidationError(+ {+ "filters": (+ f"Cohort '{cohort_name}' targets event behavior, which batch/schedule audiences "+ "can't evaluate. Use a static or property-based cohort, or an event trigger "+ "for behavioral targeting.")+ }+ )def _validate_create_task_action(self, inputs: dict) -> None:"""Save-time checks for the "Create AI task" step beyond input shape: whether the@@ -1591,7 +1580,7 @@ class HogFlowActionSerializer(serializers.Serializer):get_team = self.context.get("get_team")if get_team is not None:_apply_email_template_content(config, get_team(), strict, self.context)- template = HogFunctionTemplate.get_template(template_id)+ template = get_function_template_schema(template_id)gating_flag = FLAG_GATED_TEMPLATE_IDS.get(template_id)already_stored = data.get("id") in (self.context.get("stored_gated_template_action_ids") or set())if template is not None and gating_flag is not None and not already_stored:diff --git a/products/workflows/backend/services/batch_audience_cohorts.py b/products/workflows/backend/services/batch_audience_cohorts.pynew file mode 100644index 000000000000..f0ec3fffb6ca--- /dev/null+++ b/products/workflows/backend/services/batch_audience_cohorts.py@@ -0,0 +1,21 @@+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.util import get_all_cohort_dependencies+++def find_behavioral_cohort_name(project_id: int, cohort_ids: list[int | str]) -> str | None:+ """The name of the first non-static cohort, among the given cohorts and their dependencies,+ that filters on event behavior. Static cohorts are exempt, because their membership is frozen."""+ for cohort_id in cohort_ids:+ try:+ cohort = Cohort.objects.get(pk=cohort_id, team__project_id=project_id, deleted=False)+ except (Cohort.DoesNotExist, ValueError, TypeError):+ continue # missing/invalid cohort surfaces during audience resolution, not here+ if cohort.is_static:+ continue+ for dep in [cohort, *get_all_cohort_dependencies(cohort)]:+ if dep.is_static:+ continue+ if any(p.type == "behavioral" for p in dep.properties.flat):+ # Cohort.name is nullable, and the caller reads None as "no behavioral cohort".+ return str(dep.name)+ return Nonediff --git a/products/workflows/backend/services/hog_flow_templates.py b/products/workflows/backend/services/hog_flow_templates.pyindex e8e57698e6b9..1a185fd56aa1 100644--- a/products/workflows/backend/services/hog_flow_templates.py+++ b/products/workflows/backend/services/hog_flow_templates.py@@ -5,7 +5,7 @@ from uuid import UUIDfrom django.db.models import Q, QuerySetfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplate-from products.workflows.backend.facade.contracts import WorkflowTemplate+from products.workflows.backend.facade.contracts import FunctionTemplateSchema, WorkflowTemplatefrom products.workflows.backend.facade.enums import HogFlowTemplateExitCondition, HogFlowTemplateScopefrom products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplatefrom products.workflows.backend.templates import get_global_template_by_id, load_global_templates@@ -120,3 +120,10 @@ def get_global_template(template_id: str) -> dict[str, Any] | None:def function_template_exists(template_id: str) -> bool:return HogFunctionTemplate.get_template(template_id) is not None+++def get_function_template_schema(template_id: str) -> FunctionTemplateSchema | None:+ template = HogFunctionTemplate.get_template(template_id)+ if template is None:+ return None+ return FunctionTemplateSchema(type=template.type, inputs_schema=template.inputs_schema)diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex 6513f8097b0e..e2e65d216b51 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -3576,7 +3576,7 @@ class TestHogFlowAPI(APIBaseTest):assert data["confirm_token"]assert mock_count.call_count == 2- def _make_cohort(self, *, behavioral=False, static=False, nested_cohort_id=None) -> Cohort:+ def _make_cohort(self, *, behavioral=False, static=False, nested_cohort_id=None, name="c") -> Cohort:if behavioral:properties = {"type": "OR",@@ -3617,7 +3617,7 @@ class TestHogFlowAPI(APIBaseTest):filters = {}else:filters = {"properties": properties}- return Cohort.objects.create(team=self.team, name="c", filters=filters, is_static=static)+ return Cohort.objects.create(team=self.team, name=name, filters=filters, is_static=static)def _post_batch_with_cohort(self, cohort_id: int, *, status: str = "active", trigger_type: str = "batch", **extra):trigger_action = {@@ -3632,9 +3632,9 @@ class TestHogFlowAPI(APIBaseTest):hog_flow = {"name": "Test Batch Flow", "status": status, "actions": [trigger_action]}return self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, **extra)- @parameterized.expand(["batch", "schedule"])- def test_hog_flow_audience_rejects_behavioral_cohort(self, trigger_type: str):- cohort = self._make_cohort(behavioral=True)+ @parameterized.expand([("batch", "c"), ("schedule", "c"), ("batch", None)])+ def test_hog_flow_audience_rejects_behavioral_cohort(self, trigger_type: str, name: str | None):+ cohort = self._make_cohort(behavioral=True, name=name)response = self._post_batch_with_cohort(cohort.pk, trigger_type=trigger_type)assert response.status_code == 400, response.json()assert "behavior" in response.json()["detail"].lower()diff --git a/pyproject.toml b/pyproject.tomlindex a6c0d5747faa..33dbdc3fb654 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -735,9 +735,6 @@ ignore_imports = [# parse -> facade -> serialize and delete each entry. backend:contract-check stays off until# this list is empty. Only delete entries here: a new import from these views goes through# the facade.- "products.workflows.backend.presentation.views.hog_flow -> products.cdp.backend.models.hog_function_template",- "products.workflows.backend.presentation.views.hog_flow -> products.cohorts.backend.models.cohort",- "products.workflows.backend.presentation.views.hog_flow -> products.cohorts.backend.models.util","products.workflows.backend.presentation.views.hog_flow -> products.feature_flags.backend.person_sampling","products.workflows.backend.presentation.views.hog_flow -> products.feature_flags.backend.user_blast_radius","products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.api.design_operations",@@ -759,11 +756,9 @@ ignore_imports = ["products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.batch_audience","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.email_sending_attribution","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.timing_reschedule",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.wait_clock_conditions","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.workflow_email_health","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.tasks.hog_flows","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.batch_trigger_limit",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.durations","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.email_sending_tiers","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.rrule_utils",# TODO: access-control presentation wave — the consolidated RBAC viewsets carry their ORM