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.

chore(caching): remove query failure caching flag (#107786)

Vasco de Krijgerc95262e58c16
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index ee069fa8a8e7..145834c4ce6c 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -194,7 +194,6 @@ from posthog.query_cache import QueryCache, count_query_cache_hit, retention_ttl
from posthog.query_cache.failures import (
BUDGET_EXTENDED,
QUERY_FAILURE_CACHE_COUNTER,
- QUERY_FAILURE_CACHING_FLAG,
Budget,
QueryFailureCache,
QueryFailureRecord,
@@ -2079,7 +2078,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
raw_results: Optional[bytes] = None
# 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 (
+ include_failure = 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,
@@ -2210,10 +2209,6 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
self.raw_cached_results_bytes = None
return None
- @cached_property
- def _query_failure_caching_enabled(self) -> bool:
- return self._team_flag_enabled_locally(QUERY_FAILURE_CACHING_FLAG)
-
@cached_property
def _query_single_flight_enabled(self) -> bool:
return self._team_flag_enabled_locally(QUERY_SINGLE_FLIGHT_FLAG)
@@ -2487,8 +2482,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# 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, user)
+ self._raise_if_failure_fresh_for(cache_manager.open_failure(), BUDGET_EXTENDED, user)
# 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")
@@ -2591,15 +2585,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
)
def _raise_if_breaker_forbids(self, cache_manager: QueryCache, user: Optional[User]) -> None:
- if not self._query_failure_caching_enabled:
- return
self._raise_if_failure_fresh_for(
cache_manager.open_failure(), budget_for_limit_context(self.limit_context), user
)
def _record_breaker_failure(self, cache_manager: QueryCache, exc: Exception) -> None:
- if not self._query_failure_caching_enabled:
- return
# Transient error classes classify to None and are never recorded.
failure_kind = classify_failure(exc, self.team.pk)
if failure_kind is not None:
@@ -2908,7 +2898,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# Published as soon as the entry lands, so followers do not wait on this run's reporting.
flight.succeed(last_refresh)
- if not has_error and self._query_failure_caching_enabled:
+ if not has_error:
# 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()
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 376833b67e77..3e58bc8f1ca0 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -106,7 +106,6 @@ from posthog.query_cache.failures import (
BUDGET_EXTENDED,
BUDGET_INTERACTIVE,
KIND_POLICIES,
- QUERY_FAILURE_CACHING_FLAG,
QueryFailureCache,
WarmingQueryFailureCache,
)
@@ -1297,6 +1296,7 @@ class TestQueryRunner(BaseTest):
}
mock_cache_manager.lookup.return_value.entry = mock_entry
mock_cache_manager.lookup.return_value.failure = None
+ mock_cache_manager.open_failure.return_value = None
mock_query_cache_cls.return_value = mock_cache_manager
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
@@ -2402,10 +2402,6 @@ class TestQueryRunnerAccessControlFingerprint(BaseTest):
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:
server_error = ServerException("Memory limit (for query) exceeded: would use 30.1 GiB", code=241)
error = wrap_clickhouse_query_error(server_error)
@@ -2436,37 +2432,35 @@ class TestQueryFailureCaching(BaseTest):
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)
+ mock_calculate = self._open_breaker(runner_class, runner)
- with mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report:
- 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
- assert [call.args[0] for call in report.call_args_list] == ["query execution failed"]
- refused_props = report.call_args.args[1]
- assert (refused_props["outcome"], refused_props["error_category"], refused_props["failed_in"]) == (
- "refused",
- "query_performance_error",
- "prepare",
- )
+ with mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report:
+ 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
+ assert [call.args[0] for call in report.call_args_list] == ["query execution failed"]
+ refused_props = report.call_args.args[1]
+ assert (refused_props["outcome"], refused_props["error_category"], refused_props["failed_in"]) == (
+ "refused",
+ "query_performance_error",
+ "prepare",
+ )
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 time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:
- runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS) # seed the cache
- frozen.shift(timedelta(minutes=15)) # past the harness's 10-minute staleness window
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS) # seed the cache
+ frozen.shift(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)
+ 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(
[
@@ -2478,14 +2472,13 @@ class TestQueryFailureCaching(BaseTest):
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
+ 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)
+ 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)
@parameterized.expand(
[
@@ -2510,7 +2503,6 @@ class TestQueryFailureCaching(BaseTest):
redis_client = mock.Mock()
redis_client.get.return_value = json.dumps({"pending": True})
with (
- mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag),
mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis_client),
mock.patch("posthog.query_scan.trigger._KINDS_A_PERSON_BUILDS", _KINDS_WITH_THE_TEST_KIND),
mock.patch.object(
@@ -2539,49 +2531,46 @@ class TestQueryFailureCaching(BaseTest):
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)
+ 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)
+ 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())
+ 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)
+ 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 time_machine.travel("2026-01-01T00:00:00Z", tick=False) 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
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) 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
- # once the backoff elapses, the next run executes (the real harness _calculate),
- # succeeds, and closes the breaker
- frozen.shift(BASE_BACKOFF + timedelta(seconds=1))
+ # while open, even a forced refresh is refused without touching ClickHouse
+ with self.assertRaises(ClickHouseQueryTimeOut):
runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
- assert QueryFailureCache(runner.get_cache_key()).get_open() is None
+ 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.shift(BASE_BACKOFF + timedelta(seconds=1))
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert QueryFailureCache(runner.get_cache_key()).get_open() is None
@parameterized.expand([(None,), (EventSource.CACHE_WARMING,)])
def test_extended_budget_run_ignores_interactive_breaker(self, source: EventSource | None) -> None:
@@ -2594,11 +2583,10 @@ class TestQueryFailureCaching(BaseTest):
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,
- analytics_props={"source": source} if source is not None else None,
- )
+ response = runner.run(
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ analytics_props={"source": source} if source is not None else None,
+ )
assert response.is_cached is False
assert failure_cache.get_open() is None # the success closed the breaker
@@ -2619,10 +2607,7 @@ class TestQueryFailureCaching(BaseTest):
runner_class = setup_test_query_runner_class()
runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=LimitContext.QUERY_ASYNC)
failure_cache = WarmingQueryFailureCache(runner.get_cache_key())
- with (
- time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen,
- mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag),
- ):
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:
if has_fresh_cache:
runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
for _ in range(3):
@@ -2654,10 +2639,7 @@ class TestQueryFailureCaching(BaseTest):
runner_class = setup_test_query_runner_class()
runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=LimitContext.QUERY_ASYNC)
start = datetime(2026, 1, 1, tzinfo=UTC)
- with (
- time_machine.travel(start, tick=False) as frozen,
- mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag),
- ):
+ with time_machine.travel(start, tick=False) as frozen:
def time_out_after_ten_minutes(_runner: QueryRunner) -> None:
frozen.shift(timedelta(minutes=10))
@@ -2697,68 +2679,42 @@ class TestQueryFailureCaching(BaseTest):
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)
+ with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
assert getattr(ctx.exception, "served_from_query_failure_cache", False)
- @parameterized.expand([(None,), (EventSource.CACHE_WARMING,)])
- def test_no_behavior_change_when_flag_disabled(self, source: EventSource | None) -> None:
- runner_class = setup_test_query_runner_class()
- runner = runner_class(query={"some_attr": "bla"}, team=self.team)
- 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)
- 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,
- analytics_props={"source": source} if source is not None else None,
- )
- 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)
+ 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)
+ 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())
+ 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)
+ 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)
def _single_flight_flag(key: str, *args: Any, **kwargs: Any) -> bool:
return key == QUERY_SINGLE_FLIGHT_FLAG
-def _single_flight_and_failure_caching_flags(key: str, *args: Any, **kwargs: Any) -> bool:
- return key in (QUERY_FAILURE_CACHING_FLAG, QUERY_SINGLE_FLIGHT_FLAG)
-
-
class _LeaderInterrupted(BaseException):
pass
@@ -2809,7 +2765,7 @@ class TestQuerySingleFlightRunner(BaseTest):
recorded_at_release.append(QueryFailureCache(runner.get_cache_key()).get_open() is not None)
published.append(failure)
- with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_and_failure_caching_flags):
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_flag):
with mock.patch.object(runner_class, "_calculate", autospec=True, side_effect=_per_query_memory_error()):
with mock.patch.object(QuerySingleFlight, "fail", autospec=True, side_effect=note_failure):
with self.assertRaises(ClickHouseQueryMemoryLimitExceeded):
diff --git a/posthog/query_cache/failures.py b/posthog/query_cache/failures.py
index 6825cc604efe..b1e4222a8218 100644
--- a/posthog/query_cache/failures.py
+++ b/posthog/query_cache/failures.py
@@ -11,8 +11,6 @@ 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",