: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
feat(query-cache): break on TOO_MANY_BYTES failures (#82393)
Andy Zhao01e0225450f1
diff --git a/posthog/exceptions.py b/posthog/exceptions.pyindex 2dba8ac14542..3f6c4ee5f1d0 100644--- a/posthog/exceptions.py+++ b/posthog/exceptions.py@@ -5,7 +5,7 @@ from django.http.response import JsonResponseimport structlogfrom rest_framework import status-from rest_framework.exceptions import APIException+from rest_framework.exceptions import APIException, ValidationErrorfrom rest_framework.response import Responsefrom posthog.clickhouse.query_tagging import get_query_tags@@ -85,6 +85,12 @@ class ClickHouseQuerySizeExceeded(APIException):default_detail = "Query size exceeded."+class ClickHouseBytesLimitExceeded(ValidationError):+ # A fresh TOO_MANY_BYTES surfaces as ValidationError(str(error), "too_many_bytes") in the+ # query API, so the breaker's replay must produce the same status and machine code.+ default_code = "too_many_bytes"++class ClickHouseQueryTimeOut(APIException):status_code = 504default_detail = "Query has hit the max execution time before completing. See our docs for how to improve your query performance. You may need to materialize."diff --git a/posthog/hogql_queries/query_failure_handling.py b/posthog/hogql_queries/query_failure_handling.pyindex 52de9c497fb1..25aad60d9890 100644--- a/posthog/hogql_queries/query_failure_handling.py+++ b/posthog/hogql_queries/query_failure_handling.py@@ -5,7 +5,10 @@ from rest_framework.exceptions import APIExceptionfrom posthog.hogql.constants import LimitContext+from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level, get_team_kill_switch_level+from posthog.errors import CHQueryErrorTooManyBytesfrom posthog.exceptions import (+ ClickHouseBytesLimitExceeded,ClickHouseEstimatedQueryExecutionTimeTooLong,ClickHouseQueryMemoryLimitExceeded,ClickHouseQuerySizeExceeded,@@ -21,10 +24,11 @@ FAILURE_KIND_EXCEPTIONS: dict[FailureKind, type[APIException]] = {"timeout": ClickHouseQueryTimeOut,"too_slow": ClickHouseEstimatedQueryExecutionTimeTooLong,"query_size": ClickHouseQuerySizeExceeded,+ "too_many_bytes": ClickHouseBytesLimitExceeded,}-def classify_failure(error: Exception) -> Optional[FailureKind]:+def classify_failure(error: Exception, team_id: Optional[int] = None) -> Optional[FailureKind]:"""Return the failure kind for errors that will repeat on retry, None for everything else."""if isinstance(error, ClickHouseQueryMemoryLimitExceeded):return "memory_limit" if error.is_per_query_limit else None@@ -34,6 +38,14 @@ def classify_failure(error: Exception) -> Optional[FailureKind]:return "too_slow"if isinstance(error, ClickHouseQuerySizeExceeded):return "query_size"+ if isinstance(error, CHQueryErrorTooManyBytes):+ # Under an active kill switch (global or team-scoped) the bytes cap is temporary+ # cluster protection, so the failure says nothing about the query once it lifts.+ if get_kill_switch_level() != KillSwitchLevel.OFF:+ return None+ if team_id is not None and get_team_kill_switch_level(team_id) != KillSwitchLevel.OFF:+ return None+ return "too_many_bytes"return Nonediff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex e12602734a73..3aad4f838610 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -2080,7 +2080,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):capture_exception(exc)if self._query_failure_caching_enabled:# Transient error classes classify to None and are never recorded.- failure_kind = classify_failure(exc)+ failure_kind = classify_failure(exc, self.team.pk)if failure_kind is not None:QueryCache(team_id=self.team.pk, cache_key=cache_key).record_failure(failure_kind, str(exc), budget=budget_for_limit_context(self.limit_context)diff --git a/posthog/hogql_queries/test/test_query_failure_handling.py b/posthog/hogql_queries/test/test_query_failure_handling.pyindex cda625058339..edd586d6520a 100644--- a/posthog/hogql_queries/test/test_query_failure_handling.py+++ b/posthog/hogql_queries/test/test_query_failure_handling.py@@ -1,6 +1,7 @@from datetime import UTC, datetime, timedeltafrom freezegun import freeze_time+from unittest.mock import patchfrom django.test import SimpleTestCase@@ -10,10 +11,12 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.hogql.constants import LimitContext+from posthog.clickhouse.client.execute import KillSwitchLevelfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.errors import wrap_clickhouse_query_errorfrom posthog.exceptions import (ClickHouseAtCapacity,+ ClickHouseBytesLimitExceeded,ClickHouseEstimatedQueryExecutionTimeTooLong,ClickHouseQueryMemoryLimitExceeded,ClickHouseQuerySizeExceeded,@@ -57,6 +60,11 @@ class TestQueryFailureHandling(SimpleTestCase):("timeout", ClickHouseQueryTimeOut(), "timeout"),("too_slow", ClickHouseEstimatedQueryExecutionTimeTooLong(), "too_slow"),("query_size", ClickHouseQuerySizeExceeded(), "query_size"),+ (+ "too_many_bytes",+ wrap_clickhouse_query_error(ServerException("Limit for bytes to read exceeded", code=307)),+ "too_many_bytes",+ ),("at_capacity", ClickHouseAtCapacity(), None),("concurrency_limit", ConcurrencyLimitExceeded("busy"), None),("too_many_simultaneous", wrap_clickhouse_query_error(ServerException("busy", code=202)), None),@@ -66,6 +74,26 @@ class TestQueryFailureHandling(SimpleTestCase):def test_classify_failure(self, _name, error, expected):assert classify_failure(error) == expected+ @parameterized.expand([("light", KillSwitchLevel.LIGHT), ("full", KillSwitchLevel.FULL)])+ def test_too_many_bytes_not_classified_under_kill_switch(self, _name, level):+ error = wrap_clickhouse_query_error(ServerException("Limit for bytes to read exceeded", code=307))+ with patch("posthog.hogql_queries.query_failure_handling.get_kill_switch_level", return_value=level):+ assert classify_failure(error) is None++ @parameterized.expand([("light", KillSwitchLevel.LIGHT), ("full", KillSwitchLevel.FULL)])+ def test_too_many_bytes_not_classified_under_team_kill_switch(self, _name, level):+ error = wrap_clickhouse_query_error(ServerException("Limit for bytes to read exceeded", code=307))+ with patch("posthog.hogql_queries.query_failure_handling.get_team_kill_switch_level", return_value=level):+ assert classify_failure(error, team_id=42) is None++ def test_too_many_bytes_classified_when_no_switch_covers_team(self):+ error = wrap_clickhouse_query_error(ServerException("Limit for bytes to read exceeded", code=307))+ with patch(+ "posthog.hogql_queries.query_failure_handling.get_team_kill_switch_level",+ return_value=KillSwitchLevel.OFF,+ ):+ assert classify_failure(error, team_id=42) == "too_many_bytes"+@parameterized.expand([("interactive", None, BUDGET_INTERACTIVE),@@ -91,6 +119,15 @@ class TestQueryFailureHandling(SimpleTestCase):assert "This query failed the same way 3 times in a row" in detailassert detail.endswith("It can run again in about 2 minutes.")+ def test_build_failure_exception_matches_fresh_too_many_bytes_shape(self):+ record = _record("too_many_bytes", 1, "Limit for bytes to read exceeded: 1.10 TB, maximum: 1.00 TB")++ error = build_failure_exception(record)+ assert isinstance(error, ClickHouseBytesLimitExceeded)+ assert error.status_code == 400+ assert error.get_codes() == ["too_many_bytes"]+ assert "was not run again" in str(error.detail)+def test_build_failure_exception_first_failure_wording(self):with freeze_time("2026-01-01T00:00:00Z"):original_detail = str(ClickHouseQueryMemoryLimitExceeded().detail)diff --git a/posthog/query_cache/failures.py b/posthog/query_cache/failures.pyindex f5c128b46e83..38df4bd823fa 100644--- a/posthog/query_cache/failures.py+++ b/posthog/query_cache/failures.py@@ -20,7 +20,7 @@ QUERY_FAILURE_CACHE_COUNTER = Counter()# A kind names a failure class that repeats on retry; transient conditions must never get one.-FailureKind = Literal["memory_limit", "timeout", "too_slow", "query_size"]+FailureKind = Literal["memory_limit", "timeout", "too_slow", "query_size", "too_many_bytes"]Budget = Literal["interactive", "extended"]BUDGET_INTERACTIVE: Budget = "interactive"@@ -39,6 +39,7 @@ KIND_POLICIES: dict[FailureKind, KindPolicy] = {"timeout": KindPolicy(open_threshold=3, max_backoff=timedelta(hours=4), timeout_independent=False),"too_slow": KindPolicy(open_threshold=3, max_backoff=timedelta(hours=4), timeout_independent=False),"query_size": KindPolicy(open_threshold=1, max_backoff=timedelta(hours=4), timeout_independent=True),+ "too_many_bytes": KindPolicy(open_threshold=1, max_backoff=timedelta(hours=4), timeout_independent=True),}BASE_BACKOFF = timedelta(minutes=2)diff --git a/posthog/query_cache/test/test_failures.py b/posthog/query_cache/test/test_failures.pyindex 6bd15e787e15..ed132e910c66 100644--- a/posthog/query_cache/test/test_failures.py+++ b/posthog/query_cache/test/test_failures.py@@ -82,7 +82,7 @@ class TestQueryFailureCache(SimpleTestCase):assert record is not Noneassert record.open_until == datetime.now(UTC) + BASE_BACKOFF * 2- @parameterized.expand([("memory_limit",), ("query_size",)])+ @parameterized.expand([("memory_limit",), ("query_size",), ("too_many_bytes",)])def test_deterministic_kinds_open_on_first_failure(self, kind):failure_cache = QueryFailureCache(f"cache_key_instant_{kind}")with freeze_time("2026-01-01T00:00:00Z"):