: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): serve active hours heatmap from precompute buckets (#75710)
Lucas Ricoyfdc4cd919376
diff --git a/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.py b/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.pyindex 89777da38161..d2f55846a6e3 100644--- a/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/calendar_heatmap_trends_query_runner.py@@ -1,4 +1,12 @@-from posthog.schema import CalendarHeatmapQuery, ResolvedDateRangeResponse, TrendsQueryResponse+from typing import Optional++from posthog.schema import (+ CalendarHeatmapQuery,+ EventsHeatMapStructuredResult,+ QueryTiming,+ ResolvedDateRangeResponse,+ TrendsQueryResponse,+)from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner@@ -38,7 +46,21 @@ class CalendarHeatmapTrendsQueryRunner(TrendsQueryRunner):calendar_response = calendar_runner._calculate()- # Convert calendar response to trends response format+ return self._wrap_calendar_results(+ calendar_response.results,+ timings=calendar_response.timings,+ hogql=calendar_response.hogql,+ )++ def _wrap_calendar_results(+ self,+ results: EventsHeatMapStructuredResult,+ *,+ timings: Optional[list[QueryTiming]] = None,+ hogql: Optional[str] = None,+ ) -> TrendsQueryResponse:+ """Wrap an EventsHeatMapStructuredResult in the TrendsQueryResponse shape+ the frontend's heatmap visualization consumes."""return TrendsQueryResponse(results=[{@@ -51,13 +73,13 @@ class CalendarHeatmapTrendsQueryRunner(TrendsQueryRunner):},"label": self.series_event(self.query.series[0]) if self.query.series else "Heatmap","data": [], # Empty array for non-time-series data- "aggregated_value": calendar_response.results.allAggregations,- "calendar_heatmap_data": calendar_response.results, # Store the original heatmap data- "count": calendar_response.results.allAggregations,+ "aggregated_value": results.allAggregations,+ "calendar_heatmap_data": results, # Store the original heatmap data+ "count": results.allAggregations,}],- timings=calendar_response.timings,- hogql=calendar_response.hogql,+ timings=timings,+ hogql=hogql,modifiers=self.modifiers,resolved_date_range=ResolvedDateRangeResponse(date_from=self.query_date_range.date_from(),diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex d9b5961c4e40..6719fe69b535 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -521,6 +521,26 @@ def get_query_runner(display_type = get_from_dict_or_attr(trends_filter, "display") if trends_filter else Noneif display_type == ChartDisplayType.CALENDAR_HEATMAP:+ query_tags = get_from_dict_or_attr(query_obj, "tags")+ if query_tags and get_from_dict_or_attr(query_tags, "productKey") == "web_analytics":+ from products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute import (+ is_trends_precompute_enabled_for_team,+ )++ if is_trends_precompute_enabled_for_team(team):+ from products.web_analytics.backend.hogql_queries.web_calendar_heatmap import (+ WebCalendarHeatmapTrendsQueryRunner,+ )++ return WebCalendarHeatmapTrendsQueryRunner(+ query=query_obj,+ team=team,+ timings=timings,+ limit_context=limit_context,+ modifiers=modifiers,+ user=user,+ )+from .insights.trends.calendar_heatmap_trends_query_runner import CalendarHeatmapTrendsQueryRunnerreturn CalendarHeatmapTrendsQueryRunner(diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex eb26e951fc98..6e2c80665cb9 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -277,9 +277,9 @@ Because the eager job and the lazy read path consult the same flag, the warmingThis job is complementary to `cache_warming.py`, which replays whatever queries users actually ran in the last N days. The eager job covers the fixed UI matrix; the replay job covers the long tail of team-specific filter combinations.-## Trend tiles (precompute-backed trends)+## Trend tiles and Active Hours (precompute-backed trends)-The dashboard's graph tiles run vanilla `TrendsQuery`, routed at dispatch to `WebTrendsQueryRunner` when the query carries `tags.productKey == "web_analytics"` AND the `web-analytics-trends-precompute` flag (locally evaluated, fails closed) is on for the team. The runner serves eligible single-series shapes — unique visitors, page views, sessions, avg session duration, bounce rate — from the same hourly `web_overview_preaggregated` buckets the overview tile keeps warm (the query is mapped to an inner `WebOverviewQuery`, so the precompute job hash is identical and buckets are shared), and falls back to the standard trends path for everything else.+The dashboard's graph tiles run vanilla `TrendsQuery`, routed at dispatch to `WebTrendsQueryRunner` when the query carries `tags.productKey == "web_analytics"` AND the `web-analytics-trends-precompute` flag (locally evaluated, fails closed) is on for the team. The runner serves eligible single-series shapes — unique visitors, page views, sessions, avg session duration, bounce rate — from the same hourly `web_overview_preaggregated` buckets the overview tile keeps warm (the query is mapped to an inner `WebOverviewQuery`, so the precompute job hash is identical and buckets are shared), and falls back to the standard trends path for everything else. The Active Hours unique-visitors tab is served the same way by `WebCalendarHeatmapTrendsQueryRunner`.Rollout gates, in order:@@ -289,6 +289,8 @@ Rollout gates, in order:Accepted semantic differences vs vanilla trends (the tiles align with the overview tile instead): session-start-hour attribution, HLL uniques, `$pageview + $screen` counted together, sessionless events excluded. The per-query "Allow precompute" opt-out does not reach trend tiles (TrendsQuery deliberately carries no web-analytics fields); the flag is the kill switch.+The Active Hours path is stricter than the trend tiles: it falls back to the live heatmap for teams that track both `$pageview` and `$screen` (the buckets carry no event dimension, and the live heatmap filters exactly to the requested event), for teams aggregating by distinct ID, and for date bounds that are not hour-aligned in UTC (explicit sub-hour ranges, fractional-offset timezones).+## Related code- `products/web_analytics/backend/hogql_queries/web_overview.py` — runner@@ -303,5 +305,6 @@ Accepted semantic differences vs vanilla trends (the tiles align with the overvi- `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` — vitals lazy path- `posthog/clickhouse/preaggregation/web_vitals_paths_preaggregated_sql.py` — vitals schema- `products/web_analytics/backend/hogql_queries/web_trends.py` + `web_trends_lazy_precompute.py` — trend tiles lazy path+- `products/web_analytics/backend/hogql_queries/web_calendar_heatmap.py` — Active Hours lazy path- `products/analytics_platform/backend/lazy_computation/` — framework + CONSISTENCY.md + README- `products/web_analytics/dags/eager_web_analytics_precompute.py` — hourly baseline pre-warmerdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_calendar_heatmap_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_calendar_heatmap_lazy_precompute.pynew file mode 100644index 000000000000..f5b9c55782b8--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_web_calendar_heatmap_lazy_precompute.py@@ -0,0 +1,170 @@+from collections.abc import Iterator+from contextlib import ExitStack, contextmanager++from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person+from unittest.mock import patch++from django.test import override_settings++from parameterized import parameterized++from posthog.schema import (+ CalendarHeatmapFilter,+ ChartDisplayType,+ DateRange,+ EventsHeatMapStructuredResult,+ EventsNode,+ TrendsFilter,+ TrendsQuery,+)++from posthog.clickhouse.client import sync_execute+from posthog.hogql_queries.insights.trends.calendar_heatmap_trends_query_runner import CalendarHeatmapTrendsQueryRunner+from posthog.hogql_queries.query_runner import get_query_runner+from posthog.models import EventDefinition+from posthog.models.utils import uuid7++from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.web_analytics.backend.hogql_queries.web_calendar_heatmap import WebCalendarHeatmapTrendsQueryRunner+++@override_settings(IN_UNIT_TESTING=True)+class TestWebCalendarHeatmapLazyPrecompute(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_overview_preaggregated")++ @contextmanager+ def _enable(self) -> Iterator[None]:+ with patch(+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",+ return_value=True,+ ):+ yield++ def _seed(self) -> None:+ # Two sessions on different weekdays/hours plus a second visitor sharing+ # one cell — exercises cell dedupe, row/column rollups, and the total.+ # 2024-01-02 is a Tuesday (dow 2), 2024-01-03 a Wednesday (dow 3).+ _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={})+ _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={})+ s1 = str(uuid7("2024-01-02"))+ s2 = str(uuid7("2024-01-03"))+ s3 = str(uuid7("2024-01-02"))+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p1",+ timestamp="2024-01-02T10:00:00Z",+ properties={"$session_id": s1, "$host": "example.com"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p1",+ timestamp="2024-01-03T15:00:00Z",+ properties={"$session_id": s2, "$host": "example.com"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p2",+ timestamp="2024-01-02T10:30:00Z",+ properties={"$session_id": s3, "$host": "example.com"},+ )++ def _build_query(self, unique_tab: bool = True) -> TrendsQuery:+ return TrendsQuery(+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-07"),+ series=[EventsNode(event="$pageview", math="dau" if unique_tab else "total")],+ trendsFilter=TrendsFilter(display=ChartDisplayType.CALENDAR_HEATMAP),+ calendarHeatmapFilter=CalendarHeatmapFilter(bucketBySessionStart=True) if unique_tab else None,+ properties=[],+ )++ @staticmethod+ def _heatmap_as_dicts(+ structured: EventsHeatMapStructuredResult,+ ) -> tuple[set[tuple[int, int, int]], set[tuple[int, int]], set[tuple[int, int]], int]:+ cells = {(d.row, d.column, d.value) for d in structured.data}+ rows = {(r.row, r.value) for r in structured.rowAggregations}+ cols = {(c.column, c.value) for c in structured.columnAggregations}+ return cells, rows, cols, structured.allAggregations++ @freeze_time("2024-01-15T12:00:00Z")+ def test_unique_tab_matches_live_calendar_heatmap(self) -> None:+ self._seed()+ query = self._build_query(unique_tab=True)++ live = CalendarHeatmapTrendsQueryRunner(team=self.team, query=query).calculate()++ with self._enable():+ precomputed = WebCalendarHeatmapTrendsQueryRunner(team=self.team, query=query).calculate()++ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0+ live_hm = live.results[0]["calendar_heatmap_data"]+ pre_hm = precomputed.results[0]["calendar_heatmap_data"]+ assert self._heatmap_as_dicts(pre_hm) == self._heatmap_as_dicts(live_hm)+ assert precomputed.results[0]["count"] == live.results[0]["count"]++ @freeze_time("2024-01-15T12:00:00Z")+ def test_total_events_tab_falls_back(self) -> None:+ # The total tab buckets by raw event timestamp; the session-start-keyed+ # buckets can't reproduce that, so serving it would shift midnight- and+ # hour-spanning activity into wrong cells. It must take the live path.+ self._seed()+ query = self._build_query(unique_tab=False)+ with self._enable():+ response = WebCalendarHeatmapTrendsQueryRunner(team=self.team, query=query).calculate()+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0+ assert response.results[0]["count"] > 0++ @parameterized.expand(+ [+ ("distinct_id_aggregation",),+ ("mixed_event_types",),+ ("sub_hour_range",),+ ]+ )+ def test_falls_back_when_buckets_cannot_reproduce_live_semantics(self, case: str) -> None:+ with ExitStack() as stack:+ stack.enter_context(freeze_time("2024-01-15T12:00:00Z"))+ self._seed()+ query = self._build_query()+ if case == "distinct_id_aggregation":+ stack.enter_context(+ patch.object(type(self.team), "aggregate_users_by_distinct_id", property(lambda self: True))+ )+ elif case == "mixed_event_types":+ EventDefinition.objects.create(team=self.team, name="$screen")+ else:+ query.dateRange = DateRange(+ date_from="2024-01-02T10:15:00", date_to="2024-01-02T12:45:00", explicitDate=True+ )+ stack.enter_context(self._enable())+ response = WebCalendarHeatmapTrendsQueryRunner(team=self.team, query=query).calculate()+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0+ assert response.results[0]["count"] > 0++ def test_dispatch_routes_wa_tagged_heatmap_queries(self) -> None:+ tagged = self._build_query().model_dump()+ tagged["tags"] = {"productKey": "web_analytics"}+ with override_settings(WEB_ANALYTICS_TRENDS_PRECOMPUTE_TEAM_IDS=[self.team.pk]):+ assert isinstance(get_query_runner(tagged, self.team), WebCalendarHeatmapTrendsQueryRunner)++ # Flag off: even tagged queries stay on the untouched vanilla wrapper.+ flag_off = patch(+ "products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=False,+ )+ with flag_off:+ runner = get_query_runner(tagged, self.team)+ assert isinstance(runner, CalendarHeatmapTrendsQueryRunner)+ assert not isinstance(runner, WebCalendarHeatmapTrendsQueryRunner)++ with override_settings(WEB_ANALYTICS_TRENDS_PRECOMPUTE_TEAM_IDS=[self.team.pk]):+ runner = get_query_runner(self._build_query(), self.team)+ assert isinstance(runner, CalendarHeatmapTrendsQueryRunner)+ assert not isinstance(runner, WebCalendarHeatmapTrendsQueryRunner)diff --git a/products/web_analytics/backend/hogql_queries/web_calendar_heatmap.py b/products/web_analytics/backend/hogql_queries/web_calendar_heatmap.pynew file mode 100644index 000000000000..bd06a04f272e--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_calendar_heatmap.py@@ -0,0 +1,266 @@+import time+from datetime import UTC, datetime+from typing import Optional++import structlog+from prometheus_client import Counter++from posthog.schema import (+ EventsHeatMapColumnAggregationResult,+ EventsHeatMapDataResult,+ EventsHeatMapRowAggregationResult,+ EventsHeatMapStructuredResult,+ EventsNode,+ TrendsQuery,+ TrendsQueryResponse,+)++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (+ DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE,+)+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.hogql_queries.insights.trends.calendar_heatmap_trends_query_runner import CalendarHeatmapTrendsQueryRunner+from posthog.models import EventDefinition++from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS,+ can_use_lazy_precompute as _can_use_lazy_precompute_shared,+ ceil_utc_day,+ floor_utc_day,+)+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ handle_stale_served,+ is_precompute_enabled_for_team,+)+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner+from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (+ _READ_SETTINGS,+ ensure_web_overview_precomputed,+)+from products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute import (+ build_inner_overview_query,+ is_trends_precompute_enabled_for_team,+)++logger = structlog.get_logger(__name__)++_FAMILY = "web_calendar_heatmap"++WEB_CALENDAR_HEATMAP_LAZY_FAILED = Counter(+ "web_calendar_heatmap_lazy_precompute_failed_total",+ "Web calendar heatmap lazy precompute path failures, by error class",+ ["error_type"],+)++# grouping() markers disambiguate the aggregation levels: hour 0 / dow 1 are+# real values, so the cell rows can't be told apart from the rollup rows by+# their defaults alone.+_HEATMAP_READ_SQL_TEMPLATE = """+SELECT+ grouping(dow) AS g_dow,+ grouping(hour) AS g_hour,+ toDayOfWeek(toTimeZone(time_window_start, %(tz)s)) AS dow,+ toHour(toTimeZone(time_window_start, %(tz)s)) AS hour,+ uniqMerge(uniq_users_state) AS value+FROM {table}+WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s+ AND time_window_start >= %(range_start)s AND time_window_start < %(range_end)s+GROUP BY GROUPING SETS ((dow, hour), (dow), (hour), ())+"""+++def heatmap_precompute_servable(query: TrendsQuery) -> bool:+ """Only the Active Hours unique-visitors tab is servable: it buckets by+ session start (matching the buckets' attribution) and counts unique+ persons (matching `uniq_users_state`). The total-events tab buckets by raw+ event timestamp, which the session-start-keyed buckets can't reproduce."""+ if len(query.series) != 1:+ return False+ series = query.series[0]+ if not isinstance(series, EventsNode):+ return False+ if series.event not in ("$pageview", "$screen"):+ return False+ if series.math != "dau":+ return False+ if series.fixedProperties:+ return False+ if query.conversionGoal is not None:+ return False+ if query.aggregation_group_type_index is not None:+ return False+ if query.samplingFactor is not None:+ return False+ chf = getattr(query, "calendarHeatmapFilter", None)+ if chf is None or not chf.bucketBySessionStart:+ return False+ if query.properties is not None and not isinstance(query.properties, list):+ return False+ return True+++def _hour_aligned_bounds(start_utc: datetime, end_utc: datetime) -> bool:+ """The read filters whole hourly buckets, so a bound inside an hour would+ silently include or drop up to an hour of sessions vs the live path's exact+ timestamp filter. The end bound may also be an inclusive hour-end+ (…:59:59.xxxxxx), which covers its final bucket exactly."""+ if start_utc.minute or start_utc.second or start_utc.microsecond:+ return False+ if end_utc.minute == 59 and end_utc.second == 59:+ return True+ return end_utc.minute == 0 and end_utc.second == 0 and end_utc.microsecond == 0+++def _assemble_structured_result(rows: list[tuple[int, int, int, int, int]]) -> EventsHeatMapStructuredResult:+ data: list[EventsHeatMapDataResult] = []+ row_aggs: list[EventsHeatMapRowAggregationResult] = []+ col_aggs: list[EventsHeatMapColumnAggregationResult] = []+ total = 0+ for g_dow, g_hour, dow, hour, value in rows:+ value = int(value)+ if g_dow == 0 and g_hour == 0:+ data.append(EventsHeatMapDataResult(row=int(dow), column=int(hour), value=value))+ elif g_dow == 0 and g_hour == 1:+ row_aggs.append(EventsHeatMapRowAggregationResult(row=int(dow), value=value))+ elif g_dow == 1 and g_hour == 0:+ col_aggs.append(EventsHeatMapColumnAggregationResult(column=int(hour), value=value))+ else:+ total = value+ return EventsHeatMapStructuredResult(+ data=data, rowAggregations=row_aggs, columnAggregations=col_aggs, allAggregations=total+ )+++def execute_lazy_precomputed_heatmap(+ runner: "WebCalendarHeatmapTrendsQueryRunner",+) -> Optional[EventsHeatMapStructuredResult]:+ """Serve the Active Hours heatmap from the shared web_overview preagg+ buckets. Returns None on any ineligibility/miss (caller falls back)."""+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)+ team = runner.team+ overall_started = time.perf_counter()+ try:+ if not heatmap_precompute_servable(runner.query):+ return None+ if not is_trends_precompute_enabled_for_team(team):+ return None++ # The buckets store person-id uniq states, which cannot represent+ # distinct-id aggregation, so keep these teams on the live path.+ if team.aggregate_users_by_distinct_id:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="distinct_id_aggregation").inc()+ return None++ series = runner.query.series[0]+ assert isinstance(series, EventsNode) # guaranteed by heatmap_precompute_servable+ props = list(runner.query.properties or [])+ if series.properties:+ props.extend(series.properties)++ # The buckets aggregate $pageview and $screen into one uniq state with+ # no event dimension, while the live path filters exactly to+ # series.event. Serving is only faithful when the team tracks just the+ # requested event, so fall back if the other one has ever been seen.+ other_event = "$screen" if series.event == "$pageview" else "$pageview"+ if EventDefinition.objects.filter(team=team, name=other_event).exists():+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="mixed_event_types").inc()+ return None++ inner_query = build_inner_overview_query(runner.query, props)+ inner_runner = WebOverviewQueryRunner(query=inner_query, team=team, modifiers=runner.modifiers)++ if not _can_use_lazy_precompute_shared(inner_runner, log_prefix=_FAMILY):+ return None++ date_from = runner.query_date_range.date_from()+ date_to = runner.query_date_range.date_to()+ assert date_from is not None and date_to is not None+ start_utc = date_from.astimezone(UTC)+ end_utc = date_to.astimezone(UTC)++ # Covers explicit sub-hour date bounds and timezones with fractional+ # UTC offsets, both of which put a bound inside a bucket.+ if not _hour_aligned_bounds(start_utc, end_utc):+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="sub_hour_range").inc()+ return None++ time_range_start = floor_utc_day(start_utc)+ time_range_end = ceil_utc_day(end_utc)+ if time_range_start >= time_range_end:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="empty_range").inc()+ return None++ result = ensure_web_overview_precomputed(+ runner=inner_runner,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ )+ if result.stale:+ # Family web_overview on purpose: the shared buckets are refreshed+ # by one debounced overview re-run.+ handle_stale_served(runner=inner_runner, family="web_overview")+ if not result.job_ids:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="no_job_ids").inc()+ return None+ if not result.ready:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="current_not_ready").inc()+ return None++ sql = _HEATMAP_READ_SQL_TEMPLATE.format(table=DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE())+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY, query_type="web_calendar_heatmap_lazy_query")+ rows = sync_execute(+ sql,+ {+ "team_id": team.pk,+ "job_ids": tuple(str(jid) for jid in result.job_ids),+ "tz": team.timezone,+ "range_start": start_utc,+ "range_end": end_utc,+ },+ settings=_READ_SETTINGS,+ team_id=team.pk,+ )++ structured = _assemble_structured_result(rows)+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=_FAMILY).inc()+ logger.info(+ "web_calendar_heatmap_lazy_precompute_completed",+ team_id=team.pk,+ job_count=len(result.job_ids),+ cells=len(structured.data),+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return structured+ except Exception as exc:+ WEB_CALENDAR_HEATMAP_LAZY_FAILED.labels(error_type=type(exc).__name__).inc()+ logger.exception(+ "web_calendar_heatmap_lazy_precompute_failed",+ team_id=team.pk,+ error_type=type(exc).__name__,+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return None+++class WebCalendarHeatmapTrendsQueryRunner(CalendarHeatmapTrendsQueryRunner):+ """Active Hours runner for web-analytics-tagged calendar heatmap queries.+ Serves the unique-visitors tab from the shared web_overview precompute+ buckets and falls back to the live calendar heatmap path otherwise."""++ def get_cache_payload(self) -> dict:+ payload = super().get_cache_payload()+ # Rollout state in the cache key = immediate kill switch: disabling a+ # flag must not keep serving cached precompute-derived results until+ # they stale out (same mechanism as WebTrendsQueryRunner).+ payload["web_trends_precompute"] = is_trends_precompute_enabled_for_team(+ self.team+ ) and is_precompute_enabled_for_team(self.team)+ return payload++ def _calculate(self) -> TrendsQueryResponse:+ structured = execute_lazy_precomputed_heatmap(self)+ if structured is None:+ return super()._calculate()+ return self._wrap_calendar_results(structured, timings=self.timings.to_list(), hogql=None)