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): stop cohort list from reading deprecated team columns (#92407)

posthog[bot]933730939b44
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 74ef0d5fd27e..6829876c13d4 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -74,7 +74,7 @@ from posthog.models.filters.filter import Filter
from posthog.models.filters.utils import earliest_timestamp_func
from posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist
from posthog.models.property.property import Property
-from posthog.models.team.team import Team
+from posthog.models.team.team import DEPRECATED_ATTRS, Team
from posthog.models.utils import UUIDT
from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.ph_client import feature_enabled_or_false
@@ -1695,9 +1695,21 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
if is_basic_list:
queryset = queryset.defer("query")
- # `created_by` and `team` are forward FKs, so `select_related` JOINs them in
- # one query instead of the two extra round-trips `prefetch_related` costs.
- queryset = queryset.select_related("created_by", "team")
+ # `created_by` and `team` are forward FKs, so `select_related` JOINs them in one query
+ # instead of the extra round-trips `prefetch_related` costs. The list serializer never
+ # reads `cohort.team`, so the list path only `select_related`s `created_by`. Project
+ # scoping still JOINs `posthog_team` to filter on `project_id`, but without hydration that
+ # JOIN reads only the id — not the full team payload (heavy JSON and array columns) each
+ # cohort row would otherwise carry. Detail and write actions do read `cohort.team`, so they
+ # keep the hydrating JOIN but re-apply `.defer(*DEPRECATED_ATTRS)` — mirroring
+ # `TeamManager`'s lazy-load defer — so the deprecated taxonomy columns, which TOAST out to
+ # megabytes per team, stay off it.
+ if self.action == "list":
+ queryset = queryset.select_related("created_by")
+ else:
+ queryset = queryset.select_related("created_by", "team").defer(
+ *(f"team__{attr}" for attr in DEPRECATED_ATTRS)
+ )
# `experiment_set` is a reverse relation (a prefetch) and the per-row correlated
# subquery over CohortCalculationHistory only feeds `last_error_message`. The basic
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 36bfcee08eab..1f25f7386aeb 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -364,6 +364,62 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
response = self.client.get(f"/api/projects/{self.team.id}/cohorts")
assert len(response.json()["results"]) == 3
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_list_cohorts_does_not_hydrate_team(self, patch_calculate_cohort, patch_capture):
+ # The list serializer never reads `cohort.team`, so the cohort SELECT must not hydrate the
+ # team payload — the heavy JSON and array columns each row would otherwise carry. Project
+ # scoping still JOINs `posthog_team` to filter on `project_id`, so guard the payload columns
+ # specifically rather than the JOIN. The nplus1 query-count guard would not catch a re-added
+ # `select_related("team")`, since hydrating columns onto that existing JOIN adds no query,
+ # so assert the SQL directly.
+ self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "whatever", "groups": [{"properties": {"team_id": 5}}]},
+ )
+
+ with capture_db_queries() as context:
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts")
+ assert response.status_code == status.HTTP_200_OK
+
+ cohort_queries = [q["sql"] for q in context.captured_queries if 'FROM "posthog_cohort"' in q["sql"]]
+ assert cohort_queries, "expected the list to run a query against posthog_cohort"
+ # These team payload columns are never part of the cohort filter, so their presence would
+ # mean the team row is hydrated onto each cohort row.
+ for sql in cohort_queries:
+ for column in ("test_account_filters", "session_replay_config"):
+ assert f'posthog_team"."{column}"' not in sql
+
+ @patch("posthog.api.cohort.report_user_action")
+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")
+ def test_detail_cohort_defers_deprecated_team_columns(self, patch_calculate_cohort, patch_capture):
+ # Detail and write actions read `cohort.team`, so they keep the hydrating `select_related("team")`
+ # JOIN. They must re-apply `.defer(*DEPRECATED_ATTRS)` the way `TeamManager` does on lazy loads, or
+ # every retrieve re-reads the deprecated taxonomy columns (`event_names` and siblings) that TOAST
+ # out to megabytes per team. `test_list_cohorts_does_not_hydrate_team` guards only the list query
+ # and only non-deprecated columns, so it cannot catch a dropped defer here. Assert the SQL directly.
+ cohort_id = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "whatever", "groups": [{"properties": {"team_id": 5}}]},
+ ).json()["id"]
+
+ with capture_db_queries() as context:
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}")
+ assert response.status_code == status.HTTP_200_OK
+
+ # The query that hydrates the team carries a non-deprecated team column; find it to make sure the
+ # detail path still JOINs and hydrates the team, so the deprecated-column check below is not vacuous.
+ team_hydrating_queries = [
+ q["sql"]
+ for q in context.captured_queries
+ if 'FROM "posthog_cohort"' in q["sql"] and 'posthog_team"."test_account_filters"' in q["sql"]
+ ]
+ assert team_hydrating_queries, "expected the detail fetch to hydrate the team onto the cohort row"
+ # `event_names` is a deprecated taxonomy column that TOASTs out to megabytes. The defer keeps it off
+ # the hydrated team row; dropping the defer would pull it back in.
+ for sql in team_hydrating_queries:
+ assert 'posthog_team"."event_names"' not in sql
+
@parameterized.expand(
[
# A group with none of properties/action_id/event_id used to raise an uncaught