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): single-flight blocking executions per cache key (#100666)

Andy Zhao73fde10bb65f
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 8487d78be43f..4891b4847d55 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -56,6 +56,7 @@ from posthog.event_usage import EventSource, get_request_analytics_properties, r
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.apply_dashboard_filters import apply_dashboard_filters, apply_dashboard_variables
from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
+from posthog.hogql_queries.query_failure_handling import captured_elsewhere
from posthog.hogql_queries.query_runner import ExecutionMode, execution_mode_from_refresh
from posthog.models.user import User
from posthog.models.utils import uuid7
@@ -402,8 +403,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
# caller's signal, not error noise.
raise
except Exception as e:
- # Breaker replays were already captured when the original failure happened.
- if not getattr(e, "served_from_query_failure_cache", False):
+ if not captured_elsewhere(e):
capture_exception(e)
raise
@@ -534,8 +534,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
# caller's signal, not error noise.
raise
except Exception as e:
- # Breaker replays were already captured when the original failure happened.
- if not getattr(e, "served_from_query_failure_cache", False):
+ if not captured_elsewhere(e):
capture_exception(e)
raise
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 7c066f7766b7..0fe392a6d8b2 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -89,6 +89,15 @@ class ClickHouseAtCapacity(APIException):
)
+class QueryRanConcurrently(APIException):
+ """Raised by a query single flight follower whose leader left nothing to serve or rebuild: the
+ leader failed in a way that cannot be shared, died, or held its lock past the limit."""
+
+ status_code = 503
+ default_code = "query_ran_concurrently"
+ default_detail = "This query was already running and its result couldn't be reused. Try again in a moment."
+
+
class ClickHouseEstimatedQueryExecutionTimeTooLong(APIException):
status_code = 512 # Custom error code
default_detail = "Estimated query execution time is too long. Try reducing its scope by changing the time range."
diff --git a/posthog/hogql_queries/ai/session_query_runner.py b/posthog/hogql_queries/ai/session_query_runner.py
index 840683936fd3..775b1325e608 100644
--- a/posthog/hogql_queries/ai/session_query_runner.py
+++ b/posthog/hogql_queries/ai/session_query_runner.py
@@ -276,10 +276,12 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
return cast(ast.SelectQuery, query)
def get_cache_payload(self) -> dict[str, Any]:
- return {
- **super().get_cache_payload(),
- "schema_version": 2,
- }
+ payload = {**super().get_cache_payload(), "schema_version": 2}
+ # An evaluation read has a bounded window and no events fallback, so it must not share a result
+ # with a plain read. Keyed only when on, so plain reads keep their cache entries.
+ if self.for_evaluation:
+ payload["for_evaluation"] = True
+ return payload
def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:
if last_refresh is None:
diff --git a/posthog/hogql_queries/ai/test/test_session_query_runner.py b/posthog/hogql_queries/ai/test/test_session_query_runner.py
index 307845184079..af389f22b64f 100644
--- a/posthog/hogql_queries/ai/test/test_session_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_session_query_runner.py
@@ -59,6 +59,12 @@ def _select_queries_without_metadata(queries: list[str]) -> list[str]:
class TestSessionQueryRunner(ClickhouseTestMixin, BaseTest):
+ def test_evaluation_reads_do_not_share_a_cache_key_with_plain_reads(self) -> None:
+ query = SessionQuery(sessionId="session-a", dateRange=DateRange(date_from="-1d", date_to="now"))
+ plain = SessionQueryRunner(team=self.team, query=query)
+ evaluation = SessionQueryRunner(team=self.team, query=query, for_evaluation=True)
+ self.assertNotEqual(evaluation.get_cache_key(), plain.get_cache_key())
+
def test_reads_complete_trace_when_only_root_has_session_id(self) -> None:
bulk_create_ai_events(
[
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index 85ea0d0c7bcf..6245593265a3 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -48,6 +48,8 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
query: HogQLQuery
cached_response: CachedHogQLQueryResponse
settings: Optional[HogQLGlobalSettings]
+ # p95 duration of a query service HogQL query is 2.78sec
+ QUERY_SERVICE_MAX_EXECUTION_TIME = 10
def __init__(
self,
@@ -222,18 +224,29 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
def to_actors_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
return self.to_query()
- def _calculate(self) -> HogQLQueryResponse:
- tag_contains_user_hogql()
- if (
+ def single_flight_variant(self) -> str:
+ # The query service cap and custom settings change the execution time without reaching the cache key.
+ max_execution_time: Optional[int] = (
+ self.QUERY_SERVICE_MAX_EXECUTION_TIME
+ if self._capped_for_query_service()
+ else (self.settings.max_execution_time if self.settings else None)
+ )
+ return f"{super().single_flight_variant()}:max_execution_time={max_execution_time}"
+
+ def _capped_for_query_service(self) -> bool:
+ return bool(
self.is_query_service
and app_settings.API_QUERIES_LEGACY_TEAM_LIST
and self.team.pk not in app_settings.API_QUERIES_LEGACY_TEAM_LIST
- ):
+ )
+
+ def _calculate(self) -> HogQLQueryResponse:
+ tag_contains_user_hogql()
+ if self._capped_for_query_service():
assert self.settings is not None
# p95 threads is 102, limiting to 60 (below global max_threads of 64)
self.settings.max_threads = 60
- # p95 duration of HogQL query is 2.78sec
- self.settings.max_execution_time = 10
+ self.settings.max_execution_time = self.QUERY_SERVICE_MAX_EXECUTION_TIME
self._validate_direct_connection()
diff --git a/posthog/hogql_queries/query_failure_handling.py b/posthog/hogql_queries/query_failure_handling.py
index d36ae3e28a6c..d7bd26aff6d7 100644
--- a/posthog/hogql_queries/query_failure_handling.py
+++ b/posthog/hogql_queries/query_failure_handling.py
@@ -1,20 +1,30 @@
from datetime import UTC, datetime
-from typing import Optional
+from typing import Optional, TypeIs
+from clickhouse_driver.errors import ServerException
from rest_framework.exceptions import APIException
+from posthog.hogql import errors as hogql_errors
from posthog.hogql.constants import LimitContext
+from posthog.hogql.errors import ExposedHogQLError, TableAccessDeniedError
from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level, get_team_kill_switch_level
-from posthog.errors import CHQueryErrorTooManyBytes
+from posthog.errors import (
+ CHQueryErrorTooManyBytes,
+ QueryErrorCategory,
+ classify_query_error,
+ wrap_clickhouse_query_error,
+)
from posthog.exceptions import (
ClickHouseBytesLimitExceeded,
ClickHouseEstimatedQueryExecutionTimeTooLong,
ClickHouseQueryMemoryLimitExceeded,
ClickHouseQuerySizeExceeded,
ClickHouseQueryTimeOut,
+ QueryRanConcurrently,
)
from posthog.query_cache.failures import BUDGET_EXTENDED, BUDGET_INTERACTIVE, Budget, FailureKind, QueryFailureRecord
+from posthog.query_cache.single_flight import SharedFailure
# 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,
@@ -28,6 +38,89 @@ FAILURE_KIND_EXCEPTIONS: dict[FailureKind, type[APIException]] = {
}
+# Failure categories that repeat for every run of the same query under the same limits. Capacity,
+# cancellation, and unclassified errors can pass on the next try, so followers do not inherit them.
+SHAREABLE_FAILURE_CATEGORIES = frozenset({QueryErrorCategory.USER_ERROR, QueryErrorCategory.QUERY_PERFORMANCE_ERROR})
+
+
+def captured_elsewhere(error: BaseException) -> bool:
+ """Whether error tracking already holds this failure or has nothing to learn from it: a breaker
+ replay, a follower's rebuild of its leader's failure, or a follower whose leader left it nothing
+ to serve, which the leader's own capture and the flight metrics account for."""
+ return bool(
+ isinstance(error, QueryRanConcurrently)
+ or getattr(error, "served_from_query_failure_cache", False)
+ or getattr(error, "served_from_query_single_flight", False)
+ )
+
+
+def shareable_failure(error: Exception) -> Optional[SharedFailure]:
+ """The part of a leader's failure a follower can rebuild into the same exception.
+
+ Only failures that repeat for every run of the query are shared. A ClickHouse server error
+ travels by its code; the ClickHouse client raises the app's exception from the server error, so
+ the code is found on the exception or behind it. An exposed HogQL error travels by its class.
+ The candidate is rebuilt here first and shared only when that gives back the leader's own class
+ and message, so nothing the app decided on its own, such as an app-side limit, ever travels."""
+ if classify_query_error(error) not in SHAREABLE_FAILURE_CATEGORIES:
+ return None
+ try:
+ candidate = _shared_failure_candidate(error)
+ rebuilt = rebuild_shared_failure(candidate) if candidate is not None else None
+ except Exception:
+ # Sharing is best effort and must never replace the error the leader raises.
+ return None
+ if candidate is None or rebuilt is None or not same_failure(rebuilt, error):
+ return None
+ return candidate
+
+
+def same_failure(rebuilt: Exception, error: Exception) -> bool:
+ # The error factory builds a class per call for codes without a dedicated class, so the
+ # class name and its bases stand for identity.
+ return (
+ type(rebuilt).__name__ == type(error).__name__
+ and type(rebuilt).__mro__[1:] == type(error).__mro__[1:]
+ and str(rebuilt) == str(error)
+ )
+
+
+def _shared_failure_candidate(error: Exception) -> Optional[SharedFailure]:
+ cause: Optional[BaseException] = error
+ while cause is not None:
+ if isinstance(cause, ServerException) and cause.code is not None:
+ return SharedFailure(message=str(cause.message), code=cause.code)
+ cause = cause.__cause__
+ if isinstance(error, ExposedHogQLError) and _is_shareable_hogql_error(type(error)):
+ return SharedFailure(
+ message=str(error), class_name=type(error).__name__, start=error.start, end=error.end, fix=error.fix
+ )
+ return None
+
+
+def _is_shareable_hogql_error(cls: object) -> TypeIs[type[ExposedHogQLError]]:
+ # Table access depends on the user, and the users behind one cache key can differ.
+ return isinstance(cls, type) and issubclass(cls, ExposedHogQLError) and not issubclass(cls, TableAccessDeniedError)
+
+
+def rebuild_shared_failure(failure: SharedFailure) -> Optional[Exception]:
+ """The leader's exception again, marked as served by the flight. None when this code version
+ cannot rebuild it, in which case the follower fails with QueryRanConcurrently."""
+ error: Exception
+ if failure.code is not None:
+ error = wrap_clickhouse_query_error(ServerException(failure.message, code=failure.code))
+ else:
+ cls = getattr(hogql_errors, failure.class_name or "", None)
+ if not _is_shareable_hogql_error(cls):
+ return None
+ try:
+ error = cls(failure.message, start=failure.start, end=failure.end, fix=failure.fix)
+ except TypeError:
+ return None
+ error.served_from_query_single_flight = True # type: ignore[attr-defined]
+ return error
+
+
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):
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 7d850d1adec1..57b7b5b529b3 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -136,13 +136,16 @@ from posthog.constants import AvailableFeature
from posthog.dataclasses import frozen
from posthog.errors import QueryErrorCategory, classify_query_error, clickhouse_error_type
from posthog.event_usage import AnalyticsProps, groups, report_team_action, report_user_or_team_action
-from posthog.exceptions import APIQueriesBudgetExceeded
+from posthog.exceptions import APIQueriesBudgetExceeded, QueryRanConcurrently
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.access_controlled_resources import queried_access_controlled_resources
from posthog.hogql_queries.query_failure_handling import (
budget_for_limit_context,
build_failure_exception,
+ captured_elsewhere,
classify_failure,
+ rebuild_shared_failure,
+ shareable_failure,
)
from posthog.hogql_queries.query_metadata import extract_query_metadata
from posthog.hogql_queries.utils.breakdowns import has_multi_breakdown, has_single_breakdown
@@ -166,10 +169,16 @@ from posthog.query_cache.failures import (
Budget,
QueryFailureRecord,
)
+from posthog.query_cache.single_flight import (
+ QUERY_SINGLE_FLIGHT_COUNTER,
+ QUERY_SINGLE_FLIGHT_FLAG,
+ FlightWait,
+ QuerySingleFlight,
+)
from posthog.schema_helpers import to_dict
from posthog.scopes import APIScopeObject
from posthog.shared_link_user import SharedLinkUser
-from posthog.slo.context import JsonValue, SloSpec, slo_operation
+from posthog.slo.context import JsonValue, SloSpec, slo_operation, tag_current_slo
from posthog.slo.types import SloArea, SloOperation, SloOutcome
from posthog.synthetic_user import SyntheticUser
from posthog.utils import generate_cache_key, get_from_dict_or_attr, to_json
@@ -2042,12 +2051,19 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
@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)
+
+ def _team_flag_enabled_locally(self, flag_key: str) -> 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,
+ flag_key,
str(self.team.uuid),
groups={
"organization": str(self.team.organization_id),
@@ -2242,7 +2258,6 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
trigger: str | None = get_query_tag_value("trigger")
- CachedResponse: type[CR] = self.cached_response_type
cache_manager = QueryCache(
team_id=self.team.pk,
cache_key=cache_key,
@@ -2281,52 +2296,17 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
analytics_props=analytics_props,
)
if results:
- cache_tracking_props = {}
- if isinstance(results, CachedResponse):
- if (not trigger or not trigger.startswith("warming")) and results.query_metadata:
- log_event_usage_from_query_metadata(
- results.query_metadata,
- team_id=self.team.id,
- user_id=user.id if user else None,
- )
-
- last_refresh = last_refresh_from_cached_result(results)
- cache_tracking_props = {
- "is_cache_stale": self._is_stale_for_request(last_refresh=last_refresh),
- "calculation_trigger": results.calculation_trigger,
- "cache_age_seconds": round((datetime.now(UTC) - last_refresh).total_seconds(), 2)
- if last_refresh
- else None,
- "last_refresh": last_refresh.isoformat() if last_refresh else None,
- }
- slo.tag(
- execution_path="cache_hit",
- cache_hit=True,
- **cache_tracking_props,
- )
- else:
- slo.tag(execution_path="cache_miss", cache_hit=False)
-
- query_executed_props = {
- "insight_id": insight_id,
- "dashboard_id": dashboard_id,
- "execution_mode": execution_mode.value,
- "query_type": query_type,
- "cache_key": cache_key,
- "cache_hit": isinstance(results, CachedResponse),
- "cache_age_override": cache_age_seconds,
- "response_time_ms": round((perf_counter() - start_time) * 1000, 2),
- **cache_tracking_props,
- }
- report_user_or_team_action(
- "query executed",
- query_executed_props,
+ self._report_result_from_cache(
+ results,
+ cache_key=cache_key,
+ execution_mode=execution_mode,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ trigger=trigger,
user=user,
- team=self.team,
- organization=self.team.organization,
+ start_time=start_time,
analytics_props=analytics_props,
)
-
return results
# cache_hit is left unset on this path: either the caller passed
@@ -2349,6 +2329,10 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# classified and captured when it happened.
slo.succeed(error_category="query_failure_cache")
raise
+ if getattr(exc, "served_from_query_single_flight", False):
+ # The leader ran the query, and it already classified and captured this failure.
+ slo.succeed(error_category="query_single_flight")
+ 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
@@ -2364,14 +2348,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# gate is the SLO outcome, not a strict platform-vs-user split:
# 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, 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)
- )
+ if not captured_elsewhere(exc):
+ capture_exception(exc)
raise
def _execute_and_cache_blocking(
@@ -2389,9 +2367,201 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
) -> 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))
+ self._raise_if_breaker_forbids(cache_manager)
+ flight: Optional[QuerySingleFlight] = None
+ if self._joins_single_flight():
+ flight = cache_manager.flight(budget_for_limit_context(self.limit_context), self.single_flight_variant())
+ if flight.acquire():
+ QUERY_SINGLE_FLIGHT_COUNTER.labels(action="leader").inc()
+ else:
+ wait = flight.wait()
+ if wait.outcome != "unavailable":
+ return self._serve_flight_outcome(
+ wait,
+ cache_manager,
+ cache_key=cache_key,
+ execution_mode=execution_mode,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ trigger=trigger,
+ user=user,
+ start_time=start_time,
+ analytics_props=analytics_props,
+ )
+ # The flight cannot be read, so this run goes alone, as it does when acquire hits a storage error.
+ QUERY_SINGLE_FLIGHT_COUNTER.labels(action="follower_ran_alone").inc()
+ flight = None
+
+ try:
+ return self._calculate_and_cache_blocking(
+ cache_key=cache_key,
+ cache_manager=cache_manager,
+ execution_mode=execution_mode,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ trigger=trigger,
+ user=user,
+ start_time=start_time,
+ analytics_props=analytics_props,
+ flight=flight,
+ )
+ except Exception as exc:
+ # Recorded before the release so the next request to take the lead sees this failure.
+ self._record_breaker_failure(cache_manager, exc)
+ if flight is not None:
+ flight.fail(shareable_failure(exc))
+ raise
+ finally:
+ if flight is not None:
+ # Releases on every way out that published nothing, such as a result that was not stored.
+ flight.release()
+
+ def _joins_single_flight(self) -> bool:
+ # A runner that requires a fresh calculation exists so a stored result is never served, which
+ # rules out serving a leader's entry too. An export never stores its result, so its leader
+ # would have nothing to hand a follower.
+ return (
+ self._query_single_flight_enabled
+ and not self.requires_fresh_calculation()
+ and self.limit_context != LimitContext.EXPORT
+ )
+
+ def _raise_if_breaker_forbids(self, cache_manager: QueryCache) -> 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))
+
+ 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:
+ cache_manager.record_failure(failure_kind, str(exc), budget=budget_for_limit_context(self.limit_context))
+
+ def _serve_flight_outcome(
+ self,
+ wait: FlightWait,
+ cache_manager: QueryCache,
+ *,
+ cache_key: str,
+ execution_mode: ExecutionMode,
+ insight_id: Optional[int],
+ dashboard_id: Optional[int],
+ trigger: Optional[str],
+ user: Optional[User],
+ start_time: float,
+ analytics_props: Optional["AnalyticsProps"],
+ ) -> CR:
+ """Serve the entry the leader published, or fail the way it failed."""
+ if wait.outcome == "done":
+ # Only the entry the leader published. Identity is settled by last_refresh, so the
+ # read ignores the request's freshness window: an entry a moment old is still the
+ # answer, whatever cache age was requested.
+ served = self.handle_cache_and_async_logic(
+ execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
+ cache_manager=cache_manager,
+ user=user,
+ analytics_props=analytics_props,
+ )
+ if (
+ isinstance(served, self.cached_response_type)
+ and last_refresh_from_cached_result(served) == wait.last_refresh
+ ):
+ QUERY_SINGLE_FLIGHT_COUNTER.labels(action="follower_served_cache").inc()
+ self._report_result_from_cache(
+ served,
+ cache_key=cache_key,
+ execution_mode=execution_mode,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ trigger=trigger,
+ user=user,
+ start_time=start_time,
+ analytics_props=analytics_props,
+ execution_path="single_flight_follower",
+ )
+ return served
+ if wait.outcome == "failed" and wait.failure is not None:
+ error = rebuild_shared_failure(wait.failure)
+ if error is not None:
+ QUERY_SINGLE_FLIGHT_COUNTER.labels(action="follower_failed_with_leader").inc()
+ raise error
+ # The leader failed in a way that cannot be shared, died, held its lock past the limit, or its entry is gone.
+ QUERY_SINGLE_FLIGHT_COUNTER.labels(action=f"follower_unresolved_{wait.outcome}").inc()
+ raise QueryRanConcurrently()
+
+ def _report_result_from_cache(
+ self,
+ results: CR | CacheMissResponse,
+ *,
+ cache_key: str,
+ execution_mode: ExecutionMode,
+ insight_id: Optional[int],
+ dashboard_id: Optional[int],
+ trigger: Optional[str],
+ user: Optional[User],
+ start_time: float,
+ analytics_props: Optional["AnalyticsProps"],
+ execution_path: str = "cache_hit",
+ ) -> None:
+ cache_tracking_props: dict[str, Any] = {}
+ if isinstance(results, self.cached_response_type):
+ if (not trigger or not trigger.startswith("warming")) and results.query_metadata:
+ log_event_usage_from_query_metadata(
+ results.query_metadata,
+ team_id=self.team.id,
+ user_id=user.id if user else None,
+ )
+
+ last_refresh = last_refresh_from_cached_result(results)
+ cache_tracking_props = {
+ "is_cache_stale": self._is_stale_for_request(last_refresh=last_refresh),
+ "calculation_trigger": results.calculation_trigger,
+ "cache_age_seconds": round((datetime.now(UTC) - last_refresh).total_seconds(), 2)
+ if last_refresh
+ else None,
+ "last_refresh": last_refresh.isoformat() if last_refresh else None,
+ }
+ tag_current_slo(execution_path=execution_path, cache_hit=True, **cache_tracking_props)
+ else:
+ tag_current_slo(execution_path="cache_miss", cache_hit=False)
+
+ query_executed_props = {
+ "insight_id": insight_id,
+ "dashboard_id": dashboard_id,
+ "execution_mode": execution_mode.value,
+ "query_type": getattr(self.query, "kind", "Other"),
+ "cache_key": cache_key,
+ "cache_hit": isinstance(results, self.cached_response_type),
+ "cache_age_override": self._cache_age_override,
+ "response_time_ms": round((perf_counter() - start_time) * 1000, 2),
+ **cache_tracking_props,
+ }
+ report_user_or_team_action(
+ "query executed",
+ query_executed_props,
+ user=user,
+ team=self.team,
+ organization=self.team.organization,
+ analytics_props=analytics_props,
+ )
+
+ def _calculate_and_cache_blocking(
+ self,
+ *,
+ cache_key: str,
+ cache_manager: QueryCache,
+ execution_mode: ExecutionMode,
+ insight_id: Optional[int],
+ dashboard_id: Optional[int],
+ trigger: Optional[str],
+ user: Optional[User],
+ start_time: float,
+ analytics_props: Optional["AnalyticsProps"] = None,
+ flight: Optional[QuerySingleFlight] = None,
+ ) -> CR:
CachedResponse: type[CR] = self.cached_response_type
last_refresh = datetime.now(UTC)
@@ -2495,13 +2665,16 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
errors: Optional[list[Any]] = fresh_response_dict.get("error", None)
has_error = errors is not None and len(errors) > 0
if not has_error and self.limit_context != LimitContext.EXPORT:
- cache_manager.store_result(
+ stored = cache_manager.store_result(
response=fresh_response_dict,
# This would be a possible place to decide to not ever keep this cache warm
# Example: Not for super quickly calculated insights
# Set target_age to None in that case
target_age=target_age,
)
+ if stored and flight is not None:
+ # 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:
# Deliberately outside the cache-write condition above: a successful export or
@@ -2885,6 +3058,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
def _refresh_frequency(self) -> timedelta:
return timedelta(minutes=1)
+ def single_flight_variant(self) -> str:
+ """Separates single flights of runs that share a cache key but not their limits or results.
+ Runners add any input that changes either without reaching the cache key."""
+ return self.workload.value
+
def requires_fresh_calculation(self) -> bool:
"""Runners whose results reflect live, mutable state that must never be served stale
override this to force a blocking recompute, bypassing cached results. See
diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.py
index 3cee2b739a45..417afa8b2e23 100644
--- a/posthog/hogql_queries/test/test_hogql_query_runner.py
+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py
@@ -516,6 +516,18 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
response = runner.calculate()
self.assertEqual(len(response.results), 5)
+ def test_query_service_runs_do_not_share_a_flight_with_app_runs(self):
+ app_runner = self._create_runner(HogQLQuery(query="select event from events limit 1"))
+ service_runner = self._create_runner(HogQLQuery(query="select event from events limit 1"))
+ service_runner.is_query_service = True
+ with patch(
+ "posthog.hogql_queries.hogql_query_runner.app_settings.API_QUERIES_LEGACY_TEAM_LIST", {self.team.pk + 1}
+ ):
+ assert (service_runner.get_cache_key(), service_runner.single_flight_variant()) != (
+ app_runner.get_cache_key(),
+ app_runner.single_flight_variant(),
+ )
+
@patch("posthoganalytics.feature_enabled", return_value=False)
def test_non_query_service_allows_offset(self, _mock_flag):
# Product queries (Trends/Funnels/etc.) have is_query_service=False — must pass through
diff --git a/posthog/hogql_queries/test/test_query_failure_handling.py b/posthog/hogql_queries/test/test_query_failure_handling.py
index 78be5b5cbca9..d93f41cc2292 100644
--- a/posthog/hogql_queries/test/test_query_failure_handling.py
+++ b/posthog/hogql_queries/test/test_query_failure_handling.py
@@ -1,3 +1,4 @@
+from dataclasses import asdict
from datetime import UTC, datetime, timedelta
import time_machine
@@ -10,6 +11,11 @@ from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.hogql.constants import LimitContext
+from posthog.hogql.errors import (
+ QueryError,
+ SyntaxError as HogQLSyntaxError,
+ TableAccessDeniedError,
+)
from posthog.clickhouse.client.execute import KillSwitchLevel
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
@@ -21,13 +27,17 @@ from posthog.exceptions import (
ClickHouseQueryMemoryLimitExceeded,
ClickHouseQuerySizeExceeded,
ClickHouseQueryTimeOut,
+ DatabaseSchemaUnavailable,
)
from posthog.hogql_queries.query_failure_handling import (
budget_for_limit_context,
build_failure_exception,
classify_failure,
+ rebuild_shared_failure,
+ shareable_failure,
)
from posthog.query_cache.failures import BUDGET_EXTENDED, BUDGET_INTERACTIVE, QueryFailureRecord
+from posthog.query_cache.single_flight import SharedFailure
def _memory_error(message: str):
@@ -45,6 +55,74 @@ def _record(kind, consecutive_failures, detail, open_until=None):
)
+def _clickhouse_error(message: str, code: int) -> Exception:
+ server_error = ServerException(message, code=code)
+ error = wrap_clickhouse_query_error(server_error)
+ error.__cause__ = server_error # as the ClickHouse client raises it
+ return error
+
+
+def _wrapped_by_the_app() -> Exception:
+ error = DatabaseSchemaUnavailable()
+ error.__cause__ = ServerException("Cannot compare", code=386)
+ return error
+
+
+class TestSharedFailures(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("clickhouse_server_error", lambda: _clickhouse_error("Cannot compare", 386)),
+ ("clickhouse_error_without_a_dedicated_class", lambda: _clickhouse_error("Division by zero", 153)),
+ ("timeout", lambda: _clickhouse_error("Timeout exceeded", 159)),
+ ("too_slow", lambda: _clickhouse_error("Estimated query execution time (300 seconds) is too long.", 160)),
+ (
+ "per_query_memory_limit",
+ lambda: _clickhouse_error("Memory limit (for query) exceeded: would use 30.1 GiB", 241),
+ ),
+ ("hogql_query_error", lambda: QueryError("Unknown field: nope", start=7, end=11)),
+ ("hogql_syntax_error", lambda: HogQLSyntaxError("Unexpected token", start=0, end=3, fix="select")),
+ ]
+ )
+ def test_shared_failure_rebuilds_the_same_exception(self, _name, make_error):
+ original = make_error()
+ shared = shareable_failure(original)
+ assert shared is not None
+ rebuilt = rebuild_shared_failure(SharedFailure(**asdict(shared))) # as it comes back from Redis
+ assert rebuilt is not None
+ assert type(rebuilt).__name__ == type(original).__name__
+ assert type(rebuilt).__mro__[1:] == type(original).__mro__[1:]
+ assert str(rebuilt) == str(original)
+ for attribute in ("is_per_query_limit", "code_name", "start", "end", "fix"):
+ assert getattr(rebuilt, attribute, None) == getattr(original, attribute, None)
+ assert getattr(rebuilt, "served_from_query_single_flight", False)
+
+ @parameterized.expand(
+ [
+ ("at_capacity", lambda: _clickhouse_error("Too many simultaneous queries", 202)),
+ ("cluster_memory_limit", lambda: _clickhouse_error("Memory limit (total) exceeded", 241)),
+ ("query_cancelled", lambda: _clickhouse_error("Query was cancelled", 394)),
+ ("concurrency_limit", lambda: ConcurrencyLimitExceeded("busy")),
+ ("app_raised_timeout", lambda: ClickHouseQueryTimeOut()),
+ ("wrapped_by_the_app", _wrapped_by_the_app),
+ ("table_access", lambda: TableAccessDeniedError("events")),
+ ("validation", lambda: ValidationError("bad")),
+ ("plain", lambda: RuntimeError("boom")),
+ ]
+ )
+ def test_failures_that_may_pass_on_retry_or_do_not_rebuild_faithfully_are_not_shared(self, _name, make_error):
+ assert shareable_failure(make_error()) is None
+
+ @parameterized.expand(
+ [
+ ("unknown_class", SharedFailure(message="x", class_name="RenamedInANewerDeploy")),
+ ("not_an_exposed_hogql_error", SharedFailure(message="x", class_name="ResolutionError")),
+ ("table_access_depends_on_the_user", SharedFailure(message="x", class_name="TableAccessDeniedError")),
+ ]
+ )
+ def test_published_class_this_version_cannot_rebuild_is_not_rebuilt(self, _name, failure):
+ assert rebuild_shared_failure(failure) is None
+
+
class TestQueryFailureHandling(SimpleTestCase):
@parameterized.expand(
[
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 2a7e6b7b7e80..442b21d14acf 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -15,6 +15,7 @@ from django.db import OperationalError, connection
from django.test import override_settings
from django.test.utils import CaptureQueriesContext
+from clickhouse_driver.errors import ServerException
from parameterized import parameterized
from pydantic import BaseModel
from rest_framework.exceptions import ValidationError
@@ -58,14 +59,20 @@ from posthog.hogql.constants import LimitContext
from posthog.hogql.database.database import Database
from posthog.hogql.errors import QueryError, ResolutionError
+from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries
from posthog.constants import AvailableFeature
-from posthog.errors import ExposedCHQueryError
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOut
+from posthog.errors import ExposedCHQueryError, wrap_clickhouse_query_error
+from posthog.exceptions import (
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQuerySizeExceeded,
+ ClickHouseQueryTimeOut,
+ QueryRanConcurrently,
+)
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
-from posthog.hogql_queries.query_failure_handling import classify_failure
+from posthog.hogql_queries.query_failure_handling import budget_for_limit_context, classify_failure
from posthog.hogql_queries.query_runner import (
SHARED_FORCE_BLOCKING_STALENESS_WINDOW,
AnalyticsQueryRunner,
@@ -83,7 +90,10 @@ from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team.team import Team, WeekStartDay
from posthog.models.team.team_revenue_analytics_config import TeamRevenueAnalyticsConfig
from posthog.models.user import User
-from posthog.query_cache import storage as qc_storage
+from posthog.query_cache import (
+ QueryCache,
+ storage as qc_storage,
+)
from posthog.query_cache.failures import (
BASE_BACKOFF,
BUDGET_EXTENDED,
@@ -92,6 +102,7 @@ from posthog.query_cache.failures import (
QUERY_FAILURE_CACHING_FLAG,
QueryFailureCache,
)
+from posthog.query_cache.single_flight import QUERY_SINGLE_FLIGHT_FLAG, FlightWait, QuerySingleFlight, SharedFailure
from posthog.query_cache.storage import entry_redis_key
from posthog.shared_link_user import SharedLinkUser
from posthog.slo.types import SloOutcome
@@ -921,6 +932,15 @@ class TestQueryRunner(BaseTest):
"query_performance_error",
True,
),
+ (
+ # A follower whose leader left nothing to serve fails the SLO; the leader's capture and
+ # the flight metrics already account for it.
+ "query_ran_concurrently",
+ QueryRanConcurrently,
+ SloOutcome.FAILURE,
+ "error",
+ False,
+ ),
("unclassified_value_error", ValueError, SloOutcome.FAILURE, "error", True),
]
)
@@ -1771,8 +1791,10 @@ def _failure_caching_flag(key: str, *args: Any, **kwargs: Any) -> bool:
def _per_query_memory_error() -> ClickHouseQueryMemoryLimitExceeded:
- error = ClickHouseQueryMemoryLimitExceeded()
- error.is_per_query_limit = True
+ server_error = ServerException("Memory limit (for query) exceeded: would use 30.1 GiB", code=241)
+ error = wrap_clickhouse_query_error(server_error)
+ error.__cause__ = server_error # as the ClickHouse client raises it
+ assert isinstance(error, ClickHouseQueryMemoryLimitExceeded)
return error
@@ -1958,6 +1980,211 @@ class TestQueryFailureCaching(BaseTest):
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
+
+
+class TestQuerySingleFlightRunner(BaseTest):
+ def tearDown(self):
+ super().tearDown()
+ cache.clear()
+
+ def _become_follower(self, wait_result: Any = None) -> None:
+ if wait_result is None:
+ wait_result = FlightWait(outcome="released")
+ wait_kwargs = {"side_effect": wait_result} if callable(wait_result) else {"return_value": wait_result}
+ for name, kwargs in (("acquire", {"return_value": False}), ("wait", wait_kwargs)):
+ patcher = mock.patch.object(QuerySingleFlight, name, autospec=True, **kwargs)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ @staticmethod
+ def _flight_of(runner: Any) -> QuerySingleFlight:
+ return QuerySingleFlight(
+ runner.get_cache_key(), budget_for_limit_context(runner.limit_context), runner.single_flight_variant()
+ )
+
+ @parameterized.expand([("success", None), ("failure", ClickHouseQueryTimeOut), ("interrupted", _LeaderInterrupted)])
+ def test_leader_releases_the_flight(self, _name, error_class):
+ 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=_single_flight_flag):
+ if error_class is None:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ else:
+ with mock.patch.object(runner_class, "_calculate", autospec=True, side_effect=error_class()):
+ with self.assertRaises(error_class):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
+ probe = self._flight_of(runner)
+ self.addCleanup(probe.release)
+ assert probe.acquire() is True # the leader released its lock
+
+ def test_leader_records_its_failure_before_releasing_the_flight(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ recorded_at_release: list[bool] = []
+ published: list[Any] = []
+
+ def note_failure(flight: QuerySingleFlight, failure: Any) -> None:
+ 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.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):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert recorded_at_release == [True]
+ assert published == [SharedFailure(message="Memory limit (for query) exceeded: would use 30.1 GiB", code=241)]
+
+ def test_leader_that_stores_nothing_publishes_nothing(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=_single_flight_flag):
+ with mock.patch.object(QueryCache, "store_result", autospec=True, return_value=False):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert self._flight_of(runner).wait(timeout_seconds=0) == FlightWait(outcome="released")
+
+ @parameterized.expand(
+ [
+ (
+ "clickhouse_error",
+ SharedFailure(message="Memory limit (for query) exceeded", code=241),
+ ClickHouseQueryMemoryLimitExceeded,
+ ),
+ (
+ "hogql_error",
+ SharedFailure(message="Unknown field: nope", class_name="QueryError", start=7, end=11),
+ QueryError,
+ ),
+ ]
+ )
+ def test_follower_fails_the_way_the_leader_published(self, _name, failure, error_class):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ self._become_follower(FlightWait(outcome="failed", failure=failure))
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_flag):
+ with mock.patch.object(runner_class, "_calculate", autospec=True) as mock_calculate:
+ with self.assertRaises(error_class) as ctx:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ mock_calculate.assert_not_called()
+ assert getattr(ctx.exception, "served_from_query_single_flight", False)
+
+ @parameterized.expand(
+ [
+ ("leader_failed_without_a_shareable_failure", FlightWait(outcome="failed")),
+ (
+ "published_failure_unknown_to_this_version",
+ FlightWait(outcome="failed", failure=SharedFailure(message="x", class_name="RenamedInANewerDeploy")),
+ ),
+ ("leader_vanished", FlightWait(outcome="released")),
+ ("wait_timed_out", FlightWait(outcome="timeout")),
+ ("published_entry_never_landed", FlightWait(outcome="done", last_refresh=datetime(2026, 1, 1, tzinfo=UTC))),
+ ]
+ )
+ def test_follower_fails_instead_of_running_when_the_leader_leaves_nothing_to_serve(self, _name, wait_result):
+ runner_class = setup_test_query_runner_class()
+ runner_class(query={"some_attr": "bla"}, team=self.team).run(
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ ) # fresh for this request, but not written by the leader
+
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ self._become_follower(wait_result)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_flag):
+ with mock.patch.object(runner_class, "_calculate", autospec=True) as mock_calculate:
+ with self.assertRaises(QueryRanConcurrently):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ mock_calculate.assert_not_called()
+
+ def test_follower_runs_alone_when_the_flight_is_unavailable(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ self._become_follower(FlightWait(outcome="unavailable"))
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_flag):
+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert response.is_cached is False
+
+ @parameterized.expand(
+ [
+ ("budget", {"limit_context": LimitContext.QUERY_ASYNC}),
+ ("workload", {"workload": Workload.OFFLINE}),
+ ]
+ )
+ def test_runs_that_differ_in_limits_do_not_share_a_flight(self, _name, other_kwargs):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ other = runner_class(query={"some_attr": "bla"}, team=self.team, **other_kwargs)
+ assert other.get_cache_key() == runner.get_cache_key() # the cache key cannot tell them apart
+ other_leader = self._flight_of(other)
+ self.addCleanup(other_leader.release)
+ assert other_leader.acquire() is True
+ with mock.patch.object(QuerySingleFlight, "wait", autospec=True) as mock_wait:
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_flag):
+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ mock_wait.assert_not_called()
+ assert response.is_cached is False # it led a flight of its own
+
+ def test_follower_serves_the_entry_the_leader_wrote(self):
+ runner_class = setup_test_query_runner_class()
+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False) as frozen:
+ runner_class(query={"some_attr": "bla"}, team=self.team).run(
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ ) # an earlier entry, still fresh for this request
+
+ def leader_writes_while_we_wait(*args: Any, **kwargs: Any) -> FlightWait:
+ frozen.shift(timedelta(seconds=1))
+ with mock.patch("posthoganalytics.feature_enabled", return_value=False):
+ leader_response = runner_class(query={"some_attr": "bla"}, team=self.team).run(
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ )
+ return FlightWait(outcome="done", last_refresh=leader_response.last_refresh)
+
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+ self._become_follower(leader_writes_while_we_wait)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_flag):
+ with mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report:
+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert response.is_cached is True
+ assert response.last_refresh == datetime(2026, 1, 1, 0, 0, 1, tzinfo=UTC) # the leader's, not the earlier entry
+ assert report.call_args.args[0] == "query executed"
+ assert report.call_args.args[1]["cache_hit"] is True
+
+ def test_follower_serves_the_published_entry_whatever_cache_age_was_requested(self):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)
+
+ def leader_writes_while_we_wait(*args: Any, **kwargs: Any) -> FlightWait:
+ with mock.patch("posthoganalytics.feature_enabled", return_value=False):
+ leader_response = runner_class(query={"some_attr": "bla"}, team=self.team).run(
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ )
+ return FlightWait(outcome="done", last_refresh=leader_response.last_refresh)
+
+ self._become_follower(leader_writes_while_we_wait)
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=_single_flight_flag):
+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, cache_age_seconds=0)
+ assert response.is_cached is True # a zero cache age window must not reject the leader's own write
+
+ @parameterized.expand([("flag_off", False, None), ("export", True, LimitContext.EXPORT)])
+ def test_runs_that_cannot_share_a_result_never_touch_the_flight(self, _name, flag_on, limit_context):
+ runner_class = setup_test_query_runner_class()
+ runner = runner_class(query={"some_attr": "bla"}, team=self.team, limit_context=limit_context)
+ flags = _single_flight_flag if flag_on else (lambda *args, **kwargs: False)
+ with mock.patch.object(QuerySingleFlight, "acquire", autospec=True) as mock_acquire:
+ with mock.patch("posthoganalytics.feature_enabled", side_effect=flags):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ mock_acquire.assert_not_called()
+
+
class TestRunnersBuildDatabaseOnce(ClickhouseTestMixin, APIBaseTest):
# Guards the context threading in each runner's _calculate: the one Database build
# must go through shared_database (visible as the build_shared_database timing),
diff --git a/posthog/query_cache/cache.py b/posthog/query_cache/cache.py
index 9cbe05b1fb6b..356464f177b5 100644
--- a/posthog/query_cache/cache.py
+++ b/posthog/query_cache/cache.py
@@ -13,6 +13,7 @@ from posthog.query_cache.freshness_index import remove_last_refresh, update_targ
from posthog.query_cache.metrics import count_cache_write_data
from posthog.query_cache.results import EntryFreshness, fetch_entry, fetch_entry_freshness
from posthog.query_cache.serialization import CachedEntry, encode_split_cached_response
+from posthog.query_cache.single_flight import QuerySingleFlight
from posthog.query_cache.size_tracker import TeamCacheSizeTracker
from posthog.query_cache.storage import encode_inline_value, schedule_upload_for_pointer
@@ -92,7 +93,10 @@ class QueryCache:
def clear_failure(self) -> None:
QueryFailureCache(self.cache_key).clear()
- def store_result(self, *, response: dict, target_age: Optional[datetime]) -> None:
+ def flight(self, budget: Budget, variant: str = "") -> QuerySingleFlight:
+ return QuerySingleFlight(self.cache_key, budget, variant)
+
+ def store_result(self, *, response: dict, target_age: Optional[datetime]) -> bool:
if isinstance(response.get("results"), list):
# Split format keeps `results` as its own JSON segment so cache hits can skip
# parsing it (see CachedEntry). Pods that predate the format treat split entries
@@ -125,7 +129,7 @@ class QueryCache:
)
except Exception:
logger.exception("query_cache_store_result_failed", team_id=self.team_id, cache_key=self.cache_key)
- return
+ return False
if target_age:
update_target_age(
@@ -138,3 +142,4 @@ class QueryCache:
remove_last_refresh(team_id=self.team_id, insight_id=self.insight_id, dashboard_id=self.dashboard_id)
count_cache_write_data(data_size)
+ return True
diff --git a/posthog/query_cache/single_flight.py b/posthog/query_cache/single_flight.py
new file mode 100644
index 000000000000..5c9473e8f004
--- /dev/null
+++ b/posthog/query_cache/single_flight.py
@@ -0,0 +1,290 @@
+import json
+import time
+import uuid
+import threading
+from dataclasses import asdict, fields
+from datetime import datetime
+from typing import Any, Literal, Optional
+
+import structlog
+from prometheus_client import Counter, Histogram
+
+from posthog.dataclasses import frozen
+from posthog.query_cache import storage
+from posthog.query_cache.failures import BUDGET_EXTENDED, BUDGET_INTERACTIVE, Budget
+
+logger = structlog.get_logger(__name__)
+
+QUERY_SINGLE_FLIGHT_FLAG = "query-single-flight"
+
+QUERY_SINGLE_FLIGHT_COUNTER = Counter(
+ "posthog_query_single_flight_total",
+ "Blocking query executions by their role in a single flight",
+ labelnames=["action"],
+)
+
+QUERY_SINGLE_FLIGHT_WAIT_SECONDS = Histogram(
+ "posthog_query_single_flight_wait_seconds",
+ "Time a follower spent waiting for the leader of an identical blocking query",
+ buckets=[0.1, 0.5, 1, 2, 5, 10, 20, 30, 60, 120, 300, 600, 1800, 3600],
+)
+
+# The leader extends the lock on every heartbeat, so the lock lives for as long as the leader
+# does, and a leader that dies without releasing is noticed within three missed heartbeats.
+FLIGHT_HEARTBEAT_INTERVAL = 5.0
+FLIGHT_LOCK_TTL = 3 * FLIGHT_HEARTBEAT_INTERVAL
+# The longest a leader holds its lock. Past it the heartbeat stops and the lock expires, so a leader
+# stuck in its query cannot hold a cache key for as long as its process lives. Followers wait while
+# the lock exists, so this also bounds their wait. It covers limiter queueing and runners that send
+# several queries, not only one ClickHouse execution.
+FLIGHT_MAX_LEADER_SECONDS: dict[Budget, float] = {
+ BUDGET_INTERACTIVE: 300.0,
+ BUDGET_EXTENDED: 3600.0,
+}
+# Followers poll quickly at first and then back off, so a follower of a long leader costs little.
+FLIGHT_POLL_INTERVAL = 0.25
+FLIGHT_MAX_POLL_INTERVAL = 1.0
+# Acquiring the lock drops the previous result, so the result can safely outlive a stalled follower.
+FLIGHT_RESULT_TTL = 60
+
+# Acquiring the lock also drops the result the previous leader published, so a result can only ever
+# belong to the flight that is currently in progress or just ended.
+_ACQUIRE_LOCK_SCRIPT = """
+if redis.call("set", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) then
+ redis.call("del", KEYS[2])
+ return 1
+end
+return 0
+"""
+
+# Every other leader script acts only while this leader still owns the lock, so a leader that lost
+# the lock cannot extend, release, or publish over the leader that replaced it.
+_EXTEND_OWN_LOCK_SCRIPT = """
+if redis.call("get", KEYS[1]) == ARGV[1] then
+ return redis.call("pexpire", KEYS[1], ARGV[2])
+end
+return 0
+"""
+
+_RELEASE_OWN_LOCK_SCRIPT = """
+if redis.call("get", KEYS[1]) == ARGV[1] then
+ return redis.call("del", KEYS[1])
+end
+return 0
+"""
+
+_PUBLISH_RESULT_AND_RELEASE_OWN_LOCK_SCRIPT = """
+if redis.call("get", KEYS[1]) == ARGV[1] then
+ redis.call("set", KEYS[2], ARGV[2], "EX", ARGV[3])
+ return redis.call("del", KEYS[1])
+end
+return 0
+"""
+
+# Reads the lock and the result in one step, so a new leader cannot drop the result between two reads.
+_POLL_SCRIPT = """
+if redis.call("exists", KEYS[1]) == 1 then
+ return {1}
+end
+return {0, redis.call("get", KEYS[2]) or ""}
+"""
+
+FlightOutcome = Literal["done", "failed", "released", "timeout", "unavailable"]
+
+
+@frozen
+class SharedFailure:
+ """A leader's failure in the form a follower rebuilds into the same exception: a ClickHouse
+ server error by its code, or an exposed HogQL error by its class name."""
+
+ message: str
+ code: Optional[int] = None
+ class_name: Optional[str] = None
+ start: Optional[int] = None
+ end: Optional[int] = None
+ fix: Optional[str] = None
+
+ def __post_init__(self) -> None:
+ if (self.code is None) == (self.class_name is None):
+ raise ValueError("SharedFailure needs exactly one of code or class_name")
+
+
+@frozen
+class FlightWait:
+ # "unavailable" means the flight could not be read: storage failed, or the publication was unreadable.
+ outcome: FlightOutcome
+ # last_refresh of the entry the leader wrote, present only when the outcome is "done".
+ last_refresh: Optional[datetime] = None
+ # The leader's failure, present when the outcome is "failed" and the failure could be shared.
+ failure: Optional[SharedFailure] = None
+
+
+class QuerySingleFlight:
+ """Collapses concurrent blocking executions of one cache key onto one leader.
+
+ Followers wait while the leader holds the lock, then serve the entry it published or fail the
+ way it published. A follower runs the query only when the flight itself is unavailable: storage
+ errors and unreadable publications fail open to independent execution, never to a query failure.
+ """
+
+ def __init__(self, cache_key: str, budget: Budget, variant: str = "") -> None:
+ # The hash tag keeps both keys in one Redis Cluster slot so one script can touch both. Runs
+ # pair only within one budget and variant, which carry what changes a run's limits or
+ # results without reaching the cache key.
+ partition = f"{budget}:{variant}" if variant else budget
+ self.lock_key = f"query_flight:{{{cache_key}}}:{partition}"
+ self.result_key = f"query_flight_result:{{{cache_key}}}:{partition}"
+ self._budget = budget
+ self._token = uuid.uuid4().hex
+ self._held = False
+ self._heartbeat: Optional[_Heartbeat] = None
+
+ def acquire(self) -> bool:
+ try:
+ client = storage.query_cache_raw_client()
+ # redis-py's stubs omit register_script on RedisCluster; the runtime supports it.
+ acquired = client.register_script(_ACQUIRE_LOCK_SCRIPT)( # type: ignore[union-attr]
+ keys=[self.lock_key, self.result_key], args=[self._token, _millis(FLIGHT_LOCK_TTL)]
+ )
+ except Exception:
+ self._storage_failed("acquire")
+ return True
+ if not acquired:
+ return False
+ self._held = True
+ self._heartbeat = _Heartbeat(self, max_seconds=FLIGHT_MAX_LEADER_SECONDS[self._budget])
+ return True
+
+ def extend(self) -> Optional[bool]:
+ """Push the lock's expiry out by one TTL. False once this leader no longer owns the lock,
+ None when storage was unreachable and ownership is unknown."""
+ try:
+ client = storage.query_cache_raw_client()
+ extended = client.register_script(_EXTEND_OWN_LOCK_SCRIPT)( # type: ignore[union-attr]
+ keys=[self.lock_key], args=[self._token, _millis(FLIGHT_LOCK_TTL)]
+ )
+ return bool(extended)
+ except Exception:
+ self._storage_failed("extend")
+ return None
+
+ def succeed(self, last_refresh: datetime) -> None:
+ """Release the lock, telling followers which entry to serve."""
+ self._release({"last_refresh": last_refresh.isoformat()})
+
+ def fail(self, failure: Optional[SharedFailure]) -> None:
+ """Release the lock, telling followers the leader failed, with the failure when it can be shared."""
+ self._release({"failure": None if failure is None else asdict(failure)})
+
+ def release(self) -> None:
+ """Release the lock without a publication. Does nothing once the lock is released."""
+ self._release(None)
+
+ def _release(self, published: Optional[dict]) -> None:
+ if not self._held:
+ return
+ self._held = False
+ if self._heartbeat is not None:
+ self._heartbeat.stop()
+ self._heartbeat = None
+ try:
+ client = storage.query_cache_raw_client()
+ if published is None:
+ client.register_script(_RELEASE_OWN_LOCK_SCRIPT)(keys=[self.lock_key], args=[self._token]) # type: ignore[union-attr]
+ else:
+ client.register_script(_PUBLISH_RESULT_AND_RELEASE_OWN_LOCK_SCRIPT)( # type: ignore[union-attr]
+ keys=[self.lock_key, self.result_key],
+ args=[self._token, json.dumps(published), FLIGHT_RESULT_TTL],
+ )
+ except Exception:
+ self._storage_failed("release")
+
+ def wait(self, timeout_seconds: Optional[float] = None) -> FlightWait:
+ """Poll until the leader releases the lock, the lock expires, or the timeout elapses. The
+ default timeout outlasts the longest a leader can hold the lock."""
+ if timeout_seconds is None:
+ timeout_seconds = FLIGHT_MAX_LEADER_SECONDS[self._budget] + FLIGHT_LOCK_TTL
+ start = time.monotonic()
+ deadline = start + timeout_seconds
+ interval = FLIGHT_POLL_INTERVAL
+ while True:
+ result = self._poll()
+ if result is not None:
+ break
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ result = FlightWait(outcome="timeout")
+ break
+ time.sleep(min(interval, remaining))
+ interval = min(interval * 2, FLIGHT_MAX_POLL_INTERVAL)
+ QUERY_SINGLE_FLIGHT_WAIT_SECONDS.observe(time.monotonic() - start)
+ return result
+
+ def _poll(self) -> Optional[FlightWait]:
+ """None while the leader holds the lock, otherwise what it published."""
+ try:
+ client = storage.query_cache_raw_client()
+ reply = client.register_script(_POLL_SCRIPT)(keys=[self.lock_key, self.result_key]) # type: ignore[union-attr]
+ except Exception:
+ self._storage_failed("poll")
+ return FlightWait(outcome="unavailable")
+ if reply[0]:
+ return None
+ return self._read_publication(reply[1])
+
+ def _read_publication(self, value: Any) -> FlightWait:
+ if not value:
+ return FlightWait(outcome="released")
+ try:
+ published = json.loads(value)
+ if "failure" in published:
+ return FlightWait(outcome="failed", failure=_shared_failure_from(published["failure"]))
+ return FlightWait(outcome="done", last_refresh=datetime.fromisoformat(published["last_refresh"]))
+ except Exception:
+ # A publication this version cannot read, such as one a newer deploy wrote.
+ logger.warning("query_single_flight_unreadable_publication", key=self.result_key)
+ QUERY_SINGLE_FLIGHT_COUNTER.labels(action="unreadable_publication").inc()
+ return FlightWait(outcome="unavailable")
+
+ def _storage_failed(self, operation: str) -> None:
+ # A warning without a traceback: a Redis outage would otherwise log one per blocking query.
+ logger.warning("query_single_flight_storage_error", operation=operation, key=self.lock_key)
+ QUERY_SINGLE_FLIGHT_COUNTER.labels(action="storage_error").inc()
+
+
+def _shared_failure_from(published: Optional[dict[str, Any]]) -> Optional[SharedFailure]:
+ if published is None:
+ return None
+ # Fields a newer deploy added are dropped, so the failure still rebuilds on this version.
+ known = {field.name for field in fields(SharedFailure)}
+ return SharedFailure(**{name: value for name, value in published.items() if name in known})
+
+
+class _Heartbeat:
+ """Extends the leader's lock every FLIGHT_HEARTBEAT_INTERVAL until stopped, until the lock is no
+ longer the leader's, or until max_seconds have passed. A daemon thread, so a dying process takes
+ it down and the lock expires on its own."""
+
+ def __init__(self, flight: QuerySingleFlight, *, max_seconds: float) -> None:
+ self._flight = flight
+ self._deadline = time.monotonic() + max_seconds
+ self._stop = threading.Event()
+ self._thread = threading.Thread(target=self._run, name="query-single-flight-heartbeat", daemon=True)
+ self._thread.start()
+
+ def _run(self) -> None:
+ while not self._stop.wait(FLIGHT_HEARTBEAT_INTERVAL):
+ if time.monotonic() >= self._deadline:
+ break
+ # Keep beating through a storage error: the lock is still ours until it expires, and
+ # stopping here would hand the flight to a follower while this leader still runs.
+ if self._flight.extend() is False:
+ break
+
+ def stop(self) -> None:
+ # No join: an extend still in flight checks ownership, so it cannot outlive the release.
+ self._stop.set()
+
+
+def _millis(seconds: float) -> int:
+ return int(seconds * 1000)
diff --git a/posthog/query_cache/test/test_single_flight.py b/posthog/query_cache/test/test_single_flight.py
new file mode 100644
index 000000000000..dfa0912210de
--- /dev/null
+++ b/posthog/query_cache/test/test_single_flight.py
@@ -0,0 +1,188 @@
+import json
+import uuid
+from datetime import UTC, datetime
+
+from unittest import mock
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.query_cache import single_flight, storage
+from posthog.query_cache.failures import BUDGET_EXTENDED, BUDGET_INTERACTIVE
+from posthog.query_cache.single_flight import FlightWait, QuerySingleFlight, SharedFailure
+
+
+def _cache_key() -> str:
+ return f"test_{uuid.uuid4().hex}"
+
+
+class TestQuerySingleFlight(SimpleTestCase):
+ def test_only_one_leader_until_release(self):
+ key = _cache_key()
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ assert leader.acquire() is True
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).acquire() is False
+ assert QuerySingleFlight(_cache_key(), BUDGET_INTERACTIVE).acquire() is True
+
+ leader.release()
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).acquire() is True
+
+ @parameterized.expand(
+ [
+ ("budget", (BUDGET_INTERACTIVE, ""), (BUDGET_EXTENDED, "")),
+ ("variant", (BUDGET_INTERACTIVE, "DEFAULT"), (BUDGET_INTERACTIVE, "OFFLINE")),
+ ]
+ )
+ def test_runs_in_different_partitions_lead_their_own_flights(self, _name, first, second):
+ key = _cache_key()
+ first_leader = QuerySingleFlight(key, *first)
+ second_leader = QuerySingleFlight(key, *second)
+ self.addCleanup(first_leader.release)
+ self.addCleanup(second_leader.release)
+ assert first_leader.acquire() is True
+ assert second_leader.acquire() is True
+
+ def test_release_keeps_a_replacement_leaders_lock(self):
+ key = _cache_key()
+ expired_leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ assert expired_leader.acquire() is True
+ storage.query_cache_raw_client().delete(expired_leader.lock_key) # the TTL ran out mid-query
+ replacement_leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ self.addCleanup(replacement_leader.release)
+ assert replacement_leader.acquire() is True
+
+ expired_leader.succeed(datetime(2026, 1, 1, tzinfo=UTC))
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).acquire() is False # the replacement still holds it
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=0) == FlightWait(
+ outcome="timeout"
+ ) # and published nothing
+
+ def test_heartbeat_extends_only_the_leaders_own_lock(self):
+ key = _cache_key()
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ self.addCleanup(leader.release)
+ leader.acquire()
+ client = storage.query_cache_raw_client()
+ client.pexpire(leader.lock_key, 1) # about to expire, as if the leader had gone quiet
+ assert leader.extend() is True
+ assert client.pttl(leader.lock_key) > 1000
+
+ client.delete(leader.lock_key)
+ replacement = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ self.addCleanup(replacement.release)
+ replacement.acquire()
+ client.pexpire(replacement.lock_key, 500)
+ assert leader.extend() is False # not the owner any more
+ assert client.pttl(replacement.lock_key) <= 500
+
+ def test_a_dead_leaders_lock_expires_and_followers_get_released(self):
+ key = _cache_key()
+ with mock.patch.object(single_flight, "FLIGHT_LOCK_TTL", 0.05):
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ leader.acquire()
+ assert leader._heartbeat is not None
+ leader._heartbeat.stop() # the process died: no more heartbeats, no release
+ with mock.patch.object(single_flight, "FLIGHT_POLL_INTERVAL", 0.01):
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=1) == FlightWait(outcome="released")
+
+ def test_a_leader_past_its_maximum_hold_loses_the_lock(self):
+ key = _cache_key()
+ with mock.patch.multiple(
+ single_flight,
+ FLIGHT_HEARTBEAT_INTERVAL=0.01,
+ FLIGHT_LOCK_TTL=0.05,
+ FLIGHT_MAX_LEADER_SECONDS={BUDGET_INTERACTIVE: 0.1, BUDGET_EXTENDED: 0.1},
+ FLIGHT_POLL_INTERVAL=0.01,
+ FLIGHT_MAX_POLL_INTERVAL=0.01,
+ ):
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ self.addCleanup(leader.release)
+ leader.acquire() # still running, and its heartbeat never stopped
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=2) == FlightWait(outcome="released")
+
+ def test_acquire_drops_the_previous_flights_published_result(self):
+ key = _cache_key()
+ first_leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ first_leader.acquire()
+ first_leader.succeed(datetime(2026, 1, 1, tzinfo=UTC))
+
+ second_leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ assert second_leader.acquire() is True
+ second_leader.release()
+
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=1) == FlightWait(outcome="released")
+
+ def test_succeeded_tells_followers_which_entry_to_serve(self):
+ key = _cache_key()
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ leader.acquire()
+ written_at = datetime(2026, 1, 1, 12, 0, 0, 123456, tzinfo=UTC)
+ leader.succeed(written_at)
+
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=1) == FlightWait(
+ outcome="done", last_refresh=written_at
+ )
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).acquire() is True # the result does not hold the lock
+
+ def test_released_without_a_publication_reads_as_released(self):
+ key = _cache_key()
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ leader.acquire()
+ leader.release()
+
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=1) == FlightWait(outcome="released")
+
+ def test_failed_with_a_shareable_failure_tells_followers_to_fail_the_same_way(self):
+ key = _cache_key()
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ leader.acquire()
+ failure = SharedFailure(message="Memory limit (for query) exceeded", code=241)
+ leader.fail(failure)
+
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=1) == FlightWait(
+ outcome="failed", failure=failure
+ )
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).acquire() is True # the failure does not hold the lock
+
+ def test_failed_without_a_shareable_failure_tells_followers_the_leader_failed(self):
+ key = _cache_key()
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ leader.acquire()
+ leader.fail(None)
+
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=1) == FlightWait(outcome="failed")
+
+ def test_wait_times_out_while_leader_holds_the_lock(self):
+ key = _cache_key()
+ leader = QuerySingleFlight(key, BUDGET_INTERACTIVE)
+ leader.acquire()
+ with mock.patch.object(single_flight, "FLIGHT_POLL_INTERVAL", 0.01):
+ assert QuerySingleFlight(key, BUDGET_INTERACTIVE).wait(timeout_seconds=0.05) == FlightWait(
+ outcome="timeout"
+ )
+ leader.release()
+
+ @parameterized.expand(
+ [
+ ("unreadable", "not a timestamp", FlightWait(outcome="unavailable")),
+ (
+ "failure_with_a_field_from_a_newer_deploy",
+ json.dumps({"failure": {"message": "Query memory limit exceeded", "code": 241, "added_later": True}}),
+ FlightWait(outcome="failed", failure=SharedFailure(message="Query memory limit exceeded", code=241)),
+ ),
+ ]
+ )
+ def test_a_follower_reads_what_it_can_of_a_publication(self, _name, publication, expected):
+ flight = QuerySingleFlight(_cache_key(), BUDGET_INTERACTIVE)
+ storage.query_cache_raw_client().set(flight.result_key, publication)
+
+ assert flight.wait(timeout_seconds=1) == expected
+
+ def test_storage_errors_fail_open(self):
+ flight = QuerySingleFlight(_cache_key(), BUDGET_INTERACTIVE)
+ with mock.patch.object(single_flight.storage, "query_cache_raw_client", side_effect=RuntimeError("redis down")):
+ assert flight.acquire() is True # act alone rather than block the query
+ assert flight.extend() is None # ownership unknown, so the heartbeat keeps trying
+ assert flight.wait(timeout_seconds=1) == FlightWait(outcome="unavailable") # run it yourself
+ flight.succeed(datetime(2026, 1, 1, tzinfo=UTC)) # holds no lock, so there is nothing to release
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 03c0be5a4a81..86c73029bb71 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -24,7 +24,7 @@ from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, limit_conc
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, CHQueryErrorUnknownTable
-from posthog.exceptions import ClickHouseAtCapacity
+from posthog.exceptions import ClickHouseAtCapacity, QueryRanConcurrently
from posthog.exceptions_capture import capture_exception
from posthog.metrics import pushed_metrics_registry
from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
@@ -421,6 +421,7 @@ def _process_query_task_failure(
# Important: Only retry for things that might be okay on the next try
ClickHouseAtCapacity,
ConcurrencyLimitExceeded,
+ QueryRanConcurrently,
),
on_failure=_process_query_task_failure,
retry_backoff=1,
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 4a49df3821a4..961975d2ea47 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -242,6 +242,7 @@ class ExperimentQueryRunner(QueryRunner):
self.user_facing = user_facing
self.max_execution_time = max_execution_time if max_execution_time is not None else MAX_EXECUTION_TIME
self.bypass_warehouse_access_control = bypass_warehouse_access_control
+ self._requested_as_of = as_of
# Tags the terminal `experiment metric error` event with where the load came from. Defaults to "ui"
# because the generic /query API path constructs runners without kwargs; internal callers that own
# their own retries/telemetry (recalc, warming, canary, backfills) must pass None or user_facing=False
@@ -1022,6 +1023,16 @@ class ExperimentQueryRunner(QueryRunner):
return None
return last_refresh + timedelta(hours=24)
+ def single_flight_variant(self) -> str:
+ # A recalculation passes its own window end, warehouse access, and execution time. None of
+ # them reach the cache key, so a recalculation must not pair with a results request.
+ as_of = self._requested_as_of.isoformat() if self._requested_as_of else ""
+ return (
+ f"{super().single_flight_variant()}:as_of={as_of}"
+ f":bypass_warehouse_access_control={self.bypass_warehouse_access_control}"
+ f":max_execution_time={self.max_execution_time}"
+ )
+
def get_cache_payload(self) -> dict:
payload = super().get_cache_payload()
payload["experiment_response_version"] = 2
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_query_runner_single_flight.py b/products/experiments/backend/hogql_queries/test/test_experiment_query_runner_single_flight.py
new file mode 100644
index 000000000000..1142e3c44e96
--- /dev/null
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_query_runner_single_flight.py
@@ -0,0 +1,52 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+from posthog.schema import EventsNode, ExperimentMeanMetric, ExperimentMetricMathType, ExperimentQuery
+
+from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestExperimentQueryRunnerSingleFlight(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ feature_flag = FeatureFlag.objects.create(
+ name="Test flag",
+ key="test-flag",
+ team=self.team,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": None}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "control", "rollout_percentage": 50},
+ {"key": "test", "name": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ created_by=self.user,
+ )
+ experiment = Experiment.objects.create(name="test-experiment", team=self.team, feature_flag=feature_flag)
+ self.query = ExperimentQuery(
+ experiment_id=experiment.id,
+ kind="ExperimentQuery",
+ metric=ExperimentMeanMetric(source=EventsNode(event="$pageview", math=ExperimentMetricMathType.TOTAL)),
+ )
+
+ @parameterized.expand(
+ [
+ ("as_of", {"as_of": datetime(2026, 1, 1, tzinfo=UTC)}),
+ ("bypass_warehouse_access_control", {"bypass_warehouse_access_control": True}),
+ ("max_execution_time", {"max_execution_time": 30}),
+ ]
+ )
+ def test_recalculation_does_not_pair_with_a_results_request(self, _name, recalculation_kwargs):
+ results_request = ExperimentQueryRunner(query=self.query, team=self.team)
+ recalculation = ExperimentQueryRunner(query=self.query, team=self.team, **recalculation_kwargs)
+ assert (recalculation.get_cache_key(), recalculation.single_flight_variant()) != (
+ results_request.get_cache_key(),
+ results_request.single_flight_variant(),
+ )
diff --git a/products/logs/backend/count_ranges_query_runner.py b/products/logs/backend/count_ranges_query_runner.py
index 3223810ed2b7..1985a7482ebf 100644
--- a/products/logs/backend/count_ranges_query_runner.py
+++ b/products/logs/backend/count_ranges_query_runner.py
@@ -42,6 +42,10 @@ class CountRangesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
self.BUCKET_TARGET = max(1, min(target_buckets, MAX_TARGET_BUCKETS))
super().__init__(*args, **kwargs)
+ def get_cache_payload(self) -> dict:
+ # A runner argument, not a query field, so the base payload cannot see it.
+ return {**super().get_cache_payload(), "target_buckets": self.BUCKET_TARGET}
+
@cached_property
def settings(self) -> HogQLGlobalSettings:
return fail_fast_aggregate_settings(max_bytes_to_read=1_000_000_000)
diff --git a/products/logs/backend/log_facet_values_query_runner.py b/products/logs/backend/log_facet_values_query_runner.py
index 7908723b56db..2cb007deceb7 100644
--- a/products/logs/backend/log_facet_values_query_runner.py
+++ b/products/logs/backend/log_facet_values_query_runner.py
@@ -94,6 +94,16 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQue
# query.searchTerm which searches log bodies. Lets a dynamic facet search past the LIMIT window.
self.facet_search = (facet_search or "").strip() or None
+ def get_cache_payload(self) -> dict:
+ # Runner arguments, not query fields, so the base payload cannot see them.
+ attribute = self.attribute_facet
+ return {
+ **super().get_cache_payload(),
+ "facet_field": self.facet_field,
+ "facet_attribute": None if attribute is None else [attribute.attribute_type, attribute.key],
+ "facet_search": self.facet_search,
+ }
+
@cached_property
def settings(self) -> HogQLGlobalSettings:
if self.attribute_facet is not None:
diff --git a/products/logs/backend/patterns_query_runner.py b/products/logs/backend/patterns_query_runner.py
index 058915ca1584..a5634102d804 100644
--- a/products/logs/backend/patterns_query_runner.py
+++ b/products/logs/backend/patterns_query_runner.py
@@ -68,6 +68,14 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
use_stored_patterns: bool = True
_query_deadline: float | None = None
+ def get_cache_payload(self) -> dict:
+ payload = super().get_cache_payload()
+ # Set after construction, so the base payload cannot see it. Keyed only when off, so
+ # stored-pattern runs keep their cache entries.
+ if not self.use_stored_patterns:
+ payload["use_stored_patterns"] = False
+ return payload
+
@cached_property
def settings(self) -> HogQLGlobalSettings:
# Bytes are intentionally uncapped: a hard `max_bytes_to_read` + "throw" cap 500s on
diff --git a/products/logs/backend/services_query_runner.py b/products/logs/backend/services_query_runner.py
index 9acfc633b701..c2352b88e535 100644
--- a/products/logs/backend/services_query_runner.py
+++ b/products/logs/backend/services_query_runner.py
@@ -185,11 +185,12 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
def __init__(self, *args: Any, service_name_search: str | None = None, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
- # Not part of the query object, so it never reaches the cache key. Safe
- # only while the services endpoint runs CALCULATE_BLOCKING_ALWAYS; a move
- # to any cached execution mode requires this on LogsQuery instead.
self.service_name_search = service_name_search.strip() if service_name_search else None
+ def get_cache_payload(self) -> dict[str, Any]:
+ # A runner argument, not a query field, so the base payload cannot see it.
+ return {**super().get_cache_payload(), "service_name_search": self.service_name_search}
+
def _calculate(self) -> LogsQueryResponse:
aggregates_response = execute_hogql_query(
query_type="LogsQuery",
diff --git a/products/logs/backend/test/test_query_runner_cache_keys.py b/products/logs/backend/test/test_query_runner_cache_keys.py
new file mode 100644
index 000000000000..50cb8ae60f7d
--- /dev/null
+++ b/products/logs/backend/test/test_query_runner_cache_keys.py
@@ -0,0 +1,56 @@
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.schema import DateRange, FilterLogicalOperator, LogsQuery, PropertyGroupFilter
+
+from products.logs.backend.count_ranges_query_runner import CountRangesQueryRunner
+from products.logs.backend.log_facet_values_query_runner import LogFacetValuesQueryRunner
+from products.logs.backend.patterns_query_runner import PatternsQueryRunner
+from products.logs.backend.services_query_runner import ServicesQueryRunner
+
+
+def _logs_query() -> LogsQuery:
+ return LogsQuery(
+ dateRange=DateRange(date_from="-1h"),
+ serviceNames=[],
+ severityLevels=[],
+ filterGroup=PropertyGroupFilter(type=FilterLogicalOperator.AND_, values=[]),
+ )
+
+
+class TestRunnerArgumentsReachTheCacheKey(BaseTest):
+ @parameterized.expand(
+ [
+ ("services_search", ServicesQueryRunner, {"service_name_search": "api"}, {"service_name_search": "web"}),
+ (
+ "facet_field",
+ LogFacetValuesQueryRunner,
+ {"facet_field": "service_name"},
+ {"facet_field": "severity_text"},
+ ),
+ (
+ "facet_attribute_type",
+ LogFacetValuesQueryRunner,
+ {"facet_resource_attribute": "k8s.pod.name"},
+ {"facet_attribute": "k8s.pod.name"},
+ ),
+ (
+ "facet_search",
+ LogFacetValuesQueryRunner,
+ {"facet_field": "service_name", "facet_search": "kafka"},
+ {"facet_field": "service_name"},
+ ),
+ ("count_ranges_buckets", CountRangesQueryRunner, {"target_buckets": 10}, {"target_buckets": 20}),
+ ]
+ )
+ def test_different_runner_arguments_give_different_cache_keys(self, _name, runner_class, first, second):
+ first_key = runner_class(query=_logs_query(), team=self.team, **first).get_cache_key()
+ second_key = runner_class(query=_logs_query(), team=self.team, **second).get_cache_key()
+ assert first_key != second_key
+
+ def test_live_mined_patterns_do_not_share_a_cache_key_with_stored_patterns(self):
+ stored = PatternsQueryRunner(query=_logs_query(), team=self.team)
+ live = PatternsQueryRunner(query=_logs_query(), team=self.team)
+ live.use_stored_patterns = False
+ assert live.get_cache_key() != stored.get_cache_key()
diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
index 293b085aa0fd..26b73e716b4b 100644
--- a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
@@ -164,6 +164,12 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
self.update_hogql_modifiers()
self.series = self.setup_series()
+ def single_flight_variant(self) -> str:
+ # A caller can pass its own execution time, which does not reach the cache key.
+ if self.hogql_settings is None:
+ return super().single_flight_variant()
+ return f"{super().single_flight_variant()}:max_execution_time={self.hogql_settings.max_execution_time}"
+
def validators(self) -> Sequence[QueryValidationRule[TrendsQuery]]:
return (
RequireAtLeastOneSeries(),
diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.py
index ece0b2f7456d..933892e6886c 100644
--- a/products/tracing/backend/aggregation_query_runner.py
+++ b/products/tracing/backend/aggregation_query_runner.py
@@ -250,6 +250,10 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn
self._limit = _ROW_LIMIT if limit is None else max(1, min(limit, _ROW_LIMIT))
self._offset = max(0, offset)
+ def get_cache_payload(self) -> dict:
+ # Runner arguments, not query fields, so the base payload cannot see them.
+ return {**super().get_cache_payload(), "limit": self._limit, "offset": self._offset}
+
def _calculate(self) -> TraceSpansAggregationQueryResponse:
current_rows, previous_rows = self._run_with_compare()
return TraceSpansAggregationQueryResponse(results=current_rows, compare=previous_rows)
diff --git a/products/tracing/backend/tests/test_aggregation_query_runner.py b/products/tracing/backend/tests/test_aggregation_query_runner.py
index 908d158a52d4..a019adef0334 100644
--- a/products/tracing/backend/tests/test_aggregation_query_runner.py
+++ b/products/tracing/backend/tests/test_aggregation_query_runner.py
@@ -1,11 +1,14 @@
import datetime as dt
+from posthog.test.base import BaseTest
+
from parameterized import parameterized
-from posthog.schema import DateRange
+from posthog.schema import DateRange, TraceSpansAggregationQuery
from posthog.clickhouse.client import sync_execute
+from products.tracing.backend.aggregation_query_runner import TraceSpansAggregationQueryRunner
from products.tracing.backend.logic import run_aggregation_query, run_tree_query
from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase
@@ -17,6 +20,15 @@ EXPECTED_OFFSET_NANO = CHILD_OFFSET_MS * 1_000_000
MS_TO_NANO = 1_000_000
+class TestPaginationReachesTheCacheKey(BaseTest):
+ @parameterized.expand([("limit", {"limit": 10}, {"limit": 20}), ("offset", {"offset": 0}, {"offset": 10})])
+ def test_different_pages_give_different_cache_keys(self, _name, first, second):
+ query = TraceSpansAggregationQuery(dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO))
+ first_key = TraceSpansAggregationQueryRunner(query, self.team, **first).get_cache_key()
+ second_key = TraceSpansAggregationQueryRunner(query, self.team, **second).get_cache_key()
+ assert first_key != second_key
+
+
class TestTraceSpansTreeStartOffset(_TraceSpansTestBase):
@classmethod
def setUpTestData(cls):