: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): cache warmer demand selection to widen the lookback window (#73493)
Lucas Ricoy62ae082a8ef5
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex 231de1a42ed9..aefe265c2056 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -113,6 +113,7 @@ jobs:- 'posthog/person_db_router.py'- 'posthog/persons_db.py'- 'posthog/redis.py'+ - 'posthog/storage/**'- 'posthog/event_usage.py'- 'posthog/products.py'- 'posthog/cloud_utils.py'diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex 97fffbefc28d..cd74cc855748 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -287,9 +287,17 @@ CONSTANCE_CONFIG = {bool,),"WEB_ANALYTICS_WARMING_DAYS": (- get_from_env("WEB_ANALYTICS_WARMING_DAYS", default=2, type_cast=int),+ get_from_env("WEB_ANALYTICS_WARMING_DAYS", default=14, type_cast=int),"Number of days of system.query_log to look back for frequently-run web analytics queries. "- "Selection scans log_comment fleet-wide (terabytes per day), so keep this small.",+ "A longer window catches teams that use web analytics every few days rather than daily. "+ "The selection is cached (WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS), so the fleet-wide "+ "scan runs on that cadence — not every warming run.",+ int,+ ),+ "WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS": (+ get_from_env("WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS", default=21600, type_cast=int),+ "How long the fleet-wide demand selection is cached in object storage. Warming replays the "+ "cached shape list every run; the expensive query_log scan only re-runs once this expires (default 6h).",int,),"WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT": (@@ -304,9 +312,11 @@ CONSTANCE_CONFIG = {list[int],),"WEB_ANALYTICS_WARMING_MAX_SHAPES": (- get_from_env("WEB_ANALYTICS_WARMING_MAX_SHAPES", default=40000, type_cast=int),+ get_from_env("WEB_ANALYTICS_WARMING_MAX_SHAPES", default=400000, type_cast=int),"Cap on the number of hot query shapes web analytics warming selects fleet-wide per run. "- "Sized above the ~29k shapes the min=2 selection produces so the cap doesn't silently truncate.",+ "Sized above the ~234k shapes the 14-day min=2 selection produces, with headroom for growth, so "+ "the cap doesn't silently truncate weekly-cadence teams; raising it warms more shapes at the cost "+ "of more background compute.",int,),}@@ -363,6 +373,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = ("CLICKHOUSE_HEDGED_APP_QUERIES","REDIRECT_APP_TO_US","WEB_ANALYTICS_WARMING_DAYS",+ "WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS","WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT","WEB_ANALYTICS_WARMING_MAX_SHAPES",)diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex abb263195a1d..fd72e1b7ea80 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -1,5 +1,7 @@import re+import gzipimport json+import timeimport threadingimport statisticsfrom concurrent.futures import ThreadPoolExecutor@@ -25,6 +27,7 @@ from posthog.hogql_queries.query_runner import get_query_runner_or_nonefrom posthog.models import Teamfrom posthog.models.instance_setting import get_instance_settingfrom posthog.settings import CLICKHOUSE_CLUSTER+from posthog.storage import object_storagefrom products.analytics_platform.backend.lazy_computation.stale_policy import SHARED_BACKGROUND_WARMING_TRIGGERSfrom products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import (@@ -99,6 +102,12 @@ UNWARMABLE_QUERY_KINDS = ("WebVitalsQuery",)INTERNAL_QUERY_TYPE_SUFFIXES = ("_lazy_insert", "_preflight")_INTERNAL_QUERY_TYPE_FILTER = " OR ".join(f"endsWith(query_type, '{s}')" for s in INTERNAL_QUERY_TYPE_SUFFIXES)+# Read-bytes ceiling for the demand-selection scan. The 14-day fleet-wide+# query_log scan reads ~40 TiB, over the default cap, so it's raised — but to a+# finite value (~150 TiB, generous headroom for fleet growth) rather than 0, so+# the ClickHouse kill switch's overload cap still clamps it during an overload.+_SELECTION_MAX_BYTES_TO_READ = 150 * 1024**4+def maybe_opt_into_lazy_precompute(query_json: dict) -> dict:"""Opt a replayed query into the lazy precompute path.@@ -243,10 +252,23 @@ def queries_to_keep_fresh(# to offline nodes, while the user traffic we want to replay lands on other# replicas. (metrics_query_log_mv only looks usable — its DDL in# posthog/models/query_metrics/sql.py was never migrated, the table does not- # exist in production.) Grouping by the query JSON alone (hash only kept for- # logging) collapses strategy variants of one shape into one replay, and- # demand is counted as distinct query_ids so duplicated log rows for one- # request can't inflate it. The+ # exist in production.) Grouping by the query JSON alone collapses strategy+ # variants of one shape into one replay, and demand is counted as distinct+ # query_ids so duplicated log rows for one request can't inflate it. The+ # per-shape hash is derived from the JSON we already read out of log_comment+ # (cityHash64 of the group key) rather than normalizedQueryHash(query): the+ # latter reads the full `query` SQL-text column — the largest column in+ # query_log — across the whole window purely for a logging id, which over a+ # multi-day scan dominates the read cost.+ #+ # The scan spans the whole WEB_ANALYTICS_WARMING_DAYS window fleet-wide, which+ # exceeds the default max_bytes_to_read, so the cap is raised to+ # _SELECTION_MAX_BYTES_TO_READ — a finite value, not 0, so the ClickHouse+ # kill switch's overload byte cap still clamps it (min(kill_switch_cap, ours))+ # and the giant scan is refused rather than piled on during an overload. The+ # run is also bounded by max_execution_time and by the demand-selection cache+ # upstream, so this heavy scan happens on the cache TTL cadence, not every run.+ ## trigger/feature exclusions keep the warmer's own replays — and every other# background warmer — out of the demand counts, otherwise a once-warmed shape# would keep itself hot forever. LIKE literals are %%-escaped because@@ -258,23 +280,34 @@ def queries_to_keep_fresh(team_id,query_json_raw,uniqExact(query_id) AS query_count,- any(normalized_query_hash) AS normalized_query_hash+ cityHash64(query_json_raw) AS normalized_query_hashFROM (SELECTJSONExtractInt(log_comment, 'team_id') AS team_id,- JSONExtractString(log_comment, 'query', 'kind') AS query_kind,+ -- aliased away from the native `query_kind` column so the PREWHERE+ -- below binds to the column (Select/Insert/…), not this JSON kind+ -- (WebOverviewQuery/…); with prefer_column_name_to_alias=0 a name+ -- collision would resolve `query_kind = 'Select'` against the alias+ -- and silently select nothing.+ JSONExtractString(log_comment, 'query', 'kind') AS web_query_kind,JSONExtractString(log_comment, 'query_type') AS query_type,JSONExtractString(log_comment, 'trigger') AS trigger,JSONExtractString(log_comment, 'feature') AS feature,JSONExtractRaw(log_comment, 'query') AS query_json_raw,- normalizedQueryHash(query) AS normalized_query_hash,query_idFROM clusterAllReplicas(%(cluster)s, system.query_log)+ -- Filter the cheap native columns first so the big log_comment String+ -- is read only for surviving rows. is_initial_query alone drops roughly+ -- nine-tenths of the window (the rest are distributed subqueries), and+ -- query_kind excludes the warmer's own INSERT replays without a JSON+ -- parse — every warmable web query executes as a Select.+ PREWHERE+ type = 'QueryFinish'+ AND is_initial_query+ AND query_kind = 'Select'WHEREevent_date >= toDate(now() - INTERVAL %(days)s DAY)AND event_time >= now() - INTERVAL %(days)s DAY- AND type = 'QueryFinish'- AND is_initial_query-- cheap substring prefilter before any JSON extraction; a-- superset of the kind filter below, false positives re-checkedAND log_comment LIKE '%%{WARMABLE_QUERY_KIND_PREFIX}%%'@@ -282,8 +315,8 @@ def queries_to_keep_fresh(WHEREteam_id != 0AND query_json_raw != ''- AND startsWith(query_kind, %(kind_prefix)s)- AND query_kind NOT IN %(unwarmable_kinds)s+ AND startsWith(web_query_kind, %(kind_prefix)s)+ AND web_query_kind NOT IN %(unwarmable_kinds)sAND NOT ({_INTERNAL_QUERY_TYPE_FILTER})AND trigger NOT IN %(background_triggers)sAND feature != %(cache_warmup_feature)s@@ -307,6 +340,7 @@ def queries_to_keep_fresh("background_triggers": tuple(BACKGROUND_WARMING_TRIGGERS | SHARED_BACKGROUND_WARMING_TRIGGERS),"cache_warmup_feature": Feature.CACHE_WARMUP.value,},+ settings={"max_bytes_to_read": _SELECTION_MAX_BYTES_TO_READ, "max_execution_time": 600},)return [@@ -320,22 +354,87 @@ def queries_to_keep_fresh(]+# The demand selection scans terabytes of query_log fleet-wide, so its result is+# cached in Redis and shared across warming runs: the hourly warmer replays the+# cached shape list and the scan only re-runs once the cache expires+# (WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS). This is what lets the lookback+# window grow to weeks without multiplying the scan by the warming cadence.+#+# The payload is stored in object storage rather than Redis: at the default cap+# it is already ~34 MiB uncompressed (~890 bytes per shape × max_shapes) and+# grows linearly as max_shapes is raised for coverage, which is a poor fit for a+# single Redis value. The cached blob embeds the selection parameters and a+# timestamp so a settings change or an entry older than the TTL is treated as a+# miss — object storage has no per-key expiry of its own.+_WARMABLE_QUERIES_STORAGE_KEY = "web_analytics/warmable_queries/v1.json.gz"+++def _read_cached_warmable_queries(+ days: int, minimum_query_count: int, max_shapes: int, ttl_seconds: int+) -> Optional[list[dict]]:+ # Fail open: any storage, decode, or unexpected-payload problem is treated as+ # a miss so warming falls back to a fresh scan rather than erroring. The field+ # access stays inside the try so a decodable-but-malformed blob (wrong shape,+ # bad field type) misses rather than crashing the hourly run.+ try:+ raw = object_storage.read_bytes(_WARMABLE_QUERIES_STORAGE_KEY, missing_ok=True)+ if raw is None:+ return None+ payload = json.loads(gzip.decompress(raw))+ params_match = (payload["days"], payload["minimum_query_count"], payload["max_shapes"]) == (+ days,+ minimum_query_count,+ max_shapes,+ )+ is_fresh = time.time() - payload["generated_at"] < ttl_seconds+ if not params_match or not is_fresh:+ return None+ return payload["queries"]+ except Exception:+ logger.warning("web_analytics_warming_cache_read_failed", exc_info=True)+ return None+++def _write_cached_warmable_queries(days: int, minimum_query_count: int, max_shapes: int, queries: list[dict]) -> None:+ payload = {+ "days": days,+ "minimum_query_count": minimum_query_count,+ "max_shapes": max_shapes,+ "generated_at": time.time(),+ "queries": queries,+ }+ try:+ object_storage.write(_WARMABLE_QUERIES_STORAGE_KEY, gzip.compress(json.dumps(payload).encode()))+ except Exception:+ logger.warning("web_analytics_warming_cache_write_failed", exc_info=True)++@dagster.opdef get_warmable_queries_op(context: dagster.OpExecutionContext) -> list[dict]:days = get_instance_setting("WEB_ANALYTICS_WARMING_DAYS")minimum_query_count = get_instance_setting("WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT")max_shapes = get_instance_setting("WEB_ANALYTICS_WARMING_MAX_SHAPES")+ ttl_seconds = get_instance_setting("WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS")++ queries = _read_cached_warmable_queries(days, minimum_query_count, max_shapes, ttl_seconds)+ from_cache = queries is not None+ if queries is None:+ queries = queries_to_keep_fresh(+ context, days=days, minimum_query_count=minimum_query_count, max_shapes=max_shapes+ )+ _write_cached_warmable_queries(days, minimum_query_count, max_shapes, queries)- queries = queries_to_keep_fresh(context, days=days, minimum_query_count=minimum_query_count, max_shapes=max_shapes)team_count = len({q["team_id"] for q in queries})WARMING_SHAPES_SELECTED_GAUGE.set(len(queries))- context.log.info(f"Selected {len(queries)} hot query shapes across {team_count} teams")+ source = "cached" if from_cache else "freshly selected"+ context.log.info(f"Warming {len(queries)} {source} hot query shapes across {team_count} teams")context.add_output_metadata({"query_count": len(queries),"team_count": team_count,"cap_reached": len(queries) >= max_shapes,+ "from_cache": from_cache,})return queriesdiff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.pyindex 84d9e0b1f0ea..c797d8154272 100644--- a/products/web_analytics/dags/tests/test_cache_warming.py+++ b/products/web_analytics/dags/tests/test_cache_warming.py@@ -1,3 +1,6 @@+import gzip+import json+from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -213,14 +216,72 @@ class TestFleetQuerySelection(BaseTest):self.assertIn("LIKE '%Web%'", rendered)self.assertIn("system.query_log", rendered)+ @patch("products.web_analytics.dags.cache_warming._read_cached_warmable_queries", return_value=None)+ @patch("products.web_analytics.dags.cache_warming._write_cached_warmable_queries")@patch("products.web_analytics.dags.cache_warming.sync_execute", return_value=[])- def test_op_reads_instance_settings(self, _mock_exec: MagicMock) -> None:+ def test_op_reads_instance_settings(+ self, _mock_exec: MagicMock, _mock_write: MagicMock, _mock_read: MagicMock+ ) -> None:# Runs the op against the real instance-setting machinery so a renamed or- # unregistered setting key fails here instead of at the hourly run.+ # unregistered setting key fails here instead of at the hourly run. Cache+ # forced to miss so the assertion doesn't depend on Redis state.result = get_warmable_queries_op(dagster.build_op_context())self.assertEqual(result, [])+class _FakeObjectStorage:+ def __init__(self) -> None:+ self.store: dict[str, bytes] = {}++ def read_bytes(self, key: str, bucket: str | None = None, *, missing_ok: bool = False) -> bytes | None:+ return self.store.get(key)++ def write(self, key: str, content: bytes, extras: dict | None = None, bucket: str | None = None) -> None:+ self.store[key] = content+++class TestWarmableQueriesCaching(BaseTest):+ @patch("products.web_analytics.dags.cache_warming.object_storage", new_callable=_FakeObjectStorage)+ @patch("products.web_analytics.dags.cache_warming.sync_execute")+ def test_second_run_reuses_cached_selection(self, mock_exec: MagicMock, _storage: _FakeObjectStorage) -> None:+ # The whole reason this cache exists: the fleet-wide query_log scan is+ # terabytes. If the cache read regresses, the scan runs every warming run+ # again — this fails when the second run re-hits ClickHouse.+ mock_exec.return_value = [(101, '{"kind": "WebOverviewQuery"}', 50, 123)]++ first = get_warmable_queries_op(dagster.build_op_context())+ second = get_warmable_queries_op(dagster.build_op_context())++ self.assertEqual(mock_exec.call_count, 1)+ self.assertEqual(first, second)+ self.assertEqual(first[0]["team_id"], 101)++ @patch("products.web_analytics.dags.cache_warming.object_storage")+ @patch("products.web_analytics.dags.cache_warming.sync_execute")+ def test_storage_failure_falls_back_to_scan(self, mock_exec: MagicMock, mock_storage: MagicMock) -> None:+ # Object storage being unavailable must degrade to a fresh scan, not break warming.+ mock_storage.read_bytes.side_effect = Exception("storage unavailable")+ mock_exec.return_value = [(101, '{"kind": "WebOverviewQuery"}', 50, 123)]++ result = get_warmable_queries_op(dagster.build_op_context())++ self.assertEqual(len(result), 1)+ self.assertEqual(mock_exec.call_count, 1)++ @patch("products.web_analytics.dags.cache_warming.object_storage")+ @patch("products.web_analytics.dags.cache_warming.sync_execute")+ def test_malformed_cache_payload_falls_back_to_scan(self, mock_exec: MagicMock, mock_storage: MagicMock) -> None:+ # A decodable-but-malformed blob (missing the expected fields) must miss+ # and trigger a fresh scan, not raise out of the op and skip warming.+ mock_storage.read_bytes.return_value = gzip.compress(json.dumps({"unexpected": "shape"}).encode())+ mock_exec.return_value = [(101, '{"kind": "WebOverviewQuery"}', 50, 123)]++ result = get_warmable_queries_op(dagster.build_op_context())++ self.assertEqual(len(result), 1)+ self.assertEqual(mock_exec.call_count, 1)++class TestWarmQueriesOp(BaseTest):@parameterized.expand([