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): drop redundant person join in count_cohort_members (#58843)

José Sequeira068ffe659a61
diff --git a/posthog/models/cohort/util.py b/posthog/models/cohort/util.py
index 2ea3949ec604..33450ccda55b 100644
--- a/posthog/models/cohort/util.py
+++ b/posthog/models/cohort/util.py
@@ -1449,9 +1449,7 @@ def count_cohort_members(team_id: int, cohort_id: int, *, consistency: ReadConsi
return 0
def orm_fn() -> int:
- qs = CohortPeople.objects.filter( # nosemgrep: no-direct-persons-db-orm
- cohort_id=cohort_id, person__team_id=team_id
- )
+ qs = CohortPeople.objects.filter(cohort_id=cohort_id) # nosemgrep: no-direct-persons-db-orm
if consistency == "strong":
from posthog.person_db_router import PERSONS_DB_FOR_WRITE
diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.py
index 846f22307e12..cfe842e12724 100644
--- a/posthog/test/test_cohort_model.py
+++ b/posthog/test/test_cohort_model.py
@@ -471,13 +471,19 @@ class TestCohort(BaseTest):
assert isinstance(size, int), f"Expected int, got {type(size)}: {size}"
assert size == 3, f"Expected 3 persons in cohort, got {size}"
- # Test with team leakage - person from another team should not be counted
+ # Cross-team CohortPeople rows are counted: get_static_cohort_size scopes by
+ # cohort_id (gated by an upfront `Cohort.team_id == team_id` ownership check
+ # in count_cohort_members), not by person.team_id. The previous join through
+ # posthog_person was a hot per-PK lookup on the write replica that we
+ # dropped for IOPS reasons — production cannot reach this state via the
+ # supported APIs, and a raw M2M add() like the one below is what would have
+ # had to break for a count discrepancy to surface in real traffic.
team2 = Team.objects.create(organization=self.organization)
person4 = Person.objects.create(team=team2, distinct_ids=["person4"])
cohort.people.add(person4)
size = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id)
- assert size == 3, f"Expected 3 persons from team {self.team.id}, got {size}"
+ assert size == 4, f"Expected 4 cohort rows after cross-team add, got {size}"
@pytest.mark.ee
def test_calculate_people_ch_clears_realtime_type_when_exceeding_threshold(self):