: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): forced refresh expires the current-day precompute band (#86699)
Lucas Ricoy11c9c2502a43
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.pyindex 6406db6abb47..3a1ec923c160 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@@ -1,9 +1,11 @@from datetime import UTC, datetime+from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixinfrom unittest import mockfrom django.test import override_settings+from django.utils import timezone as django_timezonefrom parameterized import parameterizedfrom structlog.contextvars import get_contextvars@@ -563,6 +565,80 @@ class TestWebEnsurePrecomputed(BaseTest):web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)assert mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"] == expected_grace+ @parameterized.expand(+ [+ # A fresh-enough current-day bucket is still hours coarse (today band+ # is 4h), which an hourly graph renders as missing recent data. On a+ # forced refresh the current day must read as expired so the request+ # falls through to the live query instead of the coarse bucket.+ ("forced", ExecutionMode.CALCULATE_BLOCKING_ALWAYS.value, None, True),+ # The SWR revalidation task also runs under the forced execution mode,+ # and on background triggers the schedule sets the insert TTL too. The+ # override must not apply there, or the rebuilt current-day bucket+ # persists with a 1-second expiry that every ambient read misses.+ ("forced_background", ExecutionMode.CALCULATE_BLOCKING_ALWAYS.value, REVALIDATION_TRIGGER, False),+ ("not_forced", ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE.value, None, False),+ ]+ )+ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_forced_refresh_expires_current_day_band(+ self, _name, execution_mode, trigger, expect_override, mock_ensure+ ):+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])+ reset_query_tags()+ tags = {"execution_mode": execution_mode}+ if trigger is not None:+ tags["trigger"] = trigger+ with tags_context(**tags):+ web_ensure_precomputed(team=self.team, ttl_seconds={"0d": 4 * 3600, "default": 3600}, table=None)+ schedule = mock_ensure.call_args.kwargs["ttl_seconds"]+ first_cutoff, first_ttl = schedule.rules[0]+ if expect_override:+ assert first_ttl == 1+ assert first_cutoff.hour == 0 and first_cutoff.minute == 0+ assert schedule.get_ttl(django_timezone.now()) == 1+ else:+ assert first_ttl == 4 * 3600+ assert schedule.get_ttl(django_timezone.now()) == 4 * 3600++ @parameterized.expand(+ [+ # Jobs split on UTC day boundaries. For a team behind UTC the+ # current-day window starts before local midnight, and for a team+ # ahead of UTC the local morning lives in the previous UTC window;+ # a cutoff at local midnight itself misses those windows and Reload+ # keeps serving the coarse bucket.+ (+ "behind_utc",+ "America/Sao_Paulo",+ [datetime(2026, 8, 20, tzinfo=UTC)],+ datetime(2026, 8, 19, tzinfo=UTC),+ ),+ (+ "ahead_of_utc",+ "Asia/Tokyo",+ [datetime(2026, 8, 19, tzinfo=UTC), datetime(2026, 8, 20, tzinfo=UTC)],+ datetime(2026, 8, 18, tzinfo=UTC),+ ),+ ]+ )+ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_forced_cutoff_expires_utc_windows_overlapping_local_day(+ self, _name, tz, expired_window_starts, fresh_window_start, mock_ensure+ ):+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])+ reset_query_tags()+ self.team.timezone = tz+ with (+ freeze_time("2026-08-20T12:00:00Z"),+ tags_context(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS.value),+ ):+ web_ensure_precomputed(team=self.team, ttl_seconds={"0d": 4 * 3600, "default": 3600}, table=None)+ schedule = mock_ensure.call_args.kwargs["ttl_seconds"]+ for window_start in expired_window_starts:+ assert schedule.get_ttl(window_start) == 1+ assert schedule.get_ttl(fresh_window_start) == 3600+class TestStaleRevalidationEnqueue(BaseTest):def setUp(self):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.pyindex f12e62ae1133..782848238ae4 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@@ -15,8 +15,10 @@ from collections.abc import Callablefrom dataclasses import replacefrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional+from zoneinfo import ZoneInfofrom django.conf import settings+from django.utils import timezone as django_timezoneimport structlogimport posthoganalytics@@ -353,8 +355,9 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResulrunner = kwargs.pop("runner", None)family = kwargs.pop("family", None)background = is_background_warming_request()+ forced = is_forced_refresh_request()if "stale_while_revalidate_seconds" not in kwargs:- if is_forced_refresh_request():+ if forced:# An explicit user-initiated force refresh must never be handed a# complete-but-stale row — that is exactly the state the user is trying# to clear (the reported bug: repeated Reload clicks kept serving the@@ -402,6 +405,30 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResulschedule = parse_ttl_schedule(existing, team.timezone, settling_period_seconds=SESSION_SETTLING_SECONDS)if pinned:schedule = replace(schedule, max_window_days=OOM_PIN_WINDOW_DAYS)+ if forced and not background:+ # A within-TTL current-day bucket can still be hours behind (the+ # today band is 4h), which on an hourly graph reads as missing+ # recent data. Disabling the grace above cannot help there because+ # the bucket is not stale, just coarse. Treat the windows covering+ # the current team-local day as expired for this read only: the+ # ensure reports a miss, the read falls through to the live query,+ # and the SWR enqueue rebuilds the bucket in the background.+ # Jobs split on UTC day boundaries, so the cutoff is the UTC-day+ # floor of team-local midnight; a cutoff at local midnight itself+ # sits after the window start for teams behind UTC and would never+ # match today's window. Background builds are excluded because the+ # same schedule sets the insert TTL, and the revalidation task runs+ # under the forced execution mode, so it would persist the rebuilt+ # bucket with a 1-second expiry that every ambient read then+ # misses. `rules` are first-match by descending cutoff, so+ # prepending wins over the normal today band.+ today_start_local = (+ django_timezone.now()+ .astimezone(ZoneInfo(team.timezone))+ .replace(hour=0, minute=0, second=0, microsecond=0)+ )+ forced_cutoff = floor_utc_day(today_start_local.astimezone(UTC))+ schedule = replace(schedule, rules=[(forced_cutoff, 1), *schedule.rules])kwargs["ttl_seconds"] = scheduleresult = ensure_precomputed(team=team, **kwargs)if not result.ready and not background and runner is not None and family is not None: