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(caching): retry clickhouse capacity errors in cache warming (#70973)

posthog[bot]4611de07d58c
diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.py
index d3c0a2a530b1..dced4c1cbfa3 100644
--- a/posthog/caching/test/test_warming.py
+++ b/posthog/caching/test/test_warming.py
@@ -3,7 +3,8 @@ from datetime import UTC, datetime, timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from posthog.caching.warming import insights_to_keep_fresh, schedule_warming_for_teams_task
+from posthog.caching.warming import insights_to_keep_fresh, schedule_warming_for_teams_task, warm_insight_cache_task
+from posthog.exceptions import ClickHouseAtCapacity
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -156,3 +157,17 @@ class TestScheduleWarmingForTeamsTask(APIBaseTest):
self.assertEqual(mock_warm_insight_cache_task_si.call_args_list[0][0][0], "1234")
self.assertEqual(mock_warm_insight_cache_task_si.call_args_list[0][0][1], "5678")
self.assertEqual(mock_warm_insight_cache_task_si.call_args_list[1][0][0], "2345")
+
+
+class TestWarmInsightCacheTask(APIBaseTest):
+ @patch("posthog.caching.warming.capture_exception")
+ @patch("posthog.caching.warming.process_query_dict", side_effect=ClickHouseAtCapacity())
+ def test_capacity_errors_propagate_for_retry_instead_of_being_captured(
+ self, mock_process_query_dict, mock_capture_exception
+ ):
+ insight = Insight.objects.create(team=self.team, query={"kind": "TrendsQuery", "series": []})
+
+ with self.assertRaises(ClickHouseAtCapacity):
+ warm_insight_cache_task(insight.pk, None)
+
+ mock_capture_exception.assert_not_called()
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.py
index 4e5610e45aff..1ef328ff82f3 100644
--- a/posthog/caching/warming.py
+++ b/posthog/caching/warming.py
@@ -16,8 +16,9 @@ from posthog.hogql.errors import TableAccessDeniedError
from posthog.api.services.query import process_query_dict
from posthog.caching.utils import largest_teams
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import Feature, get_team_query_tags, tag_queries
-from posthog.errors import CHQueryErrorTooManySimultaneousQueries
+from posthog.errors import CH_TRANSIENT_ERRORS
from posthog.event_usage import EventSource
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_cache_base import QueryCacheManagerBase
@@ -49,6 +50,10 @@ PRIORITY_INSIGHTS_COUNTER = Counter(
LAST_VIEWED_THRESHOLD = timedelta(days=7)
SHARED_INSIGHTS_LAST_VIEWED_THRESHOLD = timedelta(days=3)
+# ClickHouse capacity/concurrency errors that should retry with backoff rather than fail the task.
+# ClickHouseAtCapacity is included via CH_TRANSIENT_ERRORS (it's what codes 202/439 surface as).
+RETRIABLE_WARMING_ERRORS = (*CH_TRANSIENT_ERRORS, ConcurrencyLimitExceeded)
+
def teams_enabled_for_cache_warming() -> list[int]:
enabled_team_ids = []
@@ -207,7 +212,7 @@ def schedule_warming_for_teams_task():
queue=CeleryQueue.ANALYTICS_LIMITED.value, # Important! Prevents Clickhouse from being overwhelmed
ignore_result=True,
expires=60 * 60,
- autoretry_for=(CHQueryErrorTooManySimultaneousQueries,),
+ autoretry_for=RETRIABLE_WARMING_ERRORS,
retry_backoff=2,
retry_backoff_max=3,
max_retries=3,
@@ -273,7 +278,7 @@ def warm_insight_cache_task(insight_id: int, dashboard_id: Optional[int]):
},
)
- except CHQueryErrorTooManySimultaneousQueries:
+ except RETRIABLE_WARMING_ERRORS:
raise
except Exception as e:
# A revoked creator's access-denied error is a known limitation - report it as an event
diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.py
index 96f07b6f0921..5350cffebd6b 100644
--- a/posthog/clickhouse/client/execute_async.py
+++ b/posthog/clickhouse/client/execute_async.py
@@ -16,8 +16,10 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog import celery, redis
from posthog.clickhouse.client.async_task_chain import add_task_to_on_commit
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import get_query_tags, tag_queries
-from posthog.errors import CHQueryErrorTooManySimultaneousQueries, ExposedCHQueryError
+from posthog.errors import ExposedCHQueryError
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.renderers import SafeJSONRenderer
@@ -240,7 +242,15 @@ def execute_process_query(
seconds=1
)
QUERY_PROCESS_TIME.labels(team=team_id).observe(process_duration)
- except CHQueryErrorTooManySimultaneousQueries:
+ except (ClickHouseAtCapacity, ConcurrencyLimitExceeded):
+ # Capacity/concurrency errors are transient — let them propagate so the enclosing
+ # Celery task (process_query_task) retries with backoff instead of being swallowed
+ # below as a "user-safe" APIException that never retries. Clear the assumed-complete
+ # flags stored in the finally below, or the retry would short-circuit at the
+ # `if query_status.complete: return` guard above and never re-run the query.
+ # If retries are exhausted, process_query_task's on_failure marks the status errored.
+ query_status.complete = False
+ query_status.error = False
raise
except Exception as err:
from posthog.rbac.user_access_control import UserAccessControlError
diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.py
index e90708350952..d71c36c89757 100644
--- a/posthog/clickhouse/client/test/test_execute_async.py
+++ b/posthog/clickhouse/client/test/test_execute_async.py
@@ -22,8 +22,8 @@ from posthog.clickhouse.client import (
from posthog.clickhouse.client.async_task_chain import task_chain_context
from posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, execute_process_query
from posthog.clickhouse.query_tagging import tag_queries
-from posthog.errors import CHQueryErrorTooManySimultaneousQueries, ExposedCHQueryError
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.errors import ExposedCHQueryError
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded
from posthog.models import Organization, Team
from posthog.models.user import User
from posthog.redis import get_client
@@ -63,6 +63,25 @@ class TestQueryStatusManager(SimpleTestCase):
self.query_status.expiration_time = None # We don't care about expiration time in this test
self.assertEqual(self.manager.get_query_status(True), self.query_status)
+ def test_process_query_task_on_failure_marks_status_errored(self):
+ from posthog.tasks.tasks import process_query_task
+
+ self.manager.store_query_status(self.query_status)
+
+ process_query_task.on_failure(
+ exc=ClickHouseAtCapacity(),
+ task_id="celery-task-id",
+ args=(self.team_id, None, self.query_id),
+ kwargs={},
+ einfo=None,
+ )
+
+ result = self.manager.get_query_status()
+ self.assertTrue(result.complete)
+ self.assertTrue(result.error)
+ self.assertEqual(result.error_message, ClickHouseAtCapacity.default_detail)
+ self.assertIsNotNone(result.end_time)
+
def test_store_clickhouse_query_progress(self):
query_status = {f"{self.team_id}_{self.query_id}_1": {"progress": 1234}}
self.manager._store_clickhouse_query_progress_dict(query_status)
@@ -243,11 +262,9 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):
def test_async_query_server_errors(self):
query = build_query("SELECT * FROM events")
- with patch(
- "posthog.api.services.query.process_query_dict", side_effect=CHQueryErrorTooManySimultaneousQueries("bla")
- ):
+ with patch("posthog.api.services.query.process_query_dict", side_effect=ClickHouseAtCapacity()):
self.assertRaises(
- CHQueryErrorTooManySimultaneousQueries,
+ ClickHouseAtCapacity,
client.enqueue_process_query_task,
**{"team": self.team, "user_id": self.user.id, "query_json": query, "_test_only_bypass_celery": True},
)
@@ -260,8 +277,11 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):
except Exception:
pass
+ # Transient capacity errors leave the status re-runnable (not complete, not errored)
+ # so the Celery retry doesn't short-circuit on the `if query_status.complete` guard.
result = client.get_query_status(self.team.id, query_id)
- self.assertTrue(result.error)
+ self.assertFalse(result.error)
+ self.assertFalse(result.complete)
assert result.error_message is None
self.assertIsNotNone(result.start_time)
self.assertIsNotNone(result.pickup_time)
diff --git a/posthog/errors.py b/posthog/errors.py
index bb3d8b9612ff..f0cb8c10fc4d 100644
--- a/posthog/errors.py
+++ b/posthog/errors.py
@@ -213,14 +213,6 @@ def classify_query_error(e: Exception) -> QueryErrorCategory:
# Specific error classes we need
# These exist here and are not dynamically created because they are used in the codebase.
-class CHQueryErrorTooManySimultaneousQueries(InternalCHQueryError):
- pass
-
-
-class CHQueryErrorCannotScheduleTask(InternalCHQueryError):
- pass
-
-
class CHQueryErrorS3Error(InternalCHQueryError):
pass
@@ -1007,10 +999,10 @@ CLICKHOUSE_ERROR_CODE_LOOKUP: dict[int, ErrorCodeMeta] = {
# Transient ClickHouse infrastructure errors that are safe to retry.
# This can be used in things like celery `autoretry_for` to increase resiliency.
+# Capacity errors (codes 202/439) are wrapped as ClickHouseAtCapacity by wrap_clickhouse_query_error.
CH_TRANSIENT_ERRORS = (
- CHQueryErrorTooManySimultaneousQueries,
- CHQueryErrorCannotScheduleTask,
CHQueryErrorS3Error,
CHQueryErrorS3FileChangedDuringRead,
CHQueryErrorTableIsReadOnly,
+ ClickHouseAtCapacity,
)
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 2e2fdd2541eb..ea9b406dc61d 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -72,8 +72,9 @@ from posthog.auth import (
)
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.cloud_utils import is_cloud
-from posthog.errors import CHQueryErrorCannotScheduleTask, CHQueryErrorTooManySimultaneousQueries, ExposedCHQueryError
+from posthog.errors import ExposedCHQueryError
from posthog.event_usage import report_user_action
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.models import Organization, Team, User
@@ -952,9 +953,9 @@ class SessionRecordingViewSet(
)
return response
- except CHQueryErrorTooManySimultaneousQueries:
- _count_session_recording_throttled(location="too_many_simultaneous_queries", auth_type=auth_type)
- raise Throttled(detail="Too many simultaneous queries. Try again later.")
+ except ClickHouseAtCapacity:
+ _count_session_recording_throttled(location="clickhouse_at_capacity", auth_type=auth_type)
+ raise Throttled(detail="ClickHouse is at capacity. Try again later.")
except (ExposedHogQLError, ExposedCHQueryError) as e:
# A bad filter or query (e.g. a property referencing a field that doesn't exist on the
# event) is the caller's problem, not a server error. Surface the actual reason as a 400
@@ -1492,7 +1493,7 @@ class SessionRecordingViewSet(
"$exception_fingerprint": f"session_recording_api.snapshots.{e.__class__.__name__}",
},
)
- is_ch_error = isinstance(e, CHQueryErrorCannotScheduleTask)
+ is_ch_error = isinstance(e, ClickHouseAtCapacity)
message = (
"ClickHouse over capacity. Please retry"
@@ -1538,7 +1539,7 @@ class SessionRecordingViewSet(
)
@retry(
- retry=retry_if_exception_type(CHQueryErrorCannotScheduleTask),
+ retry=retry_if_exception_type(ClickHouseAtCapacity),
# if retrying doesn't work, raise the actual error, not a retry error
reraise=True,
# try again after 0.2 seconds
diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.py
index f644ab72dfce..d24c2f422cc2 100644
--- a/posthog/session_recordings/test/test_session_recordings.py
+++ b/posthog/session_recordings/test/test_session_recordings.py
@@ -29,8 +29,7 @@ from posthog.schema import LogEntryPropertyFilter, RecordingsQuery
from posthog.hogql.errors import QueryError
-from posthog.errors import CHQueryErrorCannotScheduleTask, CHQueryErrorTooManySimultaneousQueries
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded
from posthog.models import Organization, SessionRecording, User
from posthog.models.team import Team
from posthog.models.utils import uuid7
@@ -1330,9 +1329,9 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
@parameterized.expand(
[
(
- "too_many_queries",
- CHQueryErrorTooManySimultaneousQueries("Too many simultaneous queries"),
- "Too many simultaneous queries. Try again later.",
+ "at_capacity",
+ ClickHouseAtCapacity(),
+ "ClickHouse is at capacity. Try again later.",
),
(
"timeout_exceeded",
@@ -1379,14 +1378,14 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
# the real reason must reach the client, not a generic "internal server error"
assert expected_detail_substring in response.json()["detail"]
- def test_sync_execute_ch_cannot_schedule_task_retry_then_503(self):
- """Test that list_blocks throws CHQueryErrorCannotScheduleTask multiple times and eventually returns 503"""
+ def test_sync_execute_ch_at_capacity_retry_then_503(self):
+ """Test that list_blocks throws ClickHouseAtCapacity multiple times and eventually returns 503"""
call_count = 0
def mock_list_blocks(*args, **kwargs):
nonlocal call_count
call_count += 1
- raise CHQueryErrorCannotScheduleTask("Cannot schedule task", code=439)
+ raise ClickHouseAtCapacity()
# Patch list_blocks where it's imported and used in session_recording_v2_service
with patch(
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index f5303072d10d..4862879ccaf2 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -15,14 +15,7 @@ from prometheus_client import Counter, Gauge, Histogram
from posthog.api.monitoring import Feature
from posthog.clickhouse import query_tagging
from posthog.clickhouse.query_tagging import QueryTags, update_tags
-from posthog.errors import (
- CHQueryErrorCannotScheduleTask,
- CHQueryErrorS3Error,
- CHQueryErrorS3FileChangedDuringRead,
- CHQueryErrorTableIsReadOnly,
- CHQueryErrorTooManySimultaneousQueries,
-)
-from posthog.exceptions import ClickHouseAtCapacity
+from posthog.errors import CH_TRANSIENT_ERRORS
from posthog.exceptions_capture import capture_exception
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -457,14 +450,7 @@ def _enqueue_single_cohort_calculation(cohort: Cohort, initiating_user: Optional
ignore_result=True,
queue=CeleryQueue.LONG_RUNNING.value,
# Auto-retry for transient ClickHouse errors with exponential backoff
- autoretry_for=(
- CHQueryErrorTooManySimultaneousQueries,
- CHQueryErrorCannotScheduleTask,
- ClickHouseAtCapacity,
- CHQueryErrorS3Error,
- CHQueryErrorS3FileChangedDuringRead,
- CHQueryErrorTableIsReadOnly,
- ),
+ autoretry_for=CH_TRANSIENT_ERRORS,
retry_backoff=60,
retry_backoff_max=1800,
max_retries=6,
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 312cdd86a90e..43c5de938fb0 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -1,7 +1,7 @@
import time
import datetime
from collections.abc import Callable
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from posthog.event_usage import AnalyticsProps
@@ -15,6 +15,7 @@ import requests
from celery import shared_task
from prometheus_client import Counter, Gauge
from redis import Redis
+from rest_framework.exceptions import APIException
from structlog import get_logger
from posthog.hogql.constants import LimitContext
@@ -22,7 +23,7 @@ from posthog.hogql.constants import LimitContext
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, limit_concurrency
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tag_queries
from posthog.cloud_utils import is_cloud
-from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorTooManySimultaneousQueries
+from posthog.errors import CH_TRANSIENT_ERRORS
from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.metrics import pushed_metrics_registry
@@ -342,15 +343,46 @@ def redis_heartbeat() -> None:
get_client().set("POSTHOG_HEARTBEAT", int(time.time()))
+def _process_query_task_failure(
+ self: Any, exc: Exception, task_id: str, args: tuple[Any, ...], kwargs: dict[str, Any], einfo: Any
+) -> None:
+ # Transient errors (capacity/concurrency) clear the stored completion flags so each
+ # retry re-runs the query. Once Celery gives up, mark the status errored here so
+ # clients don't poll a forever-pending status until it expires.
+ from posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager
+
+ bound = dict(zip(("team_id", "user_id", "query_id"), args))
+ bound.update(kwargs)
+ team_id = bound.get("team_id")
+ query_id = bound.get("query_id")
+ if team_id is None or query_id is None:
+ return
+
+ manager = QueryStatusManager(query_id, team_id)
+ try:
+ query_status = manager.get_query_status()
+ except QueryNotFoundError:
+ return
+
+ query_status.complete = True
+ query_status.error = True
+ if isinstance(exc, APIException):
+ # User-safe message (e.g. ClickHouseAtCapacity's "try again later" copy)
+ query_status.error_message = str(exc.detail)
+ query_status.end_time = datetime.datetime.now(datetime.UTC)
+ manager.store_query_status(query_status)
+
+
@shared_task(
ignore_result=True,
queue=CeleryQueue.ANALYTICS_QUERIES.value,
acks_late=True,
autoretry_for=(
# Important: Only retry for things that might be okay on the next try
- CHQueryErrorTooManySimultaneousQueries,
+ ClickHouseAtCapacity,
ConcurrencyLimitExceeded,
),
+ on_failure=_process_query_task_failure,
retry_backoff=1,
retry_backoff_max=10,
max_retries=10,
@@ -1179,8 +1211,8 @@ def _queue_delete_team_recordings(team_ids: list[int], deleted_by: str) -> None:
ignore_result=True,
queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,
# sync_execute wraps TOO_MANY_SIMULTANEOUS_QUERIES/CANNOT_SCHEDULE_TASK into
- # ClickHouseAtCapacity, so it must be listed alongside the raw CH error classes.
- autoretry_for=(*CH_TRANSIENT_ERRORS, ClickHouseAtCapacity),
+ # ClickHouseAtCapacity, which CH_TRANSIENT_ERRORS includes.
+ autoretry_for=CH_TRANSIENT_ERRORS,
retry_backoff=30,
retry_backoff_max=120,
max_retries=3,
diff --git a/posthog/tasks/test/test_exporter.py b/posthog/tasks/test/test_exporter.py
index ba282828bcc9..f3094f26431b 100644
--- a/posthog/tasks/test/test_exporter.py
+++ b/posthog/tasks/test/test_exporter.py
@@ -10,7 +10,7 @@ from parameterized import parameterized
from posthog.hogql.errors import QueryError
-from posthog.errors import CHQueryErrorTooManySimultaneousQueries
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.tasks import exporter
from products.dashboards.backend.models.dashboard import Dashboard
@@ -40,7 +40,6 @@ class TestIsUserQueryErrorType(TestCase):
("TimeoutError", False),
("ValueError", False),
("CHQueryErrorS3Error", False),
- ("CHQueryErrorTooManySimultaneousQueries", False),
("ClickHouseAtCapacity", False),
("ConcurrencyLimitExceeded", False),
(None, False),
@@ -114,7 +113,7 @@ class TestExportAssetFailureRecording(APIBaseTest):
@patch("products.exports.backend.tasks.image_exporter.export_image")
def test_transient_error_records_failure_without_retry(self, mock_export_direct: MagicMock) -> None:
- mock_export_direct.side_effect = CHQueryErrorTooManySimultaneousQueries("Too many queries")
+ mock_export_direct.side_effect = ClickHouseAtCapacity()
asset = ExportedAsset.objects.create(
team=self.team,
@@ -127,6 +126,6 @@ class TestExportAssetFailureRecording(APIBaseTest):
assert mock_export_direct.call_count == 1
asset.refresh_from_db()
- assert asset.exception == "Code: None.\nToo many queries"
- assert asset.exception_type == "CHQueryErrorTooManySimultaneousQueries"
+ assert asset.exception == ClickHouseAtCapacity.default_detail
+ assert asset.exception_type == "ClickHouseAtCapacity"
assert asset.failure_type == FAILURE_TYPE_SYSTEM
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index c05396fd0c6b..d42c314cefe9 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -22,7 +22,7 @@ from posthog.schema import (
)
from posthog.constants import AvailableFeature
-from posthog.errors import CHQueryErrorTooManySimultaneousQueries
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.models import User
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
@@ -441,12 +441,13 @@ class TestEvaluateAlert:
async def test_evaluate_reraises_ch_transient_error(self, alert) -> None:
# Transient CH errors bubble up so Temporal's retry policy handles them.
+ # Capacity errors (codes 202/439) surface as ClickHouseAtCapacity, so that's what we simulate.
with patch(
"posthog.temporal.alerts.activities.check_alert_for_insight",
- side_effect=CHQueryErrorTooManySimultaneousQueries("too many"),
+ side_effect=ClickHouseAtCapacity(),
):
env = ActivityEnvironment()
- with pytest.raises(CHQueryErrorTooManySimultaneousQueries):
+ with pytest.raises(ClickHouseAtCapacity):
await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))
# No AlertCheck should have been written
diff --git a/products/exports/backend/api/test/test_exports.py b/products/exports/backend/api/test/test_exports.py
index 0804bbe49742..e42329c6e7f8 100644
--- a/products/exports/backend/api/test/test_exports.py
+++ b/products/exports/backend/api/test/test_exports.py
@@ -19,7 +19,7 @@ from rest_framework import status
from posthog.hogql.errors import QueryError
-from posthog.errors import CHQueryErrorTooManySimultaneousQueries
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.filters.filter import Filter
from posthog.models.team import Team
@@ -1543,7 +1543,7 @@ class TestExportAssetCounters(APIBaseTest):
# User error: recorded but not raised
(QueryError("Invalid query"), FAILURE_TYPE_USER, 0.0, 1.0, False),
# System error: retried by tenacity, then recorded (not raised, swallowed by export_asset)
- (CHQueryErrorTooManySimultaneousQueries("err"), FAILURE_TYPE_SYSTEM, 0.0, 1.0, False),
+ (ClickHouseAtCapacity(), FAILURE_TYPE_SYSTEM, 0.0, 1.0, False),
],
name_func=lambda func, num, params: f"{func.__name__}_{['success', 'user_error', 'system_error'][int(num)]}",
)
diff --git a/products/exports/backend/tasks/failure_handler.py b/products/exports/backend/tasks/failure_handler.py
index a4d8382b3efa..772ba71721d3 100644
--- a/products/exports/backend/tasks/failure_handler.py
+++ b/products/exports/backend/tasks/failure_handler.py
@@ -31,12 +31,7 @@ from posthog.errors import (
CHQueryErrorUnknownTable,
CHQueryErrorUnsupportedMethod,
)
-from posthog.exceptions import (
- ClickHouseAtCapacity,
- ClickHouseQueryMemoryLimitExceeded,
- ClickHouseQuerySizeExceeded,
- ClickHouseQueryTimeOut,
-)
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOut
# =============================================================================
# Export Failure Classification
@@ -92,7 +87,6 @@ EXCEPTIONS_TO_RETRY = (
ConcurrencyLimitExceeded,
MaxRetryError, # This is from urllib, e.g. HTTP retries instead of "job retries"
ReadTimeoutError, # Network timeout from urllib3
- ClickHouseAtCapacity,
SocketTimeoutError,
SSLError,
BrowserlessUnavailable,
diff --git a/products/exports/backend/tasks/test/test_failure_handler.py b/products/exports/backend/tasks/test/test_failure_handler.py
index 8cd19525bcaf..6e5a8b1e0d5e 100644
--- a/products/exports/backend/tasks/test/test_failure_handler.py
+++ b/products/exports/backend/tasks/test/test_failure_handler.py
@@ -38,7 +38,6 @@ class TestIsUserQueryErrorType(TestCase):
("TimeoutError", False),
("ValueError", False),
("CHQueryErrorS3Error", False),
- ("CHQueryErrorTooManySimultaneousQueries", False),
("ClickHouseAtCapacity", False),
("ConcurrencyLimitExceeded", False),
("ReadTimeoutError", False),
@@ -69,7 +68,6 @@ class TestClassifyFailureType(TestCase):
("ValidationError", FAILURE_TYPE_USER),
# System errors (from EXCEPTIONS_TO_RETRY)
("CHQueryErrorS3Error", FAILURE_TYPE_SYSTEM),
- ("CHQueryErrorTooManySimultaneousQueries", FAILURE_TYPE_SYSTEM),
("OperationalError", FAILURE_TYPE_SYSTEM),
("ClickHouseAtCapacity", FAILURE_TYPE_SYSTEM),
("ReadTimeoutError", FAILURE_TYPE_SYSTEM),
diff --git a/products/signals/backend/temporal/clickhouse.py b/products/signals/backend/temporal/clickhouse.py
index 55d3ddc42776..1cb70d754f71 100644
--- a/products/signals/backend/temporal/clickhouse.py
+++ b/products/signals/backend/temporal/clickhouse.py
@@ -9,11 +9,10 @@ from asgiref.sync import sync_to_async
from posthog.hogql.query import execute_hogql_query
from posthog.errors import CH_TRANSIENT_ERRORS
-from posthog.exceptions import ClickHouseAtCapacity
from posthog.models import Team
-# Errors worth retrying
-RETRIABLE_ERRORS = (ClickHouseAtCapacity, *CH_TRANSIENT_ERRORS)
+# Errors worth retrying (includes ClickHouseAtCapacity via CH_TRANSIENT_ERRORS)
+RETRIABLE_ERRORS = CH_TRANSIENT_ERRORS
logger = structlog.get_logger(__name__)
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index b63d5dd22dad..443395e85296 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -29,7 +29,8 @@ from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_param_
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.errors import CHQueryErrorTooManySimultaneousQueries, wrap_clickhouse_query_error
+from posthog.errors import wrap_clickhouse_query_error
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr
from posthog.schema_enums import DatabaseSerializedFieldType
@@ -844,13 +845,17 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
def _safe_expose_ch_error(self, err):
err = wrap_clickhouse_query_error(err)
+
+ # Capacity errors are transient — surface them so the caller can retry. Check this
+ # before the message matching below, since ClickHouseAtCapacity is an APIException
+ # and has no `.message` attribute.
+ if isinstance(err, ClickHouseAtCapacity):
+ raise err
+
for key, value in ExtractErrors.items():
if key in err.message:
raise Exception(value)
- if isinstance(err, CHQueryErrorTooManySimultaneousQueries):
- raise err
-
raise Exception(
"Could not read the files from your storage bucket. Check that the files URL pattern, file format, "
"and credentials are correct, then try again."
diff --git a/products/warehouse_sources/backend/tests/test_table.py b/products/warehouse_sources/backend/tests/test_table.py
index 792a089395dd..bbe26cd819f2 100644
--- a/products/warehouse_sources/backend/tests/test_table.py
+++ b/products/warehouse_sources/backend/tests/test_table.py
@@ -4,6 +4,10 @@ import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
+from clickhouse_driver.errors import ServerException
+
+from posthog.exceptions import ClickHouseAtCapacity
+
from products.warehouse_sources.backend.models.table import DataWarehouseTable, run_chdb_query
@@ -35,6 +39,16 @@ class TestDataWarehouseTableColumnOrder(BaseTest):
assert table.column_order == ["z", "a"]
+class TestSafeExposeChError:
+ # ClickHouseAtCapacity is a DRF APIException with no `.message`, so the capacity check
+ # must run before the message-matching loop — reordering them would reintroduce an
+ # AttributeError on every capacity error during column introspection.
+ @pytest.mark.parametrize("code", [202, 439]) # TOO_MANY_SIMULTANEOUS_QUERIES, CANNOT_SCHEDULE_TASK
+ def test_capacity_errors_surface_as_clickhouse_at_capacity(self, code: int) -> None:
+ with pytest.raises(ClickHouseAtCapacity):
+ DataWarehouseTable()._safe_expose_ch_error(ServerException("busy", code=code))
+
+
class TestRunChdbQuery:
def test_hung_query_is_killed_and_raises_instead_of_blocking(self) -> None:
# Real subprocess: chdb import alone exceeds the timeout, so this exercises the
diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
index 76d0b5b240a1..36c10a31838a 100644
--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
@@ -2,61 +2,21 @@
import type { App } from '@modelcontextprotocol/ext-apps'
import { useCallback } from 'react'
+import { Component } from '../components/Component'
import { ActionListView, ActionView, type ActionData, type ActionListData } from 'products/actions/mcp/apps'
import { LLMCostsView, type LLMCostsData } from 'products/ai_observability/mcp/apps'
import { CohortListView, CohortView, type CohortData, type CohortListData } from 'products/cohorts/mcp/apps'
-import {
- ErrorDetailsView,
- ErrorIssueListView,
- ErrorIssueView,
- type ErrorDetailsData,
- type ErrorIssueData,
- type ErrorIssueListData,
-} from 'products/error_tracking/mcp/apps'
-import {
- ExperimentListView,
- ExperimentResultsView,
- ExperimentView,
- type ExperimentData,
- type ExperimentListData,
- type ExperimentResultsData,
-} from 'products/experiments/mcp/apps'
-import {
- FeatureFlagListView,
- FeatureFlagTestingView,
- FeatureFlagView,
- type FeatureFlagData,
- type FeatureFlagListData,
- type FeatureFlagTestingData,
-} from 'products/feature_flags/mcp/apps'
+import { ErrorDetailsView, ErrorIssueListView, ErrorIssueView, type ErrorDetailsData, type ErrorIssueData, type ErrorIssueListData } from 'products/error_tracking/mcp/apps'
+import { ExperimentListView, ExperimentResultsView, ExperimentView, type ExperimentData, type ExperimentListData, type ExperimentResultsData } from 'products/experiments/mcp/apps'
+import { FeatureFlagListView, FeatureFlagTestingView, FeatureFlagView, type FeatureFlagData, type FeatureFlagListData, type FeatureFlagTestingData } from 'products/feature_flags/mcp/apps'
import { InsightActorsView, type InsightActorsData } from 'products/product_analytics/mcp/apps'
-import {
- SessionRecordingView,
- SessionSummaryView,
- type SessionRecordingData,
- type SessionSummaryData,
-} from 'products/replay/mcp/apps'
-import {
- SurveyListView,
- SurveyStatsView,
- SurveyView,
- type SurveyData,
- type SurveyListData,
- type SurveyStatsData,
-} from 'products/surveys/mcp/apps'
+import { SessionRecordingView, SessionSummaryView, type SessionRecordingData, type SessionSummaryData } from 'products/replay/mcp/apps'
+import { SurveyListView, SurveyStatsView, SurveyView, type SurveyData, type SurveyListData, type SurveyStatsData } from 'products/surveys/mcp/apps'
import { TraceSpanListView, TraceSpanView, type TraceSpanData, type TraceSpanListData } from 'products/tracing/mcp/apps'
import { InviteEmailPreviewView, type InviteEmailPreviewData } from 'products/user_interviews/mcp/apps'
-import {
- EmailTemplateView,
- WorkflowListView,
- WorkflowView,
- type EmailTemplateData,
- type WorkflowData,
- type WorkflowListData,
-} from 'products/workflows/mcp/apps'
+import { EmailTemplateView, WorkflowListView, WorkflowView, type EmailTemplateData, type WorkflowData, type WorkflowListData } from 'products/workflows/mcp/apps'
import type { UiAppKey } from '../../resources/ui-apps.generated'
-import { Component } from '../components/Component'
export interface RenderDispatchProps {
data: unknown
@@ -369,34 +329,32 @@ function WorkflowListContent({ data, app }: { data: WorkflowListData; app: App |
}
export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchProps) => JSX.Element>> = {
- action: ({ data }) => <ActionView action={data as ActionData} />,
+ 'action': ({ data }) => <ActionView action={data as ActionData} />,
'action-list': ({ data, app }) => <ActionListContent data={data as ActionListData} app={app} />,
- cohort: ({ data }) => <CohortView cohort={data as CohortData} />,
+ 'cohort': ({ data }) => <CohortView cohort={data as CohortData} />,
'cohort-list': ({ data, app }) => <CohortListContent data={data as CohortListData} app={app} />,
'email-template': ({ data }) => <EmailTemplateView template={data as EmailTemplateData} />,
'error-details': ({ data }) => <ErrorDetailsView data={data as ErrorDetailsData} />,
'error-issue': ({ data }) => <ErrorIssueView issue={data as ErrorIssueData} />,
'error-issue-list': ({ data, app }) => <ErrorIssueListContent data={data as ErrorIssueListData} app={app} />,
- experiment: ({ data }) => <ExperimentView experiment={data as ExperimentData} />,
+ 'experiment': ({ data }) => <ExperimentView experiment={data as ExperimentData} />,
'experiment-list': ({ data, app }) => <ExperimentListContent data={data as ExperimentListData} app={app} />,
'experiment-results': ({ data }) => <ExperimentResultsView data={data as ExperimentResultsData} />,
'feature-flag': ({ data }) => <FeatureFlagView flag={data as FeatureFlagData} />,
'feature-flag-list': ({ data, app }) => <FeatureFlagListContent data={data as FeatureFlagListData} app={app} />,
'feature-flag-testing': ({ data }) => <FeatureFlagTestingView flag={data as FeatureFlagTestingData} />,
- 'insight-actors': ({ data, openLink }) => (
- <InsightActorsView data={data as InsightActorsData} openLink={openLink} />
- ),
+ 'insight-actors': ({ data, openLink }) => <InsightActorsView data={data as InsightActorsData} openLink={openLink} />,
'invite-email-preview': ({ data }) => <InviteEmailPreviewView data={data as InviteEmailPreviewData} />,
'llm-costs': ({ data }) => <LLMCostsView data={data as LLMCostsData} />,
'query-results': ({ data }) => <Component data={data} />,
'session-recording': ({ data }) => <SessionRecordingView recording={data as SessionRecordingData} />,
'session-summary': ({ data }) => <SessionSummaryView data={data as SessionSummaryData} />,
- survey: ({ data }) => <SurveyView survey={data as SurveyData} />,
+ 'survey': ({ data }) => <SurveyView survey={data as SurveyData} />,
'survey-global-stats': ({ data }) => <SurveyStatsView data={data as SurveyStatsData} />,
'survey-list': ({ data, app }) => <SurveyListContent data={data as SurveyListData} app={app} />,
'survey-stats': ({ data }) => <SurveyStatsView data={data as SurveyStatsData} />,
'trace-span': ({ data }) => <TraceSpanView data={data as TraceSpanData} />,
'trace-span-list': ({ data, app }) => <TraceSpanListContent data={data as TraceSpanListData} app={app} />,
- workflow: ({ data }) => <WorkflowView workflow={data as WorkflowData} />,
+ 'workflow': ({ data }) => <WorkflowView workflow={data as WorkflowData} />,
'workflow-list': ({ data, app }) => <WorkflowListContent data={data as WorkflowListData} app={app} />,
}