: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
fix(web-analytics): stitch live today into precomputed trend charts (#91056)
Lucas Ricoyc4e9fcc33c73
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.pyindex 12250e09a7bb..a2cd057dd3af 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py@@ -1,10 +1,12 @@from dataclasses import replace+from datetime import datetime+from zoneinfo import ZoneInfofrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_personfrom unittest.mock import patch-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized@@ -32,10 +34,76 @@ from products.web_analytics.backend.hogql_queries.web_overview import WebOverviefrom products.web_analytics.backend.hogql_queries.web_trends import WebTrendsQueryRunnerfrom products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute import (WebTrendsMetric,+ _current_period_boundary,build_inner_overview_query,trends_precompute_metric,)+_UTC = ZoneInfo("UTC")+++def _d(year: int, month: int, day: int, hour: int = 0) -> datetime:+ return datetime(year, month, day, hour, tzinfo=_UTC)+++class TestCurrentPeriodBoundary(SimpleTestCase):+ @parameterized.expand(+ [+ # The boundary is the start of the first still-evolving bucket. Below+ # it precompute serves; at or above it the live tail does. Snapping to+ # the containing week/month start is what sends a whole in-progress+ # period live instead of only its trailing day.+ (+ "day_today_in_range",+ [_d(2024, 1, x) for x in range(10, 17)],+ _d(2024, 1, 16),+ _d(2024, 1, 15),+ _d(2024, 1, 15),+ ),+ # Range ends before today: nothing is evolving, so the boundary sits+ # past every bucket and the whole range stays on precompute.+ (+ "fully_historical",+ [_d(2024, 1, x) for x in range(1, 8)],+ _d(2024, 1, 7),+ _d(2024, 1, 15),+ _d(2024, 1, 15),+ ),+ # Today is mid-week (Jan 17); the boundary snaps back to the Monday+ # bucket so the in-progress week reads live.+ (+ "week_snaps_back",+ [_d(2023, 12, 25), _d(2024, 1, 1), _d(2024, 1, 8), _d(2024, 1, 15)],+ _d(2024, 1, 17),+ _d(2024, 1, 17),+ _d(2024, 1, 15),+ ),+ (+ "month_snaps_back",+ [_d(2023, 11, 1), _d(2023, 12, 1), _d(2024, 1, 1)],+ _d(2024, 1, 15),+ _d(2024, 1, 15),+ _d(2024, 1, 1),+ ),+ # A single-bucket "today" range has no settled portion; the boundary+ # equals that bucket, and the caller falls fully back to live.+ ("today_only", [_d(2024, 1, 15)], _d(2024, 1, 15), _d(2024, 1, 15), _d(2024, 1, 15)),+ # Hourly range whose tail is today: the boundary is today's midnight,+ # so every hour of today reads live.+ (+ "hour_today",+ [_d(2024, 1, 14, h) for h in range(24)] + [_d(2024, 1, 15, h) for h in range(13)],+ _d(2024, 1, 15, 12),+ _d(2024, 1, 15),+ _d(2024, 1, 15),+ ),+ ]+ )+ def test_boundary(+ self, _name: str, buckets: list[datetime], date_to: datetime, today_start: datetime, expected: datetime+ ) -> None:+ assert _current_period_boundary(buckets, date_to, today_start) == expected+@override_settings(IN_UNIT_TESTING=True)class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):@@ -79,6 +147,21 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):properties={"$session_id": s2, "$host": "other.com", "$current_url": "https://other.com/x"},)+ def _seed_span(self) -> None:+ # One historical day inside the range and one on the frozen "today"+ # (2024-01-15). Each is a single-day session, so session-start and+ # event-time attribution agree and both paths return identical data.+ for day, distinct, host in (("2024-01-12", "p_hist", "example.com"), ("2024-01-15", "p_today", "other.com")):+ _create_person(team_id=self.team.pk, distinct_ids=[distinct], properties={})+ sid = str(uuid7(day))+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=distinct,+ timestamp=f"{day}T09:00:00Z",+ properties={"$session_id": sid, "$host": host, "$current_url": f"https://{host}/x"},+ )+def _build_query(self,math: str = "dau",@@ -383,6 +466,43 @@ class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):assert mock_stale.calledassert mock_stale.call_args.kwargs["family"] == "web_overview"+ @freeze_time("2024-01-15T12:00:00Z")+ def test_today_spanning_range_stitches_live_tail(self) -> None:+ # A range whose last bucket is "today": settled days come from precompute,+ # today comes from the live tail. If the tail merge keyed buckets wrong,+ # today would zero-fill and the served series would diverge from live.+ self._seed_span()+ query = self._build_query()+ query.dateRange = DateRange(date_from="2024-01-10", date_to="2024-01-15")++ live = TrendsQueryRunner(team=self.team, query=query).calculate()+ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=query).calculate()++ assert precomputed.results[0]["data"] == live.results[0]["data"]+ assert precomputed.results[0]["days"] == live.results[0]["days"]+ assert precomputed.results[0]["labels"] == live.results[0]["labels"]+ # Today (last bucket) is the live tail, not a zero-fill.+ assert precomputed.results[0]["data"][-1] == 1+ # Settled days were still precomputed — the path did not fully fall back.+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_today_only_range_falls_back_to_live(self) -> None:+ # The whole range is the in-progress day, so nothing is settled enough to+ # precompute: the path bails to live and mints no precompute jobs.+ self._seed_span()+ query = self._build_query()+ query.dateRange = DateRange(date_from="2024-01-15", date_to="2024-01-15")++ live = TrendsQueryRunner(team=self.team, query=query).calculate()+ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=query).calculate()++ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0+ assert precomputed.results[0]["data"] == live.results[0]["data"]+ assert sum(precomputed.results[0]["data"]) == 1+@freeze_time("2024-01-15T12:00:00Z")def test_week_interval_zero_fills_full_range(self) -> None:self._seed()diff --git a/products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.pyindex 5cf67c8b73f9..b54c6c552397 100644--- a/products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.py@@ -2,8 +2,10 @@ import timefrom datetime import UTC, datetimefrom enum import Enumfrom typing import TYPE_CHECKING, Any, Optional+from zoneinfo import ZoneInfofrom django.conf import settings+from django.utils import timezone as django_timezoneimport structlogimport posthoganalytics@@ -24,6 +26,7 @@ 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.trends_query_runner import TrendsQueryRunnerfrom posthog.hogql_queries.query_runner import resolve_series_custom_namefrom posthog.hogql_queries.utils.timestamp_utils import format_label_datefrom posthog.models.team import Team@@ -328,10 +331,60 @@ def _series_dict(return series_object+def _current_period_boundary(cur_buckets: list[datetime], date_to: datetime, today_start_local: datetime) -> datetime:+ """Start of the first bucket that is still evolving — today, or the in-progress+ week/month that contains today.++ Buckets at or after this boundary must be read live, not from precompute: the+ today band's TTL lets a precompute bucket stay "fresh" while hours behind, so the+ latest hours are absent and would render as a flat, low tail on the chart.+ Snaps back to the containing bucket's start so a whole in-progress week/month goes+ live. Returns a value after every bucket when the range ends before today, keeping+ a fully historical range entirely on the precompute path.+ """+ if today_start_local > date_to:+ return today_start_local+ boundary = today_start_local+ for bucket in cur_buckets:+ if bucket <= today_start_local:+ boundary = bucket+ else:+ break+ return boundary+++def _live_tail_values(+ *, runner: "WebTrendsQueryRunner", live_from: datetime, date_to: datetime+) -> dict[datetime, float]:+ """Per-bucket values for the in-progress tail, read from the live trends path so+ the current period reflects events newer than the last precompute build.++ Runs the base `TrendsQueryRunner` directly (never `get_query_runner`), so the WA+ dispatch can't re-enter this precompute path. Keyed by naive team-local bucket+ start to match `_series_dict`.+ """+ live_query = runner.query.model_copy(deep=True)+ live_query.dateRange = DateRange(date_from=live_from.isoformat(), date_to=date_to.isoformat(), explicitDate=True)+ live_query.compareFilter = None+ live_runner = TrendsQueryRunner(query=live_query, team=runner.team, modifiers=runner.modifiers)+ response = live_runner.calculate()+ if not response.results:+ return {}+ data = response.results[0].get("data") or []+ buckets = live_runner.query_date_range.all_values()+ return {bucket.replace(tzinfo=None): float(value) for bucket, value in zip(buckets, data)}++def execute_lazy_precomputed_trends(runner: "WebTrendsQueryRunner") -> Optional[list[dict[str, Any]]]:"""Serve the trends series from the shared web_overview preagg buckets.Returns the formatted results list, or None on any ineligibility/miss (the- caller falls back to the live trends path)."""+ caller falls back to the live trends path).++ The current period is stitched: buckets before the in-progress period come from+ precompute, and the in-progress tail (today, or the current week/month) is read+ live so recent hours are never zero-filled. The compare period is always fully in+ the past, so it stays entirely on the precompute path.+ """tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)team = runner.teamoverall_started = time.perf_counter()@@ -381,8 +434,26 @@ def execute_lazy_precomputed_trends(runner: "WebTrendsQueryRunner") -> Optional[cur_start_utc = cur_buckets[0].astimezone(UTC)cur_end_utc = cur_to.astimezone(UTC)+ # Split the current range at the in-progress period: precompute serves the+ # settled buckets, the live path serves the evolving tail (see the boundary+ # helper). Reading the tail from precompute is what produced the flat, low+ # recent buckets — the precompute build lags the latest hours.+ now_local = django_timezone.now().astimezone(ZoneInfo(runner.team.timezone))+ today_start_local = now_local.replace(hour=0, minute=0, second=0, microsecond=0)+ live_from = _current_period_boundary(cur_buckets, cur_to, today_start_local)+ settled_buckets = [bucket for bucket in cur_buckets if bucket < live_from]+ serve_live_tail = len(settled_buckets) < len(cur_buckets)+ if serve_live_tail and not settled_buckets:+ # The whole requested range is the in-progress period (e.g. a "Today"+ # view): nothing is settled enough to precompute, so serve it all live.+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="current_period_only").inc()+ return None++ # Precompute only ever covers the settled portion of the current range.+ current_read_end_utc = live_from.astimezone(UTC) if serve_live_tail else cur_end_utc+time_range_start = floor_utc_day(cur_start_utc)- time_range_end = ceil_utc_day(cur_end_utc)+ time_range_end = ceil_utc_day(current_read_end_utc)if time_range_start >= time_range_end:WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="empty_range").inc()return None@@ -448,8 +519,10 @@ def execute_lazy_precomputed_trends(runner: "WebTrendsQueryRunner") -> Optional[interval=interval,job_ids=job_ids,range_start_utc=cur_start_utc,- range_end_utc=cur_end_utc,+ range_end_utc=current_read_end_utc,)+ if serve_live_tail:+ current_values = {**current_values, **_live_tail_values(runner=runner, live_from=live_from, date_to=cur_to)}results.append(_series_dict(runner, metric_values=current_values, date_range=runner.query_date_range, is_previous=False))