: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): remove membership filter backfill command (#66952)
Daniel Marchukd4fdb97d0585
diff --git a/products/workflows/backend/management/commands/recompile_membership_filter_bytecode.py b/products/workflows/backend/management/commands/recompile_membership_filter_bytecode.pydeleted file mode 100644index e920e1c95667..000000000000--- a/products/workflows/backend/management/commands/recompile_membership_filter_bytecode.py+++ /dev/null@@ -1,138 +0,0 @@-import copy-from collections.abc import Iterator-from typing import Any--from django.core.management.base import BaseCommand--from posthog.cdp.filters import compile_filters_bytecode--from products.cdp.backend.models.hog_functions.hog_function import HogFunction-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow---class Command(BaseCommand):- help = (- "Recompile filter bytecode for workflows and hog functions so constant-list membership "- "(operator 'exact'/'in' with two or more values) inherits type coercion. Such filters used to "- "compile to the strict IN opcode, which never matched a numeric property (e.g. a survey rating "- "sent as a number) against a list of string literals. The compiler now lowers them to a "- "type-coercing equality chain; this recompiles already-stored rows so the fix takes effect "- "without an edit-and-save. Idempotent — only rows whose bytecode actually changes are written. "- "internal_destination hog functions are system-managed and skipped unless --include-internal. "- "Default dry-run; pass --live-run to apply."- )-- 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)")- parser.add_argument(- "--include-internal",- action="store_true",- help="Also recompile internal_destination hog functions (system-managed; skipped by default)",- )-- def handle(self, *args, **options):- live_run = options.get("live_run", False)- team_id = options.get("team_id")- include_internal = options.get("include_internal", False)- mode = "LIVE RUN" if live_run else "DRY RUN"- self.stdout.write(f"Starting recompile_membership_filter_bytecode ({mode})")- if team_id:- self.stdout.write(f"Filtering to team_id={team_id}")-- flows_changed = self._handle_hog_flows(team_id, live_run)- functions_changed = self._handle_hog_functions(team_id, live_run, include_internal)-- verb = "recompiled" if live_run else "to recompile"- self.stdout.write(- self.style.SUCCESS(- f"Completed ({mode}): {flows_changed} workflow(s) and {functions_changed} hog function(s) {verb}"- )- )- if not live_run and (flows_changed or functions_changed):- self.stdout.write(self.style.NOTICE("Run with --live-run to apply changes"))-- def _recompile_filters(self, filters: Any, team) -> bool:- """Recompile filters['bytecode'] in place. Returns True if the bytecode changed.-- Compilation already succeeded when the row was saved, so a failure here is unexpected; skip the- filter rather than abort the whole backfill."""- if not isinstance(filters, dict):- return False- before = filters.get("bytecode")- try:- compile_filters_bytecode(filters, team) # mutates filters in place- except Exception as e:- self.stderr.write(f" skipped a filter for team {team.id}: {e}")- return False- return filters.get("bytecode") != before-- def _iter_action_filter_dicts(self, actions: Any) -> Iterator[dict]:- """Yield every filters dict embedded in a hog flow's actions JSON (trigger, conditional_branch- conditions, and wait_until_condition)."""- if not isinstance(actions, list):- return- for action in actions:- if not isinstance(action, dict):- continue- config = action.get("config") or {}- if not isinstance(config, dict):- continue- if isinstance(config.get("filters"), dict):- yield config["filters"]- for condition in config.get("conditions") or []:- if isinstance(condition, dict) and isinstance(condition.get("filters"), dict):- yield condition["filters"]- single_condition = config.get("condition")- if isinstance(single_condition, dict) and isinstance(single_condition.get("filters"), dict):- yield single_condition["filters"]-- def _handle_hog_flows(self, team_id, live_run) -> int:- flows = HogFlow.objects.select_related("team")- if team_id:- flows = flows.filter(team_id=team_id)-- changed = 0- for flow in flows.iterator():- actions = copy.deepcopy(flow.actions)- # Recompile every embedded filter — don't short-circuit, or a workflow with multiple- # filters (e.g. a trigger filter and a branch condition) would leave the later ones on- # the old bytecode.- row_changed = False- for filters in self._iter_action_filter_dicts(actions):- if self._recompile_filters(filters, flow.team):- row_changed = True- if not row_changed:- continue- changed += 1- self.stdout.write(- f" {'Recompiling' if live_run else 'Would recompile'} workflow 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(actions=actions)- return changed-- def _handle_hog_functions(self, team_id, live_run, include_internal) -> int:- functions = HogFunction.objects.select_related("team").filter(deleted=False)- if team_id:- functions = functions.filter(team_id=team_id)- if not include_internal:- functions = functions.exclude(type="internal_destination")-- changed = 0- for function in functions.iterator():- if not isinstance(function.filters, dict):- continue- filters = copy.deepcopy(function.filters)- if not self._recompile_filters(filters, function.team):- continue- changed += 1- self.stdout.write(- f" {'Recompiling' if live_run else 'Would recompile'} hog function id={function.id} "- f"team_id={function.team_id} type={function.type}"- )- if live_run:- HogFunction.objects.filter(pk=function.pk).update(filters=filters)- return changeddiff --git a/products/workflows/backend/test/test_recompile_membership_filter_bytecode.py b/products/workflows/backend/test/test_recompile_membership_filter_bytecode.pydeleted file mode 100644index 6acb769210e0..000000000000--- a/products/workflows/backend/test/test_recompile_membership_filter_bytecode.py+++ /dev/null@@ -1,134 +0,0 @@-import json-from copy import deepcopy--from unittest.mock import patch--from django.core.management import call_command-from django.test import TestCase--from posthog.hogql.compiler.bytecode import create_bytecode--from posthog.cdp.filters import compile_filters_expr-from posthog.models.user import User--from products.cdp.backend.models.hog_functions.hog_function import HogFunction-from products.workflows.backend.models.hog_flow.hog_flow import HogFlow--from common.hogvm.python.execute import execute_bytecode-from common.hogvm.python.operation import Operation--# A numeric event property filtered with a multi-value "exact" — the shape that used to compile to a-# strict IN and never match a numeric value (e.g. a survey rating sent as a number).-FILTERS_DEF = {- "properties": [- {- "key": "$survey_response_x",- "value": ["1", "2", "3", "4", "5", "6"],- "operator": "exact",- "type": "event",- }- ]-}---@patch("products.workflows.backend.models.hog_flow.hog_flow.reload_hog_flows_on_workers")-class TestRecompileMembershipFilterBytecode(TestCase):- def setUp(self):- super().setUp()- _org, team, _user = User.objects.bootstrap("Test org", "[email protected]", None)- self.team = team- # The genuine pre-fix bytecode: compile the expr directly, bypassing compile_filters_bytecode's- # rewrite, so we get the strict IN opcode a row would have been stored with before this change.- # json round-trip normalizes Operation enum members to the ints a JSONField round-trip yields.- self.stale_bytecode = json.loads(- json.dumps(create_bytecode(compile_filters_expr(FILTERS_DEF, self.team)).bytecode)- )-- def _stale_filters(self):- return {**deepcopy(FILTERS_DEF), "bytecode": deepcopy(self.stale_bytecode)}-- def _seed_function(self, type="destination"):- fn = HogFunction.objects.create(team=self.team, name="fn", type=type, hog="return event")- # .update() bypasses HogFunction.save(), which would recompile (and fix) the filters.- HogFunction.objects.filter(pk=fn.pk).update(filters=self._stale_filters())- fn.refresh_from_db()- return fn-- def _seed_flow(self):- flow = HogFlow.objects.create(name="flow", team=self.team)- actions = [- {"id": "trigger_node", "type": "trigger", "config": {}},- {- "id": "branch",- "type": "conditional_branch",- "config": {"conditions": [{"filters": self._stale_filters()}]},- },- ]- HogFlow.objects.filter(pk=flow.pk).update(actions=actions)- flow.refresh_from_db()- return flow-- @staticmethod- def _flow_condition_bytecode(flow):- return flow.actions[1]["config"]["conditions"][0]["filters"]["bytecode"]-- def test_seeded_bytecode_reproduces_the_bug(self, _mock_reload):- # Sanity check: the strict-IN bytecode genuinely fails to match a numeric value.- assert Operation.IN in self.stale_bytecode- assert execute_bytecode(self.stale_bytecode, {"properties": {"$survey_response_x": 6}}).result is False-- def test_dry_run_changes_nothing(self, _mock_reload):- fn = self._seed_function()- flow = self._seed_flow()-- call_command("recompile_membership_filter_bytecode")-- fn.refresh_from_db()- flow.refresh_from_db()- assert fn.filters["bytecode"] == self.stale_bytecode- assert self._flow_condition_bytecode(flow) == self.stale_bytecode-- def test_live_run_recompiles_function_and_workflow(self, _mock_reload):- fn = self._seed_function()- flow = self._seed_flow()-- call_command("recompile_membership_filter_bytecode", "--live-run")-- fn.refresh_from_db()- flow.refresh_from_db()- for bytecode in (fn.filters["bytecode"], self._flow_condition_bytecode(flow)):- # The strict IN is gone, replaced by a coercing equality chain that matches the number.- assert Operation.IN not in bytecode- assert execute_bytecode(bytecode, {"properties": {"$survey_response_x": 6}}).result is True- assert execute_bytecode(bytecode, {"properties": {"$survey_response_x": 7}}).result is False-- def test_live_run_is_idempotent(self, _mock_reload):- fn = self._seed_function()-- call_command("recompile_membership_filter_bytecode", "--live-run")- fn.refresh_from_db()- recompiled = fn.filters["bytecode"]-- # A second live run recompiles to the same bytecode, so nothing is rewritten again.- call_command("recompile_membership_filter_bytecode", "--live-run")- fn.refresh_from_db()- assert fn.filters["bytecode"] == recompiled-- def test_internal_destinations_skipped_unless_opted_in(self, _mock_reload):- fn = self._seed_function(type="internal_destination")-- call_command("recompile_membership_filter_bytecode", "--live-run")- fn.refresh_from_db()- assert fn.filters["bytecode"] == self.stale_bytecode # untouched by default-- call_command("recompile_membership_filter_bytecode", "--live-run", "--include-internal")- fn.refresh_from_db()- assert Operation.IN not in fn.filters["bytecode"]-- def test_team_id_scopes_the_backfill(self, _mock_reload):- fn = self._seed_function()- _other_org, other_team, _other_user = User.objects.bootstrap("Other org", "[email protected]", None)-- call_command("recompile_membership_filter_bytecode", "--live-run", f"--team-id={other_team.id}")- fn.refresh_from_db()- assert fn.filters["bytecode"] == self.stale_bytecode # different team, untouched