: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): match warehouse row filters against the synced row (#105687)
Meikel Ratz7fe0116042cf
diff --git a/posthog/cdp/filters.py b/posthog/cdp/filters.pyindex b05818fabdf3..f20321246958 100644--- a/posthog/cdp/filters.py+++ b/posthog/cdp/filters.py@@ -10,6 +10,7 @@ from posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, ast, property_to_exprfrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor+from posthog.dataclasses import frozenfrom posthog.models.team.team import Teamfrom products.actions.backend.models.action import Action@@ -23,6 +24,14 @@ COHORT_FILTER_TYPES = frozenset({"cohort", "static-cohort", "precalculated-cohor# keys resolved into nested field chains so the HogVM matches against the nested object.INTERNAL_NESTED_PROPERTY_EVENTS = frozenset({"$activity_log_entry_created"})+# Filter sources whose rows come from the warehouse rather than from events: one invocation per+# row, with the row under `event.properties` and no person attached.+DATA_WAREHOUSE_SOURCES = ("data-warehouse-table", "data-warehouse-view")++# The warehouse consumer writes the row's table name under this key. Keep it equal to+# DWH_SOURCE_TABLE_PROPERTY in nodejs/src/cdp/schema/hogflow.ts.+WAREHOUSE_SOURCE_TABLE_PROPERTY = "$source_table"+class _NestedPropertyKeyResolver(CloningVisitor):"""Resolve dotted event-property keys into nested field chains.@@ -182,11 +191,76 @@ def _build_test_account_filters(filters: dict, team: Team) -> list[ast.Expr]:return result+class _WarehouseRowFields(CloningVisitor):+ """+ A warehouse row reaches the filter with its columns under `properties`. A hand-written filter+ names a column bare, the way the column hint lists it, or as `record.<column>` the way an input+ template does. Both resolve there. Only the given roots move, and a lambda parameter or a `let`+ inside a lambda body shadows them there. A global the runtime does provide, such as `timestamp` or `event`, is+ never moved, so a column with such a name has to be read as `record.<column>`.+ """++ def __init__(self, roots: set[str]):+ super().__init__()+ self.roots = roots+ self.locals: list[set[str]] = []++ def visit_lambda(self, node: ast.Lambda) -> ast.Lambda:+ self.locals.append(set(node.args))+ try:+ return super().visit_lambda(node)+ finally:+ self.locals.pop()++ def visit_block(self, node: ast.Block) -> ast.Block:+ # A `let` shadows a column from its own declaration on, as in the compiler, so a read before+ # it still means the column. A lambda initializer may call its own name, so that name is+ # bound before the lambda body is visited, again as in the compiler.+ self.locals.append(set())+ try:+ declarations = []+ for declaration in node.declarations:+ if isinstance(declaration, ast.VariableDeclaration) and isinstance(declaration.expr, ast.Lambda):+ self.locals[-1].add(declaration.name)+ declarations.append(self.visit(declaration))+ if isinstance(declaration, ast.VariableDeclaration):+ self.locals[-1].add(declaration.name)+ return ast.Block(start=node.start, end=node.end, declarations=declarations)+ finally:+ self.locals.pop()++ def visit_field(self, node: ast.Field) -> ast.Field:+ chain = list(node.chain)+ root = str(chain[0]) if chain else ""+ if any(root in scope for scope in self.locals):+ return super().visit_field(node)+ if root == "record":+ return ast.Field(chain=["properties", *chain[1:]])+ if root in self.roots:+ return ast.Field(chain=["properties", *chain])+ return super().visit_field(node)+++def _as_row_properties(properties: list[Any]) -> list[Any]:+ """Read a `data_warehouse` column filter from `properties`, where the consumer puts the row.++ Such a filter otherwise compiles to a bare field such as `organization`, which the filter+ globals never carry, so the row fails the filter.+ """+ return [+ {**prop, "type": "event"} if isinstance(prop, dict) and prop.get("type") == "data_warehouse" else prop+ for prop in properties+ ]++def _build_global_property_filters(filters: dict, team: Team) -> list[ast.Expr]:"""Build global property filters that apply to all events."""if not filters.get("properties"):return []- return [property_to_expr(prop, team) for prop in filters["properties"]]+ properties = filters["properties"]+ if filters.get("source") in DATA_WAREHOUSE_SOURCES:+ properties = _as_row_properties(properties)+ return [property_to_expr(prop, team) for prop in properties]def _build_event_filter_expr(filter: dict) -> ast.Expr:@@ -250,6 +324,29 @@ def _combine_expressions(expressions: list[ast.Expr]) -> ast.Expr:return ast.And(exprs=expressions)+def _build_warehouse_table_filters(filters: dict, team: Team) -> list[ast.Expr]:+ if filters.get("source") not in DATA_WAREHOUSE_SOURCES:+ return []+ entries = [entry for entry in filters.get("data_warehouse") or [] if isinstance(entry, dict)]+ if not any(entry.get("properties") for entry in entries):+ return []++ # Row filters apply only to rows from their own entry's table. Every entry checks its table name,+ # because an entry without row filters would otherwise match rows from the filtered tables too.+ entry_exprs: list[ast.Expr] = []+ for entry in entries:+ exprs: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["properties", WAREHOUSE_SOURCE_TABLE_PROPERTY]),+ right=ast.Constant(value=entry.get("table_name")),+ )+ ]+ exprs.extend(property_to_expr(prop, team) for prop in _as_row_properties(entry.get("properties") or []))+ entry_exprs.append(_combine_expressions(exprs))+ return [ast.Or(exprs=entry_exprs) if len(entry_exprs) > 1 else entry_exprs[0]]++def hog_function_filters_to_expr(filters: dict, team: Team, actions: dict[int, Action]) -> ast.Expr:"""Build a HogQL expression from hog function filters.@@ -260,13 +357,14 @@ def hog_function_filters_to_expr(filters: dict, team: Team, actions: dict[int, A# Build component filterstest_account_filters = _build_test_account_filters(filters, team)global_property_filters = _build_global_property_filters(filters, team)+ warehouse_table_filters = _build_warehouse_table_filters(filters, team)# Get all event and action filtersall_filters = filters.get("events", []) + filters.get("actions", [])- # If no event/action filters, return just the account and property filters+ # If no event/action filters, return just the account, property and warehouse table filtersif not all_filters:- return _combine_expressions(test_account_filters + global_property_filters)+ return _combine_expressions(test_account_filters + global_property_filters + warehouse_table_filters)# Build expressions for each event/action filter (dotted keys on internal events are resolved# per-branch inside _build_single_filter_expr).@@ -388,6 +486,46 @@ def _unknown_filter_globals(expr: ast.Expr) -> list[str]:)+@frozen+class _RuntimeCompilation:+ bytecode: list[Any]+ # Every root the program reads that the runtime does not provide.+ unknown_roots: list[str]+ context: HogQLContext+++def _compile_against_runtime(expr: ast.Expr, team: Team) -> _RuntimeCompilation:+ # Declaring the globals turns the compiler's field resolution into a check: it warns on a+ # root that is neither a local, an upvalue, nor one of ours.+ context = HogQLContext(team_id=team.id, globals=dict.fromkeys(FILTER_GLOBALS), allowed_functions=FILTER_FUNCTIONS)+ bytecode = create_bytecode(expr, context=context).bytecode+ unknown = sorted(+ {w.message.removeprefix(_UNKNOWN_GLOBAL) for w in context.warnings if w.message.startswith(_UNKNOWN_GLOBAL)}+ )+ return _RuntimeCompilation(bytecode=bytecode, unknown_roots=unknown, context=context)+++def _own_filters_expr(filters: dict, team: Team, actions: Optional[dict[int, Action]]) -> ast.Expr:+ """The destination's filters without the team's test account filters, with warehouse columns resolved."""+ own = _LowerConstantMembership().visit(+ compile_filters_expr({**filters, "filter_test_accounts": False}, team, actions)+ )+ if filters.get("source") in DATA_WAREHOUSE_SOURCES:+ own = _WarehouseRowFields(roots=set(_compile_against_runtime(own, team).unknown_roots)).visit(own)+ return own+++def _resolve_warehouse_columns(filters: dict, team: Team, actions: Optional[dict[int, Action]]) -> ast.Expr:+ """+ Only the destination's own filters read the row. The team's test account filters are written+ against events, so a root they read that the runtime lacks stays an error rather than becoming+ a column.+ """+ return _combine_expressions(+ [*_build_test_account_filters(filters, team), _own_filters_expr(filters, team, actions)]+ )++def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optional[dict[int, Action]] = None) -> dict:filters = filters or {}try:@@ -396,16 +534,12 @@ def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optioraise Exception("Select queries are not allowed in filters")expr = _LowerConstantMembership().visit(expr)- # Declaring the globals turns the compiler's field resolution into a check: it warns on a- # root that is neither a local, an upvalue, nor one of ours.- context = HogQLContext(- team_id=team.id, globals=dict.fromkeys(FILTER_GLOBALS), allowed_functions=FILTER_FUNCTIONS- )- filters["bytecode"] = create_bytecode(expr, context=context).bytecode-- unknown = sorted(- {w.message.removeprefix(_UNKNOWN_GLOBAL) for w in context.warnings if w.message.startswith(_UNKNOWN_GLOBAL)}- )+ compiled = _compile_against_runtime(expr, team)+ if compiled.unknown_roots and filters.get("source") in DATA_WAREHOUSE_SOURCES:+ compiled = _compile_against_runtime(_resolve_warehouse_columns(filters, team, actions), team)+ filters["bytecode"] = compiled.bytecode+ unknown = compiled.unknown_roots+ context = compiled.contextif unknown:# The person saving a destination did not write the team's test account filters, so a# message that only names the field sends them looking in the wrong place.@@ -414,9 +548,7 @@ def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optioif from_team:# Compile the destination's own filters alone rather than subtracting the team's# roots: a field that both sources read drops out of the difference and goes unnamed.- own = _unknown_filter_globals(- compile_filters_expr({**filters, "filter_test_accounts": False}, team, actions)- )+ own = _unknown_filter_globals(_own_filters_expr(filters, team, actions))raise Exception(f"Your internal/test user filters read {', '.join(from_team)}, which real-time filters "f"cannot read. Check the spelling, or use a field or function that real-time filters support. "diff --git a/posthog/cdp/test/test_filters.py b/posthog/cdp/test/test_filters.pyindex a9c9c688da44..896ec296fd58 100644--- a/posthog/cdp/test/test_filters.py+++ b/posthog/cdp/test/test_filters.py@@ -105,6 +105,206 @@ class TestHogFunctionFilters(ClickhouseTestMixin, APIBaseTest, QueryMatchingTestassert execute_bytecode(bytecode, {}).result is True+ @parameterized.expand(+ [+ (+ "trigger_filter_matches_row",+ {+ "source": "data-warehouse-view",+ "properties": [+ {"key": "organization", "value": "acme", "operator": "exact", "type": "data_warehouse"}+ ],+ },+ {"organization": "acme", "$source_table": "accounts"},+ True,+ ),+ (+ "trigger_filter_rejects_row",+ {+ "source": "data-warehouse-view",+ "properties": [+ {"key": "organization", "value": "acme", "operator": "exact", "type": "data_warehouse"}+ ],+ },+ {"organization": "globex", "$source_table": "accounts"},+ False,+ ),+ (+ "destination_table_filter_matches_row",+ {+ "source": "data-warehouse-table",+ "data_warehouse": [+ {+ "table_name": "postgres.accounts",+ "properties": [+ {"key": "organization", "value": "acme", "operator": "exact", "type": "data_warehouse"}+ ],+ }+ ],+ },+ {"organization": "acme", "$source_table": "postgres.accounts"},+ True,+ ),+ (+ "destination_unfiltered_table_still_matches",+ {+ "source": "data-warehouse-table",+ "data_warehouse": [+ {+ "table_name": "postgres.accounts",+ "properties": [+ {"key": "organization", "value": "acme", "operator": "exact", "type": "data_warehouse"}+ ],+ },+ {"table_name": "postgres.orders"},+ ],+ },+ {"organization": "globex", "$source_table": "postgres.orders"},+ True,+ ),+ (+ "destination_unfiltered_table_does_not_bypass_filtered_table",+ {+ "source": "data-warehouse-table",+ "data_warehouse": [+ {+ "table_name": "postgres.accounts",+ "properties": [+ {"key": "organization", "value": "acme", "operator": "exact", "type": "data_warehouse"}+ ],+ },+ {"table_name": "postgres.orders"},+ ],+ },+ {"organization": "globex", "$source_table": "postgres.accounts"},+ False,+ ),+ ]+ )+ def test_warehouse_row_filters_match_row_columns(self, _name: str, filters: dict, row: dict, expected: bool):+ bytecode = self.filters_to_bytecode(filters=filters)+ assert execute_bytecode(bytecode, {"properties": row}).result is expected++ @parameterized.expand(+ [+ # The column hint lists bare names, so that is what people type into the SQL leaf.+ ("bare_column", {"type": "hogql", "key": "organization = 'acme'"}),+ # What an input template reads the row as.+ ("record_alias", {"type": "hogql", "key": "record.organization = 'acme'"}),+ # Already where the row is; must not become properties.properties.+ ("qualified_column", {"type": "hogql", "key": "properties.organization = 'acme'"}),+ # A lambda parameter is a local, not a column.+ ("lambda_local", {"type": "hogql", "key": "arrayExists(x -> x = 'acme', [organization])"}),+ # A lambda parameter named like the column shadows it inside the lambda only.+ (+ "lambda_shadows_column",+ {+ "type": "hogql",+ "key": "arrayExists(organization -> organization = 'acme', ['acme']) and organization = 'acme'",+ },+ ),+ # The same for the record alias.+ (+ "lambda_shadows_record",+ {+ "type": "hogql",+ "key": "arrayExists(record -> record = 'acme', ['acme']) and record.organization = 'acme'",+ },+ ),+ ]+ )+ def test_warehouse_sql_filters_read_columns_from_the_row(self, _name: str, prop: dict):+ for filters in (+ {"source": "data-warehouse-view", "properties": [prop]},+ {"source": "data-warehouse-table", "data_warehouse": [{"table_name": "accounts", "properties": [prop]}]},+ ):+ response = compile_filters_bytecode(filters=filters, team=self.team)+ assert "bytecode_error" not in response, response+ row = {"$source_table": "accounts"}+ assert (+ execute_bytecode(response["bytecode"], {"properties": {**row, "organization": "acme"}}).result is True+ )+ assert (+ execute_bytecode(response["bytecode"], {"properties": {**row, "organization": "globex"}}).result+ is False+ )++ def test_warehouse_sql_filter_keeps_a_block_local_over_the_column(self):+ # The `let` inside the lambda is a local named like the column; only the outer read is the column.+ response = compile_filters_bytecode(+ filters={+ "source": "data-warehouse-view",+ "properties": [+ {+ "type": "hogql",+ "key": "arrayExists(x -> { let organization := 'acme'; return organization = 'acme' }, [1]) and organization = 'globex'",+ }+ ],+ },+ team=self.team,+ )+ assert "bytecode_error" not in response, response+ assert execute_bytecode(response["bytecode"], {"properties": {"organization": "globex"}}).result is True++ def test_warehouse_filters_leave_the_team_test_account_filters_under_the_guard(self):+ # The rewrite is for the row the destination filters on. The team's filters are written+ # against events, so an unknown root there is still the team's mistake to fix.+ self.team.test_account_filters = [{"type": "hogql", "key": "$virt_is_bot = false"}]+ self.team.save()+ response = compile_filters_bytecode(+ filters={+ "source": "data-warehouse-view",+ "filter_test_accounts": True,+ "properties": [{"type": "hogql", "key": "organization = 'acme'"}],+ },+ team=self.team,+ )+ assert response["bytecode"] is None+ assert "internal/test user filters read $virt_is_bot" in response["bytecode_error"]+ assert "organization" not in response["bytecode_error"]++ def test_warehouse_sql_filter_reads_the_column_until_a_let_shadows_it(self):+ # `picked` reads the column, the `let` after it does not reach back.+ response = compile_filters_bytecode(+ filters={+ "source": "data-warehouse-view",+ "properties": [+ {+ "type": "hogql",+ "key": "arrayExists(x -> { let picked := organization; let organization := 'other'; return picked = 'acme' }, [1])",+ }+ ],+ },+ team=self.team,+ )+ assert "bytecode_error" not in response, response+ assert execute_bytecode(response["bytecode"], {"properties": {"organization": "acme"}}).result is True+ assert execute_bytecode(response["bytecode"], {"properties": {"organization": "other"}}).result is False++ def test_warehouse_sql_filter_keeps_a_recursive_lambda_local(self):+ # The lambda calls its own name, which must stay the local and not become the column.+ response = compile_filters_bytecode(+ filters={+ "source": "data-warehouse-view",+ "properties": [+ {+ "type": "hogql",+ "key": "arrayExists(x -> { let organization := (n -> if(n = 'acme', true, organization('acme'))); return organization(x) }, ['zzz'])",+ }+ ],+ },+ team=self.team,+ )+ assert "bytecode_error" not in response, response+ assert execute_bytecode(response["bytecode"], {"properties": {"organization": "other"}}).result is True++ def test_event_filters_still_reject_a_bare_unknown_column(self):+ # Only a warehouse row lives under properties; an event filter naming an unknown root is a typo.+ response = compile_filters_bytecode(+ filters={"properties": [{"type": "hogql", "key": "organization = 'acme'"}]}, team=self.team+ )+ assert "organization" in response["bytecode_error"]+def test_filters_raises_on_select(self):response = compile_filters_bytecode(filters={diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.pyindex a5fd709e1af6..e587ee0d0f0e 100644--- a/posthog/cdp/test/test_validation.py+++ b/posthog/cdp/test/test_validation.py@@ -1010,6 +1010,37 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingTwith self.assertRaises(ValidationError):serializer.is_valid(raise_exception=True)+ def test_warehouse_row_filter_needs_its_table(self):+ # The row filter compiles against the entry's table name, so an entry without one never matches.+ row_filter = [{"key": "organization", "value": "acme", "operator": "exact", "type": "data_warehouse"}]+ serializer = HogFunctionFiltersSerializer(+ data={"source": "data-warehouse-table", "data_warehouse": [{"properties": row_filter}]},+ context=self.filters_context,+ )+ with self.assertRaises(ValidationError) as ctx:+ serializer.is_valid(raise_exception=True)+ assert "Pick a table" in str(ctx.exception)++ # The picker's placeholder entry is dropped on save; a filter on it must not vanish with it.+ serializer = HogFunctionFiltersSerializer(+ data={+ "source": "data-warehouse-table",+ "data_warehouse": [{"name": "Select a table", "table_name": "", "properties": row_filter}],+ },+ context=self.filters_context,+ )+ with self.assertRaises(ValidationError):+ serializer.is_valid(raise_exception=True)++ serializer = HogFunctionFiltersSerializer(+ data={+ "source": "data-warehouse-table",+ "data_warehouse": [{"table_name": "accounts", "properties": row_filter}],+ },+ context=self.filters_context,+ )+ assert serializer.is_valid(), serializer.errors+@parameterized.expand([("valid_dotted", "{person.properties.email}", False),diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex 0e62630e9c9c..bfc509884e43 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -16,7 +16,13 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_program, parse_string_templatefrom posthog.hogql.visitor import TraversingVisitor-from posthog.cdp.filters import TEMPLATE_CALLABLES, TEMPLATE_GLOBALS, compile_filters_bytecode, compile_filters_expr+from posthog.cdp.filters import (+ DATA_WAREHOUSE_SOURCES,+ TEMPLATE_CALLABLES,+ TEMPLATE_GLOBALS,+ compile_filters_bytecode,+ compile_filters_expr,+)from posthog.models.integration import POSTHOG_CONNECT_KIND, Integrationfrom products.cdp.backend.models.hog_functions.hog_function import (@@ -952,11 +958,6 @@ class InputsSerializer(serializers.DictField):# Unlike standard dict validation we are iterating the schema - not the inputs-# Filter sources whose rows come from the warehouse rather than from events: one invocation per-# row, with the row under `event.properties` and no person attached.-DATA_WAREHOUSE_SOURCES = ("data-warehouse-table", "data-warehouse-view")--def _contains_behavioral_property(filters: dict) -> bool:"""Behavioral ("performed event") property filters compile to a ClickHouse subquery over eventshistory, which realtime function filters (bytecode per-event, or JS transpiled into the browser)@@ -1060,6 +1061,13 @@ class HogFunctionFiltersSerializer(serializers.Serializer):data.pop("actions", None)if "data_warehouse" in data and isinstance(data["data_warehouse"], list):+ # A row filter is compiled against its entry's table name, so without one it matches nothing.+ # Checked before the placeholder is dropped, or a filter on the placeholder would vanish silently.+ if any(+ entry.get("properties") and (not entry.get("table_name") or entry.get("name") == "Select a table")+ for entry in data["data_warehouse"]+ ):+ raise serializers.ValidationError({"data_warehouse": "Pick a table for each row filter."})data["data_warehouse"] = [entry for entry in data["data_warehouse"] if entry.get("name") != "Select a table"]diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 34c50418352d..2915076eedc0 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -27,11 +27,11 @@ from posthog.api.log_entries import LogEntryMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.utils import action, log_activity_from_viewset+from posthog.cdp.filters import DATA_WAREHOUSE_SOURCESfrom posthog.cdp.internal_events import is_managed_alert_internal_event, is_reserved_internal_eventfrom posthog.cdp.services.icons import CDPIconsServicefrom posthog.cdp.site_functions import get_transpiled_functionfrom posthog.cdp.validation import (- DATA_WAREHOUSE_SOURCES,HogFunctionFiltersSerializer,InputsSchemaItemSerializer,InputsSerializer,diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 9778434154d4..bf7e5827002a 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -72,10 +72,9 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import log_activity_from_viewsetfrom posthog.auth import InternalAPIAuthentication-from posthog.cdp.filters import compile_filters_expr+from posthog.cdp.filters import DATA_WAREHOUSE_SOURCES, compile_filters_exprfrom posthog.cdp.flag_gated_templates import FLAG_GATED_TEMPLATE_IDS, gated_template_enabledfrom posthog.cdp.validation import (- DATA_WAREHOUSE_SOURCES,HogFunctionFiltersSerializer,InputsSchemaItemSerializer,InputsSerializer,