: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): report clustering capacity errors only on the last attempt (#117557)
Carlos Marchale946db510fb7
diff --git a/posthog/temporal/ai_observability/retries.py b/posthog/temporal/ai_observability/retries.pynew file mode 100644index 000000000000..b8c8622b7b97--- /dev/null+++ b/posthog/temporal/ai_observability/retries.py@@ -0,0 +1,29 @@+from datetime import UTC, datetime, timedelta++import temporalio.activity+from temporalio.common import RetryPolicy+++def is_last_attempt(next_retry_delay: timedelta | None = None) -> bool:+ """Whether Temporal will not retry the running activity attempt if it fails.++ Retries end when the attempt count reaches the policy's maximum, or when the delay before the next+ attempt lands past the activity's schedule-to-close deadline. The delay defaults to the policy's own+ backoff; pass it when the activity raises with an explicit `next_retry_delay`. A missing or unlimited+ policy counts as last, so its failures stay reported.+ """+ if not temporalio.activity.in_activity():+ return True+ info = temporalio.activity.info()+ policy = info.retry_policy+ if policy is None or not policy.maximum_attempts or info.attempt >= policy.maximum_attempts:+ return True+ if info.schedule_to_close_timeout is None:+ return False+ delay = next_retry_delay or _policy_backoff(policy, info.attempt)+ return datetime.now(UTC) + delay > info.scheduled_time + info.schedule_to_close_timeout+++def _policy_backoff(policy: RetryPolicy, attempt: int) -> timedelta:+ delay = policy.initial_interval * policy.backoff_coefficient ** (attempt - 1)+ return min(delay, policy.maximum_interval) if policy.maximum_interval else delaydiff --git a/posthog/temporal/ai_observability/test_retries.py b/posthog/temporal/ai_observability/test_retries.pynew file mode 100644index 000000000000..baecf19cad68--- /dev/null+++ b/posthog/temporal/ai_observability/test_retries.py@@ -0,0 +1,46 @@+import dataclasses+from datetime import UTC, datetime, timedelta++import pytest+import time_machine++from temporalio.common import RetryPolicy+from temporalio.testing import ActivityEnvironment++from posthog.temporal.ai_observability.retries import is_last_attempt++NOW = datetime(2026, 1, 1, tzinfo=UTC)+SCHEDULE_TO_CLOSE = timedelta(seconds=600)+POLICY = RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=10), backoff_coefficient=2.0)+UNLIMITED_POLICY = RetryPolicy(maximum_attempts=0, initial_interval=timedelta(seconds=10))+++ "attempt, policy, seconds_to_deadline, next_retry_delay, expected",+ [+ pytest.param(3, POLICY, 600, None, True, id="last_attempt_by_count"),+ pytest.param(1, POLICY, 600, timedelta(seconds=30), False, id="deadline_far_away"),+ pytest.param(1, POLICY, 10, timedelta(seconds=30), True, id="delay_lands_past_deadline"),+ pytest.param(2, POLICY, 15, None, True, id="policy_backoff_lands_past_deadline"),+ pytest.param(2, POLICY, 25, None, False, id="policy_backoff_lands_before_deadline"),+ pytest.param(1, UNLIMITED_POLICY, 600, None, True, id="unlimited_policy"),+ ],+)+def test_is_last_attempt(+ attempt: int,+ policy: RetryPolicy,+ seconds_to_deadline: float,+ next_retry_delay: timedelta | None,+ expected: bool,+) -> None:+ env = ActivityEnvironment()+ env.info = dataclasses.replace(+ env.info,+ attempt=attempt,+ retry_policy=policy,+ schedule_to_close_timeout=SCHEDULE_TO_CLOSE,+ scheduled_time=NOW - SCHEDULE_TO_CLOSE + timedelta(seconds=seconds_to_deadline),+ )++ with time_machine.travel(NOW, tick=False):+ assert env.run(is_last_attempt, next_retry_delay) is expecteddiff --git a/posthog/temporal/ai_observability/trace_clustering/README.md b/posthog/temporal/ai_observability/trace_clustering/README.mdindex 103bcce6927b..dce627cd8bd4 100644--- a/posthog/temporal/ai_observability/trace_clustering/README.md+++ b/posthog/temporal/ai_observability/trace_clustering/README.md@@ -398,7 +398,7 @@ Key constants in `constants.py`:## Error Handling- **Insufficient data**: Skip clustering if fewer than 1000 items (per analysis level)-- **Compute activity retries**: 3 attempts with exponential backoff+- **Compute activity retries**: 2 attempts with exponential backoff. `ClickHouseAtCapacity` and `ConcurrencyLimitExceeded` wait a jittered 20–60s before the retry instead, and reach error tracking only on the last attempt- **LLM activity retries**: 2 attempts with longer intervals (for rate limits)- **Emit activity retries**: 3 attempts with exponential backoff- **LLM fallback**: If label generation fails, use "Cluster N" as titlediff --git a/posthog/temporal/ai_observability/trace_clustering/activities.py b/posthog/temporal/ai_observability/trace_clustering/activities.pyindex 97e2fc2d8df0..06b208b26140 100644--- a/posthog/temporal/ai_observability/trace_clustering/activities.py+++ b/posthog/temporal/ai_observability/trace_clustering/activities.py@@ -18,8 +18,10 @@ import structlogfrom temporalio import activityfrom temporalio.exceptions import ApplicationError+from posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.models.team import Team+from posthog.temporal.ai_observability.retries import is_last_attemptfrom posthog.temporal.ai_observability.team_discovery import get_min_traces_overridefrom posthog.temporal.ai_observability.trace_clustering import constantsfrom posthog.temporal.ai_observability.trace_clustering.clustering import (@@ -48,6 +50,7 @@ from posthog.temporal.ai_observability.trace_clustering.models import (GenerateLabelsActivityOutputs,TraceSummary,)+from posthog.temporal.common.errors import NonReportableApplicationErrorfrom posthog.temporal.common.heartbeat import Heartbeaterlogger = structlog.get_logger(__name__)@@ -307,23 +310,31 @@ async def perform_clustering_compute_activity(inputs: ClusteringActivityInputs)async with Heartbeater():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.+ except (ClickHouseAtCapacity, ConcurrencyLimitExceeded) as e:+ # ClickHouse is saturated, or our own limiter holds no free slot for the query. Retrying+ # immediately would only add load, so back off with jitter to give the pool room to recover.backoff = random.uniform(- constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MIN.total_seconds(),- constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MAX.total_seconds(),+ constants.QUERY_CAPACITY_BACKOFF_MIN.total_seconds(),+ constants.QUERY_CAPACITY_BACKOFF_MAX.total_seconds(),)logger.warning(- "clustering_compute_clickhouse_at_capacity",+ "clustering_compute_query_capacity_exhausted",team_id=inputs.team_id,analysis_level=inputs.analysis_level,+ error_type=type(e).__name__,backoff_seconds=round(backoff, 1),)- raise ApplicationError(- "ClickHouse at capacity while fetching embeddings for clustering",- type="ClickHouseAtCapacity",- next_retry_delay=timedelta(seconds=backoff),+ # The retry usually gets through, so only a saturation that outlasts every attempt reaches error tracking.+ next_retry_delay = timedelta(seconds=backoff)+ error_class = (+ ApplicationError+ if is_last_attempt(next_retry_delay=next_retry_delay)+ else NonReportableApplicationError+ )+ raise error_class(+ "No ClickHouse query capacity while fetching embeddings for clustering",+ type=type(e).__name__,+ next_retry_delay=next_retry_delay,) from ediff --git a/posthog/temporal/ai_observability/trace_clustering/constants.py b/posthog/temporal/ai_observability/trace_clustering/constants.pyindex 0e4ff0eead1a..f82fe1ba3a12 100644--- a/posthog/temporal/ai_observability/trace_clustering/constants.py+++ b/posthog/temporal/ai_observability/trace_clustering/constants.py@@ -69,12 +69,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)+# When ClickHouse reports it is at capacity (too many simultaneous queries), or our own query+# limiter has no free slot, 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.+QUERY_CAPACITY_BACKOFF_MIN = timedelta(seconds=20)+QUERY_CAPACITY_BACKOFF_MAX = timedelta(seconds=60)# LLM activity - external dependency, longer intervals between retriesLLM_ACTIVITY_RETRY_POLICY = RetryPolicy(diff --git a/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py b/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.pyindex 4cf9d5ae3cfd..340284f63a9c 100644--- a/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py+++ b/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py@@ -1,18 +1,30 @@"""Tests for trace clustering workflow."""import uuid-from datetime import UTC, datetime+import dataclasses+from datetime import UTC, datetime, timedeltaimport pytest+import time_machinefrom unittest.mock import patchimport numpy as npfrom temporalio import activity-from temporalio.testing import WorkflowEnvironment+from temporalio.exceptions import ApplicationError+from temporalio.testing import ActivityEnvironment, WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded+from posthog.exceptions import ClickHouseAtCapacity+from posthog.temporal.ai_observability.trace_clustering.activities import perform_clustering_compute_activityfrom posthog.temporal.ai_observability.trace_clustering.clustering import perform_kmeans_with_optimal_k-from posthog.temporal.ai_observability.trace_clustering.constants import DEFAULT_MAX_SAMPLES+from posthog.temporal.ai_observability.trace_clustering.constants import (+ COMPUTE_ACTIVITY_RETRY_POLICY,+ COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT,+ DEFAULT_MAX_SAMPLES,+ QUERY_CAPACITY_BACKOFF_MAX,+ QUERY_CAPACITY_BACKOFF_MIN,+)from posthog.temporal.ai_observability.trace_clustering.models import (ClusterAggregateMetrics,ClusteringActivityInputs,@@ -29,6 +41,7 @@ from posthog.temporal.ai_observability.trace_clustering.models import (TraceLabelingMetadata,)from posthog.temporal.ai_observability.trace_clustering.workflow import DailyTraceClusteringWorkflow+from posthog.temporal.common.errors import NonReportableError@pytest.fixture@@ -425,42 +438,55 @@ class TestEmptyComputeResultShortCircuit: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.+ Guards the incident fix: on `ClickHouseAtCapacity` or `ConcurrencyLimitExceeded` 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.parametrize("capacity_error", [ClickHouseAtCapacity, ConcurrencyLimitExceeded])+ @pytest.mark.parametrize(+ "attempt, seconds_to_deadline, reportable",+ [+ (1, COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT.total_seconds(), False),+ (COMPUTE_ACTIVITY_RETRY_POLICY.maximum_attempts, COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT.total_seconds(), True),+ (1, QUERY_CAPACITY_BACKOFF_MIN.total_seconds() / 2, True),+ ],+ )@pytest.mark.asyncio- async def test_clickhouse_at_capacity_raises_jittered_backoff(self):- 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-+ async def test_query_capacity_errors_back_off_and_report_only_the_last_attempt(+ self, capacity_error: type[Exception], attempt: int, seconds_to_deadline: float, reportable: bool+ ):inputs = ClusteringActivityInputs(team_id=1,window_start="2025-01-01T00:00:00Z",window_end="2025-01-08T00:00:00Z",)+ now = datetime(2026, 1, 1, tzinfo=UTC)+ env = ActivityEnvironment()+ env.info = dataclasses.replace(+ env.info,+ attempt=attempt,+ retry_policy=COMPUTE_ACTIVITY_RETRY_POLICY,+ schedule_to_close_timeout=COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT,+ scheduled_time=now - COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT + timedelta(seconds=seconds_to_deadline),+ )- with patch(- "posthog.temporal.ai_observability.trace_clustering.activities._perform_clustering_compute",- side_effect=ClickHouseAtCapacity(),+ with (+ time_machine.travel(now, tick=False),+ patch(+ "posthog.temporal.ai_observability.trace_clustering.activities._perform_clustering_compute",+ side_effect=capacity_error(),+ ),):with pytest.raises(ApplicationError) as exc_info:- await ActivityEnvironment().run(perform_clustering_compute_activity, inputs)+ await env.run(perform_clustering_compute_activity, inputs)err = exc_info.value- assert err.type == "ClickHouseAtCapacity"+ assert err.type == capacity_error.__name__assert err.non_retryable is False+ assert isinstance(err, NonReportableError) is not reportableassert err.next_retry_delay is not None- assert (- constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MIN- <= err.next_retry_delay- <= constants.CLICKHOUSE_AT_CAPACITY_BACKOFF_MAX- )+ assert QUERY_CAPACITY_BACKOFF_MIN <= err.next_retry_delay <= QUERY_CAPACITY_BACKOFF_MAX@pytest.mark.django_db