: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(marketing): bound live attribution query parallelism (#108537)
Javier Bahamondes915a8229e9b2
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.mdindex b2efc950cd92..0e6cd3996334 100644--- a/docs/internal/marketing-attribution-session-precompute.md+++ b/docs/internal/marketing-attribution-session-precompute.md@@ -63,6 +63,10 @@ Late-arriving events and session updates therefore do not depend on a cached dimA missing cache window at a calendar boundary does not switch this route back to the legacy live query.The report's date range and timezone remain unchanged.+Eligible live-session queries limit ClickHouse execution to 16 threads and enable aggregation in storage order where the grouping keys permit it.+This limits partial aggregation states and temporary spill files while preserving the existing spill threshold and timeout.+Cached reads and ineligible queries keep the default execution settings.+The initial rollout keeps the cached reader's eligibility restrictions, including date-boundary, access-control, test-account, range, and session-modifier checks.Conversion goals that depend on session fields or deferred action expressions also use legacy live attribution, preserving its wider session-ID lookup window.Ineligible queries continue to use legacy live attribution.diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.pyindex 529ffdc8524d..a1ab660ce19d 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_base.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py@@ -20,11 +20,13 @@ from posthog.schema import ()from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team_marketing_analytics_config import MAX_ATTRIBUTION_WINDOW_DAYS, MIN_ATTRIBUTION_WINDOW_DAYSfrom .attribution_weights import DAY_IN_SECONDS+from .constants import MARKETING_SPILL_AFTER_BYTESfrom .conversion_goal_conditions import conversion_goal_conditionfrom .marketing_analytics_base_query_runner import ResponseTypefrom .session_breakdown_base import MarketingSessionBreakdownQueryRunnerBase@@ -58,6 +60,14 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon# Narrower than the session-breakdown base's union: everything below reads attribution-only fields.query: MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery+ def get_query_settings(self) -> HogQLGlobalSettings:+ # Extra aggregation threads create more partial states and spill files for the same sessions.+ return HogQLGlobalSettings(+ max_bytes_before_external_group_by=MARKETING_SPILL_AFTER_BYTES,+ max_threads=16 if self._live_session_resolution_used else None,+ optimize_aggregation_in_order=True if self._live_session_resolution_used else None,+ )+def get_cache_key_variant(self) -> str:variant = super().get_cache_key_variant()if self.config.live_session_resolution_enabled:diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.pyindex a209bb4a99e8..94aaeae70cb8 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py@@ -22,12 +22,12 @@ from posthog.schema import ()from posthog.hogql import ast-from posthog.hogql.constants import HogQLGlobalSettings, LimitContext+from posthog.hogql.constants import LimitContextfrom posthog.hogql.query import execute_hogql_queryfrom .attribution_base import PERSON_ARRAYS_CTE, PERSON_CONVERSION_COUNT, AttributionQueryRunnerBasefrom .attribution_sessions_read import session_ctes-from .constants import MARKETING_SPILL_AFTER_BYTES, PAGINATION_EXTRA+from .constants import PAGINATION_EXTRA# Paths longer than this are grouped on their most recent steps — the same truncation direction as# MAX_TOUCHPOINTS_PER_PERSON, and for the same reason: the touches nearest the conversion are the ones@@ -301,7 +301,7 @@ class MarketingAnalyticsAttributionPathsQueryRunner(context=self._shared_hogql_context,# The per-person touchpoint arrays are unbounded, so let the GROUP BY spill to disk# rather than hit the memory limit. Same guard funnels, retention and paths use.- settings=HogQLGlobalSettings(max_bytes_before_external_group_by=MARKETING_SPILL_AFTER_BYTES),+ settings=self.get_query_settings(),)# Mapped by column name, not tuple position, so adding a column can't shift every later one.diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.pyindex 338b1b50e504..5825995dd633 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py@@ -29,7 +29,7 @@ from posthog.schema import ()from posthog.hogql import ast-from posthog.hogql.constants import HogQLGlobalSettings, LimitContext+from posthog.hogql.constants import LimitContextfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange@@ -43,7 +43,7 @@ from .attribution_weights import (build_position_based_weights,build_time_decay_weights,)-from .constants import DEFAULT_LIMIT, MARKETING_SPILL_AFTER_BYTES, PAGINATION_EXTRA+from .constants import DEFAULT_LIMIT, PAGINATION_EXTRA# Column order for the table's model groups: single-touch first, then multi-touch, so the columns read# left to right from the crudest split to the most nuanced.@@ -506,7 +506,7 @@ class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[Marketcontext=self._shared_hogql_context,# The per-person touchpoint arrays are unbounded, so let the GROUP BY spill to disk# rather than hit the memory limit. Same guard funnels, retention and paths use.- settings=HogQLGlobalSettings(max_bytes_before_external_group_by=MARKETING_SPILL_AFTER_BYTES),+ settings=self.get_query_settings(),)# Mapped by column name, not tuple position, so adding a column can't shift every later one.diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.pyindex c968fa43c65e..de7ebe621ab9 100644--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py@@ -15,6 +15,7 @@ from posthog.schema import (DateRange,HogQLPropertyFilter,HogQLQueryModifiers,+ HogQLQueryResponse,MarketingAnalyticsAttributionPathsQuery,MarketingAnalyticsAttributionQuery,PropertyMathType,@@ -406,3 +407,49 @@ class TestAttributionSessionsRead(SimpleTestCase):assert identities[0].runtime_hash == identities[2].runtime_hashlive_keys.append(keys[1])assert live_keys[0] == live_keys[1]++ @parameterized.expand(+ [+ (shape, query_type, runner_type, live, timezone)+ for shape, query_type, runner_type in [+ ("table", MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),+ ("paths", MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),+ ]+ for live, timezone in [(True, "UTC"), (False, "UTC"), (True, "Asia/Kolkata")]+ ]+ )+ def test_execution_settings_follow_selected_session_source(+ self,+ _name: str,+ query_type: type[MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery],+ runner_type: type[MarketingAnalyticsAttributionQueryRunner | MarketingAnalyticsAttributionPathsQueryRunner],+ live: bool,+ timezone: str,+ ) -> None:+ self.team.timezone = timezone+ runner = runner_type(+ team=self.team,+ query=query_type(+ conversionGoalId="goal",+ properties=[],+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),+ ),+ )+ runner.config.live_session_resolution_enabled = live+ with (+ time_machine.travel("2023-01-12T12:00:00Z", tick=False),+ patch.object(+ runner_type, "_shared_hogql_context", new_callable=PropertyMock, return_value=HogQLContext(team_id=1)+ ),+ patch(+ f"{runner_type.__module__}.execute_hogql_query",+ return_value=HogQLQueryResponse(results=[], columns=[]),+ ) as execute,+ ):+ runner.calculate()+ execute.assert_called_once()+ settings = execute.call_args.kwargs["settings"]+ eligible_live = live and timezone == "UTC"+ assert settings.max_threads == (16 if eligible_live else None)+ assert settings.optimize_aggregation_in_order == (True if eligible_live else None)+ assert settings.max_bytes_before_external_group_by == 512 * 1024 * 1024