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: revert: "fix(insights): handle non-boolean filter values on..." (#59920)

Gustavo H. Strassburger78c49c8f5797
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index 6d412cfcc706..c6cfa1f18056 100644
--- a/posthog/hogql/property.py
+++ b/posthog/hogql/property.py
@@ -1,6 +1,5 @@
import re
from collections.abc import Callable
-from functools import lru_cache
from typing import Literal, Optional, TypeGuard, cast
from django.db import models
@@ -265,57 +264,15 @@ class AggregationFinder(TraversingVisitor):
self.visit(arg)
-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:
+def _handle_bool_values(value: ValueT, expr: ast.Expr, property: Property, team: Team) -> ValueT | bool:
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 type
if property.key and property.key.startswith("$virt_"):
@@ -324,19 +281,26 @@ 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 _resolve_boolean_value(value)
+ return value == "true"
return value
if property.type == "person":
- if _property_definition_is_boolean(team.project_id, property.key, PropertyDefinition.Type.PERSON, None):
- return _resolve_boolean_value(value)
- return value
+ 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,
+ )
elif property.type == "group":
- if _property_definition_is_boolean(
- team.project_id, property.key, PropertyDefinition.Type.GROUP, property.group_type_index
- ):
- return _resolve_boolean_value(value)
- return value
+ 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,
+ )
elif property.type == "data_warehouse_person_property":
if not isinstance(expr, ast.Field):
raise Exception(f"Requires a Field expression")
@@ -365,20 +329,38 @@ 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":
- return _resolve_boolean_value(value)
+ if value == "true":
+ value = True
+ if value == "false":
+ value = False
return value
elif property.type == "session":
field_definition = LAZY_SESSIONS_FIELDS.get(property.key)
if isinstance(field_definition, BooleanDatabaseField):
- return _resolve_boolean_value(value)
+ if value == "true":
+ return True
+ if value == "false":
+ return False
return value
else:
- if _property_definition_is_boolean(team.project_id, property.key, PropertyDefinition.Type.EVENT, None):
- return _resolve_boolean_value(value)
- return value
+ 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
def _resolve_date_value(value: ValueT, team: Team) -> ValueT:
@@ -564,17 +546,10 @@ 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=resolved_value),
+ right=ast.Constant(value=_handle_bool_values(value, expr, property, team)),
)
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.py
index 723d0816b1f7..4c342a5b939e 100644
--- a/posthog/hogql/test/test_property.py
+++ b/posthog/hogql/test/test_property.py
@@ -24,7 +24,6 @@ from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr
from posthog.hogql.printer.utils import prepare_and_print_ast
from posthog.hogql.property import (
- _resolve_boolean_value,
entity_to_expr,
has_aggregation,
map_virtual_properties,
@@ -1984,53 +1983,3 @@ 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 expected
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 52b604edca5c..893794ee4b2d 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -40,7 +40,6 @@ from posthog.hogql import (
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
-from posthog.hogql.property import _property_definition_is_boolean
from posthog.hogql.visitor import clone_expr
from posthog import rate_limit, redis
@@ -665,7 +664,6 @@ 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