: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): retry static cohort list population on ClickHouse capacity errors (#70655)
posthog[bot]5c61fd1913c3
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex e36dbfc64391..d0bbb4af6aa5 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -8,7 +8,7 @@ from django.utils import timezoneimport structlogimport posthoganalytics-from celery import chain, current_task, shared_task+from celery import Task, chain, current_task, shared_taskfrom dateutil.relativedelta import relativedeltafrom prometheus_client import Counter, Gauge, Histogram@@ -498,9 +498,33 @@ def calculate_cohort_ch(cohort_id: int, pending_version: int, initiating_user_idcohort.calculate_people_ch(pending_version, initiating_user_id=initiating_user_id)-@shared_task(ignore_result=True, max_retries=1)+def _is_final_attempt(task: Task, err: Exception) -> bool:+ """Whether a failure is permanent, so the task must finalize terminal state now.++ Nothing retries an error outside CH_TRANSIENT_ERRORS, a direct (synchronous) call, which has no+ Celery retry machinery behind it, or the last autoretry attempt.+ """+ if not isinstance(err, CH_TRANSIENT_ERRORS):+ return True+ if task.request.called_directly:+ return True+ return task.max_retries is not None and (task.request.retries or 0) >= task.max_retries+++@shared_task(+ bind=True,+ ignore_result=True,+ # Auto-retry transient ClickHouse capacity errors with exponential backoff, matching the+ # dynamic-cohort sibling calculate_cohort_ch. Without this, a brief capacity blip during+ # the person_static_cohort insert leaves the static cohort permanently half-populated.+ autoretry_for=CH_TRANSIENT_ERRORS,+ retry_backoff=60,+ retry_backoff_max=1800,+ max_retries=6,+)@skip_team_scope_auditdef calculate_cohort_from_list(+ self: Task,cohort_id: int,items: list[str],team_id: Optional[int] = None,@@ -516,14 +540,30 @@ def calculate_cohort_from_list(if team_id is None:team_id = cohort.team_id- if id_type == "distinct_id":- batch_count = cohort.insert_users_by_list(items, team_id=team_id)- elif id_type == "person_id":- batch_count = cohort.insert_users_list_by_uuid(items, team_id=team_id)- elif id_type == "email":- batch_count = cohort.insert_users_by_email(items, team_id=team_id, email_property_key=email_property_key)- else:+ if id_type not in ("distinct_id", "person_id", "email"):raise ValueError(f"Unsupported id_type: {id_type}")++ # raise_on_error surfaces a batch insert failure instead of swallowing it, so a transient+ # capacity blip propagates and triggers the backed-off retry above. Retries are safe: the+ # insert path dedupes members already in the cohort (ClickHouse excludes existing UUIDs, the+ # InsertCohortMembers RPC dedupes on person id), so re-running the whole list adds no duplicates.+ try:+ if id_type == "distinct_id":+ batch_count = cohort.insert_users_by_list(items, team_id=team_id, raise_on_error=True)+ elif id_type == "person_id":+ batch_count = cohort.insert_users_list_by_uuid(items, team_id=team_id, raise_on_error=True)+ else:+ batch_count = cohort.insert_users_by_email(+ items, team_id=team_id, email_property_key=email_property_key, raise_on_error=True+ )+ except Exception as err:+ # raise_on_error also hands terminal-state finalization to us, so record the failure, but+ # only when nothing will retry. Recording it while attempts remain would leave a cohort+ # that is still being retried looking errored and no longer calculating.+ if _is_final_attempt(self, err):+ cohort._safe_save_cohort_state(team_id=team_id, processing_error=err)+ raise+logger.warn("Cohort {}: {:,} items in {} batches from CSV completed in {:.2f}s".format(cohort.pk, len(items), batch_count, (time.time() - start_time)diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.pyindex a7783aa991a9..b800b9f3e101 100644--- a/posthog/tasks/test/test_calculate_cohort.py+++ b/posthog/tasks/test/test_calculate_cohort.py@@ -7,9 +7,11 @@ from unittest.mock import MagicMock, patchfrom django.test import override_settingsfrom django.utils import timezone+from celery.exceptions import Retryfrom dateutil.relativedelta import relativedeltafrom parameterized import parameterized+from posthog.exceptions import ClickHouseAtCapacityfrom posthog.tasks.calculate_cohort import (COHORT_STUCK_COUNT_GAUGE,COHORTS_STALE_COUNT_GAUGE,@@ -25,6 +27,7 @@ from posthog.tasks.calculate_cohort import (trigger_cohort_backfill_run_task,update_cohort_metrics,)+from posthog.test.persons import create_personfrom products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRunfrom products.cohorts.backend.models.cohort import Cohort, CohortType@@ -1398,3 +1401,87 @@ class TestCohortCalculationTasks(APIBaseTest):cohort_b.refresh_from_db()self.assertFalse(cohort_a.is_calculating)self.assertFalse(cohort_b.is_calculating)+++class TestCalculateCohortFromListRetries(APIBaseTest):+ def _create_static_cohort(self) -> Cohort:+ # Mirrors the enqueue site, which flips is_calculating before dispatching the task.+ return Cohort.objects.create(+ team_id=self.team.pk,+ name="csv_upload_cohort",+ is_static=True,+ is_calculating=True,+ )++ def _run_task(self, cohort: Cohort, *, retries: int, called_directly: bool) -> None:+ task = calculate_cohort_from_list+ task.push_request(retries=retries, called_directly=called_directly, is_eager=True)+ try:+ task.run(cohort.id, ["user123"], team_id=self.team.id, id_type="distinct_id")+ finally:+ task.pop_request()++ @parameterized.expand(+ [+ ("retries_exhausted", ClickHouseAtCapacity, calculate_cohort_from_list.max_retries, False),+ ("called_directly", ClickHouseAtCapacity, 0, True),+ ("not_retryable", ValueError, 0, False),+ ]+ )+ @patch("products.cohorts.backend.models.util.insert_static_cohort")+ def test_records_failure_when_nothing_will_retry(+ self,+ _name: str,+ error_class: type[Exception],+ retries: int,+ called_directly: bool,+ mock_insert_ch: MagicMock,+ ) -> None:+ # raise_on_error hands terminal-state finalization to the task, so whenever no retry+ # follows, the task itself has to clear is_calculating and bump errors_calculating.+ # Otherwise the cohort is stranded looking in-flight forever with no recorded error.+ mock_insert_ch.side_effect = error_class("boom")+ create_person(team=self.team, distinct_ids=["user123"])+ cohort = self._create_static_cohort()++ with self.assertRaises(error_class):+ self._run_task(cohort, retries=retries, called_directly=called_directly)++ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 1)+ self.assertIsNotNone(cohort.last_error_at)++ @patch("products.cohorts.backend.models.util.insert_static_cohort")+ def test_leaves_state_untouched_while_retries_remain(self, mock_insert_ch: MagicMock) -> None:+ # A transient failure with attempts left belongs to the pending autoretry, so recording it+ # now would show a cohort that is still being retried as errored and no longer calculating.+ # Celery raising Retry rather than the original error is what confirms one was scheduled.+ mock_insert_ch.side_effect = ClickHouseAtCapacity()+ create_person(team=self.team, distinct_ids=["user123"])+ cohort = self._create_static_cohort()++ with self.assertRaises(Retry):+ self._run_task(cohort, retries=0, called_directly=False)++ cohort.refresh_from_db()+ self.assertTrue(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 0)++ @patch("products.cohorts.backend.models.util.insert_static_cohort")+ def test_retry_after_transient_failure_completes_the_cohort(self, mock_insert_ch: MagicMock) -> None:+ # What the retry buys: the attempt that follows a capacity blip populates every member and+ # finalizes clean state, and re-running the whole list adds no duplicate members.+ mock_insert_ch.side_effect = [ClickHouseAtCapacity(), None]+ create_person(team=self.team, distinct_ids=["user123"])+ cohort = self._create_static_cohort()++ with self.assertRaises(Retry):+ self._run_task(cohort, retries=0, called_directly=False)++ self._run_task(cohort, retries=1, called_directly=False)++ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 0)+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 1)diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 2660166c1450..ebda2955c7b2 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -811,6 +811,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):team_id: Optional[int] = None,batch_size: int = DEFAULT_COHORT_INSERT_BATCH_SIZE,email_property_key: str | None = None,+ raise_on_error: bool = False,) -> int:"""Insert a list of users identified by their email address into the cohort, for the given team.@@ -820,6 +821,10 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):batch_size: Number of records to process in each batch. Defaults to 1000.email_property_key: Accepted for backwards compatibility but ignored — all lookupsuse the ClickHouse pmat_email materialized column.+ raise_on_error: When True, a batch insert failure is re-raised and terminal cohort+ state is left for the caller to finalize, instead of being swallowed and+ recorded on the cohort here. Use when the caller must not treat a partial+ insert as success."""if team_id is None:team_id = self.team_id@@ -836,7 +841,9 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):return self._get_uuids_for_emails_batch_ch(items[start_idx:end_idx], team_id)batch_iterator = FunctionBatchIterator(create_uuid_batch, batch_size=batch_size, max_items=len(items))- return self._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=True, team_id=team_id)+ return self._insert_users_list_with_batching(+ batch_iterator, insert_in_clickhouse=True, team_id=team_id, raise_on_error=raise_on_error+ )def _get_uuids_for_emails_batch_ch(self, emails: list[str], team_id: int) -> list[str]:if not emails:diff --git a/products/cohorts/backend/models/test/test_cohort_membership.py b/products/cohorts/backend/models/test/test_cohort_membership.pyindex 28992811727c..9a58f71677c1 100644--- a/products/cohorts/backend/models/test/test_cohort_membership.py+++ b/products/cohorts/backend/models/test/test_cohort_membership.py@@ -3,6 +3,9 @@from posthog.test.base import BaseTestfrom unittest.mock import patch+from parameterized import parameterized++from posthog.exceptions import ClickHouseAtCapacityfrom posthog.models import Teamfrom posthog.personhog_client.fake_client import get_active_fakefrom posthog.test.persons import add_cohort_members, create_person@@ -464,3 +467,24 @@ class TestInsertUsersListWithBatchingPersonhog(BaseTest):cohort.insert_users_list_by_uuid([str(person.uuid)], team_id=self.team.id)cohort.insert_users_list_by_uuid([str(person.uuid)], team_id=self.team.id)++ @parameterized.expand([(True,), (False,)])+ @patch("products.cohorts.backend.models.util.insert_static_cohort")+ def test_insert_capacity_error_surfaces_only_with_raise_on_error(self, raise_on_error, mock_insert_ch):+ # A transient ClickHouse capacity error during static-cohort population must propagate when+ # raise_on_error=True, so the retrying calculate_cohort_from_list task can re-run it instead+ # of leaving the cohort half-populated, and terminal state must be left for that task to+ # finalize. Without the flag it stays swallowed and recorded here, which the create() path+ # relies on.+ mock_insert_ch.side_effect = ClickHouseAtCapacity()+ create_person(team=self.team, distinct_ids=["d1"])+ cohort = self._create_static_cohort()++ if raise_on_error:+ with self.assertRaises(ClickHouseAtCapacity):+ cohort.insert_users_by_list(["d1"], team_id=self.team.id, raise_on_error=True)+ else:+ cohort.insert_users_by_list(["d1"], team_id=self.team.id)++ cohort.refresh_from_db()+ assert cohort.errors_calculating == (0 if raise_on_error else 1)