: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 workflow write path through the facade (#110632)
Harley Alexander91089ee2f6fc
diff --git a/products/workflows/backend/facade/writes.py b/products/workflows/backend/facade/writes.pyindex 1fd955bb3ccf..024ecfcd7450 100644--- a/products/workflows/backend/facade/writes.py+++ b/products/workflows/backend/facade/writes.py@@ -1,7 +1,6 @@"""The workflow write path: live saves, staged drafts, surgical edits, publish and discard, each underthe 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_redirectsfrom products.workflows.backend.services.hog_flow_writes import (DRAFT_CONTENT_FIELDS,create_workflow,@@ -11,13 +10,13 @@ from products.workflows.backend.services.hog_flow_writes import (publish_confirm_value,publish_draft,trigger_has_audience,+ update_workflow,)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",@@ -25,4 +24,5 @@ __all__ = ["publish_confirm_value","publish_draft","trigger_has_audience",+ "update_workflow",]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 2a2ac84999dd..96d081505414 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -19,7 +19,6 @@ from django.db.models.expressions import RawSQLfrom django.db.models.functions import Coalescefrom django.http import Http404, HttpResponsefrom django.utils import timezone-from django.utils.dateparse import parse_datetimeimport requestsimport structlog@@ -221,7 +220,6 @@ from products.workflows.backend.facade.validation import ()from products.workflows.backend.facade.writes import (build_publish_impact,- compute_action_redirects,create_workflow,destroy_workflow,discard_draft,@@ -229,6 +227,7 @@ from products.workflows.backend.facade.writes import (publish_confirm_value,publish_draft,trigger_has_audience,+ update_workflow,)from products.workflows.backend.models.hog_flow.hog_flow import (BILLABLE_ACTION_TYPES,@@ -240,7 +239,6 @@ from products.workflows.backend.models.hog_flow.hog_flow import (WORKFLOW_SAFE_INTERNAL_EVENTS,HogFlow,)-from products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.models.workflow_proposal import WorkflowProposalfrom products.workflows.backend.presentation.views.graph_operations import apply_graph_operationsfrom products.workflows.backend.presentation.views.graph_validation import validate_graph@@ -258,11 +256,6 @@ from products.workflows.backend.presentation.views.message_assets import (MessageAssetSerializer,MessageAssetsRequestSerializer,)-from products.workflows.backend.services.timing_reschedule import (- get_all_timing_action_ids,- get_timing_reschedule_action_ids,-)-from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timinglogger = structlog.get_logger(__name__)@@ -285,33 +278,6 @@ def _authored_condition(condition: Optional[dict]) -> Optional[dict]:}-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 _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.@@ -4753,106 +4719,30 @@ class HogFlowViewSet(# existing raw-API automation is unaffected.route_to_draft = bool(set(self.request.data.keys()) & set(DRAFT_CONTENT_FIELDS))- instance_id = serializer.instance.id-- # Optimistic concurrency: a client may send the `updated_at` it last loaded as `base_updated_at`.- # If the stored row is strictly newer, another channel (a second UI tab, MCP, or the API) wrote in- # between, so we reject with 409 rather than silently clobbering it. Strictly-newer (not equality)- # avoids false positives from timestamp round-tripping — equal means the client is already current.- # Callers that omit `base_updated_at` keep the previous last-writer-wins behavior.- base_updated_at_raw = self.request.data.get("base_updated_at")- base_updated_at = parse_datetime(base_updated_at_raw) if base_updated_at_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 base_updated_at is not None and timezone.is_naive(base_updated_at):- base_updated_at = timezone.make_aware(base_updated_at)-- with transaction.atomic():- try:- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance; locked for the staleness check + save)- before_update = HogFlow.objects.select_for_update().get(pk=instance_id)- except HogFlow.DoesNotExist:- before_update = None-- # Draft edits race against other draft edits, not against the live row (which they don't- # touch), so the staleness baseline is the draft's own timestamp once a draft exists.- guard_timestamp = before_update.updated_at if before_update else None- if route_to_draft and before_update and before_update.draft_updated_at:- guard_timestamp = before_update.draft_updated_at- # The web builder sends "includes_staged_draft" (raw body, like "stage_draft") when a save on- # a non-active workflow carries the staged draft merged into it. The draft is only cleared on- # that explicit signal, so an API caller that resends live content never loses a draft.- clears_staged_draft = (- not route_to_draft- and before_update is not None- and before_update.status != HogFlow.State.ACTIVE- and before_update.draft is not None- and bool(self.request.data.get("includes_staged_draft"))- and WRITABLE_DRAFT_CONTENT_FIELDS <= self.request.data.keys()+ try:+ result = update_workflow(+ team_id=self.team_id,+ user_id=self._actor_id(),+ hog_flow_id=serializer.instance.id,+ validated_data=serializer.validated_data,+ route_to_draft=route_to_draft,+ base_updated_at=self.request.data.get("base_updated_at"),+ base_live_updated_at=self.request.data.get("base_live_updated_at"),+ includes_staged_draft=bool(self.request.data.get("includes_staged_draft"))+ and WRITABLE_DRAFT_CONTENT_FIELDS <= self.request.data.keys(),+ validated_status=serializer.instance.status,)- if clears_staged_draft:- assert before_update is not None- # A revision restore writes the draft without moving the live stamp, so fence on the newer one.- if before_update.draft_updated_at and (- guard_timestamp is None or before_update.draft_updated_at > guard_timestamp- ):- guard_timestamp = before_update.draft_updated_at- if base_updated_at and guard_timestamp and guard_timestamp > base_updated_at:- raise StaleWorkflowUpdateError()+ except WorkflowStale:+ raise StaleWorkflowUpdateError()+ self._apply_written_state(serializer.instance, result)+ before_update = HogFlow(**result.previous)- if route_to_draft:- assert before_update is not None- self._write_draft(serializer.instance, before_update, serializer.validated_data)- # Metadata in the same payload still applies live. Content (and the fields validate()- # derives from it — trigger, billable_action_types) must not leak onto the live row:- # they were computed from the draft's graph.- remaining = {- k: v- for k, v in serializer.validated_data.items()- if k not in DRAFT_CONTENT_FIELDS and k != "billable_action_types"- }- if remaining:- # The draft-stamp guard above doesn't protect this live write: a concurrent- # live-metadata edit bumps updated_at but not draft_updated_at, so a staged save- # would silently overwrite it. Clients that write metadata alongside a staged- # draft send the live stamp they loaded as a second fence.- base_live_raw = self.request.data.get("base_live_updated_at")- base_live = parse_datetime(base_live_raw) if base_live_raw else None- if base_live is not None and timezone.is_naive(base_live):- base_live = timezone.make_aware(base_live)- if base_live and before_update.updated_at and before_update.updated_at > base_live:- raise StaleWorkflowUpdateError()- serializer.validated_data.clear()- serializer.validated_data.update(remaining)- serializer.save()- else:- bump = False- if before_update is not None:- self._refresh_action_redirects(- serializer.instance, before_update, serializer.validated_data.get("actions")- )- bump = self._stage_revision_bump(serializer.instance, before_update, serializer.validated_data)- if clears_staged_draft:- serializer.save(draft=None, draft_updated_at=None, draft_encrypted_inputs=None)- unstage_workflow_proposals(team_id=serializer.instance.team_id, hog_flow_id=serializer.instance.pk)- else:- serializer.save()- if bump:- assert before_update is not None- self._append_revisions(serializer.instance, before_update)-- if not route_to_draft:- self._maybe_reschedule_timing_edits(before_update, serializer.instance)- self._pause_schedules_on_audience_change(before_update, serializer.instance)+ self._report_schedules_paused(result, serializer.instance)log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=before_update)self._emit_resource_edited(serializer.instance)# PostHog capture for hog_flow activated (draft -> active)- if (- before_update- and before_update.status == HogFlow.State.DRAFT- and serializer.instance.status == HogFlow.State.ACTIVE- ):+ if before_update.status == HogFlow.State.DRAFT and serializer.instance.status == HogFlow.State.ACTIVE:self._report_workflow_action("hog_flow_activated",serializer.instance,@@ -4873,86 +4763,6 @@ class HogFlowViewSet(instance.id = flow_idself._report_workflow_action("hog_flow_deleted", instance, {"via": "destroy"})- def _refresh_action_redirects(self, 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 serializer.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(self, 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 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(self, instance: HogFlow, before: HogFlow) -> None:- # Must run inside the same transaction as the content write it snapshots. A workflow created- # before the create path wrote revisions has no rows, and there is no backfill. On its first- # tracked write, also snapshot the outgoing live content, so the state before any tracked- # change stays available to roll back to.- if not HogFlowRevision.objects.filter(hog_flow=instance).exists():- self._append_revision(before, created_by=None)- self._append_revision(instance, created_by=self._revision_author())-- def _append_revision(self, flow: HogFlow, *, created_by: User | None) -> None:- HogFlowRevision.objects.create(- team_id=self.team_id,- hog_flow=flow,- version=flow.version,- content=snapshot_flow_content(flow),- created_by=created_by,- )-- def _revision_author(self) -> User | None:- user = self.request.user- return user if isinstance(user, User) else None-- def _write_draft(self, 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 _actor_id(self) -> Optional[int]:return self.request.user.id if self.request.user.is_authenticated else None@@ -5100,61 +4910,6 @@ class HogFlowViewSet(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- 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 not before or 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- team_id = self.team_id- 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(self, before: Optional[HogFlow], after: HogFlow) -> None:- """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.- """- if not before or not _trigger_has_audience(after):- return- if _trigger_has_audience(before) and (before.trigger or {}).get("filters") == (after.trigger or {}).get(- "filters"- ):- return- paused = after.schedules.filter(status=HogFlowScheduleStatus.ACTIVE).update(- status=HogFlowScheduleStatus.PAUSED, next_run_at=None, updated_at=timezone.now()- )- if paused:- self._report_workflow_action("hog_flow_schedules_paused_on_audience_change", after, {"paused": paused})-def _require_audience_confirm_token(self, request: Request, hog_flow: HogFlow) -> None:"""Only meaningful for triggers that fan out to a person audience; see _trigger_has_audience."""confirm_token = request.data.get("confirm_token")diff --git a/products/workflows/backend/services/hog_flow_writes.py b/products/workflows/backend/services/hog_flow_writes.pyindex 3f551aafacf8..e3e7d6477404 100644--- a/products/workflows/backend/services/hog_flow_writes.py+++ b/products/workflows/backend/services/hog_flow_writes.py@@ -9,7 +9,7 @@ from django.utils.dateparse import parse_datetimefrom products.workflows.backend.facade.contracts import WorkflowHasNoDraft, WorkflowStale, WorkflowWriteResultfrom 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.hog_flow import BILLABLE_ACTION_TYPES, ROW_SCOPED_TRIGGER_TYPES, HogFlowfrom products.workflows.backend.models.hog_flow_revision import HogFlowRevisionfrom products.workflows.backend.services.action_redirects import compute_action_redirectsfrom products.workflows.backend.services.hog_flow_content import DRAFT_CONTENT_FIELDS, snapshot_flow_content@@ -106,6 +106,32 @@ def _save_live(instance: HogFlow, validated_data: dict, **overrides: object) ->instance.save()+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 a+ # concurrent graph write can change those actions before the lock. Derive these fields again from the+ # locked actions, so that the save does not pair the new graph with fields derived from the old graph.+ if "actions" in validated_data:+ return validated_data+ actions = locked.actions or []+ derived = dict(validated_data)+ trigger_action = next((action for action in actions if action.get("type") == "trigger"), None)+ if "trigger" in derived and trigger_action is not None:+ derived["trigger"] = trigger_action.get("config")+ if "exit_condition" in derived:+ # validate forces exit_only_at_end when the trigger it read is row-scoped. Apply that rule to the+ # locked trigger instead. When only the old trigger forced the value, keep the locked row's value.+ if (derived.get("trigger") or {}).get("type") in ROW_SCOPED_TRIGGER_TYPES:+ derived["exit_condition"] = HogFlow.ExitCondition.ONLY_AT_END+ elif (validated_data.get("trigger") or {}).get("type") in ROW_SCOPED_TRIGGER_TYPES:+ del derived["exit_condition"]+ if "billable_action_types" in derived:+ derived["billable_action_types"] = sorted(+ {action.get("type", "") for action in actions if action.get("type") in BILLABLE_ACTION_TYPES}+ )+ return derived++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@@ -242,6 +268,97 @@ def _pause_schedules_on_audience_change(before: HogFlow, after: HogFlow) -> int:)+def update_workflow(+ *,+ team_id: int,+ user_id: Optional[int],+ hog_flow_id: UUID,+ validated_data: dict,+ route_to_draft: bool,+ base_updated_at: Optional[str],+ base_live_updated_at: Optional[str],+ includes_staged_draft: bool,+ validated_status: str,+) -> WorkflowWriteResult:+ # Optimistic concurrency: a client may send the `updated_at` it last loaded as `base_updated_at`.+ # If the stored row is strictly newer, another channel (a second UI tab, MCP, or the API) wrote in+ # between, so we reject with 409 rather than silently clobbering it. Strictly-newer (not equality)+ # avoids false positives from timestamp round-tripping - equal means the client is already current.+ # Callers that omit `base_updated_at` keep the previous last-writer-wins behavior.+ base_stamp = _parse_stamp(base_updated_at)++ with transaction.atomic():+ before_update = HogFlow.objects.select_for_update().get(pk=hog_flow_id, team_id=team_id)+ # Validation ran before this lock, and a draft validates leniently. If the status moved since+ # and the payload does not set it, that lenient content would land on a live workflow.+ if "status" not in validated_data and before_update.status != validated_status:+ raise WorkflowStale()+ # The write target is a second read, so `before_update` keeps the pre-write state.+ instance = HogFlow.objects.get(pk=hog_flow_id, team_id=team_id)++ # Draft edits race against other draft edits, not against the live row (which they don't+ # touch), so the staleness baseline is the draft's own timestamp once a draft exists.+ guard_timestamp = before_update.updated_at+ if route_to_draft and before_update.draft_updated_at:+ guard_timestamp = before_update.draft_updated_at+ # The web builder sends "includes_staged_draft" (raw body, like "stage_draft") when a save on+ # a non-active workflow carries the staged draft merged into it. The draft is only cleared on+ # that explicit signal, so an API caller that resends live content never loses a draft.+ clears_staged_draft = (+ not route_to_draft+ and before_update.status != HogFlow.State.ACTIVE+ and before_update.draft is not None+ and includes_staged_draft+ )+ if clears_staged_draft:+ # A revision restore writes the draft without moving the live stamp, so fence on the newer one.+ if before_update.draft_updated_at and (+ guard_timestamp is None or before_update.draft_updated_at > guard_timestamp+ ):+ guard_timestamp = before_update.draft_updated_at+ if base_stamp and guard_timestamp and guard_timestamp > base_stamp:+ raise WorkflowStale()++ if route_to_draft:+ _write_draft(instance, before_update, validated_data)+ # Metadata in the same payload still applies live. Content (and the fields validate()+ # derives from it - trigger, billable_action_types) must not leak onto the live row:+ # they were computed from the draft's graph.+ remaining = {+ k: v+ for k, v in validated_data.items()+ if k not in DRAFT_CONTENT_FIELDS and k != "billable_action_types"+ }+ if remaining:+ # The draft-stamp guard above doesn't protect this live write: a concurrent+ # live-metadata edit bumps updated_at but not draft_updated_at, so a staged save+ # would silently overwrite it. Clients that write metadata alongside a staged+ # draft send the live stamp they loaded as a second fence.+ base_live = _parse_stamp(base_live_updated_at)+ if base_live and before_update.updated_at and before_update.updated_at > base_live:+ raise WorkflowStale()+ _save_live(instance, remaining)+ else:+ validated_data = _derive_from_locked_graph(before_update, validated_data)+ _refresh_action_redirects(instance, before_update, validated_data.get("actions"))+ bump = _stage_revision_bump(instance, before_update, validated_data)+ if clears_staged_draft:+ _save_live(instance, validated_data, draft=None, draft_updated_at=None, draft_encrypted_inputs=None)+ unstage_workflow_proposals(team_id=instance.team_id, hog_flow_id=instance.pk)+ else:+ _save_live(instance, validated_data)+ if bump:+ _append_revisions(team_id, user_id, instance, before_update)++ paused = 0+ if not route_to_draft:+ _reschedule_timing_edits(team_id, before_update, instance)+ paused = _pause_schedules_on_audience_change(before_update, instance)+ return WorkflowWriteResult(+ previous=field_values(before_update), current=field_values(instance), schedules_paused=paused+ )++def edit_workflow_content(*,team_id: int,diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex b8482533d0ca..e61fea0b02fb 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -37,6 +37,7 @@ from products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cohorts.backend.models.cohort import Cohortfrom products.skills.backend.models.skills import LLMSkillfrom products.tasks.backend.facade.contracts import WorkflowLastRunDTO+from products.workflows.backend.facade.writes import update_workflowfrom products.workflows.backend.models.hog_flow.hog_flow import SUPPORTED_ACTION_TYPES, HogFlowfrom products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule@@ -4307,6 +4308,153 @@ class TestHogFlowAPI(APIBaseTest):assert "delay" in action_types # Delay is presentassert action_types.count("function") == 2 # Two function actions+ def test_metadata_update_derives_trigger_and_billable_types_from_the_locked_graph(self):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ }+ webhook_action = {+ "id": "a1",+ "name": "webhook",+ "type": "function",+ "config": {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}},+ }+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Locked graph", "actions": [trigger_action, webhook_action]},+ )+ assert response.status_code == 201, response.json()+ flow_id = response.json()["id"]++ concurrent_trigger = {+ "type": "event",+ "filters": {"events": [{"id": "$autocapture", "name": "$autocapture", "type": "events", "order": 0}]},+ }++ def update_after_concurrent_graph_write(**kwargs):+ HogFlow.objects.filter(pk=flow_id).update(+ actions=[{**trigger_action, "config": concurrent_trigger}],+ trigger=concurrent_trigger,+ billable_action_types=[],+ )+ return update_workflow(**kwargs)++ with patch(+ "products.workflows.backend.presentation.views.hog_flow.update_workflow",+ side_effect=update_after_concurrent_graph_write,+ ):+ rename = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"name": "Renamed"})++ assert rename.status_code == 200, rename.json()+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.name == "Renamed"+ assert flow.trigger == concurrent_trigger+ assert flow.billable_action_types == []++ @parameterized.expand(+ [+ (+ "locked_trigger_becomes_row_scoped",+ "event",+ "data-warehouse-table",+ "exit_only_at_end",+ {"exit_condition": "exit_on_conversion"},+ "exit_only_at_end",+ ),+ (+ "locked_trigger_stops_being_row_scoped",+ "data-warehouse-table",+ "event",+ "exit_on_conversion",+ {"name": "Renamed"},+ "exit_on_conversion",+ ),+ ]+ )+ def test_update_without_actions_derives_exit_condition_from_the_locked_trigger(+ self, _name, initial_trigger_type, concurrent_trigger_type, concurrent_exit_condition, payload, expected+ ):+ trigger_configs = {+ "event": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ "data-warehouse-table": {+ "type": "data-warehouse-table",+ "table_name": "postgres.table_1",+ "filters": {"properties": []},+ },+ }+ trigger_action = {"id": "trigger_node", "name": "trigger_1", "type": "trigger"}+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {+ "name": "Locked trigger",+ "actions": [{**trigger_action, "config": trigger_configs[initial_trigger_type]}],+ },+ )+ assert response.status_code == 201, response.json()+ flow_id = response.json()["id"]++ def update_after_concurrent_trigger_change(**kwargs):+ HogFlow.objects.filter(pk=flow_id).update(+ actions=[{**trigger_action, "config": trigger_configs[concurrent_trigger_type]}],+ trigger=trigger_configs[concurrent_trigger_type],+ exit_condition=concurrent_exit_condition,+ )+ return update_workflow(**kwargs)++ with patch(+ "products.workflows.backend.presentation.views.hog_flow.update_workflow",+ side_effect=update_after_concurrent_trigger_change,+ ):+ update = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", payload)++ assert update.status_code == 200, update.json()+ assert HogFlow.objects.get(pk=flow_id).exit_condition == expected++ def test_draft_content_save_that_races_an_activation_is_rejected(self):+ event_trigger = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ }+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Racing draft", "status": "draft", "actions": [event_trigger]},+ )+ assert response.status_code == 201, response.json()+ flow_id = response.json()["id"]++ def update_after_concurrent_activation(**kwargs):+ HogFlow.objects.filter(pk=flow_id).update(status=HogFlow.State.ACTIVE)+ return update_workflow(**kwargs)++ # A Slack trigger with no channel passes draft validation but must never run live.+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.update_workflow",+ side_effect=update_after_concurrent_activation,+ ):+ update = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"actions": [self._slack_trigger_action([])]},+ )++ assert update.status_code == 409, update.json()+ assert update.json()["code"] == "stale_update"+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.status == HogFlow.State.ACTIVE+ assert flow.actions[0]["config"]["type"] == "event"+@override_settings(HOGFLOW_BATCH_TRIGGER_LIMIT=5000, HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS=set())@patch("products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"@@ -4841,6 +4989,37 @@ class TestHogFlowAPI(APIBaseTest):assert name_change["before"] == original_nameassert name_change["after"] == new_name+ def test_update_activity_excludes_a_write_committed_after_the_lock_releases(self):+ hog_flow, _ = self._create_hog_flow_with_action(+ {+ "template_id": "template-webhook",+ "inputs": {"url": {"value": "https://example.com"}},+ }+ )+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ flow_id = response.json()["id"]+ original_name = response.json()["name"]++ def update_then_concurrent_rename(**kwargs):+ result = update_workflow(**kwargs)+ HogFlow.objects.filter(pk=flow_id).update(name="Renamed elsewhere")+ return result++ with patch(+ "products.workflows.backend.presentation.views.hog_flow.update_workflow",+ side_effect=update_then_concurrent_rename,+ ):+ update_response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"description": "New description"}+ )+ assert update_response.status_code == status.HTTP_200_OK, update_response.json()+ assert update_response.json()["name"] == original_name++ latest = self._get_hog_flow_activity(flow_id)[0]+ assert latest["detail"]["name"] == original_name+ assert {change["field"] for change in latest["detail"]["changes"]} == {"description"}+def test_hog_flow_draft_allows_incomplete_actions(self):trigger_action = {"id": "trigger_node",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 a9ba0d869183..ec4c860e9dce 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@@ -10,7 +10,7 @@ from products.workflows.backend.models.hog_flow.hog_flow import HogFlowwebhook_template = MOCK_NODE_TEMPLATES[0]-TASK_PATH = "products.workflows.backend.presentation.views.hog_flow.reschedule_hog_flow_timing"+TASK_PATH = "products.workflows.backend.services.hog_flow_writes.reschedule_hog_flow_timing"def _actions(delay_duration: str = "7d", webhook_url: str = "https://example.com") -> list[dict]:@@ -117,7 +117,7 @@ class TestHogFlowTimingRescheduleTrigger(APIBaseTest):assert response.status_code == 200, response.json()mock_task.delay.assert_not_called()- @patch("products.workflows.backend.services.hog_flow_writes.reschedule_hog_flow_timing")+ @patch(TASK_PATH)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("products.workflows.backend.services.hog_flow_writes.reschedule_hog_flow_timing")+ @patch(TASK_PATH)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("products.workflows.backend.services.hog_flow_writes.reschedule_hog_flow_timing")+ @patch(TASK_PATH)def test_graph_operation_shortening_delay_enqueues_sweep(self, mock_task):flow_id = self._create_flow()diff --git a/pyproject.toml b/pyproject.tomlindex 350097ad5a6c..4931202d375d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -719,10 +719,7 @@ ignore_imports = [# the facade."products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.api.message_templates","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow.hog_flow",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_revision","products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.workflow_proposal",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.timing_reschedule",- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.tasks.hog_flows",# TODO: access-control presentation wave — the consolidated RBAC viewsets carry their ORM# access with them. Thin them to parse -> facade -> serialize and delete each entry."products.access_control.backend.presentation.access_control -> products.access_control.backend.models.access_control",