: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
feat(workflows): stamp existing workflows without rewriting what they match (#106870)
Meikel Ratzfcd91ea8b0f2
diff --git a/posthog/management/commands/refresh_hog_flows.py b/posthog/management/commands/refresh_hog_flows.pyindex fe1482cb6e88..1e870cd2165e 100644--- a/posthog/management/commands/refresh_hog_flows.py+++ b/posthog/management/commands/refresh_hog_flows.py@@ -1,30 +1,34 @@import time+from copy import deepcopy+from typing import Anyfrom django.core.management.base import BaseCommandfrom django.core.paginator import Paginator+from django.db import transactionfrom django.test import RequestFactoryimport structlog-from products.workflows.backend.api.hog_flow import HogFlowSerializer+from products.workflows.backend.api.hog_flow import (+ HogFlowSerializer,+ TemplateCache,+ mask_secret_action_inputs,+ merge_secret_maps,+ partition_flow_secrets,+ plaintext_secret_map,+)from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = structlog.get_logger(__name__)-def remove_event_filters_from_conditionals(actions):- updated_actions = []- for action in actions:- conditions = action.get("config", {}).get("conditions", [])- if conditions:- for condition in conditions:- filters = condition.get("filters", {})- if "events" in filters:- del filters["events"]-- updated_actions.append(action)-- return updated_actions+def _secret_values(secrets: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:+ # Compare secrets by value only. The save recompiles each input, so its bytecode can change.+ return {+ action_id: {key: value.get("value") if isinstance(value, dict) else value for key, value in inputs.items()}+ for action_id, inputs in secrets.items()+ if inputs+ }class Command(BaseCommand):@@ -39,6 +43,11 @@ class Command(BaseCommand):type=str,help="Specific HogFlow ID to refresh (if provided, only this flow is processed)",)+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Report what would be re-saved, and which flows no longer validate, without saving.",+ )parser.add_argument("--page-size",type=int,@@ -55,10 +64,11 @@ class Command(BaseCommand):team_id = options.get("team_id")hog_flow_id = options.get("hog_flow_id")page_size = options.get("page_size", 1000)+ dry_run: bool = options.get("dry_run", False)- self.stdout.write("Starting HogFlow refresh...")+ self.stdout.write("Starting HogFlow refresh..." + (" (dry run, nothing is saved)" if dry_run else ""))- queryset = HogFlow.objects.select_related("team")+ queryset = HogFlow.objects.all()if hog_flow_id:queryset = queryset.filter(id=hog_flow_id)@@ -76,86 +86,132 @@ class Command(BaseCommand):self.stdout.write(self.style.WARNING("No HogFlows found matching criteria"))return- paginator = Paginator(queryset.order_by("id"), page_size)+ paginator = Paginator(queryset.order_by("id").values_list("id", flat=True), page_size)for page_num in paginator.page_range:page = paginator.page(page_num)self.stdout.write(f"Processing page {page_num}/{paginator.num_pages} ({len(page.object_list)} flows)...")- for hog_flow in page.object_list:+ for flow_id in page.object_list:+ hog_flow = Nonetry:- total_processed += 1-- # Create a mock request context for the serializer- request = RequestFactory().post("/")- if hog_flow.created_by:- request.user = hog_flow.created_by-- def get_team_func(flow=hog_flow):- return flow.team-- serializer_context = {- "request": request,- "team_id": hog_flow.team_id,- "get_team": get_team_func,- }-- # Get the current data from the HogFlow- data = {- "name": hog_flow.name,- "description": hog_flow.description,- "status": hog_flow.status,- "trigger": hog_flow.trigger,- "trigger_masking": hog_flow.trigger_masking,- "conversion": hog_flow.conversion,- "exit_condition": hog_flow.exit_condition,- "edges": hog_flow.edges,- "actions": hog_flow.actions,- "variables": hog_flow.variables,- }-- data["actions"] = remove_event_filters_from_conditionals(hog_flow.actions)-- # Process through serializer to regenerate bytecode- serializer = HogFlowSerializer(- instance=hog_flow, data=data, context=serializer_context, partial=True- )+ # Reload and lock each flow just before its save. A copy loaded with the page goes+ # stale, and a full save of it overwrites any edit made while the page runs.+ with transaction.atomic():+ flows = HogFlow.objects if dry_run else HogFlow.objects.select_for_update()+ hog_flow = flows.filter(id=flow_id).first()+ if hog_flow is None:+ continue+ total_processed += 1++ # Create a mock request context for the serializer+ request = RequestFactory().post("/")+ if hog_flow.created_by:+ request.user = hog_flow.created_by++ def get_team_func(flow=hog_flow):+ return flow.team++ serializer_context = {+ "request": request,+ "team_id": hog_flow.team_id,+ "get_team": get_team_func,+ }++ # Stored actions hold no secret inputs. Resend each live secret as the+ # {"secret": true} marker, so validation recovers it as it does for an editor save.+ template_cache: TemplateCache = {}+ live_secrets = merge_secret_maps(+ plaintext_secret_map(hog_flow.actions, template_cache), hog_flow.encrypted_inputs+ )+ actions = mask_secret_action_inputs(+ deepcopy(hog_flow.actions or []), live_secrets, template_cache+ )- if serializer.is_valid():- serializer.save()- total_updated += 1- logger.info(- "Successfully refreshed HogFlow",- hog_flow_id=str(hog_flow.id),- team_id=hog_flow.team_id,- status=hog_flow.status,- name=hog_flow.name,- version=hog_flow.version,+ # Get the current data from the HogFlow+ data = {+ "name": hog_flow.name,+ "description": hog_flow.description,+ "status": hog_flow.status,+ "trigger": hog_flow.trigger,+ "trigger_masking": hog_flow.trigger_masking,+ "conversion": hog_flow.conversion,+ "exit_condition": hog_flow.exit_condition,+ "edges": hog_flow.edges,+ "actions": actions,+ "variables": hog_flow.variables,+ }++ # Process through serializer to regenerate bytecode+ serializer = HogFlowSerializer(+ instance=hog_flow, data=data, context=serializer_context, partial=True)- else:- raise Exception(f"Serializer validation failed: {serializer.errors}")++ # Validation recovers secrets with the draft first, because an editor saw the+ # draft. A refresh writes the live store, so it must recover the live secrets.+ draft_secrets = hog_flow.draft_encrypted_inputs+ hog_flow.draft_encrypted_inputs = None+ try:+ is_valid = serializer.is_valid()+ finally:+ hog_flow.draft_encrypted_inputs = draft_secrets++ if is_valid:+ _, written_secrets = partition_flow_secrets(+ serializer.validated_data.get("actions") or [], template_cache+ )+ if _secret_values(written_secrets) != _secret_values(live_secrets):+ # A save that changes a secret can delete a credential that nobody can+ # enter again. Skip the workflow and name it.+ self.stdout.write(+ self.style.WARNING(+ f"Secrets would change: team {hog_flow.team_id}, workflow {hog_flow.id} ({hog_flow.name!r})"+ )+ )+ raise Exception("Refresh would change the stored secrets")+ if not dry_run:+ serializer.save()+ total_updated += 1+ logger.info(+ "Would refresh HogFlow" if dry_run else "Successfully refreshed HogFlow",+ hog_flow_id=str(hog_flow.id),+ team_id=hog_flow.team_id,+ status=hog_flow.status,+ name=hog_flow.name,+ version=hog_flow.version,+ dry_run=dry_run,+ )+ else:+ # A workflow that no longer validates cannot be re-saved, so it keeps whatever+ # it was last compiled against. Name it: the owner has to fix it or turn it off.+ self.stdout.write(+ self.style.WARNING(+ f"Does not validate: team {hog_flow.team_id}, workflow {hog_flow.id} ({hog_flow.name!r})"+ )+ )+ raise Exception(f"Serializer validation failed: {serializer.errors}")except Exception as e:error_count += 1logger.error("Error refreshing HogFlow",- hog_flow_id=str(hog_flow.id),- team_id=hog_flow.team_id,- status=hog_flow.status,- name=hog_flow.name,+ hog_flow_id=str(flow_id),+ team_id=hog_flow.team_id if hog_flow else None,+ status=hog_flow.status if hog_flow else None,+ name=hog_flow.name if hog_flow else None,error=str(e),exc_info=True,)- self.stdout.write(self.style.ERROR(f"Error processing flow {hog_flow.id}: {str(e)}"))+ self.stdout.write(self.style.ERROR(f"Error processing flow {flow_id}: {str(e)}"))# Output summaryduration = time.time() - start_timeself.stdout.write(self.style.SUCCESS(- f"\nRefresh completed in {duration:.2f}s.\n"+ f"\n{'Dry run' if dry_run else 'Refresh'} completed in {duration:.2f}s.\n"f"Processed: {total_processed}\n"- f"Updated: {total_updated}\n"+ f"{'Would update' if dry_run else 'Updated'}: {total_updated}\n"f"Errors: {error_count}"))diff --git a/posthog/management/commands/test/test_refresh_hog_flows.py b/posthog/management/commands/test/test_refresh_hog_flows.pyindex e8a7f9d9faf3..dfba81496511 100644--- a/posthog/management/commands/test/test_refresh_hog_flows.py+++ b/posthog/management/commands/test/test_refresh_hog_flows.py@@ -1,13 +1,19 @@+from copy import deepcopyfrom io import StringIO+from typing import Anyfrom posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.core.management import call_command-from posthog.management.commands.refresh_hog_flows import remove_event_filters_from_conditionals+from parameterized import parameterized++from posthog.cdp.filters import RUNTIME_CONTRACT+from posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.models import Team+from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow@@ -219,9 +225,22 @@ class TestRefreshHogFlows(BaseTest):self.assertIn("Check logs for details on 1 errors encountered", output)@patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")- def test_bytecode_regeneration_on_conditional_branch(self, mock_reload):- """Test that bytecode is regenerated when a conditional branch action is missing bytecode."""+ def test_keeps_an_edit_made_to_a_workflow_while_the_run_is_in_progress(self, mock_reload):+ first_saved: list[str] = []++ def turn_off_the_rest_once(team_id: int, hog_flow_ids: list[str]) -> None:+ if not first_saved:+ first_saved.extend(hog_flow_ids)+ HogFlow.objects.exclude(id__in=hog_flow_ids).update(status=HogFlow.State.DRAFT)++ mock_reload.side_effect = turn_off_the_rest_once+ call_command("refresh_hog_flows", stdout=StringIO())+ statuses = set(HogFlow.objects.exclude(id__in=first_saved).values_list("status", flat=True))+ assert statuses == {HogFlow.State.DRAFT}++ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")+ def test_refuses_a_conditional_branch_carrying_event_filters(self, mock_reload):# Create a HogFlow with conditional branch that has filters but no bytecodeactions = [{@@ -297,103 +316,122 @@ class TestRefreshHogFlows(BaseTest):# Refresh the flow from databasetest_flow.refresh_from_db()- # Check that bytecode was generated for the conditional branch- updated_actions = test_flow.actions- updated_conditional_branch = next(a for a in updated_actions if a["type"] == "conditional_branch")-- # After save, the bytecode should be generated- self.assertIn("bytecode", updated_conditional_branch["config"]["conditions"][0]["filters"])- bytecode = updated_conditional_branch["config"]["conditions"][0]["filters"]["bytecode"]- self.assertIsInstance(bytecode, list)- self.assertGreater(len(bytecode), 0)+ # The validator refuses event filters in a conditional, so the flow cannot be re-saved.+ branch = next(a for a in test_flow.actions if a["type"] == "conditional_branch")+ assert branch["config"]["conditions"][0]["filters"]["events"] == [+ {"id": "$pageview", "name": "$pageview", "type": "events"}+ ]- # Verify the command outputoutput = out.getvalue()self.assertIn("Found 1 HogFlows to process", output)- self.assertIn("Updated: 1", output)- self.assertIn("Errors: 0", output)-- def test_remove_event_filters_from_single_condition(self):- actions = [- {- "id": "action_conditional_branch_test",- "name": "Conditional branch",- "type": "conditional_branch",- "config": {- "conditions": [- {- "filters": {- "events": [{"id": "$pageview", "name": "$pageview", "type": "events"}],- "source": "events",- "properties": [- {"key": "$browser", "type": "event", "value": "is_set", "operator": "is_set"}- ],- }- }- ]- },- }+ self.assertIn(f"workflow {test_flow.id}", output)+ self.assertIn("Updated: 0", output)+ self.assertIn("Errors: 1", output)++ def _unstamped(self, trigger_filters: dict[str, Any], conditions: list[dict[str, Any]] | None = None) -> HogFlow:+ trigger_config = {"type": "event", "filters": trigger_filters}+ actions: list[dict[str, Any]] = [+ {"id": "trigger_node", "name": "trigger", "type": "trigger", "config": trigger_config},+ {"id": "exit_node", "name": "exit", "type": "exit", "config": {}},]- updated = remove_event_filters_from_conditionals(actions)- filters = updated[0]["config"]["conditions"][0]["filters"]- self.assertNotIn("events", filters)- self.assertEqual(filters["source"], "events")- self.assertEqual(- filters["properties"], [{"key": "$browser", "type": "event", "value": "is_set", "operator": "is_set"}]- )-- def test_remove_event_filters_does_not_fail_if_no_events(self):- actions = [- {- "id": "action_conditional_branch_test",- "name": "Conditional branch",- "type": "conditional_branch",- "config": {- "conditions": [- {- "filters": {- "source": "events",- "properties": [- {"key": "$browser", "type": "event", "value": "is_set", "operator": "is_set"}- ],- }- }- ]+ if conditions is not None:+ actions.insert(+ 1,+ {+ "id": "branch",+ "name": "branch",+ "type": "conditional_branch",+ "config": {"conditions": conditions},},- }- ]- updated = remove_event_filters_from_conditionals(actions)- filters = updated[0]["config"]["conditions"][0]["filters"]- self.assertNotIn("events", filters)- self.assertEqual(filters["source"], "events")- self.assertEqual(- filters["properties"], [{"key": "$browser", "type": "event", "value": "is_set", "operator": "is_set"}]+ )+ flow = HogFlow.objects.create(+ team=self.team,+ name="Saved before stamping",+ status="active",+ trigger=trigger_config,+ actions=actions,+ edges=[],+ exit_condition="exit_only_at_end",)+ return HogFlow.objects.get(pk=flow.pk)- def test_remove_event_filters_multiple_conditions_and_actions(self):- actions = [- {- "id": "action_conditional_branch_test",- "name": "Conditional branch",- "type": "conditional_branch",- "config": {- "conditions": [- {"filters": {"events": [{"id": "a"}], "source": "events"}},- {"filters": {"source": "events"}},- ]- },- },+ @parameterized.expand([("dry_run", True), ("real_run", False)])+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")+ def test_stamps_the_trigger_filters_of_a_workflow(self, _name, dry_run, mock_reload):+ flow = self._unstamped({"events": [{"id": "$pageview", "type": "events"}]})+ assert "bytecode_contract" not in (flow.trigger or {})["filters"]++ out = StringIO()+ call_command("refresh_hog_flows", hog_flow_id=str(flow.id), dry_run=dry_run, stdout=out)++ flow.refresh_from_db()+ stamped = (flow.trigger or {}).get("filters", {}).get("bytecode_contract")+ assert stamped == (None if dry_run else RUNTIME_CONTRACT)+ assert ("Dry run" in out.getvalue()) is dry_run+ assert ("Would update: 1" if dry_run else "Updated: 1") in out.getvalue()++ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")+ def test_names_a_workflow_that_no_longer_validates(self, mock_reload):+ # A count alone cannot be acted on: the run has to say which workflow to look at.+ flow = self._unstamped({"properties": [{"type": "hogql", "key": "nosuch.thing"}]})++ out = StringIO()+ call_command("refresh_hog_flows", hog_flow_id=str(flow.id), stdout=out)++ flow.refresh_from_db()+ assert "bytecode_contract" not in (flow.trigger or {})["filters"]+ assert f"workflow {flow.id}" in out.getvalue()+ assert "Errors: 1" in out.getvalue()++ @parameterized.expand(+ [+ # The draft secret must not reach the live store before a publish.+ ("active_flow_with_a_draft_secret", HogFlow.State.ACTIVE, "https://example.com", True),+ # Lenient validation keeps the invalid input, and nothing restores the stripped secret.+ ("draft_flow_with_an_invalid_input", HogFlow.State.DRAFT, "", False),+ ]+ )+ @patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")+ def test_leaves_the_stored_secrets_unchanged(self, _name, status, url, has_draft, mock_reload):+ template = deepcopy(MOCK_NODE_TEMPLATES[0])+ template["id"] = "template-secret-webhook"+ template["inputs_schema"] = [+ {"key": "url", "type": "string", "label": "URL", "secret": False, "required": True},+ {"key": "api_key", "type": "string", "label": "API key", "secret": True, "required": False},+ ]+ sync_template_to_db(template)+ trigger_config = {"type": "event", "filters": {"events": [{"id": "$pageview", "type": "events"}]}}+ actions: list[dict[str, Any]] = [+ {"id": "trigger_node", "name": "trigger", "type": "trigger", "config": trigger_config},{- "id": "other_action",- "name": "Other",- "type": "exit",- "config": {},+ "id": "action_1",+ "name": "webhook",+ "type": "function",+ "config": {"template_id": "template-secret-webhook", "inputs": {"url": {"value": url}}},},]- updated = remove_event_filters_from_conditionals(actions)- cond1 = updated[0]["config"]["conditions"][0]["filters"]- cond2 = updated[0]["config"]["conditions"][1]["filters"]- self.assertNotIn("events", cond1)- self.assertNotIn("events", cond2)- self.assertEqual(cond1, {"source": "events"})- self.assertEqual(cond2, {"source": "events"})+ live_secrets = {"action_1": {"api_key": {"value": "fake-live-key"}}}+ draft_secrets = {"action_1": {"api_key": {"value": "fake-draft-key"}}} if has_draft else None+ flow = HogFlow.objects.create(+ team=self.team,+ name="Secret flow",+ status=status,+ trigger=trigger_config,+ edges=[{"from": "trigger_node", "to": "action_1", "type": "continue"}],+ actions=actions,+ encrypted_inputs=live_secrets,+ draft={"actions": actions} if has_draft else None,+ draft_encrypted_inputs=draft_secrets,+ )++ out = StringIO()+ call_command("refresh_hog_flows", hog_flow_id=str(flow.id), stdout=out)++ assert "Updated: 1" in out.getvalue()+ flow.refresh_from_db()+ live_values = {+ action_id: {key: value.get("value") for key, value in inputs.items()}+ for action_id, inputs in (flow.encrypted_inputs or {}).items()+ }+ assert live_values == {"action_1": {"api_key": "fake-live-key"}}+ assert flow.draft_encrypted_inputs == draft_secrets