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(cohorts): dedup static cohort membership in joins (#75203)

posthog[bot]af47bac8641c
diff --git a/posthog/hogql/transforms/in_cohort.py b/posthog/hogql/transforms/in_cohort.py
index 08ed949acebf..1bf7ab8a8281 100644
--- a/posthog/hogql/transforms/in_cohort.py
+++ b/posthog/hogql/transforms/in_cohort.py
@@ -214,10 +214,12 @@ class MultipleInCohortResolver(TraversingVisitor):
parts: list[ast.SelectQuery | ast.SelectSetQuery] = []
if static_cohorts:
+ # DISTINCT because duplicate membership rows survive in `person_static_cohort` (its sort
+ # key carries a per-row UUID), and each one would fan out through the LEFT JOIN below.
parts.append(
parse_select(
"""
- SELECT person_id AS cohort_person_id, 1 AS matched, cohort_id
+ SELECT DISTINCT person_id AS cohort_person_id, 1 AS matched, cohort_id
FROM static_cohort_people
WHERE {clause}
""",
@@ -403,7 +405,10 @@ class InCohortResolver(TraversingVisitor):
)
else:
if is_static:
- sql = "(SELECT person_id, 1 as matched FROM static_cohort_people WHERE cohort_id = {cohort_id})"
+ # DISTINCT because `person_static_cohort` keeps a per-row UUID in its sort key, so
+ # ReplacingMergeTree can't collapse repeated inserts of the same member. Without it
+ # every duplicate membership row fans out through the LEFT JOIN below.
+ sql = "(SELECT DISTINCT person_id, 1 as matched FROM static_cohort_people WHERE cohort_id = {cohort_id})"
elif version is not None:
sql = "(SELECT person_id, 1 as matched FROM raw_cohort_people WHERE cohort_id = {cohort_id} AND version = {version})"
else:
diff --git a/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr b/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr
index 5d3a2ce1793c..1c5e362c05a7 100644
--- a/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr
+++ b/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr
@@ -26,7 +26,7 @@
-- ClickHouse
SELECT events.event AS event
FROM events LEFT JOIN (
- SELECT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_id
+ SELECT DISTINCT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_id
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), in(person_static_cohort.cohort_id, [1, 2, 3, 4, 5 /* ... */]))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)
WHERE and(equals(events.team_id, 99999), equals(__in_cohort.matched, 1))
@@ -36,7 +36,7 @@
-- HogQL
SELECT event
FROM events LEFT JOIN (
- SELECT person_id AS cohort_person_id, 1 AS matched, cohort_id
+ SELECT DISTINCT person_id AS cohort_person_id, 1 AS matched, cohort_id
FROM static_cohort_people
WHERE in(cohort_id, [1, 2, 3, 4, 5 /* ... */])) AS __in_cohort ON equals(__in_cohort.cohort_person_id, person_id)
WHERE and(equals(1, 1), equals(__in_cohort.matched, 1))
@@ -48,7 +48,7 @@
-- ClickHouse
SELECT events.event AS event
FROM events LEFT JOIN (
- SELECT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_id
+ SELECT DISTINCT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_id
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), in(person_static_cohort.cohort_id, [1, 2, 3, 4, 5 /* ... */]))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)
WHERE and(equals(events.team_id, 99999), equals(__in_cohort.matched, 1))
@@ -58,7 +58,7 @@
-- HogQL
SELECT event
FROM events LEFT JOIN (
- SELECT person_id AS cohort_person_id, 1 AS matched, cohort_id
+ SELECT DISTINCT person_id AS cohort_person_id, 1 AS matched, cohort_id
FROM static_cohort_people
WHERE in(cohort_id, [1, 2, 3, 4, 5 /* ... */])) AS __in_cohort ON equals(__in_cohort.cohort_person_id, person_id)
WHERE and(equals(1, 1), equals(__in_cohort.matched, 1))
@@ -70,7 +70,7 @@
-- ClickHouse
SELECT events.event AS event
FROM events LEFT JOIN (
- SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) 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))
@@ -80,7 +80,7 @@
-- HogQL
SELECT event
FROM events LEFT JOIN (
- SELECT person_id, 1 AS matched
+ SELECT DISTINCT person_id, 1 AS matched
FROM static_cohort_people
WHERE equals(cohort_id, XX)) AS in_cohort__XX ON equals(in_cohort__XX.person_id, person_id)
WHERE equals(in_cohort__XX.matched, 1)
@@ -144,7 +144,7 @@
-- ClickHouse
SELECT events.event AS event
FROM events LEFT JOIN (
- SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) 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))
@@ -154,7 +154,7 @@
-- HogQL
SELECT event
FROM events LEFT JOIN (
- SELECT person_id, 1 AS matched
+ SELECT DISTINCT person_id, 1 AS matched
FROM static_cohort_people
WHERE equals(cohort_id, XX)) AS in_cohort__XX ON equals(in_cohort__XX.person_id, person_id)
WHERE equals(in_cohort__XX.matched, 1)
@@ -166,7 +166,7 @@
-- ClickHouse
SELECT events.event AS event
FROM events LEFT JOIN (
- SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) 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))
@@ -176,7 +176,7 @@
-- HogQL
SELECT event
FROM events LEFT JOIN (
- SELECT person_id, 1 AS matched
+ SELECT DISTINCT person_id, 1 AS matched
FROM static_cohort_people
WHERE equals(cohort_id, XX)) AS in_cohort__XX ON equals(in_cohort__XX.person_id, person_id)
WHERE equals(in_cohort__XX.matched, 1)
@@ -188,7 +188,7 @@
-- ClickHouse
SELECT events.event AS event
FROM events LEFT JOIN (
- SELECT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_id
+ SELECT DISTINCT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_id
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), in(person_static_cohort.cohort_id, [1, 2, 3, 4, 5 /* ... */])) UNION ALL
SELECT id AS cohort_person_id, 1 AS matched, 99999 AS cohort_id
@@ -213,7 +213,7 @@
-- HogQL
SELECT event
FROM events LEFT JOIN (
- SELECT person_id AS cohort_person_id, 1 AS matched, cohort_id
+ SELECT DISTINCT person_id AS cohort_person_id, 1 AS matched, cohort_id
FROM static_cohort_people
WHERE in(cohort_id, [1, 2, 3, 4, 5 /* ... */]) UNION ALL
SELECT id AS cohort_person_id, 1 AS matched, 99999 AS cohort_id
@@ -382,7 +382,7 @@
-- ClickHouse
SELECT events.event AS event
FROM events LEFT JOIN (
- SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) 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))
@@ -392,7 +392,7 @@
-- HogQL
SELECT event
FROM events LEFT JOIN (
- SELECT person_id, 1 AS matched
+ SELECT DISTINCT person_id, 1 AS matched
FROM static_cohort_people
WHERE equals(cohort_id, XX)) 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'))
diff --git a/posthog/hogql/transforms/test/test_in_cohort.py b/posthog/hogql/transforms/test/test_in_cohort.py
index 9ea6af528544..5cb92ba70bc1 100644
--- a/posthog/hogql/transforms/test/test_in_cohort.py
+++ b/posthog/hogql/transforms/test/test_in_cohort.py
@@ -6,6 +6,8 @@ from posthog.test.base import BaseTest, QueryMatchingTest, _create_event, _creat
from django.conf import settings
from django.test import override_settings
+from parameterized import parameterized
+
from posthog.schema import HogQLQueryModifiers, InCohortVia, InlineCohortCalculation
from posthog.hogql import ast
@@ -244,6 +246,34 @@ class TestInCohort(EventsSchemaSnapshotMixin, BaseTest):
)
self.assertEqual(str(e.exception), "Could not find a cohort with the name 'blabla'")
+ @parameterized.expand([(InCohortVia.LEFTJOIN,), (InCohortVia.LEFTJOIN_CONJOINED,)])
+ @override_settings(PERSON_ON_EVENTS_OVERRIDE=True, PERSON_ON_EVENTS_V2_OVERRIDE=False)
+ def test_static_cohort_duplicate_membership_rows_do_not_fan_out(self, in_cohort_via: InCohortVia):
+ # person_static_cohort keeps a per-row UUID in its sort key, so ReplacingMergeTree never
+ # collapses repeated inserts of the same member. Without dedup in the join, each duplicate
+ # row multiplies the matched events.
+ random_uuid = f"RANDOM_TEST_ID::{UUIDT()}"
+ person = _create_person(
+ properties={"$os": "Chrome"},
+ team=self.team,
+ distinct_ids=["person1"],
+ is_identified=True,
+ )
+ _create_event(distinct_id="person1", event=random_uuid, team=self.team)
+ flush_persons_and_events()
+
+ cohort = Cohort.objects.create(team=self.team, is_static=True)
+ for _ in range(3):
+ insert_static_cohort([person.uuid], cohort.pk, team_id=self.team.pk)
+
+ response = execute_hogql_query(
+ f"SELECT event FROM events WHERE person_id IN COHORT {cohort.pk} AND event = '{random_uuid}'",
+ self.team,
+ modifiers=HogQLQueryModifiers(inCohortVia=in_cohort_via),
+ pretty=False,
+ )
+ assert len(response.results or []) == 1
+
class TestInlineCohortLeftjoin(EventsSchemaSnapshotMixin, QueryMatchingTest, BaseTest):
maxDiff = None
diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.py
index b043866eaa6c..a58f22123f7f 100644
--- a/posthog/hogql_queries/hogql_cohort_query.py
+++ b/posthog/hogql_queries/hogql_cohort_query.py
@@ -592,7 +592,9 @@ class HogQLCohortQuery:
return cast(
ast.SelectQuery,
parse_select(
- "SELECT person_id as id FROM static_cohort_people WHERE cohort_id = {cohort_id} AND team_id = {team_id}",
+ # DISTINCT because `person_static_cohort` can hold repeated rows for the same member
+ # (its sort key includes a per-row UUID), and this select is joined into other queries.
+ "SELECT DISTINCT person_id as id FROM static_cohort_people WHERE cohort_id = {cohort_id} AND team_id = {team_id}",
{"cohort_id": ast.Constant(value=cohort.pk), "team_id": ast.Constant(value=self.team.pk)},
),
)
diff --git a/posthog/session_recordings/queries/sub_queries/cohort_subquery.py b/posthog/session_recordings/queries/sub_queries/cohort_subquery.py
index a04456819c1e..658a7f653a81 100644
--- a/posthog/session_recordings/queries/sub_queries/cohort_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/cohort_subquery.py
@@ -92,7 +92,9 @@ class CohortPropertyGroupsSubQuery(SessionRecordingsListingBaseQuery):
# HogQL automatically adds team_id filter, so we only need cohort_id (and version)
if is_static:
- subquery = f"(SELECT person_id, 1 AS matched FROM static_cohort_people WHERE cohort_id = {{{cohort_id_placeholder}}})"
+ # DISTINCT because `person_static_cohort` can hold repeated rows for the same member
+ # (its sort key includes a per-row UUID), which would fan out through the LEFT JOIN.
+ subquery = f"(SELECT DISTINCT person_id, 1 AS matched FROM static_cohort_people WHERE cohort_id = {{{cohort_id_placeholder}}})"
else:
version_placeholder = f"version_{idx}"
placeholders[version_placeholder] = ast.Constant(value=version)
diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr
index e60d7ed3f349..498ea7c00b76 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr
+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr
@@ -688,7 +688,7 @@
GROUP BY person_distinct_id2.distinct_id
HAVING equals(is_deleted, 0)) AS pdi
LEFT JOIN
- (SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ (SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)
WHERE equals(cohort_0.matched, 1))))
@@ -743,7 +743,7 @@
GROUP BY person_distinct_id2.distinct_id
HAVING equals(is_deleted, 0)) AS pdi
LEFT JOIN
- (SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ (SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)
WHERE notEquals(ifNull(cohort_0.matched, 0), 1))))
@@ -912,7 +912,7 @@
FROM cohortpeople
WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)
LEFT JOIN
- (SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ (SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))) AS cohort_1 ON equals(cohort_1.person_id, pdi.person_id)
WHERE and(notEquals(ifNull(cohort_0.matched, 0), 1), notEquals(ifNull(cohort_1.matched, 0), 1)))))
@@ -971,7 +971,7 @@
FROM cohortpeople
WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)
LEFT JOIN
- (SELECT person_static_cohort.person_id AS person_id, 1 AS matched
+ (SELECT DISTINCT person_static_cohort.person_id AS person_id, 1 AS matched
FROM person_static_cohort
WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))) AS cohort_1 ON equals(cohort_1.person_id, pdi.person_id)
WHERE and(notEquals(ifNull(cohort_0.matched, 0), 1), notEquals(ifNull(cohort_1.matched, 0), 1)))))
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index a6f06c4c1b36..85267ce12d29 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -993,9 +993,9 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
Trusts the pairs — see the tenant-isolation contract on
``insert_users_list_by_id_uuid_pairs_skip_validation``. Calls the InsertCohortMembers RPC.
- ClickHouse inserts (if requested) exclude persons already in the cohort
- because the person_static_cohort table's ORDER BY includes a per-row UUID,
- preventing ReplacingMergeTree from deduplicating repeated inserts.
+ Duplicates have to be kept out of person_static_cohort by the writer: the table's ORDER BY
+ includes a per-row UUID, so ReplacingMergeTree never collapses repeated inserts. Hence both
+ the within-batch dedup below and the existing-member check before the ClickHouse insert.
"""
from posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE
@@ -1004,8 +1004,16 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
if not id_uuid_pairs:
return
- person_ids = [person_id for person_id, _ in id_uuid_pairs]
- person_uuids = [person_uuid for _, person_uuid in id_uuid_pairs]
+ seen_uuids: set[str] = set()
+ deduped_pairs: list[tuple[int, str]] = []
+ for person_id, person_uuid in id_uuid_pairs:
+ if person_uuid in seen_uuids:
+ continue
+ seen_uuids.add(person_uuid)
+ deduped_pairs.append((person_id, person_uuid))
+
+ person_ids = [person_id for person_id, _ in deduped_pairs]
+ person_uuids = [person_uuid for _, person_uuid in deduped_pairs]
if insert_in_clickhouse:
existing_uuids = self._get_existing_ch_member_uuids(person_uuids, team_id, PERSON_STATIC_COHORT_TABLE)
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index bb2ec59053d9..236d2439dae7 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -1336,7 +1336,7 @@ def insert_cohort_people_into_pg(cohort: Cohort, *, team_id: int):
def fetch_batch(cursor: str, batch_size: int) -> tuple[list[str], str]:
# nosemgrep: clickhouse-fstring-param-audit - table name from constant, values parameterized
rows = sync_execute(
- f"SELECT person_id FROM {PERSON_STATIC_COHORT_TABLE} WHERE team_id = %(team_id)s AND cohort_id = %(cohort_id)s AND person_id > %(cursor)s ORDER BY person_id LIMIT %(limit)s",
+ f"SELECT DISTINCT person_id FROM {PERSON_STATIC_COHORT_TABLE} WHERE team_id = %(team_id)s AND cohort_id = %(cohort_id)s AND person_id > %(cursor)s ORDER BY person_id LIMIT %(limit)s",
{
"cohort_id": cohort.pk,
"team_id": team_id,