:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(clickhouse): add lowercase bloom filter skip index for materialized columns (#58754)
Robbieb934f383bdf8
diff --git a/ee/clickhouse/materialized_columns/columns.py b/ee/clickhouse/materialized_columns/columns.pyindex ebbc0ff7442f..370dd28d885d 100644--- a/ee/clickhouse/materialized_columns/columns.py+++ b/ee/clickhouse/materialized_columns/columns.py@@ -71,6 +71,7 @@ class MaterializedColumn:has_minmax_index: bool = Falsehas_bloom_filter_index: bool = Falsehas_ngram_lower_index: bool = False+ has_bloom_filter_lower_index: bool = False@propertydef type(self) -> str:@@ -123,7 +124,7 @@ class MaterializedColumn:c.name,c.comment,c.type like 'Nullable(%%)' as is_nullable,- arrayFilter(x -> x != '', [i_minmax.name, i_bf.name, i_ngram.name]) as index_names+ arrayFilter(x -> x != '', [i_minmax.name, i_bf.name, i_ngram.name, i_bf_lower.name]) as index_namesFROM system.columns cLEFT JOIN system.data_skipping_indices i_minmaxON i_minmax.database = c.database@@ -137,6 +138,10 @@ class MaterializedColumn:ON i_ngram.database = c.databaseAND i_ngram.table = %(data_table)sAND i_ngram.name = concat('ngram_bf_lower_', c.name)+ LEFT JOIN system.data_skipping_indices i_bf_lower+ ON i_bf_lower.database = c.database+ AND i_bf_lower.table = %(data_table)s+ AND i_bf_lower.name = concat('bloom_filter_lower_', c.name)WHERE c.database = %(database)sAND c.table = %(table)sAND c.comment LIKE '%%column_materializer::%%'@@ -163,16 +168,15 @@ class MaterializedColumn:rows = MaterializedColumn._get_all(table)for name, comment, is_nullable, index_names in rows:- has_minmax = any(idx and idx.startswith("minmax_") for idx in index_names)- has_bloom = any(idx and idx.startswith("bloom_filter_") for idx in index_names)- has_ngram = any(idx and idx.startswith("ngram_bf_lower_") for idx in index_names)+ # Exact name matches: a prefix check would mismatch `bloom_filter_` against `bloom_filter_lower_`yield MaterializedColumn(name,MaterializedColumnDetails.from_column_comment(comment),is_nullable=bool(is_nullable),- has_minmax_index=has_minmax,- has_bloom_filter_index=has_bloom,- has_ngram_lower_index=has_ngram,+ has_minmax_index=get_minmax_index_name(name) in index_names,+ has_bloom_filter_index=get_bloom_filter_index_name(name) in index_names,+ has_ngram_lower_index=get_ngram_lower_index_name(name) in index_names,+ has_bloom_filter_lower_index=get_bloom_filter_lower_index_name(name) in index_names,)@staticmethod@@ -283,6 +287,10 @@ def get_ngram_lower_index_name(column: str) -> str:return f"ngram_bf_lower_{column}"+def get_bloom_filter_lower_index_name(column: str) -> str:+ return f"bloom_filter_lower_{column}"++@dataclassclass MinMaxIndex:column_name: str@@ -339,6 +347,32 @@ class NgramLowerIndex:return f"ADD INDEX IF NOT EXISTS {self.name} lower({self.column_name}) TYPE {ngram_type} GRANULARITY {self.granularity}"+@dataclass+class BloomFilterLowerIndex:+ """+ A plain bloom_filter index over lower(column) for case-insensitive equality / IN lookups.++ Same 2 ClickHouse limitations as NgramLowerIndex (case-sensitive indexes, no nullable columns),+ so we index lower(col) and wrap nullable columns in coalesce(col, '').+ """++ column_name: str+ is_nullable: bool+ false_positive_rate: float = 0.01+ granularity: int = 1++ @property+ def name(self) -> str:+ return get_bloom_filter_lower_index_name(self.column_name)++ def as_add_sql(self) -> str:+ bf_type = f"bloom_filter({self.false_positive_rate})"+ if self.is_nullable:+ return f"ADD INDEX IF NOT EXISTS {self.name} lower(coalesce({self.column_name}, '')) TYPE {bf_type} GRANULARITY {self.granularity}"+ else:+ return f"ADD INDEX IF NOT EXISTS {self.name} lower({self.column_name}) TYPE {bf_type} GRANULARITY {self.granularity}"++@dataclassclass CreateColumnOnDataNodesTask:table: str@@ -347,6 +381,7 @@ class CreateColumnOnDataNodesTask:add_column_comment: boolcreate_bloom_filter_index: bool = Falsecreate_ngram_lower_index: bool = False+ create_bloom_filter_lower_index: bool = Falsedef execute(self, client: Client) -> None:expression, parameters = self.column.get_expression_and_parameters()@@ -367,6 +402,9 @@ class CreateColumnOnDataNodesTask:if self.create_ngram_lower_index:actions.append(NgramLowerIndex(self.column.name, self.column.is_nullable).as_add_sql())+ if self.create_bloom_filter_lower_index:+ actions.append(BloomFilterLowerIndex(self.column.name, self.column.is_nullable).as_add_sql())+client.execute(f"ALTER TABLE {self.table} " + ", ".join(actions),parameters,@@ -400,6 +438,7 @@ def materialize(is_nullable: bool = False,create_bloom_filter_index: bool = False,create_ngram_lower_index: bool = False,+ create_bloom_filter_lower_index: bool = False,) -> MaterializedColumn:if existing_column := get_materialized_columns(table).get((property, table_column)):if TEST:@@ -432,6 +471,7 @@ def materialize(add_column_comment=table_info.read_table == table_info.data_table,create_bloom_filter_index=create_bloom_filter_index,create_ngram_lower_index=create_ngram_lower_index,+ create_bloom_filter_lower_index=create_bloom_filter_lower_index,).execute,).result()@@ -530,6 +570,7 @@ class DropColumnTask:get_minmax_index_name,get_bloom_filter_index_name,get_ngram_lower_index_name,+ get_bloom_filter_lower_index_name,]:index_name = get_index_name_fn(column_name)drop_index_action = f"DROP INDEX IF EXISTS {index_name}"diff --git a/ee/clickhouse/materialized_columns/test/test_columns.py b/ee/clickhouse/materialized_columns/test/test_columns.pyindex 81fa11705153..203f03cc489a 100644--- a/ee/clickhouse/materialized_columns/test/test_columns.py+++ b/ee/clickhouse/materialized_columns/test/test_columns.py@@ -9,6 +9,7 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, get_from unittest import TestCasefrom unittest.mock import patch+from parameterized import parameterizedfrom tenacity import retry, stop_after_attempt, wait_exponentialfrom posthog.clickhouse.client import sync_execute@@ -25,6 +26,7 @@ from ee.clickhouse.materialized_columns.columns import (backfill_materialized_columns,drop_column,get_bloom_filter_index_name,+ get_bloom_filter_lower_index_name,get_enabled_materialized_columns,get_materialized_columns,get_minmax_index_name,@@ -488,12 +490,32 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):index_info = get_index_from_explain(query, index_name)assert index_info is not None, f"N-gram index {index_name} should appear in EXPLAIN output"+ @parameterized.expand([("non_nullable", False), ("nullable", True)])+ def test_bloom_filter_lower_index_usage(self, _name, is_nullable):+ property_name = "ci_category_prop"+ _create_event(+ team=self.team,+ event="test_event",+ distinct_id="user1",+ properties={property_name: "Category_A"},+ )++ column = materialize("events", property_name, create_bloom_filter_lower_index=True, is_nullable=is_nullable)+ index_name = get_bloom_filter_lower_index_name(column.name)++ # The index expression is lower(coalesce(col, '')) for nullable columns, lower(col) otherwise+ indexed_expr = f"lower(coalesce({column.name}, ''))" if is_nullable else f"lower({column.name})"+ query = f"SELECT count() FROM {EVENTS_DATA_TABLE()} WHERE {indexed_expr} = 'category_a'"+ index_info = get_index_from_explain(query, index_name)+ assert index_info is not None, f"Bloom filter lower index {index_name} should appear in EXPLAIN output"+def test_get_all_returns_index_flags(self):"""Test that get_materialized_columns returns correct index flags from ClickHouse."""prop_all = "prop_all"prop_minmax = "prop_minmax"prop_bf = "prop_bf"prop_ngram_lower = "prop_ngram_lower"+ prop_bf_lower = "prop_bf_lower"prop_none = "prop_none"_create_event(@@ -505,17 +527,19 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):prop_minmax: prop_minmax,prop_bf: prop_bf,prop_ngram_lower: prop_ngram_lower,+ prop_bf_lower: prop_bf_lower,prop_none: prop_none,},)- # Create column with all three index types+ # Create column with all index typesmaterialize("events",prop_all,create_minmax_index=True,create_bloom_filter_index=True,create_ngram_lower_index=True,+ create_bloom_filter_lower_index=True,)materialize("events",@@ -523,6 +547,7 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):create_minmax_index=True,create_bloom_filter_index=False,create_ngram_lower_index=False,+ create_bloom_filter_lower_index=False,)materialize("events",@@ -530,6 +555,7 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):create_bloom_filter_index=True,create_ngram_lower_index=False,create_minmax_index=False,+ create_bloom_filter_lower_index=False,)materialize("events",@@ -537,6 +563,15 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):create_bloom_filter_index=False,create_ngram_lower_index=True,create_minmax_index=False,+ create_bloom_filter_lower_index=False,+ )+ materialize(+ "events",+ prop_bf_lower,+ create_bloom_filter_index=False,+ create_ngram_lower_index=False,+ create_minmax_index=False,+ create_bloom_filter_lower_index=True,)materialize("events",@@ -544,6 +579,7 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):create_bloom_filter_index=False,create_ngram_lower_index=False,create_minmax_index=False,+ create_bloom_filter_lower_index=False,)cols = get_materialized_columns("events")@@ -551,37 +587,50 @@ class TestMaterializedColumns(ClickhouseTestMixin, BaseTest):mat_col_minmax = cols.get((prop_minmax, "properties"))mat_col_bf = cols.get((prop_bf, "properties"))mat_col_ngram_lower = cols.get((prop_ngram_lower, "properties"))+ mat_col_bf_lower = cols.get((prop_bf_lower, "properties"))mat_col_none = cols.get((prop_none, "properties"))assert mat_col_all is not Noneassert mat_col_minmax is not Noneassert mat_col_bf is not Noneassert mat_col_ngram_lower is not None+ assert mat_col_bf_lower is not Noneassert mat_col_none is not None- # Verify index flags: (has_minmax, has_bloom_filter, has_ngram_lower)+ # Verify index flags: (has_minmax, has_bloom_filter, has_ngram_lower, has_bloom_filter_lower)assert (mat_col_all.has_minmax_index,mat_col_all.has_bloom_filter_index,mat_col_all.has_ngram_lower_index,- ) == (True, True, True)+ mat_col_all.has_bloom_filter_lower_index,+ ) == (True, True, True, True)assert (mat_col_minmax.has_minmax_index,mat_col_minmax.has_bloom_filter_index,mat_col_minmax.has_ngram_lower_index,- ) == (True, False, False)+ mat_col_minmax.has_bloom_filter_lower_index,+ ) == (True, False, False, False)assert (mat_col_bf.has_minmax_index,mat_col_bf.has_bloom_filter_index,mat_col_bf.has_ngram_lower_index,- ) == (False, True, False)+ mat_col_bf.has_bloom_filter_lower_index,+ ) == (False, True, False, False)assert (mat_col_ngram_lower.has_minmax_index,mat_col_ngram_lower.has_bloom_filter_index,mat_col_ngram_lower.has_ngram_lower_index,- ) == (False, False, True)+ mat_col_ngram_lower.has_bloom_filter_lower_index,+ ) == (False, False, True, False)+ assert (+ mat_col_bf_lower.has_minmax_index,+ mat_col_bf_lower.has_bloom_filter_index,+ mat_col_bf_lower.has_ngram_lower_index,+ mat_col_bf_lower.has_bloom_filter_lower_index,+ ) == (False, False, False, True)assert (mat_col_none.has_minmax_index,mat_col_none.has_bloom_filter_index,mat_col_none.has_ngram_lower_index,- ) == (False, False, False)+ mat_col_none.has_bloom_filter_lower_index,+ ) == (False, False, False, False)diff --git a/posthog/clickhouse/materialized_columns.py b/posthog/clickhouse/materialized_columns.pyindex e1f9c023405c..1380c6cd796a 100644--- a/posthog/clickhouse/materialized_columns.py+++ b/posthog/clickhouse/materialized_columns.py@@ -15,6 +15,7 @@ class MaterializedColumn(Protocol):has_minmax_index: boolhas_bloom_filter_index: boolhas_ngram_lower_index: bool+ has_bloom_filter_lower_index: boolif EE_AVAILABLE:diff --git a/posthog/dags/add_index_to_materialized_column.py b/posthog/dags/add_index_to_materialized_column.pyindex 12045c009d5f..7cd80f112b53 100644--- a/posthog/dags/add_index_to_materialized_column.py+++ b/posthog/dags/add_index_to_materialized_column.py@@ -9,6 +9,7 @@ from posthog.settings import TESTfrom ee.clickhouse.materialized_columns.columns import (BloomFilterIndex,+ BloomFilterLowerIndex,MaterializedColumn,MinMaxIndex,NgramLowerIndex,@@ -24,6 +25,7 @@ class AddIndexConfig(dagster.Config):add_minmax_index: bool = Falseadd_bloom_filter_index: bool = Falseadd_ngram_lower_index: bool = False+ add_bloom_filter_lower_index: bool = Falsedry_run: bool = False@@ -36,6 +38,7 @@ class AddIndexTask:add_minmax: bool,add_bloom_filter: bool,add_ngram_lower: bool,+ add_bloom_filter_lower: bool,dry_run: bool,logger: dagster.DagsterLogManager,):@@ -45,6 +48,7 @@ class AddIndexTask:self.add_minmax = add_minmaxself.add_bloom_filter = add_bloom_filterself.add_ngram_lower = add_ngram_lower+ self.add_bloom_filter_lower = add_bloom_filter_lowerself.dry_run = dry_runself.logger = logger@@ -72,6 +76,13 @@ class AddIndexTask:else:actions.append(ngram_index.as_add_sql())+ if self.add_bloom_filter_lower:+ bloom_lower_index = BloomFilterLowerIndex(self.column_name, self.is_nullable)+ if check_index_exists(client, self.table, bloom_lower_index.name):+ self.logger.info(f"Skipping bloom_filter_lower index {bloom_lower_index.name}, already exists")+ else:+ actions.append(bloom_lower_index.as_add_sql())+if not actions:self.logger.info(f"No indexes to add for column {self.column_name}")return@@ -98,7 +109,12 @@ def add_indexes_to_columns(config: AddIndexConfig,cluster: dagster.ResourceParam[ClickhouseCluster],):- if not config.add_minmax_index and not config.add_bloom_filter_index and not config.add_ngram_lower_index:+ if (+ not config.add_minmax_index+ and not config.add_bloom_filter_index+ and not config.add_ngram_lower_index+ and not config.add_bloom_filter_lower_index+ ):context.log.warning("No index types selected. Nothing to do.")return@@ -123,6 +139,7 @@ def add_indexes_to_columns(add_minmax=config.add_minmax_index,add_bloom_filter=config.add_bloom_filter_index,add_ngram_lower=config.add_ngram_lower_index,+ add_bloom_filter_lower=config.add_bloom_filter_lower_index,dry_run=config.dry_run,logger=context.log,)diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.pyindex cc82d9b37ac0..6f7bf58ddbb0 100644--- a/posthog/hogql/printer/base.py+++ b/posthog/hogql/printer/base.py@@ -1294,6 +1294,7 @@ class BasePrinter(Visitor[str]):has_minmax_index=materialized_column.has_minmax_index,has_ngram_lower_index=materialized_column.has_ngram_lower_index,has_bloom_filter_index=materialized_column.has_bloom_filter_index,+ has_bloom_filter_lower_index=materialized_column.has_bloom_filter_lower_index,)# Check for dmat (dynamic materialized) columns@@ -1305,6 +1306,7 @@ class BasePrinter(Visitor[str]):has_minmax_index=False,has_ngram_lower_index=False,has_bloom_filter_index=False,+ has_bloom_filter_lower_index=False,)yield from self._yield_property_group_columns(field_type, table_name, field_name, property_name)@@ -1324,6 +1326,7 @@ class BasePrinter(Visitor[str]):has_minmax_index=materialized_column.has_minmax_index,has_ngram_lower_index=materialized_column.has_ngram_lower_index,has_bloom_filter_index=materialized_column.has_bloom_filter_index,+ has_bloom_filter_lower_index=materialized_column.has_bloom_filter_lower_index,)def visit_property_type(self, type: ast.PropertyType):diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.pyindex 2fac52b79bc6..8f63aeeecd8d 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -889,6 +889,68 @@ class ClickHousePrinter(BasePrinter):else:return f"notIn({materialized_column_sql}, tuple({values_sql}))"+ def _get_optimized_materialized_column_lower_in_operation(self, node: ast.CompareOperation) -> str | None:+ """+ Optimized printed expression for `lower(<property>) IN (...)`, matching the lower() expression the+ bloom_filter_lower / ngram_lower indexes are built on so ClickHouse can pick whichever one exists.+ """+ if node.op not in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):+ return None++ # HogQL `lower` is case-insensitive, so `LOWER(...)` keeps the user-typed casing on the Call+ if not (isinstance(node.left, ast.Call) and node.left.name.lower() == "lower" and len(node.left.args) == 1):+ return None++ property_source = self._get_materialized_string_property_source(node.left.args[0])+ if not isinstance(property_source, PrintableMaterializedColumn) or not (+ property_source.has_bloom_filter_lower_index or property_source.has_ngram_lower_index+ ):+ return None++ if property_source.column.strip("`\"'") in COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING:+ return None++ # IN values: a string constant, a tuple/array of constants, or a constant list (from a {placeholder})+ if isinstance(node.right, ast.Constant) and isinstance(node.right.value, str):+ string_values: list[str] = [node.right.value]+ elif isinstance(node.right, ast.Constant) and isinstance(node.right.value, (list, tuple)):+ if not all(isinstance(value, str) for value in node.right.value):+ return None+ string_values = list(node.right.value)+ elif isinstance(node.right, (ast.Tuple, ast.Array)):+ string_values = []+ for value in node.right.exprs:+ if isinstance(value, ast.Constant) and isinstance(value.value, str):+ string_values.append(value.value)+ else:+ return None+ else:+ return None++ if len(string_values) == 0:+ return None++ # Bail if an IN value could collide with a stored NULL sentinel: nullable columns alias NULL to ''+ # (via coalesce); non-nullable columns store NULL as '' or 'null'. 'null' is a real value when nullable.+ null_sentinels = [""] if property_source.is_nullable else MAT_COL_NULL_SENTINELS+ if any(value in null_sentinels for value in string_values):+ return None++ materialized_column_sql = str(property_source)+ values_sql = ", ".join(self.context.add_value(value) for value in string_values)++ # Match the index expression; coalesce() removes NULL so no ifNull / IS NOT NULL guard is needed+ if property_source.is_nullable:+ indexed_expr = f"lower(coalesce({materialized_column_sql}, ''))"+ else:+ indexed_expr = f"lower({materialized_column_sql})"++ if node.op == ast.CompareOperationOp.In:+ # has() with a constant array keeps the skip index usable (unlike in() under transform_null_in=1)+ return f"has([{values_sql}], {indexed_expr})"+ else:+ return f"notIn({indexed_expr}, tuple({values_sql}))"+def _get_events_session_id_table_type(self, node: ast.Expr) -> ast.BaseTableType | None:"""If the expression resolves to $session_id on the events table, return the table type."""from posthog.hogql.database.schema.events import EventsTable@@ -1156,6 +1218,8 @@ class ClickHousePrinter(BasePrinter):return optimized_materialized_likeif optimized_materialized_in := self._get_optimized_materialized_column_in_operation(node):return optimized_materialized_in+ if optimized_materialized_lower_in := self._get_optimized_materialized_column_lower_in_operation(node):+ return optimized_materialized_lower_inin_join_constraint = any(isinstance(item, ast.JoinConstraint) for item in self.stack)# indexHint() is purely an optimizer directive — its result is always true,diff --git a/posthog/hogql/printer/test/__snapshots__/test_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_printer.ambrindex f4fbbf44bbf8..01c0ee98b6e8 100644--- a/posthog/hogql/printer/test/__snapshots__/test_printer.ambr+++ b/posthog/hogql/printer/test/__snapshots__/test_printer.ambr@@ -2555,6 +2555,141 @@use_hive_partitioning=0'''# ---+# name: TestMaterializedColumnOptimization.test_lower_in_optimization_handles_null_and_sentinel_rows_0_nullable+ '''+ SELECT events.distinct_id AS distinct_id+ FROM events+ WHERE and(equals(events.team_id, 99999), has(['[email protected]'], lower(coalesce(events.mat_test_prop, ''))))+ ORDER BY events.distinct_id ASC+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestMaterializedColumnOptimization.test_lower_in_optimization_handles_null_and_sentinel_rows_0_nullable.1+ '''+ SELECT events.distinct_id AS distinct_id+ FROM events+ WHERE and(equals(events.team_id, 99999), notIn(lower(coalesce(events.mat_test_prop, '')), tuple('[email protected]')))+ ORDER BY events.distinct_id ASC+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestMaterializedColumnOptimization.test_lower_in_optimization_handles_null_and_sentinel_rows_1_non_nullable+ '''+ SELECT events.distinct_id AS distinct_id+ FROM events+ WHERE and(equals(events.team_id, 99999), has(['[email protected]'], lower(events.mat_test_prop)))+ ORDER BY events.distinct_id ASC+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestMaterializedColumnOptimization.test_lower_in_optimization_handles_null_and_sentinel_rows_1_non_nullable.1+ '''+ SELECT events.distinct_id AS distinct_id+ FROM events+ WHERE and(equals(events.team_id, 99999), notIn(lower(events.mat_test_prop), tuple('[email protected]')))+ ORDER BY events.distinct_id ASC+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestMaterializedColumnOptimization.test_lower_in_optimization_on_persons+ '''+ SELECT persons.id AS id,+ persons.properties___email AS email+ FROM+ (SELECT tupleElement(argMax(tuple(person.pmat_email), 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), has(['[email protected]', '[email protected]'], lower(coalesce(where_optimization.pmat_email, '')))))))+ GROUP BY person.id+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons+ WHERE in(lower(persons.properties___email),+ ['[email protected]', '[email protected]'])+ ORDER BY persons.properties___email ASC+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestMaterializedColumnOptimization.test_lower_in_uses_bloom_filter_lower_index_on_events+ '''+ SELECT count() AS `count()`+ FROM events+ WHERE and(equals(events.team_id, 99999), has(['[email protected]', '[email protected]'], lower(coalesce(events.mat_email, ''))))+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestMaterializedColumnOptimization.test_lower_in_uses_ngram_lower_index_on_events+ '''+ SELECT count() AS `count()`+ FROM events+ WHERE and(equals(events.team_id, 99999), has(['[email protected]', '[email protected]'], lower(coalesce(events.mat_email, ''))))+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestMaterializedColumnOptimization.test_materialized_column_optimization_returns_correct_results_0_nullable'''SELECT events.distinct_id AS distinct_iddiff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 898e986604fc..6ec098e8dce0 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -14,6 +14,7 @@ from posthog.test.base import (cleanup_materialized_columns,flush_persons_and_events,get_index_from_explain,+ get_inner_person_subquery_clickhouse_sql,materialized,snapshot_clickhouse_queries,)@@ -66,6 +67,7 @@ from products.event_definitions.backend.models.property_definition import Properfrom ee.clickhouse.materialized_columns.columns import (get_bloom_filter_index_name,+ get_bloom_filter_lower_index_name,get_minmax_index_name,get_ngram_lower_index_name,materialize,@@ -4480,6 +4482,81 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):{"hogql_val_0": "value1", "hogql_val_1": "value2"},)+ def test_materialized_column_lower_in_uses_bloom_filter_lower_index_non_nullable(self) -> None:+ # lower(property) IN (...) is rewritten to has([...], lower(column)) so it can hit a bloom_filter_lower index+ with materialized("events", "test_prop", is_nullable=False, create_bloom_filter_lower_index=True) as mat_col:+ self._test_materialized_column_comparison(+ "lower(properties.test_prop) in ('value1', 'value2')",+ f"has([%(hogql_val_0)s, %(hogql_val_1)s], lower(events.{mat_col.name}))",+ {"hogql_val_0": "value1", "hogql_val_1": "value2"},+ )++ def test_materialized_column_lower_not_in_uses_bloom_filter_lower_index_non_nullable(self) -> None:+ with materialized("events", "test_prop", is_nullable=False, create_bloom_filter_lower_index=True) as mat_col:+ self._test_materialized_column_comparison(+ "lower(properties.test_prop) not in ('value1', 'value2')",+ f"notIn(lower(events.{mat_col.name}), tuple(%(hogql_val_0)s, %(hogql_val_1)s))",+ {"hogql_val_0": "value1", "hogql_val_1": "value2"},+ )++ def test_materialized_column_lower_in_uses_bloom_filter_lower_index_nullable(self) -> None:+ # The index is built on lower(coalesce(column, '')) so the printed expression must match it exactly+ with materialized("events", "test_prop", is_nullable=True, create_bloom_filter_lower_index=True) as mat_col:+ self._test_materialized_column_comparison(+ "lower(properties.test_prop) in ('value1', 'value2')",+ f"has([%(hogql_val_0)s, %(hogql_val_1)s], lower(coalesce(events.{mat_col.name}, '')))",+ {"hogql_val_0": "value1", "hogql_val_1": "value2"},+ )++ def test_materialized_column_lower_not_in_nullable(self) -> None:+ with materialized("events", "test_prop", is_nullable=True, create_bloom_filter_lower_index=True) as mat_col:+ self._test_materialized_column_comparison(+ "lower(properties.test_prop) not in ('value1', 'value2')",+ f"notIn(lower(coalesce(events.{mat_col.name}, '')), tuple(%(hogql_val_0)s, %(hogql_val_1)s))",+ {"hogql_val_0": "value1", "hogql_val_1": "value2"},+ )++ def test_materialized_column_lower_in_matches_case_insensitive_lower_call(self) -> None:+ # HogQL `lower` is case-insensitive, so `LOWER(...)` must still hit the optimization+ with materialized("events", "test_prop", is_nullable=False, create_bloom_filter_lower_index=True) as mat_col:+ self._test_materialized_column_comparison(+ "LOWER(properties.test_prop) in ('value1', 'value2')",+ f"has([%(hogql_val_0)s, %(hogql_val_1)s], lower(events.{mat_col.name}))",+ {"hogql_val_0": "value1", "hogql_val_1": "value2"},+ )++ def test_materialized_column_lower_in_uses_ngram_lower_index(self) -> None:+ # An ngram_lower index also serves IN lookups, so the rewrite fires for it too+ with materialized("events", "test_prop", is_nullable=False, create_ngram_lower_index=True) as mat_col:+ self._test_materialized_column_comparison(+ "lower(properties.test_prop) in ('value1', 'value2')",+ f"has([%(hogql_val_0)s, %(hogql_val_1)s], lower(events.{mat_col.name}))",+ {"hogql_val_0": "value1", "hogql_val_1": "value2"},+ )++ def test_materialized_column_lower_in_not_optimized_without_a_lower_index(self) -> None:+ # Without a bloom_filter_lower or ngram_lower index there's nothing to hit - leave the generic path+ with materialized("events", "test_prop", is_nullable=False) as mat_col:+ printed = self._expr("lower(properties.test_prop) in ('value1', 'value2')")+ assert "has(" not in printed, printed+ assert mat_col.name in printed++ def test_materialized_column_lower_in_bails_out_for_sentinel_value(self) -> None:+ # '' and 'null' are NULL sentinels for non-nullable columns - bail so the generic path stays correct+ with materialized("events", "test_prop", is_nullable=False, create_bloom_filter_lower_index=True):+ assert "has(" not in self._expr("lower(properties.test_prop) in ('null', 'value2')")+ assert "has(" not in self._expr("lower(properties.test_prop) in ('', 'value2')")++ def test_materialized_column_lower_in_sentinels_for_nullable(self) -> None:+ # Nullable columns only alias NULL to '' (via coalesce); 'null' is a real value, so it still optimizes+ with materialized("events", "test_prop", is_nullable=True, create_bloom_filter_lower_index=True) as mat_col:+ self._test_materialized_column_comparison(+ "lower(properties.test_prop) in ('null', 'value2')",+ f"has([%(hogql_val_0)s, %(hogql_val_1)s], lower(coalesce(events.{mat_col.name}, '')))",+ {"hogql_val_0": "null", "hogql_val_1": "value2"},+ )+ assert "has(" not in self._expr("lower(properties.test_prop) in ('', 'value2')")+def test_force_data_skipping_indices_works_with_simple_equality(self) -> None:with materialized("events", "test_prop", is_nullable=False, create_bloom_filter_index=True) as mat_col:_create_event(team=self.team, distinct_id="test", event="test", properties={"test_prop": "foo"})@@ -4515,6 +4592,78 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):assert "index" in str(exc_info.value).lower()+ def test_lower_in_optimization_on_persons(self) -> None:+ # The persons table hides the property filter in a subquery; the helper extracts it (see its docstring)+ with materialized("person", "email", is_nullable=True, create_bloom_filter_lower_index=True) as mat_col:+ _create_person(+ distinct_ids=["p_foo"], team=self.team, properties={"email": "[email protected]"}, immediate=True+ )+ _create_person(+ distinct_ids=["p_bar"], team=self.team, properties={"email": "[email protected]"}, immediate=True+ )+ _create_person(+ distinct_ids=["p_other"], team=self.team, properties={"email": "[email protected]"}, immediate=True+ )++ result = execute_hogql_query(+ team=self.team,+ query="SELECT id, properties.email FROM persons "+ "WHERE lower(properties.email) IN {emails} ORDER BY properties.email",+ placeholders={"emails": ast.Constant(value=["[email protected]", "[email protected]"])},+ modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.AUTO),+ )+ # Correctness: case-insensitive match through the deduplication subquery+ assert {email for (_id, email) in result.results} == {"[email protected]", "[email protected]"}+ assert result.clickhouse++ # Index usage: EXPLAIN the person-filter subquery from the SQL that actually ran.+ subquery = get_inner_person_subquery_clickhouse_sql(result.clickhouse)+ index_name = get_bloom_filter_lower_index_name(mat_col.name)+ index_info = get_index_from_explain(subquery, index_name)+ assert index_info is not None, (+ f"Expected skip index {index_name} to be used in the persons filter subquery:\n{subquery}"+ )++ def test_lower_in_uses_bloom_filter_lower_index_on_events(self) -> None:+ # Events are a single direct scan, so EXPLAIN of the executed query exposes the skip index directly+ with materialized("events", "email", is_nullable=True, create_bloom_filter_lower_index=True) as mat_col:+ _create_event(team=self.team, distinct_id="u1", event="e", properties={"email": "[email protected]"})++ result = execute_hogql_query(+ team=self.team,+ query="SELECT count() FROM events WHERE lower(properties.email) IN {emails}",+ placeholders={"emails": ast.Constant(value=["[email protected]", "[email protected]"])},+ modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.AUTO),+ )+ assert result.results == [(1,)]+ assert result.clickhouse++ index_name = get_bloom_filter_lower_index_name(mat_col.name)+ index_info = get_index_from_explain(result.clickhouse, index_name)+ assert index_info is not None, (+ f"Expected skip index {index_name} to be used in EXPLAIN output for:\n{result.clickhouse}"+ )++ def test_lower_in_uses_ngram_lower_index_on_events(self) -> None:+ # The rewrite must also let an ngram_lower index serve the IN lookup end to end.+ with materialized("events", "email", is_nullable=True, create_ngram_lower_index=True) as mat_col:+ _create_event(team=self.team, distinct_id="u1", event="e", properties={"email": "[email protected]"})++ result = execute_hogql_query(+ team=self.team,+ query="SELECT count() FROM events WHERE lower(properties.email) IN {emails}",+ placeholders={"emails": ast.Constant(value=["[email protected]", "[email protected]"])},+ modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.AUTO),+ )+ assert result.results == [(1,)]+ assert result.clickhouse++ index_name = get_ngram_lower_index_name(mat_col.name)+ index_info = get_index_from_explain(result.clickhouse, index_name)+ assert index_info is not None, (+ f"Expected skip index {index_name} to be used in EXPLAIN output for:\n{result.clickhouse}"+ )+@parameterized.expand([("no_mat_col", None, False),@@ -4715,6 +4864,44 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):not_in_matches = {d for (d,) in not_in_result.results}assert not_in_matches == not_in_expected, f"NOT IN {in_values}"+ @parameterized.expand([("nullable", True), ("non_nullable", False)])+ def test_lower_in_optimization_handles_null_and_sentinel_rows(self, _, is_nullable) -> None:+ # The rewrite must stay correct for NULL/missing, empty-string, and literal-"null" property rows+ with materialized("events", "test_prop", is_nullable=is_nullable, create_bloom_filter_lower_index=True):+ events: list[tuple[str, dict]] = [+ ("mixed_case", {"test_prop": "[email protected]"}),+ ("lower_case", {"test_prop": "[email protected]"}),+ ("other", {"test_prop": "OTHER"}),+ ("literal_null_str", {"test_prop": "null"}),+ ("empty_str", {"test_prop": ""}),+ ("missing_key", {}),+ ("json_null", {"test_prop": None}),+ ]+ for distinct_id, properties in events:+ _create_event(team=self.team, distinct_id=distinct_id, event="e", properties=properties)+ all_ids = {distinct_id for distinct_id, _ in events}++ def run(op: str) -> tuple[set[str], str]:+ result = execute_hogql_query(+ team=self.team,+ query=(+ f"SELECT distinct_id FROM events "+ f"WHERE lower(properties.test_prop) {op} ('[email protected]') ORDER BY distinct_id"+ ),+ modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.AUTO),+ )+ assert result.clickhouse+ return {d for (d,) in result.results}, result.clickhouse++ # Case-insensitive IN: matches the mixed-case and already-lowercase rows, nothing else.+ in_matches, in_sql = run("IN")+ assert "has(" in in_sql, f"expected the bloom_filter_lower rewrite to fire: {in_sql}"+ assert in_matches == {"mixed_case", "lower_case"}++ # NOT IN returns the exact complement, including the NULL / missing / empty-string rows.+ not_in_matches, _ = run("NOT IN")+ assert not_in_matches == all_ids - {"mixed_case", "lower_case"}+def test_recursive_cte_raises(self):query = """WITH RECURSIVE cte AS (diff --git a/posthog/hogql/printer/types.py b/posthog/hogql/printer/types.pyindex 9b278f8dfd52..777b16869d4c 100644--- a/posthog/hogql/printer/types.py+++ b/posthog/hogql/printer/types.py@@ -17,6 +17,7 @@ class PrintableMaterializedColumn:has_minmax_index: boolhas_bloom_filter_index: boolhas_ngram_lower_index: bool+ has_bloom_filter_lower_index: booldef __str__(self) -> str:if self.table is None:diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 25c6b957c3ce..d810ebcfde79 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -983,6 +983,7 @@ def cleanup_materialized_columns():try:from ee.clickhouse.materialized_columns.columns import (get_bloom_filter_index_name,+ get_bloom_filter_lower_index_name,get_materialized_columns,get_minmax_index_name,get_ngram_lower_index_name,@@ -1011,6 +1012,8 @@ def cleanup_materialized_columns():indexes_to_drop.append(get_bloom_filter_index_name(column.name))if column.has_ngram_lower_index:indexes_to_drop.append(get_ngram_lower_index_name(column.name))+ if column.has_bloom_filter_lower_index:+ indexes_to_drop.append(get_bloom_filter_lower_index_name(column.name))for index_name in indexes_to_drop:sync_execute(f"ALTER TABLE {data_table} DROP INDEX IF EXISTS {index_name} SETTINGS mutations_sync = 2")@@ -1104,6 +1107,29 @@ def get_indexes_from_explain(query: str, values: dict | None = None) -> list[dicreturn read_node.get("Indexes", [])+def get_inner_person_subquery_clickhouse_sql(clickhouse_sql: str) -> str:+ """Extract the pushed-down person-filter subquery from a compiled persons query.++ Filtering `persons` by a property pushes the filter into a `where_optimization` IN-subquery that+ ClickHouse evaluates eagerly, so EXPLAIN of the full query never shows the subquery's index analysis.+ Pass a `HogQLQueryResponse.clickhouse` string; test-only, fails loudly if the subquery is not found.+ """+ match = re.search(r"\(\s*SELECT\s+where_optimization", clickhouse_sql)+ assert match is not None, (+ f"No `where_optimization` person subquery found - is this a persons query with a property filter?"+ f"\n{clickhouse_sql}"+ )+ depth = 0+ for i in range(match.start(), len(clickhouse_sql)):+ if clickhouse_sql[i] == "(":+ depth += 1+ elif clickhouse_sql[i] == ")":+ depth -= 1+ if depth == 0:+ return clickhouse_sql[match.start() + 1 : i]+ raise AssertionError(f"Unbalanced parentheses extracting the person subquery:\n{clickhouse_sql}")++@contextmanagerdef materialized(table,@@ -1112,11 +1138,13 @@ def materialized(is_nullable: bool = False,create_bloom_filter_index: bool = False,create_ngram_lower_index: bool = False,+ create_bloom_filter_lower_index: bool = False,) -> Iterator[MaterializedColumn]:"""Materialize a property within the managed block, removing it on exit."""try:from ee.clickhouse.materialized_columns.columns import (get_bloom_filter_index_name,+ get_bloom_filter_lower_index_name,get_minmax_index_name,get_ngram_lower_index_name,materialize,@@ -1133,6 +1161,7 @@ def materialized(is_nullable=is_nullable,create_bloom_filter_index=create_bloom_filter_index,create_ngram_lower_index=create_ngram_lower_index,+ create_bloom_filter_lower_index=create_bloom_filter_lower_index,)yield columnfinally:@@ -1145,6 +1174,8 @@ def materialized(indexes_to_drop.append(get_bloom_filter_index_name(column.name))if create_ngram_lower_index:indexes_to_drop.append(get_ngram_lower_index_name(column.name))+ if create_bloom_filter_lower_index:+ indexes_to_drop.append(get_bloom_filter_lower_index_name(column.name))for index_name in indexes_to_drop:sync_execute(f"ALTER TABLE {data_table} DROP INDEX IF EXISTS {index_name} SETTINGS mutations_sync = 2")cleanup_materialized_columns()diff --git a/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambr b/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambrindex 9626640f6215..7e32e1170099 100644--- a/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambr+++ b/products/conversations/backend/api/tests/__snapshots__/test_tickets.ambr@@ -1,5 +1,5 @@# serializer version: 1-# name: TestTicketEmailFallbackPersonLookup.test_email_fallback_uses_ngram_skip_index+# name: TestTicketEmailFallbackPersonLookup.test_email_fallback_uses_bloom_filter_lower_skip_index'''SELECT persons.id AS id,persons.properties___email AS email@@ -10,7 +10,35 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), in(lower(nullIf(nullIf(where_optimization.pmat_email, ''), 'null')), ['[email protected]'])))))+ WHERE and(equals(where_optimization.team_id, 99999), has(['[email protected]'], lower(where_optimization.pmat_email))))))+ GROUP BY person.id+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS persons+ WHERE in(lower(persons.properties___email),+ ['[email protected]'])+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestTicketEmailFallbackPersonLookup.test_email_fallback_uses_bloom_filter_lower_skip_index.1+ '''+ SELECT persons.id AS id,+ persons.properties___email AS email+ 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), has(['[email protected]'], lower(where_optimization.pmat_email))))))GROUP BY person.idHAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))) AS personsWHERE in(lower(persons.properties___email),diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 3080bc78fb88..4a953333e07f 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -6,6 +6,7 @@ from posthog.test.base import (ClickhouseTestMixin,_create_person,get_index_from_explain,+ get_inner_person_subquery_clickhouse_sql,materialized,snapshot_clickhouse_queries,)@@ -19,15 +20,18 @@ from rest_framework import statusfrom posthog.schema import HogQLQueryModifiers, MaterializationMode+from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query+from posthog.models import ActivityLog, Comment, Organization, Userfrom posthog.models.person import Personfrom posthog.personhog_client.test_helpers import PersonhogTestMixin-from products.conversations.backend.api.tickets import _get_persons_by_email+from products.conversations.backend.api.tickets import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_emailfrom products.conversations.backend.models import Ticket, TicketAssignmentfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Status-from ee.clickhouse.materialized_columns.columns import get_ngram_lower_index_name+from ee.clickhouse.materialized_columns.columns import get_bloom_filter_lower_index_namefrom ee.models.rbac.role import Role@@ -1329,7 +1333,7 @@ class TestTicketEmailFallbackPersonLookup(ClickhouseTestMixin, APIBaseTest):assert response.json()["results"][0]["person"] is None@snapshot_clickhouse_queries- def test_email_fallback_uses_ngram_skip_index(self, mock_on_commit):+ def test_email_fallback_uses_bloom_filter_lower_skip_index(self, mock_on_commit):_create_person(team=self.team,distinct_ids=["idx-test-id"],@@ -1337,20 +1341,25 @@ class TestTicketEmailFallbackPersonLookup(ClickhouseTestMixin, APIBaseTest):immediate=True,)- with materialized("person", "email", create_ngram_lower_index=True) as mat_col:- index_name = get_ngram_lower_index_name(mat_col.name)+ with materialized("person", "email", create_bloom_filter_lower_index=True) as mat_col:+ index_name = get_bloom_filter_lower_index_name(mat_col.name)+ modifiers = HogQLQueryModifiers(materializationMode=MaterializationMode.AUTO)- result = _get_persons_by_email(- self.team,- ["[email protected]"],- modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.AUTO),+ assert "[email protected]" in _get_persons_by_email(+ self.team, ["[email protected]"], modifiers=modifiers)- assert len(result) == 1- assert "[email protected]" in result- raw_query = f"SELECT id FROM person WHERE lower({mat_col.name}) IN ('[email protected]')"- index_info = get_index_from_explain(raw_query, index_name)- assert index_info is not None, f"Expected skip index {index_name} to be used"+ # EXPLAIN the person-filter subquery of the exact query that ran, not a hand-written approximation+ result = execute_hogql_query(+ PERSON_EMAIL_LOOKUP_QUERY,+ placeholders={"emails": ast.Constant(value=["[email protected]"])},+ team=self.team,+ modifiers=modifiers,+ )+ assert result.clickhouse+ subquery = get_inner_person_subquery_clickhouse_sql(result.clickhouse)+ index_info = get_index_from_explain(subquery, index_name)+ assert index_info is not None, f"Expected skip index {index_name} to be used:\n{subquery}"@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex d00bb620307c..ca5525d30524 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -70,6 +70,13 @@ from ee.models.rbac.role import Rolelogger = structlog.get_logger(__name__)+# Case-insensitive batch email lookup. Exposed so tests can EXPLAIN the exact query that runs.+PERSON_EMAIL_LOOKUP_QUERY = """+SELECT id, properties.email+FROM persons+WHERE lower(properties.email) IN {emails}+"""+def _get_persons_by_email(team: Team,@@ -89,11 +96,7 @@ def _get_persons_by_email(emails_lower = [e.lower() for e in emails]with tags_context(product=Product.CONVERSATIONS, feature=Feature.QUERY):response = execute_hogql_query(- """- SELECT id, properties.email- FROM persons- WHERE lower(properties.email) IN {emails}- """,+ PERSON_EMAIL_LOOKUP_QUERY,placeholders={"emails": ast.Constant(value=emails_lower)},team=team,query_type="conversations_person_email_lookup",