: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 create, delete, edits, publish and discard through the facade (#113123)
Harley Alexander591224ef74c8
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 708eb3bcb6cc..4e62400db22e 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -374,6 +374,22 @@ class WorkflowDraftChanged(Exception):"""The staged draft changed since the caller confirmed the overwrite."""+class WorkflowStale(Exception):+ """The workflow was written elsewhere after the caller loaded the version it edits."""+++class WorkflowHasNoDraft(Exception):+ """Publish found no staged draft."""+++@frozen+class WorkflowWriteResult:+ previous: Mapping[str, object]+ current: Mapping[str, object]+ routed_to_draft: bool = False+ schedules_paused: int = 0++@frozenclass ProposalChanges:"""What approving a suggestion would stage. `conflicts` names the steps or fields someone elsediff --git a/products/workflows/backend/facade/writes.py b/products/workflows/backend/facade/writes.pynew file mode 100644index 000000000000..1fd955bb3ccf--- /dev/null+++ b/products/workflows/backend/facade/writes.py@@ -0,0 +1,28 @@+"""The workflow write path: live saves, staged drafts, surgical edits, publish and discard, each under+the workflow's row lock with its staleness fences, revision bump and post-commit follow-ups."""++from products.workflows.backend.services.action_redirects import compute_action_redirects+from products.workflows.backend.services.hog_flow_writes import (+ DRAFT_CONTENT_FIELDS,+ create_workflow,+ destroy_workflow,+ discard_draft,+ edit_workflow_content,+ publish_confirm_value,+ publish_draft,+ trigger_has_audience,+)+from products.workflows.backend.services.publish_impact import build_publish_impact++__all__ = [+ "DRAFT_CONTENT_FIELDS",+ "build_publish_impact",+ "compute_action_redirects",+ "create_workflow",+ "discard_draft",+ "destroy_workflow",+ "edit_workflow_content",+ "publish_confirm_value",+ "publish_draft",+ "trigger_has_audience",+]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 5093e1a12acb..2a2ac84999dd 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -140,10 +140,13 @@ from products.workflows.backend.facade.contracts import (WorkflowBatchJobNotFound,WorkflowDraftChanged,WorkflowDraftExists,+ WorkflowHasNoDraft,WorkflowProposalRecord,WorkflowRevisionNotFound,WorkflowRevisionSummary,WorkflowScheduleNotFound,+ WorkflowStale,+ WorkflowWriteResult,)from products.workflows.backend.facade.email_design import (apply_email_design_operations,@@ -216,6 +219,17 @@ from products.workflows.backend.facade.validation import (is_duration,is_signed_duration,)+from products.workflows.backend.facade.writes import (+ build_publish_impact,+ compute_action_redirects,+ create_workflow,+ destroy_workflow,+ discard_draft,+ edit_workflow_content,+ publish_confirm_value,+ publish_draft,+ trigger_has_audience,+)from products.workflows.backend.models.hog_flow.hog_flow import (BILLABLE_ACTION_TYPES,MESSAGING_ACTION_TYPES,@@ -228,7 +242,6 @@ from products.workflows.backend.models.hog_flow.hog_flow import ()from products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.models.workflow_proposal import WorkflowProposal-from products.workflows.backend.presentation.views.action_redirects import compute_action_redirectsfrom products.workflows.backend.presentation.views.graph_operations import apply_graph_operationsfrom products.workflows.backend.presentation.views.graph_validation import validate_graphfrom products.workflows.backend.presentation.views.hog_flow_batch_job import (@@ -245,7 +258,6 @@ from products.workflows.backend.presentation.views.message_assets import (MessageAssetSerializer,MessageAssetsRequestSerializer,)-from products.workflows.backend.presentation.views.publish_impact import build_publish_impactfrom products.workflows.backend.services.timing_reschedule import (get_all_timing_action_ids,get_timing_reschedule_action_ids,@@ -291,6 +303,15 @@ def _without_bytecode_contracts(node: Any) -> Any:return node+def _trigger_has_audience(hog_flow: HogFlow) -> bool:+ """Whether a dispatch of this workflow fans out to persons matched by the trigger's filters.++ Only the batch trigger does. A schedule trigger fires one person-less run, so there is no+ audience to preview and no blast-radius token to demand.+ """+ return (hog_flow.trigger or {}).get("type") == "batch"++def _wait_condition_already_stored(action: dict, context: dict) -> bool:"""True when this wait's condition matches the one already persisted for the same action.@@ -2081,15 +2102,6 @@ def _hog_flow_run_idempotency_cache_key(team_id: int, hog_flow_id: str, idempotereturn f"hog_flow_run_idempotency:{team_id}:{hog_flow_id}:{idempotency_key}"-def _trigger_has_audience(hog_flow: HogFlow) -> bool:- """Whether a dispatch of this workflow fans out to persons matched by the trigger's filters.-- Only the batch trigger does. A schedule trigger fires one person-less run, so there is no- audience to preview and no blast-radius token to demand.- """- return (hog_flow.trigger or {}).get("type") == "batch"--def _email_sending_rates(sent: int, bounced: int, complained: int) -> dict[str, float | int]:# Sends are counted at send time but bounces/complaints at webhook time, so feedback arriving# just inside the window for sends just outside it can push the ratio past 1 (worst case: a@@ -4135,13 +4147,10 @@ PUBLISH_CONFIRM_TOKEN_MAX_AGE = timedelta(minutes=15)_PUBLISH_CONFIRM_SALT = "hogflow-publish"-def _publish_confirm_value(hog_flow: HogFlow) -> str:- draft_updated_at = hog_flow.draft_updated_at.isoformat() if hog_flow.draft_updated_at else ""- return f"{hog_flow.id}:{draft_updated_at}"--def mint_publish_confirm_token(hog_flow: HogFlow) -> str:- return TimestampSigner(salt=_PUBLISH_CONFIRM_SALT).sign(_publish_confirm_value(hog_flow))+ return TimestampSigner(salt=_PUBLISH_CONFIRM_SALT).sign(+ publish_confirm_value(hog_flow_id=hog_flow.id, draft_updated_at=hog_flow.draft_updated_at)+ )# Same structural-unskippability pattern for batch dispatch: only the blast-radius preview mints@@ -4687,9 +4696,12 @@ class HogFlowViewSet("Create as draft, test with workflows-test-run, then enable with workflows-enable.")- with transaction.atomic():- serializer.save()- self._append_revision(serializer.instance, created_by=self._revision_author())+ result = create_workflow(+ team_id=self.team_id,+ user_id=self._actor_id(),+ validated_data=serializer.validated_data,+ )+ serializer.instance = HogFlow(**result.current)log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, detail_type="standard")self._emit_resource_edited(serializer.instance)@@ -4857,7 +4869,7 @@ class HogFlowViewSet(flow_id = instance.idwith transaction.atomic():log_activity_from_viewset(self, instance, activity="deleted", name=instance.name)- instance.delete()+ destroy_workflow(team_id=self.team_id, hog_flow_id=instance.pk)instance.id = flow_idself._report_workflow_action("hog_flow_deleted", instance, {"via": "destroy"})@@ -4941,6 +4953,33 @@ class HogFlowViewSet(# An edit over an approved draft may undo the suggestion, and publish reads approved as shipped.unstage_workflow_proposals(team_id=instance.team_id, hog_flow_id=instance.pk)+ def _actor_id(self) -> Optional[int]:+ return self.request.user.id if self.request.user.is_authenticated else None++ @staticmethod+ def _apply_written_state(instance: HogFlow, result: WorkflowWriteResult) -> None:+ # Not refresh_from_db: a write that another request commits after this lock releases must not+ # appear in this request's activity diff, events or response.+ for attname, value in result.current.items():+ setattr(instance, attname, value)++ def _report_schedules_paused(self, result: WorkflowWriteResult, instance: HogFlow) -> None:+ if result.schedules_paused:+ self._report_workflow_action(+ "hog_flow_schedules_paused_on_audience_change", instance, {"paused": result.schedules_paused}+ )++ def _validate_locked_content(self, instance: HogFlow, data: dict, enforce_graph_structure: bool = False) -> dict:+ # Runs inside the write's row lock: reload first so validation reads the locked row.+ instance.refresh_from_db()+ serializer = self.get_serializer(instance, data=data, partial=True)+ if enforce_graph_structure:+ # The surgical endpoints are the paths where structural corruption would be newly introduced,+ # so they enforce graph validation as a hard error (unlike the lenient full-save path).+ serializer.context["enforce_graph_structure"] = True+ serializer.is_valid(raise_exception=True)+ return serializer.validated_data+@extend_schema(request=HogFlowGraphUpdateSerializer, responses={200: HogFlowSerializer})@action(detail=True, methods=["PATCH"])def graph(self, request: Request, *args, **kwargs):@@ -4954,68 +4993,40 @@ class HogFlowViewSet(# Authorize + team-scope via the normal lookup, then re-read FOR UPDATE inside the transaction.instance = self.get_object()- with transaction.atomic():- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)- locked = HogFlow.objects.select_for_update().get(pk=instance.pk)-- route_to_draft = self._is_mcp_request(request) and locked.status == HogFlow.State.ACTIVE-- # Optimistic concurrency, mirroring perform_update: the graph endpoint is the only MCP- # path that writes graph content, so it carries the base_updated_at staleness contract.- # Draft edits race against other draft edits, so the baseline is the draft's timestamp- # once one exists.- base_updated_at_raw = request.data.get("base_updated_at")- base_updated_at = parse_datetime(base_updated_at_raw) if base_updated_at_raw else None- if base_updated_at is not None and timezone.is_naive(base_updated_at):- base_updated_at = timezone.make_aware(base_updated_at)- guard_timestamp = locked.updated_at- if route_to_draft and locked.draft_updated_at:- guard_timestamp = locked.draft_updated_at- if base_updated_at and guard_timestamp and guard_timestamp > base_updated_at:- raise StaleWorkflowUpdateError()-- # Draft edits compose on the staged draft, not on live — a second patch must see the first.- if route_to_draft and locked.draft:- base_actions = list(locked.draft.get("actions") or [])- base_edges = list(locked.draft.get("edges") or [])- else:- base_actions = list(locked.actions or [])- base_edges = list(locked.edges or [])-+ def edit(base_actions: list[dict], base_edges: list[dict]) -> dict:new_actions, new_edges = apply_graph_operations(base_actions, base_edges, operations)+ return self._validate_locked_content(+ instance, {"actions": new_actions, "edges": new_edges}, enforce_graph_structure=True+ )- serializer = self.get_serializer(locked, data={"actions": new_actions, "edges": new_edges}, partial=True)- # The surgical endpoint is the one path where structural corruption would be newly introduced,- # so it enforces graph validation as a hard error (unlike the lenient full-save path).- serializer.context["enforce_graph_structure"] = True- serializer.is_valid(raise_exception=True)-- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)- before_update = HogFlow.objects.get(pk=instance.pk)- if route_to_draft:- self._write_draft(locked, locked, serializer.validated_data)- else:- self._refresh_action_redirects(locked, before_update, serializer.validated_data.get("actions"))- bump = self._stage_revision_bump(locked, before_update, serializer.validated_data)- # save() mutates and returns `locked` in place, so it's the saved HogFlow from here on.- serializer.save()- if bump:- self._append_revisions(locked, before_update)+ try:+ result = edit_workflow_content(+ team_id=self.team_id,+ user_id=self._actor_id(),+ hog_flow_id=instance.pk,+ stage_if_active=self._is_mcp_request(request),+ base_updated_at=request.data.get("base_updated_at"),+ edit=edit,+ changes_graph=True,+ )+ except WorkflowStale:+ raise StaleWorkflowUpdateError()+ self._apply_written_state(instance, result)- if not route_to_draft:- self._maybe_reschedule_timing_edits(before_update, locked)- self._pause_schedules_on_audience_change(before_update, locked)+ self._report_schedules_paused(result, instance)# Explicit "updated" (the action name "graph" isn't in ACTIVITY_TYPES, which would fall back to# the indistinct "changed" and miss the describer's per-field rendering).- log_activity_from_viewset(self, locked, activity="updated", name=locked.name, previous=before_update)- self._emit_resource_edited(locked)+ log_activity_from_viewset(+ self, instance, activity="updated", name=instance.name, previous=HogFlow(**result.previous)+ )+ self._emit_resource_edited(instance)self._report_workflow_action("hog_flow_graph_updated",- locked,- {"operations_count": len(operations), "routed_to_draft": route_to_draft},+ instance,+ {"operations_count": len(operations), "routed_to_draft": result.routed_to_draft},)- return Response(self.get_serializer(locked).data)+ return Response(self.get_serializer(instance).data)@extend_schema(parameters=[@@ -5053,62 +5064,41 @@ class HogFlowViewSet(render_base = list(instance.actions or [])rendered = _render_action_email_operations(render_base, action_id, operations)- with transaction.atomic():- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)- locked = HogFlow.objects.select_for_update().get(pk=instance.pk)-- route_to_draft = self._is_mcp_request(request) and locked.status == HogFlow.State.ACTIVE-- # Same staleness contract as /graph: draft edits race against other draft edits, so the- # baseline is the draft's timestamp once one exists.- base_updated_at_raw = request.data.get("base_updated_at")- base_updated_at = parse_datetime(base_updated_at_raw) if base_updated_at_raw else None- if base_updated_at is not None and timezone.is_naive(base_updated_at):- base_updated_at = timezone.make_aware(base_updated_at)- guard_timestamp = locked.updated_at- if route_to_draft and locked.draft_updated_at:- guard_timestamp = locked.draft_updated_at- if base_updated_at and guard_timestamp and guard_timestamp > base_updated_at:- raise StaleWorkflowUpdateError()-- # Draft edits compose on the staged draft, not on live - a second patch must see the first.- if route_to_draft and locked.draft:- base_actions = list(locked.draft.get("actions") or [])- else:- base_actions = list(locked.actions or [])-+ def edit(base_actions: list[dict], base_edges: list[dict]) -> dict:new_actions = _apply_action_email_edit(base_actions, action_id, email_patch, rendered)+ return self._validate_locked_content(instance, {"actions": new_actions}, enforce_graph_structure=True)- serializer = self.get_serializer(locked, data={"actions": new_actions}, partial=True)- serializer.context["enforce_graph_structure"] = True- serializer.is_valid(raise_exception=True)-- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)- before_update = HogFlow.objects.get(pk=instance.pk)- if route_to_draft:- self._write_draft(locked, locked, serializer.validated_data)- else:- bump = self._stage_revision_bump(locked, before_update, serializer.validated_data)- # save() mutates and returns `locked` in place, so it's the saved HogFlow from here on.- serializer.save()- if bump:- self._append_revisions(locked, before_update)+ # Same staleness and draft contract as /graph, but no action-redirect refresh or timing+ # reschedule: an email edit can't delete steps or change timing config.+ try:+ result = edit_workflow_content(+ team_id=self.team_id,+ user_id=self._actor_id(),+ hog_flow_id=instance.pk,+ stage_if_active=self._is_mcp_request(request),+ base_updated_at=request.data.get("base_updated_at"),+ edit=edit,+ changes_graph=False,+ )+ except WorkflowStale:+ raise StaleWorkflowUpdateError()+ self._apply_written_state(instance, result)- # Unlike /graph, no action-redirect refresh or timing reschedule: an email edit can't delete- # steps or change timing config.- log_activity_from_viewset(self, locked, activity="updated", name=locked.name, previous=before_update)- self._emit_resource_edited(locked)+ log_activity_from_viewset(+ self, instance, activity="updated", name=instance.name, previous=HogFlow(**result.previous)+ )+ self._emit_resource_edited(instance)self._report_workflow_action("hog_flow_action_email_updated",- locked,+ instance,{"operations_count": len(operations),"merged_fields": sorted(email_patch.keys()),- "routed_to_draft": route_to_draft,+ "routed_to_draft": result.routed_to_draft,},)- return Response(self.get_serializer(locked).data)+ return Response(self.get_serializer(instance).data)def _maybe_reschedule_timing_edits(self, before: Optional[HogFlow], after: HogFlow) -> None:"""Kick off a reschedule sweep of parked runs when a go-live config change could move@@ -5301,40 +5291,28 @@ class HogFlowViewSet(})- with transaction.atomic():- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)- locked = HogFlow.objects.select_for_update().get(pk=instance.pk)- if not locked.draft:- raise exceptions.ValidationError("This workflow has no staged draft to publish.")- if previewed_value != _publish_confirm_value(locked):- raise StaleWorkflowUpdateError()+ def validate(content: dict) -> dict:+ return self._validate_locked_content(instance, content)- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)- before_update = HogFlow.objects.get(pk=instance.pk)- # The draft goes back through the normal serializer so publish revalidates strictly and- # recompiles bytecode — a stored blob is never trusted to be execution-ready.- serializer = self.get_serializer(locked, data=dict(locked.draft), partial=True)- serializer.is_valid(raise_exception=True)- self._refresh_action_redirects(locked, before_update, serializer.validated_data.get("actions"))- bump = self._stage_revision_bump(locked, before_update, serializer.validated_data)- # save() runs update(), which recovers the draft's secrets (from the merged live+draft- # encrypted maps) and re-splits them into the live encrypted_inputs column. The draft's own- # secret column is then cleared alongside the draft.- serializer.save()- if bump:- self._append_revisions(locked, before_update)- locked.draft = None- locked.draft_updated_at = None- locked.draft_encrypted_inputs = None- locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])- # Every path that changes the draft unstages what it dropped, so whatever is approved here just went live.- WorkflowProposal.objects.filter(hog_flow=locked, status=WorkflowProposal.Status.APPROVED).update(- status=WorkflowProposal.Status.APPLIED, applied_version=locked.version+ try:+ result = publish_draft(+ team_id=self.team_id,+ user_id=self._actor_id(),+ hog_flow_id=instance.pk,+ previewed_value=previewed_value,+ validate=validate,)+ except WorkflowHasNoDraft:+ raise exceptions.ValidationError("This workflow has no staged draft to publish.")+ except WorkflowStale:+ raise StaleWorkflowUpdateError()+ self._apply_written_state(instance, result)+ locked = instance- self._maybe_reschedule_timing_edits(before_update, locked)- self._pause_schedules_on_audience_change(before_update, locked)- log_activity_from_viewset(self, locked, activity="published", name=locked.name, previous=before_update)+ self._report_schedules_paused(result, locked)+ log_activity_from_viewset(+ self, locked, activity="published", name=locked.name, previous=HogFlow(**result.previous)+ )self._emit_resource_edited(locked)self._report_workflow_action("hog_flow_draft_published", locked)@@ -5352,29 +5330,17 @@ class HogFlowViewSet(@extend_schema(request=None, responses={200: HogFlowSerializer})@action(detail=True, methods=["POST"])def discard_draft(self, request: Request, *args, **kwargs):- # Throw away the staged draft. Idempotent: discarding when nothing is staged is a no-op.instance = self.get_object()- with transaction.atomic():- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)- locked = HogFlow.objects.select_for_update().get(pk=instance.pk)- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)- before_update = HogFlow.objects.get(pk=instance.pk)- locked.draft = None- locked.draft_updated_at = None- locked.draft_encrypted_inputs = None- # updated_at (auto_now) is deliberately bumped: without a fresh live stamp the- # resource_edited broadcast carries the old updated_at — older than the draft stamp- # concurrent editors loaded, so they'd ignore the discard, and their next draft save- # would pass the staleness guard (which falls back to the live stamp once the draft is- # gone) and silently resurrect the discarded draft.- locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs", "updated_at"])- unstage_workflow_proposals(team_id=locked.team_id, hog_flow_id=locked.pk)+ result = discard_draft(team_id=self.team_id, hog_flow_id=instance.pk)+ self._apply_written_state(instance, result)- log_activity_from_viewset(self, locked, activity="draft_discarded", name=locked.name, previous=before_update)- self._emit_resource_edited(locked)- self._report_workflow_action("hog_flow_draft_discarded", locked)+ log_activity_from_viewset(+ self, instance, activity="draft_discarded", name=instance.name, previous=HogFlow(**result.previous)+ )+ self._emit_resource_edited(instance)+ self._report_workflow_action("hog_flow_draft_discarded", instance)- return Response(self.get_serializer(locked).data)+ return Response(self.get_serializer(instance).data)@extend_schema(responses={200: HogFlowRevisionBasicSerializer(many=True)})# filter_backends=[]: don't inherit the viewset's HogFlow filterset — its fields would be@@ -5417,7 +5383,7 @@ class HogFlowViewSet(instance = self.get_object()restored_version = int(version or 0)try:- restore_revision(+ result = restore_revision(hog_flow_id=instance.pk,version=restored_version,overwrite=param_serializer.validated_data["overwrite"],@@ -5429,10 +5395,12 @@ class HogFlowViewSet(raise DraftExistsError()except WorkflowDraftChanged:raise StaleWorkflowUpdateError()- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance)- locked = HogFlow.objects.get(pk=instance.pk)+ self._apply_written_state(instance, result)+ locked = instance- log_activity_from_viewset(self, locked, activity="revision_restored", name=locked.name, previous=instance)+ log_activity_from_viewset(+ self, locked, activity="revision_restored", name=locked.name, previous=HogFlow(**result.previous)+ )self._emit_resource_edited(locked)self._report_workflow_action("hog_flow_revision_restored", locked, {"version": restored_version})@@ -6552,7 +6520,7 @@ class HogFlowViewSet(# could sidestep the batch_jobs token gate by scheduling the send instead. Same scoping:# the web builder keeps its own confirm UI, headless callers stay token-free. A schedule# trigger runs once per firing with no person audience, so there is nothing to size.- if get_event_source(request) in AGENT_EVENT_SOURCES and _trigger_has_audience(hog_flow):+ if get_event_source(request) in AGENT_EVENT_SOURCES and trigger_has_audience(hog_flow.trigger):# A draft's trigger can still be edited after the audience was sized, so a schedule# staged on a draft could fire on a broadened audience once enabled. Same rule the# MCP tool enforces, applied at the API boundary.diff --git a/products/workflows/backend/presentation/views/action_redirects.py b/products/workflows/backend/services/action_redirects.pysimilarity index 100%rename from products/workflows/backend/presentation/views/action_redirects.pyrename to products/workflows/backend/services/action_redirects.pydiff --git a/products/workflows/backend/services/hog_flow_revisions.py b/products/workflows/backend/services/hog_flow_revisions.pyindex 939875e81468..4cdaec5aeda9 100644--- a/products/workflows/backend/services/hog_flow_revisions.py+++ b/products/workflows/backend/services/hog_flow_revisions.py@@ -10,9 +10,11 @@ from products.workflows.backend.facade.contracts import (WorkflowRevision,WorkflowRevisionNotFound,WorkflowRevisionSummary,+ WorkflowWriteResult,)from products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_revision import HogFlowRevision+from products.workflows.backend.services.hog_flow_writes import field_valuesfrom products.workflows.backend.services.workflow_proposals import unstage_proposals_for_flow@@ -47,10 +49,11 @@ def get_revision(*, hog_flow_id: UUID, version: int) -> WorkflowRevision | None:def restore_revision(*, hog_flow_id: UUID, version: int, overwrite: bool, expected_draft_updated_at: datetime | None-) -> None:+) -> WorkflowWriteResult:with transaction.atomic():# nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)locked = HogFlow.objects.select_for_update().get(pk=hog_flow_id)+ previous = field_values(locked)try:revision = HogFlowRevision.objects.get(hog_flow_id=locked.pk, version=version)except HogFlowRevision.DoesNotExist:@@ -74,3 +77,4 @@ def restore_revision(# Clear any stale draft secrets from a prior draft so they can't bleed into this one.locked.draft_encrypted_inputs = Nonelocked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])+ return WorkflowWriteResult(previous=previous, current=field_values(locked))diff --git a/products/workflows/backend/services/hog_flow_writes.py b/products/workflows/backend/services/hog_flow_writes.pynew file mode 100644index 000000000000..3f551aafacf8--- /dev/null+++ b/products/workflows/backend/services/hog_flow_writes.py@@ -0,0 +1,364 @@+from collections.abc import Callable+from datetime import datetime+from typing import Any, Optional+from uuid import UUID++from django.db import transaction+from django.utils import timezone+from django.utils.dateparse import parse_datetime++from products.workflows.backend.facade.contracts import WorkflowHasNoDraft, WorkflowStale, WorkflowWriteResult+from products.workflows.backend.facade.enums import HogFlowScheduleStatus+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow_revision import HogFlowRevision+from products.workflows.backend.services.action_redirects import compute_action_redirects+from products.workflows.backend.services.hog_flow_content import DRAFT_CONTENT_FIELDS, snapshot_flow_content+from products.workflows.backend.services.hog_flow_secrets import (+ TemplateCache,+ strip_content_secrets,+ strip_secrets_from_content,+)+from products.workflows.backend.services.timing_reschedule import (+ get_all_timing_action_ids,+ get_timing_reschedule_action_ids,+)+from products.workflows.backend.services.workflow_proposals import (+ apply_approved_proposals_for_flow,+ unstage_workflow_proposals,+)+from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timing+++def field_values(flow: HogFlow) -> dict[str, object]:+ return {field.attname: getattr(flow, field.attname) for field in flow._meta.concrete_fields}+++def create_workflow(*, team_id: int, user_id: Optional[int], validated_data: dict) -> WorkflowWriteResult:+ with transaction.atomic():+ data = dict(validated_data)+ if "actions" in data:+ data["encrypted_inputs"] = strip_secrets_from_content(data, template_cache={})+ instance = HogFlow.objects.create(team_id=team_id, created_by_id=user_id, **data)+ HogFlowRevision.objects.create(+ team_id=team_id,+ hog_flow=instance,+ version=instance.version,+ content=snapshot_flow_content(instance),+ created_by_id=user_id,+ )+ return WorkflowWriteResult(previous={}, current=field_values(instance))+++def destroy_workflow(*, team_id: int, hog_flow_id: UUID) -> None:+ HogFlow.objects.get(team_id=team_id, pk=hog_flow_id).delete()+++def trigger_has_audience(trigger: Optional[dict]) -> bool:+ """Whether a dispatch of this workflow fans out to persons matched by the trigger's filters.++ Only the batch trigger does. A schedule trigger fires one person-less run, so there is no+ audience to preview and no blast-radius token to demand.+ """+ return (trigger or {}).get("type") == "batch"+++def publish_confirm_value(*, hog_flow_id: UUID, draft_updated_at: Optional[datetime]) -> str:+ draft_stamp = draft_updated_at.isoformat() if draft_updated_at else ""+ return f"{hog_flow_id}:{draft_stamp}"+++def _without_bytecode_contracts(node: Any) -> Any:+ # Every recompile writes the current runtime's stamp beside each filter and input bytecode. A flow+ # stored before stamping, or under an older runtime, gets a new stamp on its next save even when+ # nobody changed it, so the revision comparison must not count the stamp as content. A stamp only+ # ever sits next to a `bytecode` key, so a same-named key inside a person's own JSON value stays+ # content and still versions the flow.+ if isinstance(node, dict):+ derived = "bytecode" in node+ return {+ key: _without_bytecode_contracts(value)+ for key, value in node.items()+ if not (derived and key == "bytecode_contract")+ }+ if isinstance(node, list):+ return [_without_bytecode_contracts(item) for item in node]+ return node+++def _parse_stamp(raw: Optional[str]) -> Optional[datetime]:+ stamp = parse_datetime(raw) if raw else None+ # A timezone-less timestamp parses naive; comparing it to the tz-aware stored updated_at would+ # raise TypeError (500). Assume UTC so callers can send a bare ISO string.+ if stamp is not None and timezone.is_naive(stamp):+ stamp = timezone.make_aware(stamp)+ return stamp+++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+ # 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}+ if "actions" in data:+ data["encrypted_inputs"] = strip_secrets_from_content(data, template_cache={})+ for attr, value in data.items():+ setattr(instance, attr, value)+ instance.save()+++def _refresh_action_redirects(target: HogFlow, old: HogFlow, new_actions: Optional[list]) -> None:+ # Skip-forward for deleted steps: refresh the redirect map whenever a live graph write is about+ # to land, while both the old graph (`old`, the locked pre-write row) and the new actions are in+ # hand. Must run before the save so the map persists in the same write, transaction,+ # and worker reload as the graph it describes.+ # No status gate: disabling a flow doesn't purge its parked runs (the worker only cancels them+ # if they wake while the flow is still disabled), so a step deleted during a disable/re-enable+ # window needs its redirect recorded just like one deleted live.+ if new_actions is None:+ return+ target.action_redirects = compute_action_redirects(+ old.actions or [], old.edges or [], new_actions, old.action_redirects+ )+++def _stage_revision_bump(instance: HogFlow, before: HogFlow, validated_data: dict) -> bool:+ # Revision history: only live-content changes get a version. Compared pre-save so the bumped+ # version lands in the same UPDATE (and worker reload) as the content it describes. The+ # serializer injects derived fields (trigger, billable_action_types) into every validated+ # payload, so a status/metadata-only write compares equal here and stays unversioned.+ raw_old = snapshot_flow_content(before)+ raw_new = {+ **raw_old,+ **{field: validated_data[field] for field in DRAFT_CONTENT_FIELDS if field in validated_data},+ }+ # Compare secret-free on both sides. `raw_new` still carries the plaintext secrets validation+ # recovered into `actions` (stripping happens later in the save), while `before` is the persisted+ # stripped snapshot; without this a secret-bearing flow would bump on every actions-carrying save.+ template_cache: TemplateCache = {}+ old_content = _without_bytecode_contracts(strip_content_secrets(raw_old, template_cache))+ new_content = _without_bytecode_contracts(strip_content_secrets(raw_new, template_cache))+ if new_content == old_content:+ return False+ instance.version = (before.version or 0) + 1+ return True+++def _append_revisions(team_id: int, user_id: Optional[int], instance: HogFlow, before: HogFlow) -> None:+ # Must run inside the same transaction as the content write it snapshots. On the first+ # tracked write, also snapshot the outgoing live content so the state before any tracked+ # change is always available to roll back to (there's no backfill).+ if not HogFlowRevision.objects.filter(team_id=team_id, hog_flow=instance).exists():+ HogFlowRevision.objects.create(+ team_id=team_id,+ hog_flow=instance,+ version=before.version,+ content=snapshot_flow_content(before),+ created_by=None,+ )+ HogFlowRevision.objects.create(+ team_id=team_id,+ hog_flow=instance,+ version=instance.version,+ content=snapshot_flow_content(instance),+ created_by_id=user_id,+ )+++def _write_draft(instance: HogFlow, locked: HogFlow, validated_data: dict) -> None:+ # The draft is always a full content snapshot (live config as the base, staged draft on top,+ # this edit's validated fields last) so publish is a plain copy with no merge logic.+ draft = {**snapshot_flow_content(locked), **(locked.draft or {})}+ for field in DRAFT_CONTENT_FIELDS:+ if field in validated_data:+ draft[field] = validated_data[field]++ # Keep secrets out of the draft snapshot too. When this edit carried the full action set (its+ # secrets recovered in-place), split them into the draft's own encrypted column and strip the+ # snapshot; otherwise the draft's secrets are unchanged. Publish/restore re-attach from here.+ draft_encrypted_inputs = locked.draft_encrypted_inputs+ if "actions" in validated_data:+ draft_encrypted_inputs = strip_secrets_from_content(draft, template_cache={})++ instance.draft = draft+ instance.draft_updated_at = timezone.now()+ instance.draft_encrypted_inputs = draft_encrypted_inputs+ instance.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])++ # An edit over an approved draft may undo the suggestion, and publish reads approved as shipped.+ unstage_workflow_proposals(team_id=instance.team_id, hog_flow_id=instance.pk)+++def _reschedule_timing_edits(team_id: int, before: HogFlow, after: HogFlow) -> None:+ """Kick off a reschedule sweep of parked runs when a go-live config change could move+ their wake times earlier or change what they resolve to (issue #66380): shortened+ delays, moved wait windows, edited wait conditions, and deleted timing steps (whose+ parked runs should skip forward or exit now, not at their old wake time).++ Called wherever the LIVE config changes - a direct save (the builder path, where save+ is go-live), the graph endpoint, or publish - and never for draft writes, which don't+ touch what runs execute. Deliberately called AFTER the writing transaction, so the diff and+ the enqueue never extend the select_for_update row-lock hold. on_commit outside an atomic+ block runs the enqueue immediately, and in tests (where an outer transaction wraps the+ request) it defers to that commit.+ """+ if after.status != HogFlow.State.ACTIVE:+ return+ if before.status != HogFlow.State.ACTIVE:+ # Re-enable: runs parked during the prior active period survive a disable (cancelled+ # lazily, at wake, only while the flow is inactive), and timing edits made while+ # inactive never swept - so converge every timing step rather than diffing against a+ # baseline that may predate any number of unswept edits.+ action_ids = get_all_timing_action_ids(after.actions)+ else:+ action_ids = get_timing_reschedule_action_ids(before.actions, after.actions)+ if not action_ids:+ return+ hog_flow_id = str(after.id)+ transaction.on_commit(+ lambda: reschedule_hog_flow_timing.delay(team_id=team_id, hog_flow_id=hog_flow_id, action_ids=action_ids)+ )+++def _pause_schedules_on_audience_change(before: HogFlow, after: HogFlow) -> int:+ """Pause every active schedule when the audience a batch dispatch fans out to changes.++ The scheduler reads the live trigger at fire time, so each firing broadcasts to whatever+ the trigger says then, not to what someone confirmed when the schedule was created. Two+ edits break that confirmation: a person-less trigger becoming `batch`, and a batch+ trigger's filters being widened. Both leave a recurring send whose recipient count nobody+ was shown, so the cadence stops until it is created again through the audience preview.++ Called wherever the LIVE trigger changes (direct save, graph edit, publish), never for+ draft writes, which don't change what the scheduler reads. Returns how many it paused.+ """+ if not trigger_has_audience(after.trigger):+ return 0+ if trigger_has_audience(before.trigger) and (before.trigger or {}).get("filters") == (after.trigger or {}).get(+ "filters"+ ):+ return 0+ return after.schedules.filter(status=HogFlowScheduleStatus.ACTIVE).update(+ status=HogFlowScheduleStatus.PAUSED, next_run_at=None, updated_at=timezone.now()+ )+++def edit_workflow_content(+ *,+ team_id: int,+ user_id: Optional[int],+ hog_flow_id: UUID,+ stage_if_active: bool,+ base_updated_at: Optional[str],+ edit: Callable[[list[dict], list[dict]], dict],+ changes_graph: bool,+) -> WorkflowWriteResult:+ """Apply a surgical edit under the row lock. `edit` receives the actions and edges it builds on+ (the staged draft's when the edit stages) and returns the validated fields to write."""+ with transaction.atomic():+ locked = HogFlow.objects.select_for_update().get(pk=hog_flow_id, team_id=team_id)++ route_to_draft = stage_if_active and locked.status == HogFlow.State.ACTIVE++ # Optimistic concurrency, mirroring update_workflow: the surgical endpoints are the only MCP+ # paths that write graph content, so they carry the base_updated_at staleness contract.+ # Draft edits race against other draft edits, so the baseline is the draft's timestamp+ # once one exists.+ base_stamp = _parse_stamp(base_updated_at)+ guard_timestamp = locked.updated_at+ if route_to_draft and locked.draft_updated_at:+ guard_timestamp = locked.draft_updated_at+ if base_stamp and guard_timestamp and guard_timestamp > base_stamp:+ raise WorkflowStale()++ # Draft edits compose on the staged draft, not on live - a second patch must see the first.+ if route_to_draft and locked.draft:+ base_actions = list(locked.draft.get("actions") or [])+ base_edges = list(locked.draft.get("edges") or [])+ else:+ base_actions = list(locked.actions or [])+ base_edges = list(locked.edges or [])++ validated_data = edit(base_actions, base_edges)++ before_update = HogFlow.objects.get(pk=hog_flow_id, team_id=team_id)+ if route_to_draft:+ _write_draft(locked, locked, validated_data)+ else:+ # An email edit can't delete steps or change timing config, so only graph edits refresh redirects.+ if changes_graph:+ _refresh_action_redirects(locked, before_update, validated_data.get("actions"))+ bump = _stage_revision_bump(locked, before_update, validated_data)+ _save_live(locked, validated_data)+ if bump:+ _append_revisions(team_id, user_id, locked, before_update)++ paused = 0+ if changes_graph and not route_to_draft:+ _reschedule_timing_edits(team_id, before_update, locked)+ paused = _pause_schedules_on_audience_change(before_update, locked)+ return WorkflowWriteResult(+ previous=field_values(before_update),+ current=field_values(locked),+ routed_to_draft=route_to_draft,+ schedules_paused=paused,+ )+++def publish_draft(+ *,+ team_id: int,+ user_id: Optional[int],+ hog_flow_id: UUID,+ previewed_value: str,+ validate: Callable[[dict], dict],+) -> WorkflowWriteResult:+ """Promote the staged draft to the live config. `validate` receives the draft content and returns+ the validated fields to write."""+ with transaction.atomic():+ locked = HogFlow.objects.select_for_update().get(pk=hog_flow_id, team_id=team_id)+ if not locked.draft:+ raise WorkflowHasNoDraft()+ if previewed_value != publish_confirm_value(hog_flow_id=locked.id, draft_updated_at=locked.draft_updated_at):+ raise WorkflowStale()++ before_update = HogFlow.objects.get(pk=hog_flow_id, team_id=team_id)+ # The draft goes back through the normal serializer so publish revalidates strictly and+ # recompiles bytecode - a stored blob is never trusted to be execution-ready.+ validated_data = validate(dict(locked.draft))+ _refresh_action_redirects(locked, before_update, validated_data.get("actions"))+ bump = _stage_revision_bump(locked, before_update, validated_data)+ # Validation recovered the draft's secrets (from the merged live+draft encrypted maps), and+ # the save re-splits them into the live encrypted_inputs column. The draft's own secret+ # column is then cleared alongside the draft.+ _save_live(locked, validated_data)+ if bump:+ _append_revisions(team_id, user_id, locked, before_update)+ locked.draft = None+ locked.draft_updated_at = None+ locked.draft_encrypted_inputs = None+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])+ apply_approved_proposals_for_flow(locked)++ _reschedule_timing_edits(team_id, before_update, locked)+ paused = _pause_schedules_on_audience_change(before_update, locked)+ return WorkflowWriteResult(+ previous=field_values(before_update), current=field_values(locked), schedules_paused=paused+ )+++def discard_draft(*, team_id: int, hog_flow_id: UUID) -> WorkflowWriteResult:+ """Throw away the staged draft. Idempotent: discarding when nothing is staged is a no-op."""+ with transaction.atomic():+ locked = HogFlow.objects.select_for_update().get(pk=hog_flow_id, team_id=team_id)+ before_update = HogFlow.objects.get(pk=hog_flow_id, team_id=team_id)+ locked.draft = None+ locked.draft_updated_at = None+ locked.draft_encrypted_inputs = None+ # updated_at (auto_now) is deliberately bumped: without a fresh live stamp the+ # resource_edited broadcast carries the old updated_at - older than the draft stamp+ # concurrent editors loaded, so they'd ignore the discard, and their next draft save+ # would pass the staleness guard (which falls back to the live stamp once the draft is+ # gone) and silently resurrect the discarded draft.+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs", "updated_at"])+ unstage_workflow_proposals(team_id=locked.team_id, hog_flow_id=locked.pk)+ return WorkflowWriteResult(previous=field_values(before_update), current=field_values(locked))diff --git a/products/workflows/backend/presentation/views/publish_impact.py b/products/workflows/backend/services/publish_impact.pysimilarity index 98%rename from products/workflows/backend/presentation/views/publish_impact.pyrename to products/workflows/backend/services/publish_impact.pyindex 95d16d226352..713771af1135 100644--- a/products/workflows/backend/presentation/views/publish_impact.py+++ b/products/workflows/backend/services/publish_impact.py@@ -1,7 +1,7 @@import refrom typing import Any, Optional-from products.workflows.backend.presentation.views.action_redirects import compute_action_redirects+from products.workflows.backend.services.action_redirects import compute_action_redirects# Publish-time impact summary: what applying a staged draft will do to people already in the flow.# Pure functions over the two graphs plus externally-fetched counts, so the matrix is unit-testablediff --git a/products/workflows/backend/services/workflow_proposals.py b/products/workflows/backend/services/workflow_proposals.pyindex 2e3d616ff503..58133186d378 100644--- a/products/workflows/backend/services/workflow_proposals.py+++ b/products/workflows/backend/services/workflow_proposals.py@@ -497,6 +497,12 @@ def _write_leaf(item: dict, path: tuple[str, ...], value: Any) -> None:item[path[-1]] = value+def apply_approved_proposals_for_flow(hog_flow: HogFlow) -> None:+ WorkflowProposal.objects.filter(hog_flow=hog_flow, status=WorkflowProposal.Status.APPROVED).update(+ status=WorkflowProposal.Status.APPLIED, applied_version=hog_flow.version+ )++def unstage_proposals_for_flow(hog_flow: HogFlow) -> None:"""Put back in the queue any approved suggestion whose change the draft no longer carries.diff --git a/products/workflows/backend/tests/api/test_action_redirects.py b/products/workflows/backend/tests/api/test_action_redirects.pyindex 3b4e89173614..785e8e467848 100644--- a/products/workflows/backend/tests/api/test_action_redirects.py+++ b/products/workflows/backend/tests/api/test_action_redirects.py@@ -2,10 +2,7 @@ from unittest import TestCasefrom parameterized import parameterized-from products.workflows.backend.presentation.views.action_redirects import (- MAX_ACTION_REDIRECTS,- compute_action_redirects,-)+from products.workflows.backend.services.action_redirects import MAX_ACTION_REDIRECTS, compute_action_redirectsdef _actions(*ids: str) -> list[dict]:diff --git a/products/workflows/backend/tests/api/test_hog_flow_timing_reschedule.py b/products/workflows/backend/tests/api/test_hog_flow_timing_reschedule.pyindex 788b428df2ef..a9ba0d869183 100644--- a/products/workflows/backend/tests/api/test_hog_flow_timing_reschedule.py+++ b/products/workflows/backend/tests/api/test_hog_flow_timing_reschedule.py@@ -117,7 +117,7 @@ class TestHogFlowTimingRescheduleTrigger(APIBaseTest):assert response.status_code == 200, response.json()mock_task.delay.assert_not_called()- @patch(TASK_PATH)+ @patch("products.workflows.backend.services.hog_flow_writes.reschedule_hog_flow_timing")def test_mcp_draft_routed_edit_does_not_enqueue_sweep(self, mock_task):flow_id = self._create_flow()@@ -128,7 +128,7 @@ class TestHogFlowTimingRescheduleTrigger(APIBaseTest):assert HogFlow.objects.get(pk=flow_id).draft is not Nonemock_task.delay.assert_not_called()- @patch(TASK_PATH)+ @patch("products.workflows.backend.services.hog_flow_writes.reschedule_hog_flow_timing")def test_publish_of_timing_shortening_draft_enqueues_sweep(self, mock_task):flow_id = self._create_flow()response = self._patch_delay_via_mcp(flow_id)@@ -169,7 +169,7 @@ class TestHogFlowTimingRescheduleTrigger(APIBaseTest):assert enable.status_code == 200, enable.json()mock_task.delay.assert_called_once_with(team_id=self.team.id, hog_flow_id=flow_id, action_ids=["delay_1"])- @patch(TASK_PATH)+ @patch("products.workflows.backend.services.hog_flow_writes.reschedule_hog_flow_timing")def test_graph_operation_shortening_delay_enqueues_sweep(self, mock_task):flow_id = self._create_flow()diff --git a/products/workflows/backend/tests/api/test_publish_impact.py b/products/workflows/backend/tests/api/test_publish_impact.pyindex 6e42b5640d78..b6220e8f87b1 100644--- a/products/workflows/backend/tests/api/test_publish_impact.py+++ b/products/workflows/backend/tests/api/test_publish_impact.py@@ -4,7 +4,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from products.workflows.backend.presentation.views.publish_impact import build_publish_impact, find_variable_references+from products.workflows.backend.services.publish_impact import build_publish_impact, find_variable_referencesdef _action(action_id: str, name: str | None = None, output_variable: dict | list | None = None, **config) -> dict: