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(clickhouse): wait for zero cohort mutations before enqueueing (#97051)

Eli Reisman7a945ec08d6d
diff --git a/posthog/models/async_deletion/delete_cohorts.py b/posthog/models/async_deletion/delete_cohorts.py
index 40403e12076a..2088c85bc1be 100644
--- a/posthog/models/async_deletion/delete_cohorts.py
+++ b/posthog/models/async_deletion/delete_cohorts.py
@@ -28,10 +28,12 @@ from django.db.models.functions import Cast
from django.utils import timezone
import structlog
+from clickhouse_driver.errors import ServerException
from more_itertools import chunked
from prometheus_client import Counter
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.cluster import TOO_MANY_MUTATIONS
from posthog.dataclasses import frozen
from posthog.models.async_deletion import AsyncDeletion, DeletionType
@@ -64,7 +66,16 @@ COHORT_MARK_PAGE_SIZE = 50_000
# Unfinished mutations on `cohortpeople` the sweep will tolerate before it stops enqueueing more.
# Mutations are enqueued asynchronously, so without this every target chunk lands at once and they
# all compete for the same background pool.
-COHORT_MUTATION_CAPACITY = 2
+#
+# One, not two. `cohortpeople` rejects an enqueue while any mutation on it is unfinished, with
+# "Too many unfinished mutations", so tolerating one in flight means the next chunk is refused and
+# its whole pass is lost. `MutationRunner.wait_for_mutation_capacity`, which the person tables use,
+# waits for zero for the same reason.
+COHORT_MUTATION_CAPACITY = 1
+# The cluster sets `number_of_mutations_to_throw = 1` for every user on the default profile, so a
+# mutation from any other source rejects ours, and the capacity check cannot rule that out: it
+# reads the table before the enqueue, not atomically with it.
+COHORT_MUTATION_RETRIES = 3
COHORT_MUTATION_POLL_SECONDS = 30.0
# Log one line in this many polls. Dagster stores every log line, and a drain can poll for an hour,
# so the wait reports periodically rather than every tick.
@@ -248,7 +259,7 @@ def _mutation_counts(since: datetime | None = None) -> MutationCounts:
def _wait_for_capacity(timeout: float = COHORT_MUTATION_TIMEOUT_SECONDS) -> None:
- """Block until `cohortpeople` is carrying fewer than `COHORT_MUTATION_CAPACITY` mutations.
+ """Block until `cohortpeople` is carrying no unfinished mutations.
Bounded on purpose. A mutation this sweep did not enqueue can hold the table for as long as it
likes, and the ClickHouse client is configured with no practical socket timeout, so an unbounded
@@ -308,17 +319,28 @@ def _delete(targets: list[CohortDeleteTarget], settings: Mapping[str, Any] | Non
"""
issued = 0
for chunk in chunked(targets, COHORT_DELETION_CHUNK_SIZE):
- _wait_for_capacity()
conditions, params = _conditions(list(chunk))
- # nosemgrep: clickhouse-fstring-param-audit - conditions come from CohortDeleteTarget.condition
- sync_execute(
- f"""
- DELETE FROM cohortpeople
- WHERE {" OR ".join(conditions)}
- """,
- params,
- settings={**(settings or {}), "lightweight_deletes_sync": 0},
- )
+ for attempt in range(COHORT_MUTATION_RETRIES + 1):
+ _wait_for_capacity()
+ try:
+ # nosemgrep: clickhouse-fstring-param-audit - conditions come from CohortDeleteTarget.condition
+ sync_execute(
+ f"""
+ DELETE FROM cohortpeople
+ WHERE {" OR ".join(conditions)}
+ """,
+ params,
+ settings={**(settings or {}), "lightweight_deletes_sync": 0},
+ )
+ break
+ except ServerException as error:
+ if error.code != TOO_MANY_MUTATIONS or attempt == COHORT_MUTATION_RETRIES:
+ raise
+ logger.info(
+ "cohortpeople rejected the mutation for capacity, waiting to retry",
+ attempt=attempt + 1,
+ retries=COHORT_MUTATION_RETRIES,
+ )
issued += 1
return issued
diff --git a/posthog/models/test/test_delete_cohorts.py b/posthog/models/test/test_delete_cohorts.py
index efbc5ce5949e..03c490060d83 100644
--- a/posthog/models/test/test_delete_cohorts.py
+++ b/posthog/models/test/test_delete_cohorts.py
@@ -5,15 +5,20 @@ from unittest.mock import patch
from django.test import TestCase
+from clickhouse_driver.errors import ServerException
from parameterized import parameterized
+from posthog.clickhouse.cluster import TOO_MANY_MUTATIONS
from posthog.models import AsyncDeletion, DeletionType, Organization, Team
from posthog.models.async_deletion.delete_cohorts import (
+ COHORT_MUTATION_RETRIES,
CohortDeleteTarget,
CohortKey,
MutationCounts,
_collapse,
+ _delete,
_mark_verified,
+ _wait_for_capacity,
sweep_cohort_deletions,
)
@@ -193,3 +198,58 @@ class TestCollapseCohortDeletions(TestCase):
assert AsyncDeletion.objects.filter(delete_verified_at__isnull=True).count() == 1
assert AsyncDeletion.objects.get(delete_verified_at__isnull=True).key == "21_0"
+
+ def test_capacity_waits_while_any_cohort_mutation_is_still_running(self):
+ # cohortpeople refuses an enqueue while one of its mutations is unfinished, with
+ # "Too many unfinished mutations". Returning on a single in-flight mutation loses the whole
+ # next pass: prod-EU run fb4a4e31 swept Cohort_full, then Cohort_stale was rejected with
+ # code 692 and its targets went unswept. The person tables avoid this because
+ # MutationRunner.wait_for_mutation_capacity waits for zero.
+ counts = [counts_of(3, 1), counts_of(1, 1), counts_of(0, 0)]
+ with (
+ patch(
+ "posthog.models.async_deletion.delete_cohorts._mutation_counts", side_effect=counts
+ ) as mutation_counts,
+ patch("posthog.models.async_deletion.delete_cohorts.time.sleep"),
+ patch("posthog.models.async_deletion.delete_cohorts.time.monotonic", side_effect=range(0, 1000, 10)),
+ ):
+ _wait_for_capacity()
+
+ assert mutation_counts.call_count == len(counts)
+
+ def test_a_rejected_mutation_is_retried_rather_than_losing_the_pass(self):
+ rejected = ServerException("Too many unfinished mutations (1)", code=TOO_MANY_MUTATIONS)
+ with (
+ patch("posthog.models.async_deletion.delete_cohorts.sync_execute", side_effect=[rejected, None]) as execute,
+ patch("posthog.models.async_deletion.delete_cohorts._wait_for_capacity") as capacity,
+ ):
+ issued = _delete([CohortDeleteTarget(team_id=1, cohort_id=2, below_version=None)])
+
+ assert issued == 1
+ assert execute.call_count == 2
+ assert capacity.call_count == 2
+
+ def test_a_mutation_rejected_past_the_retry_bound_fails_the_pass(self):
+ rejected = ServerException("Too many unfinished mutations (1)", code=TOO_MANY_MUTATIONS)
+ attempts = COHORT_MUTATION_RETRIES + 1
+ with (
+ patch(
+ "posthog.models.async_deletion.delete_cohorts.sync_execute", side_effect=[rejected] * attempts
+ ) as execute,
+ patch("posthog.models.async_deletion.delete_cohorts._wait_for_capacity"),
+ pytest.raises(ServerException),
+ ):
+ _delete([CohortDeleteTarget(team_id=1, cohort_id=2, below_version=None)])
+
+ assert execute.call_count == attempts
+
+ def test_a_failure_that_is_not_about_capacity_is_not_retried(self):
+ denied = ServerException("Not enough privileges", code=497)
+ with (
+ patch("posthog.models.async_deletion.delete_cohorts.sync_execute", side_effect=denied) as execute,
+ patch("posthog.models.async_deletion.delete_cohorts._wait_for_capacity"),
+ pytest.raises(ServerException),
+ ):
+ _delete([CohortDeleteTarget(team_id=1, cohort_id=2, below_version=None)])
+
+ assert execute.call_count == 1