: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): drop the ineligible reason off non-live reads (#92827)
posthog[bot]eb42fb05dd38
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.pyindex f5feb1ebebdc..24c0895fd9d6 100644--- a/products/web_analytics/backend/hogql_queries/stats_table.py+++ b/products/web_analytics/backend/hogql_queries/stats_table.py@@ -254,6 +254,35 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryResponsreturn SimpleBreakdownStrategy(self)+ def _owning_lazy_precompute_family(self) -> Literal["paths", "frustration", "simple"]:+ """Which precompute family is the only one that could serve this query shape.++ Mirrors the family-level branches of `_get_strategy` above, deliberately not its join+ variants: those pick how a family runs the query, not which family owns it. The two+ taxonomies diverge in one place. INITIAL_PAGE with bounce rate is a simple breakdown with an+ entry-pathname override on the live path, but the paths family is what precomputes it.++ The families are disjoint, so asking only the owner loses no precompute hit: PAGE,+ INITIAL_PAGE and FRUSTRATION_METRICS are all absent from the simple family's+ SUPPORTED_BREAKDOWNS.+ """+ breakdown = self._effective_breakdown()++ if breakdown == WebStatsBreakdown.FRUSTRATION_METRICS:+ return "frustration"++ if (+ breakdown == WebStatsBreakdown.PAGE+ and not self.query.conversionGoal+ and (self.query.includeAvgTimeOnPage or self.query.includeBounceRate)+ ):+ return "paths"++ if breakdown == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:+ return "paths"++ return "simple"+def _order_by(self, columns: list[str]) -> list[ast.OrderExpr] | None:column = Nonedirection: Literal["ASC", "DESC"] = "DESC"@@ -735,20 +764,23 @@ WHERE and(return field, directiondef _calculate(self):- # Try each lazy precompute path in turn. Each `can_use_*` check short-- # circuits on the wrong `breakdownBy`, so the order only matters for- # rejection reason attribution in logs/metrics.- lazy_response = self._maybe_calculate_via_lazy_precompute()- if lazy_response is not None:- return lazy_response-- lazy_response = self._maybe_calculate_via_frustration_lazy_precompute()- if lazy_response is not None:- return lazy_response-- lazy_result = self.get_lazy_precomputed_result()- if lazy_result is not None:- return self._build_response_from_lazy(lazy_result)+ # Ask only the family that owns this shape. Trying all three in turn made the other two+ # refuse a query they could never have served, and each refusal recorded its own rejection+ # reason, so the last gate to run decided what the read reported.+ family = self._owning_lazy_precompute_family()++ if family == "paths":+ lazy_response = self._maybe_calculate_via_lazy_precompute()+ if lazy_response is not None:+ return lazy_response+ elif family == "frustration":+ lazy_response = self._maybe_calculate_via_frustration_lazy_precompute()+ if lazy_response is not None:+ return lazy_response+ else:+ lazy_result = self.get_lazy_precomputed_result()+ if lazy_result is not None:+ return self._build_response_from_lazy(lazy_result)# Preflight only when the live query will actually run as the id-set# shape — pre-aggregated serving must not pay a discarded events scan.@@ -809,6 +841,12 @@ WHERE and(columns = [*list(columns), "context.columns.cross_sell"]results_mapped = [[*row, ""] for row in (results_mapped or [])]+ strategy = (+ WebAnalyticsPreComputeStrategy.PRE_AGGREGATED+ if self.used_preaggregated_tables+ else WebAnalyticsPreComputeStrategy.LIVE+ )+return WebStatsTableQueryResponse(columns=columns,results=results_mapped,@@ -816,12 +854,8 @@ WHERE and(types=response.types,hogql=response.hogql,modifiers=self.modifiers,- preComputeStrategy=(- WebAnalyticsPreComputeStrategy.PRE_AGGREGATED- if self.used_preaggregated_tables- else WebAnalyticsPreComputeStrategy.LIVE- ),- preComputeIneligibleReason=lazy_precompute_ineligible_reason(),+ preComputeStrategy=strategy,+ preComputeIneligibleReason=lazy_precompute_ineligible_reason(strategy),**self.paginator.response_params(),)diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.pyindex 5796caba2608..6a6276958147 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py@@ -13,11 +13,13 @@ from structlog.contextvars import get_contextvarsfrom posthog.schema import (CohortPropertyFilter,CompareFilter,+ CustomEventConversionGoal,DateRange,EventPropertyFilter,PersonPropertyFilter,PropertyOperator,SessionPropertyFilter,+ WebAnalyticsPreComputeStrategy,WebOverviewQuery,WebStatsBreakdown,WebStatsTableQuery,@@ -61,6 +63,9 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common impweb_ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner+from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import (+ can_use_lazy_precompute as can_use_stats_lazy_precompute,+)from products.web_analytics.backend.tasks.lazy_precompute_revalidation import REVALIDATION_EXPIRES_SECONDS_COMMON = "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common"@@ -172,10 +177,143 @@ class TestEligibilityReasonTagging(BaseTest):def test_rejection_reason_is_tagged_then_cleared_once_a_gate_admits(self) -> None:log_eligibility_outcome(log_prefix="web_goals", team_id=self.team.pk, error=DateRangeOverMax(120))- assert lazy_precompute_ineligible_reason() == "DateRangeOverMax"+ assert lazy_precompute_ineligible_reason(WebAnalyticsPreComputeStrategy.LIVE) == "DateRangeOverMax"log_eligibility_outcome(log_prefix="web_goals", team_id=self.team.pk, error=None)- assert lazy_precompute_ineligible_reason() is None+ assert lazy_precompute_ineligible_reason(WebAnalyticsPreComputeStrategy.LIVE) is None++ @parameterized.expand(+ [+ (WebAnalyticsPreComputeStrategy.PRE_AGGREGATED,),+ (WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE,),+ ]+ )+ def test_rejection_reason_is_dropped_when_another_strategy_serves_the_read(+ self, strategy: WebAnalyticsPreComputeStrategy+ ) -> None:+ # The lazy gate can refuse a read that the pre-aggregated tables then serve. Telemetry that+ # breaks down by the reason must not count such a read as live.+ log_eligibility_outcome(log_prefix="web_stats_table", team_id=self.team.pk, error=DateRangeOverMax(120))++ assert lazy_precompute_ineligible_reason(strategy) is None++ def test_a_remapped_breakdown_records_a_reason(self) -> None:+ # First-pageview attribution rewrites the breakdown and no family precomputes the rewritten+ # shape, so this gate refuses before any reason is recorded. Left silent, the read is+ # indistinguishable from one the owning family admitted but had no data for.+ runner = WebStatsTableQueryRunner(+ team=self.team,+ query=WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"),+ properties=[],+ breakdownBy=WebStatsBreakdown.INITIAL_UTM_SOURCE,+ ),+ )++ with mock.patch.object(+ WebStatsTableQueryRunner,+ "_first_pageview_attribution_enabled",+ new_callable=mock.PropertyMock,+ return_value=True,+ ):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):+ assert not can_use_stats_lazy_precompute(runner)++ assert lazy_precompute_ineligible_reason(WebAnalyticsPreComputeStrategy.LIVE) == "BreakdownRemapped"+++class TestOwningLazyPrecomputeFamily(BaseTest):+ @parameterized.expand(+ [+ (+ "page with bounce rate",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"),+ properties=[],+ breakdownBy=WebStatsBreakdown.PAGE,+ includeBounceRate=True,+ ),+ "paths",+ ),+ (+ "page with avg time and no bounce rate",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"),+ properties=[],+ breakdownBy=WebStatsBreakdown.PAGE,+ includeAvgTimeOnPage=True,+ ),+ "paths",+ ),+ (+ "page with neither",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"), properties=[], breakdownBy=WebStatsBreakdown.PAGE+ ),+ "simple",+ ),+ (+ "page with a conversion goal",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"),+ properties=[],+ breakdownBy=WebStatsBreakdown.PAGE,+ includeBounceRate=True,+ conversionGoal=CustomEventConversionGoal(customEventName="signed_up"),+ ),+ "simple",+ ),+ (+ "entry page with bounce rate",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"),+ properties=[],+ breakdownBy=WebStatsBreakdown.INITIAL_PAGE,+ includeBounceRate=True,+ ),+ "paths",+ ),+ (+ "entry page without bounce rate",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"), properties=[], breakdownBy=WebStatsBreakdown.INITIAL_PAGE+ ),+ "simple",+ ),+ (+ "frustration metrics",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"),+ properties=[],+ breakdownBy=WebStatsBreakdown.FRUSTRATION_METRICS,+ ),+ "frustration",+ ),+ (+ "previous page",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"), properties=[], breakdownBy=WebStatsBreakdown.PREVIOUS_PAGE+ ),+ "simple",+ ),+ (+ "browser",+ WebStatsTableQuery(+ dateRange=DateRange(date_from="-7d"), properties=[], breakdownBy=WebStatsBreakdown.BROWSER+ ),+ "simple",+ ),+ ]+ )+ def test_family_mirrors_the_live_strategy_taxonomy(+ self, _name: str, query: WebStatsTableQuery, expected: str+ ) -> None:+ # The classifier hand-mirrors the family-level branches of `_get_strategy`, and drift is+ # silent either way: too narrow and a read consults a family that could never serve it, too+ # broad and it skips the family that can and loses the precompute hit.+ runner = WebStatsTableQueryRunner(team=self.team, query=query)++ assert runner._owning_lazy_precompute_family() == expectedclass TestCacheKeyVariesWithRolloutState(BaseTest):diff --git a/products/web_analytics/backend/hogql_queries/web_goals.py b/products/web_analytics/backend/hogql_queries/web_goals.pyindex 533367927dae..7d940ec445c8 100644--- a/products/web_analytics/backend/hogql_queries/web_goals.py+++ b/products/web_analytics/backend/hogql_queries/web_goals.py@@ -205,7 +205,7 @@ WHERE {periods_expression}results=[],modifiers=self.modifiers,preComputeStrategy=WebAnalyticsPreComputeStrategy.LIVE,- preComputeIneligibleReason=lazy_precompute_ineligible_reason(),+ preComputeIneligibleReason=lazy_precompute_ineligible_reason(WebAnalyticsPreComputeStrategy.LIVE),)response = execute_hogql_query(@@ -270,7 +270,7 @@ WHERE {periods_expression}results=results,modifiers=self.modifiers,preComputeStrategy=WebAnalyticsPreComputeStrategy.LIVE,- preComputeIneligibleReason=lazy_precompute_ineligible_reason(),+ preComputeIneligibleReason=lazy_precompute_ineligible_reason(WebAnalyticsPreComputeStrategy.LIVE),)def _maybe_calculate_via_lazy_precompute(self) -> Optional[WebGoalsQueryResponse]: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 2d3b9507cb0f..2fd2e56859c4 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@@ -24,7 +24,7 @@ import structlogimport posthoganalyticsfrom prometheus_client import Counter-from posthog.schema import SessionsV2JoinMode+from posthog.schema import SessionsV2JoinMode, WebAnalyticsPreComputeStrategyfrom posthog.hogql import astfrom posthog.hogql.property import get_property_type, property_to_expr@@ -742,7 +742,15 @@ def set_lazy_precompute_ineligible_reason(reason: Optional[str]) -> None:tag_queries(web_analytics_precompute_ineligible_reason=reason)-def lazy_precompute_ineligible_reason() -> Optional[str]:+def lazy_precompute_ineligible_reason(strategy: WebAnalyticsPreComputeStrategy) -> Optional[str]:+ """Give the reason a gate refused this read, but only for a response the live path served.++ The gates run before the runner selects a strategy. A read the lazy gate rejects can still be+ served from the pre-aggregated tables, so the tag must not ride out next to a strategy that is+ not `LIVE`.+ """+ if strategy != WebAnalyticsPreComputeStrategy.LIVE:+ return Nonereturn get_query_tag_value("web_analytics_precompute_ineligible_reason")diff --git a/products/web_analytics/backend/hogql_queries/web_overview.py b/products/web_analytics/backend/hogql_queries/web_overview.pyindex c62acefb7829..c5afa8c8a4cf 100644--- a/products/web_analytics/backend/hogql_queries/web_overview.py+++ b/products/web_analytics/backend/hogql_queries/web_overview.py@@ -398,17 +398,19 @@ CROSS JOIN {sessions_agg} AS sessions_aggto_data("bounce rate", "percentage", row[8], get_prev_val(9), is_increase_bad=True),]+ strategy = (+ WebAnalyticsPreComputeStrategy.PRE_AGGREGATED+ if response == pre_aggregated_response+ else WebAnalyticsPreComputeStrategy.LIVE+ )+return WebOverviewQueryResponse(results=results,modifiers=self.modifiers,dateFrom=self.query_date_range.date_from_str,dateTo=self.query_date_range.date_to_str,- preComputeStrategy=(- WebAnalyticsPreComputeStrategy.PRE_AGGREGATED- if response == pre_aggregated_response- else WebAnalyticsPreComputeStrategy.LIVE- ),- preComputeIneligibleReason=lazy_precompute_ineligible_reason(),+ preComputeStrategy=strategy,+ preComputeIneligibleReason=lazy_precompute_ineligible_reason(strategy),)@cached_propertydiff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.pyindex 3297855c7f4c..bcdf42451f89 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py@@ -40,6 +40,7 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute)from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (handle_stale_served,+ set_lazy_precompute_ineligible_reason,web_ensure_precomputed,)@@ -197,6 +198,13 @@ def can_use_lazy_precompute(runner: "WebStatsTableQueryRunner") -> bool:"""Return True iff the lazy precompute path is eligible for this web statstable query — the shared web analytics gate plus stats-specific checks."""if runner._effective_breakdown() != runner.query.breakdownBy:+ # First-pageview attribution rewrites the breakdown, and no family precomputes the rewritten+ # shape. This returns before the shared gate that would otherwise log and record, so do both+ # here. Left silent, the read reports no reason at all, which is how a read the owning family+ # admitted but had no data for reports. Recorded as a bare name rather than an exception+ # because nothing raises it, and the two families' exceptions come from different hierarchies.+ set_lazy_precompute_ineligible_reason("BreakdownRemapped")+ logger.info(f"{_FAMILY}_lazy_precompute_rejected", team_id=runner.team.pk, reason="BreakdownRemapped")return Falsereturn _can_use_lazy_precompute_shared(runner, log_prefix="web_stats", extra_check=_check_stats_eligible)diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.pyindex 5c28584fec9f..b5f6109026d3 100644--- a/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py+++ b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py@@ -122,7 +122,7 @@ HAVING value >= 0hogql=response.hogql,modifiers=self.modifiers,preComputeStrategy=WebAnalyticsPreComputeStrategy.LIVE,- preComputeIneligibleReason=lazy_precompute_ineligible_reason(),+ preComputeIneligibleReason=lazy_precompute_ineligible_reason(WebAnalyticsPreComputeStrategy.LIVE),)def _get_results_for_band(