: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): validate without saving through the workflow serializers (#113258)
Harley Alexander5a68bb6f4382
diff --git a/products/canvas/backend/actions.py b/products/canvas/backend/actions.pyindex a7a828c45048..90c92b0a4627 100644--- a/products/canvas/backend/actions.py+++ b/products/canvas/backend/actions.py@@ -106,12 +106,15 @@ def _set_workflows_enabled(team_id: int, user_id: int, payload: dict[str, Any],from rest_framework.response import Response # noqa: PLC0415from products.workflows.backend.facade import api as workflows_facade # noqa: PLC0415 — load on execute+ from products.workflows.backend.presentation.views.hog_flow import ( # noqa: PLC0415 — load on execute+ set_workflow_enabled,+ )with transaction.atomic():changed = []for workflow_id in payload["workflow_ids"]:try:- new_status = workflows_facade.set_workflow_enabled(+ new_status = set_workflow_enabled(team_id=team_id, user_id=user_id, workflow_id=workflow_id, enabled=enabled)except workflows_facade.WorkflowNotFound:diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.pyindex 10f7ecac3fba..03bf86ead106 100644--- a/products/workflows/backend/facade/api.py+++ b/products/workflows/backend/facade/api.py@@ -17,6 +17,7 @@ from products.workflows.backend.facade.contracts import (TwilioPhoneNumber,WorkflowAccessDenied,WorkflowActivitySummary,+ WorkflowArchived,WorkflowNotFound,WorkflowSummary,WorkflowTaskDailyLimits,@@ -44,6 +45,7 @@ from products.workflows.backend.utils.rrule_utils import compute_next_occurrence__all__ = ["WorkflowAccessDenied",+ "WorkflowArchived","WorkflowNotFound","MIN_EMAIL_SENDING_TIER","compute_next_occurrences",@@ -61,10 +63,6 @@ __all__ = []-class WorkflowArchived(Exception):- pass--def search_workflows(*,project_id: int,@@ -167,45 +165,6 @@ def accept_ses_event(delivery: WebhookDelivery) -> None:handle_ses_tenant_event(delivery)-def set_workflow_enabled(*, team_id: int, user_id: int, workflow_id: UUID, enabled: bool) -> str:- """Flip a workflow between ``active`` and ``draft`` as ``user_id`` and return the new status.-- The same transition the lifecycle API tools make (enable is ``active``, disable is- ``draft``); the scheduler fires only active workflows, so a disabled one stops at its- next occurrence and keeps its schedule for when it is enabled again. Archived workflows- are left alone. The user must hold editor access to the workflow, as in the API.- """- from posthog.models.user import User # noqa: PLC0415 — keeps the user model off the facade import path-- from products.workflows.backend.presentation.views.hog_flow import ( # noqa: PLC0415 - heavy DRF import- HogFlowSerializer,- )-- hog_flow = HogFlow.objects.select_related("team").filter(team_id=team_id, id=workflow_id).first()- if hog_flow is None:- raise WorkflowNotFound()- if hog_flow.status == HogFlow.State.ARCHIVED:- raise WorkflowArchived()- user = User.objects.get(id=user_id)- if not UserAccessControl(user=user, team=hog_flow.team).check_access_level_for_object(hog_flow, "editor"):- raise WorkflowAccessDenied("editor")- target = HogFlow.State.ACTIVE if enabled else HogFlow.State.DRAFT- if hog_flow.status != target:- if enabled:- serializer = HogFlowSerializer(- hog_flow,- data={"status": target},- partial=True,- context={"team_id": team_id, "get_team": lambda: hog_flow.team},- )- serializer.is_valid(raise_exception=True)- serializer.save()- else:- hog_flow.status = target- hog_flow.save(update_fields=["status", "updated_at"])- return str(hog_flow.status)--def get_workflow_names(*, team_id: int, workflow_ids: Iterable[str]) -> dict[str, str]:"""Names keyed by the workflow id as a string. Deleted workflows are left out."""return {diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 9815e9f93ec5..6979864b93b8 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -434,6 +434,10 @@ class WorkflowNotFound(Exception):pass+class WorkflowArchived(Exception):+ """An archived workflow cannot be enabled or disabled."""++@frozenclass WorkflowListQuery:"""What a workflow list asks for. The view validates each value before it builds one.diff --git a/products/workflows/backend/facade/writes.py b/products/workflows/backend/facade/writes.pyindex 024ecfcd7450..53edddd098a4 100644--- a/products/workflows/backend/facade/writes.py+++ b/products/workflows/backend/facade/writes.py@@ -9,6 +9,7 @@ from products.workflows.backend.services.hog_flow_writes import (edit_workflow_content,publish_confirm_value,publish_draft,+ save_validated_workflow,trigger_has_audience,update_workflow,)@@ -23,6 +24,7 @@ __all__ = ["edit_workflow_content","publish_confirm_value","publish_draft",+ "save_validated_workflow","trigger_has_audience","update_workflow",]diff --git a/products/workflows/backend/management/commands/refresh_hog_flows.py b/products/workflows/backend/management/commands/refresh_hog_flows.pyindex 6e72a17ba0d5..67c90c092bbd 100644--- a/products/workflows/backend/management/commands/refresh_hog_flows.py+++ b/products/workflows/backend/management/commands/refresh_hog_flows.py@@ -16,6 +16,7 @@ from products.workflows.backend.facade.secrets import (partition_flow_secrets,plaintext_secret_map,)+from products.workflows.backend.facade.writes import save_validated_workflowfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.presentation.views.hog_flow import HogFlowSerializer@@ -171,7 +172,11 @@ class Command(BaseCommand):)raise Exception("Refresh would change the stored secrets")if not dry_run:- serializer.save()+ save_validated_workflow(+ team_id=hog_flow.team_id,+ hog_flow_id=hog_flow.id,+ validated_data=dict(serializer.validated_data),+ )total_updated += 1logger.info("Would refresh HogFlow" if dry_run else "Successfully refreshed HogFlow",diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex d7eb466d2c6e..a34696413d8f 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -133,6 +133,7 @@ from products.workflows.backend.facade.contracts import (StaffPausedError,Workflow,WorkflowAccessDenied,+ WorkflowArchived,WorkflowBatchJobNotFound,WorkflowDraftChanged,WorkflowDraftExists,@@ -205,7 +206,6 @@ from products.workflows.backend.facade.secrets import (rehydrate_flow_secrets,secret_keys_for_action,strip_content_secrets,- strip_secrets_from_content,)from products.workflows.backend.facade.templates import get_function_template_schemafrom products.workflows.backend.facade.validation import (@@ -232,6 +232,7 @@ from products.workflows.backend.facade.writes import (edit_workflow_content,publish_confirm_value,publish_draft,+ save_validated_workflow,trigger_has_audience,update_workflow,)@@ -2474,8 +2475,28 @@ class HogFlowLastRunSerializer(serializers.Serializer):)-class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):+class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Serializer):+ # The fields the model used to supply. Each is read-only here; the full serializer declares the+ # writable ones again, so those are typed as any field.+ id = serializers.UUIDField(read_only=True)+ name = serializers.CharField(read_only=True, allow_null=True)+ description = serializers.CharField(read_only=True)+ version = serializers.IntegerField(read_only=True)+ status = serializers.ChoiceField(choices=HogFlow.State.choices, read_only=True)+ origin_product = serializers.ChoiceField(choices=HogFlow.OriginProduct.choices, read_only=True, allow_null=True)+ created_at = serializers.DateTimeField(read_only=True)created_by = UserBasicSerializer(read_only=True)+ updated_at = serializers.DateTimeField(read_only=True)+ trigger = serializers.JSONField(read_only=True)+ trigger_masking: serializers.Field = serializers.JSONField(read_only=True, allow_null=True)+ conversion: serializers.Field = serializers.JSONField(read_only=True, allow_null=True)+ exit_condition = serializers.ChoiceField(choices=HogFlow.ExitCondition.choices, read_only=True)+ email_sending_rate_limit: serializers.Field = serializers.JSONField(read_only=True, allow_null=True)+ edges: serializers.Field = serializers.JSONField(read_only=True)+ actions: serializers.Field = serializers.JSONField(read_only=True)+ abort_action = serializers.CharField(read_only=True, allow_null=True)+ variables: serializers.Field = serializers.JSONField(read_only=True, allow_null=True)+ billable_action_types = serializers.JSONField(read_only=True, allow_null=True)last_run = serializers.SerializerMethodField(help_text="Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run.")@@ -2495,7 +2516,7 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod)class Meta:- model = HogFlow+ # The fields each serializer returns, in this order. get_fields applies it.fields = ["id","name",@@ -2526,6 +2547,10 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod]read_only_fields = fields+ def get_fields(self) -> dict[str, serializers.Field]:+ fields = super().get_fields()+ return {name: fields[name] for name in self.Meta.fields}+@extend_schema_field(HogFlowLastRunSerializer(allow_null=True))def get_last_run(self, instance: HogFlow) -> dict | None:if instance.origin_product != HogFlow.OriginProduct.LOOPS:@@ -2851,7 +2876,6 @@ class HogFlowSerializer(HogFlowMinimalSerializer):return super().to_internal_value(data)class Meta:- model = HogFlowfields = ["id","name",@@ -3056,28 +3080,6 @@ class HogFlowSerializer(HogFlowMinimalSerializer):return data- def _strip_secret_inputs(self, validated_data: dict) -> None:- # Move secret function inputs out of the live `actions` (and the derived `trigger`) into the- # encrypted_inputs column before persisting. Only runs when this write carries actions - a- # metadata-only update must not touch stored secrets. The map is rebuilt from the incoming- # action set, so deleted actions' secrets drop out.- if "actions" not in validated_data:- return- validated_data["encrypted_inputs"] = strip_secrets_from_content(validated_data, template_cache={})-- def create(self, validated_data: dict, *args, **kwargs) -> HogFlow:- request = self.context["request"]- team_id = self.context["team_id"]- validated_data["created_by"] = request.user- validated_data["team_id"] = team_id- self._strip_secret_inputs(validated_data)-- return super().create(validated_data=validated_data)-- def update(self, instance, validated_data):- self._strip_secret_inputs(validated_data)- return super().update(instance, validated_data)-class HogFlowUpdateSerializer(HogFlowSerializer):origin_product = serializers.ChoiceField(@@ -3099,6 +3101,40 @@ class HogFlowUpdateSerializer(HogFlowSerializer):return super().validate(data)+def set_workflow_enabled(*, team_id: int, user_id: int, workflow_id: uuid_mod.UUID, enabled: bool) -> str:+ """Flip a workflow between ``active`` and ``draft`` as ``user_id`` and return the new status.++ The same transition the lifecycle API tools make (enable is ``active``, disable is+ ``draft``); the scheduler fires only active workflows, so a disabled one stops at its+ next occurrence and keeps its schedule for when it is enabled again. Archived workflows+ are left alone. The user must hold editor access to the workflow, as in the API.+ Enabling validates the whole workflow the way an API activation does, so it lives with+ the serializer rather than behind the facade.+ """+ hog_flow = HogFlow.objects.select_related("team").filter(team_id=team_id, id=workflow_id).first()+ if hog_flow is None:+ raise WorkflowNotFound()+ if hog_flow.status == HogFlow.State.ARCHIVED:+ raise WorkflowArchived()+ user = User.objects.get(id=user_id)+ if not UserAccessControl(user=user, team=hog_flow.team).check_access_level_for_object(hog_flow, "editor"):+ raise WorkflowAccessDenied("editor")+ target = HogFlow.State.ACTIVE if enabled else HogFlow.State.DRAFT+ if hog_flow.status != target:+ validated_data: dict[str, Any] = {"status": target}+ if enabled:+ serializer = HogFlowSerializer(+ hog_flow,+ data={"status": target},+ partial=True,+ context={"team_id": team_id, "get_team": lambda: hog_flow.team},+ )+ serializer.is_valid(raise_exception=True)+ validated_data = dict(serializer.validated_data)+ save_validated_workflow(team_id=team_id, hog_flow_id=hog_flow.id, validated_data=validated_data)+ return str(target)++GRAPH_OPERATION_TYPES = ["update_action","add_action",diff --git a/products/workflows/backend/services/hog_flow_writes.py b/products/workflows/backend/services/hog_flow_writes.pyindex e3e7d6477404..cc81abb03489 100644--- a/products/workflows/backend/services/hog_flow_writes.py+++ b/products/workflows/backend/services/hog_flow_writes.py@@ -95,7 +95,7 @@ def _parse_stamp(raw: Optional[str]) -> Optional[datetime]:def _save_live(instance: HogFlow, validated_data: dict, **overrides: object) -> None:- # What HogFlowSerializer.update does: move secret function inputs out of the live `actions` into+ # Move secret function inputs out of the live `actions` into# encrypted_inputs when the write carries actions (a metadata-only update must not touch stored# secrets), then save the whole row.data = {**validated_data, **overrides}@@ -106,6 +106,15 @@ def _save_live(instance: HogFlow, validated_data: dict, **overrides: object) ->instance.save()+def save_validated_workflow(*, team_id: int, hog_flow_id: UUID, validated_data: dict) -> None:+ """Write a workflow's validated fields to the live row, with no draft routing, revision bump or+ follow-ups. For callers outside a request: enabling a workflow and the bytecode refresh."""+ # The save writes every column. Lock the read so that a concurrent write, such as a staff email+ # sending pause, either lands before this read or waits for this save, and is never overwritten.+ with transaction.atomic():+ _save_live(HogFlow.objects.select_for_update().get(team_id=team_id, pk=hog_flow_id), validated_data)++def _derive_from_locked_graph(locked: HogFlow, validated_data: dict) -> dict:# HogFlowSerializer.validate derives trigger, billable_action_types and exit_condition from the# actions it read before the row lock. A write without actions keeps the locked row's actions, and adiff --git a/pyproject.toml b/pyproject.tomlindex 2591e736774f..de0dded6ad5f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -864,7 +864,6 @@ ignore_imports = ["products.logs.backend.facade.retention_views -> products.logs.backend.presentation.views.retention_api","products.managed_warehouse.backend.facade.api -> products.managed_warehouse.backend.presentation.views","products.tasks.backend.facade.api -> products.tasks.backend.presentation.serializers",- "products.workflows.backend.facade.api -> products.workflows.backend.presentation.views.hog_flow","products.billing_alerts.backend.facade.api -> rest_framework","products.dashboards.backend.facade.api -> rest_framework","products.experiments.backend.facade.api -> rest_framework",