: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(experiments): kill the recalc clickhouse query when its activity is cancelled (#100070)
Andersc31121da3693
diff --git a/posthog/clickhouse/cancel.py b/posthog/clickhouse/cancel.pyindex fb76987ad243..31e7ab5dbe06 100644--- a/posthog/clickhouse/cancel.py+++ b/posthog/clickhouse/cancel.py@@ -4,7 +4,12 @@ from posthog import settingsfrom posthog.api.services.query import loggerfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import default_client-from posthog.settings import CLICKHOUSE_CLUSTER+from posthog.settings import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE++# The pooled clients run with an effectively unbounded send/receive timeout, so a kill issued through them+# would hold the caller's thread for as long as a stalled node stays silent. A kill is cleanup and its+# statements carry their own max_execution_time, so its sockets get a short bound instead.+_SEND_RECEIVE_TIMEOUT_SECONDS = 15def cancel_query_on_cluster(team_id: int, client_query_id: str) -> None:@@ -12,15 +17,17 @@ def cancel_query_on_cluster(team_id: int, client_query_id: str) -> None:statsd.incr("clickhouse.query.cancellation.requested", tags={"team_id": team_id})try:- result = sync_execute(- """- SELECT FQDN(), query_id- FROM distributed_system_processes- WHERE query_id LIKE %(client_query_id)s- SETTINGS max_execution_time = 2- """,- {"client_query_id": f"{team_id}_{client_query_id}%"},- )+ with default_client(database=CLICKHOUSE_DATABASE, send_receive_timeout=_SEND_RECEIVE_TIMEOUT_SECONDS) as client:+ result = sync_execute(+ """+ SELECT FQDN(), query_id+ FROM distributed_system_processes+ WHERE query_id LIKE %(client_query_id)s+ SETTINGS max_execution_time = 2+ """,+ {"client_query_id": f"{team_id}_{client_query_id}%"},+ sync_client=client,+ )initiator_host, query_id = result[0] if (result and len(result[0]) == 2) else (None, None)except Exception as e:logger.info("Failed to find initiator host for query %s: %s", client_query_id, e)@@ -28,7 +35,7 @@ def cancel_query_on_cluster(team_id: int, client_query_id: str) -> None:if initiator_host:logger.debug("Found initiator host %s for query %s, cancelling query on host", initiator_host, client_query_id)- with default_client(host=initiator_host) as client:+ with default_client(host=initiator_host, send_receive_timeout=_SEND_RECEIVE_TIMEOUT_SECONDS) as client:result = sync_execute("KILL QUERY WHERE query_id=%(query_id)s SETTINGS max_execution_time = 5",{"query_id": query_id},@@ -38,10 +45,12 @@ def cancel_query_on_cluster(team_id: int, client_query_id: str) -> None:statsd.incr("clickhouse.query.cancellation.ok", tags={"team_id": team_id})elif settings.CLICKHOUSE_FALLBACK_CANCEL_QUERY_ON_CLUSTER:logger.debug("No initiator host found for query %s, cancelling query on cluster", client_query_id)- # nosemgrep: clickhouse-fstring-param-audit - CLICKHOUSE_CLUSTER from settings constant- result = sync_execute(- f"KILL QUERY ON CLUSTER '{CLICKHOUSE_CLUSTER}' WHERE query_id LIKE %(client_query_id)s SETTINGS max_execution_time = 10, skip_unavailable_shards=1",- {"client_query_id": f"{team_id}_{client_query_id}%"},- )+ with default_client(database=CLICKHOUSE_DATABASE, send_receive_timeout=_SEND_RECEIVE_TIMEOUT_SECONDS) as client:+ # nosemgrep: clickhouse-fstring-param-audit - CLICKHOUSE_CLUSTER from settings constant+ result = sync_execute(+ f"KILL QUERY ON CLUSTER '{CLICKHOUSE_CLUSTER}' WHERE query_id LIKE %(client_query_id)s SETTINGS max_execution_time = 10, skip_unavailable_shards=1",+ {"client_query_id": f"{team_id}_{client_query_id}%"},+ sync_client=client,+ )logger.info("Cancelled query %s for team %s, result: %s", client_query_id, team_id, result)statsd.incr("clickhouse.query.cancellation.on_cluster", tags={"team_id": team_id})diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex 6fd136e10a57..4e87937d1a18 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -372,22 +372,30 @@ def get_pool(return make_ch_pool(**kwargs)-def default_client(host=settings.CLICKHOUSE_HOST, password=None):+def default_client(+ host=settings.CLICKHOUSE_HOST,+ password=None,+ *,+ database: str = "system",+ send_receive_timeout: int | None = None,+):"""Return a bare bones client for use in places where we are only interested in general ClickHouse stateDO NOT USE THIS FOR QUERYING DATApassword overrides the static CLICKHOUSE_PASSWORD, for example with a resolved file-backed token.+ send_receive_timeout bounds each socket read and write; None keeps the driver default."""return SyncClient(host=host,+ **({"send_receive_timeout": send_receive_timeout} if send_receive_timeout is not None else {}),# We set "system" here as we don't necessarily have a "default" database,# which is what the clickhouse_driver would use by default. We are# assuming that this exists and we have permissions to access it. This# feels like a reasonably safe assumption as e.g. we already reference# `system.numbers` in multiple places within queries. We also assume# access to various other tables e.g. to handle async migrations.- database="system",+ database=database,secure=settings.CLICKHOUSE_SECURE,user=settings.CLICKHOUSE_USER,password=settings.CLICKHOUSE_PASSWORD if password is None else password,diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pyindex 877e681f85d1..d1fd255588b4 100644--- a/products/experiments/backend/recalculation.py+++ b/products/experiments/backend/recalculation.py@@ -93,8 +93,9 @@ def get_live_query_progress(recalc: ExperimentMetricsRecalculation) -> dict | Noqueries already finished during the run from system.query_log, matched by query_id prefix.Returns None unless the run is IN_PROGRESS. No storage needed: each metric query is tagged with the- deterministic client_query_id `experiment_metric_recalc_{recalc_id}_{metric_uuid}`, which ClickHouse- stamps into query_id as `{team_id}_{client_query_id}_{random}`. system.processes only holds a query+ deterministic client_query_id `experiment_metric_recalc_{recalc_id}_{metric_uuid}_attempt{attempt:02d}`,+ which ClickHouse stamps into query_id as `{team_id}_{client_query_id}_{random}`. The prefix matched below+ stops at the recalc id, so the metric and attempt suffixes do not affect it. system.processes only holds a querywhile it executes, and the metric queries are usually shorter than the poll interval, so processesalone reads zero for most of the run; the query_log branch keeps finished queries counted, makingrows_read cumulative and roughly monotonic across the run (modulo query_log flush lag).diff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.pyindex 4e59842e6cb3..8eb09c4021ef 100644--- a/products/experiments/backend/temporal/recalculation_activities.py+++ b/products/experiments/backend/temporal/recalculation_activities.py@@ -19,12 +19,61 @@ from products.experiments.backend.temporal.models import ()from products.experiments.backend.temporal.recalculation_logic import (_calculate_experiment_metric_for_recalculation_sync,+ _cancel_metric_query_sync,_discover_experiment_metrics_sync,_update_recalculation_progress_sync,)logger = structlog.get_logger(__name__)+_CANCEL_KILL_RETRY_INTERVAL_SECONDS = 2.0+++async def _drain_cancelled_body(+ task: asyncio.Task[MetricRecalculationResult],+ deadline: float,+ recalculation_id: str,+ metric_uuid: str,+ attempt: int,+) -> None:+ # sync_to_async cannot stop its worker thread, and returning while it runs leaves the ClickHouse query, its+ # DB connection and the runner's result buffers alive and unsupervised. Kill the query so the thread returns+ # now instead of at max_execution_time, then wait it out until the attempt's own deadline, which the body+ # cannot outlive by design. The kill repeats because it only hits a query ClickHouse has registered, and a+ # cancel during the body's Postgres phase precedes that. It also runs once past the deadline, because it is+ # the cheap part and the thread keeps reading otherwise.+ loop = asyncio.get_running_loop()+ while not task.done():+ try:+ await _cancel_metric_query_sync(recalculation_id, metric_uuid, attempt)+ except Exception:+ logger.warning(+ "experiment_metric_recalculation_query_cancel_failed",+ metric_uuid=metric_uuid,+ recalculation_id=recalculation_id,+ exc_info=True,+ )+ remaining = deadline - loop.time()+ if remaining <= 0:+ logger.warning(+ "experiment_metric_recalculation_drain_after_cancel_timed_out",+ metric_uuid=metric_uuid,+ recalculation_id=recalculation_id,+ )+ return+ try:+ await asyncio.wait_for(asyncio.shield(task), timeout=min(_CANCEL_KILL_RETRY_INTERVAL_SECONDS, remaining))+ except TimeoutError:+ continue+ except Exception:+ logger.warning(+ "experiment_metric_recalculation_drain_after_cancel_failed",+ metric_uuid=metric_uuid,+ recalculation_id=recalculation_id,+ exc_info=True,+ )+ return+@temporalio.activity.defnasync def discover_experiment_metrics(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:@@ -63,6 +112,7 @@ async def calculate_experiment_metric_for_recalculation("""attempt = temporalio.activity.info().attemptis_final_attempt = attempt >= MAX_METRIC_ATTEMPTS+ deadline = asyncio.get_running_loop().time() + METRIC_CALC_ACTIVITY_TIMEOUT_SECONDStask = asyncio.ensure_future(_calculate_experiment_metric_for_recalculation_sync(experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt, attempt@@ -72,7 +122,7 @@ async def calculate_experiment_metric_for_recalculation(return await asyncio.shield(task)except asyncio.CancelledError:# Keep the worker slot while the uncancellable thread finishes, but bound shutdown cleanup.- drain = asyncio.create_task(asyncio.wait_for(asyncio.shield(task), METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS))+ drain = asyncio.create_task(_drain_cancelled_body(task, deadline, recalculation_id, metric_uuid, attempt))while True:try:await asyncio.shield(drain)@@ -80,12 +130,4 @@ async def calculate_experiment_metric_for_recalculation(except asyncio.CancelledError:if drain.cancelled():break- except Exception:- logger.warning(- "experiment_metric_recalculation_drain_after_cancel_failed",- metric_uuid=metric_uuid,- recalculation_id=recalculation_id,- exc_info=True,- )- breakraisediff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 8788ec861596..0d1ff510a539 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -19,9 +19,10 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.schema import ExperimentQuery+from posthog.clickhouse.cancel import cancel_query_on_clusterfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries, tags_contextfrom posthog.event_usage import groupsfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exception@@ -612,6 +613,38 @@ def _capture_experiment_metric_event(# ---------------------------------------------------------------------------+def _client_query_id(recalculation_id: str, metric_uuid: str, attempt: int) -> str:+ """The ClickHouse client_query_id this metric's recalc query runs under.++ The calculation path tags its query with this, and the cancellation path kills the query by it, so both+ sides must derive it the same way.++ The attempt keeps one attempt's cancellation off another attempt's query, which matters when Temporal+ re-dispatches an activity whose previous attempt is still draining. It is zero-padded because the kill+ matches the id as a LIKE prefix, where an unpadded "1" would also match attempt 12.++ `get_live_query_progress` matches on the recalculation id, which sits before this suffix, so its prefix+ still matches.+ """+ return f"experiment_metric_recalc_{recalculation_id}_{metric_uuid}_attempt{attempt:02d}"+++@database_sync_to_async_pool+def _cancel_metric_query_sync(recalculation_id: str, metric_uuid: str, attempt: int) -> None:+ """Kill the ClickHouse query the metric's calc left running, so the abandoned attempt stops reading."""+ close_old_connections()+ state = _get_recalc_state(recalculation_id)+ # This runs in its own thread, so it inherits none of the calc body's tags. Untagged statements raise in+ # local dev and log a stack trace each in production.+ with tags_context(+ trigger="warming/experiment_metrics_recalculation",+ team_id=state.team_id,+ product=Product.EXPERIMENTS,+ feature=Feature.CACHE_WARMUP,+ ):+ cancel_query_on_cluster(state.team_id, _client_query_id(recalculation_id, metric_uuid, attempt))++@database_sync_to_async_pooldef _calculate_experiment_metric_for_recalculation_sync(experiment_id: int,@@ -705,7 +738,7 @@ def _calculate_experiment_metric_for_recalculation_sync(_clear_retry(recalculation_id, metric_uuid)return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)- client_query_id = f"experiment_metric_recalc_{recalculation_id}_{metric_uuid}"+ client_query_id = _client_query_id(recalculation_id, metric_uuid, attempt)calc_started_at = time.perf_counter()query_from = experiment.start_datediff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex 634dbaa78251..28091931dc5c 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -6,7 +6,7 @@ from types import SimpleNamespaceimport pytestimport time_machinefrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import AsyncMock, patchfrom django.utils import timezone@@ -16,6 +16,7 @@ from rest_framework.exceptions import ValidationErrorfrom temporalio.exceptions import ApplicationErrorfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tagsfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOutfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint@@ -37,6 +38,7 @@ from products.experiments.backend.temporal.recalc_fingerprint import compute_recfrom products.experiments.backend.temporal.recalculation_activities import calculate_experiment_metric_for_recalculationfrom products.experiments.backend.temporal.recalculation_logic import (_calculate_experiment_metric_for_recalculation_sync,+ _cancel_metric_query_sync,_discover_experiment_metrics_sync,_store_result,_update_recalculation_progress_sync,@@ -47,6 +49,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag_discover_raw = _discover_experiment_metrics_sync.func # type: ignore[attr-defined]_update_raw = _update_recalculation_progress_sync.func # type: ignore[attr-defined]_calculate_raw = _calculate_experiment_metric_for_recalculation_sync.func # type: ignore[attr-defined]+_cancel_raw = _cancel_metric_query_sync.func # type: ignore[attr-defined]def _discover(recalculation_id: str):@@ -928,7 +931,7 @@ class TestCalculateActivity(BaseTest):_calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")- assert row.query_id == f"experiment_metric_recalc_{recalc.id}_m1"+ assert row.query_id == f"experiment_metric_recalc_{recalc.id}_m1_attempt01"def test_multiple_failures_accumulate_in_metric_errors(self):# Two metrics fail in sequence (not in parallel — that would need threads + a real Postgres). Pins the@@ -1242,6 +1245,30 @@ class TestCalculateActivity(BaseTest):assert row.error_message is not Noneassert len(row.error_message) <= 2000+ def test_cancel_metric_query_tags_its_queries(self):+ # The kill runs in its own thread, so it inherits none of the calc body's tags. Untagged sync_execute+ # calls raise in local dev, which makes the kill fail silently there.+ exp = self._experiment(flag_key="cancel-tags", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])+ seen: dict = {}++ def _capture(team_id: int, client_query_id: str) -> None:+ seen["args"] = (team_id, client_query_id)+ seen["tags"] = get_query_tags().model_copy()++ with (+ patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"),+ patch("products.experiments.backend.temporal.recalculation_logic.cancel_query_on_cluster", _capture),+ ):+ _cancel_raw(str(recalc.id), "m1", 3)++ assert seen["args"] == (self.team.id, f"experiment_metric_recalc_{recalc.id}_m1_attempt03")+ assert (seen["tags"].team_id, seen["tags"].product, seen["tags"].feature) == (+ self.team.id,+ Product.EXPERIMENTS,+ Feature.CACHE_WARMUP,+ )+@pytest.mark.django_db(transaction=True)class TestMissingRecalcRow:@@ -1271,6 +1298,24 @@ class TestMissingRecalcRow:class TestCalculateActivityCancellation:+ @contextmanager+ def _patched_boundaries(self, body, cancel_query):+ with (+ patch(+ "products.experiments.backend.temporal.recalculation_activities._calculate_experiment_metric_for_recalculation_sync",+ body,+ ),+ patch(+ "products.experiments.backend.temporal.recalculation_activities._cancel_metric_query_sync", cancel_query+ ),+ patch(+ "products.experiments.backend.temporal.recalculation_activities._CANCEL_KILL_RETRY_INTERVAL_SECONDS",+ 0.001,+ ),+ patch("temporalio.activity.info", return_value=SimpleNamespace(attempt=1)),+ ):+ yield+@pytest.mark.parametrize("cancellations", [1, 2])@pytest.mark.parametrize("body_fails", [False, True])async def test_cancellation_drains_the_body_before_propagating(self, cancellations: int, body_fails: bool) -> None:@@ -1287,13 +1332,7 @@ class TestCalculateActivityCancellation:raise RuntimeError("calculation failed during cleanup")return MetricRecalculationResult(metric_uuid="m1", success=True)- with (- patch(- "products.experiments.backend.temporal.recalculation_activities._calculate_experiment_metric_for_recalculation_sync",- _slow_body,- ),- patch("temporalio.activity.info", return_value=SimpleNamespace(attempt=1)),- ):+ with self._patched_boundaries(_slow_body, AsyncMock()):task = asyncio.create_task(calculate_experiment_metric_for_recalculation(1, "m1", "r1", _QUERY_TO))await started.wait()try:@@ -1313,6 +1352,7 @@ class TestCalculateActivityCancellation:started = asyncio.Event()release = asyncio.Event()body_finished = asyncio.Event()+ cancel_query = AsyncMock()async def _slow_body(*args: object, **kwargs: object) -> MetricRecalculationResult:started.set()@@ -1321,11 +1361,7 @@ class TestCalculateActivityCancellation:return MetricRecalculationResult(metric_uuid="m1", success=True)with (- patch(- "products.experiments.backend.temporal.recalculation_activities._calculate_experiment_metric_for_recalculation_sync",- _slow_body,- ),- patch("temporalio.activity.info", return_value=SimpleNamespace(attempt=1)),+ self._patched_boundaries(_slow_body, cancel_query),patch("products.experiments.backend.temporal.recalculation_activities.METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS", 0),@@ -1337,10 +1373,65 @@ class TestCalculateActivityCancellation:with pytest.raises(asyncio.CancelledError, match="original cancellation"):await asyncio.wait_for(task, timeout=5)assert not body_finished.is_set()+ assert cancel_query.await_count == 1finally:release.set()await asyncio.wait_for(body_finished.wait(), timeout=5)+ async def _cancel_during_body(self, kills_until_query_dies: int = 1) -> dict:+ started = asyncio.Event()+ query_died = asyncio.Event()+ observed: dict = {+ "body_finished": False,+ "cancel_calls": 0,+ "cancel_args": None,+ "cancelled_before_body_finished": None,+ }++ async def _slow_body(*args: object, **kwargs: object) -> MetricRecalculationResult:+ started.set()+ await query_died.wait()+ observed["body_finished"] = True+ return MetricRecalculationResult(metric_uuid="m1", success=True)++ async def _fake_cancel_query(recalculation_id: str, metric_uuid: str, attempt: int) -> None:+ observed["cancel_calls"] += 1+ observed["cancel_args"] = (recalculation_id, metric_uuid, attempt)+ observed["cancelled_before_body_finished"] = not observed["body_finished"]+ if observed["cancel_calls"] == kills_until_query_dies:+ query_died.set()++ with (+ self._patched_boundaries(_slow_body, _fake_cancel_query),+ patch(+ "products.experiments.backend.temporal.recalculation_activities.METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS", 1+ ),+ ):+ task = asyncio.create_task(calculate_experiment_metric_for_recalculation(1, "m1", "r1", _QUERY_TO))+ await started.wait()+ task.cancel()++ with pytest.raises(asyncio.CancelledError):+ await task++ return observed++ async def test_cancellation_kills_the_running_clickhouse_query_first(self) -> None:+ # Without the kill the drain waits out the query's full max_execution_time, and ClickHouse keeps reading+ # for an attempt whose result nothing will use.+ observed = await self._cancel_during_body()++ assert observed["cancel_args"] == ("r1", "m1", 1)+ assert observed["cancelled_before_body_finished"] is True++ async def test_cancellation_retries_the_kill_when_the_first_one_misses(self) -> None:+ # A cancel that lands during the body's Postgres phase kills before ClickHouse registers the query, so+ # the first kill finds nothing.+ observed = await self._cancel_during_body(kills_until_query_dies=2)++ assert observed["cancel_calls"] == 2+ assert observed["body_finished"] is True+@contextmanagerdef _record_captures():diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.pyindex c54c933e07e4..e2d279bca1fa 100644--- a/products/experiments/backend/test/test_recalculation_service.py+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -586,7 +586,7 @@ class TestLiveQueryProgressFinishedQueries(BaseTest, ClickhouseTestMixin):with tags_context(team_id=self.team.id,- client_query_id=f"experiment_metric_recalc_{recalc.id}_metric-1",+ client_query_id=f"experiment_metric_recalc_{recalc.id}_metric-1_attempt01",product=Product.EXPERIMENTS,feature=Feature.CACHE_WARMUP,):