: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): stop snapshot rotations from re-warming the whole fleet (#76068)
Lucas Ricoy9d279672c877
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex ee45de069c03..5cdbde347b88 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -168,13 +168,17 @@ _EXACT_LOOKBACK_DATE_FROM_RE = re.compile(r"^-(\d+)([hdw])$")def _exact_lookback_days(date_from: str | None) -> int | None:- """Days a -Nh/-Nd/-Nw range reaches back, or None for any other form."""+ """Days a -Nh/-Nd/-Nw range reaches back, or None for any other form.++ Hours round up: callers use this as "how many days of buckets cover the+ span", so flooring -721h to 30 would leave the oldest partial day cold.+ """match = _EXACT_LOOKBACK_DATE_FROM_RE.match(date_from or "")if not match:return Nonevalue, unit = int(match.group(1)), match.group(2)if unit == "h":- return value // _HOURS_PER_DAY+ return -(-value // _HOURS_PER_DAY)if unit == "w":return value * _DAYS_PER_WEEKreturn value@@ -246,6 +250,55 @@ def maybe_expand_warming_date_range(query_json: dict) -> dict:return {**query_json, "dateRange": {**date_range, "date_from": WARMING_EXPANDED_DATE_FROM}}+# The canonical lazy replay drops every field the bucket namespace ignores —+# except the two it still needs: the opt-in flag (the eligibility gates read it)+# and the date range (canonicalized below rather than dropped).+_CANONICAL_REPLAY_DROPPED_FIELDS: frozenset[str] = SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS - {+ "useWebAnalyticsPrecompute",+ "dateRange",+}++# The deepened lookback rounds UP to the next multiple of this step. Without it+# the replay's depth tracks the deepest variant in the rolling demand window+# exactly, so a -44d/-46d drift alone rotates the cache key. A step trades at+# most (step - 1) days of extra immutable-bucket depth for a key that only moves+# when demand genuinely crosses a step boundary.+_CANONICAL_LOOKBACK_STEP_DAYS = 15+++def canonicalize_lazy_replay_json(query_json: dict) -> dict:+ """Collapse a lazy-path replay to its shape's canonical variant.++ The warm/cold + staleness discriminator is the replayed runner's result-cache+ key, but the replayed variant is the demand snapshot's most-requested RAW+ variant. Fields the bucket namespace ignores (compareFilter, limit, modifiers,+ …) and small drifts in the deepest observed lookback flip that variant on+ every snapshot rotation, rotating the cache key — the warmer then re-warms a+ shape whose buckets are already fresh. Measured before this: ~90% of the+ fleet re-warmed on every 6h rotation. Dropping the ignored fields and+ stepping the lookback makes the replay a pure function of the normalized+ shape, so the discriminator survives rotations.++ Confined to the lazy path, mirroring the deepen/expand gates: a raw replay's+ exact result-cache row is the whole value of warming it, so its variant must+ stay faithful. A bounded range (date_to) keeps its faithful span for the same+ reason deepening skips it, but still sheds the ignored fields.+ """+ if query_json.get("kind") not in LAZY_PRECOMPUTE_QUERY_KINDS:+ return query_json+ if query_json.get("useWebAnalyticsPrecompute") is not True:+ return query_json+ canonical = {k: v for k, v in query_json.items() if k not in _CANONICAL_REPLAY_DROPPED_FIELDS}+ date_range = canonical.get("dateRange") or {}+ if not date_range.get("date_to"):+ days = _exact_lookback_days(date_range.get("date_from"))+ if days:+ step = _CANONICAL_LOOKBACK_STEP_DAYS+ stepped = min(MAX_PRECOMPUTE_DAYS, ((days + step - 1) // step) * step)+ canonical["dateRange"] = {**date_range, "date_from": f"-{stepped}d"}+ return canonical++# Family-level eligibility dispatch, mirroring each runner's own lazy-path# entry points (stats_table tries three families; a shape is lazy-served iff# any accepts). Keyed by query kind — only LAZY_PRECOMPUTE_QUERY_KINDS appear.@@ -288,28 +341,36 @@ def build_replay_runner(the warmer's purpose — so the decision rests on the shape itself."""# The lazy candidate: deepen to the widest range the shape's demand covers,- # then widen a sub-30d range up to the standard warm depth. Both are no-ops- # off the lazy path, so an unchanged result means nothing to try there.- lazy_json = maybe_expand_warming_date_range(+ # then widen a sub-30d range up to the standard warm depth. Both only ever+ # substitute ranges the shape's own demand (or the standard warm depth)+ # covers, so eligibility is decided on this json.+ eligible_json = maybe_expand_warming_date_range(deepen_to_widest_warmable_range(query_json, observed_date_froms, MAX_PRECOMPUTE_DAYS))- if lazy_json is query_json:- runner = get_query_runner_or_none(query=query_json, team=team, limit_context=LimitContext.QUERY_ASYNC)- if runner is None:- return None, query_json, False- return runner, query_json, _is_lazy_eligible(runner, query_json)-- runner = get_query_runner_or_none(query=lazy_json, team=team, limit_context=LimitContext.QUERY_ASYNC)+ runner = get_query_runner_or_none(query=eligible_json, team=team, limit_context=LimitContext.QUERY_ASYNC)if runner is None:- return None, lazy_json, False- if _is_lazy_eligible(runner, lazy_json):- return runner, lazy_json, True- # Raw path: replay the faithful original range, never the deepened/widened one.- return (- get_query_runner_or_none(query=query_json, team=team, limit_context=LimitContext.QUERY_ASYNC),- query_json,- False,- )+ return None, eligible_json, False+ if not _is_lazy_eligible(runner, eligible_json):+ if eligible_json is query_json:+ return runner, query_json, False+ # Raw path: replay the faithful original range, never the deepened/widened one.+ return (+ get_query_runner_or_none(query=query_json, team=team, limit_context=LimitContext.QUERY_ASYNC),+ query_json,+ False,+ )+ # Only a proven-eligible replay collapses to the canonical variant:+ # canonicalizing before the check could manufacture eligibility — dropping+ # a rejected modifier, stepping a >90d lookback under the cap — and build+ # buckets the shape's real queries can never consume, on the lazy demand+ # floor instead of the raw one. Dropping namespace-ignored fields can only+ # relax the gate, so the canonical replay is re-checked and falls back to+ # the proven json if construction or the gate disagrees.+ lazy_json = canonicalize_lazy_replay_json(eligible_json)+ lazy_runner = get_query_runner_or_none(query=lazy_json, team=team, limit_context=LimitContext.QUERY_ASYNC)+ if lazy_runner is not None and _is_lazy_eligible(lazy_runner, lazy_json):+ return lazy_runner, lazy_json, True+ return runner, eligible_json, Truedef queries_to_keep_fresh(diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.pyindex 90b9953286d9..7dd9cb647f8f 100644--- a/products/web_analytics/dags/tests/test_cache_warming.py+++ b/products/web_analytics/dags/tests/test_cache_warming.py@@ -20,6 +20,7 @@ from products.web_analytics.dags import cache_warmingfrom products.web_analytics.dags.cache_warming import (WarmQueriesConfig,build_replay_runner,+ canonicalize_lazy_replay_json,deepen_to_widest_warmable_range,get_warmable_queries_op,maybe_expand_warming_date_range,@@ -246,6 +247,35 @@ class TestBuildReplayRunner(BaseTest):self.assertFalse(lazy_eligible)self.assertEqual(used_json["dateRange"]["date_from"], "-7d")+ @parameterized.expand(+ [+ # The shared gate rejects both shapes as submitted; canonicalizing+ # before the check would erase the rejection (drop the modifier,+ # step the over-cap lookback under MAX_PRECOMPUTE_DAYS) and build+ # buckets the shape's real queries can never consume, held only to+ # the lazy demand floor instead of the raw one.+ ("uuid_join_mode", {"modifiers": {"sessionsV2JoinMode": "uuid"}}, ["-7d"], "-7d"),+ ("only_over_cap_demand", {"dateRange": {"date_from": "-180d"}}, ["-180d"], "-180d"),+ ]+ )+ def test_ineligible_shape_is_not_canonicalized_into_eligibility(+ self, _name: str, extra: dict, observed: list[str], expected_from: str+ ) -> None:+ query = {+ "kind": "WebOverviewQuery",+ "properties": [],+ "useWebAnalyticsPrecompute": True,+ "dateRange": {"date_from": "-7d"},+ **extra,+ }++ runner, used_json, lazy_eligible = build_replay_runner(self.team, query, observed)++ self.assertIsNotNone(runner)+ self.assertFalse(lazy_eligible)+ self.assertEqual(used_json["dateRange"]["date_from"], expected_from)+ self.assertEqual(used_json, query)+def test_outside_warming_context_gate_fails_closed(self) -> None:reset_query_tags()query = {@@ -261,6 +291,115 @@ class TestBuildReplayRunner(BaseTest):self.assertFalse(lazy_eligible)self.assertEqual(used_json["dateRange"]["date_from"], "-7d")+ @parameterized.expand(+ [+ # A snapshot rotation that flips the representative to a sibling+ # variant — compare toggled, a different sub-30d preset — must not+ # rotate the staleness cache key; before canonicalization every such+ # flip re-warmed the shape even though its buckets were fresh.+ (+ "overview_compare_and_preset_variant",+ {"kind": "WebOverviewQuery", "properties": []},+ {"dateRange": {"date_from": "wStart"}, "compareFilter": {"compare": True}},+ ),+ (+ "stats_limit_variant",+ {"kind": "WebStatsTableQuery", "properties": [], "breakdownBy": "Browser"},+ {"dateRange": {"date_from": "dStart"}, "limit": 50},+ ),+ ]+ )+ def test_representative_variants_share_one_cache_key(self, _name: str, shape: dict, variant_extra: dict) -> None:+ base = {**shape, "useWebAnalyticsPrecompute": True, "dateRange": {"date_from": "-7d"}}+ variant = {**base, **variant_extra}++ base_runner, _, base_eligible = build_replay_runner(self.team, base, ["-7d"])+ variant_runner, _, variant_eligible = build_replay_runner(self.team, variant, ["-7d"])++ assert base_runner is not None and variant_runner is not None+ self.assertTrue(base_eligible)+ self.assertTrue(variant_eligible)+ self.assertEqual(base_runner.get_cache_key(), variant_runner.get_cache_key())+++class TestCanonicalizeLazyReplay(BaseTest):+ @parameterized.expand(+ [+ ("steps_up_to_next_multiple", "-31d", "-45d"),+ ("on_step_unchanged", "-45d", "-45d"),+ ("weeks_convert_then_step", "-6w", "-45d"),+ # 721h is just over 30 days; flooring to -30d would leave the+ # oldest partial day of the real request's span cold.+ ("hours_round_up", "-721h", "-45d"),+ ("cap_holds", "-90d", "-90d"),+ ]+ )+ def test_lookback_steps(self, _name: str, date_from: str, expected: str) -> None:+ query = {+ "kind": "WebOverviewQuery",+ "useWebAnalyticsPrecompute": True,+ "dateRange": {"date_from": date_from},+ }++ self.assertEqual(canonicalize_lazy_replay_json(query)["dateRange"]["date_from"], expected)++ def test_variant_fields_dropped_shape_fields_kept(self) -> None:+ query = {+ "kind": "WebStatsTableQuery",+ "useWebAnalyticsPrecompute": True,+ "properties": [{"key": "$host", "value": "posthog.com", "type": "event"}],+ "breakdownBy": "Browser",+ "filterTestAccounts": True,+ "dateRange": {"date_from": "-30d"},+ "compareFilter": {"compare": True},+ "limit": 50,+ "modifiers": {"sessionTableVersion": "v2"},+ "version": 2,+ }++ canonical = canonicalize_lazy_replay_json(query)++ for dropped in ("compareFilter", "limit", "modifiers", "version"):+ self.assertNotIn(dropped, canonical)+ self.assertEqual(canonical["properties"], query["properties"])+ self.assertEqual(canonical["breakdownBy"], "Browser")+ self.assertIs(canonical["filterTestAccounts"], True)+ self.assertIs(canonical["useWebAnalyticsPrecompute"], True)++ @parameterized.expand(+ [+ (+ "non_lazy_kind",+ {"kind": "WebExternalClicksTableQuery", "useWebAnalyticsPrecompute": True, "compareFilter": {}},+ ),+ ("opted_out", {"kind": "WebOverviewQuery", "useWebAnalyticsPrecompute": False, "compareFilter": {}}),+ ]+ )+ def test_off_lazy_path_is_untouched(self, _name: str, query: dict) -> None:+ self.assertIs(canonicalize_lazy_replay_json(query), query)++ @parameterized.expand(+ [+ # A bounded span keeps its faithful range for the same reason+ # deepening skips it, and non-exact forms have no monotonic depth+ # to step — both still shed the variant fields.+ ("bounded_range", {"date_from": "-7d", "date_to": "-1d"}),+ ("month_start", {"date_from": "mStart"}),+ ]+ )+ def test_unsteppable_ranges_keep_span_but_shed_variant_fields(self, _name: str, date_range: dict) -> None:+ query = {+ "kind": "WebOverviewQuery",+ "useWebAnalyticsPrecompute": True,+ "dateRange": date_range,+ "compareFilter": {"compare": True},+ }++ canonical = canonicalize_lazy_replay_json(query)++ self.assertEqual(canonical["dateRange"], date_range)+ self.assertNotIn("compareFilter", canonical)+class TestSplitWarmableQueries(BaseTest):def _shape(self, team_id: int, n: int) -> dict: