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(hogql): keep rows on missing property for negative operators (#91418)

Phil Haackc2cd7098ad25
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.md
index 9f067ada3e99..1fd71f66f187 100644
--- a/docs/internal/feature-flags/flag-evaluation-engine.md
+++ b/docs/internal/feature-flags/flag-evaluation-engine.md
@@ -237,18 +237,19 @@ Each flag has one or more condition groups (OR'd). Within each group, property f
Defined in `rust/feature-flags/src/properties/property_matching.rs`. The service supports 23 operators:
-| Category | Operators | Behavior |
-| ------------ | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Existence | `is_set`, `is_not_set` | Key presence check in property map |
-| Equality | `exact`, `is_not` | Case-insensitive comparison. Arrays checked with contains. Boolean normalization for `"true"`/`"false"` strings. |
-| String | `icontains`, `not_icontains` | ASCII-case-insensitive substring match |
-| Regex | `regex`, `not_regex` | `fancy_regex` with 10,000 step backtrack limit (ReDoS protection). Patterns are pre-compiled once per request via `prepare_regexes()`. Three-state dispatch in `match_property()`: pre-compiled fast path → `InvalidPattern` short-circuit to `Ok(false)` → fallback on-the-fly compilation. |
-| Numeric | `gt`, `gte`, `lt`, `lte` | Parse both sides as `f64` |
-| Semver | `semver_gt`, `semver_gte`, `semver_lt`, `semver_lte`, `semver_eq`, `semver_neq` | Direct `Version` comparison |
-| Semver range | `semver_tilde`, `semver_caret`, `semver_wildcard` | `VersionReq` parsing (`~1.2.3`, `^1.2.3`, `1.2.x`) |
-| Date | `is_date_exact`, `is_date_after`, `is_date_before` | Supports relative dates, ISO 8601, Unix timestamps |
-| Cohort | `in`, `not_in` | Handled by cohort matching, not property matching |
-| Flag | `flag_evaluates_to` | Handled by flag dependency matching |
+| Category | Operators | Behavior |
+| ------------ | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Existence | `is_set`, `is_not_set` | Key presence check in property map |
+| Equality | `exact`, `is_not` | Case-insensitive comparison. Arrays checked with contains. Boolean normalization for `"true"`/`"false"` strings. |
+| String | `icontains`, `not_icontains` | ASCII-case-insensitive substring match |
+| Regex | `regex`, `not_regex` | `fancy_regex` with 10,000 step backtrack limit (ReDoS protection). Patterns are pre-compiled once per request via `prepare_regexes()`. Three-state dispatch in `match_property()`: pre-compiled fast path → `InvalidPattern` short-circuit to `Ok(false)` → fallback on-the-fly compilation. |
+| Numeric | `gt`, `gte`, `lt`, `lte` | Parse both sides as `f64` |
+| Range | `between`, `not_between` | Inclusive on both ends, parsed as `f64`. A value that is missing, JSON null, or not a number is out of range (`between` false, `not_between` true), mirroring HogQL where it reads as NULL. NaN is a non-match for both. Malformed bounds are a `ValidationError` even when the property is missing. |
+| Semver | `semver_gt`, `semver_gte`, `semver_lt`, `semver_lte`, `semver_eq`, `semver_neq` | Direct `Version` comparison |
+| Semver range | `semver_tilde`, `semver_caret`, `semver_wildcard` | `VersionReq` parsing (`~1.2.3`, `^1.2.3`, `1.2.x`) |
+| Date | `is_date_exact`, `is_date_after`, `is_date_before` | Supports relative dates, ISO 8601, Unix timestamps |
+| Cohort | `in`, `not_in` | Handled by cohort matching, not property matching |
+| Flag | `flag_evaluates_to` | Handled by flag dependency matching |
## Multivariate flags (variant selection)
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index 5df17decebe8..e15930fb204f 100644
--- a/posthog/hogql/property.py
+++ b/posthog/hogql/property.py
@@ -1,4 +1,5 @@
import re
+import math
from collections.abc import Callable
from typing import Literal, Optional, TypeGuard, cast
@@ -8,6 +9,7 @@ from django.db.models.functions.comparison import Coalesce
import re2
import posthoganalytics
+from more_itertools import chunked
from pydantic import BaseModel
from rest_framework.exceptions import ValidationError
@@ -548,11 +550,27 @@ def _force_datetime(expr: ast.Expr) -> ast.Expr:
def _validate_between_values(value: ValueT, operator: PropertyOperator) -> TypeGuard[list[str]]:
if not isinstance(value, list) or len(value) != 2:
raise QueryError(f"{operator} operator requires a two-element array [min, max]")
- try:
- if float(value[0]) > float(value[1]):
- raise QueryError(f"{operator} operator requires min value to be less than or equal to max value")
- except (ValueError, TypeError):
- raise QueryError(f"{operator} operator requires numeric values")
+
+ # ValueT declares list[str], but a filter value reaches here as parsed JSON, so a bound can be
+ # any scalar. Taking `object` keeps the runtime checks below reachable.
+ def _to_bound(bound: object) -> float:
+ # bool is a subclass of int, so float() would silently accept it, and float("NaN") parses
+ # to a real NaN. The Rust evaluator (rust/feature-flags/src/properties/property_matching.rs)
+ # rejects both as bounds.
+ not_numeric = QueryError(f"{operator} operator requires numeric values")
+ if isinstance(bound, bool) or not isinstance(bound, (str, int, float)):
+ raise not_numeric
+ try:
+ parsed = float(bound)
+ except (ValueError, TypeError):
+ raise not_numeric
+ if math.isnan(parsed):
+ raise not_numeric
+ return parsed
+
+ low, high = _to_bound(value[0]), _to_bound(value[1])
+ if low > high:
+ raise QueryError(f"{operator} operator requires min value to be less than or equal to max value")
return True
@@ -561,9 +579,41 @@ def _multi_search_found(search_call: ast.Call) -> ast.CompareOperation:
return ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=search_call, right=ast.Constant(value=0))
-def _multi_search_not_found(search_call: ast.Call) -> ast.CompareOperation:
- """Create comparison operation to check if multiSearchAnyCaseInsensitive did not find a match."""
- return ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=search_call, right=ast.Constant(value=0))
+def _multi_search_not_found(search_call: ast.Call) -> ast.Expr:
+ """Create an expression that is true when multiSearchAnyCaseInsensitive found no match.
+
+ Negates the positive form instead of adding a separate NULL check: multiSearchAnyCaseInsensitive
+ resolves as nullable, so the printer already wraps the found comparison in ifNull(..., 0), and a
+ missing property therefore makes the found check false and this negation true, matching every
+ other negative operator. The bare multiSearchAnyCaseInsensitive call also stays what
+ _optimize_materialized_array_multisearch matches on to build an arrayExists scan."""
+ return ast.Not(expr=_multi_search_found(search_call))
+
+
+_NEGATIVE_OPERATOR_COMPLEMENTS = {
+ PropertyOperator.IS_NOT: PropertyOperator.EXACT,
+ PropertyOperator.NOT_IN: PropertyOperator.IN_,
+ PropertyOperator.IS_NOT_SET: PropertyOperator.IS_SET,
+ PropertyOperator.NOT_ICONTAINS: PropertyOperator.ICONTAINS,
+ PropertyOperator.NOT_ICONTAINS_MULTI: PropertyOperator.ICONTAINS_MULTI,
+ PropertyOperator.NOT_REGEX: PropertyOperator.REGEX,
+ PropertyOperator.NOT_STARTS_WITH: PropertyOperator.STARTS_WITH,
+ PropertyOperator.NOT_ENDS_WITH: PropertyOperator.ENDS_WITH,
+ PropertyOperator.NOT_BETWEEN: PropertyOperator.BETWEEN,
+}
+
+
+def operator_is_negative(operator: PropertyOperator) -> bool:
+ return operator in _NEGATIVE_OPERATOR_COMPLEMENTS
+
+
+def _array_property_filter(array: ast.Expr, element_predicate: ast.Expr, negate: bool) -> ast.Expr:
+ """`element_predicate` is the positive form even when `negate` is set: a negative operator
+ negates the whole arrayExists, so an empty or missing array is kept and an array holding any
+ matching element is dropped. Negating per element instead keeps a row as soon as one element
+ fails to match and drops a row whose array is empty."""
+ exists = ast.Call(name="arrayExists", args=[ast.Lambda(args=["v"], expr=element_predicate), array])
+ return ast.Not(expr=exists) if negate else exists
def _create_multi_search_call(expr: ast.Expr, value: list) -> ast.Call:
@@ -577,6 +627,29 @@ def _create_multi_search_call(expr: ast.Expr, value: list) -> ast.Call:
)
+# ClickHouse 26.6.2 rejects a nonconstant multiSearchAnyCaseInsensitive call with more than 255
+# needles ("passed N, should be at most 255").
+_MULTI_SEARCH_NEEDLE_LIMIT = 255
+
+
+def _chunk_needles(value: list) -> list[list]:
+ return [list(chunk) for chunk in chunked(value, _MULTI_SEARCH_NEEDLE_LIMIT)]
+
+
+def _multi_search_found_for_values(expr: ast.Expr, value: list) -> ast.Expr:
+ """True if `expr` matches any of `value`, chunking past ClickHouse's needle limit and ORing
+ the chunks together."""
+ found_exprs: list[ast.Expr] = [
+ _multi_search_found(_create_multi_search_call(expr, chunk)) for chunk in _chunk_needles(value)
+ ]
+ return found_exprs[0] if len(found_exprs) == 1 else ast.Or(exprs=found_exprs)
+
+
+def _multi_search_not_found_for_values(expr: ast.Expr, value: list) -> ast.Expr:
+ """True if `expr` matches none of `value`, chunking past ClickHouse's needle limit."""
+ return ast.Not(expr=_multi_search_found_for_values(expr, value))
+
+
def _validate_regex(value: ValueT) -> None:
"""Reject an invalid regular expression with a clear user-facing error rather
than letting ClickHouse fail the whole query with CANNOT_COMPILE_REGEXP. The
@@ -607,7 +680,7 @@ def _expr_to_compare_op(
elif operator == PropertyOperator.ICONTAINS:
if isinstance(value, list) and len(value) > 1:
# Multiple values: use ClickHouse's multiSearchAnyCaseInsensitive for efficient searching
- return _multi_search_found(_create_multi_search_call(expr, value))
+ return _multi_search_found_for_values(expr, value)
else:
# Single value (or single-element array): keep existing ILIKE logic for backward compatibility
single_value = value[0] if isinstance(value, list) and len(value) == 1 else value
@@ -619,7 +692,7 @@ def _expr_to_compare_op(
elif operator == PropertyOperator.NOT_ICONTAINS:
if isinstance(value, list) and len(value) > 1:
# Multiple values: use ClickHouse's multiSearchAnyCaseInsensitive with negation
- return _multi_search_not_found(_create_multi_search_call(expr, value))
+ return _multi_search_not_found_for_values(expr, value)
else:
# Single value (or single-element array): keep existing NOT ILIKE logic for backward compatibility
single_value = value[0] if isinstance(value, list) and len(value) == 1 else value
@@ -652,14 +725,14 @@ def _expr_to_compare_op(
values_list = value
else:
values_list = cast(list, [value])
- return _multi_search_found(_create_multi_search_call(expr, values_list))
+ return _multi_search_found_for_values(expr, values_list)
elif operator == PropertyOperator.NOT_ICONTAINS_MULTI:
# Always expect multiple values for multi-not-contains operator
if isinstance(value, list):
values_list = value
else:
values_list = cast(list, [value])
- return _multi_search_not_found(_create_multi_search_call(expr, values_list))
+ return _multi_search_not_found_for_values(expr, values_list)
elif operator == PropertyOperator.REGEX:
_validate_regex(value)
return ast.Call(
@@ -748,6 +821,9 @@ def _expr_to_compare_op(
exprs=[
ast.CompareOperation(op=ast.CompareOperationOp.Lt, left=expr, right=ast.Constant(value=value[0])),
ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=expr, right=ast.Constant(value=value[1])),
+ # A missing property makes both comparisons NULL and drops the row; keep it, matching
+ # every other negative operator.
+ ast.Call(name="isNull", args=[expr]),
]
)
elif operator == PropertyOperator.IS_CLEANED_PATH_EXACT:
@@ -1300,17 +1376,17 @@ def property_to_expr(
expr = ast.Call(name="argMinMerge", args=[field])
is_visited_page_property = property.type == "recording" and property.key == "visited_page"
- if is_visited_page_property:
- # Use the all_urls array field to filter for pages visited during recording.
- all_urls_field = ast.Call(name="groupUniqArrayArray", args=[ast.Field(chain=["all_urls"])])
-
is_exception_string_array_property = (
property.type == "event" and property.key in EXCEPTION_STRING_ARRAY_PROPERTIES
)
- if is_exception_string_array_property:
+ array_field: ast.Expr | None = None
+ if is_visited_page_property:
+ # Use the all_urls array field to filter for pages visited during recording.
+ array_field = ast.Call(name="groupUniqArrayArray", args=[ast.Field(chain=["all_urls"])])
+ elif is_exception_string_array_property:
# if materialized these columns will be strings so we need to extract them
- extracted_field = ast.Call(
+ array_field = ast.Call(
name="JSONExtract",
args=[
ast.Call(name="ifNull", args=[field, ast.Constant(value="")]),
@@ -1318,6 +1394,14 @@ def property_to_expr(
],
)
+ # _expr_to_compare_op combines every value of these into one multiSearchAnyCaseInsensitive
+ # call, so they must reach it with the list intact. Expanding them per value would OR
+ # separate negations together and keep a row that matches only one needle.
+ combines_values_itself = operator in (
+ PropertyOperator.ICONTAINS_MULTI,
+ PropertyOperator.NOT_ICONTAINS_MULTI,
+ )
+
if isinstance(value, list) and operator not in (
PropertyOperator.BETWEEN,
PropertyOperator.NOT_BETWEEN,
@@ -1327,71 +1411,36 @@ def property_to_expr(
# primitive exists, so multi-value use falls through to per-value ILIKE scans below.
):
if len(value) == 0:
+ # An unconfigured filter matches every row. multiSearchAnyCaseInsensitive(x, [])
+ # would instead fail the query with ILLEGAL_TYPE_OF_ARGUMENT.
return ast.Constant(value=1)
elif len(value) == 1:
+ # _expr_to_compare_op's ICONTAINS_MULTI/NOT_ICONTAINS_MULTI arms re-wrap a scalar
+ # into a single-element list, so collapsing here is a no-op round trip for them too.
value = value[0]
- else:
+ elif not combines_values_itself:
if operator in (
PropertyOperator.EXACT,
PropertyOperator.IS_NOT,
PropertyOperator.IN_,
PropertyOperator.NOT_IN,
):
- op = (
- ast.CompareOperationOp.In
- if operator in (PropertyOperator.EXACT, PropertyOperator.IN_)
- else ast.CompareOperationOp.NotIn
- )
-
- left = (
- ast.Field(chain=["v"])
- if (is_exception_string_array_property or is_visited_page_property)
- else expr
- )
coerced = cast(list, _coerce_numeric_value_for_string_property(value, property, team))
- compare_op = ast.CompareOperation(
- op=op,
- left=left,
- right=ast.Tuple(exprs=[ast.Constant(value=v) for v in coerced]),
- )
-
- if is_exception_string_array_property:
- return parse_expr(
- "arrayExists(v -> {compare_op}, {field})",
- {
- "compare_op": compare_op,
- "field": extracted_field,
- },
- )
- elif is_visited_page_property:
- return parse_expr(
- "arrayExists(v -> {compare_op}, {field})",
- {
- "compare_op": compare_op,
- "field": all_urls_field,
- },
+ values = ast.Tuple(exprs=[ast.Constant(value=v) for v in coerced])
+ negate = operator_is_negative(operator)
+ if array_field is not None:
+ return _array_property_filter(
+ array_field,
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In, left=ast.Field(chain=["v"]), right=values
+ ),
+ negate=negate,
)
- else:
- return compare_op
- elif operator in (PropertyOperator.ICONTAINS, PropertyOperator.NOT_ICONTAINS):
- # For contains operators, delegate to _expr_to_compare_op which handles multiple values efficiently
- if is_exception_string_array_property or is_visited_page_property:
- # For exception properties and visited_page, use multiSearch optimization within arrayExists
- multi_search_expr = _expr_to_compare_op(
- ast.Field(chain=["v"]), value, operator, property, property.type != "session", team
- )
- if is_exception_string_array_property:
- return parse_expr(
- "arrayExists(v -> {expr}, {key})",
- {"expr": multi_search_expr, "key": extracted_field},
- )
- else: # is_visited_page_property
- return parse_expr(
- "arrayExists(v -> {expr}, {key})",
- {"expr": multi_search_expr, "key": all_urls_field},
- )
- else:
- return _expr_to_compare_op(expr, value, operator, property, property.type != "session", team)
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.NotIn if negate else ast.CompareOperationOp.In,
+ left=expr,
+ right=values,
+ )
exprs = [
property_to_expr(
@@ -1418,41 +1467,34 @@ def property_to_expr(
return ast.And(exprs=exprs)
return ast.Or(exprs=exprs)
- expr = _expr_to_compare_op(
- expr=ast.Field(chain=["v"]) if (is_exception_string_array_property or is_visited_page_property) else expr,
+ is_json_field = property.type != "session"
+
+ if array_field is None:
+ return _expr_to_compare_op(
+ expr=expr,
+ value=value,
+ operator=operator,
+ team=team,
+ property=property,
+ is_json_field=is_json_field,
+ )
+
+ if operator in (PropertyOperator.IS_SET, PropertyOperator.IS_NOT_SET):
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt if operator == PropertyOperator.IS_SET else ast.CompareOperationOp.Eq,
+ left=ast.Call(name="length", args=[array_field]),
+ right=ast.Constant(value=0),
+ )
+
+ element_predicate = _expr_to_compare_op(
+ expr=ast.Field(chain=["v"]),
value=value,
- operator=operator,
+ operator=_NEGATIVE_OPERATOR_COMPLEMENTS.get(operator, operator),
team=team,
property=property,
- is_json_field=property.type != "session",
+ is_json_field=is_json_field,
)
-
- if is_exception_string_array_property:
- return parse_expr(
- "arrayExists(v -> {expr}, {key})",
- {"expr": expr, "key": extracted_field},
- )
- elif is_visited_page_property:
- # Handle IS_SET and IS_NOT_SET operators specially for arrays
- if operator == PropertyOperator.IS_SET:
- return ast.CompareOperation(
- op=ast.CompareOperationOp.Gt,
- left=ast.Call(name="length", args=[all_urls_field]),
- right=ast.Constant(value=0),
- )
- elif operator == PropertyOperator.IS_NOT_SET:
- return ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Call(name="length", args=[all_urls_field]),
- right=ast.Constant(value=0),
- )
- else:
- return parse_expr(
- "arrayExists(v -> {expr}, {key})",
- {"expr": expr, "key": all_urls_field},
- )
- else:
- return expr
+ return _array_property_filter(array_field, element_predicate, negate=operator_is_negative(operator))
elif property.type == "element":
if scope == "person":
raise NotImplementedError(f"property_to_expr for scope {scope} not implemented for type '{property.type}'")
@@ -1898,17 +1940,3 @@ class _LowercaseIndexRewriter(CloningVisitor):
right=right,
op=op,
)
-
-
-def operator_is_negative(operator: PropertyOperator) -> bool:
- return operator in [
- PropertyOperator.IS_NOT,
- PropertyOperator.NOT_ICONTAINS,
- PropertyOperator.NOT_ICONTAINS_MULTI,
- PropertyOperator.NOT_STARTS_WITH,
- PropertyOperator.NOT_ENDS_WITH,
- PropertyOperator.NOT_REGEX,
- PropertyOperator.IS_NOT_SET,
- PropertyOperator.NOT_BETWEEN,
- PropertyOperator.NOT_IN,
- ]
diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.py
index 0502d0b292c6..f6328882e7d5 100644
--- a/posthog/hogql/test/test_property.py
+++ b/posthog/hogql/test/test_property.py
@@ -6,6 +6,7 @@ from posthog.test.base import APIBaseTest, BaseTest, _create_event, cleanup_mate
from unittest.mock import MagicMock, patch
from django.conf import settings
+from django.test import override_settings
from parameterized import parameterized
@@ -32,12 +33,13 @@ from posthog.hogql.property import (
entity_to_expr,
has_aggregation,
map_virtual_properties,
+ operator_is_negative,
property_to_expr,
selector_to_expr,
tag_name_to_expr,
)
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql.visitor import clear_locations
+from posthog.hogql.visitor import TraversingVisitor, clear_locations
from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_EVENTS, PropertyOperatorType
from posthog.models import Property, PropertyDefinition, Team
@@ -57,6 +59,20 @@ elements_chain_imatch = lambda x: parse_expr("elements_chain =~* {regex}", {"reg
not_call = lambda x: ast.Call(name="not", args=[x])
+class _FieldChainCollector(TraversingVisitor):
+ def __init__(self) -> None:
+ self.parts: set[str] = set()
+
+ def visit_field(self, node: ast.Field) -> None:
+ self.parts.update(str(part) for part in node.chain)
+
+
+def field_parts_read_by(expr: ast.Expr) -> set[str]:
+ collector = _FieldChainCollector()
+ collector.visit(expr)
+ return collector.parts
+
+
class TestProperty(BaseTest):
maxDiff = None
@@ -450,7 +466,7 @@ class TestProperty(BaseTest):
"operator": "not_icontains",
}
),
- self._parse_expr("multiSearchAnyCaseInsensitive(toString(properties.a), ['b', 'c']) = 0"),
+ self._parse_expr("NOT multiSearchAnyCaseInsensitive(toString(properties.a), ['b', 'c']) > 0"),
)
a = self._property_to_expr(
{
@@ -546,7 +562,7 @@ class TestProperty(BaseTest):
}
),
self._parse_expr(
- "arrayExists(v -> v not in ('ReferenceError', 'TypeError'), JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
+ "NOT arrayExists(v -> v in ('ReferenceError', 'TypeError'), JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
),
)
self.assertEqual(
@@ -559,7 +575,7 @@ class TestProperty(BaseTest):
}
),
self._parse_expr(
- "arrayExists(v -> ifNull(not(match(toString(v), 'ValidationError')), 1), JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
+ "NOT arrayExists(v -> ifNull(match(toString(v), 'ValidationError'), 0), JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
),
)
self.assertEqual(
@@ -585,7 +601,7 @@ class TestProperty(BaseTest):
}
),
self._parse_expr(
- "arrayExists(v -> toString(v) NOT ILIKE '%ValidationError%', JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
+ "NOT arrayExists(v -> toString(v) ILIKE '%ValidationError%', JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
),
)
self.assertEqual(
@@ -611,7 +627,7 @@ class TestProperty(BaseTest):
}
),
self._parse_expr(
- "arrayExists(v -> multiSearchAnyCaseInsensitive(toString(v), ['ReferenceError', 'TypeError']) = 0, JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
+ "NOT arrayExists(v -> multiSearchAnyCaseInsensitive(toString(v), ['ReferenceError', 'TypeError']) > 0, JSONExtract(ifNull(properties.$exception_types, ''), 'Array(String)'))"
),
)
@@ -1602,7 +1618,7 @@ class TestProperty(BaseTest):
self.assertEqual(
self._property_to_expr({"type": "event", "key": "score", "operator": "not_between", "value": [0, 100]}),
- self._parse_expr("(properties.score < 0 OR properties.score > 100)"),
+ self._parse_expr("(properties.score < 0 OR properties.score > 100 OR isNull(properties.score))"),
)
def test_property_to_expr_between_operator_validation(self):
@@ -1637,6 +1653,15 @@ class TestProperty(BaseTest):
with self.assertRaisesMessage(QueryError, "between operator requires numeric values"):
self._property_to_expr({"type": "event", "key": "age", "operator": "between", "value": [None, 10]})
+ # float("NaN") parses without error, and float(bool) silently coerces to 0.0/1.0, so both need an
+ # explicit reject to match rust/feature-flags/src/properties/property_matching.rs, which refuses
+ # both as filter bounds.
+ with self.assertRaisesMessage(QueryError, "not_between operator requires numeric values"):
+ self._property_to_expr({"type": "event", "key": "age", "operator": "not_between", "value": ["NaN", 100]})
+
+ with self.assertRaisesMessage(QueryError, "not_between operator requires numeric values"):
+ self._property_to_expr({"type": "event", "key": "age", "operator": "not_between", "value": [False, True]})
+
@parameterized.expand(
[
("trailing_backslash", "^abc\\"),
@@ -1963,7 +1988,29 @@ class TestProperty(BaseTest):
result = self._property_to_expr(
{"type": "event", "key": "test_prop", "value": value, "operator": operator_value}
)
- self.assertIsInstance(result, ast.Expr)
+ # An unhandled operator degrades to a neutral constant that matches every row, which an
+ # isinstance check accepts. Requiring the compiled expression to read the filtered property
+ # rejects that. This guards dispatch only: how multiple values combine is behavior, covered
+ # by test_multi_value_negative_operator_drops_row_matching_any_value.
+ assert "test_prop" in field_parts_read_by(result)
+
+ # An empty value list means the filter is not configured, so HogQL matches every row. Without a
+ # guard these two operators build multiSearchAnyCaseInsensitive(x, []), which ClickHouse rejects
+ # with ILLEGAL_TYPE_OF_ARGUMENT. This is HogQL's own convention, not a cross-engine agreement:
+ # the Rust flag evaluator treats an empty icontains_multi list as matching nothing instead.
+ # "$exception_types" exercises the array-backed path, which compiles through arrayExists.
+ @parameterized.expand([("icontains_multi",), ("not_icontains_multi",)])
+ def test_empty_value_list_is_a_neutral_filter(self, operator: str):
+ for key in ("plan", "$exception_types"):
+ assert self._property_to_expr({"type": "event", "key": key, "value": [], "operator": operator}) == (
+ ast.Constant(value=1)
+ )
+
+ def test_every_negative_operator_is_known(self):
+ # A negative operator missing from operator_is_negative silently negates per element on
+ # array properties and loses its lowercase index hint, so the name pattern pins the set.
+ by_name = {op for op in PropertyOperator if op.value.startswith(("not_", "is_not"))}
+ assert {op for op in PropertyOperator if operator_is_negative(op)} == by_name
def test_flag_evaluates_to_produces_neutral_expr(self):
prop = FlagPropertyFilter(type="flag", key="my-flag", value="true", operator="flag_evaluates_to")
@@ -2445,3 +2492,288 @@ class TestPropertyDateOperatorsWithData(APIBaseTest):
count = self._run({"type": "event", "key": "signup_dt", "value": value, "operator": operator})
assert count == expected_count
+
+
+# A property missing from a row extracts to NULL, which a WHERE clause discards, so every negative
+# operator must keep such a row on its own. The NULL default is applied in the printer, not the AST,
+# so these run the printed SQL against ClickHouse rather than asserting AST shape. The events carry
+# no person, so a person-scoped filter sees person_properties '{}' and must keep that row too.
+class TestNegativeOperatorNullParityWithData(APIBaseTest):
+ EVENT = "purchase"
+ SCORED_EVENT = "scored"
+ EXCEPTION_EVENT = "exception"
+ ARRAYS_WITHOUT_MATCH = {"types_missing", "types_empty", "types_nonmatch_only"}
+ ARRAYS_WITH_MATCH = {"types_match_only", "types_mixed"}
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ PropertyDefinition.objects.create(
+ team=cls.team,
+ name="score",
+ type=PropertyDefinition.Type.EVENT,
+ property_type=PropertyType.Numeric,
+ )
+ _create_event(
+ team=cls.team,
+ event=cls.EVENT,
+ distinct_id="present_nonmatch",
+ properties={"plan": "enterprise", "score": 50},
+ )
+ _create_event(
+ team=cls.team, event=cls.EVENT, distinct_id="present_match", properties={"plan": "free", "score": 500}
+ )
+ _create_event(team=cls.team, event=cls.EVENT, distinct_id="missing", properties={})
+ for distinct_id, score in [
+ ("score_50", 50),
+ ("score_500", 500),
+ ("score_abc", "abc"),
+ ("score_null", None),
+ ("score_str50", "50"),
+ ("score_nan", "NaN"),
+ ]:
+ _create_event(team=cls.team, event=cls.SCORED_EVENT, distinct_id=distinct_id, properties={"score": score})
+ _create_event(team=cls.team, event=cls.SCORED_EVENT, distinct_id="score_missing", properties={})
+ for distinct_id, types in [
+ ("types_empty", []),
+ ("types_match_only", ["ReferenceError"]),
+ ("types_nonmatch_only", ["OtherError"]),
+ ("types_mixed", ["ReferenceError", "OtherError"]),
+ ]:
+ _create_event(
+ team=cls.team,
+ event=cls.EXCEPTION_EVENT,
+ distinct_id=distinct_id,
+ properties={"$exception_types": types},
+ )
+ _create_event(team=cls.team, event=cls.EXCEPTION_EVENT, distinct_id="types_missing", properties={})
+
+ def _kept(self, filter: dict, event: str) -> set[str]:
+ expr = property_to_expr(filter, team=self.team, scope="event")
+ query_ast = ast.SelectQuery(
+ select=[ast.Field(chain=["distinct_id"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["event"]),
+ right=ast.Constant(value=event),
+ ),
+ expr,
+ ]
+ ),
+ )
+ return {row[0] for row in execute_hogql_query(team=self.team, query=query_ast).results}
+
+ @parameterized.expand(
+ [
+ (
+ "event_multi_value_not_icontains",
+ {"type": "event", "key": "plan", "value": ["free", "trial"], "operator": "not_icontains"},
+ {"present_nonmatch", "missing"},
+ ),
+ (
+ "event_not_icontains_multi",
+ {"type": "event", "key": "plan", "value": ["free"], "operator": "not_icontains_multi"},
+ {"present_nonmatch", "missing"},
+ ),
+ (
+ "event_not_between",
+ {"type": "event", "key": "score", "value": [0, 100], "operator": "not_between"},
+ {"present_match", "missing"},
+ ),
+ ("event_is_not_set", {"type": "event", "key": "plan", "operator": "is_not_set"}, {"missing"}),
+ (
+ "person_multi_value_not_icontains_personless",
+ {"type": "person", "key": "email", "value": ["@a.com", "@b.com"], "operator": "not_icontains"},
+ {"present_nonmatch", "present_match", "missing"},
+ ),
+ (
+ "person_is_not_set_personless",
+ {"type": "person", "key": "email", "operator": "is_not_set"},
+ {"present_nonmatch", "present_match", "missing"},
+ ),
+ ]
+ )
+ def test_negative_operator_keeps_row_when_property_is_missing(
+ self, _name: str, filter: dict, expected_kept: set[str]
+ ):
+ assert self._kept(filter, self.EVENT) == expected_kept
+
+ # present_nonmatch holds "enterprise" and present_match holds "free", so each row matches exactly
+ # one of the two values and both must drop. A negative operator that ORs its per-value negations
+ # keeps both instead, because each row fails to match the other value.
+ @parameterized.expand(
+ [
+ ("not_icontains",),
+ ("not_icontains_multi",),
+ ("is_not",),
+ ("not_in",),
+ ("not_regex",),
+ ("not_starts_with",),
+ ("not_ends_with",),
+ ]
+ )
+ def test_multi_value_negative_operator_drops_row_matching_any_value(self, operator: str):
+ filter = {"type": "event", "key": "plan", "value": ["free", "enterprise"], "operator": operator}
+ assert self._kept(filter, self.EVENT) == {"missing"}
+
+ # 256 needles used to build one multiSearchAnyCaseInsensitive call, which ClickHouse rejects
+ # against a nonconstant haystack ("passed 256, should be at most 255"); a constant haystack
+ # folds away before that check runs, so this needs real event data rather than a literal. The
+ # matching needle sits in the second chunk, so a fix that only checked the first chunk would
+ # also fail this.
+ @parameterized.expand(
+ [
+ ("icontains", {"present_match"}),
+ ("icontains_multi", {"present_match"}),
+ ("not_icontains", {"present_nonmatch", "missing"}),
+ ("not_icontains_multi", {"present_nonmatch", "missing"}),
+ ]
+ )
+ def test_multi_value_operator_chunks_needles_past_clickhouse_limit(self, operator: str, expected_kept: set[str]):
+ needles = [f"needle_{i}" for i in range(255)] + ["free"]
+ filter = {"type": "event", "key": "plan", "value": needles, "operator": operator}
+ assert self._kept(filter, self.EVENT) == expected_kept
+
+ # Same inputs and outcomes as test_match_properties_between_operator_uncoercible_values in
+ # rust/feature-flags/src/properties/property_matching.rs. NaN is in neither set: its comparisons
+ # are false and it is not NULL.
+ @parameterized.expand(
+ [
+ ("not_between", {"score_500", "score_missing", "score_abc", "score_null"}),
+ ("between", {"score_50", "score_str50"}),
+ ]
+ )
+ def test_between_operators_treat_uncoercible_value_as_out_of_range(self, operator: str, expected_kept: set[str]):
+ filter = {"type": "event", "key": "score", "value": [0, 100], "operator": operator}
+ assert self._kept(filter, self.SCORED_EVENT) == expected_kept
+
+ @parameterized.expand(
+ [
+ (
+ "not_icontains_multi_value",
+ {"value": ["ReferenceError", "TypeError"], "operator": "not_icontains"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "not_icontains_single_value",
+ {"value": "ReferenceError", "operator": "not_icontains"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "is_not_multi_value",
+ {"value": ["ReferenceError", "TypeError"], "operator": "is_not"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "is_not_single_value",
+ {"value": "ReferenceError", "operator": "is_not"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "not_regex",
+ {"value": "Reference", "operator": "not_regex"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "not_in",
+ {"value": ["ReferenceError", "TypeError"], "operator": "not_in"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "not_icontains_multi",
+ {"value": ["ReferenceError"], "operator": "not_icontains_multi"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ # "TypeError" never appears in the fixture, so this needle alone matches nothing: the
+ # expected set stays identical to the single-needle case above only if the two needles
+ # combine with AND instead of OR.
+ (
+ "not_icontains_multi_two_needles",
+ {"value": ["ReferenceError", "TypeError"], "operator": "not_icontains_multi"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "not_starts_with",
+ {"value": "Reference", "operator": "not_starts_with"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ (
+ "not_ends_with",
+ {"value": "ceError", "operator": "not_ends_with"},
+ ARRAYS_WITHOUT_MATCH,
+ ),
+ ("is_not_set", {"operator": "is_not_set"}, {"types_missing", "types_empty"}),
+ # positive baseline: the mixed row holds a match, so it belongs on this side and only this side
+ (
+ "icontains_multi_value",
+ {"value": ["ReferenceError", "TypeError"], "operator": "icontains"},
+ ARRAYS_WITH_MATCH,
+ ),
+ ]
+ )
+ def test_negative_operator_on_array_property_negates_whole_array(
+ self, _name: str, filter_fields: dict, expected_kept: set[str]
+ ):
+ filter = {"type": "event", "key": "$exception_types", **filter_fields}
+ assert self._kept(filter, self.EXCEPTION_EVENT) == expected_kept
+
+
+@override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=True)
+# $active_feature_flags is a native Array(String) subcolumn on the new events schema, so its negative
+# multi-value filters compile through the arrayExists optimizer rather than a scalar comparison. These
+# execute against ClickHouse to prove the optimized path returns the right rows, not only the right SQL.
+class TestNegativeArrayOperatorNullParityWithData(APIBaseTest):
+ EVENT = "purchase"
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ _create_event(
+ team=cls.team,
+ event=cls.EVENT,
+ distinct_id="has_alpha",
+ properties={"$active_feature_flags": ["alpha", "gamma"]},
+ )
+ _create_event(
+ team=cls.team,
+ event=cls.EVENT,
+ distinct_id="no_alpha",
+ properties={"$active_feature_flags": ["beta", "gamma"]},
+ )
+ _create_event(team=cls.team, event=cls.EVENT, distinct_id="missing", properties={})
+
+ def _count(self, filter: dict) -> int:
+ expr = property_to_expr(filter, team=self.team, scope="event")
+ query_ast = ast.SelectQuery(
+ select=[ast.Call(name="count", args=[])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["event"]),
+ right=ast.Constant(value=self.EVENT),
+ ),
+ expr,
+ ]
+ ),
+ )
+ return execute_hogql_query(team=self.team, query=query_ast).results[0][0]
+
+ @parameterized.expand(
+ [
+ # not_icontains_multi: has_alpha dropped, no_alpha kept, missing kept
+ ("not_icontains_multi", {"value": ["alpha"], "operator": "not_icontains_multi"}, 2),
+ # A needle that spans two array elements once the array is serialized to '["alpha","gamma"]'
+ # matches the JSON text but no single element, so the element-wise scan keeps all three rows.
+ # The de-optimized serialized-text search would find it and drop has_alpha, returning 2.
+ ("not_icontains_multi_json_separator", {"value": ['pha","gam'], "operator": "not_icontains_multi"}, 3),
+ # positive baseline proving the array subcolumn is populated and queryable: only has_alpha matches
+ ("icontains_multi_baseline", {"value": ["alpha"], "operator": "icontains_multi"}, 1),
+ ]
+ )
+ def test_array_operator_row_counts(self, _name: str, filter_fields: dict, expected_count: int):
+ assert self._count({"type": "event", "key": "$active_feature_flags", **filter_fields}) == expected_count
diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.py
index 8537013b8bbd..8b8352634483 100644
--- a/posthog/hogql/transforms/test/test_property_types.py
+++ b/posthog/hogql/transforms/test/test_property_types.py
@@ -36,6 +36,7 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.property import property_to_expr
from posthog.hogql.property_access_types import RestrictedProperty
from posthog.hogql.property_planner import (
PropertyComparisonPlan,
@@ -167,6 +168,35 @@ class TestNewEventsSchemaArraySubcolumns(SimpleTestCase):
assert "toString(events.properties.`$active_feature_flags`)" not in printed, printed
assert "JSONHas(events.properties" not in printed, printed
+ @override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=True)
+ def test_negative_multi_icontains_array_property_stays_optimized(self) -> None:
+ where = property_to_expr(
+ {
+ "type": "event",
+ "key": "$active_feature_flags",
+ "value": ["alpha", "beta"],
+ "operator": "not_icontains_multi",
+ },
+ team=Team(id=1, project_id=1),
+ scope="event",
+ )
+ select = cast(ast.SelectQuery, parse_select("select count() from events"))
+ select.where = where
+ context = self._context()
+ with patch("posthog.hogql.printer.utils.build_property_swapper"):
+ query, _ = prepare_and_print_ast(select, context, "clickhouse")
+ printed = pretty_print_in_tests(query, 1)
+
+ # Wrapping the search call in ifNull hides the bare multiSearchAnyCaseInsensitive call from the
+ # array optimizer, which then falls back to multiSearchAnyCaseInsensitive(toString(…)) over the
+ # array serialized to JSON text instead of an element-wise arrayExists scan.
+ assert "arrayExists" in printed, printed
+ assert "events.properties.`$active_feature_flags`" in printed, printed
+ assert "multiSearchAnyCaseInsensitive(toString(" not in printed, printed
+ # The missing-property branch must resolve to empty(column), not isNull(toJSONString(column)),
+ # or every row pays to serialize the array just to null-check it.
+ assert "toJSONString" not in printed, printed
+
@override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=True)
def test_exception_types_use_array_subcolumn(self) -> None:
printed = self._print_select("select count() from events where properties.$exception_types = 'TypeError'")
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index 727fc4f121e0..c4b82513371c 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -3759,6 +3759,47 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
[session_id_one, session_id_two],
)
+ def test_filter_for_recordings_by_visited_page_negative_operator(self):
+ user = "test_visited_page_negative_filter-user"
+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})
+
+ pricing_only = "pricing only session"
+ produce_replay_summary(
+ distinct_id=user,
+ session_id=pricing_only,
+ team_id=self.team.id,
+ all_urls=["https://example.com/home", "https://example.com/pricing"],
+ )
+ pricing_and_billing = "pricing and billing session"
+ produce_replay_summary(
+ distinct_id=user,
+ session_id=pricing_and_billing,
+ team_id=self.team.id,
+ all_urls=["https://example.com/pricing", "https://example.com/billing"],
+ )
+ no_urls = "no urls session"
+ produce_replay_summary(
+ distinct_id=user,
+ session_id=no_urls,
+ team_id=self.team.id,
+ all_urls=[],
+ )
+
+ # A negative filter applies to the whole recording: one visit to a matching page excludes it,
+ # and a recording with no pages cannot have visited one
+ self._assert_query_matches_session_ids(
+ {
+ "properties": '[{"key": "visited_page", "value": "billing", "operator": "not_icontains", "type": "recording"}]'
+ },
+ [pricing_only, no_urls],
+ )
+ self._assert_query_matches_session_ids(
+ {
+ "properties": '[{"key": "visited_page", "value": "billing", "operator": "icontains", "type": "recording"}]'
+ },
+ [pricing_and_billing],
+ )
+
def test_duration_always_anded_with_visited_page_under_or(self):
user = "test_duration_visited_page-user"
create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})
diff --git a/products/tracing/backend/tests/test_span_attribute_filter.py b/products/tracing/backend/tests/test_span_attribute_filter.py
index e66aa5050557..eff14b7a8f7a 100644
--- a/products/tracing/backend/tests/test_span_attribute_filter.py
+++ b/products/tracing/backend/tests/test_span_attribute_filter.py
@@ -177,10 +177,12 @@ class TestSpanAttributeFilter(ClickhouseTestMixin, APIBaseTest):
{"key": "code.lineno", "type": "span_attribute", "operator": "between", "value": ["50", "60"]},
[],
),
+ # not_between keeps spans missing the attribute: a row without code.lineno is not inside
+ # [0, 41], so negating the range must return it alongside the out-of-range WITH_CODE span.
(
"lineno_not_between_matches",
{"key": "code.lineno", "type": "span_attribute", "operator": "not_between", "value": ["0", "41"]},
- [WITH_CODE],
+ sorted([WITH_CODE, WITHOUT_CODE]),
),
]
)
diff --git a/rust/feature-flags/src/properties/property_matching.rs b/rust/feature-flags/src/properties/property_matching.rs
index 1b5c7084d908..a7cbb929dda5 100644
--- a/rust/feature-flags/src/properties/property_matching.rs
+++ b/rust/feature-flags/src/properties/property_matching.rs
@@ -84,9 +84,8 @@ pub fn to_f64_representation(value: &Value) -> Option<f64> {
}
/// Parses the property value being matched as f64, for the numeric comparison operators
-/// (Gt/Gte/Lt/Lte, Between/NotBetween). A missing or non-numeric value is a validation
-/// error here, distinct from `match_value.is_none()` short-circuiting to `Ok(false)`
-/// earlier in each operator's match arm.
+/// (Gt/Gte/Lt/Lte). A missing or non-numeric value is a validation error here, distinct
+/// from `match_value.is_none()` short-circuiting to `Ok(false)` earlier in that match arm.
fn parse_numeric_match_value(
match_value: Option<&Value>,
key: &str,
@@ -425,12 +424,6 @@ pub fn match_property(
}
}
OperatorType::Between | OperatorType::NotBetween => {
- if match_value.is_none() {
- // When value doesn't exist:
- // - for Between/NotBetween: it's not a match (false)
- return Ok(false);
- }
-
// Mirrors HogQL semantics (posthog/hogql/property.py): between is inclusive
// on both ends, not_between is its complement, and the filter value must be
// a two-element numeric array with min <= max.
@@ -468,7 +461,11 @@ pub fn match_property(
));
}
- let parsed_value = parse_numeric_match_value(match_value, key, operator)?;
+ // A missing, null, or non-numeric value reads as NULL in HogQL, which is not in
+ // range: Between does not match and its complement NotBetween does.
+ let Some(parsed_value) = match_value.and_then(to_f64_representation) else {
+ return Ok(operator == OperatorType::NotBetween);
+ };
if parsed_value.is_nan() {
// "NaN" parses successfully as f64::NAN rather than failing, but a NaN
// property value is malformed input, not a real number: it must be a
@@ -2022,27 +2019,6 @@ mod test_match_properties {
)
.expect("expected match to exist"));
- // Missing person property is not a match, for both between and not_between
- assert!(!match_property(&between, &HashMap::new(), false).expect("expected match to exist"));
- let not_between = PropertyFilter {
- operator: Some(OperatorType::NotBetween),
- ..between.clone()
- };
- assert!(
- !match_property(&not_between, &HashMap::new(), false).expect("expected match to exist")
- );
-
- // Non-numeric person property value is a validation error (like Gt/Lt), which
- // cohort evaluation resolves to a non-match
- assert!(matches!(
- match_property(
- &between,
- &HashMap::from([("key".to_string(), json!("abc"))]),
- true
- ),
- Err(FlagMatchingError::ValidationError(_))
- ));
-
// A filter with no value is not a match
let no_value = PropertyFilter {
value: None,
@@ -2056,6 +2032,45 @@ mod test_match_properties {
.expect("expected match to exist"));
}
+ // Same inputs and outcomes as test_between_operators_treat_uncoercible_value_as_out_of_range in
+ // posthog/hogql/test/test_property.py, where such a value reads as NULL.
+ #[test_case(None, false, true; "absent")]
+ #[test_case(Some(json!(null)), false, true; "explicit null")]
+ #[test_case(Some(json!("abc")), false, true; "malformed")]
+ #[test_case(Some(json!("50")), true, false; "numeric string")]
+ #[test_case(Some(json!("NaN")), false, false; "NaN")]
+ #[test_case(Some(json!(50)), true, false; "in range")]
+ #[test_case(Some(json!(500)), false, true; "out of range")]
+ fn test_match_properties_between_operator_uncoercible_values(
+ property_value: Option<Value>,
+ expected_between: bool,
+ expected_not_between: bool,
+ ) {
+ let between = PropertyFilter {
+ key: "key".to_string(),
+ value: Some(json!([0, 100])),
+ operator: Some(OperatorType::Between),
+ prop_type: PropertyType::Person,
+ ..Default::default()
+ };
+ let not_between = PropertyFilter {
+ operator: Some(OperatorType::NotBetween),
+ ..between.clone()
+ };
+ let props: HashMap<String, Value> = property_value
+ .map(|v| HashMap::from([("key".to_string(), v)]))
+ .unwrap_or_default();
+
+ assert_eq!(
+ match_property(&between, &props, false).expect("expected match to exist"),
+ expected_between
+ );
+ assert_eq!(
+ match_property(&not_between, &props, false).expect("expected match to exist"),
+ expected_not_between
+ );
+ }
+
#[test_case(json!(75000); "not an array")]
#[test_case(json!([70000]); "one element")]
#[test_case(json!([70000, 75000, 80000]); "three elements")]
@@ -2064,26 +2079,27 @@ mod test_match_properties {
#[test_case(json!(["NaN", 80000]); "NaN lower bound")]
#[test_case(json!([70000, "NaN"]); "NaN upper bound")]
fn test_match_properties_between_operator_malformed_filter_value(filter_value: Value) {
+ // A malformed filter is rejected whether or not the entity carries the property, so a
+ // missing property cannot turn a filter HogQL refuses to run into a NotBetween match.
+ let property_maps = [
+ HashMap::from([("key".to_string(), json!(75000))]),
+ HashMap::new(),
+ ];
for operator in [OperatorType::Between, OperatorType::NotBetween] {
let property = PropertyFilter {
key: "key".to_string(),
value: Some(filter_value.clone()),
operator: Some(operator),
prop_type: PropertyType::Person,
- group_type_index: None,
- negation: None,
- compiled_regex: None,
- extra: Default::default(),
+ ..Default::default()
};
- assert!(matches!(
- match_property(
- &property,
- &HashMap::from([("key".to_string(), json!(75000))]),
- true
- ),
- Err(FlagMatchingError::ValidationError(_))
- ));
+ for props in &property_maps {
+ assert!(matches!(
+ match_property(&property, props, false),
+ Err(FlagMatchingError::ValidationError(_))
+ ));
+ }
}
}