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.

feat(query): cache deterministic query failures with a circuit breaker (#72777)

Andy Zhao890f6bd223fc
diff --git a/ee/clickhouse/test/test_error.py b/ee/clickhouse/test/test_error.py
index 947aac3dbcf6..061779b6bc49 100644
--- a/ee/clickhouse/test/test_error.py
+++ b/ee/clickhouse/test/test_error.py
@@ -2,7 +2,9 @@ import pytest
from clickhouse_driver.errors import ServerException
+from posthog.clickhouse.client import sync_execute
from posthog.errors import clickhouse_error_type, wrap_clickhouse_query_error
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
@pytest.mark.parametrize(
@@ -213,3 +215,12 @@ def test_wrap_clickhouse_query_error(error, expected_type, expected_message, exp
assert str(new_error) == expected_message
assert getattr(new_error, "code", None) == expected_code
assert label == expected_ch_error
+
+
+def test_per_query_memory_limit_phrasing_matches_real_clickhouse():
+ with pytest.raises(ClickHouseQueryMemoryLimitExceeded) as ctx:
+ sync_execute(
+ "SELECT groupArray(number) FROM numbers(10000000)",
+ settings={"max_memory_usage": 1_000_000},
+ )
+ assert ctx.value.is_per_query_limit
diff --git a/posthog/errors.py b/posthog/errors.py
index 96370df812e7..b0f84200ad91 100644
--- a/posthog/errors.py
+++ b/posthog/errors.py
@@ -122,7 +122,12 @@ def wrap_clickhouse_query_error(err: Exception) -> Exception:
elif name == "TIMEOUT_EXCEEDED":
return ClickHouseQueryTimeOut()
elif name == "MEMORY_LIMIT_EXCEEDED":
- return ClickHouseQueryMemoryLimitExceeded()
+ memory_error = ClickHouseQueryMemoryLimitExceeded()
+ # Match the known per-query phrasings ("Memory limit (for query) exceeded" before
+ # ClickHouse 26, "Query memory limit exceeded" since). Anything else - "(total)",
+ # "(for user)", or a future rewording - counts as transient cluster pressure.
+ memory_error.is_per_query_limit = "(for query)" in err.message or "Query memory limit exceeded" in err.message
+ return memory_error
elif (
name == "SYNTAX_ERROR" and "query size exceeded" in err.message
): # Handle syntax error when "max query size exceeded" in the message
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 22ca7200208d..7461fc5a2fd9 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -91,6 +91,9 @@ class ClickHouseQueryMemoryLimitExceeded(APIException):
# CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE constant.
default_code = "clickhouse_memory_limit_exceeded"
default_detail = "This query ran out of memory before it could finish, usually because it's scanning too much data. Try a shorter date range or narrower filters, or see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries"
+ # True only when ClickHouse hit this query's own memory ceiling, meaning a retry will fail
+ # the same way. Server-wide and per-user limits are transient cluster pressure.
+ is_per_query_limit = False
class ExceptionContext(TypedDict):
diff --git a/posthog/hogql_queries/query_failure_handling.py b/posthog/hogql_queries/query_failure_handling.py
new file mode 100644
index 000000000000..52de9c497fb1
--- /dev/null
+++ b/posthog/hogql_queries/query_failure_handling.py
@@ -0,0 +1,70 @@
+from datetime import UTC, datetime
+from typing import Optional
+
+from rest_framework.exceptions import APIException
+
+from posthog.hogql.constants import LimitContext
+
+from posthog.exceptions import (
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQuerySizeExceeded,
+ ClickHouseQueryTimeOut,
+)
+from posthog.query_cache.failures import BUDGET_EXTENDED, BUDGET_INTERACTIVE, Budget, FailureKind, QueryFailureRecord
+
+# The app-side mapping between failure kinds and exception classes; the breaker itself only
+# knows kinds. The stored failure details get shown to users, including on public share links,
+# so every class here must only ever carry user-safe detail copy.
+FAILURE_KIND_EXCEPTIONS: dict[FailureKind, type[APIException]] = {
+ "memory_limit": ClickHouseQueryMemoryLimitExceeded,
+ "timeout": ClickHouseQueryTimeOut,
+ "too_slow": ClickHouseEstimatedQueryExecutionTimeTooLong,
+ "query_size": ClickHouseQuerySizeExceeded,
+}
+
+
+def classify_failure(error: Exception) -> 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
+ if isinstance(error, ClickHouseQueryTimeOut):
+ return "timeout"
+ if isinstance(error, ClickHouseEstimatedQueryExecutionTimeTooLong):
+ return "too_slow"
+ if isinstance(error, ClickHouseQuerySizeExceeded):
+ return "query_size"
+ return None
+
+
+def budget_for_limit_context(limit_context: Optional[LimitContext]) -> Budget:
+ """Interactive requests get 60s of ClickHouse execution time while async workers and other
+ elevated contexts get 10x that, so a failure only proves anything about the budget it ran
+ under."""
+ return BUDGET_INTERACTIVE if limit_context in (None, LimitContext.QUERY) else BUDGET_EXTENDED
+
+
+def _approximate_wait(open_until: datetime) -> str:
+ minutes = max(1, round((open_until - datetime.now(UTC)).total_seconds() / 60))
+ if minutes < 60:
+ return f"{minutes} minute{'s' if minutes != 1 else ''}"
+ hours = max(1, round(minutes / 60))
+ return f"{hours} hour{'s' if hours != 1 else ''}"
+
+
+def build_failure_exception(record: QueryFailureRecord) -> APIException:
+ """Rebuild the remembered failure with its original exception class, so status codes and
+ frontend error handling stay identical to a fresh failure. The original message leads and
+ the breaker context follows it."""
+ sentences = [record.detail]
+ if record.consecutive_failures == 1:
+ sentences.append("This query failed in a way that will repeat, so it was not run again.")
+ else:
+ sentences.append(
+ f"This query failed the same way {record.consecutive_failures} times in a row, so it was not run again."
+ )
+ if record.open_until is not None:
+ sentences.append(f"It can run again in about {_approximate_wait(record.open_until)}.")
+ error = FAILURE_KIND_EXCEPTIONS[record.kind](detail=" ".join(sentences))
+ error.served_from_query_failure_cache = True # type: ignore[attr-defined]
+ return error
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 001f43417130..85a122c5b195 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -2,7 +2,7 @@ from abc import ABC, abstractmethod
from collections.abc import Sequence
from datetime import UTC, datetime, timedelta
from enum import StrEnum
-from functools import cache
+from functools import cache, cached_property
from time import perf_counter
from types import UnionType
from typing import Any, Generic, NamedTuple, Optional, Protocol, TypeGuard, TypeVar, Union, cast, get_args, get_origin
@@ -117,6 +117,11 @@ from posthog.hogql_queries.access_controlled_resources import queried_access_con
from posthog.hogql_queries.insights.utils.breakdowns import has_multi_breakdown, has_single_breakdown
from posthog.hogql_queries.insights.utils.entities import has_data_warehouse_node
from posthog.hogql_queries.insights.utils.properties import has_any_property_filters
+from posthog.hogql_queries.query_failure_handling import (
+ budget_for_limit_context,
+ build_failure_exception,
+ classify_failure,
+)
from posthog.hogql_queries.query_metadata import extract_query_metadata
from posthog.hogql_queries.utils.event_usage import log_event_usage_from_query_metadata
from posthog.hogql_queries.validation.validation import (
@@ -128,6 +133,13 @@ from posthog.models import Team, User
from posthog.models.team import WeekStartDay
from posthog.models.team.event_retention import events_retention_months_for_team
from posthog.query_cache import QueryCache, count_query_cache_hit
+from posthog.query_cache.failures import (
+ BUDGET_EXTENDED,
+ QUERY_FAILURE_CACHE_COUNTER,
+ QUERY_FAILURE_CACHING_FLAG,
+ Budget,
+ QueryFailureRecord,
+)
from posthog.rbac.user_access_control import WAREHOUSE_ACCESS_SCOPES, UserAccessControl, UserAccessControlError
from posthog.schema_helpers import to_dict
from posthog.scopes import APIScopeObject
@@ -1478,7 +1490,15 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
cached_response_candidate: Optional[dict]
self.raw_cached_results_bytes = None
raw_results: Optional[bytes] = None
- entry = cache_manager.lookup().entry
+ # The breaker record is only needed here to gate async dispatch; blocking execution is
+ # gated once, inside _execute_and_cache_blocking.
+ include_failure = self._query_failure_caching_enabled and execution_mode in (
+ ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,
+ ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
+ ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE,
+ )
+ lookup = cache_manager.lookup(include_failure=include_failure)
+ entry = lookup.entry
if self.serve_raw_cached_results:
# Serving results as raw bytes skips parsing (and later re-serializing) the results
# payload. Only safe when the caller opted in AND validation of the parsed results
@@ -1552,10 +1572,16 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
if execution_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE:
cached_response.query_status = self.get_async_query_status(cache_key=cache_manager.cache_key)
return cached_response
- elif execution_mode in (
+
+ # An open breaker forbids pointless recalculation: async dispatch is gated here,
+ # blocking recalculation is gated in _execute_and_cache_blocking.
+ failure = lookup.failure
+
+ if execution_mode in (
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
):
+ self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED)
# We're allowed to calculate, but we'll do it asynchronously and attach the query status
cached_response.query_status = self.enqueue_async_calculation(
cache_manager=cache_manager, user=user, refresh_requested=True, analytics_props=analytics_props
@@ -1565,6 +1591,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# We're allowed to calculate if the lazy check fails, but we'll do it asynchronously
assert isinstance(cached_response, CachedResponse)
if self._is_stale_for_request(last_refresh=last_refresh_from_cached_result(cached_response), lazy=True):
+ self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED)
cached_response.query_status = self.enqueue_async_calculation(
cache_manager=cache_manager, user=user, analytics_props=analytics_props
)
@@ -1577,10 +1604,14 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
if execution_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE:
cached_response.query_status = self.get_async_query_status(cache_key=cache_manager.cache_key)
return cached_response
- elif execution_mode in (
+
+ failure = lookup.failure
+
+ if execution_mode in (
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,
ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE,
):
+ self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED)
# We're allowed to calculate, but we'll do it asynchronously
cached_response.query_status = self.enqueue_async_calculation(
cache_manager=cache_manager, user=user, analytics_props=analytics_props
@@ -1592,6 +1623,38 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
self.raw_cached_results_bytes = None
return None
+ @cached_property
+ def _query_failure_caching_enabled(self) -> bool:
+ # only_evaluate_locally keeps this flag check off the network - this runs on the query
+ # hot path, so an inconclusive local evaluation must mean "off", never an HTTP call.
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ QUERY_FAILURE_CACHING_FLAG,
+ str(self.team.uuid),
+ groups={
+ "organization": str(self.team.organization_id),
+ "project": str(self.team.pk),
+ },
+ group_properties={
+ "organization": {"id": str(self.team.organization_id)},
+ "project": {"id": str(self.team.pk)},
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ return False
+
+ def _raise_if_failure_fresh_for(self, failure: Optional[QueryFailureRecord], budget: Budget) -> None:
+ """The one breaker rule: a failure outcome that is fresh for the given execution budget
+ substitutes for the execution it would forbid."""
+ if failure is None or not failure.forbids(budget):
+ return
+ QUERY_FAILURE_CACHE_COUNTER.labels(action="served_error", kind=failure.kind).inc()
+ raise build_failure_exception(failure)
+
def _call_with_rate_limits(self, *, dashboard_id: Optional[int]) -> tuple[R, float]:
"""Execute calculate() with all rate limiters applied.
@@ -1770,6 +1833,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
)
if execution_mode == ExecutionMode.CALCULATE_ASYNC_ALWAYS:
+ # The forced dispatch skips the result cache, but not the breaker: the
+ # enqueued job runs under the async budget, so only failures that cover
+ # that budget forbid it.
+ if self._query_failure_caching_enabled:
+ self._raise_if_failure_fresh_for(cache_manager.open_failure(), BUDGET_EXTENDED)
# We should always kick off async calculation and disregard the cache.
# cache_hit is left unset on this path because the cache wasn't consulted.
slo.tag(execution_path="async_dispatched")
@@ -1853,6 +1921,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
analytics_props=analytics_props,
)
except Exception as exc:
+ if getattr(exc, "served_from_query_failure_cache", False):
+ # ClickHouse was never touched; the original failure was already
+ # classified and captured when it happened.
+ slo.succeed(error_category="query_failure_cache")
+ raise
# Don't pass execution_path here: whichever branch tag was set before the raise
# (cache_hit / cache_miss / blocking / async_dispatched) stays intact so
# dashboards can attribute errors to the path they happened in. Errors that fire
@@ -1869,6 +1942,13 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# QUERY_PERFORMANCE_ERROR is FAILURE (so captured) even though a minority of
# those are user-input limits — see _classify_error_for_slo.
capture_exception(exc)
+ if self._query_failure_caching_enabled:
+ # Transient error classes classify to None and are never recorded.
+ failure_kind = classify_failure(exc)
+ 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)
+ )
raise
def _execute_and_cache_blocking(
@@ -1884,6 +1964,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
start_time: float,
analytics_props: Optional["AnalyticsProps"] = None,
) -> CR:
+ # The single gate for all blocking execution, forced refreshes included: an open
+ # breaker that covers this run's execution budget forbids touching ClickHouse.
+ if self._query_failure_caching_enabled:
+ self._raise_if_failure_fresh_for(cache_manager.open_failure(), budget_for_limit_context(self.limit_context))
+
CachedResponse: type[CR] = self.cached_response_type
last_refresh = datetime.now(UTC)
@@ -1995,6 +2080,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
target_age=target_age,
)
+ if not has_error and self._query_failure_caching_enabled:
+ # Deliberately outside the cache-write condition above: a successful export or
+ # debug run doesn't cache its result but must still close the failure breaker.
+ cache_manager.clear_failure()
+
query_executed_props = {
"insight_id": insight_id,
"dashboard_id": dashboard_id,
diff --git a/posthog/hogql_queries/test/test_query_failure_handling.py b/posthog/hogql_queries/test/test_query_failure_handling.py
new file mode 100644
index 000000000000..cda625058339
--- /dev/null
+++ b/posthog/hogql_queries/test/test_query_failure_handling.py
@@ -0,0 +1,105 @@
+from datetime import UTC, datetime, timedelta
+
+from freezegun import freeze_time
+
+from django.test import SimpleTestCase
+
+from clickhouse_driver.errors import ServerException
+from parameterized import parameterized
+from rest_framework.exceptions import ValidationError
+
+from posthog.hogql.constants import LimitContext
+
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
+from posthog.errors import wrap_clickhouse_query_error
+from posthog.exceptions import (
+ ClickHouseAtCapacity,
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQuerySizeExceeded,
+ ClickHouseQueryTimeOut,
+)
+from posthog.hogql_queries.query_failure_handling import (
+ budget_for_limit_context,
+ build_failure_exception,
+ classify_failure,
+)
+from posthog.query_cache.failures import BUDGET_EXTENDED, BUDGET_INTERACTIVE, QueryFailureRecord
+
+
+def _memory_error(message: str):
+ return wrap_clickhouse_query_error(ServerException(message, code=241))
+
+
+def _record(kind, consecutive_failures, detail, open_until=None):
+ return QueryFailureRecord(
+ kind=kind,
+ detail=detail,
+ consecutive_failures=consecutive_failures,
+ last_failed_at=datetime.now(UTC),
+ open_until=open_until,
+ budget=BUDGET_INTERACTIVE,
+ )
+
+
+class TestQueryFailureHandling(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("memory_per_query_26x", _memory_error("Query memory limit exceeded: would use 42.03 GiB"), "memory_limit"),
+ (
+ "memory_per_query_legacy",
+ _memory_error("Memory limit (for query) exceeded: would use 30.1 GiB"),
+ "memory_limit",
+ ),
+ ("memory_total", _memory_error("Memory limit (total) exceeded: would use 100 GiB"), None),
+ ("memory_for_user", _memory_error("Memory limit (for user) exceeded: would use 80 GiB"), None),
+ ("memory_unknown_phrasing", _memory_error("Some future memory message"), None),
+ ("timeout", ClickHouseQueryTimeOut(), "timeout"),
+ ("too_slow", ClickHouseEstimatedQueryExecutionTimeTooLong(), "too_slow"),
+ ("query_size", ClickHouseQuerySizeExceeded(), "query_size"),
+ ("at_capacity", ClickHouseAtCapacity(), None),
+ ("concurrency_limit", ConcurrencyLimitExceeded("busy"), None),
+ ("too_many_simultaneous", wrap_clickhouse_query_error(ServerException("busy", code=202)), None),
+ ("user_error", ValidationError("bad"), None),
+ ]
+ )
+ def test_classify_failure(self, _name, error, expected):
+ assert classify_failure(error) == expected
+
+ @parameterized.expand(
+ [
+ ("interactive", None, BUDGET_INTERACTIVE),
+ ("query", LimitContext.QUERY, BUDGET_INTERACTIVE),
+ ("worker", LimitContext.QUERY_ASYNC, BUDGET_EXTENDED),
+ ("export", LimitContext.EXPORT, BUDGET_EXTENDED),
+ ]
+ )
+ def test_budget_for_limit_context(self, _name, limit_context, expected):
+ assert budget_for_limit_context(limit_context) == expected
+
+ def test_build_failure_exception_preserves_class_and_status(self):
+ with freeze_time("2026-01-01T00:00:00Z"):
+ original_detail = str(ClickHouseQueryTimeOut().detail)
+ record = _record("timeout", 3, original_detail, open_until=datetime.now(UTC) + timedelta(minutes=2))
+
+ error = build_failure_exception(record)
+ assert isinstance(error, ClickHouseQueryTimeOut)
+ assert error.status_code == 504
+ assert getattr(error, "served_from_query_failure_cache", False)
+ detail = str(error.detail)
+ assert detail.startswith(original_detail)
+ assert "This query failed the same way 3 times in a row" in detail
+ assert detail.endswith("It can run again in about 2 minutes.")
+
+ def test_build_failure_exception_first_failure_wording(self):
+ with freeze_time("2026-01-01T00:00:00Z"):
+ original_detail = str(ClickHouseQueryMemoryLimitExceeded().detail)
+ record = _record("memory_limit", 1, original_detail, open_until=datetime.now(UTC) + timedelta(minutes=2))
+
+ error = build_failure_exception(record)
+ assert isinstance(error, ClickHouseQueryMemoryLimitExceeded)
+ assert error.status_code == 513
+ detail = str(error.detail)
+ assert detail.startswith(original_detail)
+ assert "This query failed in a way that will repeat" in detail
+ assert detail.endswith("It can run again in about 2 minutes.")
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 57cfdb2245ce..18c20b392e97 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -48,8 +48,10 @@ from posthog.hogql.errors import QueryError, ResolutionError
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.constants import AvailableFeature
from posthog.errors import ExposedCHQueryError
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOut
from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
+from posthog.hogql_queries.query_failure_handling import classify_failure
from posthog.hogql_queries.query_runner import (
SHARED_FORCE_BLOCKING_STALENESS_WINDOW,
AnalyticsQueryRunner,
@@ -62,6 +64,14 @@ from posthog.hogql_queries.query_runner import (
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team, WeekStartDay
+from posthog.query_cache.failures import (
+ BASE_BACKOFF,
+ BUDGET_EXTENDED,
+ BUDGET_INTERACTIVE,
+ KIND_POLICIES,
+ QUERY_FAILURE_CACHING_FLAG,
+ QueryFailureCache,
+)
from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError
try:
@@ -93,42 +103,46 @@ class TheTestQuery(BaseModel):
tags: QueryLogTags | None = None
-class TestQueryRunner(BaseTest):
- maxDiff = None
+def setup_test_query_runner_class(base: type[QueryRunner] = QueryRunner):
+ """Setup required methods and attributes of the abstract base class."""
- def tearDown(self):
- super().tearDown()
- cache.clear()
+ class TestQueryRunner(base): # type: ignore[misc, valid-type]
+ query: TheTestQuery
+ cached_response: TheTestCachedBasicQueryResponse
- def setup_test_query_runner_class(self, base: type[QueryRunner] = QueryRunner):
- """Setup required methods and attributes of the abstract base class."""
+ def _calculate(self):
+ return TheTestBasicQueryResponse(
+ results=[
+ ["row", 1, 2, 3],
+ (i for i in range(10)), # Test support of cache.set with iterators
+ ]
+ )
- class TestQueryRunner(base): # type: ignore[misc, valid-type]
- query: TheTestQuery
- cached_response: TheTestCachedBasicQueryResponse
+ def _refresh_frequency(self) -> timedelta:
+ return timedelta(minutes=4)
- def _calculate(self):
- return TheTestBasicQueryResponse(
- results=[
- ["row", 1, 2, 3],
- (i for i in range(10)), # Test support of cache.set with iterators
- ]
- )
+ def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False, *args, **kwargs) -> bool:
+ if not last_refresh:
+ raise ValueError("Cached results require a last_refresh")
- def _refresh_frequency(self) -> timedelta:
- return timedelta(minutes=4)
+ if lazy:
+ return last_refresh + timedelta(days=1) <= datetime.now(tz=ZoneInfo("UTC"))
+ return last_refresh + timedelta(minutes=10) <= datetime.now(tz=ZoneInfo("UTC"))
- def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False, *args, **kwargs) -> bool:
- if not last_refresh:
- raise ValueError("Cached results require a last_refresh")
+ TestQueryRunner.__abstractmethods__ = frozenset()
- if lazy:
- return last_refresh + timedelta(days=1) <= datetime.now(tz=ZoneInfo("UTC"))
- return last_refresh + timedelta(minutes=10) <= datetime.now(tz=ZoneInfo("UTC"))
+ return TestQueryRunner
- TestQueryRunner.__abstractmethods__ = frozenset()
- return TestQueryRunner
+class TestQueryRunner(BaseTest):
+ maxDiff = None
+
+ def tearDown(self):
+ super().tearDown()
+ cache.clear()
+
+ def setup_test_query_runner_class(self, base: type[QueryRunner] = QueryRunner):
+ return setup_test_query_runner_class(base)
def test_sync_warning_attach_preserves_other_warning_kinds(self):
# The accumulator attach replaces the response's warnings with the collected sync warnings.
@@ -586,6 +600,7 @@ class TestQueryRunner(BaseTest):
# Missing all the actual required fields like results, last_refresh, etc.
}
mock_cache_manager.lookup.return_value.entry = mock_entry
+ mock_cache_manager.lookup.return_value.failure = None
mock_query_cache_cls.return_value = mock_cache_manager
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
@@ -1681,3 +1696,195 @@ class TestQueryRunnerAccessControlFingerprint(BaseTest):
# Entitlement is read off the team's org, so the gate must short-circuit without building
# user_access_control (whose membership/preload reads are what we're avoiding per query).
assert runner._user_access_control is None
+
+
+def _failure_caching_flag(key: str, *args: Any, **kwargs: Any) -> bool:
+ return key == QUERY_FAILURE_CACHING_FLAG
+
+
+def _per_query_memory_error() -> ClickHouseQueryMemoryLimitExceeded:
+ error = ClickHouseQueryMemoryLimitExceeded()
+ error.is_per_query_limit = True
+ return error
+
+
+class TestQueryFailureCaching(BaseTest):
+ def tearDown(self):
+ super().tearDown()
+ cache.clear()
+
+ def _open_breaker(self, runner_class, runner, error: Optional[Exception] = None) -> mock.MagicMock:
+ error = error or ClickHouseQueryTimeOut()
+ kind = classify_failure(error)
+ assert kind is not None
+ threshold = KIND_POLICIES[kind].open_threshold
+ patcher = mock.patch.object(runner_class, "_calculate", autospec=True, side_effect=error)
+ mock_calculate = patcher.start()
+ self.addCleanup(patcher.stop)
+ for _ in range(threshold):
+ with self.assertRaises(type(error)):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert mock_calculate.call_count == threshold
+ return mock_calculate
+
+ def test_open_breaker_serves_remembered_error_without_calculating(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ mock_calculate = self._open_breaker(runner_class, runner)
+
+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ assert mock_calculate.call_count == KIND_POLICIES["timeout"].open_threshold
+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)
+ assert ctx.exception.status_code == 504
+
+ def test_open_breaker_raises_even_with_stale_cache(self):
+ # Stale data is deliberately not served to mask a failing query.
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ with freeze_time("2026-01-01T00:00:00Z") as frozen:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS) # seed the cache
+ frozen.tick(timedelta(minutes=15)) # past the harness's 10-minute staleness window
+
+ mock_calculate = self._open_breaker(runner_class, runner)
+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ assert mock_calculate.call_count == KIND_POLICIES["timeout"].open_threshold
+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)
+
+ @parameterized.expand(
+ [
+ ("memory_limit", _per_query_memory_error),
+ ("query_size", ClickHouseQuerySizeExceeded),
+ ]
+ )
+ def test_deterministic_kinds_open_on_first_failure(self, _name, make_error):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ error = make_error()
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ mock_calculate = self._open_breaker(runner_class, runner, error=error)
+ assert mock_calculate.call_count == 1
+
+ with self.assertRaises(type(error)) as ctx:
+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ assert mock_calculate.call_count == 1
+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)
+
+ def test_forced_blocking_run_respects_open_breaker(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ mock_calculate = self._open_breaker(runner_class, runner)
+
+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert mock_calculate.call_count == KIND_POLICIES["timeout"].open_threshold
+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)
+
+ def test_forced_async_dispatch_respects_open_breaker(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ self._open_breaker(runner_class, runner, error=_per_query_memory_error())
+
+ with mock.patch.object(runner_class, "enqueue_async_calculation", autospec=True) as mock_enqueue:
+ with self.assertRaises(ClickHouseQueryMemoryLimitExceeded) as ctx:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_ASYNC_ALWAYS)
+ mock_enqueue.assert_not_called()
+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)
+
+ def test_successful_run_after_backoff_closes_the_breaker(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ with freeze_time("2026-01-01T00:00:00Z") as frozen:
+ with mock.patch.object(
+ runner_class, "_calculate", autospec=True, side_effect=ClickHouseQueryTimeOut()
+ ) as mock_calculate:
+ for _ in range(KIND_POLICIES["timeout"].open_threshold):
+ with self.assertRaises(ClickHouseQueryTimeOut):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert QueryFailureCache(runner.get_cache_key()).get_open() is not None
+
+ # while open, even a forced refresh is refused without touching ClickHouse
+ with self.assertRaises(ClickHouseQueryTimeOut):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert mock_calculate.call_count == KIND_POLICIES["timeout"].open_threshold
+
+ # once the backoff elapses, the next run executes (the real harness _calculate),
+ # succeeds, and closes the breaker
+ frozen.tick(BASE_BACKOFF + timedelta(seconds=1))
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert QueryFailureCache(runner.get_cache_key()).get_open() is None
+
+ def test_extended_budget_run_ignores_interactive_breaker(self):
+ # The async worker executes with CALCULATE_BLOCKING_ALWAYS under a 10x execution budget,
+ # so a breaker opened by interactive timeouts must not stop it.
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=LimitContext.QUERY_ASYNC)
+ failure_cache = QueryFailureCache(runner.get_cache_key())
+ for _ in range(KIND_POLICIES["timeout"].open_threshold):
+ failure_cache.record_failure("timeout", "timed out", budget=BUDGET_INTERACTIVE)
+ assert failure_cache.get_open() is not None
+
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert response.is_cached is False
+ assert failure_cache.get_open() is None # the success closed the breaker
+
+ def test_extended_budget_run_blocked_by_extended_breaker(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=LimitContext.QUERY_ASYNC)
+ failure_cache = QueryFailureCache(runner.get_cache_key())
+ for _ in range(KIND_POLICIES["timeout"].open_threshold):
+ failure_cache.record_failure("timeout", "timed out", budget=BUDGET_EXTENDED)
+ assert failure_cache.get_open() is not None
+
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)
+
+ def test_no_behavior_change_when_flag_disabled(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch.object(
+ runner_class, "_calculate", autospec=True, side_effect=ClickHouseQueryTimeOut()
+ ) as mock_calculate:
+ for _ in range(KIND_POLICIES["timeout"].open_threshold + 2):
+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ assert not getattr(ctx.exception, "served_from_query_failure_cache", False)
+ assert mock_calculate.call_count == KIND_POLICIES["timeout"].open_threshold + 2
+
+ def test_interactive_timeout_breaker_spares_extended_budget(self):
+ # Interactive attempts run with a 10x smaller execution budget than the async worker, so
+ # a breaker opened by sync timeouts must still let async recalculation be enqueued.
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ self._open_breaker(runner_class, runner)
+
+ with mock.patch.object(
+ runner_class, "enqueue_async_calculation", autospec=True, return_value=None
+ ) as mock_enqueue:
+ response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE)
+ mock_enqueue.assert_called_once()
+ assert isinstance(response, CacheMissResponse)
+
+ def test_memory_limit_breaker_forbids_extended_budget(self):
+ # Memory-limit failures don't depend on the execution-time budget, so the breaker covers
+ # the async path too.
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
+ self._open_breaker(runner_class, runner, error=_per_query_memory_error())
+
+ with mock.patch.object(runner_class, "enqueue_async_calculation", autospec=True) as mock_enqueue:
+ with self.assertRaises(ClickHouseQueryMemoryLimitExceeded) as ctx:
+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE)
+ mock_enqueue.assert_not_called()
+ assert getattr(ctx.exception, "served_from_query_failure_cache", False)
diff --git a/posthog/query_cache/__init__.py b/posthog/query_cache/__init__.py
index 5e00088542f0..5120cae138bd 100644
--- a/posthog/query_cache/__init__.py
+++ b/posthog/query_cache/__init__.py
@@ -1,4 +1,5 @@
from posthog.query_cache.cache import CacheLookup, QueryCache
+from posthog.query_cache.failures import FailureKind, QueryFailureRecord
from posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insights
from posthog.query_cache.metrics import count_query_cache_hit
from posthog.query_cache.serialization import CachedEntry
@@ -6,7 +7,9 @@ from posthog.query_cache.serialization import CachedEntry
__all__ = [
"CachedEntry",
"CacheLookup",
+ "FailureKind",
"QueryCache",
+ "QueryFailureRecord",
"clean_up_stale_insights",
"count_query_cache_hit",
"get_stale_insights",
diff --git a/posthog/query_cache/cache.py b/posthog/query_cache/cache.py
index 46506c3681c6..abb4963f84de 100644
--- a/posthog/query_cache/cache.py
+++ b/posthog/query_cache/cache.py
@@ -5,6 +5,7 @@ from typing import Optional
from django.conf import settings
from posthog.cache_utils import OrjsonJsonSerializer
+from posthog.query_cache.failures import Budget, FailureKind, QueryFailureCache, QueryFailureRecord
from posthog.query_cache.freshness_index import remove_last_refresh, update_target_age
from posthog.query_cache.metrics import count_cache_write_data
from posthog.query_cache.results import fetch_entry
@@ -14,14 +15,16 @@ from posthog.query_cache.size_tracker import TeamCacheSizeTracker
@dataclass(frozen=True)
class CacheLookup:
- """Everything the cache knows about a cache key in one read."""
+ """Everything the cache knows about a cache key: the stored entry and any open failure record."""
entry: Optional[CachedEntry]
+ failure: Optional[QueryFailureRecord] = None
class QueryCache:
"""Facade over query result cache storage: blob store, wire format, per-team size limits,
- and the freshness index. Code outside posthog/query_cache goes through this class."""
+ the freshness index, and the failure circuit breaker. Code outside posthog/query_cache
+ goes through this class."""
def __init__(
self,
@@ -36,8 +39,21 @@ class QueryCache:
self.insight_id = insight_id
self.dashboard_id = dashboard_id
- def lookup(self) -> CacheLookup:
- return CacheLookup(entry=fetch_entry(self.cache_key, self.team_id))
+ def lookup(self, *, include_failure: bool = False) -> CacheLookup:
+ # The failure read is opt-in so callers that never consult the breaker (and the
+ # feature-flag-off path) don't pay an extra cache roundtrip per query.
+ failure = QueryFailureCache(self.cache_key).get_open() if include_failure else None
+ return CacheLookup(entry=fetch_entry(self.cache_key, self.team_id), failure=failure)
+
+ def open_failure(self) -> Optional[QueryFailureRecord]:
+ """The open breaker record alone, for paths that skip the result cache entirely."""
+ return QueryFailureCache(self.cache_key).get_open()
+
+ def record_failure(self, kind: FailureKind, detail: str, *, budget: Budget) -> Optional[QueryFailureRecord]:
+ return QueryFailureCache(self.cache_key).record_failure(kind, detail, budget=budget)
+
+ def clear_failure(self) -> None:
+ QueryFailureCache(self.cache_key).clear()
def store_result(self, *, response: dict, target_age: Optional[datetime]) -> None:
if isinstance(response.get("results"), list):
diff --git a/posthog/query_cache/failures.py b/posthog/query_cache/failures.py
new file mode 100644
index 000000000000..b9563708e06f
--- /dev/null
+++ b/posthog/query_cache/failures.py
@@ -0,0 +1,164 @@
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any, Literal, Optional, cast
+
+from django.core.cache import caches
+
+import structlog
+from prometheus_client import Counter
+
+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
+
+logger = structlog.get_logger(__name__)
+
+QUERY_FAILURE_CACHING_FLAG = "query-failure-caching"
+
+QUERY_FAILURE_CACHE_COUNTER = Counter(
+ "posthog_query_failure_cache_total",
+ "Circuit-breaker activity for queries that keep failing deterministically",
+ labelnames=["action", "kind"],
+)
+
+# 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"]
+
+Budget = Literal["interactive", "extended"]
+BUDGET_INTERACTIVE: Budget = "interactive"
+BUDGET_EXTENDED: Budget = "extended"
+
+
+@dataclass(frozen=True)
+class KindPolicy:
+ open_threshold: int
+ max_backoff: timedelta
+ timeout_independent: bool
+
+
+KIND_POLICIES: dict[FailureKind, KindPolicy] = {
+ "memory_limit": KindPolicy(open_threshold=1, max_backoff=timedelta(hours=4), timeout_independent=True),
+ "timeout": KindPolicy(open_threshold=3, max_backoff=timedelta(minutes=30), timeout_independent=False),
+ "too_slow": KindPolicy(open_threshold=3, max_backoff=timedelta(minutes=30), timeout_independent=False),
+ "query_size": KindPolicy(open_threshold=1, max_backoff=timedelta(hours=4), timeout_independent=True),
+}
+
+BASE_BACKOFF = timedelta(minutes=2)
+RECORD_TTL = timedelta(hours=24)
+
+
+@dataclass(frozen=True)
+class QueryFailureRecord:
+ kind: FailureKind
+ detail: str
+ consecutive_failures: int
+ last_failed_at: datetime
+ open_until: Optional[datetime]
+ budget: Budget = BUDGET_INTERACTIVE
+
+ @property
+ def is_open(self) -> bool:
+ return self.open_until is not None and datetime.now(UTC) < self.open_until
+
+ def forbids(self, budget: Budget) -> bool:
+ """A failure observed under the extended budget forbids every run, and timeout-independent
+ kinds forbid regardless. A failure observed under the interactive budget does not forbid
+ extended-budget runs, which get more execution time and may well succeed."""
+ if KIND_POLICIES[self.kind].timeout_independent or self.budget == BUDGET_EXTENDED:
+ return True
+ return budget == BUDGET_INTERACTIVE
+
+
+class QueryFailureCache:
+ """Per-cache-key circuit breaker for deterministically failing queries.
+
+ Failures are counted per query cache key; once the kind's open threshold is reached, the
+ breaker opens and requests that would otherwise recalculate are served the remembered
+ failure until an exponentially growing backoff elapses. Any successful calculation closes
+ the breaker. Storage errors fail open: a broken cache backend makes this feature a no-op,
+ never a query failure.
+ """
+
+ def __init__(self, cache_key: str) -> None:
+ self.key = f"query_failure:{cache_key}"
+
+ def get_open(self) -> Optional[QueryFailureRecord]:
+ record = self._load()
+ return record if record is not None and record.is_open else None
+
+ def record_failure(
+ self, kind: FailureKind, detail: str, budget: Budget = BUDGET_INTERACTIVE
+ ) -> Optional[QueryFailureRecord]:
+ """Count a deterministic failure. The detail is shown to users verbatim when the
+ remembered failure is served, so callers must only ever pass user-safe copy."""
+ policy = KIND_POLICIES.get(kind)
+ if policy is None:
+ # A caller bug, not a storage condition: surface it instead of failing open.
+ raise ValueError(f"Unknown failure kind: {kind}")
+ try:
+ previous = self._load()
+ failures = 1
+ record_budget = budget
+ if previous is not None and previous.kind == kind:
+ failures = previous.consecutive_failures + 1
+ if previous.budget == BUDGET_EXTENDED:
+ # Once the big-budget path has failed, a later small-budget failure must
+ # not narrow what the breaker forbids.
+ record_budget = BUDGET_EXTENDED
+ open_until: Optional[datetime] = None
+ if failures >= policy.open_threshold:
+ max_doublings = (policy.max_backoff // BASE_BACKOFF).bit_length()
+ doublings = min(failures - policy.open_threshold, max_doublings)
+ open_until = datetime.now(UTC) + min(BASE_BACKOFF * 2**doublings, policy.max_backoff)
+ record = QueryFailureRecord(
+ kind=kind,
+ # Capped so record size stays bounded no matter what copy a caller passes.
+ detail=detail[:1000],
+ consecutive_failures=failures,
+ last_failed_at=datetime.now(UTC),
+ open_until=open_until,
+ budget=record_budget,
+ )
+ caches[QUERY_CACHE_ALIAS].set(self.key, self._serialize(record), RECORD_TTL.total_seconds())
+ QUERY_FAILURE_CACHE_COUNTER.labels(action="opened" if open_until else "recorded", kind=kind).inc()
+ return record
+ except Exception:
+ logger.exception("query_failure_cache_write_failed", key=self.key)
+ return None
+
+ def clear(self) -> None:
+ try:
+ if caches[QUERY_CACHE_ALIAS].delete(self.key):
+ QUERY_FAILURE_CACHE_COUNTER.labels(action="cleared", kind="any").inc()
+ except Exception:
+ logger.exception("query_failure_cache_clear_failed", key=self.key)
+
+ def _load(self) -> Optional[QueryFailureRecord]:
+ try:
+ data = caches[QUERY_CACHE_ALIAS].get(self.key)
+ if not isinstance(data, dict):
+ return None
+ if data.get("kind") not in KIND_POLICIES:
+ # A record written by a different code version (rolling deploy, rollback) must
+ # read as "no record", never as an error.
+ return None
+ return QueryFailureRecord(
+ kind=cast(FailureKind, data["kind"]),
+ detail=data["detail"],
+ consecutive_failures=data["consecutive_failures"],
+ last_failed_at=datetime.fromisoformat(data["last_failed_at"]),
+ open_until=datetime.fromisoformat(data["open_until"]) if data["open_until"] else None,
+ budget=data.get("budget", BUDGET_INTERACTIVE),
+ )
+ except Exception:
+ logger.exception("query_failure_cache_read_failed", key=self.key)
+ return None
+
+ @staticmethod
+ def _serialize(record: QueryFailureRecord) -> dict[str, Any]:
+ return {
+ "kind": record.kind,
+ "detail": record.detail,
+ "consecutive_failures": record.consecutive_failures,
+ "last_failed_at": record.last_failed_at.isoformat(),
+ "open_until": record.open_until.isoformat() if record.open_until else None,
+ "budget": record.budget,
+ }
diff --git a/posthog/query_cache/test/test_failures.py b/posthog/query_cache/test/test_failures.py
new file mode 100644
index 000000000000..6bd15e787e15
--- /dev/null
+++ b/posthog/query_cache/test/test_failures.py
@@ -0,0 +1,134 @@
+from datetime import UTC, datetime, timedelta
+
+from freezegun import freeze_time
+
+from django.core.cache import caches
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
+from posthog.query_cache.failures import (
+ BASE_BACKOFF,
+ BUDGET_EXTENDED,
+ BUDGET_INTERACTIVE,
+ KIND_POLICIES,
+ QueryFailureCache,
+)
+
+
+class TestQueryFailureCache(SimpleTestCase):
+ def setUp(self):
+ super().setUp()
+ caches[QUERY_CACHE_ALIAS].clear()
+
+ @parameterized.expand(
+ [
+ ("interactive_timeout_spares_extended", "timeout", BUDGET_INTERACTIVE, False),
+ ("extended_timeout_forbids_extended", "timeout", BUDGET_EXTENDED, True),
+ ("interactive_too_slow_spares_extended", "too_slow", BUDGET_INTERACTIVE, False),
+ ("memory_forbids_regardless", "memory_limit", BUDGET_INTERACTIVE, True),
+ ("query_size_forbids_regardless", "query_size", BUDGET_INTERACTIVE, True),
+ ]
+ )
+ def test_forbids_extended_budget_by_kind_and_budget(self, _name, kind, budget, expected):
+ record = QueryFailureCache("cache_key_scope").record_failure(kind, "failed", budget=budget)
+ assert record is not None
+ assert record.forbids(BUDGET_EXTENDED) is expected
+ assert record.forbids(BUDGET_INTERACTIVE) is True
+
+ def test_extended_budget_is_sticky_across_later_interactive_failures(self):
+ failure_cache = QueryFailureCache("cache_key_sticky")
+ failure_cache.record_failure("timeout", "failed", budget=BUDGET_EXTENDED)
+ record = failure_cache.record_failure("timeout", "failed", budget=BUDGET_INTERACTIVE)
+ assert record is not None
+ assert record.budget == BUDGET_EXTENDED
+ assert record.forbids(BUDGET_EXTENDED)
+
+ def test_unknown_kind_raises_instead_of_failing_open(self):
+ with self.assertRaises(ValueError):
+ QueryFailureCache("cache_key_bad").record_failure("not_a_kind", "failed") # type: ignore[arg-type]
+
+ def test_unknown_kind_in_cache_fails_open(self):
+ caches[QUERY_CACHE_ALIAS].set(
+ "query_failure:cache_key_future",
+ {
+ "kind": "kind_from_a_newer_release",
+ "detail": "x",
+ "consecutive_failures": 99,
+ "last_failed_at": datetime.now(UTC).isoformat(),
+ "open_until": (datetime.now(UTC) + timedelta(hours=1)).isoformat(),
+ "budget": BUDGET_INTERACTIVE,
+ },
+ 300,
+ )
+ assert QueryFailureCache("cache_key_future").get_open() is None
+
+ def test_load_dependent_breaker_opens_after_threshold_and_backs_off_exponentially(self):
+ failure_cache = QueryFailureCache("cache_key_1")
+ with freeze_time("2026-01-01T00:00:00Z") as frozen:
+ for _ in range(KIND_POLICIES["timeout"].open_threshold - 1):
+ failure_cache.record_failure("timeout", "failed")
+ assert failure_cache.get_open() is None
+
+ record = failure_cache.record_failure("timeout", "failed")
+ assert record is not None
+ assert record.open_until == datetime.now(UTC) + BASE_BACKOFF
+ assert failure_cache.get_open() is not None
+
+ frozen.tick(BASE_BACKOFF + timedelta(seconds=1))
+ assert failure_cache.get_open() is None
+ record = failure_cache.record_failure("timeout", "failed")
+ assert record is not None
+ assert record.open_until == datetime.now(UTC) + BASE_BACKOFF * 2
+
+ @parameterized.expand([("memory_limit",), ("query_size",)])
+ 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"):
+ record = failure_cache.record_failure(kind, "failed")
+ assert record is not None
+ assert record.consecutive_failures == 1
+ assert record.open_until == datetime.now(UTC) + BASE_BACKOFF
+ assert failure_cache.get_open() is not None
+
+ record = failure_cache.record_failure(kind, "failed")
+ assert record is not None
+ assert record.open_until == datetime.now(UTC) + BASE_BACKOFF * 2
+
+ def test_backoff_is_capped_and_survives_high_failure_counts(self):
+ # 50 failures is past the point where uncapped backoff math overflows timedelta.
+ failure_cache = QueryFailureCache("cache_key_2")
+ with freeze_time("2026-01-01T00:00:00Z"):
+ record = None
+ for _ in range(50):
+ record = failure_cache.record_failure("timeout", "failed")
+ assert record is not None
+ assert record.consecutive_failures == 50
+ assert record.open_until == datetime.now(UTC) + KIND_POLICIES["timeout"].max_backoff
+
+ def test_kind_change_resets_the_consecutive_count(self):
+ failure_cache = QueryFailureCache("cache_key_kind_change")
+ failure_cache.record_failure("timeout", "failed")
+ failure_cache.record_failure("timeout", "failed")
+ record = failure_cache.record_failure("too_slow", "failed")
+ assert record is not None
+ assert record.consecutive_failures == 1
+
+ def test_clear_closes_breaker_and_resets_count(self):
+ failure_cache = QueryFailureCache("cache_key_3")
+ with freeze_time("2026-01-01T00:00:00Z"):
+ for _ in range(3):
+ failure_cache.record_failure("memory_limit", "failed")
+ assert failure_cache.get_open() is not None
+
+ failure_cache.clear()
+ assert failure_cache.get_open() is None
+ record = failure_cache.record_failure("memory_limit", "failed")
+ assert record is not None
+ assert record.consecutive_failures == 1
+
+ def test_detail_is_capped(self):
+ record = QueryFailureCache("cache_key_detail").record_failure("timeout", "x" * 5000)
+ assert record is not None
+ assert len(record.detail) == 1000