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): dedup cost charts via precomputed view (#68986)

Javier Bahamondesf13d39e91486
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
index 744bdaa5726b..b0f8dd14c7b4 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
@@ -157,11 +157,14 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
// Gated behind the same flag as the backend cost precompute read-side: when off, the tile
// keeps reading the S3-backed cost adapters (createMarketingDataWarehouseNodes) so the
- // precompute table can roll out independently. When on, read the native precompute table
- // via a single DataWarehouseNode — TrendsQuery then gives us compare, per-source breakdown
- // and currency formatting for free while the read stays off S3. `grain = 'campaign'` avoids
+ // precompute table can roll out independently. When on, read the native precompute via a
+ // single DataWarehouseNode — TrendsQuery then gives us compare, per-source breakdown and
+ // currency formatting for free while the read stays off S3. We target `marketing_costs_precomputed`,
+ // the deduplicated view, NOT the raw `marketing_costs_preaggregated`: the raw ReplacingMergeTree
+ // keeps one row per (job_id, cell), so a bare `sum()` double-counts re-materialized cells —
+ // the view collapses each cell to its latest job via argMax. `grain = 'campaign'` avoids
// double-counting the ad-group/ad grains; `expires_at > today()` keeps only fresh rows. The
- // table exposes a virtual `timestamp` (cost_date as DateTime) so a DataWarehouseNode can target it.
+ // view exposes a virtual `timestamp` (cost_date as DateTime) so a DataWarehouseNode can target it.
const costsPrecomputeEnabled = !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_COSTS_PRECOMPUTATION]
const selectedSourceIds = integrationFilter.integrationSourceIds || []
// Typed property filter, not raw HogQL interpolation: source IDs come from the
@@ -180,10 +183,10 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
: []
const costSeriesNode: DataWarehouseNode = {
kind: NodeKind.DataWarehouseNode,
- id: 'marketing_costs_preaggregated',
+ id: 'marketing_costs_precomputed',
name: tileColumnSelectionName,
custom_name: tileColumnSelectionName,
- table_name: 'posthog.marketing_costs_preaggregated',
+ table_name: 'marketing_costs_precomputed',
id_field: 'campaign_id',
distinct_id_field: 'campaign_id',
timestamp_field: 'timestamp',
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 27864897d818..3e73a24f0595 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -99,6 +99,7 @@ from posthog.hogql.database.schema.log_entries import (
from posthog.hogql.database.schema.logs import LogAttributesTable, LogsKafkaMetricsTable, LogsTable
from posthog.hogql.database.schema.marketing_conversions_preaggregated import MarketingConversionsPreaggregatedTable
from posthog.hogql.database.schema.marketing_costs_preaggregated import MarketingCostsPreaggregatedTable
+from posthog.hogql.database.schema.marketing_costs_precomputed import MarketingCostsPrecomputedTable
from posthog.hogql.database.schema.marketing_touchpoints_preaggregated import MarketingTouchpointsPreaggregatedTable
from posthog.hogql.database.schema.metrics import (
MetricAttributesTable,
@@ -437,6 +438,11 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:
},
),
"system": SystemTables(),
+ # Deduplicated read interface over posthog.marketing_costs_preaggregated. Registered at root
+ # (like `sessions`) because a lazy/aggregating view only resolves cleanly from the root scope.
+ "marketing_costs_precomputed": TableNode(
+ name="marketing_costs_precomputed", table=MarketingCostsPrecomputedTable()
+ ),
**children,
}
diff --git a/posthog/hogql/database/schema/marketing_costs_precomputed.py b/posthog/hogql/database/schema/marketing_costs_precomputed.py
new file mode 100644
index 000000000000..3a45674d7890
--- /dev/null
+++ b/posthog/hogql/database/schema/marketing_costs_precomputed.py
@@ -0,0 +1,63 @@
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.models import DateTimeDatabaseField, FieldOrTable, LazyTable, LazyTableToAdd
+from posthog.hogql.database.schema.marketing_costs_preaggregated import MarketingCostsPreaggregatedTable
+
+# 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
+# only materialized rows (S3-fallback sources are absent) — the precomputed subset, not the complete cost set.
+
+MARKETING_COSTS_PRECOMPUTED_VIEW_NAME = "marketing_costs_precomputed"
+_RAW = "marketing_costs_preaggregated"
+
+_RAW_FIELDS = MarketingCostsPreaggregatedTable().fields # reuse the raw column defs so the view can't drift
+_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"}
+# 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"}]
+
+
+class MarketingCostsPrecomputedTable(LazyTable):
+ description: str = (
+ "Deduplicated marketing ad-spend cost rows (per source, campaign, ad group, ad, day). Collapses the "
+ "raw `marketing_costs_preaggregated` ReplacingMergeTree to one latest-job row per cell via "
+ "argMax(metric, computed_at). Read this instead of the raw table to avoid double-counting."
+ )
+
+ fields: dict[str, FieldOrTable] = {
+ **{name: field for name, field in _RAW_FIELDS.items() if name not in _INTERNAL | {"timestamp"}},
+ # Materialized DateTime so a TrendsQuery DataWarehouseNode can target the view (trends hardcodes `timestamp`).
+ "timestamp": DateTimeDatabaseField(name="timestamp"),
+ }
+
+ def lazy_select(
+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery
+ ) -> ast.SelectQuery:
+ requested = table_to_add.fields_accessed
+
+ def raw(col: str) -> ast.Field:
+ return ast.Field(chain=[_RAW, col])
+
+ select_fields: list[ast.Expr] = []
+ for name in requested:
+ if name in _LATEST:
+ 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")])
+ else:
+ expr = raw(name)
+ select_fields.append(ast.Alias(alias=name, expr=expr))
+
+ 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],
+ )
+
+ def to_printed_clickhouse(self, context):
+ return MARKETING_COSTS_PRECOMPUTED_VIEW_NAME
+
+ def to_printed_hogql(self):
+ return MARKETING_COSTS_PRECOMPUTED_VIEW_NAME
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 ff7ed1a9fa96..36bef92e8aa7 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
@@ -247,7 +247,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
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 = []
+ materialized_source_ids: list = []
s3_fallback_adapters: list[MarketingSourceAdapter] = []
for adapter in mat_adapters:
with self.timings.measure("ma_precompute_build_mat_query"):
@@ -281,9 +281,11 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
)
s3_fallback_adapters.append(adapter)
continue
- job_ids.extend(result.job_ids)
+ # The ensure_precomputed call above materialized this source. We read by source, not by
+ # result.job_ids, because the `marketing_costs_precomputed` view already collapses each cell to its latest job.
+ materialized_source_ids.append(adapter.get_source_id())
- if not job_ids:
+ if not materialized_source_ids:
# Nothing materialized — let the caller read every source live, as before.
logger.info(
"marketing_costs_precompute",
@@ -295,7 +297,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
return None
cost_sources: list[ast.SelectQuery | ast.SelectSetQuery] = [
- self._costs_native_read_query(job_ids, grain, date_range)
+ self._costs_native_read_query(materialized_source_ids, grain, date_range)
]
# Sources that couldn't materialize stay on the live S3 union so the dashboard stays complete.
if s3_fallback_adapters:
@@ -312,42 +314,31 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
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),
+ materialized_source_count=len(materialized_source_ids),
)
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
+ self, source_ids: list, grain: MarketingAnalyticsDrillDownLevel, date_range: QueryDateRange
) -> ast.SelectQuery:
- """Read materialized cost rows for the given source jobs + grain, re-aliased to the adapter
- column contract so the campaign_costs CTE GROUP BY works identically to the live union.
-
- `cost_date` is bounded to the request's `date_range` with the same inclusive `toDateTime`
- comparison the live adapters use (`_get_where_conditions`). The `job_id` filter alone is not
- enough: the lazy framework reuses a job whose materialized window can be wider than the
- request (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.
-
- 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."""
+ """Read deduplicated cost rows for the given materialized sources + grain, re-aliased to the
+ adapter column contract so the campaign_costs CTE GROUP BY works identically to the live union.
+
+ Reads the `marketing_costs_precomputed` view, not the raw `marketing_costs_preaggregated` table. The raw
+ table is a ReplacingMergeTree whose sort key includes `job_id`, so the same cost cell can survive
+ under several job_ids (a re-materialized matured day, a double-triggered job, a compare period
+ reusing a wider window). The view collapses each cell to its latest job via argMax(computed_at),
+ so we filter by source (not job_id) and let the view own the dedup — one definition shared with
+ every other reader. `cost_date` is bounded to the request window with the same inclusive
+ `toDateTime` comparison the live adapters use. team_id scoping is enforced inside the view (its
+ inner raw-table reference carries the mandatory team_id guard), so no explicit filter here."""
adapter = MarketingSourceAdapter
def field(name: str) -> ast.Expr:
return ast.Field(chain=[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"),
@@ -368,37 +359,30 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
)
select_columns: list[ast.Expr] = [ast.Alias(alias=alias, expr=field(name)) for alias, name in dimension_columns]
+ # Metrics come pre-deduplicated from the view, so a bare read is correct — the downstream
+ # campaign_costs CTE still sums across days per campaign.
select_columns.extend(
[
- 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")),
+ 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")),
]
)
- # 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,
+ select_from=ast.JoinExpr(table=ast.Field(chain=["marketing_costs_precomputed"])),
where=ast.And(
exprs=[
ast.Call(
name="in",
args=[
- field("job_id"),
- ast.Tuple(exprs=[ast.Constant(value=str(jid)) for jid in job_ids]),
+ field("source_id"),
+ ast.Tuple(exprs=[ast.Constant(value=str(sid)) for sid in source_ids]),
],
),
- ast.CompareOperation(
- left=field("team_id"), op=ast.CompareOperationOp.Eq, right=ast.Constant(value=self.team.pk)
- ),
ast.CompareOperation(
left=field("grain"),
op=ast.CompareOperationOp.Eq,
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 9befcf2b1117..1e85a7d8b0c0 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
@@ -150,8 +150,9 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
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.
+ # 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
+ # its latest-computed value (argMax), not sum the two rows.
cell = {
"source_id": "google_test",
"source_name": "google",
@@ -204,7 +205,7 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
team=self.team,
)
read = runner._costs_native_read_query(
- [job_old, job_new],
+ [cell["source_id"]],
MarketingAnalyticsDrillDownLevel.CAMPAIGN,
QueryDateRange(date_range=date_range, team=self.team, interval=None, now=datetime(2025, 1, 1)),
)
@@ -255,5 +256,5 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
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 "marketing_costs_precomputed" in hogql, "materialized source should read the deduplicated view"
assert "live_s3_marker" in hogql, "unmaterializable source should stay on the live S3 union"