: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): warm demand by normalized shape, not raw query json (#73936)
Lucas Ricoyefc4ecf35131
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 a61bc0f6f536..f12e62ae1133 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@@ -727,7 +727,7 @@ def compute_filters_eligibility_hash(query: Any, team_timezone: str) -> str:# distinct namespaces rather than per-request shapes. Otherwise a user could# exhaust the ceiling by replaying one filter with different ISO timestamps until# new legitimate shapes are forced onto the live path (veria review).-_SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS: frozenset[str] = _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS | frozenset(+SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS: frozenset[str] = _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS | frozenset({"dateRange", "compareFilter"})@@ -740,7 +740,7 @@ def compute_shape_cap_key(query: Any, team_timezone: str, test_account_filters:in stops an admin from minting fresh namespaces onto one cap slot by editing thetest-account filters (veria review)."""dumped = query.model_dump(mode="json", exclude_none=True, by_alias=False)- for key in _SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS:+ for key in SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS:dumped.pop(key, None)tafs = [f.model_dump(mode="json", exclude_none=True) if hasattr(f, "model_dump") else fdiff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex b6adaf061716..f191af417398 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -33,7 +33,10 @@ from products.analytics_platform.backend.lazy_computation.stale_policy import SHfrom products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import (can_use_lazy_precompute as can_use_goals_lazy_precompute,)-from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import BACKGROUND_WARMING_TRIGGERS+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ BACKGROUND_WARMING_TRIGGERS,+ SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS,+)from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (can_use_lazy_precompute as can_use_overview_lazy_precompute,)@@ -259,14 +262,20 @@ 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 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.+ # exist in production.) Demand is grouped by the NORMALIZED shape — the query+ # JSON with the range-varying and non-shape fields stripped+ # (SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS: dateRange, compareFilter, limit, …) —+ # which is the same set the precompute bucket namespace collapses to, so one+ # warmed -30d bucket serves every date-range variant of a shape. Grouping by+ # the raw JSON instead fragmented a shape queried across many date ranges into+ # many sub-threshold entries that never cleared min-count, even though warming+ # it once would serve them all; the largest, most date-varied teams were the+ # worst hit. any(query_json_raw) keeps a representative to replay — its date+ # range is widened to -30d anyway. Demand is counted as distinct query_ids so+ # duplicated log rows for one request can't inflate it. The per-shape hash is+ # cityHash64 of the group key rather than normalizedQueryHash(query), which+ # would read the full `query` SQL-text column — the largest in query_log —+ # across the whole window purely for a logging id.## 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@@ -285,12 +294,44 @@ def queries_to_keep_fresh(f"""SELECTteam_id,- query_json_raw,- uniqExact(query_id) AS query_count,- cityHash64(query_json_raw) AS normalized_query_hash+ -- Representative = the shape's most-requested exact variant (its real+ -- date range, modifiers, …). Picking the mode rather than an arbitrary+ -- any() keeps a rare ineligible variant — an all-time range, a UUID+ -- join mode requested once — from being the one that gets replayed.+ argMax(query_json_raw, variant_count) AS representative_query_json,+ -- Summed across variants so date/compare variants of one lazy shape+ -- combine to clear the selection floor: one shared bucket serves them.+ sum(variant_count) AS query_count,+ -- The representative variant's OWN demand. The raw (ineligible) replay+ -- path gates on this, not the sum, so an expensive variant can't+ -- inherit a popular sibling's demand — raw replays aren't shared, so+ -- each stale hour re-runs a full live query.+ max(variant_count) AS representative_query_count,+ cityHash64(normalized_shape) AS normalized_query_hashFROM (+ SELECT+ team_id,+ normalized_shape,+ query_json_raw,+ uniqExact(query_id) AS variant_count+ FROM (SELECTJSONExtractInt(log_comment, 'team_id') AS team_id,+ -- The shape key: every top-level query field except the range-+ -- varying / non-shape ones the precompute namespace ignores, so+ -- date-range and compare variants of one shape group together+ -- (char(31)/char(30) are control-char separators that can't occur+ -- in JSON keys). Sorted so field order in the payload is irrelevant.+ arrayStringConcat(+ arraySort(arrayMap(+ kv -> concat(kv.1, char(31), kv.2),+ arrayFilter(+ kv -> NOT has(%(shape_ignored_fields)s, kv.1),+ JSONExtractKeysAndValuesRaw(JSONExtractRaw(log_comment, 'query'))+ )+ )),+ char(30)+ ) AS normalized_shape,-- 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@@ -334,9 +375,14 @@ def queries_to_keep_fresh(-- selection and filled the cap with shapes no dashboard reader ever-- loads. UI and personal-API-key traffic are kept.AND request_kind != %(excluded_request_kind)s+ GROUP BY+ team_id,+ normalized_shape,+ query_json_raw+ ) AS variantsGROUP BYteam_id,- query_json_raw+ normalized_shapeHAVING query_count >= %(minimum_query_count)sORDER BYquery_count DESC@@ -349,6 +395,7 @@ def queries_to_keep_fresh("minimum_query_count": minimum_query_count,"max_shapes": max_shapes,"max_shapes_per_team": MAX_SHAPES_PER_TEAM,+ "shape_ignored_fields": sorted(SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS),"kind_prefix": WARMABLE_QUERY_KIND_PREFIX,"unwarmable_kinds": UNWARMABLE_QUERY_KINDS,"background_triggers": tuple(BACKGROUND_WARMING_TRIGGERS | SHARED_BACKGROUND_WARMING_TRIGGERS),@@ -363,7 +410,8 @@ def queries_to_keep_fresh("team_id": result[0],"query_json": json.loads(result[1]),"query_count": result[2],- "normalized_query_hash": result[3],+ "representative_query_count": result[3],+ "normalized_query_hash": result[4],}for result in results]@@ -387,7 +435,7 @@ def queries_to_keep_fresh(# selection query (new filter, different grouping) would otherwise keep replaying# a stale blob written by the old logic until its TTL expired. Bump the version# whenever the selection query changes so the new logic takes effect on deploy.-_WARMABLE_QUERIES_STORAGE_KEY = "web_analytics/warmable_queries/v2.json.gz"+_WARMABLE_QUERIES_STORAGE_KEY = "web_analytics/warmable_queries/v3.json.gz"def _read_cached_warmable_queries(@@ -519,8 +567,11 @@ def warm_queries_op(context: dagster.OpExecutionContext, queries: list[dict]) -># one cheap today-bucket refresh), but an ineligible shape replays as# a full live query every stale hour — with the min-2 floor a tenant# could mint MAX_SHAPES_PER_TEAM such shapes from two runs each and- # have the warmer amplify them outside request throttles.- if not lazy_eligible and query_info.get("query_count", 0) < RAW_REPLAY_MIN_QUERY_COUNT:+ # have the warmer amplify them outside request throttles. Gate on the+ # representative variant's own demand, not the shape-wide sum: raw+ # replays aren't shared across variants, so a rarely-run expensive+ # variant must not inherit a popular sibling's count.+ if not lazy_eligible and query_info.get("representative_query_count", 0) < RAW_REPLAY_MIN_QUERY_COUNT:WARMING_QUERIES_COUNTER.labels(outcome="skipped_raw_low_demand").inc()return "skipped_raw_low_demand"diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.pyindex f22c6190a41a..e6d3eb7ff771 100644--- a/products/web_analytics/dags/tests/test_cache_warming.py+++ b/products/web_analytics/dags/tests/test_cache_warming.py@@ -178,10 +178,12 @@ class TestFleetQuerySelection(BaseTest):@patch("products.web_analytics.dags.cache_warming.sync_execute")def test_parses_fleet_rows_into_query_infos(self, mock_exec: MagicMock) -> None:# Guards the row-shape contract with the selection SQL: a column reorder- # or JSON handling change would make the warmer warm nothing or crash.+ # or JSON handling change would make the warmer warm nothing or crash. The+ # summed and representative counts are distinct columns — the raw guard+ # keys on the representative, so they must not be swapped.mock_exec.return_value = [- (101, '{"kind": "WebOverviewQuery"}', 50, "hash-a"),- (202, '{"kind": "WebStatsTableQuery"}', 12, "hash-b"),+ (101, '{"kind": "WebOverviewQuery"}', 50, 8, "hash-a"),+ (202, '{"kind": "WebStatsTableQuery"}', 12, 12, "hash-b"),]result = queries_to_keep_fresh(dagster.build_op_context(), days=7, minimum_query_count=10, max_shapes=100)@@ -192,12 +194,14 @@ class TestFleetQuerySelection(BaseTest):"team_id": 101,"query_json": {"kind": "WebOverviewQuery"},"query_count": 50,+ "representative_query_count": 8,"normalized_query_hash": "hash-a",},{"team_id": 202,"query_json": {"kind": "WebStatsTableQuery"},"query_count": 12,+ "representative_query_count": 12,"normalized_query_hash": "hash-b",},],@@ -247,7 +251,7 @@ class TestWarmableQueriesCaching(BaseTest):# 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)]+ mock_exec.return_value = [(101, '{"kind": "WebOverviewQuery"}', 50, 50, 123)]first = get_warmable_queries_op(dagster.build_op_context())second = get_warmable_queries_op(dagster.build_op_context())@@ -261,7 +265,7 @@ class TestWarmableQueriesCaching(BaseTest):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)]+ mock_exec.return_value = [(101, '{"kind": "WebOverviewQuery"}', 50, 50, 123)]result = get_warmable_queries_op(dagster.build_op_context())@@ -274,7 +278,7 @@ class TestWarmableQueriesCaching(BaseTest):# 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)]+ mock_exec.return_value = [(101, '{"kind": "WebOverviewQuery"}', 50, 50, 123)]result = get_warmable_queries_op(dagster.build_op_context())@@ -285,17 +289,16 @@ class TestWarmableQueriesCaching(BaseTest):class TestWarmQueriesOp(BaseTest):@parameterized.expand([- # A raw-path (not lazy-eligible) shape below the pre-widening demand- # bar must not replay: with the min-2 selection floor, two runs of an- # expensive ineligible shape would otherwise become hourly background- # scans outside the tenant's request throttles.+ # A raw-path (not lazy-eligible) shape below the demand bar must not+ # replay: an expensive ineligible shape would otherwise become an+ # hourly background scan outside the tenant's request throttles.("raw_low_demand_skipped", False, 2, 0),("raw_high_demand_warms", False, 10, 1),("lazy_low_demand_warms", True, 2, 1),])def test_raw_replays_keep_higher_demand_bar(- self, _name: str, lazy_eligible: bool, query_count: int, expected_runs: int+ self, _name: str, lazy_eligible: bool, representative_query_count: int, expected_runs: int) -> None:runner = MagicMock()runner.get_cache_key.return_value = f"key-{_name}"@@ -313,7 +316,11 @@ class TestWarmQueriesOp(BaseTest):{"team_id": self.team.pk,"query_json": {"kind": "WebOverviewQuery", "properties": []},- "query_count": query_count,+ # Shape-wide sum is deliberately high: the raw guard must+ # read the representative's own count, so a high sum can't+ # promote a rarely-run expensive variant.+ "query_count": 999,+ "representative_query_count": representative_query_count,"normalized_query_hash": "h",}],