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): stop match_key from splitting the costs dedup grain (#73313)

Javier Bahamondes49c2722b3459
diff --git a/posthog/hogql/database/schema/marketing_costs_precomputed.py b/posthog/hogql/database/schema/marketing_costs_precomputed.py
index 3a45674d7890..86f94470bb8e 100644
--- a/posthog/hogql/database/schema/marketing_costs_precomputed.py
+++ b/posthog/hogql/database/schema/marketing_costs_precomputed.py
@@ -15,8 +15,13 @@ _RAW_FIELDS = MarketingCostsPreaggregatedTable().fields # reuse the raw column
_INTERNAL = {"job_id", "computed_at"} # folded away by the dedup, not exposed
# argMax(…, computed_at) columns; expires_at rides along so `expires_at > today()` sees the freshest row.
_LATEST = {"cost", "clicks", "impressions", "reported_conversions", "reported_conversion_value", "expires_at"}
+# match_key is a join key re-derived per job from the team's campaign_field_preferences (campaign_name or
+# campaign_id), not cell identity — keeping it in the GROUP BY duplicates every cell when the preference
+# 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 | _LATEST | {"timestamp"}]
+_DIMENSIONS = [c for c in _RAW_FIELDS if c not in _INTERNAL | _ARGMAX | {"timestamp"}]
class MarketingCostsPrecomputedTable(LazyTable):
@@ -42,7 +47,7 @@ class MarketingCostsPrecomputedTable(LazyTable):
select_fields: list[ast.Expr] = []
for name in requested:
- if name in _LATEST:
+ 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")])
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 a074358e1e42..14919bbccd01 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
@@ -7,6 +7,8 @@ from unittest.mock import Mock, patch
from django.test import override_settings
+from parameterized import parameterized
+
from posthog.schema import DateRange, MarketingAnalyticsDrillDownLevel, MarketingAnalyticsTableQuery
from posthog.hogql import ast
@@ -148,7 +150,15 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
# 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):
+ @parameterized.expand(
+ [
+ ("stale_and_matured_job", "c1", "c1"),
+ # match_key is re-derived per job from the team's campaign_field_preferences, so a preference
+ # flip writes the same real cell under two match_key values; the view must still collapse them.
+ ("campaign_field_preference_flip", "Camp 1", "c1"),
+ ]
+ )
+ def test_native_read_takes_latest_job_per_cell_not_sum(self, _name, match_key_old, match_key_new):
# The same (campaign, day) cell materialized under two job_ids — a stale value and a matured one.
# job_id is in the raw ReplacingMergeTree sort key, so both rows survive. The read filters by
# source (not job_id) and goes through the `marketing_costs_precomputed` view, which must collapse the cell to
@@ -157,7 +167,6 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
"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),
@@ -170,7 +179,7 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
cell["source_id"],
cell["source_name"],
cell["grain"],
- cell["match_key"],
+ match_key,
cell["campaign_id"],
cell["campaign_name"],
"",
@@ -186,9 +195,9 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
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)),
+ for job, match_key, cost, computed_at in (
+ (job_old, match_key_old, 100.0, datetime(2023, 1, 15, 10, 0)),
+ (job_new, match_key_new, 150.0, datetime(2023, 1, 16, 10, 0)),
)
]
sync_execute(