: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
fix(cohorts): fetch basic payload for cohort name lookups (#72290)
posthog[bot]2af27bd0ffd6
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 276b43229e16..f994f361a86d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2228,6 +2228,9 @@ function captureLivestream401Debug(url: string, authHeader: string | undefined,}}+/** `?basic=true` response: the serializer drops these fields (see CohortSerializer.__init__). */+export type BasicCohortType = Omit<CohortType, 'groups' | 'experiment_set' | 'last_error_message'>+const api = {cspReporting: {explain(properties: Record<string, any>): Promise<{ response: string }> {@@ -3417,6 +3420,20 @@ const api = {): Promise<CountedPaginatedResponse<CohortType>> {return await new ApiRequest().cohorts().withQueryString(toParams(params)).get()},+ async listBasic(+ params: {+ limit?: number+ offset?: number+ search?: string+ } = {}+ ): Promise<CountedPaginatedResponse<BasicCohortType>> {+ // `?basic=true` returns a trimmed payload — the narrowed BasicCohortType return type+ // keeps callers from reading a field the serializer dropped (see CohortSerializer).+ return await new ApiRequest()+ .cohorts()+ .withQueryString(toParams({ ...params, basic: true }))+ .get()+ },async getCohortPersons(cohortId: CohortType['id']): Promise<PaginatedResponse<PersonType>> {return await new ApiRequest().cohortsDetailPersons(cohortId)diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsxindex 51cadaf681e1..c3779e1aca51 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx@@ -198,8 +198,9 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomiconst { id: teamId } = currentTeamconst { excludedProperties, propertyAllowList } = propertyFilters// Opt the cohort picker into the trimmed `?basic=true` payload (drops the- // filters/query/groups JSON the picker never reads). Gated by a flag so the- // smaller response shape can be rolled out and rolled back independently.+ // query/groups/last_error_message/experiment_set fields the picker never reads;+ // `filters` is kept). Gated by a flag so the smaller response shape can be rolled+ // out and rolled back independently.const cohortsEndpointParams = featureFlags[FEATURE_FLAGS.COHORTS_TAXONOMIC_BASIC_LIST] ? { basic: true } : undefinedconst groups: TaxonomicFilterGroup[] = [{diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 1658387ecf7e..a8dd39b4fd46 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -268,7 +268,7 @@ export const FEATURE_FLAGS = {CDP_VERCEL_LOG_DRAIN: 'cdp-vercel-log-drain', // owner: #team-workflows-cdpCLEARABLE_NOTIFICATIONS: 'clearable-notifications', // owner: @jordanm-posthog #team-web-analyticsCOHORT_INLINE_CALCULATION: 'inline-cohort-calculation', // owner: #team-analytics-platform, inlines fast dynamic cohort queries instead of using precomputed cohortpeople table- COHORTS_TAXONOMIC_BASIC_LIST: 'cohorts-taxonomic-basic-list', // owner: @adamleith, picker sends ?basic=true to the cohorts list endpoint (trimmed payload: no filters/query/groups)+ COHORTS_TAXONOMIC_BASIC_LIST: 'cohorts-taxonomic-basic-list', // owner: @adamleith, picker sends ?basic=true to the cohorts list endpoint (trimmed payload: no query/groups/last_error_message/experiment_set; filters is kept)CONDENSED_FILTER_BAR: 'condensed_filter_bar', // owner: @jordanm-posthog #team-web-analyticsCREATE_FORM_TOOL: 'phai-create-form-tool', // owner: @kappa90 #team-posthog-aiCRM_ITERATION_ONE: 'crm-iteration-one', // owner: @arthurdedeus #team-customer-analyticsdiff --git a/frontend/src/models/cohortsModel.test.ts b/frontend/src/models/cohortsModel.test.tsindex eacd83656593..33085572f1de 100644--- a/frontend/src/models/cohortsModel.test.ts+++ b/frontend/src/models/cohortsModel.test.ts@@ -79,7 +79,7 @@ describe('cohortsModel', () => {// Set the current location to the cohorts pagerouter.actions.push(urls.cohorts())- await expectLogic(logic).toDispatchActions(['loadCohorts', 'loadCohortsSuccess'])+ await expectLogic(logic).toDispatchActions(['loadAllCohorts', 'loadAllCohortsSuccess'])expect(logic.values.pollTimeout).not.toBeNull()})@@ -105,7 +105,7 @@ describe('cohortsModel', () => {describe('cohort operations', () => {it('can update a cohort', async () => {// Wait for initial load- await expectLogic(logic).toDispatchActions(['loadCohortsSuccess'])+ await expectLogic(logic).toDispatchActions(['loadAllCohortsSuccess'])const updatedCohort: CohortType = {id: 1,@@ -125,7 +125,7 @@ describe('cohortsModel', () => {await expectLogic(logic, () => {logic.actions.updateCohort(updatedCohort)}).toMatchValues({- cohorts: expect.objectContaining({+ allCohorts: expect.objectContaining({results: expect.arrayContaining([expect.objectContaining({id: 1,@@ -168,7 +168,7 @@ describe('cohortsModel', () => {it('can delete a cohort', async () => {// Wait for initial load- await expectLogic(logic).toDispatchActions(['loadCohortsSuccess'])+ await expectLogic(logic).toDispatchActions(['loadAllCohortsSuccess'])jest.spyOn(api.cohorts, 'determineDeleteEndpoint').mockImplementation(() => 'cohorts')@@ -177,7 +177,7 @@ describe('cohortsModel', () => {}).toDispatchActions(['deleteCohort']).toMatchValues({- cohorts: expect.objectContaining({+ allCohorts: expect.objectContaining({results: expect.not.arrayContaining([expect.objectContaining({id: 1,diff --git a/frontend/src/models/cohortsModel.ts b/frontend/src/models/cohortsModel.tsindex fb50c627b621..69dc7a909ce8 100644--- a/frontend/src/models/cohortsModel.ts+++ b/frontend/src/models/cohortsModel.ts@@ -264,12 +264,21 @@ export const cohortsModel = kea<cohortsModelType>([allCohorts: {__default: { count: 0, results: [] } as CountedPaginatedResponse<CohortType>,loadAllCohorts: async () => {- const response = await api.cohorts.listPaginated({+ // `allCohorts` feeds `cohortsById`, mostly id + name lookups, so request the+ // basic payload that drops the legacy `groups`/`query` JSON. Fetching the full+ // payload for up to 2,000 cohorts on this hot path was slow enough to hit the+ // gateway timeout on cohort-heavy teams. `filters` stays in the basic payload:+ // the feature-flag intent warning reads it off `cohortsById` (see+ // featureFlagIntentWarningLogic.hasBehavioralCriteria), and its raw shape is+ // what that check expects, so no `processCohort` normalization is needed here.+ const response = await api.cohorts.listBasic({limit: MAX_COHORTS_FOR_FULL_LIST,})return {count: response.count,- results: response.results.map((cohort) => processCohort(cohort)),+ // `groups` is dropped from the basic payload but required on CohortType, so+ // add the empty default back — nothing reading `cohortsById` uses `groups`.+ results: response.results.map((cohort): CohortType => ({ ...cohort, groups: [] })),}},},@@ -410,7 +419,9 @@ export const cohortsModel = kea<cohortsModelType>([// own, or pickers keep serving the deleted-state cache for staleTime.invalidateTaxonomicResourcesWhere(isCohortTaxonomicListKey)}- actions.loadCohorts()+ // Refresh `allCohorts` (the source for `cohortsById`) so an undo restores+ // the row's name to breadcrumbs and pickers, not just the `cohorts` list.+ actions.loadAllCohorts()if (cohort.id && cohort.id !== 'new') {if (undo) {refreshTreeItem('cohort', String(cohort.id))@@ -436,7 +447,6 @@ export const cohortsModel = kea<cohortsModelType>([actions.hydrateAllCohortsFromExport(exportedCohorts)}}- actions.loadCohorts()}),permanentlyMount(),])diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 5f0ea5042af9..5bc7638a01b9 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -671,7 +671,13 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ# response small for teams with thousands of cohorts. Default output is# unchanged; only callers that explicitly ask get the trimmed shape.if self.context.get("basic_cohort_list"):- for field_name in ("filters", "query", "groups"):+ # Keep `filters`: the feature-flag intent warning reads it off `cohortsById`+ # (see featureFlagIntentWarningLogic.hasBehavioralCriteria) to flag behavioral+ # cohorts that can't be evaluated locally. `last_error_message` is computed from+ # a per-row correlated subquery over CohortCalculationHistory (see+ # safely_get_queryset), and `experiment_set` costs a prefetch — basic-list callers+ # read neither, so drop them and skip the extra queries there.+ for field_name in ("query", "groups", "last_error_message", "experiment_set"):self.fields.pop(field_name, None)def get_last_error_message(self, cohort: Cohort) -> Optional[str]:@@ -1579,8 +1585,9 @@ def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:location=OpenApiParameter.QUERY,required=False,description=(- "Return a basic payload that omits the heavy `filters`, `query`, and "- "`groups` fields. Useful for pickers that only need id/name/count."+ "Return a basic payload that omits the `query`, `groups`, "+ "`last_error_message`, and `experiment_set` fields (`filters` is kept). "+ "Useful for pickers that only need id/name/count."),),]@@ -1638,6 +1645,9 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVidef safely_get_queryset(self, queryset) -> QuerySet:search_ordered = False+ # `_is_basic_list_request()` returns False for non-list actions, so computing it once+ # up front is safe and keeps the queryset and serializer paths reading the same flag.+ is_basic_list = self._is_basic_list_request()if self.action == "list":queryset = queryset.filter(deleted=False)@@ -1660,29 +1670,35 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi# add additional filters provided by the clientqueryset, search_ordered = self._filter_request(self.request, queryset)- # `?basic=true` callers never read these columns, so skip reading them- # off disk (the serializer drops them too; see CohortSerializer.__init__).- if self._is_basic_list_request():- queryset = queryset.defer("filters", "query", "groups")-- last_error_code_subquery = Subquery(- CohortCalculationHistory.objects.filter(- cohort=OuterRef("pk"),- error__isnull=False,- )- .exclude(error="")- .order_by("-started_at")- .values("error_code")[:1]- )+ # `?basic=true` callers never read `query`, so skip reading it off disk (the+ # serializer drops it too; see CohortSerializer.__init__). `groups` is dropped+ # from the payload but kept on disk: `to_representation`'s `filters` fallback reads+ # `instance.properties`, which reads `groups`, so deferring it would add a per-row+ # query for rows with a falsy `filters`. `filters` stays in the payload — the flag+ # intent warning reads it off `cohortsById`.+ 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.- # `experiment_set` is a reverse relation, so it stays prefetched.- queryset = (- queryset.annotate(last_error_code=last_error_code_subquery)- .select_related("created_by", "team")- .prefetch_related("experiment_set")- )+ queryset = queryset.select_related("created_by", "team")++ # `experiment_set` is a reverse relation (a prefetch) and the per-row correlated+ # subquery over CohortCalculationHistory only feeds `last_error_message`. The basic+ # list payload drops both, so skip the prefetch and the per-row subquery there — the+ # hot-path fetch would otherwise run a subquery per row for teams with thousands of+ # cohorts.+ if not is_basic_list:+ last_error_code_subquery = Subquery(+ CohortCalculationHistory.objects.filter(+ cohort=OuterRef("pk"),+ error__isnull=False,+ )+ .exclude(error="")+ .order_by("-started_at")+ .values("error_code")[:1]+ )+ queryset = queryset.prefetch_related("experiment_set").annotate(last_error_code=last_error_code_subquery)if not search_ordered:queryset = queryset.order_by("-created_at")diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex ac93e31dc23c..abbc0d434849 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -41,6 +41,7 @@ from posthog.tasks.calculate_cohort import (increment_version_and_enqueue_calculate_cohort,insert_cohort_from_filters,)+from posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.persons import create_personfrom products.actions.backend.models.action import Action@@ -1893,12 +1894,44 @@ [email protected],self.assertIn("filters", full)basic = self.client.get(f"/api/projects/{self.team.id}/cohorts?basic=true").json()["results"][0]- for dropped in ("filters", "query", "groups"):+ # `last_error_message` and `experiment_set` are dropped too — basic callers don't read+ # them, and keeping `last_error_message` would force the per-row CohortCalculationHistory+ # subquery back onto the hot path.+ for dropped in ("query", "groups", "last_error_message", "experiment_set"):self.assertNotIn(dropped, basic)- # The fields pickers actually read are still present.- for kept in ("id", "name", "count"):+ # `filters` stays: the feature-flag intent warning reads it off the basic list to flag+ # behavioral cohorts. `is_calculating` drives the 5s repoll and `is_static` drives the+ # static-cohort flag warning — both now read only from the basic payload, so trimming+ # any of these silently breaks a feature. Guard them here.+ for kept in ("id", "name", "count", "filters", "is_calculating", "is_static"):self.assertIn(kept, basic)+ @patch("posthog.api.cohort.report_user_action")+ def test_basic_list_skips_error_and_experiment_queries(self, patch_capture):+ # The basic payload drops `last_error_message` and `experiment_set`, so it must not run+ # the per-row CohortCalculationHistory subquery or the experiment prefetch. Asserting on+ # the emitted SQL (not query count) is what catches it: the correlated subquery splices+ # into the enclosing SELECT rather than issuing its own, so a count wouldn't move. The+ # full path is the positive control, so a table rename can't make the negatives pass for+ # the wrong reason.+ Cohort.objects.create(+ team=self.team,+ name="some cohort",+ filters={"properties": {"type": "OR", "values": [{"type": "person", "key": "email", "value": "[email protected]"}]}},+ )++ with capture_db_queries() as full_ctx:+ self.client.get(f"/api/projects/{self.team.id}/cohorts")+ full_sql = " ".join(q["sql"] for q in full_ctx.captured_queries)+ self.assertIn("posthog_cohortcalculationhistory", full_sql)+ self.assertIn("posthog_experiment", full_sql)++ with capture_db_queries() as basic_ctx:+ self.client.get(f"/api/projects/{self.team.id}/cohorts?basic=true")+ basic_sql = " ".join(q["sql"] for q in basic_ctx.captured_queries)+ self.assertNotIn("posthog_cohortcalculationhistory", basic_sql)+ self.assertNotIn("posthog_experiment", basic_sql)+@patch("posthog.api.cohort.report_user_action")def test_basic_is_ignored_on_detail_fetch(self, patch_capture):# `basic` only trims the list. A detail fetch must keep `filters` so thediff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.tsindex 90ee42f022b9..910de2a80622 100644--- a/products/cohorts/frontend/generated/api.schemas.ts+++ b/products/cohorts/frontend/generated/api.schemas.ts@@ -538,7 +538,7 @@ export type CohortsStaffListParams = {export type CohortsListParams = {/**- * Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.+ * Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id/name/count.*/basic?: boolean/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 078c2b207c1d..629f29d6e26f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -77876,7 +77876,7 @@ export namespace Schemas {export type CohortsListParams = {/**- * Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.+ * Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id/name/count.*/basic?: boolean;/**diff --git a/services/mcp/src/generated/cohorts/api.ts b/services/mcp/src/generated/cohorts/api.tsindex c2080ba4dea3..412f1cb9ee7a 100644--- a/services/mcp/src/generated/cohorts/api.ts+++ b/services/mcp/src/generated/cohorts/api.ts@@ -21,7 +21,7 @@ export const CohortsListQueryParams = /* @__PURE__ */ zod.object({.boolean().optional().describe(- 'Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id\/name\/count.'+ 'Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id\/name\/count.'),hide_behavioral_cohorts: zod.boolean()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.jsonindex c9b052c3a794..1ea14386a307 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"basic": {- "description": "Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.",+ "description": "Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id/name/count.","type": "boolean"},"hide_behavioral_cohorts": {