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(web-analytics): emit cache_key_hash on query and lazy precompute logs (#60378)

Lucas Ricoy30312c93014e
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
index 2201b01a83ae..3dee8eb452f8 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
@@ -7,7 +7,14 @@ from parameterized import parameterized
from posthog.schema import WebStatsBreakdown
-from posthog.clickhouse.query_tagging import create_base_tags, get_query_tag_value, query_tags, tag_queries
+from posthog.clickhouse.query_tagging import (
+ Feature,
+ Product,
+ create_base_tags,
+ get_query_tag_value,
+ query_tags,
+ tag_queries,
+)
from products.web_analytics.backend.hogql_queries.metrics import (
WEB_ANALYTICS_QUERY_COUNTER,
@@ -46,6 +53,10 @@ def _make_runner(
runner = MagicMock(spec=WebAnalyticsQueryRunner)
runner.query = query
runner.team = team
+ # The real `filters_eligibility_hash` is an Optional[str] cached_property; `spec` doesn't
+ # propagate the annotation so MagicMock would return a Mock object which fails
+ # the QueryTags pydantic validation in `tag_queries`. Pin a stable test value.
+ runner.filters_eligibility_hash = "test_filters_eligibility_hash"
cast(MagicMock, runner.query_strategy).return_value = query_strategy
cast(MagicMock, runner.clickhouse_query_type).return_value = (
f"{query_strategy}_query" if query_strategy is not None else None
@@ -88,6 +99,11 @@ class TestWebAnalyticsMetrics(TestCase):
WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED._metrics.clear()
WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK._metrics.clear()
WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS._metrics.clear()
+ # Reset `query_tags` ContextVar — it persists across tests in the same
+ # process and `tag_queries` only updates fields explicitly passed in,
+ # so a prior test's `breakdown_by` would leak into a runner whose
+ # query has no breakdown.
+ query_tags.set(create_base_tags())
@parameterized.expand(
[
@@ -302,6 +318,58 @@ class TestWebAnalyticsMetrics(TestCase):
== 1.0
)
+ @parameterized.expand(
+ [
+ # (name, query_kind, breakdown_with_value_or_none, expect_breakdown_by_tag)
+ ("overview_no_breakdown", "WebOverviewQuery", None, None),
+ ("stats_table_page", "WebStatsTableQuery", WebStatsBreakdown.PAGE, ["Page"]),
+ ("stats_table_browser", "WebStatsTableQuery", WebStatsBreakdown.BROWSER, ["Browser"]),
+ (
+ "stats_table_initial_channel",
+ "WebStatsTableQuery",
+ WebStatsBreakdown.INITIAL_CHANNEL_TYPE,
+ ["InitialChannelType"],
+ ),
+ ("goals", "WebGoalsQuery", None, None),
+ ("external_clicks", "WebExternalClicksTableQuery", None, None),
+ ("vitals_paths", "WebVitalsPathBreakdownQuery", None, None),
+ ("trends", "WebTrendsQuery", None, None),
+ ],
+ )
+ @patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
+ )
+ def test_tag_queries_payload_consistent_across_runners(
+ self, _name, query_kind, breakdown, expect_breakdown_by_tag, _mock_tag
+ ):
+ """Every web analytics query runner must land the same shape in
+ `system.query_log.log_comment` via `tag_queries` — `product`,
+ `feature`, `query`, and `breakdown_by` (when the query has a
+ `breakdownBy`). Drift here breaks downstream `query_log`-based
+ analysis (per-strategy latency, per-tile cost slicing).
+
+ `filters_eligibility_hash` is **not** in this payload — it stays on
+ the structlog contextvar only, see
+ `test_filters_eligibility_hash_not_in_query_tags`."""
+ runner = _make_runner(query_kind=query_kind, breakdown=breakdown)
+ # The real `WebQueryNode.model_dump(mode="json")` returns a dict; the
+ # MagicMock-backed `query` returns another Mock by default, which
+ # bypasses the dict-shape assertion below.
+ cast(MagicMock, runner.query.model_dump).return_value = {"kind": query_kind}
+
+ fake_response = MagicMock()
+ fake_response.usedPreAggregatedTables = False
+
+ with patch.object(WebAnalyticsQueryRunner.__mro__[1], "calculate", return_value=fake_response):
+ WebAnalyticsQueryRunner.calculate(runner)
+
+ assert get_query_tag_value("product") == Product.WEB_ANALYTICS
+ assert get_query_tag_value("feature") == Feature.QUERY
+ # `query` is the dumped query payload — a dict with at least `kind`.
+ query_tag = get_query_tag_value("query")
+ assert isinstance(query_tag, dict) and query_tag.get("kind") == query_kind
+ assert get_query_tag_value("breakdown_by") == expect_breakdown_by_tag
+
@parameterized.expand(
[
("web_overview", "web_overview"),
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
new file mode 100644
index 000000000000..f578cf77c6fe
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
@@ -0,0 +1,216 @@
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin
+from unittest import mock
+
+from structlog.contextvars import get_contextvars
+
+from posthog.schema import (
+ CompareFilter,
+ DateRange,
+ EventPropertyFilter,
+ PropertyOperator,
+ WebOverviewQuery,
+ WebStatsBreakdown,
+ WebStatsTableQuery,
+)
+
+from posthog.clickhouse.query_tagging import get_query_tag_value
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+
+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import compute_filters_eligibility_hash
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+
+
+def _overview(
+ *,
+ date_from: str = "-7d",
+ date_to: str | None = None,
+ properties: list | None = None,
+ compare: bool = False,
+) -> WebOverviewQuery:
+ return WebOverviewQuery(
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ properties=properties or [],
+ compareFilter=CompareFilter(compare=compare) if compare else None,
+ )
+
+
+def _stats(
+ *,
+ date_from: str = "-7d",
+ breakdown_by: WebStatsBreakdown = WebStatsBreakdown.BROWSER,
+ properties: list | None = None,
+) -> WebStatsTableQuery:
+ return WebStatsTableQuery(
+ dateRange=DateRange(date_from=date_from),
+ breakdownBy=breakdown_by,
+ properties=properties or [],
+ )
+
+
+class TestComputeFiltersEligibilityHash(BaseTest):
+ def test_stable_across_calls_with_identical_query(self) -> None:
+ q = _overview()
+ assert compute_filters_eligibility_hash(q, "UTC") == compute_filters_eligibility_hash(q, "UTC")
+
+ def test_stable_across_freshly_built_equal_queries(self) -> None:
+ assert compute_filters_eligibility_hash(_overview(), "UTC") == compute_filters_eligibility_hash(
+ _overview(), "UTC"
+ )
+
+ def test_date_range_fragments_key(self) -> None:
+ a = compute_filters_eligibility_hash(_overview(date_from="-7d"), "UTC")
+ b = compute_filters_eligibility_hash(_overview(date_from="-30d"), "UTC")
+ assert a != b
+
+ def test_breakdown_fragments_key(self) -> None:
+ a = compute_filters_eligibility_hash(_stats(breakdown_by=WebStatsBreakdown.BROWSER), "UTC")
+ b = compute_filters_eligibility_hash(_stats(breakdown_by=WebStatsBreakdown.OS), "UTC")
+ assert a != b
+
+ def test_filter_value_fragments_key(self) -> None:
+ chrome = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]
+ firefox = [EventPropertyFilter(key="$browser", value="Firefox", operator=PropertyOperator.EXACT)]
+ assert compute_filters_eligibility_hash(
+ _overview(properties=chrome), "UTC"
+ ) != compute_filters_eligibility_hash(_overview(properties=firefox), "UTC")
+
+ def test_filter_operator_fragments_key(self) -> None:
+ exact = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]
+ is_not = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.IS_NOT)]
+ assert compute_filters_eligibility_hash(_overview(properties=exact), "UTC") != compute_filters_eligibility_hash(
+ _overview(properties=is_not), "UTC"
+ )
+
+ def test_query_kind_fragments_key(self) -> None:
+ assert compute_filters_eligibility_hash(_overview(), "UTC") != compute_filters_eligibility_hash(_stats(), "UTC")
+
+ def test_timezone_fragments_key(self) -> None:
+ q = _overview()
+ assert compute_filters_eligibility_hash(q, "UTC") != compute_filters_eligibility_hash(q, "America/New_York")
+
+ def test_compare_filter_fragments_key(self) -> None:
+ assert compute_filters_eligibility_hash(_overview(compare=False), "UTC") != compute_filters_eligibility_hash(
+ _overview(compare=True), "UTC"
+ )
+
+ def test_property_order_currently_fragments_key_documented_not_desired(self) -> None:
+ a = [
+ EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT),
+ EventPropertyFilter(key="$os", value="Mac OS X", operator=PropertyOperator.EXACT),
+ ]
+ b = list(reversed(a))
+ # NOTE: we don't currently canonicalize order. If two clients send the
+ # same filter set in different orders they will hash to different keys.
+ # Document the current behavior rather than the desired one — change
+ # this assertion if we add canonical ordering upstream.
+ assert compute_filters_eligibility_hash(_overview(properties=a), "UTC") != compute_filters_eligibility_hash(
+ _overview(properties=b), "UTC"
+ )
+
+ def test_use_web_analytics_precompute_toggle_does_not_fragment_key(self) -> None:
+ q_on = WebOverviewQuery(
+ dateRange=DateRange(date_from="-7d"),
+ properties=[],
+ useWebAnalyticsPrecompute=True,
+ )
+ q_off = WebOverviewQuery(
+ dateRange=DateRange(date_from="-7d"),
+ properties=[],
+ useWebAnalyticsPrecompute=False,
+ )
+ assert compute_filters_eligibility_hash(q_on, "UTC") == compute_filters_eligibility_hash(q_off, "UTC")
+
+ def test_hash_is_64_char_hex(self) -> None:
+ h = compute_filters_eligibility_hash(_overview(), "UTC")
+ assert len(h) == 64
+ int(h, 16)
+
+
+class TestFiltersEligibilityHashContextvarBinding(ClickhouseTestMixin, APIBaseTest):
+ """Verifies that `WebAnalyticsQueryRunner.calculate()` binds `filters_eligibility_hash`
+ on `structlog.contextvars` so every log emitted inside the request —
+ including from code called via `super().calculate()` and downstream paths
+ like the lazy framework's `lazy_computation.executed` — picks it up via
+ the project-wide `merge_contextvars` processor.
+
+ The tests inspect `structlog.contextvars.get_contextvars()` directly rather
+ than going through `structlog.testing.capture_logs()` because the latter
+ replaces the configured processor chain and therefore doesn't run
+ `merge_contextvars` — capture_logs would falsely report the field missing
+ even when production code is correct."""
+
+ def _runner(self) -> WebOverviewQueryRunner:
+ return WebOverviewQueryRunner(
+ team=self.team,
+ query=WebOverviewQuery(
+ dateRange=DateRange(date_from="-7d"),
+ properties=[],
+ ),
+ )
+
+ def test_filters_eligibility_hash_bound_during_super_calculate(self) -> None:
+ """While `super().calculate()` is running, `get_contextvars()` should
+ return `filters_eligibility_hash` — this is the property the `merge_contextvars`
+ processor relies on to attach the field to every log inside the call
+ tree (`lazy_computation.executed`, eligibility-rejected lines, etc.).
+
+ Patches `AnalyticsQueryRunner.calculate` (the parent reached by
+ `super().calculate()`), NOT a runner-level class — patching at the
+ binding class would replace the very method that wraps the
+ contextvar block."""
+ runner = self._runner()
+ expected = runner.filters_eligibility_hash
+ assert expected is not None
+
+ captured: dict = {}
+ original = AnalyticsQueryRunner.calculate
+
+ def spy(self_):
+ captured.update(get_contextvars())
+ return original(self_)
+
+ with mock.patch.object(AnalyticsQueryRunner, "calculate", spy):
+ runner.calculate()
+
+ assert captured.get("filters_eligibility_hash") == expected
+
+ def test_filters_eligibility_hash_unbound_after_calculate_returns(self) -> None:
+ """The contextvar must not leak past `calculate()` — `get_contextvars()`
+ outside the request should NOT include the prior request's hash."""
+ runner = self._runner()
+ runner.calculate()
+ assert "filters_eligibility_hash" not in get_contextvars()
+
+ def test_filters_eligibility_hash_unbound_after_calculate_raises(self) -> None:
+ """Same cleanup invariant when `calculate()` raises — the contextvar
+ must still be unbound (otherwise an exception in one request would
+ leak its filters_eligibility_hash into the next request on the same worker)."""
+ runner = self._runner()
+
+ with mock.patch.object(AnalyticsQueryRunner, "calculate", side_effect=RuntimeError("boom")):
+ try:
+ runner.calculate()
+ except RuntimeError:
+ pass
+
+ assert "filters_eligibility_hash" not in get_contextvars()
+
+ def test_filters_eligibility_hash_not_in_query_tags(self) -> None:
+ """The hash is deliberately kept out of `tag_queries` — `system.query_log`
+ has sub-day retention on prod, so a hash for multi-day analysis only
+ makes sense on a long-retention source (Loki). This test pins the
+ decision: if someone reintroduces it to the tags, they must intend it
+ and update this assertion."""
+ runner = self._runner()
+ original = AnalyticsQueryRunner.calculate
+
+ captured: dict = {}
+
+ def spy(self_):
+ captured["query_tag"] = get_query_tag_value("filters_eligibility_hash")
+ return original(self_)
+
+ with mock.patch.object(AnalyticsQueryRunner, "calculate", spy):
+ runner.calculate()
+
+ assert captured["query_tag"] is None
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 04f7e4777bea..d1e443e85e3c 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
@@ -10,6 +10,7 @@ from django.conf import settings
from django.core.cache import cache
import structlog
+from structlog.contextvars import bound_contextvars
from posthog.schema import (
ActionConversionGoal,
@@ -52,6 +53,7 @@ from products.web_analytics.backend.hogql_queries.metrics import (
WEB_ANALYTICS_QUERY_ERRORS,
)
from products.web_analytics.backend.hogql_queries.traffic_type import get_traffic_category_expr, get_traffic_type_expr
+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import compute_filters_eligibility_hash
logger = structlog.get_logger(__name__)
@@ -84,102 +86,131 @@ class WebAnalyticsQueryRunner(AnalyticsQueryRunner[WAR], ABC):
return user_access_control.assert_access_level_for_resource("web_analytics", "viewer")
def calculate(self) -> WAR:
- # Every web analytics query runner produces user-facing dashboard
- # queries. Tag here so all downstream `sync_execute` calls (live,
- # preagg, lazy precompute) inherit `product`/`feature` and don't
- # trip DEBUG-mode `UntaggedQueryError`.
- tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)
-
- # The HTTP path tags the wrapped query payload in
- # `posthog/api/services/query.py`, but the weekly digest workflow
- # (and any other non-HTTP caller) reaches the runner directly and
- # leaves `log_comment.query` empty. Tag the inner query so every
- # web-analytics row in `system.query_log` carries `dateRange`,
- # properties, etc., and so each runner in a long-lived activity
- # records its own payload instead of inheriting the first one.
- tag_queries(query=self.query.model_dump(mode="json"))
-
- query_kind = getattr(self.query, "kind", "Unknown")
- breakdown_value = getattr(self.query, "breakdownBy", None)
- breakdown_label = breakdown_value.value if breakdown_value is not None else "none"
- has_conversion_goal = "true" if getattr(self.query, "conversionGoal", None) else "false"
-
- logger.info(
- "web_analytics_query_started",
- team_id=self.team.pk,
- query_kind=query_kind,
- )
-
- if breakdown_value is not None:
- tag_queries(breakdown_by=[breakdown_value.value])
+ # `filters_eligibility_hash` is bound on structlog contextvars here so every
+ # structured log emitted inside this request — `web_analytics_query`,
+ # each lazy-precompute path's `*_rejected` / `*_eligible`, and the
+ # framework's `lazy_computation.executed` — automatically carries it
+ # via the `merge_contextvars` processor. Joining log streams by cache
+ # key needs no further plumbing. The body is inlined inside the
+ # contextvar block (rather than delegated to a helper) so existing
+ # tests that call `WebAnalyticsQueryRunner.calculate(<MagicMock>)`
+ # exercise it directly.
+ with bound_contextvars(filters_eligibility_hash=self.filters_eligibility_hash):
+ # Tag everything ClickHouse will see for this request in one call so
+ # every downstream `sync_execute` (live, preagg, lazy precompute)
+ # inherits a coherent `log_comment` payload.
+ #
+ # `product`/`feature` are required so DEBUG-mode `sync_execute` doesn't
+ # trip `UntaggedQueryError`. `query` is set here because the HTTP
+ # layer (`posthog/api/services/query.py`) tags only the wrapping
+ # payload — the weekly digest workflow (and any other non-HTTP
+ # caller) reaches the runner directly with `log_comment.query`
+ # empty, so each runner records its own payload.
+ #
+ # `filters_eligibility_hash` deliberately stays out of the tag
+ # payload: `system.query_log` retention is sub-day on prod ClickHouse,
+ # so the hash is only useful on a multi-day source. It lives on the
+ # structlog contextvar (Loki, ~14 d retention) only.
+ query_kind = getattr(self.query, "kind", "Unknown")
+ breakdown_value = getattr(self.query, "breakdownBy", None)
+ breakdown_label = breakdown_value.value if breakdown_value is not None else "none"
+ has_conversion_goal = "true" if getattr(self.query, "conversionGoal", None) else "false"
+
+ tag_kwargs: dict[str, object] = {
+ "product": Product.WEB_ANALYTICS,
+ "feature": Feature.QUERY,
+ "query": self.query.model_dump(mode="json"),
+ }
+ if breakdown_value is not None:
+ tag_kwargs["breakdown_by"] = [breakdown_value.value]
+ tag_queries(**tag_kwargs)
- start = perf_counter()
- response: Optional[WAR] = None
- error_type = ""
- query_strategy: str | None = None
- clickhouse_query_type: str | None = None
+ logger.info(
+ "web_analytics_query_started",
+ team_id=self.team.pk,
+ query_kind=query_kind,
+ )
- try:
- response = super().calculate()
- return response
- except Exception as exc:
- error_type = type(exc).__name__
- raise
- finally:
- duration_s = perf_counter() - start
+ start = perf_counter()
+ response: Optional[WAR] = None
+ error_type = ""
+ query_strategy: str | None = None
+ clickhouse_query_type: str | None = None
try:
- query_strategy = self.query_strategy()
- clickhouse_query_type = self.clickhouse_query_type()
- except Exception:
- query_strategy = query_strategy or "strategy_resolution_failed"
- clickhouse_query_type = clickhouse_query_type or None
-
- used_preaggregated_label = "unknown"
- if response is not None:
- val = getattr(response, "usedPreAggregatedTables", None)
- if val is not None:
- used_preaggregated_label = str(val).lower()
-
- query_strategy_label = query_strategy or "none"
- metric_labels = {
- "query_kind": query_kind,
- "query_strategy": query_strategy_label,
- "used_preaggregated": used_preaggregated_label,
- "breakdown": breakdown_label,
- "has_conversion_goal": has_conversion_goal,
- }
- WEB_ANALYTICS_QUERY_DURATION.labels(**metric_labels).observe(duration_s)
- WEB_ANALYTICS_QUERY_COUNTER.labels(**metric_labels).inc()
-
- if error_type:
- WEB_ANALYTICS_QUERY_ERRORS.labels(
+ response = super().calculate()
+ return response
+ except Exception as exc:
+ error_type = type(exc).__name__
+ raise
+ finally:
+ duration_s = perf_counter() - start
+
+ try:
+ query_strategy = self.query_strategy()
+ clickhouse_query_type = self.clickhouse_query_type()
+ except Exception:
+ query_strategy = query_strategy or "strategy_resolution_failed"
+ clickhouse_query_type = clickhouse_query_type or None
+
+ used_preaggregated_label = "unknown"
+ if response is not None:
+ val = getattr(response, "usedPreAggregatedTables", None)
+ if val is not None:
+ used_preaggregated_label = str(val).lower()
+
+ query_strategy_label = query_strategy or "none"
+ metric_labels = {
+ "query_kind": query_kind,
+ "query_strategy": query_strategy_label,
+ "used_preaggregated": used_preaggregated_label,
+ "breakdown": breakdown_label,
+ "has_conversion_goal": has_conversion_goal,
+ }
+ WEB_ANALYTICS_QUERY_DURATION.labels(**metric_labels).observe(duration_s)
+ WEB_ANALYTICS_QUERY_COUNTER.labels(**metric_labels).inc()
+
+ if error_type:
+ WEB_ANALYTICS_QUERY_ERRORS.labels(
+ query_kind=query_kind,
+ query_strategy=query_strategy_label,
+ breakdown=breakdown_label,
+ error_type=error_type,
+ ).inc()
+
+ sampling = getattr(self.query, "sampling", None)
+ logger.info(
+ "web_analytics_query",
+ team_id=self.team.pk,
+ organization_id=str(self.team.organization_id),
+ user_id=get_query_tag_value("user_id"),
query_kind=query_kind,
- query_strategy=query_strategy_label,
+ query_strategy=query_strategy,
+ clickhouse_query_type=clickhouse_query_type,
breakdown=breakdown_label,
- error_type=error_type,
- ).inc()
+ has_conversion_goal=has_conversion_goal,
+ used_preaggregated=used_preaggregated_label,
+ duration_s=round(duration_s, 4),
+ error=bool(error_type),
+ error_type=error_type or None,
+ filter_count=len(self.query.properties),
+ date_from=self.query_date_range.date_from_str,
+ date_to=self.query_date_range.date_to_str,
+ sampling_enabled=sampling.enabled if sampling else False,
+ )
- sampling = getattr(self.query, "sampling", None)
- logger.info(
- "web_analytics_query",
- team_id=self.team.pk,
- organization_id=str(self.team.organization_id),
- user_id=get_query_tag_value("user_id"),
- query_kind=query_kind,
- query_strategy=query_strategy,
- clickhouse_query_type=clickhouse_query_type,
- breakdown=breakdown_label,
- has_conversion_goal=has_conversion_goal,
- used_preaggregated=used_preaggregated_label,
- duration_s=round(duration_s, 4),
- error=bool(error_type),
- error_type=error_type or None,
- filter_count=len(self.query.properties),
- date_from=self.query_date_range.date_from_str,
- date_to=self.query_date_range.date_to_str,
- sampling_enabled=sampling.enabled if sampling else False,
- )
+ @cached_property
+ def filters_eligibility_hash(self) -> Optional[str]:
+ """Stable hash of the user-facing query inputs that would fragment a
+ precompute cache key. Bound on the structlog contextvars in
+ `calculate()` so every log emitted inside the request — including the
+ framework's `lazy_computation.executed` — carries it automatically and
+ the log streams can be joined for queries-per-distinct-cache-key
+ analysis. See `compute_filters_eligibility_hash` for the exact field set."""
+ try:
+ return compute_filters_eligibility_hash(self.query, self.team.timezone)
+ except Exception:
+ return None
@cached_property
def _timezone_info(self) -> ZoneInfo:
diff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
index 8ad070f91d0f..95dfad93d53c 100644
--- a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
@@ -8,6 +8,8 @@ session-pad / UTC-day helpers. Keeping a single source of truth avoids
the two paths drifting apart.
"""
+import json
+import hashlib
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
@@ -25,6 +27,24 @@ from posthog.models import Team
logger = structlog.get_logger(__name__)
+# Fields stripped from the query payload before hashing.
+# These don't influence which precompute job_id a query would map to —
+# `useWebAnalyticsPrecompute` is just the opt-in toggle, `modifiers` is
+# HogQL execution hints applied after the fact, and the rest are
+# metadata / pagination knobs applied at read time.
+_FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS: frozenset[str] = frozenset(
+ {
+ "useWebAnalyticsPrecompute",
+ "modifiers",
+ "version",
+ "tags",
+ "response",
+ "limit",
+ "offset",
+ "limitBy",
+ }
+)
+
# Hourly UTC bucketing TTL schedule. Today gets 15 min so dashboards stay
# fresh; older buckets get longer TTLs so we don't keep recomputing them.
LAZY_TTL_SECONDS: dict[str, int] = {
@@ -212,6 +232,29 @@ def log_eligibility_outcome(*, log_prefix: str, team_id: int, error: Optional[La
logger.info(f"{log_prefix}_eligible", team_id=team_id)
+def compute_filters_eligibility_hash(query: Any, team_timezone: str) -> str:
+ """Stable hash over the user-facing inputs that would fragment a precompute cache key.
+
+ Emitted on the `web_analytics_query` and `lazy_computation.executed` structured
+ log lines so the two can be joined and queries-per-distinct-cache-key (`q/key`)
+ can be measured over multi-day windows — including for queries that didn't
+ go through the lazy precompute path (different eligibility gating, different
+ runner) but would have shared a job_id if they had.
+
+ Same hashing mechanic as `compute_query_hash` in lazy_computation_executor
+ (SHA-256 over canonical JSON). It is **not** numerically identical to the
+ precompute job's `query_hash` — that one hashes the post-build INSERT AST —
+ but it fragments along the same logical dimensions: query kind, property
+ filters (with values), date range, breakdown, conversion goal, sampling,
+ interval, compare filter, test-accounts toggle, and team timezone.
+ """
+ dumped = query.model_dump(mode="json", exclude_none=True, by_alias=False)
+ for key in _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS:
+ dumped.pop(key, None)
+ payload = {"query": dumped, "timezone": team_timezone}
+ return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()
+
+
def host_filter_expr(properties: list) -> ast.Expr:
"""Translate the (gated-down-to-≤1) user filter list to an AST expression.