: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
perf(cohorts): faster cohort list endpoint + opt-in basic payload (#61112)
Adam Leithb31901159152
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex eb487329d676..9c2961c59a30 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1301,9 +1301,9 @@ snapshots:components-search--product-recents-and-starred--light:hash: v1.k794b7964.093365121259b79e33584b3e0042ad3813b0e77f2af285369ab7b2bf98bd9c79.-imuS481bcvyD7kDEeyJ4mfKoQcmD451n4Lxv2IrE3gcomponents-search--searching--dark:- hash: v1.k794b7964.5640d6ceda1c0c42d11d0830ce6f99d435ed755f675c7bcf189625c50c6fb77e.y1r9bx5WquHigHMTHREsnNCKkDLi0SluFC9L48L6NxM+ hash: v1.k794b7964.c5785def54f95bfb7d51502afe65be1bd3ba8a4571c266ab7de9988d264ba3ac.9FUkLehZOdn6Vzp4JL4Ff2z18mk2wZKGcvEVzTteTx8components-search--searching--light:- hash: v1.k794b7964.00eec8365eb2b8e99781a485440555fdde5a1ed86e73254e927075b30d97a8cb.Vo_QisoIzatCT6K0G9D63ScY4y_-Y22PxQMJ4Kv64S4+ hash: v1.k794b7964.3bee574e53e96c750b2cfcc501e29cc05fce8be9cbac204b74e0bf4fd25f15cf.rZ1qKg9u_jxtcXCG3J1zU1CnuKBY4lXIc8SBQ3DnHgMcomponents-sentencelist--full-sentence--dark:hash: v1.k794b7964.9d72ed5224f75be3f53f1ba8edc2547978e519aa46a57cc97eef9087b403cb7d.3yHHiA7NW-p6vVSlM-2nPx7Nbk7wuTr5SA9Av2nW--gcomponents-sentencelist--full-sentence--light:@@ -4375,7 +4375,7 @@ snapshots:scenes-app-dashboards--access-control-dashboard--light:hash: v1.k794b7964.dc4668079433d9d32098abb7e7ddd0f8d7beb5a0e340bc62db5d9b3b169443d6.KHaTfpgbwW7i_WMJD2WRJHHVip8Y0xXQYcPkFzwhx_Yscenes-app-dashboards--edit--dark:- hash: v1.k794b7964.9841bf4c17d0deb6e2689f0fa121083891d04d90c51cd0a091ee8e6a45819be5.ouBCUXW6-PrHbVXG1asZ6RvcHvIpi_DDo0gsg-LKVJo+ hash: v1.k794b7964.723e3dea56735cb71301060c734e6ef55b1c50e58b00246187b99ac08e27f88a.OkJTaCHBLM4r_wmXlAEX7i_TVCmdT1AveZt0bACy2IEscenes-app-dashboards--edit--light:hash: v1.k794b7964.323ad2f789d32ab1f7ff93e7f9123a5b57584a51140d17c189ceeafe1254c6f2.xPHUsj1Ql16ii6E9XeaYqXAkHY5DCaOYimQlEbUNrA8scenes-app-dashboards--erroring--dark:diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsxindex 8507d8b1e2ec..6259be6fd9bd 100644--- a/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/utils/buildTaxonomicGroups.tsx@@ -179,6 +179,10 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonomi} = ctxconst { 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.+ const cohortsEndpointParams = featureFlags[FEATURE_FLAGS.COHORTS_TAXONOMIC_BASIC_LIST] ? { basic: true } : undefinedconst groups: TaxonomicFilterGroup[] = [{name: 'Events',@@ -654,7 +658,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonominame: 'Cohorts',searchPlaceholder: 'cohorts',type: TaxonomicFilterGroupType.Cohorts,- endpoint: combineUrl(`api/projects/${projectId}/cohorts/`).url,+ endpoint: combineUrl(`api/projects/${projectId}/cohorts/`, cohortsEndpointParams).url,value: 'cohorts',// See taxonomicFilterLogic — cohort populations comfortably fit// in one page; cache the first 100 and fuse-filter typed@@ -678,7 +682,7 @@ export function buildTaxonomicGroups(ctx: BuildTaxonomicGroupsContext): Taxonominame: 'Cohorts',searchPlaceholder: 'cohorts',type: TaxonomicFilterGroupType.CohortsWithAllUsers,- endpoint: combineUrl(`api/projects/${projectId}/cohorts/`).url,+ endpoint: combineUrl(`api/projects/${projectId}/cohorts/`, cohortsEndpointParams).url,clientFilterFirstPage: true,options: COHORTS_WITH_ALL_USERS_OPTIONS,getName: (cohort: CohortType) => cohort.name || `Cohort ${cohort.id}`,diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex e884ee269930..66aa991b338c 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -251,6 +251,7 @@ export const FEATURE_FLAGS = {COHORT_CALCULATION_HISTORY: 'cohort-calculation-history', // owner: @gustavo #team-feature-flagsCOHORT_EMAIL_LOOKUP_CLICKHOUSE: 'cohort-email-lookup-clickhouse', // owner: @gustavo #team-feature-flagsCOHORT_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)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/posthog/api/cohort.py b/posthog/api/cohort.pyindex d5215fcb8a06..d0561b15d905 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -11,7 +11,7 @@ from django.db import DatabaseErrorfrom django.db.models import OuterRef, Prefetch, QuerySet, Subquery, prefetch_related_objectsimport structlog-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_viewfrom loginas.utils import is_impersonated_sessionfrom prometheus_client import Counterfrom pydantic import (@@ -74,7 +74,7 @@ from posthog.queries.base import determine_parsed_date_for_property_matching, prfrom posthog.queries.person_query import PersonQueryfrom posthog.queries.util import get_earliest_timestampfrom posthog.renderers import SafeJSONRenderer-from posthog.utils import format_query_params_absolute_url+from posthog.utils import format_query_params_absolute_url, str_to_boolfrom products.feature_flags.backend.flag_matching import (FeatureFlagMatcher,@@ -505,6 +505,16 @@ class CohortSerializer(serializers.ModelSerializer):"experiment_set",]+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ # Basic list payload (opt-in via `?basic=true` on the list endpoint): drop+ # the heavy JSON columns the cohort picker never reads. Keeps the+ # 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"):+ self.fields.pop(field_name, None)+def get_last_error_message(self, cohort: Cohort) -> Optional[str]:# Prefer the annotated last_error_code when availableif hasattr(cohort, "last_error_code"):@@ -1122,17 +1132,47 @@ class CohortSerializer(serializers.ModelSerializer):def to_representation(self, instance):representation = super().to_representation(instance)- representation["filters"] = (- instance.filters if instance.filters else {"properties": instance.properties.to_dict()}- )+ # Skip when the slim list dropped `filters`; computing+ # `properties.to_dict()` is the expensive part we're avoiding there.+ if "filters" in self.fields:+ representation["filters"] = (+ instance.filters if instance.filters else {"properties": instance.properties.to_dict()}+ )return representation+@extend_schema_view(+ list=extend_schema(+ parameters=[+ OpenApiParameter(+ name="basic",+ type=bool,+ 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."+ ),+ ),+ ]+ )+)class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):queryset = Cohort.objects.all()serializer_class = CohortSerializerscope_object = "cohort"+ def _is_basic_list_request(self) -> bool:+ # `?basic=true` on the list endpoint: trimmed payload + deferred columns.+ # Single source of truth for both the queryset and serializer paths so they+ # can't drift if the default changes or `basic` is wired into another action.+ return self.action == "list" and str_to_bool(self.request.query_params.get("basic", "0"))++ def get_serializer_context(self) -> dict[str, Any]:+ context = super().get_serializer_context()+ context["basic_cohort_list"] = self._is_basic_list_request()+ return context+def _filter_request(self, request: Request, queryset: QuerySet) -> QuerySet:filters = request.GET.dict()@@ -1162,7 +1202,14 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVifrom products.feature_flags.backend.api.feature_flag import _is_realtime_cohort_flag_targeting_enabledallow_realtime_backfilled = _is_realtime_cohort_flag_targeting_enabled(self.request)- all_cohorts = {cohort.id: cohort for cohort in queryset.all()}+ # Lists every column read by _find_behavioral_cohorts (is_static, filters)+ # and Cohort.is_flag_compatible (cohort_type, last_backfill_person_properties_at);+ # dropping one triggers a per-cohort deferred query (an N+1 that only bites a+ # team with thousands of cohorts). Deferring the rest keeps the graph scan cheap.+ graph_source = queryset.only(+ "id", "is_static", "filters", "cohort_type", "last_backfill_person_properties_at"+ )+ all_cohorts = {cohort.id: cohort for cohort in graph_source.all()}behavioral_cohort_ids = self._find_behavioral_cohorts(all_cohorts, allow_realtime_backfilled=allow_realtime_backfilled)@@ -1171,6 +1218,11 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi# add additional filters provided by the clientqueryset = 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"),@@ -1181,46 +1233,54 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi.values("error_code")[:1])+ # `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.return (queryset.annotate(last_error_code=last_error_code_subquery)- .prefetch_related("experiment_set", "created_by", "team")+ .select_related("created_by", "team")+ .prefetch_related("experiment_set").order_by("-created_at"))def _find_behavioral_cohorts(self, all_cohorts: dict[int, Cohort], *, allow_realtime_backfilled: bool = False) -> set[int]:- """- Find all cohorts that have behavioral filters or reference cohorts with behavioral filters- using a graph-based approach.+ """Find cohorts that are behavioral, or reference (transitively) a behavioral cohort.++ A cohort is affected if it's a behavioral seed, or references one through the+ dependency graph. We walk the *reverse* graph once from the seeds (O(V+E)) —+ every node that can reach a seed via forward edges is affected.- When allow_realtime_backfilled is True, realtime cohorts that have been backfilled are- excluded from the result because they can be evaluated via the cohort_membership table- during flag evaluation.+ When allow_realtime_backfilled is True, realtime cohorts that have been backfilled+ are not seeds: they can be evaluated via the cohort_membership table during flag+ evaluation. (They can still be pulled in if they reference another seed.)"""graph, behavioral_cohorts = self._build_cohort_dependency_graph(all_cohorts)- # When the feature is enabled, realtime+backfilled cohorts are flag-compatibleflag_compatible: set[int] = set()if allow_realtime_backfilled:flag_compatible = {cid for cid in behavioral_cohorts if (cohort := all_cohorts.get(cid)) and cohort.is_flag_compatible}- affected_cohorts = behavioral_cohorts - flag_compatible-- def find_affected_cohorts() -> None:- changed = True- while changed:- changed = False- for source_id in list(graph.keys()):- if source_id not in affected_cohorts:- # NB: If this cohort points to any affected cohort, it's also affected- if any(target_id in affected_cohorts for target_id in graph[source_id]):- affected_cohorts.add(source_id)- changed = True-- find_affected_cohorts()- return affected_cohorts+ seeds = behavioral_cohorts - flag_compatible++ # Reverse adjacency: target -> sources that reference it.+ reverse: dict[int, set[int]] = defaultdict(set)+ for source_id, targets in graph.items():+ for target_id in targets:+ reverse[target_id].add(source_id)++ affected = set(seeds)+ stack = list(seeds)+ while stack:+ node = stack.pop()+ for source_id in reverse.get(node, ()):+ if source_id not in affected:+ affected.add(source_id)+ stack.append(source_id)++ return affecteddef _build_cohort_dependency_graph(self, all_cohorts: dict[int, Cohort]) -> tuple[dict[int, set[int]], set[int]]:"""diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 811dce661645..28ba487dd9d8 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -23,6 +23,7 @@ from rest_framework import statusfrom posthog.schema import PersonsOnEventsMode, PropertyOperator+from posthog.api.cohort import CohortViewSetfrom posthog.clickhouse.client.execute import sync_executefrom posthog.models import Person, Userfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -313,7 +314,7 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin)self.assertEqual(response.status_code, 201, response.content)- with self.assertNumQueries(13):+ with self.assertNumQueries(11):response = self.client.get(f"/api/projects/{self.team.id}/cohorts")assert len(response.json()["results"]) == 1@@ -328,7 +329,7 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin)self.assertEqual(response.status_code, 201, response.content)- with self.assertNumQueries(13):+ with self.assertNumQueries(11):response = self.client.get(f"/api/projects/{self.team.id}/cohorts")assert len(response.json()["results"]) == 3@@ -1772,6 +1773,77 @@ [email protected],self.assertEqual(len(results), 1)self.assertEqual(results[0]["id"], regular_cohort.id)+ def test_find_behavioral_cohorts_propagates_through_references(self):+ # Build an in-memory dependency graph (no DB needed): 1 is behavioral, 2->1,+ # 3->2 (both transitively affected), 4 unrelated. 5 is a behavioral realtime+ # cohort that has been backfilled, 6->5. 7 references both the exempt seed (5)+ # and a real seed (1), so it must stay excluded even when 5 is exempted.+ def make(cid: int, *, behavioral: bool = False, refs: tuple[int, ...] = (), realtime_backfilled: bool = False):+ values: list[dict] = []+ if behavioral:+ values.append({"type": "behavioral"})+ values += [{"type": "cohort", "value": str(ref)} for ref in refs]+ return Cohort(+ id=cid,+ team=self.team,+ is_static=False,+ filters={"properties": {"type": "OR", "values": values}},+ cohort_type=CohortType.REALTIME if realtime_backfilled else None,+ last_backfill_person_properties_at=timezone.now() if realtime_backfilled else None,+ )++ cohorts = {+ c.id: c+ for c in [+ make(1, behavioral=True),+ make(2, refs=(1,)),+ make(3, refs=(2,)),+ make(4),+ make(5, behavioral=True, realtime_backfilled=True),+ make(6, refs=(5,)),+ make(7, refs=(1, 5)),+ ]+ }+ viewset = CohortViewSet()++ # Without the realtime exemption, every behavioral cohort and its referrers are excluded.+ self.assertEqual(viewset._find_behavioral_cohorts(cohorts), {1, 2, 3, 5, 6, 7})+ # With it, 5 is flag-compatible (not a seed) and 6 only referenced 5, so both stay.+ # 7 still reaches real seed 1, so it remains excluded.+ self.assertEqual(viewset._find_behavioral_cohorts(cohorts, allow_realtime_backfilled=True), {1, 2, 3, 7})++ @patch("posthog.api.cohort.report_user_action")+ def test_basic_list_omits_heavy_fields(self, patch_capture):+ Cohort.objects.create(+ team=self.team,+ name="some cohort",+ filters={"properties": {"type": "OR", "values": [{"type": "person", "key": "email", "value": "[email protected]"}]}},+ )++ full = self.client.get(f"/api/projects/{self.team.id}/cohorts").json()["results"][0]+ 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"):+ self.assertNotIn(dropped, basic)+ # The fields pickers actually read are still present.+ for kept in ("id", "name", "count"):+ self.assertIn(kept, basic)++ @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 the+ # cohort editor (which reads them) isn't broken if `?basic=true` leaks through.+ cohort = Cohort.objects.create(+ team=self.team,+ name="some cohort",+ filters={"properties": {"type": "OR", "values": [{"type": "person", "key": "email", "value": "[email protected]"}]}},+ )+ detail = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}/?basic=true").json()+ self.assertIn("filters", detail)+ self.assertIn("query", detail)+ self.assertIn("groups", detail)+@patch("posthog.api.cohort.report_user_action")def test_list_cohorts_excludes_nested_behavioral_cohorts(self, patch_capture):# Create a behavioral cohortdiff --git a/posthog/migrations/1206_cohort_list_indexes.py b/posthog/migrations/1206_cohort_list_indexes.pynew file mode 100644index 000000000000..3d4c7d0c5330--- /dev/null+++ b/posthog/migrations/1206_cohort_list_indexes.py@@ -0,0 +1,53 @@+from django.contrib.postgres.indexes import GinIndex+from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently+++class Migration(migrations.Migration):+ # CONCURRENTLY can't run inside a transaction.+ atomic = False++ dependencies = [+ ("posthog", "1205_delete_batch_export_models"),+ ]++ operations = [+ # `CreateIndexConcurrently` (vs Django's `AddIndexConcurrently`) disables+ # lock_timeout/statement_timeout, drops any invalid leftover from an+ # interrupted build, and uses IF NOT EXISTS — so a transient cancellation+ # during deploy doesn't wedge retries. `SeparateDatabaseAndState` keeps the+ # Django model state in sync via the matching `AddIndex`. pg_trgm is already+ # installed (migration 0034), so the gin_trgm_ops index needs no extension op.+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddIndex(+ model_name="cohort",+ index=models.Index(fields=["team", "-created_at"], name="cohort_team_created_idx"),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="cohort_team_created_idx",+ table_name="posthog_cohort",+ columns="(team_id, created_at DESC)",+ ),+ ],+ ),+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddIndex(+ model_name="cohort",+ index=GinIndex(fields=["name"], name="cohort_name_trgm_idx", opclasses=["gin_trgm_ops"]),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="cohort_name_trgm_idx",+ table_name="posthog_cohort",+ columns="(name gin_trgm_ops)",+ using="gin",+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 7a92acd4d468..306d58808fe4 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1205_delete_batch_export_models+1206_cohort_list_indexesdiff --git a/posthog/models/cohort/cohort.py b/posthog/models/cohort/cohort.pyindex d446a0b7522c..589e24a41dd0 100644--- a/posthog/models/cohort/cohort.py+++ b/posthog/models/cohort/cohort.py@@ -5,6 +5,7 @@ from enum import StrEnumfrom typing import TYPE_CHECKING, Any, Literal, Optional, Union, castfrom django.conf import settings+from django.contrib.postgres.indexes import GinIndexfrom django.db import models, transactionfrom django.db.models import Q, QuerySetfrom django.db.models.expressions import F@@ -234,6 +235,12 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):name="unique_cohort_kind_per_team",),]+ indexes = [+ # Backs the default list ordering (filter by team, order by -created_at).+ models.Index(fields=["team", "-created_at"], name="cohort_team_created_idx"),+ # Backs `name__icontains` search (the cohort picker's server-side search).+ GinIndex(fields=["name"], name="cohort_name_trgm_idx", opclasses=["gin_trgm_ops"]),+ ]def __str__(self):return self.name or "Untitled cohort"diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex 00df46fd5d01..4c08424d649d 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -1122,7 +1122,7 @@WHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,(SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCdiff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.tsindex 87a79bb457af..960b99a96ca3 100644--- a/products/cohorts/frontend/generated/api.schemas.ts+++ b/products/cohorts/frontend/generated/api.schemas.ts@@ -311,6 +311,10 @@ export interface PatchedRemovePersonRequestApi {}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.+ */+ basic?: boolean/*** Number of results to return per page.*/diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d3cf011b06ae..061c4b911b1e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44913,6 +44913,10 @@ 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.+ */+ basic?: boolean;/*** Number of results to return per page.*/diff --git a/services/mcp/src/generated/cohorts/api.ts b/services/mcp/src/generated/cohorts/api.tsindex 67271299a595..d73ed57c2779 100644--- a/services/mcp/src/generated/cohorts/api.ts+++ b/services/mcp/src/generated/cohorts/api.ts@@ -17,6 +17,12 @@ export const CohortsListParams = /* @__PURE__ */ zod.object({})export const CohortsListQueryParams = /* @__PURE__ */ zod.object({+ basic: zod+ .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.'+ ),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),})diff --git a/services/mcp/src/tools/generated/cohorts.ts b/services/mcp/src/tools/generated/cohorts.tsindex 37be1a664918..004b21468832 100644--- a/services/mcp/src/tools/generated/cohorts.ts+++ b/services/mcp/src/tools/generated/cohorts.ts@@ -94,6 +94,7 @@ const cohortsList = (): ToolBase<typeof CohortsListSchema, WithPostHogUrl<Schemamethod: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/cohorts/`,query: {+ basic: params.basic,limit: params.limit,offset: params.offset,},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.jsonindex 8331b796ac73..55e911877b6b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json@@ -1,6 +1,10 @@{"$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.",+ "type": "boolean"+ },"limit": {"description": "Number of results to return per page.","type": "number"