: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-analytics): dedup cost precompute read to latest job per cell (#66582)
Javier Bahamondes202f3905179b
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 7cb979866bfe..1b5f2f26c2f7 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@@ -293,43 +293,65 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,comparison the live adapters use (`_get_where_conditions`). The `job_id` filter alone is notenough: the lazy framework reuses a job whose materialized window can be wider than therequest (e.g. one period of a compare query reusing the other's window), so without the date- bound the read over-counts boundary/overlap days."""+ bound the read over-counts boundary/overlap days.++ The same cost cell (source/campaign/ad/day) can also be materialized under several job_ids — a+ re-materialization once the day matures (the source revises the figure), an exact duplicate from+ a double-triggered job, or a compare period reusing the other's wider window. job_id is in the+ ReplacingMergeTree sort key, so those survive as distinct rows and a bare SUM downstream would+ double-count. We collapse each cell to its latest job via argMax(metric, computed_at)+ (computed_at is the ReplacingMergeTree version), so a matured value supersedes the stale one and+ exact duplicates fold together — mirroring the conversion/touchpoint read dedup."""adapter = MarketingSourceAdapterdef field(name: str) -> ast.Expr:return ast.Field(chain=[name])- select_columns: list[ast.Expr] = [- ast.Alias(alias=adapter.match_key_field, expr=field("match_key")),- ast.Alias(alias=adapter.campaign_name_field, expr=field("campaign_name")),- ast.Alias(alias=adapter.campaign_id_field, expr=field("campaign_id")),- ast.Alias(alias=adapter.source_name_field, expr=field("source_name")),+ def latest(name: str) -> ast.Expr:+ # Metric from the cell's most recently computed job (ReplacingMergeTree version).+ return ast.Call(name="argMax", args=[field(name), field("computed_at")])++ # Cost-cell identity (everything that isn't a metric). The query groups by these plus cost_date+ # so each cell folds to one latest-job row; with no duplicate jobs it is one row per cell, as before.+ dimension_columns: list[tuple[str, str]] = [+ (adapter.match_key_field, "match_key"),+ (adapter.campaign_name_field, "campaign_name"),+ (adapter.campaign_id_field, "campaign_id"),+ (adapter.source_name_field, "source_name"),]if self.config.drill_down_level in (MarketingAnalyticsDrillDownLevel.AD_GROUP,MarketingAnalyticsDrillDownLevel.AD,):- select_columns.extend(+ dimension_columns.extend([- ast.Alias(alias=adapter.ad_group_name_field, expr=field("ad_group_name")),- ast.Alias(alias=adapter.ad_group_id_field, expr=field("ad_group_id")),- ast.Alias(alias=adapter.ad_name_field, expr=field("ad_name")),- ast.Alias(alias=adapter.ad_id_field, expr=field("ad_id")),+ (adapter.ad_group_name_field, "ad_group_name"),+ (adapter.ad_group_id_field, "ad_group_id"),+ (adapter.ad_name_field, "ad_name"),+ (adapter.ad_id_field, "ad_id"),])++ select_columns: list[ast.Expr] = [ast.Alias(alias=alias, expr=field(name)) for alias, name in dimension_columns]select_columns.extend([- ast.Alias(alias=adapter.impressions_field, expr=field("impressions")),- ast.Alias(alias=adapter.clicks_field, expr=field("clicks")),- ast.Alias(alias=adapter.cost_field, expr=field("cost")),- ast.Alias(alias=adapter.reported_conversion_field, expr=field("reported_conversions")),- ast.Alias(alias=adapter.reported_conversion_value_field, expr=field("reported_conversion_value")),+ ast.Alias(alias=adapter.impressions_field, expr=latest("impressions")),+ ast.Alias(alias=adapter.clicks_field, expr=latest("clicks")),+ ast.Alias(alias=adapter.cost_field, expr=latest("cost")),+ ast.Alias(alias=adapter.reported_conversion_field, expr=latest("reported_conversions")),+ ast.Alias(alias=adapter.reported_conversion_value_field, expr=latest("reported_conversion_value")),])+ # cost_date stays out of the SELECT (the downstream campaign_costs CTE sums across days per+ # campaign) but anchors the grouping so each per-day cell collapses independently.+ group_by_exprs: list[ast.Expr] = [field(name) for _, name in dimension_columns]+ group_by_exprs.append(field("cost_date"))+return ast.SelectQuery(select=select_columns,select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "marketing_costs_preaggregated"])),+ group_by=group_by_exprs,where=ast.And(exprs=[ast.Call(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.pyindex 87457c5ca8e8..41617a761a35 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@@ -1,21 +1,31 @@-from datetime import datetime+import uuid+from datetime import date, datetimefrom pathlib import Pathfrom posthog.test.base import BaseTest, ClickhouseTestMixinfrom django.test import override_settings-from posthog.schema import DateRange, MarketingAnalyticsDrillDownLevel+from posthog.schema import DateRange, MarketingAnalyticsDrillDownLevel, MarketingAnalyticsTableQueryfrom posthog.hogql import astfrom posthog.hogql.placeholders import replace_placeholdersfrom posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.client.execute import sync_execute+from posthog.clickhouse.preaggregation.marketing_costs_sql import DISTRIBUTED_MARKETING_COSTS_TABLEfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv-from products.marketing_analytics.backend.hogql_queries.adapters.base import GoogleAdsConfig, QueryContext+from products.marketing_analytics.backend.hogql_queries.adapters.base import (+ GoogleAdsConfig,+ MarketingSourceAdapter,+ QueryContext,+)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,+)TEST_BUCKET = "test_marketing_costs"@@ -77,7 +87,7 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):date_range=DateRange(date_from=WIDE_FROM, date_to=WIDE_TO),team=self.team,interval=None,- now=datetime.now(),+ now=datetime(2025, 1, 1),),team=self.team,base_currency=self.team.base_currency or "USD",@@ -134,3 +144,67 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):assert sources == {"google"}# cost_date is a real per-day date (not the sentinel empty), enabling daily-window caching.assert all(r[self._col(cols, "cost_date")] is not None for r in rows)++ def test_native_read_takes_latest_job_per_cell_not_sum(self):+ # The same (campaign, day) cell materialized under two job_ids — a stale value and a matured one.+ # job_id is in the ReplacingMergeTree sort key, so both rows survive; the read must return the+ # latest-computed value (argMax), not their sum, even when both job_ids are read together.+ cell = {+ "source_id": "google_test",+ "source_name": "google",+ "grain": "campaign",+ "match_key": "c1",+ "campaign_id": "c1",+ "campaign_name": "Camp 1",+ "cost_date": date(2023, 1, 15),+ }+ job_old, job_new = str(uuid.uuid4()), str(uuid.uuid4())+ rows = [+ (+ self.team.pk,+ job,+ cell["source_id"],+ cell["source_name"],+ cell["grain"],+ cell["match_key"],+ cell["campaign_id"],+ cell["campaign_name"],+ "",+ "",+ "",+ "",+ cell["cost_date"],+ cost,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ computed_at,+ date(2099, 1, 1),+ )+ for job, cost, computed_at in (+ (job_old, 100.0, datetime(2023, 1, 15, 10, 0)),+ (job_new, 150.0, datetime(2023, 1, 16, 10, 0)),+ )+ ]+ sync_execute(+ f"INSERT INTO {DISTRIBUTED_MARKETING_COSTS_TABLE()} "+ "(team_id, job_id, source_id, source_name, grain, match_key, campaign_id, campaign_name, "+ "ad_group_id, ad_group_name, ad_id, ad_name, cost_date, cost, clicks, impressions, "+ "reported_conversions, reported_conversion_value, computed_at, expires_at) VALUES",+ rows,+ )++ date_range = DateRange(date_from="2023-01-01", date_to="2023-01-31")+ runner = MarketingAnalyticsTableQueryRunner(+ query=MarketingAnalyticsTableQuery(dateRange=date_range, limit=100, offset=0, properties=[]),+ team=self.team,+ )+ read = runner._costs_native_read_query(+ [job_old, job_new],+ MarketingAnalyticsDrillDownLevel.CAMPAIGN,+ QueryDateRange(date_range=date_range, team=self.team, interval=None, now=datetime(2025, 1, 1)),+ )+ 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)"