Skip to content

: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.

fix(marketing-analytics): read cost precompute per source instead of all-or-nothing (#66607)

Javier Bahamondesabef74cd4d7d
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.py
index 1b5f2f26c2f7..b32a421055e5 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
@@ -194,7 +194,9 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
return level
return MarketingAnalyticsDrillDownLevel.CAMPAIGN
- def _build_costs_from_precompute(self, date_range: QueryDateRange) -> Optional[ast.SelectQuery]:
+ def _build_costs_from_precompute(
+ self, date_range: QueryDateRange
+ ) -> Optional[ast.SelectQuery | ast.SelectSetQuery]:
"""Native-table cost source: ensure each source's cost rows are materialized at the grain
matching the current drill-down (one lazy job per source), then read them with the SAME column
contract `build_union_query_ast` produces — so `_build_campaign_cost_select` is unchanged.
@@ -230,18 +232,22 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
return None
ttl_seconds = {"0d": 6 * 60 * 60, "1d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}
+ # Per source: read the native table when it materializes, otherwise keep that one source on the
+ # live S3 union. A single unmaterializable/syncing source must not force every source back to S3.
job_ids: list = []
+ s3_fallback_adapters: list[MarketingSourceAdapter] = []
for adapter in mat_adapters:
insert_query = adapter.build_materialization_query(adapter.get_source_id())
if insert_query is None:
logger.info(
"marketing_costs_precompute",
- outcome="fallback_unmaterializable_source",
+ outcome="source_fallback_unmaterializable",
team_id=self.team.pk,
grain=grain_value,
source_id=adapter.get_source_id(),
)
- return None
+ s3_fallback_adapters.append(adapter)
+ continue
result = ensure_precomputed(
team=self.team,
insert_query=insert_query,
@@ -253,14 +259,17 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
if not result.ready:
logger.info(
"marketing_costs_precompute",
- outcome="fallback_jobs_not_ready",
+ outcome="source_fallback_jobs_not_ready",
team_id=self.team.pk,
grain=grain_value,
source_id=adapter.get_source_id(),
)
- return None
+ s3_fallback_adapters.append(adapter)
+ continue
job_ids.extend(result.job_ids)
+
if not job_ids:
+ # Nothing materialized — let the caller read every source live, as before.
logger.info(
"marketing_costs_precompute",
outcome="fallback_no_jobs",
@@ -270,8 +279,15 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
)
return None
+ cost_sources: list[ast.SelectQuery | ast.SelectSetQuery] = [
+ self._costs_native_read_query(job_ids, grain, date_range)
+ ]
+ # Sources that couldn't materialize stay on the live S3 union so the dashboard stays complete.
+ if s3_fallback_adapters:
+ cost_sources.append(mat_factory.build_union_query_ast(s3_fallback_adapters))
+
self._costs_precompute_used = True
- self._costs_sources_materialized = len(mat_adapters)
+ self._costs_sources_materialized = len(mat_adapters) - len(s3_fallback_adapters)
self._costs_grain = grain_value
logger.info(
"marketing_costs_precompute",
@@ -279,9 +295,13 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
team_id=self.team.pk,
grain=grain_value,
source_count=len(mat_adapters),
+ precompute_sources=len(mat_adapters) - len(s3_fallback_adapters),
+ s3_fallback_sources=len(s3_fallback_adapters),
job_count=len(job_ids),
)
- return self._costs_native_read_query(job_ids, grain, date_range)
+ if len(cost_sources) == 1:
+ return cost_sources[0]
+ return ast.SelectSetQuery.create_from_queries(cost_sources, set_operator="UNION ALL")
def _costs_native_read_query(
self, job_ids: list, grain: MarketingAnalyticsDrillDownLevel, date_range: QueryDateRange
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py
index be61d686f02d..a63980087604 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py
@@ -3,12 +3,14 @@ from datetime import date, datetime
from pathlib import Path
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import Mock, patch
from django.test import override_settings
from posthog.schema import DateRange, MarketingAnalyticsDrillDownLevel, MarketingAnalyticsTableQuery
from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
from posthog.hogql.placeholders import replace_placeholders
from posthog.hogql.query import execute_hogql_query
@@ -21,6 +23,7 @@ from products.marketing_analytics.backend.hogql_queries.adapters.base import (
MarketingSourceAdapter,
QueryContext,
)
+from products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory
from products.marketing_analytics.backend.hogql_queries.adapters.google_ads import GoogleAdsAdapter
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (
MarketingAnalyticsTableQueryRunner,
@@ -208,3 +211,49 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
result_rows, result_cols = self._execute(read)
total_cost = sum(float(r[self._col(result_cols, MarketingSourceAdapter.cost_field)]) for r in result_rows)
assert total_cost == 150.0, f"expected latest job cost 150 (argMax), got {total_cost} (sum would be 250)"
+
+ def test_one_unmaterializable_source_does_not_force_all_to_s3(self):
+ # One source materializes, one can't. The result must read the native table for the materialized
+ # source and keep only the other on the live S3 union — not fall back to S3 for everything.
+ runner = MarketingAnalyticsTableQueryRunner(
+ query=MarketingAnalyticsTableQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"), limit=100, offset=0, properties=[]
+ ),
+ team=self.team,
+ )
+ runner.config.costs_precomputation_enabled = True
+
+ good = Mock()
+ good.get_source_id.return_value = "good"
+ good.supports_level.return_value = True
+ good.config.source_id = "good"
+ good.build_materialization_query.return_value = parse_select("SELECT 1")
+
+ bad = Mock()
+ bad.get_source_id.return_value = "bad"
+ bad.supports_level.return_value = True
+ bad.config.source_id = "bad"
+ bad.build_materialization_query.return_value = None # cannot materialize -> stays on S3
+ bad.build_query.return_value = parse_select("SELECT 'live_s3_marker' AS source")
+
+ date_range = QueryDateRange(
+ date_range=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
+ team=self.team,
+ interval=None,
+ now=datetime(2023, 2, 1),
+ )
+ ready = Mock(ready=True, job_ids=["00000000-0000-0000-0000-000000000001"])
+ with (
+ patch.object(MarketingSourceFactory, "create_adapters", lambda self: [good, bad]),
+ patch.object(MarketingSourceFactory, "get_valid_adapters", lambda self, adapters: adapters),
+ patch(
+ "products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner.ensure_precomputed",
+ return_value=ready,
+ ),
+ ):
+ result = runner._build_costs_from_precompute(date_range)
+
+ assert result is not None, "one unmaterializable source must not force every source back to S3"
+ hogql = result.to_hogql()
+ assert "marketing_costs_preaggregated" in hogql, "materialized source should read the native table"
+ assert "live_s3_marker" in hogql, "unmaterializable source should stay on the live S3 union"