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): identity, phases and failures on the query executed event (#103151)

Sandy Spicer7b13402a6350
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index 4f48b6443838..41a535d7c158 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -266,7 +266,7 @@ def _query_stats_summary(client: Any, query_info_before: Any) -> Optional[QueryS
)
-def _record_query_stats(client: Any, query_info_before: Any, execute_start_time: float) -> None:
+def _record_query_stats(client: Any, query_info_before: Any, execute_start_time: float, workload: Workload) -> None:
"""Add what this query read to the request's totals.
Also runs after a failure, since a stopped query has still read rows. Never raises: the totals
@@ -278,7 +278,12 @@ def _record_query_stats(client: Any, query_info_before: Any, execute_start_time:
return
# elapsed_ns is 0 on old protocol revisions; fall back to the client-side round trip.
duration_ms = summary.elapsed_ns / 1e6 if summary.elapsed_ns else (perf_counter() - execute_start_time) * 1000
- query_stats.record(rows_read=summary.rows, duration_ms=duration_ms, lookup=get_query_tags().lookup is not None)
+ query_stats.record(
+ rows_read=summary.rows,
+ duration_ms=duration_ms,
+ lookup=get_query_tags().lookup is not None,
+ workload=workload.value,
+ )
except Exception:
logger.warning("query_stats_record_failed", exc_info=True)
@@ -606,7 +611,7 @@ def sync_execute(
# in the outer finally, once the connection is back in the pool.
if tags.api_queries_budgeted and tags.team_id:
budgeted_query_info = _query_info_to_meter(client, query_info_before)
- _record_query_stats(client, query_info_before, execute_start_time)
+ _record_query_stats(client, query_info_before, execute_start_time, workload)
if (
"INSERT INTO" in prepared_sql
and hasattr(client, "last_query")
diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.py
index 8f74447694ba..cbac05a7de34 100644
--- a/posthog/clickhouse/client/execute_async.py
+++ b/posthog/clickhouse/client/execute_async.py
@@ -280,6 +280,7 @@ def execute_process_query(
query_json=query_json,
limit_context=limit_context,
execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ query_id=query_id,
insight_id=query_status.insight_id,
dashboard_id=query_status.dashboard_id,
user=user,
diff --git a/posthog/clickhouse/client/test/test_execute.py b/posthog/clickhouse/client/test/test_execute.py
index 16189c5a0c4a..b840e83b7d67 100644
--- a/posthog/clickhouse/client/test/test_execute.py
+++ b/posthog/clickhouse/client/test/test_execute.py
@@ -7,7 +7,13 @@ from unittest.mock import MagicMock, patch
from posthog.hogql.query_stats import query_stats_scope
-from posthog.clickhouse.client.connection import ClickHouseClient, ClickHouseUser, ProxyClient, Workload
+from posthog.clickhouse.client.connection import (
+ ClickHouseClient,
+ ClickHouseUser,
+ ProxyClient,
+ Workload,
+ get_default_clickhouse_workload_type,
+)
from posthog.clickhouse.client.execute import query_with_columns, sync_execute
from posthog.clickhouse.client.limit import ConcurrencySlot, RateLimit, get_llm_analytics_rate_limiter
from posthog.clickhouse.query_tagging import AccessMethod, Product, tags_context
@@ -142,22 +148,39 @@ def _proxy_client() -> ProxyClient:
@pytest.mark.parametrize(
- "make_client,raises,expected",
+ "make_client,raises,tags,expected,expected_workload",
[
- (_FakeNativeClient, False, (7, 3.0)),
- (lambda: _FakeNativeClient(fails="kill"), True, (7, 3.0)),
+ (_FakeNativeClient, False, {}, (7, 3.0), "default"),
+ (_FakeNativeClient, False, {"kind": "celery"}, (7, 3.0), "OFFLINE"),
+ (
+ _FakeNativeClient,
+ False,
+ {"kind": "celery", "id": "posthog.tasks.tasks.process_query_task"},
+ (7, 3.0),
+ "ONLINE",
+ ),
+ (lambda: _FakeNativeClient(fails="kill"), True, {}, (7, 3.0), "default"),
# Counting the previous query's progress would charge this query with another query's rows.
(
lambda: _FakeNativeClient(fails="connect", last_query=_fake_query_info(rows=99, elapsed_ns=1)),
True,
+ {},
(0, 0.0),
+ None,
),
- (_proxy_client, False, (7, 3.0)),
+ (_proxy_client, False, {}, (7, 3.0), "default"),
+ ],
+ ids=[
+ "ok",
+ "celery_resolves_to_offline",
+ "app_query_task_resolves_to_online",
+ "killed_by_the_server",
+ "connect_failed",
+ "http_client",
],
- ids=["ok", "killed_by_the_server", "connect_failed", "http_client"],
)
-def test_sync_execute_records_what_clickhouse_read(make_client, raises, expected):
- with patch("posthog.clickhouse.client.execute.get_client_from_pool") as pool:
+def test_sync_execute_records_what_clickhouse_read(make_client, raises, tags, expected, expected_workload):
+ with patch("posthog.clickhouse.client.execute.get_client_from_pool") as pool, tags_context(**tags):
pool.return_value.__enter__.return_value = make_client()
with query_stats_scope() as stats:
if raises:
@@ -167,6 +190,9 @@ def test_sync_execute_records_what_clickhouse_read(make_client, raises, expected
sync_execute("SELECT 1", flush=False)
assert (stats.rows_read, stats.duration_ms) == expected
+ if expected_workload == "default":
+ expected_workload = get_default_clickhouse_workload_type().value
+ assert stats.workload() == expected_workload
@pytest.mark.parametrize(
diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.py
index ff0107e8cbde..733f7bb245fe 100644
--- a/posthog/clickhouse/client/test/test_execute_async.py
+++ b/posthog/clickhouse/client/test/test_execute_async.py
@@ -211,6 +211,7 @@ class TestExecuteProcessQuery(TestCase):
mock_redis_client.assert_called_once()
mock_process_query_dict.assert_called_once()
+ self.assertEqual(mock_process_query_dict.call_args.kwargs["query_id"], self.query_id)
self.assertEqual(get_query_tags().celery_task_id, task_id)
# Assert that Redis set method was called with the correct arguments
diff --git a/posthog/hogql/query_stats.py b/posthog/hogql/query_stats.py
index 9ba9731b8ba1..e743f7e97d7e 100644
--- a/posthog/hogql/query_stats.py
+++ b/posthog/hogql/query_stats.py
@@ -54,12 +54,15 @@ class QueryStats:
# scope without being the query the person wrote, so a reader can judge the run without them.
lookup_rows_read: int = 0
lookup_duration_ms: float = 0.0
+ # Only a scan-flagged run keeps the AST and context, which hold memory for the length of the run.
+ retain_ast: bool = False
# Runners that record from several threads share one QueryStats.
lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False)
# References only, filled by the executor, so the job can explain each execution without rerunning it.
executions: list[RecordedExecution] = field(default_factory=list, repr=False, compare=False)
+ workloads: set[str] = field(default_factory=set, repr=False, compare=False)
- def add(self, *, rows_read: int, duration_ms: float, lookup: bool = False) -> None:
+ def add(self, *, rows_read: int, duration_ms: float, lookup: bool = False, workload: str | None = None) -> None:
with self.lock:
self.rows_read += rows_read
self.duration_ms += duration_ms
@@ -67,6 +70,8 @@ class QueryStats:
if lookup:
self.lookup_rows_read += rows_read
self.lookup_duration_ms += duration_ms
+ if workload is not None:
+ self.workloads.add(workload)
def record_execution(
self,
@@ -77,11 +82,24 @@ class QueryStats:
lookup: str | None = None,
settings: HogQLGlobalSettings | None = None,
) -> None:
+ if not self.retain_ast:
+ return
with self.lock:
self.executions.append(
RecordedExecution(tree=tree, context=context, rows_read=rows_read, lookup=lookup, settings=settings)
)
+ def workload(self) -> str | None:
+ """The one cluster the request ran on, "mixed" when its queries went to more than one, or None
+ when none reached ClickHouse."""
+ with self.lock:
+ workloads = set(self.workloads)
+ if not workloads:
+ return None
+ if len(workloads) > 1:
+ return "mixed"
+ return workloads.pop()
+
_accumulator: ContextVar[QueryStats | None] = ContextVar("query_stats_accumulator", default=None)
@@ -93,13 +111,16 @@ _last_rows_read: ContextVar[int] = ContextVar("query_stats_last_rows_read", defa
@contextlib.contextmanager
-def query_stats_scope() -> Iterator[QueryStats]:
- """Add up every ClickHouse query run inside this block. Nested in another scope, it adds to that one."""
+def query_stats_scope(*, retain_ast: bool = False) -> Iterator[QueryStats]:
+ """Add up every ClickHouse query run inside this block. Nested in another scope, it adds to that
+ one, and a retaining scope turns retention on for the shared totals from then on."""
outer = _accumulator.get()
if outer is not None:
+ if retain_ast:
+ outer.retain_ast = True
yield outer
return
- stats = QueryStats()
+ stats = QueryStats(retain_ast=retain_ast)
token = _accumulator.set(stats)
try:
yield stats
@@ -126,13 +147,13 @@ def use(stats: QueryStats | None) -> Iterator[None]:
_accumulator.reset(token)
-def record(*, rows_read: int, duration_ms: float, lookup: bool = False) -> None:
+def record(*, rows_read: int, duration_ms: float, lookup: bool = False, workload: str | None = None) -> None:
"""Add one ClickHouse query to the open scope. Does nothing without one."""
_last_rows_read.set(rows_read)
stats = _accumulator.get()
if stats is None:
return
- stats.add(rows_read=rows_read, duration_ms=duration_ms, lookup=lookup)
+ stats.add(rows_read=rows_read, duration_ms=duration_ms, lookup=lookup, workload=workload)
def reset_last_rows_read() -> None:
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index d5272e1480eb..fcc18957ab47 100644
--- a/posthog/hogql/test/test_query.py
+++ b/posthog/hogql/test/test_query.py
@@ -2413,7 +2413,7 @@ class TestQueryStatsRecording(BaseTest):
record(rows_read=42, duration_ms=1.0)
return ([[0]], [("count()", "UInt64")])
- with query_stats_scope() as stats:
+ with query_stats_scope(retain_ast=True) as stats:
with mock.patch("posthog.hogql.query.sync_execute", side_effect=ok):
execute_hogql_query("select count() from events", team=self.team, query_type="test")
assert len(stats.executions) == 1
@@ -2426,7 +2426,7 @@ class TestQueryStatsRecording(BaseTest):
record(rows_read=90, duration_ms=1.0)
raise ClickHouseQueryMemoryLimitExceeded()
- with query_stats_scope() as killed_stats:
+ with query_stats_scope(retain_ast=True) as killed_stats:
with self.assertRaises(ClickHouseQueryMemoryLimitExceeded):
with mock.patch("posthog.hogql.query.sync_execute", side_effect=killed):
execute_hogql_query("select count() from events", team=self.team, query_type="test")
diff --git a/posthog/hogql/test/test_query_stats.py b/posthog/hogql/test/test_query_stats.py
index 841c2942f71b..57f8fac356d9 100644
--- a/posthog/hogql/test/test_query_stats.py
+++ b/posthog/hogql/test/test_query_stats.py
@@ -1,5 +1,9 @@
import threading
+import pytest
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
from posthog.hogql.query_stats import get_active, last_rows_read, query_stats_scope, record, reset_last_rows_read, use
@@ -61,3 +65,37 @@ def test_a_lookup_counts_in_the_totals_and_is_kept_apart():
assert (stats.rows_read, stats.duration_ms) == (1003, 52.0)
assert (stats.lookup_rows_read, stats.lookup_duration_ms) == (1000, 50.0)
+
+
+ "workloads,expected",
+ [
+ ([], None),
+ (["ONLINE"], "ONLINE"),
+ (["OFFLINE", "OFFLINE"], "OFFLINE"),
+ (["ONLINE", "OFFLINE"], "mixed"),
+ ],
+)
+def test_the_workload_is_the_one_cluster_the_queries_ran_on_or_mixed(workloads, expected):
+ with query_stats_scope() as stats:
+ for workload in workloads:
+ record(rows_read=1, duration_ms=1.0, workload=workload)
+
+ assert stats.workload() == expected
+
+
+def test_record_execution_keeps_the_ast_only_when_retaining():
+ tree = ast.Constant(value=1)
+
+ with query_stats_scope() as not_retaining:
+ not_retaining.record_execution(tree=tree, context=HogQLContext(), rows_read=7)
+ assert not_retaining.executions == []
+
+ with query_stats_scope(retain_ast=True) as retaining:
+ retaining.record_execution(tree=tree, context=HogQLContext(), rows_read=7)
+ assert len(retaining.executions) == 1
+
+ with query_stats_scope() as outer:
+ with query_stats_scope(retain_ast=True) as nested:
+ nested.record_execution(tree=tree, context=HogQLContext(), rows_read=7)
+ assert len(outer.executions) == 1
diff --git a/posthog/hogql_queries/phase_times.py b/posthog/hogql_queries/phase_times.py
new file mode 100644
index 000000000000..c6de556b4494
--- /dev/null
+++ b/posthog/hogql_queries/phase_times.py
@@ -0,0 +1,31 @@
+RATE_LIMITERS_KEY = "./rate_limiters"
+CACHE_WRITE_KEY = "./cache_write"
+FLIGHT_WAIT_KEY = "./flight_wait"
+
+
+def _node_ms(runner_timings: dict[str, float], before: dict[str, float], key: str) -> float | None:
+ seconds = runner_timings.get(key)
+ if seconds is None or seconds == before.get(key):
+ return None
+ return round((seconds - before.get(key, 0.0)) * 1000, 2)
+
+
+def compute_phase_times(
+ runner_timings: dict[str, float], before: dict[str, float] | None = None
+) -> dict[str, float | None]:
+ """The phases a run spends outside the calculation, read off the runner's ``HogQLTimings`` tree
+ (``self.timings.to_dict()``, seconds per node) for the ``query executed`` event.
+
+ ``rate_limiters_ms`` is the wait to acquire the concurrency limiters, ``cache_write_ms`` the time
+ to store the result, ``flight_wait_ms`` a single-flight follower's wait for the leader. Each is
+ ``None`` when the run did not pass through that phase. Milliseconds, two decimals. ``before`` is
+ the same tree as it stood when the run started: the tree adds up across runs of one runner, so
+ the difference is this run's own time. ClickHouse time is not derived here: the stats scope
+ already puts it on the event as ``clickhouse_duration_ms``.
+ """
+ before = before or {}
+ return {
+ "rate_limiters_ms": _node_ms(runner_timings, before, RATE_LIMITERS_KEY),
+ "cache_write_ms": _node_ms(runner_timings, before, CACHE_WRITE_KEY),
+ "flight_wait_ms": _node_ms(runner_timings, before, FLIGHT_WAIT_KEY),
+ }
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index b6df12bc6485..cfda9995690b 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -1,14 +1,28 @@
+import hashlib
import inspect
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable, Sequence
-from contextlib import AbstractContextManager, nullcontext
+from contextlib import ExitStack, suppress
from datetime import UTC, datetime, timedelta
from enum import StrEnum
from functools import cache, cached_property
from time import perf_counter
from types import UnionType
-from typing import Any, Generic, NamedTuple, Optional, Protocol, TypeGuard, TypeVar, Union, cast, get_args, get_origin
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ NamedTuple,
+ Optional,
+ Protocol,
+ TypeGuard,
+ TypeVar,
+ Union,
+ cast,
+ get_args,
+ get_origin,
+)
from django.db import OperationalError
@@ -110,7 +124,11 @@ from posthog.hogql.database.database import Database
from posthog.hogql.modifiers import create_default_modifiers_for_user
from posthog.hogql.printer import prepare_and_print_ast, to_printed_hogql
from posthog.hogql.query import create_default_modifiers_for_team
-from posthog.hogql.query_stats import QueryStats, query_stats_scope
+from posthog.hogql.query_stats import (
+ QueryStats,
+ get_active as get_active_query_stats,
+ query_stats_scope,
+)
from posthog.hogql.timings import HogQLTimings
from posthog.hogql.warehouse_warnings import accumulator_scope
@@ -141,7 +159,9 @@ from posthog.errors import QueryErrorCategory, classify_query_error, clickhouse_
from posthog.event_usage import AnalyticsProps, groups, report_team_action, report_user_or_team_action
from posthog.exceptions import APIQueriesBudgetExceeded, QueryRanConcurrently
from posthog.exceptions_capture import capture_exception
+from posthog.git import get_git_commit_short
from posthog.hogql_queries.access_controlled_resources import queried_access_controlled_resources
+from posthog.hogql_queries.phase_times import compute_phase_times
from posthog.hogql_queries.query_failure_handling import (
budget_for_limit_context,
build_failure_exception,
@@ -257,6 +277,27 @@ def _contains_user_hogql_label() -> str:
EXTENDED_CACHE_AGE = timedelta(days=1)
+QUERY_HASH_VERSION = 1
+
+
+@frozen
+class QueryIdentity:
+ """The two halves of the cache payload, hashed apart: the question a run answered and how it
+ answered it. The cache key is unchanged; these only ride on the analytics event."""
+
+ query_hash: str
+ runtime_hash: str
+
+
+@frozen
+class RunPhase:
+ """Where a run is, for the failure event a raise sends: the phase the raise lands in, the
+ ClickHouse totals recorded so far, and the calculation time once there is one."""
+
+ name: Literal["prepare", "flight_wait", "rate_limiters", "calculate", "finish"]
+ stats: Optional[QueryStats] = None
+ query_duration_ms: Optional[float] = None
+
class ExecutionMode(StrEnum):
CALCULATE_BLOCKING_ALWAYS = "force_blocking"
@@ -275,6 +316,41 @@ class ExecutionMode(StrEnum):
"""Do not initiate calculation."""
+@frozen
+class QueryRun:
+ """One call of `run`: the identity and ids every event about the run carries, and the caller
+ state the reporting helpers share. Built once, so the events for a run cannot disagree."""
+
+ cache_key: str
+ query_identity: QueryIdentity
+ query_id: Optional[str]
+ execution_mode: ExecutionMode
+ query_type: str
+ insight_id: Optional[int]
+ dashboard_id: Optional[int]
+ trigger: Optional[str]
+ user: Optional[User]
+ start_time: float
+ analytics_props: Optional[AnalyticsProps]
+
+ def elapsed_ms(self) -> float:
+ return round((perf_counter() - self.start_time) * 1000, 2)
+
+ def event_properties(self) -> dict[str, Any]:
+ return {
+ "query_hash": self.query_identity.query_hash,
+ "runtime_hash": self.query_identity.runtime_hash,
+ "hash_version": QUERY_HASH_VERSION,
+ "query_id": self.query_id,
+ "commit": get_git_commit_short(),
+ "insight_id": self.insight_id,
+ "dashboard_id": self.dashboard_id,
+ "execution_mode": self.execution_mode.value,
+ "query_type": self.query_type,
+ "cache_key": self.cache_key,
+ }
+
+
BLOCKING_EXECUTION_MODES: set[ExecutionMode] = {
ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
@@ -2164,33 +2240,44 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
if get_query_tag_value("api_queries_budgeted"):
self._enforce_api_queries_budget()
- with (
- get_materialized_endpoints_rate_limiter().run(
- team_id=self.team.pk,
- task_id=self.query_id,
- is_materialized_endpoint=is_materialized_endpoint,
- ),
- get_api_team_rate_limiter().run(
- is_api=self.is_query_service and not is_materialized_endpoint,
- team_id=self.team.pk,
- task_id=self.query_id,
- limit=concurrency_limit,
- ),
- get_app_org_rate_limiter().run(
- org_id=self.team.organization_id,
- task_id=self.query_id,
- team_id=self.team.id,
- is_api=is_api_key_access,
- limit=get_org_app_concurrency_limit(self.team.organization_id),
- ),
- get_app_dashboard_queries_rate_limiter().run(
- org_id=self.team.organization_id,
- dashboard_id=dashboard_id,
- task_id=self.query_id,
- team_id=self.team.id,
- is_api=is_api_key_access,
- ),
- ):
+ with ExitStack() as limiter_stack:
+ # Measure only the wait to acquire the limiters. calculate() runs after this closes, but
+ # still inside the stack so the limiters stay held for the whole calculation.
+ with self.timings.measure("rate_limiters"):
+ limiter_stack.enter_context(
+ get_materialized_endpoints_rate_limiter().run(
+ team_id=self.team.pk,
+ task_id=self.query_id,
+ is_materialized_endpoint=is_materialized_endpoint,
+ )
+ )
+ limiter_stack.enter_context(
+ get_api_team_rate_limiter().run(
+ is_api=self.is_query_service and not is_materialized_endpoint,
+ team_id=self.team.pk,
+ task_id=self.query_id,
+ limit=concurrency_limit,
+ )
+ )
+ limiter_stack.enter_context(
+ get_app_org_rate_limiter().run(
+ org_id=self.team.organization_id,
+ task_id=self.query_id,
+ team_id=self.team.id,
+ is_api=is_api_key_access,
+ limit=get_org_app_concurrency_limit(self.team.organization_id),
+ )
+ )
+ limiter_stack.enter_context(
+ get_app_dashboard_queries_rate_limiter().run(
+ org_id=self.team.organization_id,
+ dashboard_id=dashboard_id,
+ task_id=self.query_id,
+ team_id=self.team.id,
+ is_api=is_api_key_access,
+ )
+ )
+ self._phase = RunPhase(name="calculate", stats=get_active_query_stats())
query_start_time = perf_counter()
query_result = self.calculate()
query_duration_ms = round((perf_counter() - query_start_time) * 1000, 2)
@@ -2216,6 +2303,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
self._on_user_changed()
start_time = perf_counter()
cache_key = self.get_cache_key()
+ self._phase = RunPhase(name="prepare")
+ self._timings_before_run: dict[str, float] = self.timings.to_dict()
# Resolve per-call state before observability so SLO + analytics agree on the values.
self.query_id = query_id or self.query_id
self._cache_age_override = cache_age_seconds
@@ -2284,6 +2373,19 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# data freshness window) served cache instead of recomputing.
slo_properties["cache_age_override"] = cache_age_seconds
+ query_run = QueryRun(
+ cache_key=cache_key,
+ query_identity=self._query_identity,
+ query_id=self.query_id,
+ execution_mode=execution_mode,
+ query_type=query_type,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ trigger=get_query_tag_value("trigger"),
+ user=user,
+ start_time=start_time,
+ analytics_props=analytics_props,
+ )
with slo_operation(
spec=SloSpec(
distinct_id=distinct_id,
@@ -2323,8 +2425,6 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
raise
- trigger: str | None = get_query_tag_value("trigger")
-
cache_manager = QueryCache(
team_id=self.team.pk,
cache_key=cache_key,
@@ -2363,38 +2463,16 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
analytics_props=analytics_props,
)
if results:
- 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,
- start_time=start_time,
- analytics_props=analytics_props,
- )
+ self._report_result_from_cache(results, query_run=query_run)
return results
# cache_hit is left unset on this path: either the caller passed
# CALCULATE_BLOCKING_ALWAYS (cache skipped) or the cache returned nothing.
- slo.tag(execution_path="blocking", calculation_trigger=trigger)
- fresh_response = self._execute_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,
- )
- # A fresh run of a query analyzed earlier still has a done slot, so this is
- # where its findings reach the recomputed response.
- self._serve_query_scan(fresh_response, user)
+ slo.tag(execution_path="blocking", calculation_trigger=query_run.trigger)
+ fresh_response = self._execute_and_cache_blocking(query_run=query_run, cache_manager=cache_manager)
return fresh_response
except Exception as exc:
+ self._report_query_failed(exc, query_run=query_run)
if getattr(exc, "served_from_query_failure_cache", False):
# ClickHouse was never touched; the original failure was already
# classified and captured when it happened.
@@ -2423,22 +2501,10 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
capture_exception(exc)
raise
- def _execute_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,
- ) -> CR:
+ def _execute_and_cache_blocking(self, *, query_run: QueryRun, cache_manager: QueryCache) -> CR:
# The single gate for all blocking execution, forced refreshes included: an open
# breaker that covers this run's execution budget forbids touching ClickHouse.
- self._raise_if_breaker_forbids(cache_manager, user)
+ self._raise_if_breaker_forbids(cache_manager, query_run.user)
flight: Optional[QuerySingleFlight] = None
if self._joins_single_flight():
@@ -2446,37 +2512,17 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
if flight.acquire():
QUERY_SINGLE_FLIGHT_COUNTER.labels(action="leader").inc()
else:
- wait = flight.wait()
+ self._phase = RunPhase(name="flight_wait")
+ with self.timings.measure("flight_wait"):
+ 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,
- )
+ return self._serve_flight_outcome(wait, cache_manager, query_run=query_run)
# 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,
- )
+ return self._calculate_and_cache_blocking(query_run=query_run, cache_manager=cache_manager, 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)
@@ -2519,20 +2565,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
query_scan=getattr(exc, "query_scan", None),
)
- 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:
+ def _serve_flight_outcome(self, wait: FlightWait, cache_manager: QueryCache, *, query_run: QueryRun) -> 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
@@ -2541,26 +2574,15 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
served = self.handle_cache_and_async_logic(
execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,
cache_manager=cache_manager,
- user=user,
- analytics_props=analytics_props,
+ user=query_run.user,
+ analytics_props=query_run.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",
- )
+ self._report_result_from_cache(served, query_run=query_run, execution_path="single_flight_follower")
return served
if wait.outcome == "failed" and wait.failure is not None:
error = rebuild_shared_failure(wait.failure)
@@ -2572,29 +2594,18 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
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",
+ self, results: CR | CacheMissResponse, *, query_run: QueryRun, execution_path: str = "cache_hit"
) -> None:
cache_tracking_props: dict[str, Any] = {}
# The numbers describe the fresh run that filled the cache, not this hit. Read before serving,
# which can take the field off the response.
cached_query_scan = getattr(results, "query_scan", None)
if isinstance(results, self.cached_response_type):
- if (not trigger or not trigger.startswith("warming")) and results.query_metadata:
+ if (not query_run.trigger or not query_run.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,
+ user_id=query_run.user.id if query_run.user else None,
)
last_refresh = last_refresh_from_cached_result(results)
@@ -2607,45 +2618,70 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
"last_refresh": last_refresh.isoformat() if last_refresh else None,
}
tag_current_slo(execution_path=execution_path, cache_hit=True, **cache_tracking_props)
- self._serve_query_scan(results, user)
+ self._serve_query_scan(results, query_run.user)
else:
tag_current_slo(execution_path="cache_miss", cache_hit=False)
+ phase_times = compute_phase_times(self.timings.to_dict(), before=self._timings_before_run)
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,
+ **query_run.event_properties(),
"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),
+ "response_time_ms": query_run.elapsed_ms(),
"clickhouse_rows_read": cached_query_scan.rows_read if cached_query_scan else None,
"clickhouse_duration_ms": cached_query_scan.duration_ms if cached_query_scan else None,
+ "clickhouse_workload": None,
+ "clickhouse_query_count": None,
**cache_tracking_props,
+ **phase_times,
}
report_user_or_team_action(
"query executed",
query_executed_props,
- user=user,
+ user=query_run.user,
team=self.team,
organization=self.team.organization,
- analytics_props=analytics_props,
+ analytics_props=query_run.analytics_props,
)
+ def _report_query_failed(self, error: Exception, *, query_run: QueryRun) -> None:
+ """Send `query execution failed` for a run that raised, with the same identity and ids as
+ `query executed`, so a run that got a cache key leaves exactly one of the two events. Never raises and
+ never touches the error: the caller re-raises what it caught.
+ """
+ try:
+ phase = self._phase
+ stats = phase.stats
+ refused = getattr(error, "served_from_query_failure_cache", False)
+ query_failed_props = {
+ **query_run.event_properties(),
+ "calculation_trigger": query_run.trigger,
+ "failed_in": phase.name,
+ "outcome": "refused" if refused else "failed",
+ "error_category": _classify_error_for_slo(error)[0].value,
+ "error_type": clickhouse_error_type(error),
+ "failed_after_ms": query_run.elapsed_ms(),
+ "query_duration_ms": phase.query_duration_ms,
+ "clickhouse_rows_read": stats.rows_read if stats else None,
+ "clickhouse_duration_ms": round(stats.duration_ms) if stats else None,
+ "clickhouse_workload": stats.workload() if stats else None,
+ "clickhouse_query_count": stats.query_count if stats else None,
+ **compute_phase_times(self.timings.to_dict(), before=self._timings_before_run),
+ }
+ report_user_or_team_action(
+ "query execution failed",
+ query_failed_props,
+ user=query_run.user,
+ team=self.team,
+ organization=self.team.organization,
+ analytics_props=query_run.analytics_props,
+ )
+ except Exception as report_error:
+ with suppress(Exception):
+ capture_exception(report_error, {"team_id": self.team.pk, "context": "query_execution_failed_event"})
+
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,
+ self, *, query_run: QueryRun, cache_manager: QueryCache, flight: Optional[QuerySingleFlight] = None
) -> CR:
CachedResponse: type[CR] = self.cached_response_type
@@ -2654,26 +2690,26 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# Avoid affecting cache key
# Add user based modifiers here, primarily for user specific feature flagging
- if user:
- self.modifiers = create_default_modifiers_for_user(user, self.team, self.modifiers)
+ if query_run.user:
+ self.modifiers = create_default_modifiers_for_user(query_run.user, self.team, self.modifiers)
self.modifiers.useMaterializedViews = True
query_scan_flag = get_query_scan_flag(self.team)
- query_stats_context: AbstractContextManager[QueryStats | None] = (
- query_stats_scope() if query_scan_flag is not None else nullcontext(None)
- )
# Capture data warehouse sync warnings from every HogQL execution that contributes to this
# response. Nested calls (one runner invoking another) see the parent's accumulator via
# ContextVar and contribute to it; the outermost scope is the one that attaches and resets.
- with accumulator_scope() as warnings_accumulator, query_stats_context as query_stats:
- query_type = getattr(self.query, "kind", "Other")
+ with (
+ accumulator_scope() as warnings_accumulator,
+ query_stats_scope(retain_ast=query_scan_flag is not None) as query_stats,
+ ):
survey_query_metric_labels = get_survey_query_metric_labels(self.query)
query_start = perf_counter()
+ self._phase = RunPhase(name="rate_limiters", stats=query_stats)
try:
- query_result, query_duration_ms = self._call_with_rate_limits(dashboard_id=dashboard_id)
+ query_result, query_duration_ms = self._call_with_rate_limits(dashboard_id=query_run.dashboard_id)
QUERY_EXECUTION_TOTAL.labels(
- query_type=query_type,
+ query_type=query_run.query_type,
category="success",
error_type="none",
contains_user_hogql=_contains_user_hogql_label(),
@@ -2684,7 +2720,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
).inc()
except Exception as e:
QUERY_EXECUTION_TOTAL.labels(
- query_type=query_type,
+ query_type=query_run.query_type,
category=classify_query_error(e),
error_type=clickhouse_error_type(e),
contains_user_hogql=_contains_user_hogql_label(),
@@ -2705,24 +2741,25 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
e,
flag=query_scan_flag,
stats=query_stats,
- cache_key=cache_key,
- insight_id=insight_id,
- dashboard_id=dashboard_id,
- user=user,
+ cache_key=query_run.cache_key,
+ insight_id=query_run.insight_id,
+ dashboard_id=query_run.dashboard_id,
+ user=query_run.user,
)
raise
finally:
query_duration_seconds = perf_counter() - query_start
- QUERY_EXECUTION_DURATION.labels(query_type=query_type).observe(query_duration_seconds)
+ QUERY_EXECUTION_DURATION.labels(query_type=query_run.query_type).observe(query_duration_seconds)
if survey_query_metric_labels:
SURVEY_QUERY_EXECUTION_DURATION.labels(**survey_query_metric_labels).observe(query_duration_seconds)
+ self._phase = RunPhase(name="finish", stats=query_stats, query_duration_ms=query_duration_ms)
fresh_response_dict: dict[str, Any] = {
**query_result.model_dump(),
"is_cached": False,
"last_refresh": last_refresh,
"next_allowed_client_refresh": last_refresh + self._refresh_frequency(),
- "cache_key": cache_key,
+ "cache_key": query_run.cache_key,
"timezone": self.team.timezone,
"cache_target_age": target_age,
}
@@ -2732,11 +2769,11 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
fresh_response_dict["query_metadata"] = query_metadata
# Don't log usage for warming queries
- if not trigger or not trigger.startswith("warming"):
+ if not query_run.trigger or not query_run.trigger.startswith("warming"):
log_event_usage_from_query_metadata(
query_metadata,
team_id=self.team.id,
- user_id=user.id if user else None,
+ user_id=query_run.user.id if query_run.user else None,
)
except Exception as e:
# fail silently if we can't extract query metadata
@@ -2744,8 +2781,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
e, {"query": self.query, "team_id": self.team.pk, "context": "query_metadata_extract"}
)
- if trigger:
- fresh_response_dict["calculation_trigger"] = trigger
+ if query_run.trigger:
+ fresh_response_dict["calculation_trigger"] = query_run.trigger
# Attach accumulated warehouse sync warnings before caching, so cache hits replay them.
# Guard against response classes that don't carry the field: every analytics response
@@ -2774,8 +2811,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# Stored with the results, so a cache hit carries the numbers of the run that produced
# them.
scan_skip: QueryScanSkipReason | None = "flag_off"
- if query_scan_flag is not None and query_stats is not None:
- if not is_analyzable_principal(user):
+ if query_scan_flag is not None:
+ if not is_analyzable_principal(query_run.user):
# The summary describes the project's data volume, which a shared-link viewer
# reads from outside the project, so it stays off their response.
scan_skip = "no_principal"
@@ -2795,26 +2832,31 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
team_id=self.team.pk,
# Dashboard and tile overrides are already applied here, so the cache key
# is the right identity for the analysis.
- cache_key=cache_key,
+ cache_key=query_run.cache_key,
query=self.query,
trigger="fresh",
cacheable=cacheable,
- insight_id=insight_id,
- dashboard_id=dashboard_id,
+ insight_id=query_run.insight_id,
+ dashboard_id=query_run.dashboard_id,
)
if scan_skip in (None, "slot_exists"):
# Says only that there is an analysis to look up, never its state: the
# cached copy is not rewritten when the job finishes.
query_scan["analysis_requested"] = True
+ # Built before the cache entry and the single-flight signal go out, so a response that fails
+ # validation is a failed run that published nothing.
+ response = CachedResponse(**fresh_response_dict)
+
if cacheable:
- 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,
- )
+ with self.timings.measure("cache_write"):
+ 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)
@@ -2824,33 +2866,37 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# debug run doesn't cache its result but must still close the failure breaker.
cache_manager.clear_failure()
+ # A fresh run of a query analyzed earlier still has a done slot, so this is
+ # where its findings reach the recomputed response. Served before the event, so the
+ # response time covers the same work as on a cache hit.
+ self._serve_query_scan(response, query_run.user)
+ phase_times = compute_phase_times(self.timings.to_dict(), before=self._timings_before_run)
query_executed_props = {
- "insight_id": insight_id,
- "dashboard_id": dashboard_id,
+ **query_run.event_properties(),
"cache_hit": False,
"cache_age_override": getattr(self, "_cache_age_override", None),
- "cache_key": cache_key,
- "calculation_trigger": trigger,
- "execution_mode": execution_mode.value,
- "query_type": query_type,
- "response_time_ms": round((perf_counter() - start_time) * 1000, 2),
+ "calculation_trigger": query_run.trigger,
+ "response_time_ms": query_run.elapsed_ms(),
"query_duration_ms": query_duration_ms,
"has_error": has_error,
- "clickhouse_rows_read": query_stats.rows_read if query_stats else None,
- "clickhouse_duration_ms": round(query_stats.duration_ms) if query_stats else None,
+ "clickhouse_rows_read": query_stats.rows_read,
+ "clickhouse_duration_ms": round(query_stats.duration_ms),
+ "clickhouse_workload": query_stats.workload(),
+ "clickhouse_query_count": query_stats.query_count,
"query_scan_triggered": scan_skip is None,
"query_scan_skipped_reason": scan_skip,
+ **phase_times,
}
report_user_or_team_action(
"query executed",
query_executed_props,
- user=user,
+ user=query_run.user,
team=self.team,
organization=self.team.organization,
- analytics_props=analytics_props,
+ analytics_props=query_run.analytics_props,
)
- return CachedResponse(**fresh_response_dict)
+ return response
def _serve_query_scan(self, response: Any, user: Optional[User]) -> None:
"""Put the stored analysis on a response, or take the field off for a shared-link viewer, who
@@ -3031,6 +3077,26 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
return payload
+ def get_query_identity(self) -> QueryIdentity:
+ return self._query_identity_for(self.get_cache_payload(), self.get_cache_key_variant())
+
+ def _query_identity_for(self, payload: dict, variant: str) -> QueryIdentity:
+ """Split what the cache key hashes into the question and the answer, and hash each half. The
+ question is the query without its modifiers, plus the team; the answer is every other payload
+ key and the runner's cache key variant. Same serialization as the cache key, so a cache hit
+ and a fresh run of one query produce the same pair."""
+ question = {
+ "query": {k: v for k, v in payload["query"].items() if k != "modifiers"},
+ "team_id": payload["team_id"],
+ }
+ answer = {k: v for k, v in payload.items() if k not in ("query", "team_id")}
+ if variant:
+ answer["cache_key_variant"] = variant
+ return QueryIdentity(
+ query_hash=hashlib.sha256(to_json(question)).hexdigest()[:32],
+ runtime_hash=hashlib.sha256(to_json(answer)).hexdigest()[:32],
+ )
+
def _products_modifiers_for_cache(self) -> dict:
# The team-extension configs are loaded lazily and can hit the DB. Under connection-pool
# saturation these reads can time out (OperationalError); degrade to a stable "unavailable"
@@ -3073,7 +3139,20 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
]
def get_cache_key(self) -> str:
- return generate_cache_key(self.team.pk, f"query_{bytes.decode(to_json(self.get_cache_payload()))}")
+ payload = self.get_cache_payload()
+ variant = self.get_cache_key_variant()
+ # Taken from what the key hashes, before the fresh path adds user modifiers, so a hit and a
+ # fresh run agree, and the payload is built once per run.
+ self._query_identity = self._query_identity_for(payload, variant)
+ return f"{self._cache_key_for(payload)}{variant}"
+
+ def get_cache_key_variant(self) -> str:
+ """State outside the cache payload that changes this runner's results, as a key suffix.
+ Override this rather than `get_cache_key`, so the state also reaches `runtime_hash`."""
+ return ""
+
+ def _cache_key_for(self, payload: dict) -> str:
+ return generate_cache_key(self.team.pk, f"query_{bytes.decode(to_json(payload))}")
def apply_series_custom_names(self, cached_response: CR) -> tuple[CR, bool]:
"""
diff --git a/posthog/hogql_queries/test/test_phase_times.py b/posthog/hogql_queries/test/test_phase_times.py
new file mode 100644
index 000000000000..a040a108de0e
--- /dev/null
+++ b/posthog/hogql_queries/test/test_phase_times.py
@@ -0,0 +1,16 @@
+from django.test import SimpleTestCase
+
+from posthog.hogql_queries.phase_times import compute_phase_times
+
+
+class TestComputePhaseTimes(SimpleTestCase):
+ def test_runner_tree_rollups_convert_to_ms_and_default_none_when_absent(self) -> None:
+ result = compute_phase_times({"./rate_limiters": 0.012, "./cache_write": 0.003, "./query": 0.5})
+ self.assertEqual(result, {"rate_limiters_ms": 12.0, "cache_write_ms": 3.0, "flight_wait_ms": None})
+
+ def test_a_second_run_reports_only_what_it_added_to_the_tree(self) -> None:
+ first_run = {"./rate_limiters": 0.012, "./cache_write": 0.003}
+ result = compute_phase_times(
+ {"./rate_limiters": 0.020, "./cache_write": 0.003, "./flight_wait": 0.1}, before=first_run
+ )
+ self.assertEqual(result, {"rate_limiters_ms": 8.0, "cache_write_ms": None, "flight_wait_ms": 100.0})
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index fac42947773e..7c6552990e07 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -185,7 +185,7 @@ _QUERY_SCAN_FLAG_LOG_ONLY = QueryScanFlag(
def _calculate_recording_clickhouse_stats(_self):
- record(rows_read=12, duration_ms=34.0)
+ record(rows_read=12, duration_ms=34.0, workload="ONLINE")
return TheTestBasicQueryResponse(results=[])
@@ -193,6 +193,12 @@ def _calculate_without_clickhouse(_self):
return TheTestBasicQueryResponse(results=[])
+def _add_user_modifier(_user: User, _team: Team, modifiers: HogQLQueryModifiers | None) -> HogQLQueryModifiers:
+ changed = (modifiers or HogQLQueryModifiers()).model_copy()
+ changed.typeAwareCastSimplification = True
+ return changed
+
+
def _shared_link_user(team: Team) -> User:
# The share link is its authorization, so the query runs, but there is no user row the worker
# could resolve back.
@@ -327,7 +333,7 @@ class TestQueryRunner(BaseTest):
TestQueryRunner = self.setup_test_query_runner_class()
user = self.user if real_user else _shared_link_user(self.team)
- def calculate_until_clickhouse_gives_up(_self):
+ def calculate_until_clickhouse_gives_up(_self: QueryRunner) -> None:
# 400 ms is under the flag's 1000 ms floor: a stopped run is analyzed at any duration.
record(rows_read=90, duration_ms=400.0)
# The executor records this before the kill; the fake runner stands in for it here.
@@ -379,7 +385,7 @@ class TestQueryRunner(BaseTest):
# one's analysis still running, and says so without reading it.
TestQueryRunner = self.setup_test_query_runner_class()
- def calculate_until_clickhouse_gives_up(_self):
+ def calculate_until_clickhouse_gives_up(_self: QueryRunner) -> None:
record(rows_read=90, duration_ms=4000.0)
raise ClickHouseQueryMemoryLimitExceeded()
@@ -469,6 +475,20 @@ class TestQueryRunner(BaseTest):
validation_rule.validate.assert_called_once_with(runner.validation_context)
mock_calculate.assert_not_called()
+ def test_fresh_run_reports_its_own_phase_times_on_the_query_executed_event(self) -> None:
+ TestQueryRunner = self.setup_test_query_runner_class()
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report:
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ first = report.call_args.args[1]
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ second = report.call_args.args[1]
+ assert report.call_args.args[0] == "query executed"
+ assert first["cache_hit"] is False
+ assert isinstance(first["rate_limiters_ms"], float) and first["rate_limiters_ms"] >= 0
+ assert isinstance(first["cache_write_ms"], float) and first["cache_write_ms"] >= 0
+ assert second["cache_write_ms"] < round(runner.timings.to_dict()["./cache_write"] * 1000, 2)
+
def test_init_with_query_instance(self):
TestQueryRunner = self.setup_test_query_runner_class()
@@ -795,6 +815,176 @@ class TestQueryRunner(BaseTest):
cache_key = runner.get_cache_key()
assert cache_key == "cache_42_580a20072d3930f66666356574843255ba9418ff58cc0fc92d019bf8bf1cf972"
+ def test_query_identity_splits_the_query_from_how_it_is_answered(self) -> None:
+ TestQueryRunner = self.setup_test_query_runner_class()
+ team = self.team
+
+ base = TestQueryRunner(query={"some_attr": "bla"}, team=team).get_query_identity()
+
+ modified = TestQueryRunner(
+ query={"some_attr": "bla"}, team=team, modifiers=HogQLQueryModifiers(typeAwareCastSimplification=True)
+ ).get_query_identity()
+ assert modified.query_hash == base.query_hash
+ assert modified.runtime_hash != base.runtime_hash
+
+ team.modifiers = {"typeAwareCastSimplification": True}
+ team_modified = TestQueryRunner(query={"some_attr": "bla"}, team=team).get_query_identity()
+ assert team_modified.query_hash == base.query_hash
+ assert team_modified.runtime_hash != base.runtime_hash
+ team.modifiers = None
+
+ exported = TestQueryRunner(
+ query={"some_attr": "bla"}, team=team, limit_context=LimitContext.EXPORT
+ ).get_query_identity()
+ assert exported.query_hash == base.query_hash
+
+ changed = TestQueryRunner(query={"some_attr": "different"}, team=team).get_query_identity()
+ assert changed.query_hash != base.query_hash
+
+ def test_cache_hit_and_fresh_events_carry_one_identity(self) -> None:
+ runner_class = setup_test_query_runner_class()
+ with (
+ mock.patch(
+ "posthog.hogql_queries.query_runner.create_default_modifiers_for_user", side_effect=_add_user_modifier
+ ),
+ mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report,
+ ):
+ runner_class(query={"some_attr": "bla"}, team=self.team, user=self.user).run(
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ )
+ fresh_props = report.call_args.args[1]
+ runner_class(query={"some_attr": "bla"}, team=self.team, user=self.user).run(
+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ )
+ hit_props = report.call_args.args[1]
+
+ assert fresh_props["cache_hit"] is False
+ assert hit_props["cache_hit"] is True
+ assert fresh_props["query_hash"] == hit_props["query_hash"]
+ assert fresh_props["runtime_hash"] == hit_props["runtime_hash"]
+
+ def test_fresh_event_carries_clickhouse_counters_with_the_scan_flag_off(self) -> None:
+ TestQueryRunner = self.setup_test_query_runner_class()
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team, user=self.user)
+ with (
+ mock.patch.object(
+ TestQueryRunner, "_calculate", autospec=True, side_effect=_calculate_recording_clickhouse_stats
+ ),
+ mock.patch("posthog.hogql_queries.query_runner.get_query_scan_flag", return_value=None),
+ mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report,
+ ):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
+ props = report.call_args.args[1]
+ assert props["cache_hit"] is False
+ assert props["clickhouse_rows_read"] == 12
+ assert props["clickhouse_query_count"] == 1
+ assert props["clickhouse_workload"] == "ONLINE"
+
+ @parameterized.expand(
+ [
+ ("in the calculation", "calculate", "calculate", ClickHouseQueryTimeOut, "query_performance_error"),
+ ("with a validation error", "calculate", "calculate", ValidationError, "user_error"),
+ ("turned away by a limiter", "limiter", "rate_limiters", ConcurrencyLimitExceeded, "rate_limited"),
+ ("in the cache write", "store", "finish", RuntimeError, "error"),
+ ("while serving the scan", "serve", "finish", RuntimeError, "error"),
+ ]
+ )
+ def test_a_run_that_raises_sends_one_failure_event_and_no_success_event(
+ self, _name: str, where: str, failed_in: str, error_class: type[Exception], error_category: str
+ ) -> None:
+ TestQueryRunner = self.setup_test_query_runner_class()
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team, user=self.user)
+
+ def calculate_until_clickhouse_gives_up(_self: QueryRunner) -> None:
+ record(rows_read=90, duration_ms=400.0, workload="ONLINE")
+ raise error_class()
+
+ if where == "calculate":
+ failing = mock.patch.object(
+ TestQueryRunner, "_calculate", autospec=True, side_effect=calculate_until_clickhouse_gives_up
+ )
+ elif where == "limiter":
+ failing = mock.patch(
+ "posthog.hogql_queries.query_runner.get_app_org_rate_limiter", side_effect=error_class("over the limit")
+ )
+ elif where == "store":
+ failing = mock.patch.object(QueryCache, "store_result", side_effect=error_class("cache store failed"))
+ else:
+ failing = mock.patch.object(runner, "_serve_query_scan", side_effect=error_class("scan serve failed"))
+ with failing, mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report:
+ with self.assertRaises(error_class):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
+ assert [call.args[0] for call in report.call_args_list] == ["query execution failed"]
+ props = report.call_args.args[1]
+ assert props["failed_in"] == failed_in
+ assert (props["outcome"], props["error_category"]) == ("failed", error_category)
+ assert props["error_type"] == error_class.__name__
+ assert props["cache_key"] == runner.get_cache_key()
+ assert props["query_hash"] == runner.get_query_identity().query_hash
+ assert props["failed_after_ms"] >= 0
+ if failed_in == "calculate":
+ assert (props["clickhouse_rows_read"], props["clickhouse_workload"]) == (90, "ONLINE")
+ assert props["query_duration_ms"] is None
+ elif failed_in == "rate_limiters":
+ assert (props["clickhouse_query_count"], props["query_duration_ms"]) == (0, None)
+ else:
+ assert isinstance(props["query_duration_ms"], float)
+
+ def test_a_cache_key_variant_reaches_the_key_and_the_runtime_hash_of_a_run(self) -> None:
+ TestQueryRunner = self.setup_test_query_runner_class()
+
+ class VariantQueryRunner(TestQueryRunner): # type: ignore[valid-type,misc]
+ def get_cache_key_variant(self) -> str:
+ return "_variant"
+
+ plain = TestQueryRunner(query={"some_attr": "bla"}, team=self.team).get_query_identity()
+ runner = VariantQueryRunner(query={"some_attr": "bla"}, team=self.team)
+ with mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report:
+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
+ props = report.call_args.args[1]
+ assert response.cache_key.endswith("_variant")
+ assert props["query_hash"] == plain.query_hash
+ assert props["runtime_hash"] != plain.runtime_hash
+
+ def test_a_response_that_fails_validation_publishes_nothing(self) -> None:
+ TestQueryRunner = self.setup_test_query_runner_class()
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team, user=self.user)
+
+ class RejectingResponse:
+ def __init__(self, **_kwargs: Any) -> None:
+ raise ValueError("invalid response")
+
+ with (
+ mock.patch.object(
+ TestQueryRunner, "cached_response_type", new_callable=mock.PropertyMock, return_value=RejectingResponse
+ ),
+ mock.patch.object(QueryCache, "store_result") as store_result,
+ mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report,
+ ):
+ with self.assertRaises(ValueError):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
+ store_result.assert_not_called()
+ assert [call.args[0] for call in report.call_args_list] == ["query execution failed"]
+ assert report.call_args.args[1]["failed_in"] == "finish"
+
+ def test_a_failing_report_path_leaves_the_query_error_as_it_was(self) -> None:
+ TestQueryRunner = self.setup_test_query_runner_class()
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team, user=self.user)
+
+ with (
+ mock.patch.object(TestQueryRunner, "_calculate", side_effect=ValidationError("bad input")),
+ mock.patch(
+ "posthog.hogql_queries.query_runner.report_user_or_team_action", side_effect=RuntimeError("report")
+ ),
+ mock.patch("posthog.hogql_queries.query_runner.capture_exception", side_effect=RuntimeError("capture")),
+ ):
+ with self.assertRaises(ValidationError):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
def test_cache_payload_omits_object_restrictions_when_unrestricted(self):
TestQueryRunner = self.setup_test_query_runner_class()
runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team, user=self.user)
@@ -2184,11 +2374,19 @@ class TestQueryFailureCaching(BaseTest):
with mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag):
mock_calculate = self._open_breaker(runner_class, runner)
- with self.assertRaises(ClickHouseQueryTimeOut) as ctx:
- runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ 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.
@@ -2240,7 +2438,7 @@ class TestQueryFailureCaching(BaseTest):
runner_class = setup_test_query_runner_class()
runner = runner_class(query={"some_attr": "bla"}, team=self.team)
- def calculate_until_clickhouse_gives_up(_self):
+ def calculate_until_clickhouse_gives_up(_self: QueryRunner) -> None:
record(rows_read=90, duration_ms=4000.0)
raise _per_query_memory_error()
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index 9b621db54bf0..3cd946106e68 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -205,15 +205,15 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
return remapped
return self.query.breakdownBy
- def get_cache_key(self) -> str:
+ def get_cache_key_variant(self) -> str:
# The remap changes results for the same query, so remapped and
# entry-attributed runs must not share cache entries — and rolling the
# flag back to 0% must instantly serve the old key again.
- original = super().get_cache_key()
+ variant = super().get_cache_key_variant()
effective_breakdown = self._effective_breakdown()
if effective_breakdown != self.query.breakdownBy:
- return f"{original}_{effective_breakdown.value}"
- return original
+ return f"{variant}_{effective_breakdown.value}"
+ return variant
def _get_strategy(self) -> StatsTableQueryStrategy:
breakdown = self._effective_breakdown()
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
index aee60d56d2b9..538f8a327739 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
@@ -377,7 +377,15 @@ class TestCacheKeyVariesWithRolloutState(BaseTest):
team=self.team,
query=WebOverviewQuery(dateRange=DateRange(date_from="-7d"), properties=[]),
)
- return runner.get_cache_key()
+ identity = runner.get_query_identity()
+ return f"{runner.get_cache_key()} {identity.query_hash} {identity.runtime_hash}"
+
+ def _assert_only_the_runtime_changed(self, before: str, after: str) -> None:
+ key_before, query_hash_before, runtime_hash_before = before.split(" ")
+ key_after, query_hash_after, runtime_hash_after = after.split(" ")
+ assert key_before != key_after
+ assert query_hash_before == query_hash_after
+ assert runtime_hash_before != runtime_hash_after
def test_flipping_enrollment_changes_cache_key(self) -> None:
# With default-on reads, disabling the rollout flag (the kill switch)
@@ -387,7 +395,7 @@ class TestCacheKeyVariesWithRolloutState(BaseTest):
key_enabled = self._cache_key()
with mock.patch(f"{self._RUNNER_MOD}.is_precompute_enabled_for_team", return_value=False):
key_disabled = self._cache_key()
- assert key_enabled != key_disabled
+ self._assert_only_the_runtime_changed(key_enabled, key_disabled)
def test_crossing_the_volume_floor_changes_cache_key(self) -> None:
# A team crossing below the floor switches to the live path; the key must
@@ -397,7 +405,7 @@ class TestCacheKeyVariesWithRolloutState(BaseTest):
key_above = self._cache_key()
with mock.patch(f"{self._RUNNER_MOD}.is_team_above_volume_floor", return_value=False):
key_below = self._cache_key()
- assert key_above != key_below
+ self._assert_only_the_runtime_changed(key_above, key_below)
class TestHostFilterExpr(BaseTest):
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index bdd8b126aed7..463fff5981c0 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -1189,7 +1189,12 @@ class TestWebStatsTableQueryRunner(
with self._patch_first_pageview_flag(enabled=flag_on):
return WebStatsTableQueryRunner(team=self.team, query=query).get_cache_key()
+ def runtime_hash(flag_on):
+ with self._patch_first_pageview_flag(enabled=flag_on):
+ return WebStatsTableQueryRunner(team=self.team, query=query).get_query_identity().runtime_hash
+
assert cache_key(flag_on=False) != cache_key(flag_on=True)
+ assert runtime_hash(flag_on=False) != runtime_hash(flag_on=True)
def test_first_pageview_attribution_bypasses_lazy_precompute(self):
query = WebStatsTableQuery(
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 87b94273daf0..51bdbd7ab34f 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -762,8 +762,7 @@ WHERE and(
modifiers=self.modifiers,
)
- def get_cache_key(self) -> str:
- original = super().get_cache_key()
+ def get_cache_key_variant(self) -> str:
# Precompute enrollment is part of the key so flipping the rollout flag
# invalidates cached results: with default-on reads, disabling the flag
# (the kill switch) must not keep serving cached precompute-produced
@@ -774,12 +773,12 @@ WHERE and(
# under the old key must not keep serving until it stales out. Only read
# the floor when precompute is on — otherwise it can't change the result.
above_floor = precompute and is_team_above_volume_floor(self.team.pk)
- key = f"{original}_{self.team.path_cleaning_filters}_pc{int(precompute)}_vf{int(above_floor)}"
+ variant = f"_{self.team.path_cleaning_filters}_pc{int(precompute)}_vf{int(above_floor)}"
# A rewritten filter selects a different population for the same query, so
# rewritten and entry-attributed runs must not share cache entries.
if self.rewritten_first_pageview_filters:
- key = f"{key}_fpfilters"
- return key
+ variant = f"{variant}_fpfilters"
+ return variant
@cached_property
def events_session_property(self):