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.

feat(hogql): run negated person filters as a persons NOT IN (#114757)

Phil Haackaf343ac2d3ef
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 9a323bf7b68b..7617b9f5ce4f 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -30220,6 +30220,10 @@
"description": "Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap",
"type": "boolean"
},
+ "negatedPersonFiltersNotIn": {
+ "description": "Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.",
+ "type": "boolean"
+ },
"optimizeJoinedFilters": {
"type": "boolean"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index de335d0a4c97..43401134ccc2 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -529,6 +529,8 @@ export interface HogQLQueryModifiers {
sessionPropertyPreAggregation?: boolean
/** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
personIdPushdown?: boolean
+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
+ negatedPersonFiltersNotIn?: boolean
dataWarehouseEventsModifiers?: DataWarehouseEventsModifier[]
debug?: boolean
timings?: boolean
diff --git a/posthog/hogql/database/schema/persons.py b/posthog/hogql/database/schema/persons.py
index 1fb3c766e718..7b99834ba573 100644
--- a/posthog/hogql/database/schema/persons.py
+++ b/posthog/hogql/database/schema/persons.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Optional, Self, cast
+from typing import Optional, Self, cast
import posthoganalytics
@@ -31,9 +31,6 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
from posthog.schema_enums import PersonsArgMaxVersion
-if TYPE_CHECKING:
- from posthog.models.organization import Organization
-
PERSONS_FIELDS: dict[str, FieldOrTable] = {
"id": UUIDDatabaseField(
name="id", nullable=False, description="Stable person identifier; join target for `events.person_id`."
@@ -122,6 +119,8 @@ def select_from_persons_table(
and_conditions.append(filter)
# For now, only do this optimization for directly querying the persons table (without joins or as part of a subquery) to avoid knock-on effects to insight queries
+ # The SELECT id FROM persons that transforms/negated_person_filters.py emits inside NOT IN has persons as its own
+ # FROM, so it takes this path and reads only the persons that fail its filters.
if (
node.select_from
and node.select_from.type
@@ -367,26 +366,17 @@ def build_person_id_pushdown_predicate(join_to_add: LazyJoinToAdd, node: SelectQ
)
-def join_with_persons_table(
- join_to_add: LazyJoinToAdd,
- context: HogQLContext,
- node: SelectQuery,
-):
- from posthog.hogql import ast
-
- if not join_to_add.fields_accessed:
- raise ResolutionError("No fields requested from persons table")
- pushdown = build_person_id_pushdown_predicate(join_to_add, node) if context.modifiers.personIdPushdown else None
- join_expr = ast.JoinExpr(table=select_from_persons_table(join_to_add, context, node, filter=pushdown))
-
- organization: Organization | None = context.team.organization if context.team else None
- if organization is None:
+def persons_join_is_inner(context: HogQLContext) -> bool:
+ """True when the persons join drops each row that has no persons row."""
+ team = context.team
+ if team is None or team.organization is None:
raise ResolutionError("Organization is required to join with persons table")
+ organization = team.organization
# TODO: @raquelmsmith: Remove flag check and use left join for all once deletes are caught up
- use_inner_join = (
+ return bool(
posthoganalytics.feature_enabled(
"personless-events-not-supported",
- str(context.team.uuid),
+ str(team.uuid),
groups={"organization": str(organization.id)},
group_properties={
"organization": {
@@ -397,13 +387,22 @@ def join_with_persons_table(
only_evaluate_locally=True,
send_feature_flag_events=False,
)
- if organization and context.team
- else False
)
- if use_inner_join:
- join_expr.join_type = "INNER JOIN"
- else:
- join_expr.join_type = "LEFT JOIN"
+
+
+def join_with_persons_table(
+ join_to_add: LazyJoinToAdd,
+ context: HogQLContext,
+ node: SelectQuery,
+):
+ from posthog.hogql import ast
+
+ if not join_to_add.fields_accessed:
+ raise ResolutionError("No fields requested from persons table")
+ pushdown = build_person_id_pushdown_predicate(join_to_add, node) if context.modifiers.personIdPushdown else None
+ join_expr = ast.JoinExpr(table=select_from_persons_table(join_to_add, context, node, filter=pushdown))
+
+ join_expr.join_type = "INNER JOIN" if persons_join_is_inner(context) else "LEFT JOIN"
join_expr.alias = join_to_add.to_table
join_expr.constraint = ast.JoinConstraint(
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index be320ebd2788..de97de08b17b 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -39,6 +39,7 @@ from posthog.hogql.transforms.json_property_pushdown import (
from posthog.hogql.transforms.lazy_tables import resolve_lazy_tables
from posthog.hogql.transforms.logical_property_lowering import lower_property_access
from posthog.hogql.transforms.metrics_time_bucket_bounds import add_metrics_time_bucket_bounds
+from posthog.hogql.transforms.negated_person_filters import rewrite_negated_person_filters
from posthog.hogql.transforms.projection_pushdown import pushdown_projections
from posthog.hogql.transforms.property_types import PropertySwapper, build_property_swapper
from posthog.hogql.transforms.type_aware_simplification import (
@@ -278,6 +279,21 @@ def prepare_ast_for_printing(
resolver_factory=resolver_factory,
)
+ # This rewrite needs resolved types to find the persons-join fields. It must run before lazy-table resolution, so
+ # that lazy-table resolution never adds the persons join when the rewrite removes every field that reads it.
+ if dialect == "clickhouse" and context.modifiers.negatedPersonFiltersNotIn:
+ with context.timings.measure("rewrite_negated_person_filters"):
+ rewritten = rewrite_negated_person_filters(node, context)
+ if rewritten is not None:
+ with context.timings.measure("resolve_types_after_negated_person_filters"):
+ node = resolve_types(
+ rewritten,
+ context,
+ dialect=dialect,
+ scopes=[scope.type for scope in stack if scope.type is not None] if stack else None,
+ resolver_factory=resolver_factory,
+ )
+
# Modifier drives the production rollout (per-team override / staged default); the context flag
# remains as the direct opt-in for tests and internal callers.
if context.enable_type_aware_cast_simplification or context.modifiers.typeAwareCastSimplification:
diff --git a/posthog/hogql/transforms/negated_person_filters.py b/posthog/hogql/transforms/negated_person_filters.py
new file mode 100644
index 000000000000..2709d79c1d48
--- /dev/null
+++ b/posthog/hogql/transforms/negated_person_filters.py
@@ -0,0 +1,360 @@
+"""Replace negated person-property filters with an exclusion of the persons that fail them.
+
+On `events`, a filter such as `person.properties.email NOT ILIKE '%@internal.com%'` makes the query LEFT JOIN a subquery
+that reads every person in the team. This transform replaces those filters with
+
+ <person key> NOT IN (SELECT id FROM persons WHERE NOT (<the filters, on persons.properties>))
+
+The persons lazy table runs that subquery in two steps (see `select_from_persons_table`). It first scans a materialized
+column of every person row to find the persons that have a row which fails a filter. It then runs the argMax over only
+those persons. The argMax and the exclusion set follow the number of excluded persons. The scan still grows with the
+team.
+
+Both forms give each row the same verdict. Both judge a person in the persons table by its latest version. A row whose
+person is not in the persons table (no person, a deleted person, a person created in the future) gets NULL properties
+from the join. Every filter shape that this transform accepts is true for NULL, so the join keeps that row, and the
+exclusion does not contain its person.
+
+The forms differ when a person has two unmerged rows at its latest version. The join returns both rows, so it counts
+the event once for each row that passes the filters. The exclusion judges the person by one of the two rows and counts
+the event once or not at all.
+"""
+
+import dataclasses
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, TypeGuard, cast
+
+from posthog.hogql import ast
+from posthog.hogql.base import _T_AST
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.lazy_join_tags import PERSONS
+from posthog.hogql.database.schema.events import EventsTable
+from posthog.hogql.database.schema.persons import persons_join_is_inner
+from posthog.hogql.database.schema.util.where_clause_extractor import top_level_conjuncts
+from posthog.hogql.resolver_utils import get_long_table_name
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
+
+from posthog.dataclasses import frozen
+from posthog.schema_enums import MaterializationMode
+
+if TYPE_CHECKING:
+ from posthog.clickhouse.materialized_column_types import MaterializedColumn
+ from posthog.property_columns import PropertyName, TableColumn
+
+_MaterializedColumns = Mapping[tuple["PropertyName", "TableColumn"], "MaterializedColumn"]
+
+# With a non-NULL constant on one side, the printer makes each of these true when the property is NULL.
+_NEGATED_COMPARISONS = frozenset(
+ {
+ ast.CompareOperationOp.NotEq,
+ ast.CompareOperationOp.NotLike,
+ ast.CompareOperationOp.NotILike,
+ ast.CompareOperationOp.NotRegex,
+ ast.CompareOperationOp.NotIRegex,
+ ast.CompareOperationOp.NotIn,
+ }
+)
+
+
+def rewrite_negated_person_filters(node: _T_AST, context: HogQLContext) -> _T_AST | None:
+ """Returns None when no SELECT qualifies. Otherwise it emits untyped nodes. The caller runs type resolution again."""
+ # This mode reads the properties JSON instead of materialized columns. See `_all_materialized` for why that costs
+ # more than the join.
+ if context.modifiers.materializationMode == MaterializationMode.DISABLED:
+ return None
+ # Without a team, persons_join_is_inner cannot decide. The persons join loads the team later, so leave it in place.
+ if context.team is None:
+ return None
+ planner = _Planner()
+ planner.visit(node)
+ if planner.blocks_rewrite or not planner.rewrites:
+ return None
+ columns = _materialized_person_columns()
+ rewrites = {
+ key: rewrite for key, rewrite in planner.rewrites.items() if _all_materialized(rewrite.properties, columns)
+ }
+ # An INNER JOIN drops the rows that have no persons row. The exclusion would keep them.
+ if not rewrites or persons_join_is_inner(context):
+ return None
+ return cast(_T_AST, _Rewriter(rewrites).visit(node))
+
+
+@frozen
+class _Rewrite:
+ kept: list[ast.Expr]
+ exclusion: ast.Expr
+ properties: list[list[str | int]]
+
+
+def _plan(node: ast.SelectQuery) -> _Rewrite | None:
+ select_from = node.select_from
+ if (
+ node.where is None
+ or not isinstance(node.type, ast.SelectQueryType)
+ or select_from is None
+ or not _is_events(select_from.type)
+ ):
+ return None
+
+ join: ast.LazyJoinType | None = None
+ path: list[str] | None = None
+ excluded: list[ast.Expr] = []
+ kept: list[ast.Expr] = []
+ for conjunct in top_level_conjuncts(node.where):
+ conjunct_join = _join_when_true_for_null(conjunct)
+ if conjunct_join is not None:
+ root, conjunct_path = _root_and_path(conjunct_join)
+ if root is select_from.type and path in (None, conjunct_path):
+ join, path = conjunct_join, conjunct_path
+ excluded.append(conjunct)
+ continue
+ kept.append(conjunct)
+ if join is None or path is None:
+ return None
+
+ reader = _PersonsJoinReader(select_from.type, skip=excluded)
+ reader.visit(node)
+ if reader.found:
+ return None
+
+ # The resolver looks up a SELECT alias before a bare field, so the key names its table.
+ person_key = [get_long_table_name(node.type, select_from.type), *path[:-1], *join.lazy_join.from_field]
+ rebinder = _PersonsPropertyRebinder()
+ filters = [rebinder.visit(conjunct) for conjunct in excluded]
+ return _Rewrite(kept=kept, exclusion=_exclusion(person_key, filters), properties=rebinder.properties)
+
+
+def _materialized_person_columns() -> _MaterializedColumns:
+ # Deferred: the registry is a Django-side lookup, and the printer package must import without Django.
+ from posthog.clickhouse.materialized_columns import get_enabled_materialized_columns_by_table # noqa: PLC0415
+
+ return get_enabled_materialized_columns_by_table().get("person", {})
+
+
+def _all_materialized(properties: list[list[str | int]], columns: _MaterializedColumns) -> bool:
+ """True when each person property has a materialized column.
+
+ The persons subquery finds its candidates in every row of every person, across all versions. For a property without a
+ materialized column, it reads the whole properties JSON of each row. That costs more than the join, which reads
+ properties only for the latest row of each person.
+ """
+ return all(
+ len(chain) == 1 and _is_string_column(columns.get((str(chain[0]), "properties"))) for chain in properties
+ )
+
+
+def _is_string_column(column: "MaterializedColumn | None") -> bool:
+ # An unmatched LEFT JOIN fills a typed column, such as Float64, with its default instead of NULL. The filter can
+ # then drop a row with no person, which the exclusion keeps.
+ return column is not None and column.type in ("String", "Nullable(String)")
+
+
+def _is_events(table_type: ast.Type | None) -> TypeGuard[ast.TableType | ast.TableAliasType]:
+ if isinstance(table_type, ast.TableAliasType):
+ table_type = table_type.table_type
+ return isinstance(table_type, ast.TableType) and isinstance(table_type.table, EventsTable)
+
+
+def _exclusion(person_key: list[str | int], filters: list[ast.Expr]) -> ast.Expr:
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.NotIn,
+ left=ast.Field(chain=person_key),
+ right=ast.SelectQuery(
+ select=[ast.Field(chain=["id"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),
+ where=ast.Not(expr=_and(filters)),
+ ),
+ )
+
+
+def _and(exprs: list[ast.Expr]) -> ast.Expr:
+ return exprs[0] if len(exprs) == 1 else ast.And(exprs=exprs)
+
+
+def _join_when_true_for_null(expr: ast.Expr) -> ast.LazyJoinType | None:
+ """The persons join that `expr` filters, when `expr` has a shape that property_to_expr builds for a negated operator."""
+ match expr:
+ case ast.CompareOperation(op=op, left=left, right=right) if op in _NEGATED_COMPARISONS and _is_literal(right):
+ return _persons_join(left)
+ case ast.Not(expr=negated):
+ return _join_when_false_for_null(negated)
+ # not_regex builds ifNull(not(match(toString(property), pattern)), 1).
+ case ast.Call(
+ name="ifNull",
+ args=[ast.Call(name="not", args=[ast.Call(name="match", args=[searched, pattern])]), fallback],
+ ) if _is_int(fallback, 1) and _is_literal(pattern):
+ return _persons_join(searched)
+ return None
+
+
+def _join_when_false_for_null(expr: ast.Expr) -> ast.LazyJoinType | None:
+ match expr:
+ # A multi-value not_icontains negates multiSearchAnyCaseInsensitive(...) > 0. It has one OR term per chunk of
+ # needles.
+ case ast.Or(exprs=terms):
+ joins = [_join_when_false_for_null(term) for term in terms]
+ first = joins[0]
+ if first is None or any(join is None or not _same_join(first, join) for join in joins):
+ return None
+ return first
+ case ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Call(name="multiSearchAnyCaseInsensitive", args=[searched, needles]),
+ right=zero,
+ ) if _is_int(zero, 0) and _is_literal(needles):
+ return _persons_join(searched)
+ return None
+
+
+def _persons_join(expr: ast.Expr) -> ast.LazyJoinType | None:
+ """The persons join that `expr` reads, when `expr` is `person.properties.<key>`, alone or inside toString()."""
+ if isinstance(expr, ast.Call) and expr.name == "toString" and len(expr.args) == 1:
+ expr = expr.args[0]
+ if isinstance(expr, ast.Alias) and expr.hidden:
+ expr = expr.expr
+ if not isinstance(expr, ast.Field) or not isinstance(expr.type, ast.PropertyType):
+ return None
+ field_type = expr.type.field_type
+ join = field_type.table_type
+ if field_type.name != "properties" or not isinstance(join, ast.LazyJoinType) or join.lazy_join.resolver != PERSONS:
+ return None
+ return join
+
+
+def _is_literal(expr: ast.Expr) -> bool:
+ # WhereClauseExtractor.visit_not reads any bool constant as its marker for a filter that it cannot lift. Then
+ # get_inner_where returns None. select_from_persons_table then skips its where_optimization subquery, so the persons
+ # subquery reads every person in the team.
+ if isinstance(expr, ast.Constant):
+ return _is_literal_value(expr.value)
+ if isinstance(expr, ast.Tuple | ast.Array):
+ return bool(expr.exprs) and all(_is_literal(item) for item in expr.exprs)
+ return False
+
+
+def _is_literal_value(value: object) -> bool:
+ if isinstance(value, list | tuple):
+ return bool(value) and all(_is_literal_value(item) for item in value)
+ return value is not None and not isinstance(value, bool)
+
+
+def _is_int(expr: ast.Expr, value: int) -> bool:
+ return isinstance(expr, ast.Constant) and type(expr.value) is int and expr.value == value
+
+
+def _root_and_path(join: ast.LazyJoinType) -> tuple[ast.Type, list[str]]:
+ """The table that `join` hangs off, and the lazy-join fields from it to `join`, such as ["pdi", "person"]."""
+ path: list[str] = []
+ table_type: ast.Type = join
+ while isinstance(table_type, ast.LazyJoinType):
+ path.insert(0, table_type.field)
+ table_type = table_type.table_type
+ return table_type, path
+
+
+def _same_join(left: ast.LazyJoinType, right: ast.LazyJoinType) -> bool:
+ left_root, left_path = _root_and_path(left)
+ right_root, right_path = _root_and_path(right)
+ return left_root is right_root and left_path == right_path
+
+
+def _reads_persons_join(field_type: ast.Type | None, root: ast.Type) -> bool:
+ current = field_type
+ while current is not None:
+ if isinstance(current, ast.LazyJoinType):
+ if current.lazy_join.resolver == PERSONS and _root_and_path(current)[0] is root:
+ return True
+ current = current.table_type
+ elif isinstance(current, ast.PropertyType):
+ current = current.field_type
+ elif isinstance(current, ast.FieldAliasType):
+ current = current.type
+ elif isinstance(current, ast.FieldType | ast.AsteriskType | ast.VirtualTableType):
+ current = current.table_type
+ else:
+ return False
+ return False
+
+
+class _PersonsJoinReader(TraversingVisitor):
+ """Finds a field of one SELECT, outside the filters in `skip`, that reads a persons join off `root`."""
+
+ def __init__(self, root: ast.Type, skip: list[ast.Expr]) -> None:
+ super().__init__()
+ self.root = root
+ self.skip = {id(expr) for expr in skip}
+ self.found = False
+ self.entered = False
+
+ def visit(self, node: ast.AST | None) -> None:
+ if not self.found and node is not None and id(node) not in self.skip:
+ super().visit(node)
+
+ # A nested SELECT resolves its fields in its own scope, so its fields cannot read this SELECT's joins.
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ if not self.entered:
+ self.entered = True
+ super().visit_select_query(node)
+
+ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:
+ pass
+
+ def visit_field(self, node: ast.Field) -> None:
+ if _reads_persons_join(node.type, self.root):
+ self.found = True
+
+
+class _PersonsPropertyRebinder(CloningVisitor):
+ """Clones a filter on `person.properties.<key>` into the same filter on `properties.<key>` of `persons`."""
+
+ def __init__(self) -> None:
+ super().__init__(clear_types=True, clear_locations=True)
+ self.properties: list[list[str | int]] = []
+
+ def visit_alias(self, node: ast.Alias) -> ast.Expr:
+ if node.hidden:
+ return self.visit(node.expr)
+ return super().visit_alias(node)
+
+ def visit_field(self, node: ast.Field) -> ast.Expr:
+ if isinstance(node.type, ast.PropertyType):
+ self.properties.append(node.type.chain)
+ return ast.Field(chain=["properties", *node.type.chain])
+ return super().visit_field(node)
+
+
+class _Planner(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.rewrites: dict[int, _Rewrite] = {}
+ self.blocks_rewrite = False
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ # The exclusion reads `FROM persons`. A CTE with that name would replace the persons table in it.
+ if node.ctes and "persons" in node.ctes:
+ self.blocks_rewrite = True
+ # The caller resolves the whole tree again. That drops the isolated scope of expanded expression fields such as
+ # `events.person_id`, so their unqualified inner fields become ambiguous in a SELECT that joins two tables.
+ if node.select_from is not None and node.select_from.next_join is not None:
+ self.blocks_rewrite = True
+ rewrite = _plan(node)
+ if rewrite is not None:
+ self.rewrites[id(node)] = rewrite
+ super().visit_select_query(node)
+
+ def visit_field(self, node: ast.Field) -> None:
+ pass
+
+
+class _Rewriter(CloningVisitor):
+ def __init__(self, rewrites: dict[int, _Rewrite]) -> None:
+ super().__init__(clear_types=True)
+ self.rewrites = rewrites
+
+ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:
+ rewrite = self.rewrites.get(id(node))
+ if rewrite is None:
+ return super().visit_select_query(node)
+ query = super().visit_select_query(dataclasses.replace(node, where=None))
+ query.where = _and([*(self.visit(conjunct) for conjunct in rewrite.kept), rewrite.exclusion])
+ return query
diff --git a/posthog/hogql/transforms/test/__snapshots__/test_negated_person_filters.ambr b/posthog/hogql/transforms/test/__snapshots__/test_negated_person_filters.ambr
new file mode 100644
index 000000000000..088246534394
--- /dev/null
+++ b/posthog/hogql/transforms/test/__snapshots__/test_negated_person_filters.ambr
@@ -0,0 +1,27 @@
+# serializer version: 1
+# name: TestNegatedPersonFiltersPrinting.test_rewrite_reads_only_persons_that_ever_matched
+ '''
+ SELECT events.event AS event
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), notIn(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(nullIf(nullIf(person.pmat_email, ''), 'null')), person.version), 1) AS properties___email, person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), not(and(notILike(where_optimization.pmat_email, %(hogql_val_0)s), notILike(where_optimization.pmat_email, %(hogql_val_1)s)))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, %(hogql_val_2)s), person.version), plus(now64(6, %(hogql_val_3)s), toIntervalDay(1))))) AS persons
+ WHERE not(and(ifNull(notILike(toString(persons.properties___email), %(hogql_val_4)s), 1), ifNull(notILike(toString(persons.properties___email), %(hogql_val_5)s), 1))))))
+ LIMIT 50000
+ '''
+# ---
diff --git a/posthog/hogql/transforms/test/__snapshots__/test_negated_person_filters.new_events_schema.ambr b/posthog/hogql/transforms/test/__snapshots__/test_negated_person_filters.new_events_schema.ambr
new file mode 100644
index 000000000000..eee43805c8e8
--- /dev/null
+++ b/posthog/hogql/transforms/test/__snapshots__/test_negated_person_filters.new_events_schema.ambr
@@ -0,0 +1,27 @@
+# serializer version: 1
+# name: TestNegatedPersonFiltersPrinting.test_rewrite_reads_only_persons_that_ever_matched[new_events_schema]
+ '''
+ SELECT events.event AS event
+ FROM events_json AS events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), notIn(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),
+ (SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(nullIf(nullIf(person.pmat_email, ''), 'null')), person.version), 1) AS properties___email, person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), not(and(notILike(where_optimization.pmat_email, %(hogql_val_0)s), notILike(where_optimization.pmat_email, %(hogql_val_1)s)))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, %(hogql_val_2)s), person.version), plus(now64(6, %(hogql_val_3)s), toIntervalDay(1))))) AS persons
+ WHERE not(and(ifNull(notILike(toString(persons.properties___email), %(hogql_val_4)s), 1), ifNull(notILike(toString(persons.properties___email), %(hogql_val_5)s), 1))))))
+ LIMIT 50000
+ '''
+# ---
diff --git a/posthog/hogql/transforms/test/test_negated_person_filters.py b/posthog/hogql/transforms/test/test_negated_person_filters.py
new file mode 100644
index 000000000000..9070d78ab7a7
--- /dev/null
+++ b/posthog/hogql/transforms/test/test_negated_person_filters.py
@@ -0,0 +1,289 @@
+import re
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import (
+ APIBaseTest,
+ ClickhouseTestMixin,
+ QueryMatchingTest,
+ _create_event,
+ _create_person,
+ create_person_id_override_by_distinct_id,
+ flush_persons_and_events,
+ materialized,
+)
+from unittest.mock import patch
+
+from parameterized import param, parameterized
+
+from posthog.schema import HogQLQueryModifiers, MaterializationMode, PersonsOnEventsMode
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+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.query import execute_hogql_query
+
+from posthog.models import PropertyDefinition
+from posthog.models.person.util import create_person
+
+from products.event_definitions.backend.models.property_definition import PropertyType
+
+from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
+
+JOINED = PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED
+
+INTERNAL = {"key": "email", "type": "person", "operator": "not_icontains", "value": "@internal.example"}
+EXAMPLE = {"key": "email", "type": "person", "operator": "not_icontains", "value": "@example.com"}
+
+INTERNAL_PERSONS = {"internal", "changed_to_internal", "merged"}
+INTERNAL_OR_EXAMPLE_PERSONS = INTERNAL_PERSONS | {"external", "changed_to_external"}
+
+PERSONS_JOIN = re.compile(r"AS \w+__person ON")
+
+MATERIALIZED_PERSON_COLUMNS = {
+ "person": {
+ (name, "properties"): MaterializedColumn(
+ name=f"pmat_{name}",
+ details=MaterializedColumnDetails(table_column="properties", property_name=name, is_disabled=False),
+ is_nullable=False,
+ column_type=column_type,
+ )
+ for name, column_type in (("email", None), ("is_staff", None), ("score", "Float64"))
+ }
+}
+
+
+class TestNegatedPersonFiltersResults(ClickhouseTestMixin, APIBaseTest):
+ EVENTS = {
+ "internal",
+ "external",
+ "personless",
+ "deleted_internal",
+ "changed_to_external",
+ "changed_to_internal",
+ "cleared_email",
+ "null_email",
+ "no_email",
+ "future_internal",
+ "merged",
+ }
+
+ def setUp(self):
+ super().setUp()
+ self.enterContext(materialized("person", "email"))
+ timestamp = datetime(2024, 1, 2, 12)
+
+ def person(distinct_id: str, properties: dict):
+ created = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], properties=properties)
+ _create_event(event=distinct_id, distinct_id=distinct_id, team=self.team, timestamp=timestamp)
+ return created
+
+ person("internal", {"email": "[email protected]"})
+ person("external", {"email": "[email protected]"})
+ _create_event(event="personless", distinct_id="personless", team=self.team, timestamp=timestamp)
+ deleted = person("deleted_internal", {"email": "[email protected]"})
+ to_external = person("changed_to_external", {"email": "[email protected]"})
+ to_internal = person("changed_to_internal", {"email": "[email protected]"})
+ cleared = person("cleared_email", {"email": "[email protected]"})
+ person("null_email", {"email": "null"})
+ person("no_email", {})
+ future = person("future_internal", {"email": "[email protected]"})
+ person("merged", {"email": "[email protected]"})
+ flush_persons_and_events()
+
+ in_a_month = datetime.now(UTC) + timedelta(days=30)
+ for later, email, is_deleted, created_at in [
+ (deleted, "[email protected]", True, None),
+ (to_external, "[email protected]", False, None),
+ (to_internal, "[email protected]", False, None),
+ (cleared, "", False, None),
+ (future, "[email protected]", False, in_a_month),
+ ]:
+ create_person(
+ team_id=self.team.pk,
+ uuid=str(later.uuid),
+ properties={"email": email},
+ version=1,
+ is_deleted=is_deleted,
+ created_at=created_at,
+ )
+ create_person_id_override_by_distinct_id("merged", "internal", self.team.pk)
+
+ def _run(self, select: str, filters: list[dict], mode: PersonsOnEventsMode, rewrite: bool) -> tuple[set[str], str]:
+ response = execute_hogql_query(
+ parse_select(f"{select} WHERE {{where}}"),
+ self.team,
+ placeholders={"where": property_to_expr(filters, self.team)},
+ modifiers=HogQLQueryModifiers(personsOnEventsMode=mode, negatedPersonFiltersNotIn=rewrite),
+ )
+ assert response.clickhouse is not None
+ return {row[0] for row in response.results}, response.clickhouse
+
+ @parameterized.expand(
+ [
+ param("not_icontains", [INTERNAL], INTERNAL_PERSONS),
+ param(
+ "not_icontains_multi", [{**INTERNAL, "value": ["@internal.example", "@corp.example"]}], INTERNAL_PERSONS
+ ),
+ param(
+ "not_icontains_past_needle_limit",
+ [{**INTERNAL, "value": ["@internal.example", *(f"@unused-{i}.example" for i in range(255))]}],
+ INTERNAL_PERSONS,
+ ),
+ param(
+ "is_not",
+ [{**INTERNAL, "operator": "is_not", "value": "[email protected]"}],
+ {"internal", "merged"},
+ ),
+ param(
+ "is_not_multi",
+ [{**INTERNAL, "operator": "is_not", "value": ["[email protected]", "[email protected]"]}],
+ INTERNAL_PERSONS,
+ ),
+ param(
+ "not_regex", [{**INTERNAL, "operator": "not_regex", "value": "@internal\\.example$"}], INTERNAL_PERSONS
+ ),
+ param("two_filters", [INTERNAL, EXAMPLE], INTERNAL_OR_EXAMPLE_PERSONS),
+ param(
+ "select_alias_named_person_id",
+ [INTERNAL],
+ INTERNAL_PERSONS,
+ select="SELECT event, distinct_id AS person_id FROM events",
+ ),
+ # DISABLED mode reads person_id through an INNER JOIN on person_distinct_id2. That join drops the
+ # personless event and ignores the override.
+ param(
+ "disabled_mode",
+ [INTERNAL],
+ {"internal", "changed_to_internal", "personless"},
+ mode=PersonsOnEventsMode.DISABLED,
+ ),
+ ]
+ )
+ def test_rewrite_returns_the_rows_the_join_returns(
+ self,
+ _name: str,
+ filters: list[dict],
+ excluded: set[str],
+ mode: PersonsOnEventsMode = JOINED,
+ select: str = "SELECT event FROM events",
+ ):
+ joined, joined_sql = self._run(select, filters, mode, rewrite=False)
+ rewritten, rewritten_sql = self._run(select, filters, mode, rewrite=True)
+
+ assert joined == self.EVENTS - excluded
+ assert rewritten == joined
+ assert PERSONS_JOIN.search(joined_sql)
+ assert not PERSONS_JOIN.search(rewritten_sql)
+ assert "where_optimization" in rewritten_sql
+
+
+class TestNegatedPersonFiltersPrinting(QueryMatchingTest, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.enterContext(
+ patch(
+ "posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table",
+ return_value=MATERIALIZED_PERSON_COLUMNS,
+ )
+ )
+ PropertyDefinition.objects.create(
+ team=self.team, name="is_staff", type=PropertyDefinition.Type.PERSON, property_type=PropertyType.Boolean
+ )
+
+ def _print(
+ self,
+ query: str,
+ placeholders: dict[str, ast.Expr] | None = None,
+ *,
+ mode: PersonsOnEventsMode = JOINED,
+ materialization_mode: MaterializationMode | None = None,
+ team_on_context: bool = True,
+ ) -> str:
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team if team_on_context else None,
+ enable_select_queries=True,
+ modifiers=create_default_modifiers_for_team(
+ self.team,
+ HogQLQueryModifiers(
+ personsOnEventsMode=mode,
+ materializationMode=materialization_mode,
+ negatedPersonFiltersNotIn=True,
+ ),
+ ),
+ )
+ sql, _ = prepare_and_print_ast(parse_select(query, placeholders=placeholders), context, dialect="clickhouse")
+ return sql
+
+ def test_rewrite_reads_only_persons_that_ever_matched(self):
+ sql = self._print(
+ "SELECT event FROM events WHERE {where}", {"where": property_to_expr([INTERNAL, EXAMPLE], self.team)}
+ )
+
+ assert not PERSONS_JOIN.search(sql)
+ assert "where_optimization" in sql
+ self.assertQueryMatchesSnapshot(sql)
+
+ @parameterized.expand(
+ [
+ param("positive_filter_alongside", [INTERNAL, {"key": "email", "type": "person", "operator": "is_set"}]),
+ param("person_field_selected", [INTERNAL], select="SELECT event, person.properties.name FROM events"),
+ param("boolean_property", [{"key": "is_staff", "type": "person", "operator": "is_not", "value": "true"}]),
+ param("join_drops_rows_without_a_person", [INTERNAL], inner_join=True),
+ param("properties_on_events", [INTERNAL], mode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS),
+ param("not_events", [INTERNAL], select="SELECT distinct_id FROM person_distinct_ids"),
+ param("property_not_materialized", [{**INTERNAL, "key": "$email"}]),
+ param("persons_cte", [INTERNAL], select="WITH persons AS (SELECT 1 AS id) SELECT event FROM events"),
+ param("materialization_disabled", [INTERNAL], materialization_mode=MaterializationMode.DISABLED),
+ param(
+ "typed_materialized_column", [{"key": "score", "type": "person", "operator": "is_not", "value": "0"}]
+ ),
+ param("team_id_only", [INTERNAL], team_on_context=False),
+ ]
+ )
+ def test_keeps_the_join_when_the_rewrite_would_not_drop_it(
+ self,
+ _name: str,
+ filters: list[dict],
+ select: str = "SELECT event FROM events",
+ mode: PersonsOnEventsMode = JOINED,
+ inner_join: bool = False,
+ materialization_mode: MaterializationMode | None = None,
+ team_on_context: bool = True,
+ ):
+ with patch("posthog.hogql.database.schema.persons.posthoganalytics.feature_enabled", return_value=inner_join):
+ sql = self._print(
+ f"{select} WHERE {{where}}",
+ {"where": property_to_expr(filters, self.team)},
+ mode=mode,
+ materialization_mode=materialization_mode,
+ team_on_context=team_on_context,
+ )
+
+ assert "where_optimization" not in sql
+ assert bool(PERSONS_JOIN.search(sql)) == (mode == JOINED)
+
+ @parameterized.expand(
+ [
+ param(
+ "self_join",
+ "SELECT e.event FROM events e JOIN events f ON e.uuid = f.uuid"
+ " WHERE e.person.properties.email != '[email protected]'",
+ ),
+ param(
+ "null_in_constant_list",
+ "SELECT event FROM events WHERE person.properties.email NOT IN {excluded}",
+ {"excluded": ast.Constant(value=[None, "[email protected]"])},
+ ),
+ ]
+ )
+ def test_keeps_the_join_for_hogql_the_rewrite_would_change(
+ self, _name: str, query: str, placeholders: dict[str, ast.Expr] | None = None
+ ):
+ sql = self._print(query, placeholders)
+
+ assert "where_optimization" not in sql
+ assert PERSONS_JOIN.search(sql)
diff --git a/posthog/schema.py b/posthog/schema.py
index ce89b0ef3e29..8a828089eb4f 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -6234,6 +6234,17 @@ class HogQLQueryModifiers(BaseModel):
" one UNION ALL join, so their scans overlap"
),
)
+ negatedPersonFiltersNotIn: bool | None = Field(
+ default=None,
+ description=(
+ "Replace negated person-property filters in the WHERE of an `events` query"
+ " (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM"
+ " persons WHERE <the filters fail>)`, so the query no longer joins every"
+ " person. Applies only when every filtered person property has a"
+ " materialized column, nothing else in the query reads that persons join,"
+ " and the join would be a LEFT JOIN."
+ ),
+ )
optimizeJoinedFilters: bool | None = None
optimizeProjections: bool | None = None
parserMode: ParserMode | None = Field(
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index cc488b17dd13..ec6b1a2dea90 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -835,6 +835,8 @@ export interface HogQLQueryModifiersApi {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
/** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
mergeFederatedAggregateJoins?: boolean | null
+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
+ negatedPersonFiltersNotIn?: boolean | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.ts
index 0f0c3c0c68f0..9be37aeec211 100644
--- a/products/batch_exports/frontend/generated/api.zod.ts
+++ b/products/batch_exports/frontend/generated/api.zod.ts
@@ -592,6 +592,12 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -1543,6 +1549,12 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -2253,6 +2265,12 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -2948,6 +2966,12 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -3662,6 +3686,12 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -4093,6 +4123,12 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -4347,6 +4383,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = /* @__PURE__ */ zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 79db238d26f3..4a62b65584ae 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1765,6 +1765,8 @@ export interface HogQLQueryModifiersApi {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
/** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
mergeFederatedAggregateJoins?: boolean | null
+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
+ negatedPersonFiltersNotIn?: boolean | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 158369961f6f..df98481466ea 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1785,6 +1785,8 @@ export interface HogQLQueryModifiersApi {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
/** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
mergeFederatedAggregateJoins?: boolean | null
+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
+ negatedPersonFiltersNotIn?: boolean | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 3abb8c1f949e..38bb5892fdbc 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -210,6 +210,7 @@ export namespace Schemas {
materializationMode: MaterializationMode | null;
materializedColumnsOptimizationMode: MaterializedColumnsOptimizationMode | null;
mergeFederatedAggregateJoins: boolean | null;
+ negatedPersonFiltersNotIn: boolean | null;
optimizeJoinedFilters: boolean | null;
optimizeProjections: boolean | null;
parserMode: ParserMode | null;
diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.ts
index 5f0eed07b956..ec5e671422b7 100644
--- a/products/marketing_analytics/frontend/generated/api.schemas.ts
+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts
@@ -1622,6 +1622,8 @@ export interface HogQLQueryModifiersApi {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
/** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
mergeFederatedAggregateJoins?: boolean | null
+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
+ negatedPersonFiltersNotIn?: boolean | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
index be8a119c4889..2937a0868ac9 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
@@ -15,6 +15,7 @@ from posthog.test.base import (
_create_person,
also_test_with_materialized_columns,
flush_persons_and_events,
+ materialized,
)
from unittest.mock import MagicMock, patch
@@ -50,6 +51,7 @@ from posthog.schema import (
MetricSummary,
MultipleBreakdownType,
PersonPropertyFilter,
+ PersonsOnEventsMode,
PropertyMathType,
PropertyOperator,
Series as InsightActorsQuerySeries,
@@ -3237,6 +3239,45 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results[0]["data"] == [1]
+ def test_person_test_account_filters_return_the_same_series_without_the_persons_join(self):
+ self.enterContext(materialized("person", "email"))
+ for distinct_id, properties in [
+ ("internal", {"email": "[email protected]"}),
+ ("external", {"email": "[email protected]"}),
+ ("no_email", {}),
+ ]:
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], properties=properties)
+ _create_event(team=self.team, event="$pageview", distinct_id=distinct_id, timestamp="2020-01-11T12:00:00Z")
+ _create_event(team=self.team, event="$pageview", distinct_id="personless", timestamp="2020-01-11T12:00:00Z")
+ flush_persons_and_events()
+ self.team.test_account_filters = [
+ {"key": "email", "type": "person", "operator": "not_icontains", "value": "@internal.example"}
+ ]
+ self.team.save()
+
+ def run(rewrite: bool) -> tuple[list[int], list[str]]:
+ with self.capture_select_queries() as queries:
+ response = self._run_trends_query(
+ date_from="2020-01-11T00:00:00Z",
+ date_to="2020-01-11T23:59:59Z",
+ interval=IntervalType.DAY,
+ series=[EventsNode(event="$pageview")],
+ filter_test_accounts=True,
+ hogql_modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,
+ negatedPersonFiltersNotIn=rewrite,
+ ),
+ )
+ return response.results[0]["data"], queries
+
+ joined, _ = run(rewrite=False)
+ rewritten, queries = run(rewrite=True)
+
+ assert joined == [3]
+ assert rewritten == joined
+ assert any("where_optimization" in query for query in queries)
+ assert not any(re.search(r"AS \w+__person ON", query) for query in queries)
+
def test_smoothing(self):
self._create_test_events()
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 9be4f7d00a1a..132f679e9bfc 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -649,6 +649,8 @@ export interface HogQLQueryModifiersApi {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
/** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
mergeFederatedAggregateJoins?: boolean | null
+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
+ negatedPersonFiltersNotIn?: boolean | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f9b19a6253cb..911bb5f8c311 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2665,6 +2665,8 @@ export namespace Schemas {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationMode | null;
/** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
mergeFederatedAggregateJoins?: boolean | null;
+ /** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
+ negatedPersonFiltersNotIn?: boolean | null;
optimizeJoinedFilters?: boolean | null;
optimizeProjections?: boolean | null;
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.ts
index a7ad300e0e3c..62c7fd42d075 100644
--- a/services/mcp/src/generated/batch_exports/api.ts
+++ b/services/mcp/src/generated/batch_exports/api.ts
@@ -604,6 +604,12 @@ export const BatchExportsCreateBody = () => zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -1318,6 +1324,12 @@ export const BatchExportsPartialUpdateBody = () => zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -1763,6 +1775,12 @@ export const FileDownloadBatchExportsCreateBody = () => zod.union([
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
@@ -2053,6 +2071,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = () => zod
.describe(
'Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap'
),
+ negatedPersonFiltersNotIn: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN.'
+ ),
optimizeJoinedFilters: zod.union([zod.boolean(), zod.null()]).optional(),
optimizeProjections: zod.union([zod.boolean(), zod.null()]).optional(),
parserMode: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
index 68bfb2b4d651..59745f683118 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
@@ -859,6 +859,17 @@
],
"description": "Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap"
},
+ "negatedPersonFiltersNotIn": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN."
+ },
"optimizeJoinedFilters": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
index 58f3f855dea2..aa1aaa708123 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
@@ -858,6 +858,17 @@
],
"description": "Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap"
},
+ "negatedPersonFiltersNotIn": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN."
+ },
"optimizeJoinedFilters": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
index 9ce6fb43bae6..3993bea06e8b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
@@ -334,6 +334,17 @@
],
"description": "Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap"
},
+ "negatedPersonFiltersNotIn": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN."
+ },
"optimizeJoinedFilters": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
index b35f3e82ada1..bb77a6512c59 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
@@ -563,6 +563,17 @@
],
"description": "Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap"
},
+ "negatedPersonFiltersNotIn": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN."
+ },
"optimizeJoinedFilters": {
"anyOf": [
{