: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
chore(marketing-analytics): time the precompute ensure calls in the conversion-goal path (#70483)
Javier Bahamondes483f508e065f
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex 263bda11a0e2..6f5a70a7de46 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -1,7 +1,10 @@import mathimport uuidfrom collections.abc import Sequence-from dataclasses import dataclass+from dataclasses import (+ dataclass,+ field as dataclass_field,+)from datetime import datetime, timedeltafrom typing import ClassVar, Optional, Union@@ -21,6 +24,7 @@ from posthog.hogql import astfrom posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_exprfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.property import action_to_expr, property_to_expr+from posthog.hogql.timings import HogQLTimingsfrom posthog.models import PropertyDefinition, Team, User@@ -167,6 +171,10 @@ class ConversionGoalProcessor:config: MarketingAnalyticsConfig# Requesting user, threaded through to enforce per-user property access on the precompute path.user: Optional[User] = None+ # Per-goal timings. HogQLTimings is not thread safe and goals are built in parallel, so each+ # processor owns a clone (see HogQLTimings.clone_for_subquery); the runner merges them back once+ # the pool has joined. Defaults to a standalone instance for callers outside the read path.+ timings: HogQLTimings = dataclass_field(default_factory=HogQLTimings)_UTM_LEVEL_FIELD_MAP: ClassVar[dict[MarketingAnalyticsDrillDownLevel, str]] = {MarketingAnalyticsDrillDownLevel.MEDIUM: "medium",@@ -352,8 +360,10 @@ class ConversionGoalProcessor:team_id=self.team.pk,)- array_collection = self.build_array_collection_query(additional_conditions)- return self.build_attribution_pipeline(array_collection)+ # Live events scan. Reaching here means the precompute did not serve this goal.+ with self.timings.measure("ma_goal_events_fallback"):+ array_collection = self.build_array_collection_query(additional_conditions)+ return self.build_attribution_pipeline(array_collection)def is_goal_precomputable(self) -> bool:"""Goal-level precompute eligibility, independent of the requesting user, date range, or flag.@@ -487,32 +497,37 @@ class ConversionGoalProcessor:window = timedelta(days=self.config.attribution_window_days)# Touchpoints extend back by the attribution window; conversions only span the query range.- touchpoints_result = ensure_precomputed(- team=self.team,- insert_query=build_touchpoints_precompute_query(),- time_range_start=date_from - window,- time_range_end=date_to,- ttl_seconds=PRECOMPUTE_TTL_SECONDS,- table=LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,- )+ # Both ensure_precomputed calls can materialize inline (PG + Redis + ClickHouse) when a slice+ # is stale, so they are timed separately from the AST work that follows.+ with self.timings.measure("ma_ensure_touchpoints"):+ touchpoints_result = ensure_precomputed(+ team=self.team,+ insert_query=build_touchpoints_precompute_query(),+ time_range_start=date_from - window,+ time_range_end=date_to,+ ttl_seconds=PRECOMPUTE_TTL_SECONDS,+ table=LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,+ )if not touchpoints_result.ready:return None- conversions_result = ensure_precomputed(- team=self.team,- insert_query=self.build_conversions_precompute_query(),- time_range_start=date_from,- time_range_end=date_to,- ttl_seconds=PRECOMPUTE_TTL_SECONDS,- table=LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,- )+ with self.timings.measure("ma_ensure_conversions"):+ conversions_result = ensure_precomputed(+ team=self.team,+ insert_query=self.build_conversions_precompute_query(),+ time_range_start=date_from,+ time_range_end=date_to,+ ttl_seconds=PRECOMPUTE_TTL_SECONDS,+ table=LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,+ )if not conversions_result.ready:return None- array_collection = self._build_array_collection_from_precomputes(- touchpoints_result.job_ids, conversions_result.job_ids, date_from, date_to, window- )- return self.build_attribution_pipeline(array_collection)+ with self.timings.measure("ma_attribution_pipeline_precomputed"):+ array_collection = self._build_array_collection_from_precomputes(+ touchpoints_result.job_ids, conversions_result.job_ids, date_from, date_to, window+ )+ return self.build_attribution_pipeline(array_collection)def _build_array_collection_from_precomputes(self,diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.pyindex 7843aeb934b8..e373a26ffedc 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py@@ -721,7 +721,14 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,)if should_create:processor = ConversionGoalProcessor(- goal=conversion_goal, index=index, team=self.team, config=self.config, user=self.user+ goal=conversion_goal,+ index=index,+ team=self.team,+ config=self.config,+ user=self.user,+ # Goals are built in parallel and HogQLTimings is not thread safe, so hand each+ # processor its own clone. Merged back in _build_complete_query_ast once joined.+ timings=self.timings.clone_for_subquery(index),)processors.append(processor)return processors@@ -817,16 +824,18 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,conversion_aggregator = ConversionGoalsAggregator(processors, self.config) if processors else None# Build the main SELECT query- main_query = self._build_main_select_query(conversion_aggregator)+ with self.timings.measure("ma_main_select"):+ main_query = self._build_main_select_query(conversion_aggregator)# Build CTEs as a dictionaryctes: dict[str, ast.CTE] = {}# Add campaign_costs CTE- campaign_cost_select = self._build_campaign_cost_select(union_subquery)- campaign_cost_cte = ast.CTE(- name=self.config.campaign_costs_cte_name, expr=campaign_cost_select, cte_type="subquery"- )+ with self.timings.measure("ma_campaign_cost_cte"):+ campaign_cost_select = self._build_campaign_cost_select(union_subquery)+ campaign_cost_cte = ast.CTE(+ name=self.config.campaign_costs_cte_name, expr=campaign_cost_select, cte_type="subquery"+ )ctes[self.config.campaign_costs_cte_name] = campaign_cost_cte# Add unified conversion goal CTE if any. Skip building it entirely at levels@@ -836,14 +845,19 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,# win at hierarchy levels.level_config = DRILL_DOWN_LEVEL_CONFIG.get(self.config.drill_down_level, {})if conversion_aggregator and not level_config.get("excludes_conversion_goals"):- # Check if this is an aggregated query (no GROUP BY)- group_by_exprs = self._get_group_by_expressions()- if not group_by_exprs:- # For aggregated queries, create aggregated conversion goals CTE- unified_cte = self._generate_aggregated_conversion_goals_cte(conversion_aggregator, date_range)- else:- # For table queries, use the normal conversion goals CTE- unified_cte = conversion_aggregator.generate_unified_cte(date_range, self._get_where_conditions)+ with self.timings.measure("ma_unified_conversion_cte"):+ # Check if this is an aggregated query (no GROUP BY)+ group_by_exprs = self._get_group_by_expressions()+ if not group_by_exprs:+ # For aggregated queries, create aggregated conversion goals CTE+ unified_cte = self._generate_aggregated_conversion_goals_cte(conversion_aggregator, date_range)+ else:+ # For table queries, use the normal conversion goals CTE+ unified_cte = conversion_aggregator.generate_unified_cte(date_range, self._get_where_conditions)++ # The per-goal pool has joined, so folding each processor's cloned timings back in is safe here.+ for processor in processors:+ self.timings.timings.update(processor.timings.timings)if unified_cte:ctes[UNIFIED_CONVERSION_GOALS_CTE_ALIAS] = unified_cte