Skip to content

: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.

fix(workflows): Backfill event-based conversions into conversion.events (#62355)

Daniel Marchuk635a1bcdc9c6
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index c651138707a1..0befc8ff53cd 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -645,6 +645,16 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
conversion = data.get("conversion")
if conversion is not None:
filters = conversion.get("filters")
+ # Forward guard for the legacy bad shape (see migration 0009): an event-based conversion
+ # goal stored as an object in `conversion.filters` (e.g. {"events": [...], "source": "events"})
+ # belongs in `conversion.events`. `conversion.filters` is an array of property filters, so the
+ # object both crashes the property picker and is invisible to the matcher. Relocate it here so
+ # no client (web UI, API, MCP) can persist the malformed shape; it then compiles through the
+ # conversion.events path below.
+ if isinstance(filters, dict) and filters.get("events"):
+ data["conversion"]["events"] = [*(conversion.get("events") or []), {"filters": filters}]
+ data["conversion"]["filters"] = []
+ filters = []
if filters:
serializer = HogFunctionFiltersSerializer(data={"properties": filters}, context=self.context)
if self.context.get("is_draft"):
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index d88a0a7f55be..77b2c60c2e01 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -306,6 +306,32 @@ class TestHogFlowAPI(APIBaseTest):
}
assert flow_conversion["bytecode"] == expected_conversion_bytecode
+ def test_hog_flow_conversion_event_object_in_filters_is_relocated(self):
+ # A client (e.g. MCP) that sends an event-based conversion goal as an object in the property
+ # slot must not persist the malformed shape: it is relocated to conversion.events and compiled,
+ # and conversion.filters is cleared. Mirrors the one-time backfill in migration 0009. Without
+ # this guard the object would fail property-list validation (non-draft) or silently persist.
+ event_obj = {
+ "events": [{"id": "purchase", "name": "purchase", "type": "events", "order": 0}],
+ "source": "events",
+ }
+ hog_flow, _ = self._create_hog_flow_with_action(
+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}
+ )
+ hog_flow["status"] = "active"
+ hog_flow["conversion"] = {"filters": event_obj, "window_minutes": None}
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 201, response.json()
+
+ conversion = response.json()["conversion"]
+ assert conversion["filters"] == [], conversion
+ assert len(conversion["events"]) == 1, conversion
+ moved = conversion["events"][0]["filters"]
+ assert moved["events"] == event_obj["events"]
+ assert moved["bytecode"], moved
+ assert "purchase" in moved["bytecode"]
+
def test_hog_flow_conversion_filters_compiles_bytecode_on_update(self):
expected_conversion_bytecode = [
"_H",
diff --git a/products/workflows/backend/management/__init__.py b/products/workflows/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/workflows/backend/management/commands/__init__.py b/products/workflows/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/workflows/backend/management/commands/backfill_conversion_filters_to_events.py b/products/workflows/backend/management/commands/backfill_conversion_filters_to_events.py
new file mode 100644
index 000000000000..1af3bd26103f
--- /dev/null
+++ b/products/workflows/backend/management/commands/backfill_conversion_filters_to_events.py
@@ -0,0 +1,62 @@
+from django.core.management.base import BaseCommand
+
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+
+
+class Command(BaseCommand):
+ help = (
+ "Relocate event-based conversion goals stored in the wrong slot. Before the conversion.events "
+ "slot existed, an event-based goal could be saved as an object in conversion.filters "
+ "(e.g. {'events': [...], 'source': 'events'}). conversion.filters is meant to be an array of "
+ "property filters, so the object crashes the property-conversion picker and is invisible to "
+ "the subscription matcher (which reads conversion.events). This moves it to "
+ "conversion.events = [{filters: <object>}] and clears the property slot. Behaviour-neutral "
+ "(no bytecode compiled here; it recompiles on the next save) and idempotent. Default dry-run; "
+ "pass --live-run to apply. The serializer guard prevents new rows in this shape, so this only "
+ "needs to run once per environment."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument("--team-id", default=None, type=int, help="Limit to a specific team ID")
+ parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")
+
+ def handle(self, *args, **options):
+ live_run = options.get("live_run", False)
+ team_id = options.get("team_id")
+ mode = "LIVE RUN" if live_run else "DRY RUN"
+ self.stdout.write(f"Starting backfill_conversion_filters_to_events ({mode})")
+
+ flows = HogFlow.objects.filter(conversion__isnull=False)
+ if team_id:
+ flows = flows.filter(team_id=team_id)
+ self.stdout.write(f"Filtering to team_id={team_id}")
+
+ relocated = 0
+ for flow in flows.iterator():
+ conversion = flow.conversion or {}
+ filters = conversion.get("filters")
+
+ # A valid conversion.filters is a list of property filters (or absent). The only malformed
+ # shape we fix is the event object {"events": [...], "source": "events"} that predates the
+ # conversion.events slot. Leave any other shape untouched.
+ if not isinstance(filters, dict) or not filters.get("events"):
+ continue
+
+ new_conversion = dict(conversion)
+ new_conversion["events"] = [*(new_conversion.get("events") or []), {"filters": filters}]
+ new_conversion["filters"] = []
+ new_conversion["bytecode"] = []
+
+ self.stdout.write(
+ f" {'Relocating' if live_run else 'Would relocate'} conversion for flow id={flow.id} "
+ f"team_id={flow.team_id} status={flow.status}"
+ )
+ if live_run:
+ # .update() avoids bumping updated_at / firing save signals for a backfill.
+ HogFlow.objects.filter(pk=flow.pk).update(conversion=new_conversion)
+ relocated += 1
+
+ verb = "relocated" if live_run else "to relocate"
+ self.stdout.write(self.style.SUCCESS(f"Completed ({mode}): {relocated} flow(s) {verb}"))
+ if not live_run and relocated > 0:
+ self.stdout.write(self.style.NOTICE("Run with --live-run to apply changes"))
diff --git a/products/workflows/backend/test/test_hog_flow.py b/products/workflows/backend/test/test_hog_flow.py
index cb6b1ddf0b5a..9dfd1fafaf0c 100644
--- a/products/workflows/backend/test/test_hog_flow.py
+++ b/products/workflows/backend/test/test_hog_flow.py
@@ -1,5 +1,6 @@
from unittest.mock import patch
+from django.core.management import call_command
from django.test import TestCase
from posthog.models.user import User
@@ -30,3 +31,52 @@ class TestHogFlow(TestCase):
def test_team_saved_receiver(self, mock_refresh):
self.team.save()
mock_refresh.assert_called_once_with(team_id=self.team.id)
+
+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")
+ def test_backfill_conversion_filters_to_events_command(self, _mock_reload):
+ # Event-based conversion stored in the wrong slot (the legacy shape we're fixing).
+ event_obj = {
+ "events": [{"id": "purchase", "name": "purchase", "type": "events", "order": 0}],
+ "source": "events",
+ }
+ bad = HogFlow.objects.create(
+ name="bad",
+ team=self.team,
+ conversion={"window_minutes": 60, "filters": event_obj, "bytecode": ["_H", 1, 29]},
+ )
+ # Correctly-shaped property conversion — must be left untouched.
+ good_filters = [{"key": "plan", "type": "person", "value": ["growth"], "operator": "exact"}]
+ good = HogFlow.objects.create(
+ name="good",
+ team=self.team,
+ conversion={"window_minutes": 30, "filters": good_filters, "bytecode": ["_H", 1, 1]},
+ )
+
+ # Dry-run (the default) must not change anything.
+ call_command("backfill_conversion_filters_to_events")
+ bad.refresh_from_db()
+ assert bad.conversion is not None and isinstance(bad.conversion["filters"], dict)
+
+ # Live-run relocates the bad shape and leaves the good one untouched.
+ call_command("backfill_conversion_filters_to_events", "--live-run")
+
+ bad.refresh_from_db()
+ bad_conversion = bad.conversion
+ assert bad_conversion is not None
+ assert bad_conversion["filters"] == []
+ assert bad_conversion["bytecode"] == []
+ assert bad_conversion["events"] == [{"filters": event_obj}]
+
+ good.refresh_from_db()
+ good_conversion = good.conversion
+ assert good_conversion is not None
+ assert good_conversion["filters"] == good_filters
+ assert not good_conversion.get("events")
+
+ # Idempotent: a second live-run must not double-move or change anything.
+ call_command("backfill_conversion_filters_to_events", "--live-run")
+ bad.refresh_from_db()
+ bad_conversion = bad.conversion
+ assert bad_conversion is not None
+ assert bad_conversion["filters"] == []
+ assert bad_conversion["events"] == [{"filters": event_obj}]