Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(hogql): dedup repeated cohort left join in one scope (#66994)

Thomas Obermüllerc53f8a680c53
diff --git a/posthog/hogql/transforms/in_cohort.py b/posthog/hogql/transforms/in_cohort.py
index e70dfe9f1441..08ed949acebf 100644
--- a/posthog/hogql/transforms/in_cohort.py
+++ b/posthog/hogql/transforms/in_cohort.py
@@ -378,7 +378,10 @@ class InCohortResolver(TraversingVisitor):
must_add_join = True
last_join = select.select_from
while last_join:
- if isinstance(last_join.table, ast.Field) and last_join.table.chain[0] == f"in_cohort__{cohort_id}":
+ # Dedup on the join alias: a second `IN COHORT <id>` in the same scope must reuse the
+ # existing join, not add a colliding one. (The join's `table` is the cohort subquery, so
+ # the alias is the only place the `in_cohort__<id>` name lives.)
+ if last_join.alias == f"in_cohort__{cohort_id}":
must_add_join = False
break
if last_join.next_join:
@@ -386,6 +389,10 @@ class InCohortResolver(TraversingVisitor):
else:
break
+ current_scope = self.stack[-1].type
+ if current_scope is None:
+ raise QueryError("Could not resolve current select scope")
+
if must_add_join:
inline_ast = inline_cohort_query(cohort_id, is_static, version, self.context)
subquery: ast.Expr
@@ -421,9 +428,6 @@ class InCohortResolver(TraversingVisitor):
constraint_type="ON",
),
)
- current_scope = self.stack[-1].type
- if current_scope is None:
- raise QueryError("Could not resolve current select scope")
new_join = cast(
ast.JoinExpr,
resolve_types(
@@ -454,9 +458,6 @@ class InCohortResolver(TraversingVisitor):
else:
select.select_from = new_join
- if current_scope is None:
- raise ValueError("Expected current scope when resolving cohort comparison")
-
compare.op = ast.CompareOperationOp.NotEq if negative else ast.CompareOperationOp.Eq
compare.left = resolve_types(
ast.Field(chain=[f"in_cohort__{cohort_id}", "matched"]),
diff --git a/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr b/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr
index 24d7d7fe28ee..5d3a2ce1793c 100644
--- a/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr
+++ b/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr
@@ -113,6 +113,32 @@
LIMIT 100
'''
# ---
+# name: TestInCohort.test_in_cohort_same_cohort_referenced_twice
+ '''
+ -- ClickHouse
+ SELECT events.event AS event
+ FROM events LEFT JOIN (
+ SELECT cohortpeople.person_id AS person_id, 1 AS matched
+ FROM cohortpeople
+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, XX))
+ GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version
+ HAVING greater(sum(cohortpeople.sign), 0)) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)
+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1), equals(events.event, %(hogql_val_0)s), equals(in_cohort__XX.matched, 1))
+ 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, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0
+
+ -- HogQL
+ SELECT event
+ FROM events LEFT JOIN (
+ SELECT person_id, 1 AS matched
+ FROM raw_cohort_people
+ WHERE equals(cohort_id, XX)
+ GROUP BY person_id, cohort_id, version
+ HAVING greater(sum(sign), 0)) AS in_cohort__XX ON equals(in_cohort__XX.person_id, person_id)
+ WHERE and(equals(in_cohort__XX.matched, 1), equals(event, 'RANDOM_TEST_ID::UUID'), equals(in_cohort__XX.matched, 1))
+ LIMIT 100
+ '''
+# ---
# name: TestInCohort.test_in_cohort_static
'''
-- ClickHouse
diff --git a/posthog/hogql/transforms/test/test_in_cohort.py b/posthog/hogql/transforms/test/test_in_cohort.py
index c71f000986b7..0613c13dba5d 100644
--- a/posthog/hogql/transforms/test/test_in_cohort.py
+++ b/posthog/hogql/transforms/test/test_in_cohort.py
@@ -54,6 +54,27 @@ class TestInCohort(BaseTest):
self.assertEqual(len(response.results or []), 1)
self.assertEqual((response.results or [])[0][0], random_uuid)
+ @pytest.mark.usefixtures("unittest_snapshot")
+ @override_settings(PERSON_ON_EVENTS_OVERRIDE=True, PERSON_ON_EVENTS_V2_OVERRIDE=False)
+ def test_in_cohort_same_cohort_referenced_twice(self):
+ # Two references to the same cohort in one scope must compile to a single LEFT JOIN,
+ # not collide on the in_cohort__<id> alias. The snapshot locks in that single join.
+ random_uuid = self._create_random_events()
+ cohort = Cohort.objects.create(
+ team=self.team,
+ groups=[{"properties": [{"key": "$os", "value": "Chrome", "type": "person"}]}],
+ )
+ recalculate_cohortpeople(cohort, pending_version=0, initiating_user_id=None)
+ response = execute_hogql_query(
+ f"SELECT event FROM events WHERE person_id IN COHORT {cohort.pk} AND event = '{random_uuid}' AND person_id IN COHORT {cohort.pk}",
+ self.team,
+ modifiers=HogQLQueryModifiers(inCohortVia=InCohortVia.LEFTJOIN),
+ pretty=False,
+ )
+ assert pretty_print_response_in_tests(response, self.team.pk) == self.snapshot # type: ignore
+ self.assertEqual(len(response.results or []), 1)
+ self.assertEqual((response.results or [])[0][0], random_uuid)
+
@pytest.mark.usefixtures("unittest_snapshot")
@override_settings(PERSON_ON_EVENTS_OVERRIDE=True, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_in_cohort_static(self):