: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): stretch lazy precompute TTLs on session-final windows (#69554)
Lucas Ricoy6ac8ea31bc61
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 454140eb16b5..2f799875ed98 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -182,12 +182,23 @@ class TtlSchedule:team's GROUP BY by handing in a schedule with a tight cap, regardless of how oldthe requested window is. `None` leaves it uncapped.+ `settling_period_seconds` marks how long after `time_range_end` a window's data can+ still change (e.g. the 24h session pad in web analytics: sessions opened in the+ window keep evolving until they close). A job *computed before* the window settled+ (`time_range_end + settling_period`) captured in-motion data, so its freshness is+ capped at the settling moment regardless of the band TTL — it recomputes right when+ the data is complete instead of freezing an in-motion snapshot for a long band TTL.+ Jobs computed after the window settled keep the full band TTL. This matters for+ non-UTC teams, whose UTC-aligned edge windows can land in a long-TTL band while+ still settling. `None` disables the check.+Use parse_ttl_schedule() to create from user-facing dict format."""rules: list[tuple[datetime, int]]default_ttl_seconds: intmax_window_days: int | None = None+ settling_period_seconds: int | None = Nonedef get_ttl(self, window_start: datetime) -> int:for cutoff, ttl in self.rules:@@ -207,6 +218,7 @@ def parse_ttl_schedule(ttl: int | dict[str, int],team_timezone: str = "UTC",max_window_days: int | None = None,+ settling_period_seconds: int | None = None,) -> TtlSchedule:"""Parse a TTL specification into a TtlSchedule.@@ -227,7 +239,12 @@ def parse_ttl_schedule(if isinstance(ttl, int):if ttl <= 0:raise ValueError(f"TTL must be positive, got {ttl}")- return TtlSchedule(rules=[], default_ttl_seconds=ttl, max_window_days=max_window_days)+ return TtlSchedule(+ rules=[],+ default_ttl_seconds=ttl,+ max_window_days=max_window_days,+ settling_period_seconds=settling_period_seconds,+ )tz = ZoneInfo(team_timezone)rules: list[tuple[datetime, int]] = []@@ -250,7 +267,12 @@ def parse_ttl_schedule(rules.append((cutoff, value))rules.sort(key=lambda r: r[0], reverse=True)- return TtlSchedule(rules=rules, default_ttl_seconds=default_ttl, max_window_days=max_window_days)+ return TtlSchedule(+ rules=rules,+ default_ttl_seconds=default_ttl,+ max_window_days=max_window_days,+ settling_period_seconds=settling_period_seconds,+ )def split_ranges_by_ttl(@@ -1066,20 +1088,30 @@ class LazyComputationExecutor:"""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().+ READY jobs must satisfy: created_at + desired_ttl >= now(), and — when the+ schedule carries a `settling_period_seconds` — a job computed *before* its+ window 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.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."""now = django_timezone.now()+ settling_period = self.ttl_schedule.settling_period_secondsresult = []for job in jobs:if job.status == PreaggregationJob.Status.PENDING:result.append(job)- else:- desired_ttl = self.ttl_schedule.get_ttl(job.time_range_start)- if job.created_at + timedelta(seconds=desired_ttl) >= now:- result.append(job)+ continue+ desired_ttl = self.ttl_schedule.get_ttl(job.time_range_start)+ fresh_until = job.created_at + timedelta(seconds=desired_ttl)+ 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)+ if fresh_until >= now:+ result.append(job)return resultdef _wait_for_notification(self, pubsub: redis_lib.client.PubSub, timeout: float) -> dict | None: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 51652926660b..adaa899b1087 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@@ -1644,6 +1644,54 @@ class TestComputationExecutorExecute(BaseTest):assert insert_count[0] == 1assert stale_job.id not in result.job_ids+ @parameterized.expand(+ [+ # Job computed mid-window (before window_end + lag): its session metrics were+ # still in motion, so a long band TTL must not keep it — it recomputes once settled.+ ("computed_before_window_settled", False),+ # Job computed after the window settled: complete data, keeps the full band TTL.+ ("computed_after_window_settled", True),+ ]+ )+ def test_settling_period_caps_freshness_of_in_motion_jobs(self, _name: str, expect_reused: bool) -> None:+ query_info, query_hash = self._make_query_info()++ now = django_timezone.now()+ # UTC-day-aligned window (the executor decomposes ranges at day boundaries) that+ # ended 2 days ago; with a 24h finality lag its data became final 1 day ago.+ window_end = datetime(now.year, now.month, now.day, tzinfo=UTC) - timedelta(days=2)+ window_start = window_end - timedelta(days=1)+ created_at = window_end - timedelta(hours=12) if not expect_reused else now - timedelta(hours=1)++ job = PreaggregationJob.objects.create(+ team=self.team,+ query_hash=query_hash,+ time_range_start=window_start,+ time_range_end=window_end,+ status=PreaggregationJob.Status.READY,+ expires_at=now + timedelta(days=5),+ )+ PreaggregationJob.objects.filter(id=job.id).update(created_at=created_at)++ schedule = TtlSchedule(rules=[], default_ttl_seconds=5 * 24 * 60 * 60, settling_period_seconds=24 * 60 * 60)+ insert_count = [0]++ result = LazyComputationExecutor(ttl_schedule=schedule).execute(+ team=self.team,+ query_info=query_info,+ start=window_start,+ end=window_end,+ run_insert=lambda t, j: insert_count.__setitem__(0, insert_count[0] + 1),+ )++ assert result.ready is True+ if expect_reused:+ assert job.id in result.job_ids+ assert insert_count[0] == 0+ else:+ assert job.id not in result.job_ids+ assert insert_count[0] == 1+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_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.pyindex d724759339d2..8dc9ed1b188b 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@@ -29,6 +29,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu)from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (OOM_PIN_TTL_SECONDS,+ SESSION_SETTLING_SECONDS,PerQueryOptedOut,PerQueryOptInNotSet,TooManyFilters,@@ -390,8 +391,13 @@ class TestWebEnsurePrecomputed(BaseTest):def test_pins_team_on_oom_and_runs_uncapped_first(self, mock_ensure):mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=True)web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)- # ran with the caller's raw schedule this time (not yet pinned), then pinned for next time- assert mock_ensure.call_args.kwargs["ttl_seconds"] == {"default": 3600}+ # ran width-uncapped this time (not yet pinned), then pinned for next time; the+ # schedule is normalized to a TtlSchedule carrying the session-pad finality lag+ passed = mock_ensure.call_args.kwargs["ttl_seconds"]+ assert isinstance(passed, TtlSchedule)+ assert passed.default_ttl_seconds == 3600+ assert passed.max_window_days is None+ assert passed.settling_period_seconds == SESSION_SETTLING_SECONDSassert is_team_oom_pinned(self.team.pk) is True@mock.patch(f"{_COMMON}.ensure_precomputed")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 eeaa8f911dbb..36731a85523d 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@@ -81,15 +81,22 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResullive query — the cap only takes effect next time."""pinned = is_team_oom_pinned(team.id)- if pinned and "ttl_seconds" in kwargs:+ if "ttl_seconds" in kwargs:existing = kwargs["ttl_seconds"]- # Stamp the width cap onto whatever schedule the caller passed: an int/dict gets- # parsed with the cap; an already-built TtlSchedule (also accepted by- # ensure_precomputed) just gets the cap re-stamped — parse_ttl_schedule can't take one.+ # Normalize whatever the caller passed into a TtlSchedule so web-wide policy can be+ # stamped on: an int/dict gets parsed; an already-built TtlSchedule (also accepted+ # by ensure_precomputed) gets its fields re-stamped via replace().+ # Every web schedule settles on the 24h session pad: a job computed before+ # `window_end + pad` captured still-evolving session metrics and must not sit on+ # a long band TTL — non-UTC teams' UTC-aligned edge windows can land in a+ # multi-day band while their sessions are still settling.if isinstance(existing, TtlSchedule):- kwargs["ttl_seconds"] = replace(existing, max_window_days=OOM_PIN_WINDOW_DAYS)+ schedule = replace(existing, settling_period_seconds=SESSION_SETTLING_SECONDS)else:- kwargs["ttl_seconds"] = parse_ttl_schedule(existing, team.timezone, max_window_days=OOM_PIN_WINDOW_DAYS)+ schedule = parse_ttl_schedule(existing, team.timezone, settling_period_seconds=SESSION_SETTLING_SECONDS)+ if pinned:+ schedule = replace(schedule, max_window_days=OOM_PIN_WINDOW_DAYS)+ kwargs["ttl_seconds"] = scheduleresult = ensure_precomputed(team=team, **kwargs)if result.memory_exceeded:pin_team_oom(team.id) # set or refresh the cap so a still-OOMing team stays pinned@@ -124,9 +131,15 @@ _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS: frozenset[str] = frozenset(# warmer period (yesterday was 1h) races it and hands users multi-second# waits. Recomputing more often buys nothing anyway — the ~6h HogQL result# cache already fronts these queries, so a cache hit never reads the-# precompute. Older windows get progressively longer TTLs. Today and-# yesterday must keep *distinct* TTLs or `split_ranges_by_ttl` fuses them-# into one 2-day job and every today-refresh recomputes yesterday too.+# precompute. Today and yesterday must keep *distinct* TTLs or+# `split_ranges_by_ttl` fuses them into one 2-day job and every+# today-refresh recomputes yesterday too.+# Windows aged 2+ days are *session-final*: sessions cap at 24h (the insert+# scans window_end+24h), so bounce/duration can no longer change, and+# measured late-event ingestion beyond 49h is ≤0.03% of pageviews on the+# worst enrolled team (~0% elsewhere). Their TTLs are therefore generous —+# recomputing an immutable window buys nothing — and bounded in practice by+# hash rotations (any AST-affecting deploy rebuilds everything anyway).# 2. Job sizing — `split_ranges_by_ttl` merges *consecutive days with the same# TTL* into one job. Distinct per-week TTLs therefore force weekly job# boundaries, so a 31-day warm splits into ≤7-day jobs instead of one ~24-day@@ -136,12 +149,12 @@ _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS: frozenset[str] = frozenset(LAZY_TTL_SECONDS: dict[str, int] = {"0d": 4 * 60 * 60, # today"1d": 6 * 60 * 60, # yesterday- "7d": 24 * 60 * 60, # days 2–7 → one ~6d job- "14d": 2 * 24 * 60 * 60, # days 8–14 → one 7d job- "21d": 4 * 24 * 60 * 60, # days 15–21 → one 7d job- "28d": 7 * 24 * 60 * 60, # days 22–28 → one 7d job- "35d": 10 * 24 * 60 * 60, # days 29–35 → one 7d job (covers the tail of a 31d warm)- "default": 14 * 24 * 60 * 60, # days 36++ "7d": 5 * 24 * 60 * 60, # days 2–7 → one ~6d job+ "14d": 7 * 24 * 60 * 60, # days 8–14 → one 7d job+ "21d": 10 * 24 * 60 * 60, # days 15–21 → one 7d job+ "28d": 12 * 24 * 60 * 60, # days 22–28 → one 7d job+ "35d": 14 * 24 * 60 * 60, # days 29–35 → one 7d job (covers the tail of a 31d warm)+ "default": 21 * 24 * 60 * 60, # days 36+}# MVP user-filter allowlist: only an EventPropertyFilter on `$host` with@@ -158,6 +171,12 @@ MAX_PRECOMPUTE_DAYS = 90# See web_overview_lazy_precompute.py for the full reasoning.SESSION_FORWARD_PAD_MINUTES = 24 * 60+# How long after a window ends its session metrics can still change: sessions opened in+# the window keep evolving (bounce flips, duration grows) until they hit the SDK's 24h+# session cap — the same bound the insert's forward pad scans. Stamped onto every web+# TTL schedule as its settling period (see `web_ensure_precomputed`).+SESSION_SETTLING_SECONDS = SESSION_FORWARD_PAD_MINUTES * 60+# Org-level rollout flag — same one the frontend uses to show the "Allow# precompute" toggle.ORG_FEATURE_FLAG_KEY = "web-analytics-precompute-toggle"