: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
fix(workflows): write the first revision when a workflow is created (#104156)
Michael Reichenbach59a4f4b9712d
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 3d9b344b5317..7d48913e0257 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -361,8 +361,10 @@ def snapshot_flow_content(flow: HogFlow) -> dict:snapshot[field] = []# Defensively strip secrets: a legacy row written before encryption shipped still has plaintext# secret inputs in `actions`, and this snapshot feeds revision content — which must never carry- # secrets. New rows are already stripped, so this is a no-op for them.- return strip_content_secrets(snapshot)+ # secrets. New rows are already stripped, so this is a no-op for them. Every create takes a+ # snapshot inside its transaction, so the cache resolves each template once instead of once per+ # action.+ return strip_content_secrets(snapshot, template_cache={})# --- Secret function-action inputs -------------------------------------------------------------@@ -1299,6 +1301,7 @@ class HogFlowActionSerializer(serializers.Serializer):on_error = serializers.ChoiceField(choices=["continue", "abort"],required=False,+ default=None,allow_null=True,help_text="On failure: continue (skip the action and proceed) or abort (stop the run).",)@@ -1378,6 +1381,7 @@ class HogFlowActionSerializer(serializers.Serializer):)output_variable = serializers.JSONField(required=False,+ default=None,allow_null=True,help_text="Output variable for downstream actions: {key, result_path?, spread?, label?} or a list of those.",)@@ -5056,7 +5060,9 @@ class HogFlowViewSet("Create as draft, test with workflows-test-run, then enable with workflows-enable.")- serializer.save()+ with transaction.atomic():+ serializer.save()+ self._append_revision(serializer.instance, created_by=self._revision_author())log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, detail_type="standard")self._emit_resource_edited(serializer.instance)@@ -5264,25 +5270,27 @@ class HogFlowViewSet(return Truedef _append_revisions(self, 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).+ # 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():- HogFlowRevision.objects.create(- team_id=self.team_id,- hog_flow=instance,- version=before.version,- content=snapshot_flow_content(before),- created_by=None,- )+ 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=instance,- version=instance.version,- content=snapshot_flow_content(instance),- created_by=self.request.user if self.request.user.is_authenticated else None,+ 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.@@ -6583,7 +6591,8 @@ class HogFlowViewSet(.filter(id__in=[flow.id for flow in deletable]).values_list("id", flat=True))- deleted_count, _ = self.get_queryset().filter(id__in=deleted_ids).delete()+ _, deleted_by_model = self.get_queryset().filter(id__in=deleted_ids).delete()+ deleted_count = deleted_by_model.get(HogFlow._meta.label, 0)deleted_flows = [flow for flow in deletable if flow.id in deleted_ids]for flow in deleted_flows:log_activity_from_viewset(self, flow, activity="deleted", name=flow.name)diff --git a/products/workflows/backend/tests/api/test_hog_flow_revisions.py b/products/workflows/backend/tests/api/test_hog_flow_revisions.pyindex fb8f62c7e683..14ac7e9dc1c6 100644--- a/products/workflows/backend/tests/api/test_hog_flow_revisions.py+++ b/products/workflows/backend/tests/api/test_hog_flow_revisions.py@@ -10,7 +10,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow-from products.workflows.backend.presentation.views.hog_flow import DRAFT_CONTENT_FIELDS+from products.workflows.backend.presentation.views.hog_flow import DRAFT_CONTENT_FIELDS, snapshot_flow_contentwebhook_template = MOCK_NODE_TEMPLATES[0]@@ -129,6 +129,51 @@ class TestHogFlowRevisions(APIBaseTest):assert response.status_code == 200, response.json()return response.json()["content"]+ @parameterized.expand([("web", None), ("mcp", "mcp")])+ def test_create_writes_first_revision(self, _name, client_header):+ extra = {"HTTP_X_POSTHOG_CLIENT": client_header} if client_header else {}+ create = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]},+ **extra,+ )+ assert create.status_code == 201, create.json()+ flow_id = create.json()["id"]+ assert create.json()["version"] == 1++ revisions = self._list_revisions(flow_id)+ assert [r["version"] for r in revisions] == [1]+ assert revisions[0]["created_by"]["id"] == self.user.id+ content = self._revision_content(flow_id, 1)+ assert set(content.keys()) == set(DRAFT_CONTENT_FIELDS)+ assert content["actions"] == HogFlow.objects.get(pk=flow_id).actions++ def test_revision_snapshot_resolves_a_shared_template_once(self):+ flow = HogFlow(+ team=self.team,+ name="Many steps",+ actions=[_trigger_action(), *[_webhook_action(f"action_{i}") for i in range(5)]],+ edges=[],+ )+ with self.assertNumQueries(1):+ snapshot_flow_content(flow)++ def test_create_then_resave_of_response_keeps_single_revision(self):+ create = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]},+ )+ assert create.status_code == 201, create.json()+ flow_id = create.json()["id"]++ resave = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"name": "Renamed", "actions": create.json()["actions"], "edges": create.json()["edges"]},+ )+ assert resave.status_code == 200, resave.json()+ assert resave.json()["version"] == 1+ assert [r["version"] for r in self._list_revisions(flow_id)] == [1]+# ── Appending on live-content writes ─────────────────────────────def test_publish_appends_revision_and_bumps_version(self):@@ -138,11 +183,10 @@ class TestHogFlowRevisions(APIBaseTest):assert published.json()["workflow"]["version"] == 2revisions = self._list_revisions(flow_id)- # Newest-first: v2 (this user's publish) then the v1 bootstrap snapshot (no author)+ # Newest-first: v2 (this user's publish) then the v1 snapshot the create wroteassert [r["version"] for r in revisions] == [2, 1]assert revisions[0]["created_by"]["id"] == self.user.id- assert revisions[1]["created_by"] is None- # First write also snapshots the outgoing live content, so there's always a state to roll back to+ assert revisions[1]["created_by"]["id"] == self.user.idv1_urls = [a["config"]["inputs"]["url"]["value"]for a in self._revision_content(flow_id, 1)["actions"]@@ -199,7 +243,7 @@ class TestHogFlowRevisions(APIBaseTest):extra = {"HTTP_X_POSTHOG_CLIENT": client_header} if client_header else {}response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}{path_suffix}", payload, **extra)assert response.status_code == 200, response.json()- assert self._list_revisions(flow_id) == []+ assert [r["version"] for r in self._list_revisions(flow_id)] == [1]assert response.json()["version"] == 1@parameterized.expand([("stored_before_stamping", None), ("stamped_by_an_older_runtime", "0000000000000000")])@@ -215,7 +259,7 @@ class TestHogFlowRevisions(APIBaseTest):activate = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})assert activate.status_code == 200, activate.json()assert activate.json()["version"] == 1- assert self._list_revisions(flow_id) == []+ assert [r["version"] for r in self._list_revisions(flow_id)] == [1]def test_an_authored_key_named_like_the_stamp_still_versions_the_flow(self):# The stamp is stripped from the comparison only where it sits beside a bytecode. A person's@@ -268,7 +312,7 @@ class TestHogFlowRevisions(APIBaseTest):results = response.json()["results"]assert [r["version"] for r in results] == [2, 1]assert results[0]["created_by"]["id"] == self.user.id- assert results[1]["created_by"] is None, "the bootstrap snapshot has no author and must serialize as null"+ assert results[1]["created_by"]["id"] == self.user.idassert "content" not in results[0]detail = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/1")