: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): refresh older dimensional days on a rolling schedule (#129241)
Lucas Ricoy7b6384822482
diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 94276bdf40de..0c0284f8386c 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -35,7 +35,7 @@ Both are `ReplacingMergeTree` (version column `computed_at`), sharded by `sipHas- **Population**: the `web_dimensional_precompute_job` Dagster job, every 20 minutes (`products/web_analytics/dags/web_dimensional_precompute.py`).For each team on a region-scoped allowlist it drives `ensure_precomputed` over a rolling 92-day window, chunked to one UTC day per INSERT.92 UTC days hold the start of a `-90d` read in every team timezone.- Every window is a `PreaggregationJob` (Postgres) with a `job_id` and a TTL by age (today 1h, ≤2 days 1 day, older 90 days); re-runs recompute only expired windows.+ Every window is a `PreaggregationJob` (Postgres) with a `job_id` and a TTL by age (today 45 minutes, ≤2 days 1 day, older 90 days plus a stable per-day offset of up to 7 days); re-runs recompute only expired windows. The offset spreads older days over different runs, so each run rebuilds a few of them. Each run builds both tables for a day, newest day first.The TTL bands start at UTC midnight, like the windows, so the current UTC day keeps its 1h TTL in every team timezone.The allowlist defaults per Cloud region (`DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION`) and is overridable via `WEB_DIMENSIONAL_PRECOMPUTE_TEAM_IDS`; an empty list disables the job.The inserts carry the legacy job's memory and time ceilings, because one UTC day of a very large team outgrew the interactive defaults (#117339).diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.pyindex 459a13ed1068..83de1b35028b 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py@@ -25,6 +25,7 @@ from products.web_analytics.backend.hogql_queries.web_dimensional_precompute impDIMENSIONAL_TTL_SECONDS,STATS_INSERT_TEMPLATE,_base_placeholders,+ dimensional_ttl_schedule,ensure_web_bounces_dimensional_precomputed,ensure_web_stats_dimensional_precomputed,)@@ -333,6 +334,18 @@ class TestColdBackfillSplitsByTtlBandNotPerDay(unittest.TestCase):assert e1 == s2assert sum((e - s).days for s, e, _ in bands) >= 90+ @time_machine.travel("2024-06-15T12:00:00Z", tick=False)+ def test_older_days_refresh_on_spread_out_runs(self):+ schedule = dimensional_ttl_schedule()+ old_days = [datetime(2024, 4, 1, tzinfo=UTC) + timedelta(days=offset) for offset in range(30)]++ ttls = [schedule.get_ttl(day, jittered=True) for day in old_days]++ assert all(90 * 86400 <= ttl < 97 * 86400 for ttl in ttls)+ # A backfill builds every day in one run. Days that kept one TTL would all expire, and be+ # rebuilt, on the same later run.+ assert len(set(ttls)) > 20+@time_machine.travel("2024-06-15T12:00:00Z", tick=False)def test_today_yesterday_7d_rest_schedule_is_four_bands(self):# The exact schedule shape described in review: today / yesterday / lastdiff --git a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.pyindex 876c12df6026..7a35b77446a6 100644--- a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py@@ -53,18 +53,20 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precomputeWEB_STATS_DIMENSIONAL_READ_TABLE = "web_stats_dimensional_preaggregated"WEB_BOUNCES_DIMENSIONAL_READ_TABLE = "web_bounces_dimensional_preaggregated"-# TTL tuned for "keep ~90 days warm, don't recompute every time": today's window-# refreshes hourly, the last two days daily, everything older is computed once and-# held for 90 days. The scheduled job re-runs over the rolling window and the-# framework only recomputes windows whose jobs have expired. Today's TTL is shorter-# than the hourly schedule so that every run finds today's job expired and rebuilds-# it. A TTL equal to the schedule period lets a run find the job fresh by seconds,-# skip it, and leave it expired until the next run.+# Today's window refreshes hourly, the last two days daily, and older days are held for 90 to 97+# days so a settled day is computed once. The scheduled job re-runs over the rolling window and the+# framework only recomputes windows whose jobs have expired. Today's TTL is shorter than the hourly+# schedule so that every run finds today's job expired and rebuilds it. A TTL equal to the schedule+# period lets a run find the job fresh by seconds, skip it, and leave it expired until the next run.+#+# The jitter gives each older day a stable offset, so a backfill's days expire on different runs+# and each run rebuilds only a few of them.DIMENSIONAL_TTL_SECONDS: dict[str, int] = {"0d": 45 * 60,"2d": 24 * 60 * 60,"default": 90 * 24 * 60 * 60,}+DIMENSIONAL_DEFAULT_TTL_JITTER_SECONDS = 7 * 24 * 60 * 60def dimensional_ttl_schedule() -> TtlSchedule:@@ -72,7 +74,9 @@ def dimensional_ttl_schedule() -> TtlSchedule:# team timezone, the current UTC day moves into the 1-day band when the team's local day# starts, and that day then stops refreshing until the next UTC midnight. The band cutoffs are# relative to now, so build the schedule per call.- return parse_ttl_schedule(DIMENSIONAL_TTL_SECONDS, "UTC")+ return parse_ttl_schedule(+ DIMENSIONAL_TTL_SECONDS, "UTC", default_ttl_jitter_seconds=DIMENSIONAL_DEFAULT_TTL_JITTER_SECONDS+ )# Per-session row, then aggregated into hourly buckets. `host`/`device_type`/diff --git a/products/web_analytics/dags/tests/test_web_dimensional_precompute.py b/products/web_analytics/dags/tests/test_web_dimensional_precompute.pyindex 6d71087061b1..5e064779f79d 100644--- a/products/web_analytics/dags/tests/test_web_dimensional_precompute.py+++ b/products/web_analytics/dags/tests/test_web_dimensional_precompute.py@@ -19,6 +19,7 @@ from posthog.models import Organization, Teamfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResultfrom products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.web_analytics.backend.hogql_queries.web_dimensional_precompute import dimensional_ttl_schedulefrom products.web_analytics.dags.web_dimensional_precompute import (BOUNCES_TABLE,DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION,@@ -57,6 +58,7 @@ def _ready_job(start: int, end: int, built_minutes_ago: int, ttl_minutes: int) -time_range_end=_day(end),query_hash="hash",status=PreaggregationJob.Status.READY,+ created_at=built_at,computed_at=built_at,expires_at=built_at + timedelta(minutes=ttl_minutes),)@@ -169,10 +171,22 @@ class TestSummarizeCoverage(SimpleTestCase):(date(2026, 10, 19),),180 * 60,),+ (+ "job_past_the_schedule_ttl_is_missing_despite_a_longer_stored_expiry",+ [+ _ready_job(-3, -1, 100 * 24 * 60, 200 * 24 * 60),+ _ready_job(-1, 0, 600, 24 * 60),+ _ready_job(0, 1, 10, 60),+ ],+ (date(2026, 10, 16), date(2026, 10, 17)),+ 10 * 60,+ ),("no_jobs", [], (date(2026, 10, 16), date(2026, 10, 17), date(2026, 10, 18), date(2026, 10, 19)), None),])def test_reports_missing_days_and_today_lag(self, _name, jobs, expected_missing, expected_lag):+ with time_machine.travel(_NOW, tick=False):+ ttl_schedule = dimensional_ttl_schedule()coverage = summarize_coverage(team_id=1,table=STATS_TABLE,@@ -180,6 +194,7 @@ class TestSummarizeCoverage(SimpleTestCase):window=TimeSpan(start=_day(-3), end=_day(1)),current_day=_NOW.date(),now=_NOW,+ ttl_schedule=ttl_schedule,)assert coverage.missing_days == expected_missing@@ -277,6 +292,17 @@ class TestEnsureWebDimensionalPrecomputeOp(APIBaseTest):# Chunking bounds each ensure call to <= chunk_days so no single INSERT# scans the whole window. Exercised here with a 7-day chunk for clarity.t1 = self._make_team("A")+ calls: list[tuple[str, datetime]] = []++ def record(table: str):+ def ensure(_team: Team, start: datetime, _end: datetime) -> LazyComputationResult:+ calls.append((table, start))+ return _READY++ return ensure++ stats_mock.side_effect = record("stats")+ bounces_mock.side_effect = record("bounces")with (time_machine.travel("2026-10-14T20:21:00Z", tick=False),patch(_SINGLE_CHUNK, 7),@@ -285,6 +311,11 @@ class TestEnsureWebDimensionalPrecomputeOp(APIBaseTest):ensure_web_dimensional_precompute_op(dagster.build_op_context())chunks = [(s, e) for _t, s, e in (c.args for c in stats_mock.call_args_list)]assert len(chunks) > 1+ # A read needs both tables for a day, so each chunk builds both before the next, newest first.+ starts = [start for _table, start in calls[::2]]+ assert [table for table, _start in calls] == ["stats", "bounces"] * len(chunks)+ assert [start for _table, start in calls[1::2]] == starts+ assert starts == sorted(starts, reverse=True)assert all((e - s).days <= 7 for s, e in chunks)# A chunk that straddles UTC midnight makes the framework merge two missing days into one# INSERT, so every boundary must sit on a UTC midnight even when the run starts mid-day.diff --git a/products/web_analytics/dags/web_dimensional_precompute.py b/products/web_analytics/dags/web_dimensional_precompute.pyindex b63d79c169f6..9c0938dcb565 100644--- a/products/web_analytics/dags/web_dimensional_precompute.py+++ b/products/web_analytics/dags/web_dimensional_precompute.py@@ -40,10 +40,12 @@ from posthog.dataclasses import frozenfrom posthog.metrics import pushed_metrics_registryfrom posthog.models import Team+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import TtlSchedulefrom products.analytics_platform.backend.models.preaggregation_job import PreaggregationJobfrom products.web_analytics.backend.hogql_queries.web_dimensional_precompute import (DIMENSIONAL_TTL_SECONDS,dimensional_insert_modifiers,+ dimensional_ttl_schedule,ensure_web_bounces_dimensional_precomputed,ensure_web_stats_dimensional_precomputed,sessions_coverage_floor,@@ -209,6 +211,16 @@ def _merge_spans(spans: Iterable[TimeSpan]) -> list[TimeSpan]:return merged+def _effective_expires_at(job: PreaggregationJob, ttl_schedule: TtlSchedule) -> datetime | None:+ # The reader judges freshness by the current schedule, not by the stored `expires_at`. A job+ # written under a longer TTL keeps its old `expires_at`, so the check must apply the same+ # schedule or it reports a day as covered that the reader rejects.+ if job.expires_at is None:+ return None+ schedule_ttl = ttl_schedule.get_ttl(job.time_range_start, jittered=True)+ return min(job.expires_at, job.created_at + timedelta(seconds=schedule_ttl))++def summarize_coverage(*,team_id: int,@@ -217,6 +229,7 @@ def summarize_coverage(window: TimeSpan,current_day: date,now: datetime,+ ttl_schedule: TtlSchedule,) -> TableCoverage:"""Report which UTC days of the window have a fresh READY job, and how old the current day's job is.@@ -229,7 +242,7 @@ def summarize_coverage(merged = _merge_spans(TimeSpan(start=job.time_range_start, end=job.time_range_end)for job in jobs- if job.expires_at is not None and job.expires_at >= fresh_cutoff+ if (expires_at := _effective_expires_at(job, ttl_schedule)) is not None and expires_at >= fresh_cutoff)missing: list[date] = []@@ -287,6 +300,7 @@ def find_table_coverage(window=window,current_day=current_day,now=now,+ ttl_schedule=dimensional_ttl_schedule(),)@@ -333,13 +347,17 @@ def _ensure_for_team(`chunk_days` of raw data), so no single query scans the whole window. Failuresper (table, chunk) are caught so one bad chunk doesn't poison the rest;already-fresh chunks are cheap PG cache-checks with no INSERT.++ Chunks run newest first, and each chunk builds both tables before the next one starts. A read+ needs both tables for every day it covers, so after a full rebuild (a new job identity) the+ recent ranges become servable after a few chunks instead of after a whole pass over one table."""failures = 0- for table_label, ensure_fn in (- (STATS_TABLE, ensure_web_stats_dimensional_precomputed),- (BOUNCES_TABLE, ensure_web_bounces_dimensional_precomputed),- ):- for chunk_start, chunk_end in chunk_ranges(window.start, window.end, chunk_days):+ for chunk_start, chunk_end in chunk_ranges(window.start, window.end, chunk_days):+ for table_label, ensure_fn in (+ (STATS_TABLE, ensure_web_stats_dimensional_precomputed),+ (BOUNCES_TABLE, ensure_web_bounces_dimensional_precomputed),+ ):try:result = ensure_fn(team, chunk_start, chunk_end)except Exception as exc: