: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(insights): handle non-boolean filter values on boolean properties (#58703)
Sam Pennington526fcd0b13fd
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex c6cfa1f18056..6d412cfcc706 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -1,5 +1,6 @@import refrom collections.abc import Callable+from functools import lru_cachefrom typing import Literal, Optional, TypeGuard, castfrom django.db import models@@ -264,15 +265,57 @@ class AggregationFinder(TraversingVisitor):self.visit(arg)-def _handle_bool_values(value: ValueT, expr: ast.Expr, property: Property, team: Team) -> ValueT | bool:+def _resolve_boolean_value(value: ValueT) -> bool | None:+ """Resolve a filter value for a Boolean-typed property. Anything other than the+ 'true'/'false' the UI sends returns None, so the comparison matches nothing rather+ than failing in ClickHouse, which cannot parse e.g. 'foo' as a bool."""+ if isinstance(value, bool):+ return value+ if value == "true":+ return True+ if value == "false":+ return False+ return None+++@lru_cache(maxsize=2048)+def _property_definition_is_boolean(+ project_id: int,+ property_key: str,+ definition_type: "PropertyDefinition.Type",+ group_type_index: int | None,+) -> bool:+ """Whether a saved PropertyDefinition for this key is Boolean-typed.++ Memoized because _handle_bool_values now runs for every exact/is_not+ comparison (not just literal true/false values), and a query build can+ contain many comparisons on the same property. PropertyDefinition types+ are effectively static within a process, so a process-level cache is safe.+ """+ filters: dict[str, object] = {+ "effective_project_id": project_id,+ "name": property_key,+ "type": definition_type,+ }+ if definition_type == PropertyDefinition.Type.GROUP:+ filters["group_type_index"] = group_type_index+ property_def = (+ PropertyDefinition.objects.alias(+ effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())+ )+ .filter(**filters)+ .values_list("property_type", flat=True)+ .first()+ )+ return property_def == PropertyType.Boolean+++def _handle_bool_values(value: ValueT, expr: ast.Expr, property: Property, team: Team) -> ValueT | bool | None:if value is True:value = "true"elif value is False:value = "false"- if value != "true" and value != "false":- return value-# Virtual event properties (e.g. $virt_is_bot) don't have PropertyDefinition# records, so we check the taxonomy directly for boolean typeif property.key and property.key.startswith("$virt_"):@@ -281,26 +324,19 @@ def _handle_bool_values(value: ValueT, expr: ast.Expr, property: Property, team:for group_defs in CORE_FILTER_DEFINITIONS_BY_GROUP.values():prop_def = group_defs.get(property.key)if prop_def and prop_def.get("type") == "Boolean":- return value == "true"+ return _resolve_boolean_value(value)return valueif property.type == "person":- property_types = PropertyDefinition.objects.alias(- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())- ).filter(- effective_project_id=team.project_id,- name=property.key,- type=PropertyDefinition.Type.PERSON,- )+ if _property_definition_is_boolean(team.project_id, property.key, PropertyDefinition.Type.PERSON, None):+ return _resolve_boolean_value(value)+ return valueelif property.type == "group":- property_types = PropertyDefinition.objects.alias(- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())- ).filter(- effective_project_id=team.project_id,- name=property.key,- type=PropertyDefinition.Type.GROUP,- group_type_index=property.group_type_index,- )+ if _property_definition_is_boolean(+ team.project_id, property.key, PropertyDefinition.Type.GROUP, property.group_type_index+ ):+ return _resolve_boolean_value(value)+ return valueelif property.type == "data_warehouse_person_property":if not isinstance(expr, ast.Field):raise Exception(f"Requires a Field expression")@@ -329,38 +365,20 @@ def _handle_bool_values(value: ValueT, expr: ast.Expr, property: Property, team:raise Exception(f"Could not find table or view for key {key}")if prop_type == "BooleanDatabaseField":- if value == "true":- value = True- if value == "false":- value = False+ return _resolve_boolean_value(value)return valueelif property.type == "session":field_definition = LAZY_SESSIONS_FIELDS.get(property.key)if isinstance(field_definition, BooleanDatabaseField):- if value == "true":- return True- if value == "false":- return False+ return _resolve_boolean_value(value)return valueelse:- property_types = PropertyDefinition.objects.alias(- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())- ).filter(- effective_project_id=team.project_id,- name=property.key,- type=PropertyDefinition.Type.EVENT,- )- property_type = property_types[0].property_type if len(property_types) > 0 else None-- if property_type == PropertyType.Boolean:- if value == "true":- return True- if value == "false":- return False- return value+ if _property_definition_is_boolean(team.project_id, property.key, PropertyDefinition.Type.EVENT, None):+ return _resolve_boolean_value(value)+ return valuedef _resolve_date_value(value: ValueT, team: Team) -> ValueT:@@ -546,10 +564,17 @@ def _expr_to_compare_op(right=_force_datetime(ast.Constant(value=_resolve_date_value(value, team))),)elif operator == PropertyOperator.IS_NOT:+ resolved_value = _handle_bool_values(value, expr, property, team)+ # A non-boolean value against a Boolean property resolves to None. For+ # IS_NOT that would emit `expr != NULL`, which is NULL in ClickHouse+ # three-valued logic and matches zero rows. Every row "is not" the+ # unparseable value, so match everything instead.+ if resolved_value is None and value is not None:+ return ast.Constant(value=True)return ast.CompareOperation(op=ast.CompareOperationOp.NotEq,left=expr,- right=ast.Constant(value=_handle_bool_values(value, expr, property, team)),+ right=ast.Constant(value=resolved_value),)elif operator == PropertyOperator.LT:return ast.CompareOperation(op=ast.CompareOperationOp.Lt, left=expr, right=ast.Constant(value=value))diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.pyindex 4c342a5b939e..723d0816b1f7 100644--- a/posthog/hogql/test/test_property.py+++ b/posthog/hogql/test/test_property.py@@ -24,6 +24,7 @@ from posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_exprfrom posthog.hogql.printer.utils import prepare_and_print_astfrom posthog.hogql.property import (+ _resolve_boolean_value,entity_to_expr,has_aggregation,map_virtual_properties,@@ -1983,3 +1984,53 @@ class TestPropertyDateOperatorsWithData(APIBaseTest):count = self._run({"type": "event", "key": "signup_dt", "value": value, "operator": operator})assert count == expected_count+++# Executes generated SQL: a non-boolean value against a Boolean property renders+# valid HogQL but ClickHouse rejects it at runtime, so AST-only tests miss it.+class TestBooleanPropertyComparisonWithData(APIBaseTest):+ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ PropertyDefinition.objects.create(+ team=cls.team, name="is_active", property_type="Boolean", type=PropertyDefinition.Type.EVENT+ )+ _create_event(team=cls.team, event="signup", distinct_id="u1", properties={"is_active": "true"})+ _create_event(team=cls.team, event="signup", distinct_id="u2", properties={"is_active": "false"})++ def _run(self, filter: dict) -> int:+ query_ast = ast.SelectQuery(+ select=[ast.Call(name="count", args=[])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ where=property_to_expr(filter, team=self.team, scope="event"),+ )+ return execute_hogql_query(team=self.team, query=query_ast).results[0][0]++ @parameterized.expand(+ [+ ("true_matches", "true", "exact", 1),+ ("false_matches", "false", "exact", 1),+ # a non-boolean value cannot match a boolean property — 0 rows, not a crash+ ("non_boolean_value_matches_nothing", "not-a-boolean", "exact", 0),+ # is_not with a valid boolean value returns the complementary row+ ("is_not_true_matches_false_row", "true", "is_not", 1),+ # is_not with a non-boolean value: every row "is not" it — match all, not a crash and not 0 rows+ ("is_not_non_boolean_matches_everything", "not-a-boolean", "is_not", 2),+ ]+ )+ def test_boolean_property_comparison(self, _name, value, operator, expected_count):+ assert self._run({"type": "event", "key": "is_active", "value": value, "operator": operator}) == expected_count++ @parameterized.expand(+ [+ ("true", "true", True),+ ("false", "false", False),+ ("bool_passthrough", True, True),+ # only the UI's "true"/"false" resolve — anything else matches nothing+ ("one_is_none", "1", None),+ ("yes_is_none", "yes", None),+ ("non_boolean_is_none", "not-a-boolean", None),+ ]+ )+ def test_resolve_boolean_value(self, _name, value, expected):+ assert _resolve_boolean_value(value) is expecteddiff --git a/posthog/test/base.py b/posthog/test/base.pyindex 893794ee4b2d..52b604edca5c 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -40,6 +40,7 @@ from posthog.hogql import (from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.printer import prepare_and_print_ast+from posthog.hogql.property import _property_definition_is_booleanfrom posthog.hogql.visitor import clone_exprfrom posthog import rate_limit, redis@@ -664,6 +665,7 @@ class PostHogTestCase(SimpleTestCase):def setUp(self):get_instance_setting.cache_clear()+ _property_definition_is_boolean.cache_clear()if get_instance_setting("PERSON_ON_EVENTS_ENABLED"):from posthog.models.team import util