: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): revalidate in background on stale precompute reads (#70080)
Lucas Ricoy5018c1eb2985
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 0bbd05e7ecb4..8ebab7725e61 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -802,7 +802,7 @@ class LazyComputationExecutor:- ttl_schedule: TtlSchedule controlling how long lazy-computed data persists per time range- stale_pending_threshold_seconds: How long before a PENDING job is considered stale- ch_start_grace_period_seconds: Grace period before declaring "not started" as stale- - serve_stale_grace_seconds: When set, a request that would otherwise compute inline+ - stale_while_revalidate_seconds: When set, a request that would otherwise compute inline(or block on another executor's pending jobs) is served from READY jobs that expiredwithin the last N seconds — complete-but-stale data, returned immediately with`stale=True`. Must stay well under EXPIRY_BUFFER_SECONDS (48h) so the underlying@@ -818,10 +818,10 @@ class LazyComputationExecutor:ttl_schedule: TtlSchedule = DEFAULT_TTL_SCHEDULE,stale_pending_threshold_seconds: float = DEFAULT_STALE_PENDING_THRESHOLD_SECONDS,ch_start_grace_period_seconds: float = DEFAULT_CH_START_GRACE_PERIOD_SECONDS,- serve_stale_grace_seconds: float | None = None,+ stale_while_revalidate_seconds: float | None = None,) -> None:- if serve_stale_grace_seconds is not None and serve_stale_grace_seconds >= EXPIRY_BUFFER_SECONDS:- raise ValueError("serve_stale_grace_seconds must be below EXPIRY_BUFFER_SECONDS")+ if stale_while_revalidate_seconds is not None and stale_while_revalidate_seconds >= EXPIRY_BUFFER_SECONDS:+ raise ValueError("stale_while_revalidate_seconds must be below EXPIRY_BUFFER_SECONDS")self.wait_timeout_seconds = wait_timeout_secondsself.poll_interval_seconds = poll_interval_secondsself.max_poll_interval_seconds = max_poll_interval_seconds@@ -829,7 +829,7 @@ class LazyComputationExecutor:self.ttl_schedule = ttl_scheduleself.stale_pending_threshold_seconds = stale_pending_threshold_secondsself.ch_start_grace_period_seconds = ch_start_grace_period_seconds- self.serve_stale_grace_seconds = serve_stale_grace_seconds+ self.stale_while_revalidate_seconds = stale_while_revalidate_secondsdef execute(self,@@ -921,13 +921,13 @@ class LazyComputationExecutor:# fully cover the range, return them immediately — complete-but-stale beats# blocking. Whoever refreshes (the warmer, or a request after the grace)# replaces the data; `filter_overlapping_jobs` always prefers newer jobs.- if self.serve_stale_grace_seconds is not None and (ttl_ranges or pending_jobs):+ if self.stale_while_revalidate_seconds is not None and (ttl_ranges or pending_jobs):graced = find_existing_jobs(- team, query_hash, start, end, expired_grace_seconds=self.serve_stale_grace_seconds+ team, query_hash, start, end, expired_grace_seconds=self.stale_while_revalidate_seconds)graced_ready = self._filter_by_freshness([j for j in graced if j.status == PreaggregationJob.Status.READY],- grace_seconds=self.serve_stale_grace_seconds,+ grace_seconds=self.stale_while_revalidate_seconds,)# Coverage must be checked on the overlap-filtered set that will actually# be returned: the filter prefers newer jobs, so a newer narrow job can@@ -1192,7 +1192,7 @@ def ensure_precomputed(query_type: str | None = None,spill_to_disk: bool = False,wait_timeout_seconds: float | None = None,- serve_stale_grace_seconds: float | None = None,+ stale_while_revalidate_seconds: float | None = None,) -> LazyComputationResult:"""Ensure lazy-computed data exists for the given query and time range.@@ -1238,11 +1238,13 @@ def ensure_precomputed(persists as a READY job even when the overall call times out,so repeated calls converge. Use a small value for user-facingrequests that have a cheap fallback path.- serve_stale_grace_seconds: When set, requests that would otherwise compute- inline or wait are served from READY jobs expired within the- last N seconds (result comes back with `stale=True`). Only for- user-facing callers with a refresh mechanism (e.g. an hourly- warmer); background refreshers must leave this unset or they+ stale_while_revalidate_seconds: Mirrors the HTTP `stale-while-revalidate`+ cache directive (RFC 5861): when set, requests that would+ otherwise compute inline or wait are served from READY jobs+ expired within the last N seconds (result comes back with+ `stale=True`), and the caller is expected to revalidate in the+ background. Only for user-facing callers with a refresh+ mechanism; background refreshers must leave this unset or theywould serve stale to themselves and never recompute.Returns:@@ -1336,7 +1338,7 @@ def ensure_precomputed(executor = LazyComputationExecutor(ttl_schedule=ttl_schedule,wait_timeout_seconds=wait_timeout_seconds if wait_timeout_seconds is not None else DEFAULT_WAIT_TIMEOUT_SECONDS,- serve_stale_grace_seconds=serve_stale_grace_seconds,+ stale_while_revalidate_seconds=stale_while_revalidate_seconds,)return executor.execute(team, query_info, time_range_start, time_range_end, run_insert=_run_manual_insert)diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.pyindex f115683b8745..0c0a6ad19ee8 100644--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py@@ -1702,7 +1702,9 @@ class TestComputationExecutorExecute(BaseTest):("beyond_grace", 9, False),])- def test_stale_ready_job_serve_stale_by_grace(self, _name: str, expired_hours_ago: int, served: bool) -> None:+ def test_stale_ready_job_served_within_stale_while_revalidate(+ self, _name: str, expired_hours_ago: int, served: bool+ ) -> None:query_info, query_hash = self._make_query_info()stale_job = PreaggregationJob.objects.create(@@ -1718,7 +1720,7 @@ class TestComputationExecutorExecute(BaseTest):)executor = LazyComputationExecutor(- ttl_schedule=TtlSchedule.from_seconds(60 * 60), serve_stale_grace_seconds=6 * 60 * 60+ ttl_schedule=TtlSchedule.from_seconds(60 * 60), stale_while_revalidate_seconds=6 * 60 * 60)insert_count = [0]@@ -1740,7 +1742,7 @@ class TestComputationExecutorExecute(BaseTest):assert stale_job.id not in result.job_idsassert insert_count[0] == 1- def test_serve_stale_rechecks_coverage_after_overlap_filtering(self):+ def test_stale_while_revalidate_rechecks_coverage_after_overlap_filtering(self):query_info, query_hash = self._make_query_info()now = django_timezone.now()@@ -1763,7 +1765,7 @@ class TestComputationExecutorExecute(BaseTest):PreaggregationJob.objects.filter(id=job.id).update(created_at=now - timedelta(hours=created_ago_h))executor = LazyComputationExecutor(- ttl_schedule=TtlSchedule.from_seconds(60 * 60), serve_stale_grace_seconds=6 * 60 * 60+ ttl_schedule=TtlSchedule.from_seconds(60 * 60), stale_while_revalidate_seconds=6 * 60 * 60)insert_count = [0]@@ -1779,11 +1781,11 @@ class TestComputationExecutorExecute(BaseTest):assert result.stale is False, "gappy filtered coverage must not be served as a stale hit"assert insert_count[0] > 0- def test_serve_stale_grace_must_stay_under_expiry_buffer(self):+ def test_stale_while_revalidate_must_stay_under_expiry_buffer(self):# A grace at/above EXPIRY_BUFFER_SECONDS could return PG jobs whose ClickHouse# rows were already TTL-deleted — silent empty reads. Constructor must refuse.with self.assertRaises(ValueError):- LazyComputationExecutor(serve_stale_grace_seconds=EXPIRY_BUFFER_SECONDS)+ LazyComputationExecutor(stale_while_revalidate_seconds=EXPIRY_BUFFER_SECONDS)def test_fresh_ready_job_is_reused(self):query_info, query_hash = self._make_query_info()diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.pyindex b137c9f7ba6e..78e02bcb6155 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py@@ -245,3 +245,31 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):# The live slice is hard-coded `[:5]` in `web_goals.py`'s `to_query`.assert MAX_ACTIONS == 5++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stale_served_enqueues_background_revalidation(self):+ # Without the `result.stale` hook this family would serve stale for the whole+ # 6h grace and never refresh (the revalidate half of stale-while-revalidate).+ from posthog.clickhouse.query_tagging import reset_query_tags, tags_context++ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult+ from products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import execute_lazy_precomputed_read++ self._create_action("goal")+ with (+ tags_context(),+ self._enable_lazy(),+ patch(+ "products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute.ensure_web_goals_precomputed",+ return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),+ ),+ patch(+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ ) as delay,+ ):+ reset_query_tags()+ runner = self._runner(self._build_query())+ execute_lazy_precomputed_read(runner)++ assert delay.call_count == 1+ assert delay.call_args.kwargs["team_id"] == self.team.pkdiff --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 8dc9ed1b188b..8d5a1fa0c432 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@@ -5,6 +5,7 @@ from unittest import mockfrom django.test import override_settings+from parameterized import parameterizedfrom structlog.contextvars import get_contextvarsfrom posthog.schema import (@@ -20,16 +21,19 @@ from posthog.schema import (from posthog.hogql import astfrom posthog import redis-from posthog.clickhouse.query_tagging import get_query_tag_value+from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, reset_query_tags, tags_contextfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,TtlSchedule,)+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunnerfrom products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (OOM_PIN_TTL_SECONDS,+ REVALIDATION_TRIGGER,SESSION_SETTLING_SECONDS,+ STALE_WHILE_REVALIDATE_SECONDS,PerQueryOptedOut,PerQueryOptInNotSet,TooManyFilters,@@ -37,6 +41,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp_oom_pin_key,check_common_eligibility,compute_filters_eligibility_hash,+ handle_stale_served,host_filter_expr,is_precompute_enabled_for_team,is_precompute_unrestricted_for_team,@@ -437,3 +442,93 @@ class TestWebEnsurePrecomputed(BaseTest):assert isinstance(passed, TtlSchedule)assert passed.max_window_days == 1assert passed.default_ttl_seconds == 3600++ @parameterized.expand(+ [+ ("user_request", None),+ ("eager_warmer", {"trigger": "webAnalyticsEagerBaselineWarming"}),+ ("replay_warmer", {"trigger": "webAnalyticsQueryWarming"}),+ # The revalidation task itself must never get the grace — a re-run that can+ # be served stale would never refresh anything and freeze the cache.+ ("stale_revalidation", {"trigger": REVALIDATION_TRIGGER}),+ # The generic insight cache warmer isn't in the named trigger set — the+ # CACHE_WARMUP feature gate must classify it as background, or it would+ # persist stale rows into the insight cache under a fresh timestamp.+ ("insight_warmer", {"trigger": "warmingV2", "feature": Feature.CACHE_WARMUP}),+ # The lazy modules re-stamp feature=QUERY before ensuring, clobbering the+ # warmer's CACHE_WARMUP tag — the trigger alone must classify as background.+ ("insight_warmer_feature_clobbered", {"trigger": "warmingV2", "feature": Feature.QUERY}),+ ("unknown_future_warmer", {"feature": Feature.CACHE_WARMUP}),+ ]+ )+ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_stale_while_revalidate_grace_by_trigger(self, _name, tags, mock_ensure):+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])+ reset_query_tags()+ if tags is not None:+ with tags_context(**tags):+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)+ else:+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)+ grace = mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"]+ if tags is None:+ assert grace == STALE_WHILE_REVALIDATE_SECONDS+ else:+ assert grace is None, f"background context {tags} must not be served stale"+++class TestStaleRevalidationEnqueue(BaseTest):+ def setUp(self):+ super().setUp()+ self.query = WebOverviewQuery(dateRange=DateRange(date_from="-7d"), properties=[])++ def tearDown(self):+ reset_query_tags()+ super().tearDown()++ def _delay_patch(self):+ return mock.patch(+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation"+ ".revalidate_web_analytics_precompute.delay"+ )++ def test_handle_stale_served_tags_read_and_debounces_same_shape(self):+ # Repeated stale serves of the same shape (current + compare period, or a user+ # hammering forced refresh) must tag the read and mint exactly one revalidation+ # task within the debounce window.+ runner = WebOverviewQueryRunner(team=self.team, query=self.query)+ reset_query_tags()+ with self._delay_patch() as delay:+ for _ in range(3):+ handle_stale_served(runner=runner, family="web_overview")+ assert get_query_tag_value("precompute_stale") is True+ assert delay.call_count == 1+ payload = delay.call_args.kwargs+ assert payload["team_id"] == self.team.pk+ assert payload["query"]["kind"] == "WebOverviewQuery"++ def test_distinct_stale_shapes_each_get_a_revalidation(self):+ # The debounce is per (team, family, shape), not per request: a second stale+ # family in the same request context must still get its own refresh, or its+ # data stays stale until a warmer happens to cover it.+ overview_runner = WebOverviewQueryRunner(team=self.team, query=self.query)+ stats_query = WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"), properties=[], breakdownBy=WebStatsBreakdown.PAGE+ )+ stats_runner = WebStatsTableQueryRunner(team=self.team, query=stats_query)+ reset_query_tags()+ with self._delay_patch() as delay:+ handle_stale_served(runner=overview_runner, family="web_overview")+ handle_stale_served(runner=stats_runner, family="web_stats")+ assert delay.call_count == 2++ def test_broker_failure_does_not_break_the_stale_read_path(self):+ # handle_stale_served runs inside the families' read try/except before the stale+ # rows are read — a broker outage raising out of it would discard the stale+ # result and fall back to the expensive live query, inverting SWR's purpose.+ runner = WebOverviewQueryRunner(team=self.team, query=self.query)+ reset_query_tags()+ with self._delay_patch() as delay:+ delay.side_effect = Exception("broker down")+ handle_stale_served(runner=runner, family="web_overview")+ assert get_query_tag_value("precompute_stale") is Truediff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.pyindex ed27aa726582..f6ea3357dcf6 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py@@ -665,3 +665,32 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):self._run(self._build_query(opt_in_precompute=False))assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stale_served_enqueues_background_revalidation(self):+ # Without the `result.stale` hook this family would serve stale for the whole+ # 6h grace and never refresh (the revalidate half of stale-while-revalidate).+ from posthog.clickhouse.query_tagging import reset_query_tags, tags_context++ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult+ from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (+ execute_lazy_precomputed_read,+ )++ with (+ tags_context(),+ self._enable_lazy(),+ patch(+ "products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute.ensure_web_overview_precomputed",+ return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),+ ),+ patch(+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ ) as delay,+ ):+ reset_query_tags()+ runner = WebOverviewQueryRunner(team=self.team, query=self._build_query())+ execute_lazy_precomputed_read(runner)++ assert delay.call_count == 1+ assert delay.call_args.kwargs["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.pyindex ba84f2ae5dae..1f1892f4678b 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py@@ -306,3 +306,32 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):"errors": row[3][0],}return out++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stale_served_enqueues_background_revalidation(self):+ # Without the `result.stale` hook this family would serve stale for the whole+ # 6h grace and never refresh (the revalidate half of stale-while-revalidate).+ from posthog.clickhouse.query_tagging import reset_query_tags, tags_context++ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult+ from products.web_analytics.backend.hogql_queries.web_stats_frustration_lazy_precompute import (+ execute_lazy_precomputed_read,+ )++ with (+ tags_context(),+ self._enable_lazy(),+ patch(+ "products.web_analytics.backend.hogql_queries.web_stats_frustration_lazy_precompute.ensure_web_stats_frustration_precomputed",+ return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),+ ),+ patch(+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ ) as delay,+ ):+ reset_query_tags()+ runner = self._runner(self._build_query())+ execute_lazy_precomputed_read(runner, limit=10, offset=0)++ assert delay.call_count == 1+ assert delay.call_args.kwargs["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.pyindex 07bef57bf55b..cb74218ac8c1 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py@@ -710,3 +710,30 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):# Visitors are monotonically non-increasing on the returned page.visitors = [row[1][0] for row in lazy_metrics]assert visitors == sorted(visitors, reverse=True), f"first page not ordered by visitors desc: {visitors}"++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stale_served_enqueues_background_revalidation(self):+ # Without the `result.stale` hook this family would serve stale for the whole+ # 6h grace and never refresh (the revalidate half of stale-while-revalidate).+ from posthog.clickhouse.query_tagging import reset_query_tags, tags_context++ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult+ from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import execute_lazy_precomputed_read++ with (+ tags_context(),+ self._enable_lazy(),+ patch(+ "products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute.ensure_web_stats_precomputed",+ return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),+ ),+ patch(+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ ) as delay,+ ):+ reset_query_tags()+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query())+ execute_lazy_precomputed_read(runner)++ assert delay.call_count == 1+ assert delay.call_args.kwargs["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.pyindex 8fc04b6ae9a3..24cf6ad87067 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py@@ -808,6 +808,9 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):("user_request", None),("eager_warmer", "webAnalyticsEagerBaselineWarming"),("replay_warmer", "webAnalyticsQueryWarming"),+ # The SWR revalidation task's re-run must count as background too, or it+ # would be served stale itself and never refresh anything.+ ("stale_revalidation", "webAnalyticsStaleRevalidation"),])@freeze_time("2024-01-15T12:00:00Z")@@ -833,16 +836,13 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):runner, datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC))+ # The stale-while-revalidate grace is applied centrally by web_ensure_precomputed+ # (see test_web_lazy_precompute_common), so only the wait budget is paths policy.budget = ensure_mock.call_args.kwargs["wait_timeout_seconds"]- grace = ensure_mock.call_args.kwargs["serve_stale_grace_seconds"]if trigger is None:assert budget == mod.PATHS_USER_ENSURE_WAIT_SECONDS- assert grace == mod.PATHS_USER_STALE_GRACE_SECONDSelse:- # Warmers keep the full budget AND must never serve stale to themselves —- # they are the refresh mechanism the stale path relies on.- assert budget is None, f"warmer trigger {trigger} must keep the framework default budget"- assert grace is None, f"warmer trigger {trigger} must not serve stale"+ assert budget is None, f"background trigger {trigger} must keep the framework default budget"@parameterized.expand([diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.pyindex f1be90c34217..77aee4214c9a 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py@@ -298,3 +298,32 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):poor_items = response.results[0].poorassert len(poor_items) == 20, f"expected exactly 20 paths in poor band, got {len(poor_items)}"++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stale_served_enqueues_background_revalidation(self):+ # Without the `result.stale` hook this family would serve stale for the whole+ # 6h grace and never refresh (the revalidate half of stale-while-revalidate).+ from posthog.clickhouse.query_tagging import reset_query_tags, tags_context++ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult+ from products.web_analytics.backend.hogql_queries.web_vitals_paths_lazy_precompute import (+ execute_lazy_precomputed_read,+ )++ with (+ tags_context(),+ self._enable_lazy(),+ patch(+ "products.web_analytics.backend.hogql_queries.web_vitals_paths_lazy_precompute.ensure_web_vitals_paths_precomputed",+ return_value=LazyComputationResult(ready=True, job_ids=[], stale=True),+ ),+ patch(+ "products.web_analytics.backend.tasks.lazy_precompute_revalidation.revalidate_web_analytics_precompute.delay"+ ) as delay,+ ):+ reset_query_tags()+ runner = WebVitalsPathBreakdownQueryRunner(team=self.team, query=self._build_query())+ execute_lazy_precomputed_read(runner)++ assert delay.call_count == 1+ assert delay.call_args.kwargs["team_id"] == self.team.pkdiff --git a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.pyindex 0152a91066cf..9876313519fa 100644--- a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py@@ -45,6 +45,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common impceil_utc_day,check_common_eligibility,floor_utc_day,+ handle_stale_served,host_filter_expr,log_eligibility_outcome,test_account_filter_expr,@@ -56,6 +57,8 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)+_FAMILY = "web_goals"+# Sentinel action_id used for the per-hour denominator row. Real Django# `Action.id` values are positive auto-increment integers, so -1 is safe.@@ -446,6 +449,8 @@ def execute_lazy_precomputed_read(runner: "WebGoalsQueryRunner") -> Optional[dicjob_count=len(result.job_ids),ensure_duration_ms=ensure_duration_ms,)+ if result.stale:+ handle_stale_served(runner=runner, family=_FAMILY)if not result.job_ids or not result.ready:return None@@ -479,6 +484,10 @@ def execute_lazy_precomputed_read(runner: "WebGoalsQueryRunner") -> Optional[dictime_range_end=prev_range_end,)ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)+ if prev_result.stale:+ # handle_stale_served enqueues at most once per request; one+ # revalidation re-runs the whole query, covering both periods.+ handle_stale_served(runner=runner, family=_FAMILY)if not prev_result.ready:logger.info("web_goals_lazy_precompute_previous_not_ready",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 36731a85523d..eec2613dfabc 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@@ -19,6 +19,7 @@ from django.conf import settingsimport structlogimport posthoganalytics+from prometheus_client import Counterfrom posthog.schema import EventPropertyFilter, PropertyOperator, SessionsV2JoinMode@@ -27,6 +28,7 @@ from posthog.hogql.property import property_to_exprfrom posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezonefrom posthog import redis+from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, tag_queriesfrom posthog.models import Teamfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (@@ -72,14 +74,147 @@ def pin_team_oom(team_id: int) -> None:logger.warning("web_precompute.oom_pin_failed", team_id=team_id, exc_info=True)+# --- Stale-while-revalidate (RFC 5861) -------------------------------------------------+#+# The lazy executor's `stale_while_revalidate_seconds` is the *serve* half: user-facing+# requests whose windows expired within the grace get their complete-but-stale rows+# instantly instead of recomputing inline. The helpers below are the *revalidate* half:+# a stale hit enqueues a Celery task that re-runs the query in the background so the+# next fetch is fresh, instead of relying solely on the hourly eager warmer (which only+# covers warmed query shapes). Duplicate enqueues need no dedup layer: the HogQL result+# cache fronts these queries (stale hits are rare per shape), the framework's PENDING-job+# unique index collapses concurrent recomputes to one insert, and the ANALYTICS_LIMITED+# queue plus task `expires` pace and shed anything redundant — the same load profile the+# pre-serve-stale inline path already tolerated at user-request concurrency.++# The trigger tag the revalidation task runs under. Lives here, next to the trigger set,+# so the two cannot drift apart.+REVALIDATION_TRIGGER = "webAnalyticsStaleRevalidation"++# Requests tagged with any of these triggers ARE the refresh mechanism: they must never+# be served stale (they'd freeze the cache serving stale to themselves) and they keep+# the framework's full wait budget. This named set is the belt; the primary gate in+# `is_background_warming_request` is the CACHE_WARMUP feature tag, which classifies+# refreshers by category — including warmers this module doesn't know by name (e.g.+# the generic insight cache warmer, trigger "warmingV2"), which would otherwise be+# served stale and persist it into the insight cache under a fresh timestamp.+BACKGROUND_WARMING_TRIGGERS = frozenset(+ {+ "webAnalyticsEagerBaselineWarming",+ "webAnalyticsQueryWarming",+ # The generic insight cache warmer. Its Feature.CACHE_WARMUP tag does NOT+ # survive to the ensure call (the lazy modules re-stamp feature=QUERY before+ # ensuring), but the trigger does — without it here, warmer runs would be+ # served stale and persist stale rows into the insight cache as a fresh+ # blocking result.+ "warmingV2",+ REVALIDATION_TRIGGER,+ }+)++# Stale-while-revalidate window for *user-facing* requests: windows that expired within+# this grace are served from their existing (complete-but-stale) rows instantly instead+# of recomputing inline, and a background revalidation is enqueued. Refresh normally+# arrives within minutes via the revalidation task (plus the hourly eager warmer for+# warmed shapes) — the grace is the ceiling for revalidation failures and warmer+# outages. Must stay well under the framework's 48h ClickHouse expiry buffer (rows must+# still exist).+STALE_WHILE_REVALIDATE_SECONDS = 6 * 60 * 60++WEB_ANALYTICS_LAZY_PRECOMPUTE_STALE_SERVED = Counter(+ "web_analytics_lazy_precompute_stale_served_total",+ "Reads served from expired-within-grace jobs instead of recomputing inline (stale-while-revalidate).",+ labelnames=["family"],+)++WEB_ANALYTICS_LAZY_PRECOMPUTE_REVALIDATION_ENQUEUED = Counter(+ "web_analytics_lazy_precompute_revalidation_enqueued_total",+ "Background revalidation tasks enqueued after a stale-served read.",+ labelnames=["family"],+)++WEB_ANALYTICS_LAZY_PRECOMPUTE_REVALIDATION_ENQUEUE_FAILED = Counter(+ "web_analytics_lazy_precompute_revalidation_enqueue_failed_total",+ "Revalidation enqueues that failed (e.g. broker unavailable); the stale read is still served.",+ labelnames=["family"],+)+++def is_background_warming_request() -> bool:+ if get_query_tag_value("feature") == Feature.CACHE_WARMUP:+ return True+ return get_query_tag_value("trigger") in BACKGROUND_WARMING_TRIGGERS+++# One revalidation per (team, family, query shape) per window: a dashboard burst — or a+# user hammering forced refresh on a stale tile — fires many stale serves for the same+# shape and they must collapse to a single background rebuild. Keyed per shape (not per+# request) so two different stale families in one request each still get their refresh.+REVALIDATION_DEBOUNCE_SECONDS = 10 * 60+++def enqueue_stale_revalidation(*, team: Team, query: Any, family: str) -> None:+ """Enqueue a background re-run of `query` so a stale-served read gets fresh data next time.++ Debounced via Redis per (team, family, query shape). Best-effort: this runs on the+ user-facing read path before the stale rows are read, so a Redis or broker outage+ must degrade to "serve stale, warmer converges" — never abort the read into the+ expensive live fallback.+ """+ # The task module imports this module (for the trigger constant), so the reverse+ # import must stay local to avoid a cycle.+ from products.web_analytics.backend.tasks.lazy_precompute_revalidation import ( # noqa: PLC0415+ revalidate_web_analytics_precompute,+ )++ try:+ debounce_key = f"web_swr_reval:{team.id}:{family}:{compute_filters_eligibility_hash(query, team.timezone)[:16]}"+ if not redis.get_client().set(debounce_key, "1", ex=REVALIDATION_DEBOUNCE_SECONDS, nx=True):+ return+ revalidate_web_analytics_precompute.delay(+ team_id=team.id, query=query.model_dump(mode="json", exclude_none=True)+ )+ except Exception:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_REVALIDATION_ENQUEUE_FAILED.labels(family=family).inc()+ logger.warning("web_precompute.swr_revalidation_enqueue_failed", team_id=team.id, family=family, exc_info=True)+ return+ WEB_ANALYTICS_LAZY_PRECOMPUTE_REVALIDATION_ENQUEUED.labels(family=family).inc()+ logger.info("web_precompute.swr_revalidation_enqueued", team_id=team.id, family=family)+++def handle_stale_served(*, runner: Any, family: str) -> None:+ """Everything a read path does when an ensure came back `stale=True`.++ Counts the stale-served read, tags the upcoming read query so query_log can split+ stale-served vs fresh reads, and enqueues the background revalidation. The enqueue+ is debounced per (team, family, query shape) in Redis — a compare-period ensure+ coming back stale after the current-period one collapses to one task (one re-run+ covers both periods), while a *different* stale family in the same request still+ gets its own refresh.+ """+ WEB_ANALYTICS_LAZY_PRECOMPUTE_STALE_SERVED.labels(family=family).inc()+ tag_queries(precompute_stale=True)+ enqueue_stale_revalidation(team=runner.team, query=runner.query, family=family)++def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResult:- """`ensure_precomputed` for web analytics, with reactive per-team OOM capping.+ """`ensure_precomputed` for web analytics, with reactive per-team OOM capping and+ the web-wide stale-while-revalidate policy.A team runs uncapped until one of its precompute inserts OOMs; that pins it so laterrequests build their TTL schedule with a 1-day `max_window_days` cap (job width boundedat any window age). The request that hits the OOM still fails here and falls back to thelive query — the cap only takes effect next time.++ Every user-facing call gets the stale-while-revalidate grace by default; requests+ tagged with a background warming trigger never do (they are the refresh mechanism+ and would serve stale to themselves). Callers that see `stale=True` must hand the+ result to `handle_stale_served` so the background revalidation actually happens."""+ if "stale_while_revalidate_seconds" not in kwargs:+ kwargs["stale_while_revalidate_seconds"] = (+ None if is_background_warming_request() else STALE_WHILE_REVALIDATE_SECONDS+ )pinned = is_team_oom_pinned(team.id)if "ttl_seconds" in kwargs:existing = kwargs["ttl_seconds"]diff --git a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.pyindex abfd62c566e2..a91c3f99fcff 100644--- a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py@@ -30,7 +30,10 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precomputetest_account_filter_expr,user_filter_expr,)-from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import web_ensure_precomputed+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ handle_stale_served,+ web_ensure_precomputed,+)_FAMILY = "web_overview"@@ -260,6 +263,8 @@ def execute_lazy_precomputed_read(time_range_end=time_range_end,)ensure_duration_ms = int((time.perf_counter() - ensure_started) * 1000)+ if result.stale:+ handle_stale_served(runner=runner, family=_FAMILY)logger.info("web_overview_lazy_precompute_ensure_done",@@ -306,6 +311,10 @@ def execute_lazy_precomputed_read(time_range_end=prev_range_end,)ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)+ if prev_result.stale:+ # handle_stale_served enqueues at most once per request; one+ # revalidation re-runs the whole query, covering both periods.+ handle_stale_served(runner=runner, family=_FAMILY)if not prev_result.ready:WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="previous_not_ready").inc()diff --git a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.pyindex ad8317c1f739..5a1b413826f8 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py@@ -35,6 +35,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common impceil_utc_day,check_common_eligibility,floor_utc_day,+ handle_stale_served,host_filter_expr,log_eligibility_outcome,test_account_filter_expr,@@ -46,6 +47,8 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)+_FAMILY = "web_stats_frustration"+# Allowlist of exception class names we expect on the lazy path. Anything# outside this set is collapsed to "other" so dependency-leaking dynamic@@ -485,6 +488,8 @@ def execute_lazy_precomputed_read(job_count=len(result.job_ids),ensure_duration_ms=ensure_duration_ms,)+ if result.stale:+ handle_stale_served(runner=runner, family=_FAMILY)if not result.job_ids or not result.ready:return None@@ -517,6 +522,10 @@ def execute_lazy_precomputed_read(time_range_end=prev_range_end,)ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)+ if prev_result.stale:+ # handle_stale_served enqueues at most once per request; one+ # revalidation re-runs the whole query, covering both periods.+ handle_stale_served(runner=runner, family=_FAMILY)if not prev_result.ready:logger.info("web_stats_frustration_lazy_precompute_previous_not_ready",diff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.pyindex 77d61580de04..b0aa5216226b 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py@@ -38,7 +38,10 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precomputetest_account_filter_expr,user_filter_expr,)-from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import web_ensure_precomputed+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ handle_stale_served,+ web_ensure_precomputed,+)_FAMILY = "web_stats"@@ -617,6 +620,8 @@ def execute_lazy_precomputed_read(time_range_start=time_range_start,time_range_end=time_range_end,)+ if result.stale:+ handle_stale_served(runner=runner, family=_FAMILY)if not result.job_ids:WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="no_job_ids").inc()@@ -665,6 +670,10 @@ def execute_lazy_precomputed_read(time_range_start=prev_range_start,time_range_end=prev_range_end,)+ if prev_result.stale:+ # handle_stale_served enqueues at most once per request; one+ # revalidation re-runs the whole query, covering both periods.+ handle_stale_served(runner=runner, family=_FAMILY)if not prev_result.ready:WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="previous_not_ready").inc()diff --git a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.pyindex 6bb7d1ed041e..b3f6c13cc4f4 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py@@ -28,7 +28,7 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.clickhouse.query_tagging import Feature, Product, get_query_tag_value, tag_queries+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,@@ -41,7 +41,9 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common impceil_utc_day,check_common_eligibility,floor_utc_day,+ handle_stale_served,host_filter_expr,+ is_background_warming_request,log_eligibility_outcome,test_account_filter_expr,web_ensure_precomputed,@@ -52,6 +54,8 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)+_FAMILY = "web_stats_paths"+# Allowlist of exception class names we expect on the lazy path. Anything# outside this set is collapsed to "other" so dependency-leaking dynamic@@ -86,11 +90,6 @@ WEB_STATS_PATHS_LAZY_EMPTY = Counter("Lazy precompute reads that returned zero rows (potential silent ingestion drop or fresh team).",)-WEB_STATS_PATHS_LAZY_STALE_SERVED = Counter(- "web_stats_paths_lazy_precompute_stale_served_total",- "Reads served from expired-within-grace jobs instead of recomputing inline (serve-stale path).",-)-WEB_STATS_PATHS_LAZY_ROWS = Histogram("web_stats_paths_lazy_precompute_rows","Distinct `breakdown_value` rows returned by the lazy precompute read (post-LIMIT cap).",@@ -405,11 +404,6 @@ def _top_k_ranking_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr | None:)-# Warming triggers whose ensure calls keep the framework's full wait budget: they run in-# background Dagster jobs where long synchronous rebuilds are the whole point (rotation-# recovery depends on a single warmer tick being able to rebuild many windows).-_BACKGROUND_WARMING_TRIGGERS = frozenset({"webAnalyticsEagerBaselineWarming", "webAnalyticsQueryWarming"})-# Wall-clock budget for a *user-facing* request's whole ensure phase (current period plus# the compare period, which shares whatever remains). The executor checks the budget before# starting each inline INSERT, so completed windows always persist as READY jobs and later@@ -420,15 +414,6 @@ _BACKGROUND_WARMING_TRIGGERS = frozenset({"webAnalyticsEagerBaselineWarming", "w# a hash rotation), which previously held requests for 30s+.PATHS_USER_ENSURE_WAIT_SECONDS = 10-# Serve-stale grace for *user-facing* requests: windows that expired within this grace are-# served from their existing (complete-but-stale) rows instantly instead of recomputing-# inline. Refresh comes from the hourly eager warmer, which covers every enrolled team, so-# observed staleness is normally bounded by the warmer cadence — the grace is the ceiling-# for unwarmed query shapes and warmer outages. Must stay well under the framework's 48h-# ClickHouse expiry buffer (rows must still exist). Background warmers never get the grace:-# they are the refresh mechanism and would otherwise serve stale to themselves forever.-PATHS_USER_STALE_GRACE_SECONDS = 6 * 60 * 60-def ensure_web_stats_paths_precomputed(runner: "WebStatsTableQueryRunner",@@ -459,8 +444,7 @@ def ensure_web_stats_paths_precomputed(# Warmers keep the framework default; user-facing calls get the 10s budget, or the# caller-provided remainder of it when this is the second (compare-period) ensure.- is_background = get_query_tag_value("trigger") in _BACKGROUND_WARMING_TRIGGERS- if is_background:+ if is_background_warming_request():wait_timeout: float | None = Noneelif wait_budget_seconds is not None:wait_timeout = wait_budget_seconds@@ -477,7 +461,6 @@ def ensure_web_stats_paths_precomputed(query_type="web_stats_paths_lazy_insert",spill_to_disk=True, # high-cardinality path breakdown GROUP BY; can build a large hash tablewait_timeout_seconds=wait_timeout,- serve_stale_grace_seconds=None if is_background else PATHS_USER_STALE_GRACE_SECONDS,)@@ -747,10 +730,7 @@ def execute_lazy_precomputed_read(stale=result.stale,)if result.stale:- WEB_STATS_PATHS_LAZY_STALE_SERVED.inc()- # Tag the upcoming read query so query_log can split stale-served vs fresh- # reads (the Prometheus counter above can't be joined against query latency).- tag_queries(precompute_stale=True)+ handle_stale_served(runner=runner, family=_FAMILY)if not result.job_ids:return None@@ -782,7 +762,7 @@ def execute_lazy_precomputed_read(# 2x the intended time. Warmers keep the framework's 180s per call# (their gate is the wider ENSURE_BUDGET_MS); user-facing requests# share the single PATHS_USER_ENSURE_WAIT_SECONDS across both calls.- is_background = get_query_tag_value("trigger") in _BACKGROUND_WARMING_TRIGGERS+ is_background = is_background_warming_request()if ensure_duration_ms >= ENSURE_BUDGET_MS:logger.info("web_stats_paths_lazy_precompute_compare_budget_exceeded",@@ -811,6 +791,11 @@ def execute_lazy_precomputed_read()ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)+ if prev_result.stale:+ # handle_stale_served enqueues at most once per request; one+ # revalidation re-runs the whole query, covering both periods.+ handle_stale_served(runner=runner, family=_FAMILY)+if not prev_result.ready:logger.info("web_stats_paths_lazy_precompute_previous_not_ready",diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.pyindex ec3bd06c22b3..1dd9bafacf23 100644--- a/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py@@ -42,7 +42,10 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precomputetest_account_filter_expr,user_filter_expr,)-from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import web_ensure_precomputed+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ handle_stale_served,+ web_ensure_precomputed,+)_FAMILY = "web_vitals_paths"@@ -380,6 +383,8 @@ def execute_lazy_precomputed_read(time_range_start=time_range_start,time_range_end=time_range_end,)+ if result.stale:+ handle_stale_served(runner=runner, family=_FAMILY)if not result.job_ids:WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="no_job_ids").inc()diff --git a/products/web_analytics/backend/tasks/__init__.py b/products/web_analytics/backend/tasks/__init__.pyindex ac23eb99ada3..08bcc3a63317 100644--- a/products/web_analytics/backend/tasks/__init__.py+++ b/products/web_analytics/backend/tasks/__init__.py@@ -1,3 +1,3 @@-from . import heatmap_screenshot+from . import heatmap_screenshot, lazy_precompute_revalidation-__all__ = ["heatmap_screenshot"]+__all__ = ["heatmap_screenshot", "lazy_precompute_revalidation"]diff --git a/products/web_analytics/backend/tasks/lazy_precompute_revalidation.py b/products/web_analytics/backend/tasks/lazy_precompute_revalidation.pynew file mode 100644index 000000000000..ee1fe17a4ea6--- /dev/null+++ b/products/web_analytics/backend/tasks/lazy_precompute_revalidation.py@@ -0,0 +1,104 @@+"""Background revalidation for stale-served lazy precompute reads.++The revalidate half of the stale-while-revalidate semantics (RFC 5861): when a+user-facing read is served from expired-within-grace jobs, the read path+enqueues this task (see `web_lazy_precompute_common.enqueue_stale_revalidation`)+to re-run the query in the background so the next fetch is fresh instead of+waiting for the hourly eager warmer — which only covers warmed query shapes.++Duplicate tasks for the same query shape are tolerated rather than deduped: the+framework's PENDING-job unique index collapses concurrent recomputes to one+insert, and once the first task refreshes the jobs the rest are cheap warm+reads on a queue that paces ClickHouse work anyway.+"""++import time++import structlog+from celery import shared_task+from prometheus_client import Counter++from posthog.hogql.constants import LimitContext++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.event_usage import EventSource+from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runner+from posthog.models import Team+from posthog.scoping_audit import skip_team_scope_audit+from posthog.tasks.utils import CeleryQueue++from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import REVALIDATION_TRIGGER++logger = structlog.get_logger(__name__)++REVALIDATION_RUN = Counter(+ "web_analytics_lazy_precompute_revalidation_total",+ "Background stale-while-revalidate re-runs of web analytics queries.",+ labelnames=["outcome", "query_kind"],+)++# Worst case is two ensure phases (current + compare period) at the framework's+# 180s wait budget each, plus the read itself; mirror the heatmap task's limits.+REVALIDATION_SOFT_TIME_LIMIT = 600+REVALIDATION_TIME_LIMIT = REVALIDATION_SOFT_TIME_LIMIT + 30++# Discard tasks that sat in the queue this long: by then either a sibling task+# already refreshed the jobs, the warmer did, or a newer stale hit re-enqueued.+# This is the queue's shedding valve against enqueue bursts on a hot stale shape.+REVALIDATION_EXPIRES_SECONDS = 15 * 60+++@shared_task(+ ignore_result=True,+ # Same queue insight cache warming uses — prevents ClickHouse from being overwhelmed.+ queue=CeleryQueue.ANALYTICS_LIMITED.value,+ expires=REVALIDATION_EXPIRES_SECONDS,+ # No retries: the next stale hit re-enqueues, and the hourly warmer converges+ # regardless.+ max_retries=0,+ soft_time_limit=REVALIDATION_SOFT_TIME_LIMIT,+ time_limit=REVALIDATION_TIME_LIMIT,+)+@skip_team_scope_audit+def revalidate_web_analytics_precompute(team_id: int, query: dict) -> None:+ query_kind = str(query.get("kind"))+ try:+ team = Team.objects.get(pk=team_id)+ except Team.DoesNotExist:+ logger.warning("web_analytics_swr_revalidation_team_missing", team_id=team_id, query_kind=query_kind)+ REVALIDATION_RUN.labels(outcome="failed", query_kind=query_kind).inc()+ return++ logger.info("web_analytics_swr_revalidation_started", team_id=team_id, query_kind=query_kind)+ started = time.monotonic()+ try:+ # Tag BEFORE constructing the runner (tags live in a contextvar the runner's+ # construction-time I/O inherits). The trigger puts this re-run in+ # BACKGROUND_WARMING_TRIGGERS, so the ensure gets no stale-while-revalidate+ # grace (it cannot serve stale to itself) and the full framework wait budget.+ # Celery resets query tags on task_postrun, so this never leaks across tasks.+ tag_queries(+ team_id=team_id,+ trigger=REVALIDATION_TRIGGER,+ feature=Feature.CACHE_WARMUP,+ product=Product.WEB_ANALYTICS,+ )+ runner = get_query_runner(query=query, team=team, limit_context=LimitContext.QUERY_ASYNC)+ # Force-refresh: recomputes the expired precompute windows and replaces the+ # HogQL result cache entry, so the next user fetch is fresh on both layers.+ runner.run(+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ analytics_props={"source": EventSource.CACHE_WARMING},+ )+ except Exception:+ logger.exception("web_analytics_swr_revalidation_failed", team_id=team_id, query_kind=query_kind)+ REVALIDATION_RUN.labels(outcome="failed", query_kind=query_kind).inc()+ return++ REVALIDATION_RUN.labels(outcome="completed", query_kind=query_kind).inc()+ logger.info(+ "web_analytics_swr_revalidation_completed",+ team_id=team_id,+ query_kind=query_kind,+ duration_ms=round((time.monotonic() - started) * 1000),+ )diff --git a/products/web_analytics/backend/tasks/test/test_lazy_precompute_revalidation.py b/products/web_analytics/backend/tasks/test/test_lazy_precompute_revalidation.pynew file mode 100644index 000000000000..1e78dbc5b972--- /dev/null+++ b/products/web_analytics/backend/tasks/test/test_lazy_precompute_revalidation.py@@ -0,0 +1,58 @@+from posthog.test.base import BaseTest+from unittest import mock++from posthog.schema import DateRange, WebOverviewQuery++from posthog.clickhouse.query_tagging import get_query_tag_value, reset_query_tags+from posthog.hogql_queries.query_runner import ExecutionMode++from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import REVALIDATION_TRIGGER+from products.web_analytics.backend.tasks.lazy_precompute_revalidation import revalidate_web_analytics_precompute++_MOD = "products.web_analytics.backend.tasks.lazy_precompute_revalidation"+++class TestRevalidateWebAnalyticsPrecompute(BaseTest):+ def tearDown(self):+ # In production Celery resets query tags on task_postrun; calling the task+ # function directly leaves them on the contextvar.+ reset_query_tags()+ super().tearDown()++ def test_reruns_query_as_background_trigger_with_forced_recompute(self):+ payload = WebOverviewQuery(dateRange=DateRange(date_from="-7d"), properties=[]).model_dump(+ mode="json", exclude_none=True+ )+ seen: dict = {}++ def fake_get_query_runner(*, query, team, limit_context):+ # The trigger tag must be set BEFORE runner construction, or the ensure+ # inside the run would not see a background trigger and would be served+ # stale itself instead of recomputing.+ seen["trigger_at_construction"] = get_query_tag_value("trigger")+ seen["team"] = team+ seen["query"] = query+ seen["runner"] = mock.Mock()+ return seen["runner"]++ with mock.patch(f"{_MOD}.get_query_runner", side_effect=fake_get_query_runner):+ revalidate_web_analytics_precompute(team_id=self.team.pk, query=payload)++ assert seen["trigger_at_construction"] == REVALIDATION_TRIGGER+ assert seen["team"].pk == self.team.pk+ assert seen["query"] == payload+ run_kwargs = seen["runner"].run.call_args.kwargs+ assert run_kwargs["execution_mode"] == ExecutionMode.CALCULATE_BLOCKING_ALWAYS++ def test_missing_team_returns_without_raising(self):+ with mock.patch(f"{_MOD}.get_query_runner") as get_runner:+ revalidate_web_analytics_precompute(team_id=0, query={"kind": "WebOverviewQuery"})+ assert get_runner.call_count == 0++ def test_query_failure_is_swallowed(self):+ # A failed revalidation must not raise into Celery retry machinery — the next+ # stale hit after the debounce TTL (or the hourly warmer) converges instead.+ runner = mock.Mock()+ runner.run.side_effect = RuntimeError("clickhouse exploded")+ with mock.patch(f"{_MOD}.get_query_runner", return_value=runner):+ revalidate_web_analytics_precompute(team_id=self.team.pk, query={"kind": "WebOverviewQuery"})