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): coerce types in constant-list membership filters (#65441)

Daniel Marchuk592228cf6f70
diff --git a/posthog/cdp/filters.py b/posthog/cdp/filters.py
index 47e494a72b7f..2924150b8674 100644
--- a/posthog/cdp/filters.py
+++ b/posthog/cdp/filters.py
@@ -6,7 +6,7 @@ from posthog.hogql.compiler.bytecode import create_bytecode
from posthog.hogql.context import HogQLContext
from posthog.hogql.parser import parse_expr
from posthog.hogql.property import action_to_expr, ast, property_to_expr
-from posthog.hogql.visitor import TraversingVisitor
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
from posthog.models.team.team import Team
@@ -274,6 +274,34 @@ def _internal_user_settings_url(team_id: int) -> str:
return f"{site_url}/project/{team_id}/settings/project#internal-user-filtering"
+class _LowerConstantMembership(CloningVisitor):
+ """Rewrite `x IN (c1, c2, ...)` / `x NOT IN (...)` over constant literals into a coercing
+ OR-of-EQ / AND-of-NotEq chain. The Hog VM evaluates the IN/NOT_IN opcode with strict equality
+ (no type coercion), unlike EQ/NotEq which unify operand types first. So a numeric property — e.g.
+ a survey rating sent as a number — never matches a list of string literals like ("1".."6"), and
+ the condition silently falls through. Scoped to real-time filter bytecode: the shared Hog
+ compiler, the ClickHouse query path, and the JS-transpiled filter path are all untouched."""
+
+ def visit_compare_operation(self, node: ast.CompareOperation) -> ast.Expr:
+ if node.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn) and isinstance(
+ node.right, ast.Tuple | ast.Array
+ ):
+ elements = node.right.exprs
+ if elements and all(isinstance(element, ast.Constant) for element in elements):
+ eq_op = (
+ ast.CompareOperationOp.Eq if node.op == ast.CompareOperationOp.In else ast.CompareOperationOp.NotEq
+ )
+ comparisons: list[ast.Expr] = [
+ ast.CompareOperation(op=eq_op, left=self.visit(node.left), right=self.visit(element))
+ for element in elements
+ ]
+ if len(comparisons) == 1:
+ return comparisons[0]
+ # IN → "matches any" (OR); NOT IN → "matches none" (AND).
+ return ast.Or(exprs=comparisons) if node.op == ast.CompareOperationOp.In else ast.And(exprs=comparisons)
+ return super().visit_compare_operation(node)
+
+
def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optional[dict[int, Action]] = None) -> dict:
filters = filters or {}
try:
@@ -281,6 +309,7 @@ def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optio
if SelectFinder.has_select(expr):
raise Exception("Select queries are not allowed in filters")
+ expr = _LowerConstantMembership().visit(expr)
context = HogQLContext(team_id=team.id)
filters["bytecode"] = create_bytecode(expr, context=context).bytecode
diff --git a/posthog/cdp/test/test_filters.py b/posthog/cdp/test/test_filters.py
index 135130f39d4e..540bef1c2294 100644
--- a/posthog/cdp/test/test_filters.py
+++ b/posthog/cdp/test/test_filters.py
@@ -208,6 +208,24 @@ class TestHogFunctionFilters(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
2,
]
+ def test_multi_value_exact_filter_matches_numeric_property(self):
+ # Survey ratings and other numeric event properties arrive as numbers, while a multi-value
+ # "exact" filter stores its values as strings. Membership must still match (it compiles to a
+ # type-coercing equality chain, not a strict IN).
+ filters = {
+ "properties": [
+ {
+ "key": "$survey_response_1",
+ "value": ["1", "2", "3", "4", "5", "6"],
+ "operator": "exact",
+ "type": "event",
+ }
+ ]
+ }
+ bytecode = compile_filters_bytecode(filters, self.team)["bytecode"]
+ assert execute_bytecode(bytecode, {"properties": {"$survey_response_1": 6}}).result is True
+ assert execute_bytecode(bytecode, {"properties": {"$survey_response_1": 7}}).result is False
+
def test_filters_full(self):
bytecode = self.filters_to_bytecode(filters=self.filters)
assert bytecode == [
diff --git a/products/workflows/backend/management/commands/recompile_membership_filter_bytecode.py b/products/workflows/backend/management/commands/recompile_membership_filter_bytecode.py
new file mode 100644
index 000000000000..e920e1c95667
--- /dev/null
+++ b/products/workflows/backend/management/commands/recompile_membership_filter_bytecode.py
@@ -0,0 +1,138 @@
+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 changed
diff --git a/products/workflows/backend/test/test_recompile_membership_filter_bytecode.py b/products/workflows/backend/test/test_recompile_membership_filter_bytecode.py
new file mode 100644
index 000000000000..6acb769210e0
--- /dev/null
+++ b/products/workflows/backend/test/test_recompile_membership_filter_bytecode.py
@@ -0,0 +1,134 @@
+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