: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
perf(web-analytics): narrow frustration precompute scan to frustration events (#64378)
Lucas Ricoycf2cab489185
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.pyindex ca0cc4134a57..8d15e565f694 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py@@ -26,7 +26,11 @@ from posthog.models.utils import uuid7from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJobfrom products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner-from products.web_analytics.backend.hogql_queries.web_stats_frustration_lazy_precompute import can_use_lazy_precompute+from products.web_analytics.backend.hogql_queries.web_stats_frustration_lazy_precompute import (+ _FRUSTRATION_EVENT_TYPES,+ INSERT_QUERY_TEMPLATE,+ can_use_lazy_precompute,+)@override_settings(IN_UNIT_TESTING=True)@@ -135,6 +139,20 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):with self._enable_lazy():assert can_use_lazy_precompute(self._runner(self._build_query())) is True+ def test_insert_scans_only_frustration_event_types(self):+ # $pageview/$screen contribute 0 to every metric and their groups are+ # dropped by the HAVING, so the insert must not scan them — they only+ # inflate the GROUP BY cardinality that OOMs high-traffic teams.+ # Result-parity with the live (5-type) scan is covered by+ # test_lazy_response_matches_live.+ assert "{event_scan_filter}" in INSERT_QUERY_TEMPLATE+ assert "$pageview" not in INSERT_QUERY_TEMPLATE+ assert "$screen" not in INSERT_QUERY_TEMPLATE+ for frustration_event in ("$rageclick", "$dead_click", "$exception"):+ assert frustration_event in _FRUSTRATION_EVENT_TYPES+ assert "$pageview" not in _FRUSTRATION_EVENT_TYPES+ assert "$screen" not in _FRUSTRATION_EVENT_TYPES+def test_rejected_when_org_flag_off(self):# Default mocked-off feature flag: gate refuses.with patch(diff --git a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.pyindex dfdba2c753e6..12aea0aa4578 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py@@ -152,6 +152,26 @@ def _breakdown_value_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr:return ast.Field(chain=["events", "properties", "$pathname"])+# Frustration metrics only count `$rageclick` / `$dead_click` / `$exception`, so+# the insert scans only those — see the INSERT template note for why this is+# result-identical to also scanning `$pageview` / `$screen` and why it matters+# for memory. The runner is the single place to widen this list if a future+# breakdown or filter ever needs other event types.+_FRUSTRATION_EVENT_TYPES = ("$rageclick", "$dead_click", "$exception")+++def _event_scan_filter_expr() -> ast.Expr:+ # Built as AST (not string-interpolated into parse_expr) so there's no+ # injection surface — `events.event IN (<frustration types>)`.+ return ast.Call(+ name="in",+ args=[+ ast.Field(chain=["events", "event"]),+ ast.Call(name="tuple", args=[ast.Constant(value=event) for event in _FRUSTRATION_EVENT_TYPES]),+ ],+ )++# HogQL template for the precompute INSERT — a state-converted version of# the live `FRUSTRATION_METRICS_INNER_QUERY` + `FrustrationMetricsStrategy`# outer aggregation. The lazy_computation framework substitutes the listed@@ -161,7 +181,8 @@ def _breakdown_value_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr:# `expires_at` to the SELECT.## The inner subquery mirrors the live `FRUSTRATION_METRICS_INNER_QUERY`-# verbatim (per-session counts of rage / dead / exception events), and the+# (per-session counts of rage / dead / exception events) — bar the narrowed+# event-scan list noted below, which is result-equivalent — and the# outer aggregation mirrors the live `FrustrationMetricsStrategy.build_query`# OUTER (sums collapsed by breakdown) — but bucketed hourly so reads can# answer arbitrary date ranges via `sumMergeIf`. `sumState(...)` and `sum(...)`@@ -173,10 +194,19 @@ def _breakdown_value_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr:# `HAVING or(metric > 0, ...)` drops. Saves storing the all-zero rows that# the read query would only re-filter via its own `HAVING or(rage > 0, ...)`.#-# The `event IN (...)` filter restricts the scan to events that can possibly-# contribute to any of the three metrics, plus `$pageview` / `$screen` so the-# session-start anchoring is correct. The forward pad lets sessions that span-# a UTC-day boundary aggregate cleanly — same reasoning as overview/paths.+# The event-scan list (`{event_scan_filter}`) is restricted to the three+# frustration event types. `$pageview` / `$screen` contribute 0 to every metric+# and any resulting all-zero `(session, breakdown)` group is dropped by the+# outer `HAVING`, so scanning them only inflates the+# `GROUP BY session_id, breakdown_value` cardinality — the dominant cost behind+# insert OOMs on high-traffic teams. Narrowing is result-identical: session+# start comes from the `session.$start_timestamp` join (not scanned events), and+# each frustration event carries its own `$pathname`, so the surviving rows and+# sums are unchanged (verified by parity, with and without user filters). The+# runner owns the list via `_event_scan_filter_expr`, so a future breakdown or+# filter that genuinely needs other event types can widen it there. The forward+# pad lets sessions spanning a UTC-day boundary aggregate cleanly — same+# reasoning as overview/paths.INSERT_QUERY_TEMPLATE = """SELECTtoStartOfHour(start_timestamp) AS time_window_start,@@ -195,7 +225,7 @@ FROM (FROM eventsWHERE and({events_session_id} IS NOT NULL,- events.event IN ('$pageview', '$screen', '$rageclick', '$dead_click', '$exception'),+ {event_scan_filter},timestamp >= {time_window_min},timestamp < ({time_window_max} + toIntervalMinute({pad_minutes})),{user_filter},@@ -225,6 +255,7 @@ def ensure_web_stats_frustration_precomputed(placeholders: dict[str, ast.Expr] = {"events_session_id": _events_session_id_expr(runner),"breakdown_value_expr": _breakdown_value_expr(runner),+ "event_scan_filter": _event_scan_filter_expr(),"user_filter": host_filter_expr(runner.query.properties or []),"test_account_filter": test_account_filter_expr(test_account_filters=runner._test_account_filters, team=runner.team