: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
perf(cohorts): single-scan nested-boolean cohorts + GROUP BY spill (#65469)
Gustavo H. Strassburgerb2fb02d6f983
diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex 90904d3334c6..d0fc0c5cefa0 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -37,7 +37,7 @@ from posthog.hogql import astfrom posthog.hogql.ast import SelectQuery, SelectSetNode, SelectSetQueryfrom posthog.hogql.constants import HogQLGlobalSettings, LimitContextfrom posthog.hogql.context import HogQLContext-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.property import get_property_typefrom posthog.hogql.query import HogQLQueryExecutor@@ -1248,7 +1248,18 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):return self._build_single_condition_query(deduplicated[0])threshold = len(deduplicated) if operator == PropertyOperatorType.AND else 1+ having = parse_expr("countIf(latest_matches = 1) >= {threshold}", {"threshold": ast.Constant(value=threshold)})+ return self._single_scan_membership_query(deduplicated, having)+ def _single_scan_membership_query(self, hashes: list[str], having: ast.Expr) -> ast.SelectQuery:+ """Assemble the single-scan SELECT over precalculated_person_properties for a given HAVING expr.++ Shared scaffold for both the flat-count path (_build_count_match_query) and the boolean-tree+ path (_build_boolean_tree_query): one inner GROUP BY (person_id, condition) with argMax, one+ outer GROUP BY person_id with HAVING. Keeping the scan template in one place ensures future+ changes to the table access pattern (sort key, column renames, extra filters) are applied+ consistently.+ """query_str = """SELECTperson_id as id@@ -1265,7 +1276,7 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):GROUP BY person_id, condition)GROUP BY person_id- HAVING countIf(latest_matches = 1) >= {threshold}+ HAVING {having}"""return cast(@@ -1274,8 +1285,8 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):query_str,{"team_id": ast.Constant(value=self.team.pk),- "condition_hashes": ast.Tuple(exprs=[ast.Constant(value=h) for h in deduplicated]),- "threshold": ast.Constant(value=threshold),+ "condition_hashes": ast.Tuple(exprs=[ast.Constant(value=h) for h in hashes]),+ "having": having,},),)@@ -1364,29 +1375,108 @@ class HogQLRealtimeCohortQuery(HogQLCohortQuery):return Nonereturn hashes, operator+ def _leaf_having_expr(self, prop: Property, all_hashes: list[str]) -> Optional[ast.Expr]:+ """Build the HAVING predicate for one person-property leaf, over the single-scan rows.++ The inner scan emits one row per (person, condition) with `latest_matches`, so in the+ outer GROUP BY person_id a leaf is "did this person's latest row(s) for these hashes+ match?":+ - single hash / OR-merged → maxIf(latest_matches, condition IN hashes) = 1 (any matched)+ - AND-merged → countIf(latest_matches = 1 AND condition IN hashes) = N (all matched)++ Returns None for anything that isn't a non-negated person property with a conditionHash+ (behavioral, dynamic-cohort, negated, …), so the caller falls through to the parent path.+ """+ if prop.type != "person" or prop.negation:+ return None+ condition_hash = getattr(prop, "conditionHash", None)+ if not condition_hash:+ return None++ merged = getattr(prop, "_merged_condition_hashes", None)+ hashes = self._deduplicate_hashes(merged) if merged else [condition_hash]+ all_hashes.extend(hashes)+ hashes_tuple = ast.Tuple(exprs=[ast.Constant(value=h) for h in hashes])++ # A single hash or an OR-merged leaf matches if ANY of its hashes is the person's latest 1.+ if len(hashes) == 1 or getattr(prop, "_is_or_group", False):+ return parse_expr("maxIf(latest_matches, condition IN {hashes}) = 1", {"hashes": hashes_tuple})+ # An AND-merged leaf matches only if ALL of its hashes are the person's latest 1.+ return parse_expr(+ "countIf(latest_matches = 1 AND condition IN {hashes}) = {n}",+ {"hashes": hashes_tuple, "n": ast.Constant(value=len(hashes))},+ )++ def _build_person_property_having(self, prop_group: PropertyGroup, all_hashes: list[str]) -> Optional[ast.Expr]:+ """Recursively turn a nested AND/OR of person properties into one HAVING boolean expr.++ Every leaf hash is appended to `all_hashes` so the caller can scope the scan's+ `condition IN (...)` filter. Returns None if any leaf is unsupported, so the whole cohort+ falls through to the parent's multi-subquery path.+ """+ operator = prop_group.type+ if operator not in (PropertyOperatorType.AND, PropertyOperatorType.OR):+ return None++ child_exprs: list[ast.Expr] = []+ for value in prop_group.values:+ if isinstance(value, PropertyGroup):+ child = self._build_person_property_having(value, all_hashes)+ else:+ child = self._leaf_having_expr(value, all_hashes)+ if child is None:+ return None+ child_exprs.append(child)++ if not child_exprs:+ return None+ if len(child_exprs) == 1:+ return child_exprs[0]+ return ast.And(exprs=child_exprs) if operator == PropertyOperatorType.AND else ast.Or(exprs=child_exprs)++ def _build_boolean_tree_query(self, prop_group: PropertyGroup) -> Optional[ast.SelectQuery]:+ """One scan for an arbitrarily nested AND/OR of person properties.++ Generalises the flat single-scan: instead of INTERSECT/UNION DISTINCT-ing N person sets+ (which materialises N intermediate sets and OOMs on large cohorts), it reads the table+ once and evaluates the whole boolean expression per person in the HAVING.+ """+ all_hashes: list[str] = []+ having = self._build_person_property_having(prop_group, all_hashes)+ if having is None or not all_hashes:+ return None++ deduplicated = self._deduplicate_hashes(all_hashes)+ return self._single_scan_membership_query(deduplicated, having)+def _get_conditions(self) -> ast.SelectQuery | ast.SelectSetQuery:"""Override to emit a single-scan query when all conditions are person properties.- For cohorts whose top-level group is a flat AND/OR of non-negated person properties- (all backed by precalculated_person_properties), the parent would produce N separate- subqueries joined by INTERSECT/UNION DISTINCT. Each subquery reads the full table and- the set operations materialise large intermediate results — a common source of OOMs- for large cohorts with many person-property conditions.+ For cohorts backed entirely by precalculated_person_properties, the parent would produce+ N separate subqueries joined by INTERSECT/UNION DISTINCT. Each subquery reads the full+ table and the set operations materialise large intermediate person sets — a common source+ of OOMs for large cohorts. We instead read the table once.++ Two shapes qualify, tried in order:+ 1. Flat AND/OR of leaves → count matched conditions per person (HAVING countIf >= N).+ 2. Arbitrarily nested AND/OR of leaves → evaluate the boolean tree per person in the+ HAVING (maxIf/countIf leaves combined with AND/OR).- When the cohort qualifies, we instead do one scan and count matching conditions per- person. The peak group count is unchanged, but collapsing N full-table scans into one- with a tiny per-group argMax(Bool) state (rather than N materialized person-UUID sets)- is what avoids the OOM.+ Shape 1 is a strict subset of shape 2 (the tree would produce an equivalent AND/OR of+ per-leaf maxIf predicates), but it's kept as a faster path: one `countIf >= N` over the+ whole group is cheaper than N separate `maxIf` leaves.- Cohorts with mixed conditions (behavioral, dynamic-cohort, negation, deeply nested- groups, or nested boolean groups whose operator differs from the top level) fall through- to the parent's multi-subquery path unchanged.+ Cohorts with any non-person leaf (behavioral, dynamic-cohort, static-cohort) or a negated+ person property fall through to the parent's multi-subquery path unchanged."""if self.property_groups is not None:result = self._collect_person_property_hashes(self.property_groups)if result is not None:hashes, operator = resultreturn self._build_count_match_query(hashes, operator)+ tree_query = self._build_boolean_tree_query(self.property_groups)+ if tree_query is not None:+ return tree_queryreturn super()._get_conditions()def get_static_cohort_condition(self, prop: Property) -> ast.SelectQuery:diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.pyindex 031839265f27..fbc2a3d144f5 100644--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py@@ -1404,22 +1404,15 @@ class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):hogql_query = HogQLRealtimeCohortQuery(cohort=cohort)query_str = hogql_query.query_str("clickhouse")- # Should have 1 IN clause for ALL merged email properties (yahoo + protonmail + live = 3 hashes)- in_clause_count = query_str.lower().count("in(precalculated_person_properties.condition,")- self.assertEqual(in_clause_count, 1, "Should have exactly 1 IN clause for all merged email properties")-- # Verify the IN clause has a tuple with 3 values (all 3 hashes merged)- # The pattern will be: tuple(%(hogql_val_X)s, %(hogql_val_Y)s, %(hogql_val_Z)s)+ # The whole nested boolean is now evaluated in one scan's HAVING — no set operations.+ self.assertNotIn("UNION DISTINCT", query_str)+ self.assertNotIn("INTERSECT DISTINCT", query_str)+ self.assertIn("maxif(latest_matches", query_str.lower())- # Match tuple with exactly 3 comma-separated parameter placeholders+ # The 3 sibling email properties (yahoo + protonmail + live) still merge into one OR leaf,+ # so its IN tuple has exactly 3 values.tuple_pattern = r"tuple\(%\(hogql_val_\d+\)s,\s*%\(hogql_val_\d+\)s,\s*%\(hogql_val_\d+\)s\)"- self.assertRegex(query_str, tuple_pattern, "IN clause should have tuple with 3 values")-- # Should use UNION DISTINCT since we have multiple top-level groups- self.assertIn("UNION DISTINCT", query_str)-- # Should have INTERSECT DISTINCT for the AND group (email + name)- self.assertIn("INTERSECT DISTINCT", query_str)+ self.assertRegex(query_str, tuple_pattern, "merged email leaf should be a 3-value IN tuple")def test_properties_without_condition_hash_are_not_merged(self) -> None:"""@@ -1819,10 +1812,10 @@ class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):["greaterorequals(countif(equals(latest_matches, 1))"],),(- # (X OR Y) AND (A OR B): nested OR groups under a top-level AND must NOT collapse- # into a flat `>= 4` threshold (that would require all four). Falls through so the- # parent path expresses `(X OR Y) INTERSECT (A OR B)` correctly.- "nested_or_under_and_falls_through",+ # (X OR Y) AND (A OR B): nested OR groups under a top-level AND. The boolean-tree+ # single scan expresses this as `maxIf(...) = 1 AND maxIf(...) = 1`, NOT a flat+ # `>= 4` threshold (which would wrongly require all four).+ "nested_or_under_and_single_scan",{"type": "AND","values": [@@ -1875,12 +1868,12 @@ class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):}],},- ["intersect distinct"],- ["greaterorequals(countif(equals(latest_matches, 1)), 4)"],+ ["maxif(latest_matches"],+ ["intersect distinct", "union distinct"],),(- # Deeply nested AND-of-AND with different-key (non-mergeable) props → falls through- "deeply_nested_falls_through",+ # Deeply nested AND-of-AND with different-key (non-mergeable) props → single scan+ "deeply_nested_single_scan",{"type": "AND","values": [@@ -1933,8 +1926,8 @@ class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):}],},- ["intersect distinct"],- ["greaterorequals(countif(equals(latest_matches, 1))"],+ ["maxif(latest_matches"],+ ["intersect distinct", "union distinct"],),])@@ -2138,6 +2131,268 @@ class TestHogQLRealtimeCohortQuery(ClickhouseTestMixin, APIBaseTest):finally:sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")+ def test_nested_boolean_single_scan_membership(self) -> None:+ """Execute the nested-boolean single scan and assert membership for `(A AND B) OR (C AND D)`.++ This shape used to fall through to the INTERSECT/UNION DISTINCT path (the OOM source); the+ boolean-tree single scan must return the same person set without those set operations.+ """+ sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)+ sync_execute("TRUNCATE TABLE precalculated_person_properties")+ try:+ ab, cd, c_only, a_only = uuid4(), uuid4(), uuid4(), uuid4()+ self._seed_precalculated_person_properties(+ [+ (ab, "exec_A", True),+ (ab, "exec_B", True), # matches first branch+ (cd, "exec_C", True),+ (cd, "exec_D", True), # matches second branch+ (c_only, "exec_C", True), # half of second branch only+ (a_only, "exec_A", True), # half of first branch only+ ]+ )++ def leaf(key: str, condition_hash: str) -> dict:+ return {+ "key": key,+ "type": "person",+ "value": "x",+ "negation": False,+ "operator": "exact",+ "conditionHash": condition_hash,+ }++ cohort = Cohort.objects.create(+ team=self.team,+ name="nested",+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {+ "type": "OR",+ "values": [+ {"type": "AND", "values": [leaf("k1", "exec_A"), leaf("k2", "exec_B")]},+ {"type": "AND", "values": [leaf("k3", "exec_C"), leaf("k4", "exec_D")]},+ ],+ }+ ],+ }+ },+ )+ query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse")+ self.assertNotIn("INTERSECT DISTINCT", query_str)+ self.assertNotIn("UNION DISTINCT", query_str)++ members = self._realtime_cohort_members(cohort)+ self.assertIn(str(ab), members) # A AND B+ self.assertIn(str(cd), members) # C AND D+ self.assertNotIn(str(c_only), members) # C without D+ self.assertNotIn(str(a_only), members) # A without B+ finally:+ sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")++ def test_nested_boolean_single_scan_and_merged_leaf_membership(self) -> None:+ """Exercise the AND-merged leaf (countIf(...) = N) inside the boolean tree.++ `(email~@gmail AND email~.com) AND plan` nested under a top-level OR: the same-key email+ pair merges into one AND-merged leaf, which the tree must render as+ `countIf(latest_matches = 1 AND condition IN (g, c)) = 2` — a person matching only one of+ the two merged hashes must be excluded.+ """++ def leaf(key: str, value: str, operator: str, condition_hash: str) -> dict:+ return {+ "key": key,+ "type": "person",+ "value": value,+ "negation": False,+ "operator": operator,+ "conditionHash": condition_hash,+ }++ sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)+ sync_execute("TRUNCATE TABLE precalculated_person_properties")+ try:+ both, one_only, country_only = uuid4(), uuid4(), uuid4()+ self._seed_precalculated_person_properties(+ [+ (both, "m_g", True),+ (both, "m_c", True),+ (both, "plan_x", True), # matches the AND-merged email pair + plan+ (one_only, "m_g", True),+ (one_only, "m_c", False),+ (one_only, "plan_x", True), # missed one of the merged hashes+ (country_only, "country_y", True), # matches the other OR branch+ ]+ )+ cohort = Cohort.objects.create(+ team=self.team,+ name="and-merged",+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {+ "type": "OR",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ leaf("email", "@gmail", "icontains", "m_g"),+ leaf("email", ".com", "icontains", "m_c"),+ ],+ },+ {"type": "AND", "values": [leaf("plan", "x", "exact", "plan_x")]},+ ],+ },+ {"type": "AND", "values": [leaf("country", "y", "exact", "country_y")]},+ ],+ }+ ],+ }+ },+ )+ query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse").lower()+ self.assertNotIn("intersect distinct", query_str)+ self.assertNotIn("union distinct", query_str)+ self.assertIn("countif(", query_str) # AND-merged leaf renders as countIf(...) = N++ members = self._realtime_cohort_members(cohort)+ self.assertIn(str(both), members) # matched both merged hashes + plan+ self.assertIn(str(country_only), members) # other OR branch+ self.assertNotIn(str(one_only), members) # missed one merged hash → AND-merged leaf fails+ finally:+ sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")++ def test_nested_negated_leaf_falls_through(self) -> None:+ """A negated leaf buried in a nested group must force the parent multi-subquery path.++ The single-scan tree can't express negation, so any nested negated person property must+ make `_build_boolean_tree_query` return None and fall through — not silently drop the+ negation and produce a wrong cohort.+ """+ cohort = Cohort.objects.create(+ team=self.team,+ name="nested-negated",+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {+ "type": "OR",+ "values": [+ {+ "type": "OR",+ "values": [+ {+ "key": "email",+ "type": "person",+ "value": "@x",+ "negation": False,+ "operator": "icontains",+ "conditionHash": "nn_h1",+ }+ ],+ },+ {+ "type": "AND",+ "values": [+ {+ "key": "plan",+ "type": "person",+ "value": "A",+ "negation": False,+ "operator": "exact",+ "conditionHash": "nn_h2",+ },+ {+ "key": "name",+ "type": "person",+ "value": "spam",+ "negation": True,+ "operator": "icontains",+ "conditionHash": "nn_h3",+ },+ ],+ },+ ],+ }+ ],+ }+ },+ )+ query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse").lower()+ # Tree path must NOT fire — a negated leaf forces the parent set-operation path.+ self.assertNotIn("maxif(latest_matches", query_str)++ def test_nested_or_under_and_membership(self) -> None:+ """Execution test for `(X OR Y) AND (A OR B)` — the shape flagged in the parameterized+ test as the threshold-flip risk.++ The tree renders it as `maxIf(...X,Y...) = 1 AND maxIf(...A,B...) = 1`, NOT a flat+ `countIf >= 4` threshold that would wrongly require all four. A person matching only X+ and A (one from each OR branch) must be IN; one matching X and Y but not A or B must be OUT.+ """+ sync_execute(_PRECALCULATED_PERSON_PROPERTIES_TEST_DDL)+ sync_execute("TRUNCATE TABLE precalculated_person_properties")+ try:+ x_and_a, x_and_y, a_and_b, neither = uuid4(), uuid4(), uuid4(), uuid4()+ self._seed_precalculated_person_properties(+ [+ (x_and_a, "or_X", True),+ (x_and_a, "or_A", True), # one from each OR branch → should match+ (x_and_y, "or_X", True),+ (x_and_y, "or_Y", True), # both from first branch, none from second → no match+ (a_and_b, "or_A", True),+ (a_and_b, "or_B", True), # both from second branch, none from first → no match+ (neither, "or_X", False), # matches nothing+ ]+ )++ def leaf(key: str, condition_hash: str) -> dict:+ return {+ "key": key,+ "type": "person",+ "value": "x",+ "negation": False,+ "operator": "exact",+ "conditionHash": condition_hash,+ }++ cohort = Cohort.objects.create(+ team=self.team,+ name="or-under-and",+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {+ "type": "AND",+ "values": [+ {"type": "OR", "values": [leaf("k1", "or_X"), leaf("k2", "or_Y")]},+ {"type": "OR", "values": [leaf("k3", "or_A"), leaf("k4", "or_B")]},+ ],+ }+ ],+ }+ },+ )+ query_str = HogQLRealtimeCohortQuery(cohort=cohort).query_str("clickhouse")+ self.assertNotIn("INTERSECT DISTINCT", query_str)+ self.assertNotIn("UNION DISTINCT", query_str)++ members = self._realtime_cohort_members(cohort)+ self.assertIn(str(x_and_a), members) # one from each OR branch+ self.assertNotIn(str(x_and_y), members) # both from first branch only+ self.assertNotIn(str(a_and_b), members) # both from second branch only+ self.assertNotIn(str(neither), members) # no match+ finally:+ sync_execute("DROP TABLE IF EXISTS precalculated_person_properties")+@parameterized.expand([# A merged child's internal boolean type must match the top-level operator to flatten.diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.pyindex f0b736c0231c..c638c9a607ca 100644--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py@@ -35,6 +35,9 @@ if TYPE_CHECKING:# ConfigurationFLUSH_BATCH_SIZE = int(os.environ.get("COHORT_KAFKA_FLUSH_BATCH_SIZE", "1000"))DURATION_UPDATE_RELATIVE_THRESHOLD = 0.25 # Only update duration when change exceeds 25%+# Spill the cohort-membership GROUP BY to disk once it exceeds this fraction of the query's+# memory limit, instead of OOMing. See build_final_query.+EXTERNAL_GROUP_BY_MEMORY_RATIO = 0.5# Cohort calculation timing histogramsCOHORT_CALCULATION_TOTAL_DURATION_HISTOGRAM = Histogram(@@ -302,7 +305,16 @@ def build_final_query(current_members_sql: str) -> str:HAVING status = 'entered') previous_members ON current_matches.id = previous_members.person_idWHERE (previous_members.person_id IS NULL) OR (current_matches.id IS NULL)- SETTINGS join_use_nulls = 1+ SETTINGS+ join_use_nulls = 1,+ -- Every GROUP BY here aggregates by person_id, which is in no source table's sort+ -- key, so it builds a full in-memory hash table. On large cohorts — both the+ -- single-scan path and the INTERSECT/UNION DISTINCT fall-through — this can exhaust+ -- the query memory limit and OOM. Spill to disk past a fraction of that limit instead+ -- of failing; this is an offline job, so slower-but-completes is the right trade-off.+ -- memory_efficient bounds the distributed merge step too.+ max_bytes_ratio_before_external_group_by = {EXTERNAL_GROUP_BY_MEMORY_RATIO},+ distributed_aggregation_memory_efficient = 1FORMAT JSONEachRow"""diff --git a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.pyindex 2feba623bb00..519918b162c1 100644--- a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py@@ -1711,6 +1711,11 @@ class TestFinalQueryMembershipStatuses:# The inner subquery is embedded correctlyassert "SELECT id FROM nowhere" in sql+ # GROUP BY spill settings (the OOM fix) must survive future edits to build_final_query+ assert "join_use_nulls = 1" in sql+ assert "max_bytes_ratio_before_external_group_by = 0.5" in sql+ assert "distributed_aggregation_memory_efficient = 1" in sql+def test_if_expression_matches_full_outer_join_semantics(self):"""The if() expression and WHERE clause encode the FULL OUTER JOIN membership diff contract.