: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(aio): stop trace clustering from starving the ClickHouse pool (#73806)
posthog[bot]f4f10f8790ee
diff --git a/posthog/temporal/ai_observability/trace_clustering/README.md b/posthog/temporal/ai_observability/trace_clustering/README.mdindex f56df9f351e0..103bcce6927b 100644--- a/posthog/temporal/ai_observability/trace_clustering/README.md+++ b/posthog/temporal/ai_observability/trace_clustering/README.md@@ -345,7 +345,9 @@ Key constants in `constants.py`:| `DEFAULT_LOOKBACK_DAYS` | 7 | Days of trace history to analyze || `DEFAULT_MAX_SAMPLES` | 1500 | Maximum traces to sample || `MIN_TRACES_FOR_CLUSTERING` | 1000 | Minimum items per level required for workflow |-| `COMPUTE_ACTIVITY_TIMEOUT` | 120s | Clustering compute timeout |+| `WORKFLOW_EXECUTION_TIMEOUT` | 45m | Per-team workflow execution timeout |+| `COMPUTE_ACTIVITY_TIMEOUT` | 300s | Per-attempt clustering compute timeout |+| `COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT` | 720s | Total compute timeout including retries, backoff, and queueing || `EMIT_ACTIVITY_TIMEOUT` | 60s | Event emission timeout || `LABELING_AGENT_MODEL` | gpt-5.4 | OpenAI model for labeling agent || `LABELING_AGENT_MAX_ITERATIONS` | 50 | Max agent iterations before finalization |diff --git a/posthog/temporal/ai_observability/trace_clustering/activities.py b/posthog/temporal/ai_observability/trace_clustering/activities.pyindex 054cda8df48d..1ae0fce2c8fb 100644--- a/posthog/temporal/ai_observability/trace_clustering/activities.py+++ b/posthog/temporal/ai_observability/trace_clustering/activities.py@@ -6,7 +6,9 @@ This module contains the 3 activities that make up the clustering pipeline:3. emit_cluster_events_activity - emit results to ClickHouse"""+import randomimport asyncio+from datetime import timedeltafrom typing import Literal, castfrom django.utils.dateparse import parse_datetime@@ -14,7 +16,9 @@ from django.utils.dateparse import parse_datetimeimport numpy as npimport structlogfrom temporalio import activity+from temporalio.exceptions import ApplicationError+from posthog.exceptions import ClickHouseAtCapacityfrom posthog.models.team import Teamfrom posthog.temporal.ai_observability.team_discovery import get_min_traces_overridefrom posthog.temporal.ai_observability.trace_clustering import constants@@ -286,7 +290,26 @@ async def perform_clustering_compute_activity(inputs: ClusteringActivityInputs)Embeddings (~3-4 MB) are not passed to subsequent activities."""async with Heartbeater():- return await asyncio.to_thread(_perform_clustering_compute, inputs)+ try:+ return await asyncio.to_thread(_perform_clustering_compute, inputs)+ except ClickHouseAtCapacity as e:+ # The shared ClickHouse pool is saturated. Retrying immediately would only add load,+ # so back off with jitter to give the pool room to recover before the next attempt.+ backoff = random.uniform(+ constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MIN.total_seconds(),+ constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MAX.total_seconds(),+ )+ logger.warning(+ "clustering_compute_clickhouse_at_capacity",+ team_id=inputs.team_id,+ analysis_level=inputs.analysis_level,+ backoff_seconds=round(backoff, 1),+ )+ raise ApplicationError(+ "ClickHouse at capacity while fetching embeddings for clustering",+ type="ClickHouseAtCapacity",+ next_retry_delay=timedelta(seconds=backoff),+ ) from edef _generate_cluster_labels(inputs: GenerateLabelsActivityInputs) -> GenerateLabelsActivityOutputs:diff --git a/posthog/temporal/ai_observability/trace_clustering/constants.py b/posthog/temporal/ai_observability/trace_clustering/constants.pyindex b68b8cf69797..135b6898d3b5 100644--- a/posthog/temporal/ai_observability/trace_clustering/constants.py+++ b/posthog/temporal/ai_observability/trace_clustering/constants.py@@ -16,11 +16,14 @@ DEFAULT_MAX_K = 10# generations.MIN_TRACES_FOR_CLUSTERING = 1000-# Coordinator concurrency settings-DEFAULT_MAX_CONCURRENT_TEAMS = 4 # Max teams to process in parallel+# Coordinator concurrency settings.+# Each team's compute activity runs a heavy embedding scan against ClickHouse, so keep the+# fan-out low to avoid exhausting the shared query pool (see the offline-workload routing in+# data.py and the capacity backoff in activities.py).+DEFAULT_MAX_CONCURRENT_TEAMS = 2 # Max teams to process in parallel# Workflow timeouts-WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=30)+WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=45) # Covers all activity budgets plus orchestration overheadCOORDINATOR_EXECUTION_TIMEOUT = timedelta(hours=12) # Must be less than daily schedule interval to avoid blocking# Temporal configurationWORKFLOW_NAME = "llma-trace-clustering"@@ -33,7 +36,7 @@ GENERATION_COORDINATOR_SCHEDULE_ID = "llma-generation-clustering-coordinator-schGENERATION_CHILD_WORKFLOW_ID_PREFIX = "llma-generation-clustering-team"# Activity timeouts (per activity type, per single attempt)-COMPUTE_ACTIVITY_TIMEOUT = timedelta(seconds=120) # Fetch + clustering + distances+COMPUTE_ACTIVITY_TIMEOUT = timedelta(seconds=300) # Two 120s ClickHouse query caps plus clusteringLLM_ACTIVITY_TIMEOUT = timedelta(seconds=600) # 10 minutes for full labeling agent run (LangGraph multi-turn)AGGREGATES_ACTIVITY_TIMEOUT = timedelta(seconds=300) # 5 min budget for metricsEMIT_ACTIVITY_TIMEOUT = timedelta(seconds=60) # ClickHouse write@@ -50,7 +53,7 @@ EMIT_HEARTBEAT_TIMEOUT = timedelta(seconds=30) # 30 seconds - ClickHouse writes# Schedule-to-close timeouts - caps total time including all retry attempts,# backoff intervals, and queue time. Prevents runaway retries from blocking# the workflow indefinitely.-COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=300) # 5 min (2 attempts * 120s + backoff)+COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=720) # Two attempts, 60s backoff, and queue timeLLM_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=900) # 15 min (2 attempts * 600s + backoff, capped)AGGREGATES_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=330) # 5.5 min (1 attempt only, best-effort)EMIT_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=150) # 2.5 min (2 attempts * 60s + backoff)@@ -64,6 +67,13 @@ COMPUTE_ACTIVITY_RETRY_POLICY = RetryPolicy(non_retryable_error_types=["ValueError", "TypeError"],)+# When ClickHouse reports it is at capacity (too many simultaneous queries), an immediate retry+# just piles more load onto a pool that is already starved. Back off with jitter instead, so the+# retry lands after the contention has had a chance to clear. Jitter spreads retries from the+# concurrent per-team activities so they don't all re-fire at the same instant.+CLICKHOUSE_AT_CAPACITY_BACKOFF_MIN = timedelta(seconds=20)+CLICKHOUSE_AT_CAPACITY_BACKOFF_MAX = timedelta(seconds=60)+# LLM activity - external dependency, longer intervals between retriesLLM_ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=2,diff --git a/posthog/temporal/ai_observability/trace_clustering/data.py b/posthog/temporal/ai_observability/trace_clustering/data.pyindex d0ee3ae71793..b14ec6407990 100644--- a/posthog/temporal/ai_observability/trace_clustering/data.py+++ b/posthog/temporal/ai_observability/trace_clustering/data.py@@ -15,6 +15,7 @@ from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.team import Teamfrom posthog.temporal.ai_observability.trace_clustering import constants@@ -124,6 +125,9 @@ def fetch_item_embeddings_for_clustering(query=query,placeholders=placeholders,team=team,+ # Background clustering scans run on the offline cluster so they don't compete with+ # user-facing traffic on the online `default` pool (this is a large embedding scan).+ workload=Workload.OFFLINE,settings=HogQLGlobalSettings(max_execution_time=CLUSTERING_QUERY_MAX_EXECUTION_TIME),)@@ -244,6 +248,7 @@ def fetch_item_summaries("max_rows": ast.Constant(value=max_rows),},team=team,+ workload=Workload.OFFLINE,settings=HogQLGlobalSettings(max_execution_time=CLUSTERING_QUERY_MAX_EXECUTION_TIME),)@@ -380,6 +385,7 @@ def fetch_item_metrics(query=query,placeholders=placeholders,team=team,+ workload=Workload.OFFLINE,settings=HogQLGlobalSettings(max_execution_time=CLUSTERING_QUERY_MAX_EXECUTION_TIME),)diff --git a/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py b/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.pyindex e3451ac5c4e2..eed17f12659a 100644--- a/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py+++ b/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py@@ -342,3 +342,46 @@ class TestEmptyComputeResultShortCircuit:assert result.clusters == []assert result.clustering_run_id == "run-empty"assert result.team_id == 1+++class TestComputeActivityCapacityBackoff:+ """The compute activity must not let a ClickHouse capacity error retry immediately.++ Guards the incident fix: on `ClickHouseAtCapacity` the activity backs off with jitter+ (via ApplicationError.next_retry_delay) so a saturated pool gets breathing room instead+ of more queries. A regression here would restore the immediate-retry load spiral.+ """++ @pytest.mark.asyncio+ async def test_clickhouse_at_capacity_raises_jittered_backoff(self):+ from unittest.mock import patch++ from temporalio.exceptions import ApplicationError+ from temporalio.testing import ActivityEnvironment++ from posthog.exceptions import ClickHouseAtCapacity+ from posthog.temporal.ai_observability.trace_clustering import constants+ from posthog.temporal.ai_observability.trace_clustering.activities import perform_clustering_compute_activity++ inputs = ClusteringActivityInputs(+ team_id=1,+ window_start="2025-01-01T00:00:00Z",+ window_end="2025-01-08T00:00:00Z",+ )++ with patch(+ "posthog.temporal.ai_observability.trace_clustering.activities._perform_clustering_compute",+ side_effect=ClickHouseAtCapacity(),+ ):+ with pytest.raises(ApplicationError) as exc_info:+ await ActivityEnvironment().run(perform_clustering_compute_activity, inputs)++ err = exc_info.value+ assert err.type == "ClickHouseAtCapacity"+ assert err.non_retryable is False+ assert err.next_retry_delay is not None+ assert (+ constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MIN+ <= err.next_retry_delay+ <= constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MAX+ )