: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
perf(web-analytics): prune paths read scan and budget user-facing ensure (#69556)
Lucas Ricoyd7cd3a5db7b3
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 5989fc59b9c2..8d5558dde57c 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -426,6 +426,9 @@ class QueryTags(BaseModel):# Generic across products (experiments, marketing, web analytics) since they share the executor.precompute_window_start: Optional[str] = Noneprecompute_window_end: Optional[str] = None+ # True on precompute READ queries served from expired-within-grace jobs (serve-stale path),+ # so query_log can compare stale-served vs fresh reads without joining Prometheus.+ precompute_stale: Optional[bool] = Noneentity_math: Optional[list[str]] = None# replaysdiff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 2f799875ed98..1d11bd53c7c5 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -452,6 +452,10 @@ class LazyComputationResult:# True if any insert failed with ClickHouse MEMORY_LIMIT_EXCEEDED. Lets callers react# to an OOM (e.g. cap a high-cardinality team's future inserts) without parsing errors.memory_exceeded: bool = False+ # True when the returned job_ids include recently-expired jobs served under the+ # executor's serve-stale grace instead of recomputing inline. The data is complete+ # but up to (TTL + grace) old; the caller decides whether to surface that.+ stale: bool = Falsedef compute_query_hash(query_info: QueryInfo) -> str:@@ -505,6 +509,7 @@ def find_existing_jobs(query_hash: str,start: datetime,end: datetime,+ expired_grace_seconds: float = 0,) -> list[PreaggregationJob]:"""Find all existing lazy computation jobs for the given team and query hash@@ -512,9 +517,11 @@ def find_existing_jobs(Excludes expired jobs. ClickHouse data outlives the PG job byEXPIRY_BUFFER_SECONDS, so queries in flight when a job expires still- find data.+ find data. `expired_grace_seconds` relaxes the expiry cutoff to also return+ recently-expired jobs (for serve-stale reads); it must stay well under+ EXPIRY_BUFFER_SECONDS or the PG row may outlive its ClickHouse data."""- min_expires_at = django_timezone.now()+ min_expires_at = django_timezone.now() - timedelta(seconds=expired_grace_seconds)return list(PreaggregationJob.objects.filter(@@ -780,6 +787,11 @@ 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+ (or block on another executor's pending jobs) is served from READY jobs that expired+ within the last N seconds — complete-but-stale data, returned immediately with+ `stale=True`. Must stay well under EXPIRY_BUFFER_SECONDS (48h) so the underlying+ ClickHouse rows are guaranteed to still exist."""def __init__(@@ -791,7 +803,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,) -> 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")self.wait_timeout_seconds = wait_timeout_secondsself.poll_interval_seconds = poll_interval_secondsself.max_poll_interval_seconds = max_poll_interval_seconds@@ -799,6 +814,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_secondsdef execute(self,@@ -885,6 +901,32 @@ class LazyComputationExecutor:if had_ready_at_start is None:had_ready_at_start = any(j.status == PreaggregationJob.Status.READY for j in fresh_jobs)+ # Step 2.5: Serve stale. If this request would otherwise compute inline or+ # block on another executor's pending jobs, and READY jobs within the grace+ # 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):+ graced = find_existing_jobs(+ team, query_hash, start, end, expired_grace_seconds=self.serve_stale_grace_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,+ )+ # 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+ # evict an older broad one and reopen a gap the unfiltered set covered.+ covering = filter_overlapping_jobs(graced_ready)+ if not find_missing_contiguous_windows(covering, start, end):+ result = LazyComputationResult(+ ready=True,+ job_ids=[j.id for j in covering],+ stale=True,+ )+ _log_execution("stale_hit", result)+ return result+# Step 3: Insert missing rangesdid_work = Falseif ttl_ranges and failures <= self.max_retries:@@ -1084,15 +1126,19 @@ class LazyComputationExecutor:job_age = (django_timezone.now() - job.created_at).total_seconds()return job_age > self.stale_pending_threshold_seconds- def _filter_by_freshness(self, jobs: list[PreaggregationJob]) -> list[PreaggregationJob]:+ def _filter_by_freshness(+ self, jobs: list[PreaggregationJob], grace_seconds: float = 0.0+ ) -> list[PreaggregationJob]:"""Filter jobs by freshness according to the TTL schedule.PENDING jobs always pass (they were recently created and we should wait).- READY jobs must satisfy: created_at + desired_ttl >= now(), and — when the- schedule carries a `settling_period_seconds` — a job computed *before* its+ READY jobs must satisfy: created_at + desired_ttl + grace_seconds >= now(), and,+ when the schedule carries a `settling_period_seconds`, a job computed *before* itswindow settled (`created_at < time_range_end + settling_period`) captured- in-motion data and is only fresh until the settling moment: it recomputes- once the data can no longer change instead of sitting on a long band TTL.+ in-motion data and is only fresh until the settling moment (plus grace): it+ recomputes once the data can no longer change instead of sitting on a long band+ TTL. `grace_seconds` is only non-zero for the serve-stale path and relaxes both+ caps uniformly.This is per-query: a job created by executor A with a long TTL may berejected by executor B using a stricter schedule for the same hash.@@ -1105,11 +1151,11 @@ class LazyComputationExecutor:result.append(job)continuedesired_ttl = self.ttl_schedule.get_ttl(job.time_range_start)- fresh_until = job.created_at + timedelta(seconds=desired_ttl)+ fresh_until = job.created_at + timedelta(seconds=desired_ttl + grace_seconds)if settling_period is not None:settled_at = job.time_range_end + timedelta(seconds=settling_period)if job.created_at < settled_at:- fresh_until = min(fresh_until, settled_at)+ fresh_until = min(fresh_until, settled_at + timedelta(seconds=grace_seconds))if fresh_until >= now:result.append(job)return result@@ -1130,6 +1176,8 @@ def ensure_precomputed(sentinel_placeholders: set[str] | None = None,query_type: str | None = None,spill_to_disk: bool = False,+ wait_timeout_seconds: float | None = None,+ serve_stale_grace_seconds: float | None = None,) -> LazyComputationResult:"""Ensure lazy-computed data exists for the given query and time range.@@ -1168,6 +1216,19 @@ def ensure_precomputed(for hashing. Use this for placeholders whose values change betweenrequests (e.g. datetime.now()) but shouldn't invalidate the cache.The real values are still used at INSERT time.+ wait_timeout_seconds: Wall-clock budget for the executor's compute-and-wait+ loop (default DEFAULT_WAIT_TIMEOUT_SECONDS). The loop checks the+ budget before starting each inline INSERT and while polling for+ other requests' pending jobs, so a completed window always+ persists as a READY job even when the overall call times out,+ so repeated calls converge. Use a small value for user-facing+ requests 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+ would serve stale to themselves and never recompute.Returns:ComputationResult with job_ids that can be used to query the data@@ -1257,7 +1318,11 @@ def ensure_precomputed(ttl_schedule = (ttl_seconds if isinstance(ttl_seconds, TtlSchedule) else parse_ttl_schedule(ttl_seconds, team.timezone))- executor = LazyComputationExecutor(ttl_schedule=ttl_schedule)+ 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,+ )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 adaa899b1087..574c358d935f 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@@ -31,6 +31,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execuDEFAULT_RETRIES,DEFAULT_TTL_SCHEDULE,DEFAULT_WAIT_TIMEOUT_SECONDS,+ EXPIRY_BUFFER_SECONDS,NON_RETRYABLE_CLICKHOUSE_ERROR_CODES,PREAGGREGATION_INSERT_QUORUM,LazyComputationExecutor,@@ -1692,6 +1693,97 @@ class TestComputationExecutorExecute(BaseTest):assert job.id not in result.job_idsassert insert_count[0] == 1+ @parameterized.expand(+ [+ # Expired 1h ago (created 2h ago, 1h TTL) — within the 6h grace: served as-is.+ ("within_grace", 1, True),+ # Expired 9h ago — beyond the 6h grace: the normal recompute path runs.+ ("beyond_grace", 9, False),+ ]+ )+ def test_stale_ready_job_serve_stale_by_grace(self, _name: str, expired_hours_ago: int, served: bool) -> None:+ query_info, query_hash = self._make_query_info()++ stale_job = PreaggregationJob.objects.create(+ team=self.team,+ query_hash=query_hash,+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),+ time_range_end=datetime(2024, 1, 2, tzinfo=UTC),+ status=PreaggregationJob.Status.READY,+ expires_at=django_timezone.now() - timedelta(hours=expired_hours_ago),+ )+ PreaggregationJob.objects.filter(id=stale_job.id).update(+ created_at=django_timezone.now() - timedelta(hours=expired_hours_ago + 1),+ )++ executor = LazyComputationExecutor(+ ttl_schedule=TtlSchedule.from_seconds(60 * 60), serve_stale_grace_seconds=6 * 60 * 60+ )+ insert_count = [0]++ result = executor.execute(+ team=self.team,+ query_info=query_info,+ start=datetime(2024, 1, 1, tzinfo=UTC),+ end=datetime(2024, 1, 2, tzinfo=UTC),+ run_insert=lambda t, j: insert_count.__setitem__(0, insert_count[0] + 1),+ )++ assert result.ready is True+ if served:+ assert result.stale is True+ assert result.job_ids == [stale_job.id]+ assert insert_count[0] == 0, "serve-stale must not compute inline"+ else:+ assert result.stale is False+ assert stale_job.id not in result.job_ids+ assert insert_count[0] == 1++ def test_serve_stale_rechecks_coverage_after_overlap_filtering(self):+ query_info, query_hash = self._make_query_info()++ now = django_timezone.now()+ # An older broad stale job fully covers the range, but a newer narrow stale job+ # overlaps it. The overlap filter prefers the newer job and evicts the broad one,+ # reopening gaps (Jan 1–2 and Jan 3–4) — serving that set would silently drop+ # covered days, so the executor must fall through to recompute instead.+ for time_range, created_ago_h in [+ ((datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 4, tzinfo=UTC)), 3),+ ((datetime(2024, 1, 2, tzinfo=UTC), datetime(2024, 1, 3, tzinfo=UTC)), 2),+ ]:+ job = PreaggregationJob.objects.create(+ team=self.team,+ query_hash=query_hash,+ time_range_start=time_range[0],+ time_range_end=time_range[1],+ status=PreaggregationJob.Status.READY,+ expires_at=now - timedelta(hours=1),+ )+ 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+ )+ insert_count = [0]++ result = executor.execute(+ team=self.team,+ query_info=query_info,+ start=datetime(2024, 1, 1, tzinfo=UTC),+ end=datetime(2024, 1, 4, tzinfo=UTC),+ run_insert=lambda t, j: insert_count.__setitem__(0, insert_count[0] + 1),+ )++ assert result.ready is True+ 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):+ # 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)+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_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.pyindex 7b2a0d81ce4e..f271c648697d 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@@ -765,3 +765,146 @@ class TestWebStatsPathsLazyPrecompute(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++ @parameterized.expand(+ [+ ("user_request", None),+ ("eager_warmer", "webAnalyticsEagerBaselineWarming"),+ ("replay_warmer", "webAnalyticsQueryWarming"),+ ]+ )+ @freeze_time("2024-01-15T12:00:00Z")+ def test_ensure_wait_budget_by_trigger(self, _name: str, trigger: str | None) -> None:+ from datetime import UTC, datetime++ from posthog.clickhouse.query_tagging import reset_query_tags, tags_context++ from products.web_analytics.backend.hogql_queries import web_stats_paths_lazy_precompute as mod++ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query())+ reset_query_tags()+ with patch.object(+ mod, "web_ensure_precomputed", return_value=LazyComputationResult(ready=True, job_ids=[])+ ) as ensure_mock:+ if trigger is not None:+ with tags_context(trigger=trigger):+ mod.ensure_web_stats_paths_precomputed(+ runner, datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC)+ )+ else:+ mod.ensure_web_stats_paths_precomputed(+ runner, datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC)+ )++ 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_SECONDS+ else:+ # 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"++ @parameterized.expand(+ [+ # First ensure burned 9.5s of the 10s budget: the compare ensure must be+ # skipped entirely (fallback to raw) instead of getting a fresh budget.+ ("budget_spent_skips_compare", 9.5, None),+ # First ensure took 2s: the compare ensure runs with the 8s remainder,+ # not a fresh PATHS_USER_ENSURE_WAIT_SECONDS.+ ("remainder_passed_to_compare", 2.0, 8.0),+ ]+ )+ @freeze_time("2024-01-15T12:00:00Z")+ def test_user_ensure_budget_is_shared_across_compare_periods(+ self, _name: str, first_ensure_seconds: float, expected_compare_budget: float | None+ ) -> None:++ from posthog.clickhouse.query_tagging import reset_query_tags++ from products.web_analytics.backend.hogql_queries import web_stats_paths_lazy_precompute as mod++ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query(compare=True))+ reset_query_tags()++ # perf_counter sequence: overall_started, ensure_started, after first ensure;+ # everything after sticks to the last value so later timing reads are stable.+ ticks = [0.0, 0.0, first_ensure_seconds]++ def fake_perf_counter() -> float:+ return ticks.pop(0) if len(ticks) > 1 else ticks[0]++ with (+ patch.object(+ mod,+ "ensure_web_stats_paths_precomputed",+ return_value=LazyComputationResult(ready=True, job_ids=[uuid.uuid4()]),+ ) as ensure_mock,+ patch.object(mod, "execute_read_query", return_value=[]),+ patch.object(mod.time, "perf_counter", side_effect=fake_perf_counter),+ ):+ result = mod.execute_lazy_precomputed_read(+ runner, sort_column="visitors", sort_direction="DESC", limit=11, offset=0+ )++ if expected_compare_budget is None:+ assert result is None, "spent budget must skip the compare ensure and fall back to raw"+ assert ensure_mock.call_count == 1+ else:+ assert ensure_mock.call_count == 2+ assert ensure_mock.call_args_list[1].kwargs["wait_budget_seconds"] == expected_compare_budget++ @parameterized.expand([("no_compare", False), ("compare", True)])+ @freeze_time("2024-01-15T12:00:00Z")+ def test_read_scan_is_pruned_to_requested_windows(self, _name: str, compare: bool) -> None:+ from datetime import UTC, datetime++ from products.web_analytics.backend.hogql_queries import web_stats_paths_lazy_precompute as mod++ cur_start = datetime(2024, 1, 8, tzinfo=UTC)+ cur_end = datetime(2024, 1, 15, tzinfo=UTC)+ prev_start = datetime(2024, 1, 1, tzinfo=UTC) if compare else None+ prev_end = datetime(2024, 1, 8, tzinfo=UTC) if compare else None++ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query(compare=compare))+ captured: dict = {}++ def fake_execute(**kwargs):+ captured["query"] = kwargs["query"]+ return type("FakeResponse", (), {"results": []})()++ with patch.object(mod, "execute_hogql_query", side_effect=fake_execute):+ mod.execute_read_query(+ runner=runner,+ job_ids=[str(uuid.uuid4())],+ current_start_utc=cur_start,+ current_end_utc=cur_end,+ previous_start_utc=prev_start,+ previous_end_utc=prev_end,+ sort_column="visitors",+ sort_direction="DESC",+ limit=11,+ offset=0,+ )++ inner = captured["query"].select_from.table+ assert isinstance(inner, ast.SelectQuery)+ bounds: dict[str, object] = {}+ assert inner.where is not None+ for expr in inner.where.args if isinstance(inner.where, ast.Call) else [inner.where]:+ if (+ isinstance(expr, ast.CompareOperation)+ and isinstance(expr.left, ast.Field)+ and expr.left.chain == ["time_window_start"]+ and isinstance(expr.right, ast.Constant)+ ):+ key = "min" if expr.op == ast.CompareOperationOp.GtEq else "max"+ bounds[key] = expr.right.value++ # The scan lower bound must be the union of the requested windows — with a compare+ # period that is prev_start; without one it must stay cur_start (NOT the 1970+ # no-compare sentinel, which would defeat the pruning entirely).+ expected_min = prev_start if compare else cur_start+ assert bounds == {"min": expected_min, "max": cur_end}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 bd1babe026da..6bb7d1ed041e 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, tag_queries+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tag_value, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,@@ -86,6 +86,11 @@ 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).",@@ -400,10 +405,36 @@ 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+# requests (or the hourly warmer) converge to warm. Timing out here only means this request+# serves the v2/raw fallback instead of blocking on a long rebuild. 10s admits one or two+# typical window inserts (2-8s each on the largest teams), so the common one-stale-window+# case still completes inline; what it bounds is the pile-up case (many stale windows after+# 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",time_range_start: datetime,time_range_end: datetime,+ wait_budget_seconds: float | None = None,) -> LazyComputationResult:placeholders: dict[str, ast.Expr] = {"events_session_id": _events_session_id_expr(runner),@@ -426,6 +457,15 @@ def ensure_web_stats_paths_precomputed(else:insert_query = INSERT_QUERY_TEMPLATE+ # 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:+ wait_timeout: float | None = None+ elif wait_budget_seconds is not None:+ wait_timeout = wait_budget_seconds+ else:+ wait_timeout = PATHS_USER_ENSURE_WAIT_SECONDSreturn web_ensure_precomputed(team=runner.team,insert_query=insert_query,@@ -436,6 +476,8 @@ def ensure_web_stats_paths_precomputed(placeholders=placeholders,query_type="web_stats_paths_lazy_insert",spill_to_disk=True, # high-cardinality path breakdown GROUP BY; can build a large hash table+ wait_timeout_seconds=wait_timeout,+ serve_stale_grace_seconds=None if is_background else PATHS_USER_STALE_GRACE_SECONDS,)@@ -515,7 +557,12 @@ FROM (avgMergeIf(avg_bounce_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS raw_bounce,avgMergeIf(avg_bounce_state, and(time_window_start >= {prev_start}, time_window_start < {prev_end})) AS raw_prev_bounceFROM posthog.web_stats_paths_preaggregated- WHERE and(team_id = {team_id}, job_id IN {job_ids})+ WHERE and(+ team_id = {team_id},+ job_id IN {job_ids},+ time_window_start >= {window_min},+ time_window_start < {window_max}+ )GROUP BY {breakdown_expr}HAVING or(visitors > 0, previous_visitors > 0))@@ -589,6 +636,15 @@ def execute_read_query(prev_start = previous_start_utc if previous_start_utc is not None else datetime(1970, 1, 1, tzinfo=UTC)prev_end = previous_end_utc if previous_end_utc is not None else datetime(1970, 1, 1, tzinfo=UTC)+ # Prune the scan to the union of the two requested windows. Covering jobs can be+ # much wider than the request (a 7d read served by a 31d-warm job set), and without+ # this bound every stored row of every covering job is scanned and state-merged only+ # to be discarded by the *MergeIf conditions. Computed in Python (not `least()` in+ # SQL) because the no-compare sentinel above would otherwise widen the lower bound+ # to 1970 and defeat the pruning.+ window_min = min(current_start_utc, previous_start_utc) if previous_start_utc else current_start_utc+ window_max = max(current_end_utc, previous_end_utc) if previous_end_utc else current_end_utc+placeholders: dict[str, ast.Expr] = {"team_id": ast.Constant(value=runner.team.pk),"job_ids": ast.Constant(value=[str(jid) for jid in job_ids]),@@ -596,6 +652,8 @@ def execute_read_query("cur_end": ast.Constant(value=current_end_utc),"prev_start": ast.Constant(value=prev_start),"prev_end": ast.Constant(value=prev_end),+ "window_min": ast.Constant(value=window_min),+ "window_max": ast.Constant(value=window_max),"breakdown_expr": ast.Field(chain=["breakdown_value"]),"fill_fraction_expr": _fill_fraction_expr(sort_column),}@@ -686,7 +744,13 @@ def execute_lazy_precomputed_read(team_id=team_id,job_count=len(result.job_ids),ensure_duration_ms=ensure_duration_ms,+ 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)if not result.job_ids:return None@@ -713,11 +777,12 @@ def execute_lazy_precomputed_read(prev_range_start = floor_utc_day(previous_start_utc)prev_range_end = ceil_utc_day(previous_end_utc)if prev_range_start < prev_range_end:- # Cold-start budget: the framework's per-call wait is 180 s,- # and a 90-day compare on fresh data can do both periods- # back-to-back. If the current-period call already burned- # most of that, give up on the compare so we don't tie up- # the request handler past `DEFAULT_WAIT_TIMEOUT_SECONDS`.+ # The compare ensure spends whatever the current-period ensure left of+ # the budget, so a request with both periods stale cannot block for+ # 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_TRIGGERSif ensure_duration_ms >= ENSURE_BUDGET_MS:logger.info("web_stats_paths_lazy_precompute_compare_budget_exceeded",@@ -726,11 +791,23 @@ def execute_lazy_precomputed_read(budget_ms=ENSURE_BUDGET_MS,)return None+ remaining_budget: Optional[float] = None+ if not is_background:+ remaining_budget = PATHS_USER_ENSURE_WAIT_SECONDS - ensure_duration_ms / 1000+ if remaining_budget <= 1:+ logger.info(+ "web_stats_paths_lazy_precompute_compare_budget_exceeded",+ team_id=team_id,+ elapsed_ms=ensure_duration_ms,+ budget_ms=PATHS_USER_ENSURE_WAIT_SECONDS * 1000,+ )+ return Noneprev_ensure_started = time.perf_counter()prev_result = ensure_web_stats_paths_precomputed(runner=runner,time_range_start=prev_range_start,time_range_end=prev_range_end,+ wait_budget_seconds=remaining_budget,)ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)