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): stop sessions NOT-of-OR filter pruning every row (#69731)

George Munyorocae8e190dc11
diff --git a/posthog/hogql/database/schema/util/test/test_session_where_clause_extractor.py b/posthog/hogql/database/schema/util/test/test_session_where_clause_extractor.py
index fd770d29e62a..20206a2ac232 100644
--- a/posthog/hogql/database/schema/util/test/test_session_where_clause_extractor.py
+++ b/posthog/hogql/database/schema/util/test/test_session_where_clause_extractor.py
@@ -3,6 +3,8 @@ from typing import Any, Optional, Union
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from parameterized import parameterized
+
from posthog.schema import SessionTableVersion
from posthog.hogql import ast
@@ -317,6 +319,69 @@ SELECT
expected = f("raw_sessions.min_timestamp >= ('2024-03-12' - toIntervalDay(3))")
assert expected == actual
+ @parameterized.expand(
+ [
+ # `NOT (a OR b)` as an ast.Not node
+ ("not_node", lambda inner: ast.Not(expr=inner)),
+ # the same thing as a `not(...)` call, which the parser can also emit
+ ("not_call", lambda inner: ast.Call(name="not", args=[inner])),
+ ]
+ )
+ def test_negated_or_chain_fails_safe(self, _name, wrap):
+ # `NOT (host ILIKE 'a' OR host ILIKE 'b')` must not lift `NOT True` = False into the inner
+ # aggregation (which would drop every session). The extractor can't reduce it, so no inner filter.
+ negated_or = wrap(
+ ast.Or(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["host"]),
+ op=ast.CompareOperationOp.ILike,
+ right=ast.Constant(value="localhost:3000"),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=["host"]),
+ op=ast.CompareOperationOp.ILike,
+ right=ast.Constant(value="localhost:3001"),
+ ),
+ ]
+ )
+ )
+ select = ast.SelectQuery(select=[], where=negated_or)
+ assert self.inliner.get_inner_where(select) is None
+
+ def test_negated_or_chain_does_not_poison_timestamp_bound(self):
+ # A liftable timestamp bound alongside a negated OR-chain must still be extracted cleanly — the
+ # NOT branch fails safe to True and is dropped from the AND, rather than adding `NOT True` = False.
+ where = ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["$start_timestamp"]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value="2021-01-01"),
+ ),
+ ast.Not(
+ expr=ast.Or(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["host"]),
+ op=ast.CompareOperationOp.ILike,
+ right=ast.Constant(value="localhost:3000"),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=["host"]),
+ op=ast.CompareOperationOp.ILike,
+ right=ast.Constant(value="localhost:3001"),
+ ),
+ ]
+ )
+ ),
+ ]
+ )
+ select = ast.SelectQuery(select=[], where=where)
+ actual = f(self.inliner.get_inner_where(select))
+ expected = f("raw_sessions.min_timestamp >= ('2021-01-01' - toIntervalDay(3))")
+ assert expected == actual
+
def test_handles_select_set_query_in_comparison(self):
select_set_query = ast.SelectSetQuery(
initial_select_query=ast.SelectQuery(select=[ast.Constant(value="2021-01-01")]),
diff --git a/posthog/hogql/database/schema/util/where_clause_extractor.py b/posthog/hogql/database/schema/util/where_clause_extractor.py
index ca1a22737f02..99b58ef4dabf 100644
--- a/posthog/hogql/database/schema/util/where_clause_extractor.py
+++ b/posthog/hogql/database/schema/util/where_clause_extractor.py
@@ -153,9 +153,19 @@ class WhereClauseExtractor(CloningVisitor):
def visit_not(self, node: ast.Not) -> ast.Expr:
if self.is_join:
return ast.Constant(value=True)
- response = self.visit(node.expr)
+ # Unliftable predicates fail safe to True; negating that (`NOT (a OR b)` -> `NOT True` = False)
+ # would prune every row. Buffered timestamp bounds are over-approximations too, so ignore them
+ # here. Only negate an operand that lifts exactly; otherwise fail safe to True.
+ previous_capture = self.capture_timestamp_comparisons
+ self.capture_timestamp_comparisons = False
+ try:
+ response = self.visit(node.expr)
+ finally:
+ self.capture_timestamp_comparisons = previous_capture
if has_tombstone(response, self.tombstone_string):
return ast.Constant(value=self.tombstone_string)
+ if contains_boolean_constant(response):
+ return ast.Constant(value=True)
return ast.Not(expr=response)
def visit_call(self, node: ast.Call) -> ast.Expr:
@@ -166,6 +176,9 @@ class WhereClauseExtractor(CloningVisitor):
elif node.name == "not":
if self.is_join:
return ast.Constant(value=True)
+ # Route the `not(...)` call form through visit_not for the same guard as the `ast.Not` form.
+ if len(node.args) == 1:
+ return self.visit_not(ast.Not(expr=node.args[0]))
elif node.name in HOGQL_COMPARISON_MAPPING:
op = HOGQL_COMPARISON_MAPPING[node.name]
@@ -715,6 +728,26 @@ class HasTombstoneVisitor(TraversingVisitor):
self.has_tombstone = True
+class _BooleanConstantFinder(TraversingVisitor):
+ """Finds a boolean True/False constant anywhere in an expression - usually the sentinel this extractor
+ substitutes for a predicate it can't lift, marking an over-approximation that must not be negated. A
+ literal `true`/`false` in the query matches too; that's fine, since it only skips the NOT pushdown."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, bool):
+ self.found = True
+
+
+def contains_boolean_constant(expr: ast.Expr) -> bool:
+ finder = _BooleanConstantFinder()
+ finder.visit(expr)
+ return finder.found
+
+
def rewrite_timestamp_field(expr: ast.Expr, timestamp_field: ast.Expr, context: HogQLContext) -> ast.Expr:
return RewriteTimestampFieldVisitor(context, timestamp_field).visit(expr)