: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(clickhouse): wait for mutation capacity before enqueueing and cap… (#70531)
Bryan Ciaraldi74f0a2326e8d
diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex 422a3852b5f1..95f1767b9cc1 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -13,6 +13,7 @@ from dataclasses import dataclass, fieldfrom typing import Any, ClassVar, Generic, Literal, NamedTuple, Optional, TypeVarfrom clickhouse_driver import Client+from clickhouse_driver.errors import ServerExceptionfrom clickhouse_pool import ChPoolfrom posthog import settings@@ -684,6 +685,10 @@ class MutationNotFound(Exception):pass+# not present in clickhouse_driver.errors.ErrorCodes; see ClickHouse src/Common/ErrorCodes.cpp+TOO_MANY_MUTATIONS = 692++@dataclassclass MutationWaiter:table: str@@ -763,7 +768,17 @@ class MutationRunner(abc.ABC):if not commands_to_enqueue:return MutationWaiter(self.table, set(mutations_running.values()))- client.execute(self.get_statement(commands_to_enqueue), self.parameters, settings=self.settings)+ while True:+ self.wait_for_mutation_capacity(client)+ try:+ client.execute(self.get_statement(commands_to_enqueue), self.parameters, settings=self.settings)+ break+ except ServerException as e:+ # another mutation can land in the gap between the capacity check and our ALTER, so+ # go back to waiting instead of failing+ if e.code != TOO_MANY_MUTATIONS:+ raise+ logger.info("Mutation rejected by %s due to unfinished mutations, waiting for capacity...", self.table)# mutations are not always immediately visible, so give anything new a bit of time to show upstart = time.time()@@ -777,6 +792,31 @@ class MutationRunner(abc.ABC):f"unable to find mutation for {expected_commands - mutations_running.keys()!r} after {time.time() - start:0.2f}s!")+ def wait_for_mutation_capacity(self, client: Client, poll_interval: float = 60.0) -> None:+ """+ Block until the target table has no unfinished mutations before enqueueing a new one, since tables can be+ configured with ``number_of_mutations_to_throw`` to reject new mutations while others (e.g. a long-running+ backfill) are still in flight.+ """+ while True:+ [[count]] = client.execute(+ """+ SELECT count()+ FROM system.mutations+ WHERE database = %(database)s AND table = %(table)s AND NOT is_done AND NOT is_killed+ """,+ {"database": settings.CLICKHOUSE_DATABASE, "table": self.table},+ )+ if count == 0:+ return+ logger.info(+ "Waiting for %s unfinished mutation(s) on %s before enqueueing new mutation (checking again in %ss)...",+ count,+ self.table,+ poll_interval,+ )+ time.sleep(poll_interval)+def find_existing_mutations(self, client: Client, commands: Set[str] | None = None) -> Mapping[str, str]:"""Find the mutation ID (if it exists) associated with each command provided (or all commands if no commands arediff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.pyindex d2bbbe8fca5f..1dcd67dbae5e 100644--- a/posthog/clickhouse/test/test_cluster.py+++ b/posthog/clickhouse/test/test_cluster.py@@ -9,9 +9,11 @@ from posthog.test.base import materializedfrom unittest.mock import Mock, patch, sentinelfrom clickhouse_driver import Client+from clickhouse_driver.errors import ServerExceptionfrom posthog.clickhouse.client.connection import NodeRole, Workloadfrom posthog.clickhouse.cluster import (+ TOO_MANY_MUTATIONS,AlterTableMutationRunner,ClickhouseCluster,HostInfo,@@ -37,6 +39,37 @@ def test_mutation_runner_rejects_invalid_parameters() -> None:AlterTableMutationRunner(table="table", commands={"command"}, parameters={"__invalid_key": True})+def test_mutation_runner_waits_for_capacity_and_retries_rejected_enqueue() -> None:+ runner = AlterTableMutationRunner(table=EVENTS_DATA_TABLE(), commands={"UPDATE person_id = person_id WHERE 1"})++ # busy on the first capacity check, clear on the check preceding each of the two enqueue attempts+ capacity_results = iter([[[1]], [[0]], [[0]]])+ # no matching mutation before enqueueing, found after the enqueue succeeds+ lookup_results = iter([[(None,)], [("0000000042",)]])+ alter_attempts: list[str] = []++ def execute(query: str, *args: object, **kwargs: object) -> object:+ if query.lstrip().startswith("ALTER TABLE"):+ alter_attempts.append(query)+ if len(alter_attempts) == 1:+ raise ServerException("too many unfinished mutations", code=TOO_MANY_MUTATIONS)+ return []+ elif "NOT is_done AND NOT is_killed" in query:+ return next(capacity_results)+ else:+ return next(lookup_results)++ client = Mock()+ client.execute = Mock(side_effect=execute)++ with patch("posthog.clickhouse.cluster.time.sleep"):+ waiter = runner(client)++ assert waiter == MutationWaiter(runner.table, {"0000000042"})+ assert len(alter_attempts) == 2+ assert next(capacity_results, None) is None # polled through the busy table before each enqueue attempt++def test_exception_summary(snapshot, cluster: ClickhouseCluster) -> None:def replace_memory_addresses_and_ips(value):message = re.sub(r"0x[0-9A-Fa-f]{16}", "0x0000000000000000", value)diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.pyindex a818f5d04b6a..661f0ed3e481 100644--- a/posthog/dags/common/resources.py+++ b/posthog/dags/common/resources.py@@ -73,6 +73,7 @@ class ClickhouseClusterResource(dagster.ConfigurableResource):host: str = settings.CLICKHOUSE_HOSTcluster: str | None = None+ retry_max_attempts: int = 8def create_resource(self, context: dagster.InitResourceContext) -> ClickhouseCluster:return get_cluster(@@ -81,8 +82,8 @@ class ClickhouseClusterResource(dagster.ConfigurableResource):cluster=self.cluster,client_settings=self.client_settings,retry_policy=RetryPolicy(- max_attempts=8,- delay=ExponentialBackoff(20),+ max_attempts=self.retry_max_attempts,+ delay=ExponentialBackoff(20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),)@@ -113,7 +114,7 @@ class OpsClickhouseClusterResource(dagster.ConfigurableResource):},retry_policy=RetryPolicy(max_attempts=2,- delay=ExponentialBackoff(20),+ delay=ExponentialBackoff(20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),)@@ -156,7 +157,7 @@ class BackupsClickhouseClusterResource(dagster.ConfigurableResource):client_settings=self.client_settings,retry_policy=RetryPolicy(max_attempts=8,- delay=ExponentialBackoff(20),+ delay=ExponentialBackoff(20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),connection_overrides={"user": user, "password": password},@@ -193,7 +194,7 @@ class PartBreakerClickhouseClusterResource(dagster.ConfigurableResource):client_settings=self.client_settings,retry_policy=RetryPolicy(max_attempts=8,- delay=ExponentialBackoff(20),+ delay=ExponentialBackoff(20, max_delay=60),exceptions=_is_retryable_clickhouse_exception,),connection_overrides={"user": user, "password": password},diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex 3840835554f9..6693590fbc70 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -822,7 +822,12 @@ def deletes_job():request_job=deletes_job,)def run_deletes_after_squash(context):- return dagster.RunRequest(run_key=None)+ # mutation waits can span hours, so allow more transient failures per host before failing the+ # weekly deletes run+ return dagster.RunRequest(+ run_key=None,+ run_config={"resources": {"cluster": {"config": {"retry_max_attempts": 20}}}},+ )@dagster.opdiff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.pyindex ef22cd2348c3..66a68b43c6da 100644--- a/posthog/dags/person_overrides.py+++ b/posthog/dags/person_overrides.py@@ -330,4 +330,7 @@ squash_schedule = dagster.ScheduleDefinition(cron_schedule=settings.SQUASH_PERSON_OVERRIDES_SCHEDULE,execution_timezone="UTC",name="squash_person_overrides_schedule",+ # mutation waits can span hours, so allow more transient failures per host before failing the+ # weekly run (downstream deletes only trigger on success)+ run_config={"resources": {"cluster": {"config": {"retry_max_attempts": 20}}}},)