: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): return actionable errors when adding persons to a static cohort (#110724)
posthog[bot]0dcc8173a1e0
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex d96a1f1f68ed..3f71c844ec32 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -643,11 +643,35 @@ API_COHORT_PERSON_BYTES_READ_FROM_POSTGRES_COUNTER = Counter(logger = structlog.get_logger(__name__)+class LengthFirstListField(serializers.ListField):+ # DRF checks max_length only after it validates every item, so an oversized list of bad items+ # builds one error per item before it fails. Check the length first to reject it in constant time.+ def to_internal_value(self, data: Any) -> list[Any]:+ if self.max_length is not None and isinstance(data, list) and len(data) > self.max_length:+ self.fail("max_length", max_length=self.max_length)+ return super().to_internal_value(data)++class AddPersonsToStaticCohortRequestSerializer(serializers.Serializer):- person_ids = serializers.ListField(- child=serializers.UUIDField(),+ person_ids = LengthFirstListField(+ child=serializers.UUIDField(+ error_messages={+ "invalid": "Must be a person UUID (the `id` column of the persons table), not a distinct ID or an email."+ }+ ),required=True,- help_text="List of person UUIDs to add to the cohort",+ allow_empty=False,+ max_length=DEFAULT_COHORT_INSERT_BATCH_SIZE,+ error_messages={+ "max_length": (+ "Too many person_ids. Send at most {max_length} per request. To add a larger set, set a `query` "+ "on the static cohort instead, and the server adds every matching person."+ )+ },+ help_text=(+ "Person UUIDs to add to the cohort (the `id` column of the persons table, not distinct IDs). "+ f"At most {DEFAULT_COHORT_INSERT_BATCH_SIZE} per request."+ ),)@@ -2610,17 +2634,22 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVidef add_persons_to_static_cohort(self, request: request.Request, **kwargs):cohort: Cohort = self.get_object()if not cohort.is_static:- raise ValidationError("Can only add users to static cohorts")- person_ids = request.data.get("person_ids", None)- if not isinstance(person_ids, list):- raise ValidationError("person_ids must be a list")- if len(person_ids) == 0:- raise ValidationError("person_ids cannot be empty")- if len(person_ids) > DEFAULT_COHORT_INSERT_BATCH_SIZE:- raise ValidationError("List size exceeds limit")+ raise ValidationError(+ "Can only add users to static cohorts. This cohort is dynamic, so its filters decide who is in it. "+ "Change the filters, or create a static cohort (`is_static: true`) and add the persons to that one.",+ code="cohort_not_static",+ )+ serializer = AddPersonsToStaticCohortRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ person_ids = [str(person_id) for person_id in serializer.validated_data["person_ids"]]uuids = validate_person_uuids_exist(self.team_id, person_ids)if len(uuids) == 0:- raise ValidationError("No valid users to add to cohort")+ raise ValidationError(+ "No valid users to add to cohort. None of the person_ids match a person in this project. "+ "Use person UUIDs from the persons table (for example `SELECT id FROM persons WHERE ...`). "+ "Distinct IDs do not match, even when they look like UUIDs.",+ code="no_matching_persons",+ )cohort.insert_users_list_by_uuid(uuids, team_id=self.team_id)log_activity(organization_id=cast(UUIDT, self.organization_id),diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 679a4b31e053..6d4b925660a4 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -18,7 +18,7 @@ from unittest import mockfrom unittest.mock import ANY, MagicMock, patchfrom django.core.files.uploadedfile import SimpleUploadedFile-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom django.test.client import Clientfrom django.utils import timezone@@ -27,7 +27,12 @@ from rest_framework import statusfrom posthog.schema import PersonsOnEventsMode, PropertyOperator-from posthog.api.cohort import COHORT_USED_IN_PAGE_SIZE, CohortFilters, CohortViewSet+from posthog.api.cohort import (+ COHORT_USED_IN_PAGE_SIZE,+ AddPersonsToStaticCohortRequestSerializer,+ CohortFilters,+ CohortViewSet,+)from posthog.clickhouse.client.execute import sync_executefrom posthog.constants import AvailableFeaturefrom posthog.models import User@@ -5611,6 +5616,55 @@ [email protected],assert response.status_code == 400assert "Can only remove users from static cohorts" in response.json()["detail"]+ def test_add_persons_to_static_cohort(self):+ static_cohort = Cohort.objects.create(team=self.team, name="Test Static Cohort", is_static=True)+ person = _create_person(team_id=self.team.pk, distinct_ids=["test-person-to-add"])+ flush_persons_and_events()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{static_cohort.id}/add_persons_to_static_cohort",+ {"person_ids": [str(person.uuid)]},+ format="json",+ )++ assert response.status_code == 200, response.json()+ assert _cohort_member_uuids(self.team.pk, static_cohort) == {str(person.uuid)}++ @parameterized.expand(+ [+ (+ "dynamic_cohort",+ False,+ {"person_ids": ["12345678-1234-1234-1234-123456789abc"]},+ "cohort_not_static",+ None,+ ),+ (+ "unknown_uuid",+ True,+ {"person_ids": ["12345678-1234-1234-1234-123456789abc"]},+ "no_matching_persons",+ None,+ ),+ ("distinct_id", True, {"person_ids": ["[email protected]"]}, "invalid_input", "person_ids__0"),+ ("missing_person_ids", True, {}, "required", "person_ids"),+ ]+ )+ def test_add_persons_to_static_cohort_validation_errors(+ self, _name: str, is_static: bool, payload: dict, expected_code: str, expected_attr: str | None+ ):+ cohort = Cohort.objects.create(team=self.team, name="Test Cohort", is_static=is_static)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort.id}/add_persons_to_static_cohort",+ payload,+ format="json",+ )++ assert response.status_code == 400+ assert response.json()["code"] == expected_code+ assert response.json()["attr"] == expected_attr+def test_remove_person_from_static_cohort_person_does_not_exist(self):static_cohort = Cohort.objects.create(team=self.team,@@ -8286,3 +8340,22 @@ Jane Smith,user456,[email protected]self.assertEqual(cohort.errors_calculating, 1)self.assertIsNotNone(cohort.last_error_at)self.assertIsNone(cohort.last_calculation)+++class TestAddPersonsToStaticCohortRequestSerializer(SimpleTestCase):+ @parameterized.expand(+ [+ ("empty", {"person_ids": []}, "empty"),+ (+ "too_many",+ {"person_ids": ["not-a-uuid"] * (DEFAULT_COHORT_INSERT_BATCH_SIZE + 1)},+ "max_length",+ ),+ ("not_a_list", {"person_ids": "12345678-1234-1234-1234-123456789abc"}, "not_a_list"),+ ]+ )+ def test_rejects_unsupported_person_ids(self, _name: str, payload: dict, expected_code: str) -> None:+ serializer = AddPersonsToStaticCohortRequestSerializer(data=payload)++ assert not serializer.is_valid()+ assert serializer.errors["person_ids"][0].code == expected_codediff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.tsindex ed19319832da..9f1bae2b7771 100644--- a/products/cohorts/frontend/generated/api.schemas.ts+++ b/products/cohorts/frontend/generated/api.schemas.ts@@ -588,7 +588,10 @@ export interface ActivityLogPaginatedResponseApi {}export interface PatchedAddPersonsToStaticCohortRequestApi {- /** List of person UUIDs to add to the cohort */+ /**+ * Person UUIDs to add to the cohort (the `id` column of the persons table, not distinct IDs). At most 1000 per request.+ * @maxItems 1000+ */person_ids?: string[]}diff --git a/products/cohorts/frontend/generated/api.zod.ts b/products/cohorts/frontend/generated/api.zod.tsindex 9af270d78e9a..c36d4fc366cc 100644--- a/products/cohorts/frontend/generated/api.zod.ts+++ b/products/cohorts/frontend/generated/api.zod.ts@@ -172,8 +172,16 @@ export const CohortsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Person UUIDs to add to a new static cohort.'),})+export const cohortsAddPersonsToStaticCohortPartialUpdateBodyPersonIdsMax = 1000+export const CohortsAddPersonsToStaticCohortPartialUpdateBody = /* @__PURE__ */ zod.object({- person_ids: zod.array(zod.uuid()).optional().describe('List of person UUIDs to add to the cohort'),+ person_ids: zod+ .array(zod.uuid())+ .max(cohortsAddPersonsToStaticCohortPartialUpdateBodyPersonIdsMax)+ .optional()+ .describe(+ 'Person UUIDs to add to the cohort (the `id` column of the persons table, not distinct IDs). At most 1000 per request.'+ ),})export const CohortsRemovePersonFromStaticCohortPartialUpdateBody = /* @__PURE__ */ zod.object({diff --git a/products/cohorts/mcp/tools.yaml b/products/cohorts/mcp/tools.yamlindex 74bbedc4f003..4bde7bce7ef3 100644--- a/products/cohorts/mcp/tools.yaml+++ b/products/cohorts/mcp/tools.yaml@@ -24,7 +24,8 @@ tools:idempotent: falsetitle: Add persons to static cohortdescription: >-- Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true).+ Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true). 'person_ids'+ must be person UUIDs (the 'id' column of the persons table), not distinct IDs or emails.Intended for small, ad-hoc additions — pass at most ~20 person UUIDs per call. To build or grow a staticdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 3fa5e4c93803..1619a0018914 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3087,7 +3087,7 @@"system_prompt_hint": "First call when investigating \"metric X looks wrong\" — magnitude, onset, which labels moved"},"cohorts-add-persons-to-static-cohort-partial-update": {- "description": "Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true).\n\nIntended for small, ad-hoc additions — pass at most ~20 person UUIDs per call. To build or grow a static cohort from a larger set, do NOT loop this tool over many UUIDs; instead create the cohort from a query ('cohorts-create' with 'is_static: true' and a 'query'), or add to an existing static cohort by setting a 'query' on it via 'cohorts-partial-update'. The server then runs the query and inserts every matching person in a single call, with no row limit.",+ "description": "Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true). 'person_ids' must be person UUIDs (the 'id' column of the persons table), not distinct IDs or emails.\n\nIntended for small, ad-hoc additions — pass at most ~20 person UUIDs per call. To build or grow a static cohort from a larger set, do NOT loop this tool over many UUIDs; instead create the cohort from a query ('cohorts-create' with 'is_static: true' and a 'query'), or add to an existing static cohort by setting a 'query' on it via 'cohorts-partial-update'. The server then runs the query and inserts every matching person in a single call, with no row limit.","category": "Cohorts","feature": "cohorts","summary": "Add persons to static cohort",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9a032a57c5d6..320fdb2a0b30 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3102,7 +3102,7 @@"system_prompt_hint": "First call when investigating \"metric X looks wrong\" — magnitude, onset, which labels moved"},"cohorts-add-persons-to-static-cohort-partial-update": {- "description": "Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true).\n\nIntended for small, ad-hoc additions — pass at most ~20 person UUIDs per call. To build or grow a static cohort from a larger set, do NOT loop this tool over many UUIDs; instead create the cohort from a query ('cohorts-create' with 'is_static: true' and a 'query'), or add to an existing static cohort by setting a 'query' on it via 'cohorts-partial-update'. The server then runs the query and inserts every matching person in a single call, with no row limit.",+ "description": "Add persons to a static cohort by their UUIDs. Only works for static cohorts (is_static: true). 'person_ids' must be person UUIDs (the 'id' column of the persons table), not distinct IDs or emails.\n\nIntended for small, ad-hoc additions — pass at most ~20 person UUIDs per call. To build or grow a static cohort from a larger set, do NOT loop this tool over many UUIDs; instead create the cohort from a query ('cohorts-create' with 'is_static: true' and a 'query'), or add to an existing static cohort by setting a 'query' on it via 'cohorts-partial-update'. The server then runs the query and inserts every matching person in a single call, with no row limit.","category": "Cohorts","feature": "cohorts","summary": "Add persons to static cohort",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e19c0234bf7f..de93b5c76a0c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -83962,7 +83962,10 @@ export namespace Schemas {}export interface PatchedAddPersonsToStaticCohortRequest {- /** List of person UUIDs to add to the cohort */+ /**+ * Person UUIDs to add to the cohort (the `id` column of the persons table, not distinct IDs). At most 1000 per request.+ * @maxItems 1000+ */person_ids?: string[];}diff --git a/services/mcp/src/generated/cohorts/api.ts b/services/mcp/src/generated/cohorts/api.tsindex bdc5d118789e..10d6be52537a 100644--- a/services/mcp/src/generated/cohorts/api.ts+++ b/services/mcp/src/generated/cohorts/api.ts@@ -371,8 +371,16 @@ export const CohortsAddPersonsToStaticCohortPartialUpdateParams = () => zod.obje),})+export const cohortsAddPersonsToStaticCohortPartialUpdateBodyPersonIdsMax = 1000+export const CohortsAddPersonsToStaticCohortPartialUpdateBody = () => zod.object({- person_ids: zod.array(zod.string()).optional().describe('List of person UUIDs to add to the cohort'),+ person_ids: zod+ .array(zod.string())+ .max(cohortsAddPersonsToStaticCohortPartialUpdateBodyPersonIdsMax)+ .optional()+ .describe(+ 'Person UUIDs to add to the cohort (the `id` column of the persons table, not distinct IDs). At most 1000 per request.'+ ),})export const CohortsRemovePersonFromStaticCohortPartialUpdateParams = () => zod.object({diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-add-persons-to-static-cohort-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-add-persons-to-static-cohort-partial-update.jsonindex 6af9c339ef49..f56e8dbbb6f0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-add-persons-to-static-cohort-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-add-persons-to-static-cohort-partial-update.json@@ -6,10 +6,11 @@"type": "number"},"person_ids": {- "description": "List of person UUIDs to add to the cohort",+ "description": "Person UUIDs to add to the cohort (the `id` column of the persons table, not distinct IDs). At most 1000 per request.","items": {"type": "string"},+ "maxItems": 1000,"type": "array"}},