: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): Fix marketing analytics double count (#73747)
Jordan Mryyan4da159257e63
diff --git a/posthog/hogql/database/schema/marketing_costs_precomputed.py b/posthog/hogql/database/schema/marketing_costs_precomputed.pyindex 86f94470bb8e..ed20d9b0340c 100644--- a/posthog/hogql/database/schema/marketing_costs_precomputed.py+++ b/posthog/hogql/database/schema/marketing_costs_precomputed.py@@ -1,8 +1,15 @@+from typing import TYPE_CHECKING++import posthoganalytics+from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.models import DateTimeDatabaseField, FieldOrTable, LazyTable, LazyTableToAddfrom posthog.hogql.database.schema.marketing_costs_preaggregated import MarketingCostsPreaggregatedTable+if TYPE_CHECKING:+ from posthog.models.team import Team+# Deduplicated read interface over `marketing_costs_preaggregated`. `job_id` is in the raw ReplacingMergeTree# sort key, so a re-materialized cell survives as several rows and a bare SUM double-counts; this view collapses# each cell to its latest job via argMax. Read this, not the raw table. Named `_precomputed` because it holds@@ -20,8 +27,49 @@ _LATEST = {"cost", "clicks", "impressions", "reported_conversions", "reported_co# flips, so the latest job's value wins instead._LATEST_LABELS = {"match_key"}_ARGMAX = _LATEST | _LATEST_LABELS-# Full cell identity — always GROUP BY all of it so each cell collapses independently.-_DIMENSIONS = [c for c in _RAW_FIELDS if c not in _INTERNAL | _ARGMAX | {"timestamp"}]+# Renamable display labels, which split a cell the same way match_key does. Folded only behind the flag, so+# the wider dedup stays reversible without a second view.+_IDENTITY_LABELS = {"campaign_name", "ad_group_name", "ad_name"}++COSTS_DEDUP_V2_FLAG = "marketing-analytics-costs-dedup-v2"+_FLAG_CACHE_ATTR = "_ma_costs_dedup_v2"+++def costs_dedup_v2_enabled(team: "Team | None") -> bool:+ """Whether the renamable display labels are folded into argMax alongside the metrics.++ Evaluated locally and cached on the team instance: this sits on the query-compile path, which runs once+ per lazy-table resolution, so a network round trip or a `$feature_flag_called` event per query would be+ a real cost. Falls back to the legacy grouping when the team is unavailable or the flag can't resolve.+ """+ if team is None:+ return False+ cached = getattr(team, _FLAG_CACHE_ATTR, None)+ if cached is not None:+ return cached+ organization = team.organization+ enabled = bool(+ posthoganalytics.feature_enabled(+ COSTS_DEDUP_V2_FLAG,+ str(team.uuid),+ groups={"organization": str(organization.id)},+ group_properties={"organization": {"id": str(organization.id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+ setattr(team, _FLAG_CACHE_ATTR, enabled)+ return enabled+++def _argmax_columns(dedup_labels_by_identity: bool) -> set[str]:+ return _ARGMAX | _IDENTITY_LABELS if dedup_labels_by_identity else _ARGMAX+++def _dimension_columns(dedup_labels_by_identity: bool) -> list[str]:+ # Full cell identity — always GROUP BY all of it so each cell collapses independently.+ argmax = _argmax_columns(dedup_labels_by_identity)+ return [c for c in _RAW_FIELDS if c not in _INTERNAL | argmax | {"timestamp"}]class MarketingCostsPrecomputedTable(LazyTable):@@ -41,13 +89,16 @@ class MarketingCostsPrecomputedTable(LazyTable):self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery) -> ast.SelectQuery:requested = table_to_add.fields_accessed+ dedup_labels_by_identity = costs_dedup_v2_enabled(context.team)+ argmax = _argmax_columns(dedup_labels_by_identity)+ dimensions = _dimension_columns(dedup_labels_by_identity)def raw(col: str) -> ast.Field:return ast.Field(chain=[_RAW, col])select_fields: list[ast.Expr] = []for name in requested:- if name in _ARGMAX:+ if name in argmax:expr: ast.Expr = ast.Call(name="argMax", args=[raw(name), raw("computed_at")])elif name == "timestamp":expr = ast.Call(name="toDateTime", args=[raw("cost_date")])@@ -58,7 +109,7 @@ class MarketingCostsPrecomputedTable(LazyTable):return ast.SelectQuery(select=select_fields,select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "marketing_costs_preaggregated"]), alias=_RAW),- group_by=[raw(dim) for dim in _DIMENSIONS],+ group_by=[raw(dim) for dim in dimensions],)def to_printed_clickhouse(self, context):diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 18c20b392e97..abf09d45605e 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -296,6 +296,7 @@ class TestQueryRunner(BaseTest):"campaign_name_mappings": {},"custom_source_mappings": {},"campaign_field_preferences": {},+ "costs_dedup_v2": False,"sources_map": {"01977f7b-7f29-0000-a028-7275d1a767a4": {"cost": "cost",@@ -365,7 +366,7 @@ class TestQueryRunner(BaseTest):runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)cache_key = runner.get_cache_key()- assert cache_key == "cache_42_13ab830e775c41ee3ae4b45c386e6064d74eec55fb93092732c0bb305d7e980f"+ assert cache_key == "cache_42_c034c5f92d23cb2399f6c087694175b7e6950739ea60b0ec7cf2665d2ae82d50"def test_cache_key_runner_subclass(self):TestQueryRunner = self.setup_test_query_runner_class()@@ -379,7 +380,7 @@ class TestQueryRunner(BaseTest):runner = TestSubclassQueryRunner(query={"some_attr": "bla"}, team=team)cache_key = runner.get_cache_key()- assert cache_key == "cache_42_b624e873acbdc9829f0973b4dc14424bb26e3b5c36c11387ce24e9ff3bea2a00"+ assert cache_key == "cache_42_916dab3186430d61979f436fca08d88c23559c270894cf8c96a19e2c18a8ae4f"def test_cache_key_different_timezone(self):TestQueryRunner = self.setup_test_query_runner_class()@@ -390,7 +391,7 @@ class TestQueryRunner(BaseTest):runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)cache_key = runner.get_cache_key()- assert cache_key == "cache_42_473689ec17cc982383519776503e498bd0e44f16e6b6f0073412599254a69aba"+ assert cache_key == "cache_42_032f9a7be3ea1fc4451f1e5a77841bb79f9b9ef65ad949f251ee0e68e8ee5fb0"def test_cache_payload_omits_object_restrictions_when_unrestricted(self):TestQueryRunner = self.setup_test_query_runner_class()diff --git a/posthog/models/team/team_marketing_analytics_config.py b/posthog/models/team/team_marketing_analytics_config.pyindex 7699102d58ef..d271ff975c20 100644--- a/posthog/models/team/team_marketing_analytics_config.py+++ b/posthog/models/team/team_marketing_analytics_config.py@@ -460,6 +460,9 @@ class TeamMarketingAnalyticsConfig(models.Model):self.sources_map = current_sourcesdef to_cache_key_dict(self) -> dict:+ # Deferred: posthog.hogql imports models, and this module loads at django.setup() in every process.+ from posthog.hogql.database.schema.marketing_costs_precomputed import costs_dedup_v2_enabled # noqa: PLC0415+return {"base_currency": self.team.base_currency,"sources_map": self.sources_map,@@ -468,6 +471,8 @@ class TeamMarketingAnalyticsConfig(models.Model):"campaign_name_mappings": self.campaign_name_mappings,"custom_source_mappings": self.custom_source_mappings,"campaign_field_preferences": self.campaign_field_preferences,+ # Without this the flag isn't a kill switch: flipping it leaves the old numbers cached.+ "costs_dedup_v2": costs_dedup_v2_enabled(self.team),}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 14919bbccd01..1e65259e839c 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@@ -222,6 +222,91 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):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)"+ @parameterized.expand(+ [+ ("match_key", "Camp 1", "c1", False, 150.0, 1),+ ("campaign_name", "Old Name", "New Name", False, 300.0, 2),+ ("campaign_name", "Old Name", "New Name", True, 150.0, 1),+ ]+ )+ def test_native_read_dedups_when_label_changes_across_jobs(+ self, label_column, pre_value, post_value, dedup_v2, expected_cost, expected_rows+ ):+ base = {+ "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),+ }++ def row(job_id, computed_at, **overrides):+ cell = {**base, **overrides}+ return (+ self.team.pk,+ job_id,+ cell["source_id"],+ cell["source_name"],+ cell["grain"],+ cell["match_key"],+ cell["campaign_id"],+ cell["campaign_name"],+ "",+ "",+ "",+ "",+ cell["cost_date"],+ 150.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ computed_at,+ date(2099, 1, 1),+ )++ rows = [+ row(str(uuid.uuid4()), datetime(2023, 1, 16, 10, 0), **{label_column: pre_value}),+ row(str(uuid.uuid4()), datetime(2023, 1, 17, 10, 0), **{label_column: post_value}),+ ]+ 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,+ )+ self.team._ma_costs_dedup_v2 = dedup_v2 # type: ignore[attr-defined]+ read = runner._costs_native_read_query(+ [base["source_id"]],+ 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 == expected_cost, (+ f"{label_column} changing across jobs with dedup_v2={dedup_v2}: expected {expected_cost}, got {total_cost}"+ )+ assert len(result_rows) == expected_rows, f"expected {expected_rows} row(s), got {len(result_rows)}"++ if expected_rows == 1:+ output_alias = {+ "match_key": MarketingSourceAdapter.match_key_field,+ "campaign_name": MarketingSourceAdapter.campaign_name_field,+ }[label_column]+ assert result_rows[0][self._col(result_cols, output_alias)] == post_value, (+ f"deduped row should carry the latest {label_column} '{post_value}', not the stale '{pre_value}'"+ )+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.