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.

feat(marketing-analytics): native cost precompute table + read-side (#62784)

Javier Bahamondes3857f24d0002
diff --git a/posthog/clickhouse/migrations/0281_marketing_costs_preaggregated.py b/posthog/clickhouse/migrations/0281_marketing_costs_preaggregated.py
new file mode 100644
index 000000000000..604d9641ea7a
--- /dev/null
+++ b/posthog/clickhouse/migrations/0281_marketing_costs_preaggregated.py
@@ -0,0 +1,17 @@
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.preaggregation.marketing_costs_sql import (
+ DISTRIBUTED_MARKETING_COSTS_TABLE_SQL,
+ SHARDED_MARKETING_COSTS_TABLE_SQL,
+)
+
+operations = [
+ run_sql_with_exceptions(
+ SHARDED_MARKETING_COSTS_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ ),
+ run_sql_with_exceptions(
+ DISTRIBUTED_MARKETING_COSTS_TABLE_SQL(),
+ node_roles=[NodeRole.AUX, NodeRole.DATA],
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index 51dc46f10b9e..15b9dd6f8737 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0280_logs34
+0281_marketing_costs_preaggregated
diff --git a/posthog/clickhouse/preaggregation/marketing_costs_sql.py b/posthog/clickhouse/preaggregation/marketing_costs_sql.py
new file mode 100644
index 000000000000..fe2fa6d44192
--- /dev/null
+++ b/posthog/clickhouse/preaggregation/marketing_costs_sql.py
@@ -0,0 +1,93 @@
+# Reusable cost precompute: marketing source cost rows (per source, campaign, ad_group, ad, day)
+# materialized out of the external data-warehouse tables (S3) into native ClickHouse. The cost side
+# of marketing analytics is a `UNION ALL` of N source adapters reading S3-backed DWH tables; that S3
+# read is the dashboard's variable cold-cache bottleneck. This caches the normalized cost rows at fine
+# (ad-level) grain — one lazy job per source — so the dashboard reads native CH and every drill-down
+# (campaign/source/ad_group/ad) is a GROUP BY over the same table. Sibling of the touchpoints/conversions
+# preagg tables.
+
+from django.conf import settings
+
+from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree
+
+TABLE_BASE_NAME = "marketing_costs_preaggregated"
+
+
+def DISTRIBUTED_MARKETING_COSTS_TABLE():
+ return TABLE_BASE_NAME
+
+
+def SHARDED_MARKETING_COSTS_TABLE():
+ return f"sharded_{TABLE_BASE_NAME}"
+
+
+def SHARDED_MARKETING_COSTS_TABLE_ENGINE():
+ return ReplacingMergeTree(TABLE_BASE_NAME, ver="computed_at")
+
+
+MARKETING_COSTS_TABLE_BASE_SQL = """
+CREATE TABLE IF NOT EXISTS {table_name}
+(
+ team_id Int64,
+ job_id UUID,
+
+ source_id String,
+ source_name String,
+ grain LowCardinality(String),
+ match_key String,
+ campaign_id String,
+ campaign_name String,
+ ad_group_id String,
+ ad_group_name String,
+ ad_id String,
+ ad_name String,
+ cost_date Date,
+
+ cost Float64,
+ clicks Float64,
+ impressions Float64,
+ reported_conversions Float64,
+ reported_conversion_value Float64,
+
+ computed_at DateTime64(6, 'UTC') DEFAULT now(),
+ expires_at Date DEFAULT today() + INTERVAL 7 DAY
+) ENGINE = {engine}
+"""
+
+
+def SHARDED_MARKETING_COSTS_TABLE_SQL():
+ return (
+ MARKETING_COSTS_TABLE_BASE_SQL
+ + """
+PARTITION BY toYYYYMMDD(expires_at)
+ORDER BY (team_id, job_id, source_name, grain, campaign_id, ad_group_id, ad_id, cost_date)
+TTL expires_at
+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+"""
+ ).format(
+ table_name=SHARDED_MARKETING_COSTS_TABLE(),
+ engine=SHARDED_MARKETING_COSTS_TABLE_ENGINE(),
+ )
+
+
+def DISTRIBUTED_MARKETING_COSTS_TABLE_SQL():
+ return MARKETING_COSTS_TABLE_BASE_SQL.format(
+ table_name=DISTRIBUTED_MARKETING_COSTS_TABLE(),
+ engine=Distributed(
+ data_table=SHARDED_MARKETING_COSTS_TABLE(),
+ sharding_key="cityHash64(source_name, campaign_id)",
+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,
+ ),
+ )
+
+
+def DROP_MARKETING_COSTS_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_MARKETING_COSTS_TABLE()}"
+
+
+def DROP_SHARDED_MARKETING_COSTS_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {SHARDED_MARKETING_COSTS_TABLE()} SYNC"
+
+
+def TRUNCATE_MARKETING_COSTS_TABLE_SQL():
+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_MARKETING_COSTS_TABLE()}"
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index 786b830ce4d0..a7e72c60d5c8 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -55,6 +55,10 @@ from posthog.clickhouse.preaggregation.marketing_conversions_sql import (
DISTRIBUTED_MARKETING_CONVERSIONS_TABLE_SQL,
SHARDED_MARKETING_CONVERSIONS_TABLE_SQL,
)
+from posthog.clickhouse.preaggregation.marketing_costs_sql import (
+ DISTRIBUTED_MARKETING_COSTS_TABLE_SQL,
+ SHARDED_MARKETING_COSTS_TABLE_SQL,
+)
from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import (
DISTRIBUTED_MARKETING_TOUCHPOINTS_TABLE_SQL,
SHARDED_MARKETING_TOUCHPOINTS_TABLE_SQL,
@@ -344,6 +348,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (
SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,
SHARDED_MARKETING_TOUCHPOINTS_TABLE_SQL,
SHARDED_MARKETING_CONVERSIONS_TABLE_SQL,
+ SHARDED_MARKETING_COSTS_TABLE_SQL,
SHARDED_WEB_GOALS_PREAGGREGATED_TABLE_SQL,
SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,
@@ -414,6 +419,7 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (
DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,
DISTRIBUTED_MARKETING_TOUCHPOINTS_TABLE_SQL,
DISTRIBUTED_MARKETING_CONVERSIONS_TABLE_SQL,
+ DISTRIBUTED_MARKETING_COSTS_TABLE_SQL,
DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE_SQL,
DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index bfb13f94a8d7..550ba3eb7682 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -3151,6 +3151,38 @@
'''
# ---
+# name: test_create_table_query[marketing_costs_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS marketing_costs_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ source_id String,
+ source_name String,
+ grain LowCardinality(String),
+ match_key String,
+ campaign_id String,
+ campaign_name String,
+ ad_group_id String,
+ ad_group_name String,
+ ad_id String,
+ ad_name String,
+ cost_date Date,
+
+ cost Float64,
+ clicks Float64,
+ impressions Float64,
+ reported_conversions Float64,
+ reported_conversion_value Float64,
+
+ computed_at DateTime64(6, 'UTC') DEFAULT now(),
+ expires_at Date DEFAULT today() + INTERVAL 7 DAY
+ ) ENGINE = Distributed('aux', 'posthog_test', 'sharded_marketing_costs_preaggregated', cityHash64(source_name, campaign_id))
+
+ '''
+# ---
# name: test_create_table_query[marketing_touchpoints_preaggregated]
'''
@@ -5930,6 +5962,43 @@
'''
# ---
+# name: test_create_table_query[sharded_marketing_costs_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_marketing_costs_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ source_id String,
+ source_name String,
+ grain LowCardinality(String),
+ match_key String,
+ campaign_id String,
+ campaign_name String,
+ ad_group_id String,
+ ad_group_name String,
+ ad_id String,
+ ad_name String,
+ cost_date Date,
+
+ cost Float64,
+ clicks Float64,
+ impressions Float64,
+ reported_conversions Float64,
+ reported_conversion_value Float64,
+
+ computed_at DateTime64(6, 'UTC') DEFAULT now(),
+ expires_at Date DEFAULT today() + INTERVAL 7 DAY
+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.marketing_costs_preaggregated', '{replica}-{shard}', computed_at)
+
+ PARTITION BY toYYYYMMDD(expires_at)
+ ORDER BY (team_id, job_id, source_name, grain, campaign_id, ad_group_id, ad_id, cost_date)
+ TTL expires_at
+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+
+ '''
+# ---
# name: test_create_table_query[sharded_marketing_touchpoints_preaggregated]
'''
@@ -10189,6 +10258,43 @@
'''
# ---
+# name: test_create_table_query_replicated_and_storage[sharded_marketing_costs_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_marketing_costs_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ source_id String,
+ source_name String,
+ grain LowCardinality(String),
+ match_key String,
+ campaign_id String,
+ campaign_name String,
+ ad_group_id String,
+ ad_group_name String,
+ ad_id String,
+ ad_name String,
+ cost_date Date,
+
+ cost Float64,
+ clicks Float64,
+ impressions Float64,
+ reported_conversions Float64,
+ reported_conversion_value Float64,
+
+ computed_at DateTime64(6, 'UTC') DEFAULT now(),
+ expires_at Date DEFAULT today() + INTERVAL 7 DAY
+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.marketing_costs_preaggregated', '{replica}-{shard}', computed_at)
+
+ PARTITION BY toYYYYMMDD(expires_at)
+ ORDER BY (team_id, job_id, source_name, grain, campaign_id, ad_group_id, ad_id, cost_date)
+ TTL expires_at
+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+
+ '''
+# ---
# name: test_create_table_query_replicated_and_storage[sharded_marketing_touchpoints_preaggregated]
'''
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 3bd689302fd1..416b9977b543 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -98,6 +98,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_touchpoints_preaggregated import MarketingTouchpointsPreaggregatedTable
from posthog.hogql.database.schema.metrics import MetricAttributesTable, MetricsKafkaMetricsTable, MetricsTable
from posthog.hogql.database.schema.numbers import NumbersTable
@@ -392,6 +393,10 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:
name="marketing_conversions_preaggregated",
table=MarketingConversionsPreaggregatedTable(),
),
+ "marketing_costs_preaggregated": TableNode(
+ name="marketing_costs_preaggregated",
+ table=MarketingCostsPreaggregatedTable(),
+ ),
"web_stats_paths_preaggregated": TableNode(
name="web_stats_paths_preaggregated", table=WebStatsPathsPreaggregatedTable()
),
diff --git a/posthog/hogql/database/schema/marketing_costs_preaggregated.py b/posthog/hogql/database/schema/marketing_costs_preaggregated.py
new file mode 100644
index 000000000000..632debd04928
--- /dev/null
+++ b/posthog/hogql/database/schema/marketing_costs_preaggregated.py
@@ -0,0 +1,49 @@
+from pydantic import Field
+
+from posthog.hogql.constants import HogQLQuerySettings
+from posthog.hogql.database.models import (
+ DateDatabaseField,
+ DateTimeDatabaseField,
+ FieldOrTable,
+ FloatDatabaseField,
+ IntegerDatabaseField,
+ StringDatabaseField,
+ Table,
+)
+
+from posthog.clickhouse.preaggregation.marketing_costs_sql import DISTRIBUTED_MARKETING_COSTS_TABLE
+
+
+class MarketingCostsPreaggregatedTable(Table):
+ top_level_settings: HogQLQuerySettings | None = Field(
+ default_factory=lambda: HogQLQuerySettings(load_balancing="in_order")
+ )
+
+ fields: dict[str, FieldOrTable] = {
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "job_id": StringDatabaseField(name="job_id"),
+ "source_id": StringDatabaseField(name="source_id"),
+ "source_name": StringDatabaseField(name="source_name"),
+ "grain": StringDatabaseField(name="grain"),
+ "match_key": StringDatabaseField(name="match_key"),
+ "campaign_id": StringDatabaseField(name="campaign_id"),
+ "campaign_name": StringDatabaseField(name="campaign_name"),
+ "ad_group_id": StringDatabaseField(name="ad_group_id"),
+ "ad_group_name": StringDatabaseField(name="ad_group_name"),
+ "ad_id": StringDatabaseField(name="ad_id"),
+ "ad_name": StringDatabaseField(name="ad_name"),
+ "cost_date": DateDatabaseField(name="cost_date"),
+ "cost": FloatDatabaseField(name="cost"),
+ "clicks": FloatDatabaseField(name="clicks"),
+ "impressions": FloatDatabaseField(name="impressions"),
+ "reported_conversions": FloatDatabaseField(name="reported_conversions"),
+ "reported_conversion_value": FloatDatabaseField(name="reported_conversion_value"),
+ "computed_at": DateTimeDatabaseField(name="computed_at"),
+ "expires_at": DateDatabaseField(name="expires_at"),
+ }
+
+ def to_printed_clickhouse(self, context):
+ return DISTRIBUTED_MARKETING_COSTS_TABLE()
+
+ def to_printed_hogql(self):
+ return "marketing_costs_preaggregated"
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index 20bee6d5f91f..c262c29f1ed4 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -374,6 +374,7 @@ class LazyComputationTable(StrEnum):
CONVERSION_GOAL_ATTRIBUTED_PREAGGREGATED = "conversion_goal_attributed_preaggregated"
MARKETING_TOUCHPOINTS_PREAGGREGATED = "marketing_touchpoints_preaggregated"
MARKETING_CONVERSIONS_PREAGGREGATED = "marketing_conversions_preaggregated"
+ MARKETING_COSTS_PREAGGREGATED = "marketing_costs_preaggregated"
WEB_OVERVIEW_PREAGGREGATED = "web_overview_preaggregated"
WEB_STATS_PREAGGREGATED = "web_stats_preaggregated"
WEB_STATS_PATHS_PREAGGREGATED = "web_stats_paths_preaggregated"
@@ -395,6 +396,7 @@ _DATE_EXPIRES_AT_TABLES: set[LazyComputationTable] = {
LazyComputationTable.CONVERSION_GOAL_ATTRIBUTED_PREAGGREGATED,
LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,
LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,
+ LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,
}
diff --git a/products/marketing_analytics/backend/hogql_queries/adapters/base.py b/products/marketing_analytics/backend/hogql_queries/adapters/base.py
index d47f72e7437a..0aadaf5b8b67 100644
--- a/products/marketing_analytics/backend/hogql_queries/adapters/base.py
+++ b/products/marketing_analytics/backend/hogql_queries/adapters/base.py
@@ -3,7 +3,7 @@
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
-from typing import Any, Generic, Optional, TypeVar, cast
+from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, cast
import structlog
@@ -20,6 +20,9 @@ from posthog.hogql.parser import parse_expr
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.team import DEFAULT_CURRENCY, Team
+if TYPE_CHECKING:
+ from posthog.hogql.database.database import Database
+
from products.marketing_analytics.backend.hogql_queries.constants import (
DRILL_DOWN_LEVEL_CONFIG,
MATCH_KEY_FIELD,
@@ -141,6 +144,9 @@ class QueryContext:
base_currency: str = DEFAULT_CURRENCY
# AD_GROUP / AD pull from ad-group / ad-level tables; CAMPAIGN and below stay at campaign stats.
drill_down_level: MarketingAnalyticsDrillDownLevel = MarketingAnalyticsDrillDownLevel.CAMPAIGN
+ # Prebuilt HogQL database shared across factories in one request — the factory only needs it for
+ # warehouse table names, and Database.create_for is ~550ms. None → factory builds its own.
+ database: Optional["Database"] = None
class MarketingSourceAdapter(ABC, Generic[ConfigType]):
@@ -834,3 +840,80 @@ class MarketingSourceAdapter(ABC, Generic[ConfigType]):
self.logger.error("Query generation failed", error=error_msg, exc_info=True)
self._log_query_generation(False, error_msg)
return None
+
+ def _cost_date_expr(self) -> ast.Expr:
+ """Per-day cost date (`toDate` of the source's stats date column) for the materialized table."""
+ stats_table_name = self._level_tables().stats_table.name
+ return ast.Call(name="toDate", args=[ast.Field(chain=[stats_table_name, self._stats_date_column])])
+
+ def _materialization_date_where(self) -> ast.Expr:
+ """Date filter using `time_window_min`/`time_window_max` placeholders so the lazy framework
+ resolves the per-job window (unlike the read-time WHERE, which bakes in the request's range).
+ The window is half-open `[min, max)` to match the framework convention — using `<=` on the
+ upper bound double-counts boundary days that fall in two adjacent job windows."""
+ stats_table_name = self._level_tables().stats_table.name
+ date_field = ast.Call(name="toDateTime", args=[ast.Field(chain=[stats_table_name, self._stats_date_column])])
+ return ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=date_field,
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Placeholder(expr=ast.Field(chain=["time_window_min"])),
+ ),
+ ast.CompareOperation(
+ left=date_field,
+ op=ast.CompareOperationOp.Lt,
+ right=ast.Placeholder(expr=ast.Field(chain=["time_window_max"])),
+ ),
+ ]
+ )
+
+ def build_materialization_query(self, source_id: str) -> Optional[ast.SelectQuery]:
+ """Fine-grain (per-day) SELECT for materializing this source's cost rows into
+ `marketing_costs_preaggregated`. Reuses the normalized metric/dimension exprs (currency,
+ micros, JSON conversions) but re-aliases to the table schema, adds `source_id` + per-day
+ `cost_date`, and filters by `time_window` placeholders so the lazy framework runs it per job.
+
+ The caller sets `context.drill_down_level` to the source's finest supported level
+ (AD > AD_GROUP > CAMPAIGN); levels the source doesn't reach emit '-' for ad_group/ad so the
+ table schema stays stable. `match_key` is always the campaign match field (not the read-time
+ `_get_match_key_expr`, which blanks at AD levels) so the read-side conversion-goal join works
+ after aggregating back up to campaign level.
+ """
+ try:
+ level = self.context.drill_down_level
+ at_ad_group = level in (MarketingAnalyticsDrillDownLevel.AD_GROUP, MarketingAnalyticsDrillDownLevel.AD)
+ at_ad = level == MarketingAnalyticsDrillDownLevel.AD
+ empty = ast.Constant(value="-")
+
+ select_columns: list[ast.Expr] = [
+ ast.Alias(alias="source_id", expr=ast.Constant(value=source_id)),
+ ast.Alias(alias="source_name", expr=self._get_source_name_field()),
+ # grain = the level this row was materialized at (campaign/ad_group/ad); the read-side
+ # picks the matching grain per drill-down so each level keeps the platform's own stats
+ # (a campaign-stats row is NOT the roll-up of its ads).
+ ast.Alias(alias="grain", expr=ast.Constant(value=str(level.value))),
+ ast.Alias(alias="match_key", expr=self.get_campaign_match_field()),
+ ast.Alias(alias="campaign_id", expr=self._get_campaign_id_field()),
+ ast.Alias(alias="campaign_name", expr=self._get_campaign_name_field()),
+ ast.Alias(alias="ad_group_id", expr=self._get_ad_group_id_field() if at_ad_group else empty),
+ ast.Alias(alias="ad_group_name", expr=self._get_ad_group_name_field() if at_ad_group else empty),
+ ast.Alias(alias="ad_id", expr=self._get_ad_id_field() if at_ad else empty),
+ ast.Alias(alias="ad_name", expr=self._get_ad_name_field() if at_ad else empty),
+ ast.Alias(alias="cost_date", expr=self._cost_date_expr()),
+ ast.Alias(alias="cost", expr=self._get_cost_field()),
+ ast.Alias(alias="clicks", expr=self._get_clicks_field()),
+ ast.Alias(alias="impressions", expr=self._get_impressions_field()),
+ ast.Alias(alias="reported_conversions", expr=self._get_reported_conversion_field()),
+ ast.Alias(alias="reported_conversion_value", expr=self._get_reported_conversion_value_field()),
+ ]
+ group_by = [*self._get_group_by(), self._cost_date_expr()]
+ return ast.SelectQuery(
+ select=select_columns,
+ select_from=self._get_from(),
+ where=self._materialization_date_where(),
+ group_by=group_by,
+ )
+ except Exception as e:
+ self.logger.error("Materialization query generation failed", error=str(e), exc_info=True)
+ return None
diff --git a/products/marketing_analytics/backend/hogql_queries/adapters/factory.py b/products/marketing_analytics/backend/hogql_queries/adapters/factory.py
index 82eb5bbbd137..23c7c21cddbd 100644
--- a/products/marketing_analytics/backend/hogql_queries/adapters/factory.py
+++ b/products/marketing_analytics/backend/hogql_queries/adapters/factory.py
@@ -148,11 +148,14 @@ class MarketingSourceFactory:
self.context = context
self.logger = logger.bind(team_id=self.context.team.pk if self.context.team else None)
- # Cache warehouse data to avoid repeated queries.
- # This only enumerates table names to build adapters;
- # the marketing query runner re-resolves the schema with the requesting user, so
- # actual data access stays gated there. QueryContext has no user that could be passed for access controls.
- database = Database.create_for(team=self.context.team, bypass_warehouse_access_control=True)
+ # Cache warehouse data to avoid repeated queries. Reuse the request-shared database when the
+ # caller provides one (Database.create_for is ~550ms and we only need warehouse table names);
+ # otherwise build one bypassing access control — this only enumerates table names to build
+ # adapters, and the marketing query runner re-resolves the schema with the requesting user, so
+ # actual data access stays gated there (QueryContext has no user to pass for access controls).
+ database = self.context.database or Database.create_for(
+ team=self.context.team, bypass_warehouse_access_control=True
+ )
self._warehouse_tables = DataWarehouseTable.objects.filter(
team_id=self.context.team.pk, deleted=False, name__in=database.get_warehouse_table_names()
).prefetch_related("externaldataschema_set")
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 b4e947d08839..2ab894ba286f 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
@@ -17,6 +17,8 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_expr
from posthog.hogql.modifiers import create_default_modifiers_for_team
@@ -27,6 +29,10 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
from posthog.models.team.team import DEFAULT_CURRENCY
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationTable,
+ ensure_precomputed,
+)
from products.marketing_analytics.backend.hogql_queries.constants import (
DRILL_DOWN_LEVEL_CONFIG,
UNIFIED_CONVERSION_GOALS_CTE_ALIAS,
@@ -50,9 +56,17 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.config = MarketingAnalyticsConfig()
+ # Build from team so every runner (table, aggregated, non-integrated) picks up attribution
+ # settings and the precompute feature flags. Subclasses previously each set this; the aggregated
+ # runner didn't, so it silently used defaults (cost precompute always off).
+ self.config = MarketingAnalyticsConfig.from_team(self.team)
self._conversion_goal_warnings: list[str] = []
self._valid_conversion_goals_count: Optional[int] = None
+ # Cost-precompute observability — surfaced in the query telemetry event so we can confirm,
+ # per query, whether the native cost table was used or we fell back to the live S3 union.
+ self._costs_precompute_used: bool = False
+ self._costs_sources_materialized: int = 0
+ self._costs_grain: Optional[str] = None
def calculate(self) -> ResponseType:
start = time.perf_counter()
@@ -93,6 +107,9 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
"conversion_goals_count": conversion_goals_count,
"has_compare": has_compare,
"team_id": self.team.pk,
+ "costs_precompute_used": self._costs_precompute_used,
+ "costs_sources_materialized": self._costs_sources_materialized,
+ "costs_grain": self._costs_grain,
}
if error is None:
props["timings"] = [{"k": t.k, "t": t.t} for t in self.timings.to_list()]
@@ -117,6 +134,22 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
now=datetime.now(),
)
+ @cached_property
+ def _shared_hogql_database(self) -> Database:
+ """Built once and reused across every MarketingSourceFactory AND passed into
+ `execute_hogql_query` (via `_shared_hogql_context`), so the request pays Database.create_for
+ once instead of 3-5× (it's ~1s with the user's modifiers — feature flags + system-table
+ filtering). Built with the runner's user+modifiers so it's valid for resolving the final
+ query, not just the factory's warehouse-name lookup."""
+ modifiers = create_default_modifiers_for_team(self.team, self.modifiers)
+ return Database.create_for(team=self.team, user=self.user, modifiers=modifiers)
+
+ @cached_property
+ def _shared_hogql_context(self) -> HogQLContext:
+ """HogQLContext carrying the prebuilt database, passed to execute_hogql_query so its
+ `_generate_hogql` reuses the database instead of building a second one."""
+ return HogQLContext(team_id=self.team.pk, database=self._shared_hogql_database)
+
def _factory(self, date_range: QueryDateRange):
"""Create factory instance for the given date range"""
context = QueryContext(
@@ -124,6 +157,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
team=self.team,
base_currency=self.team.base_currency or DEFAULT_CURRENCY,
drill_down_level=self.config.drill_down_level,
+ database=self._shared_hogql_database,
)
return MarketingSourceFactory(context=context)
@@ -134,9 +168,10 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
adapters = factory.create_adapters()
valid_adapters = factory.get_valid_adapters(adapters)
- # Apply integration filter if present
- if self.query.integrationFilter and self.query.integrationFilter.integrationSourceIds:
- selected_ids = self.query.integrationFilter.integrationSourceIds
+ # Apply integration filter if present (getattr: some query kinds lack the field)
+ integration_filter = getattr(self.query, "integrationFilter", None)
+ if integration_filter and integration_filter.integrationSourceIds:
+ selected_ids = integration_filter.integrationSourceIds
valid_adapters = [adapter for adapter in valid_adapters if adapter.get_source_id() in selected_ids]
return valid_adapters
@@ -145,6 +180,183 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
logger.exception("Error getting marketing source adapters", error=str(e))
return []
+ def _cost_materialization_grain(self) -> MarketingAnalyticsDrillDownLevel:
+ """The grain a cost row is materialized at for the current drill-down. AD_GROUP/AD keep their
+ own grain (platform stats differ per level); everything else (CHANNEL/SOURCE/CAMPAIGN/UTM) reads
+ campaign-grain rows and rolls up — valid because those levels aggregate campaigns."""
+ level = self.config.drill_down_level
+ if level in (MarketingAnalyticsDrillDownLevel.AD_GROUP, MarketingAnalyticsDrillDownLevel.AD):
+ return level
+ return MarketingAnalyticsDrillDownLevel.CAMPAIGN
+
+ def _build_costs_from_precompute(self, date_range: QueryDateRange) -> Optional[ast.SelectQuery]:
+ """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.
+ Returns None if any source isn't ready → caller falls back to the live S3 adapter union.
+ """
+ grain = self._cost_materialization_grain()
+ # Adapters at the materialization grain (not the drill-down level, which may be SOURCE/CHANNEL).
+ mat_context = QueryContext(
+ date_range=date_range,
+ team=self.team,
+ base_currency=self.team.base_currency or DEFAULT_CURRENCY,
+ drill_down_level=grain,
+ database=self._shared_hogql_database,
+ )
+ mat_factory = MarketingSourceFactory(context=mat_context)
+ mat_adapters = mat_factory.get_valid_adapters(mat_factory.create_adapters())
+ # NonIntegratedConversionsTableQuery has no integrationFilter field — getattr keeps the
+ # precompute path working for it instead of raising AttributeError and falling back to S3.
+ integration_filter = getattr(self.query, "integrationFilter", None)
+ if integration_filter and integration_filter.integrationSourceIds:
+ selected_ids = integration_filter.integrationSourceIds
+ mat_adapters = [a for a in mat_adapters if a.get_source_id() in selected_ids]
+ mat_adapters = [a for a in mat_adapters if a.supports_level(grain)]
+ grain_value = str(grain.value)
+ if not mat_adapters:
+ logger.info(
+ "marketing_costs_precompute",
+ outcome="fallback_no_materializable_sources",
+ team_id=self.team.pk,
+ grain=grain_value,
+ source_count=0,
+ )
+ return None
+
+ ttl_seconds = {"0d": 6 * 60 * 60, "1d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}
+ job_ids: list = []
+ 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",
+ team_id=self.team.pk,
+ grain=grain_value,
+ source_id=adapter.get_source_id(),
+ )
+ return None
+ result = ensure_precomputed(
+ team=self.team,
+ insert_query=insert_query,
+ time_range_start=date_range.date_from(),
+ time_range_end=date_range.date_to(),
+ ttl_seconds=ttl_seconds,
+ table=LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,
+ )
+ if not result.ready:
+ logger.info(
+ "marketing_costs_precompute",
+ outcome="fallback_jobs_not_ready",
+ team_id=self.team.pk,
+ grain=grain_value,
+ source_id=adapter.get_source_id(),
+ )
+ return None
+ job_ids.extend(result.job_ids)
+ if not job_ids:
+ logger.info(
+ "marketing_costs_precompute",
+ outcome="fallback_no_jobs",
+ team_id=self.team.pk,
+ grain=grain_value,
+ source_count=len(mat_adapters),
+ )
+ return None
+
+ self._costs_precompute_used = True
+ self._costs_sources_materialized = len(mat_adapters)
+ self._costs_grain = grain_value
+ logger.info(
+ "marketing_costs_precompute",
+ outcome="used",
+ team_id=self.team.pk,
+ grain=grain_value,
+ source_count=len(mat_adapters),
+ job_count=len(job_ids),
+ )
+ return self._costs_native_read_query(job_ids, grain, date_range)
+
+ def _costs_native_read_query(
+ self, job_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."""
+ adapter = MarketingSourceAdapter
+
+ def 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")),
+ ]
+ if self.config.drill_down_level in (
+ MarketingAnalyticsDrillDownLevel.AD_GROUP,
+ MarketingAnalyticsDrillDownLevel.AD,
+ ):
+ select_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")),
+ ]
+ )
+ 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")),
+ ]
+ )
+
+ return ast.SelectQuery(
+ select=select_columns,
+ select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "marketing_costs_preaggregated"])),
+ 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]),
+ ],
+ ),
+ 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,
+ right=ast.Constant(value=str(grain.value)),
+ ),
+ # Bound to the request window, matching the live adapters' inclusive toDateTime filter.
+ ast.CompareOperation(
+ left=ast.Call(name="toDateTime", args=[field("cost_date")]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_from_str)]),
+ ),
+ ast.CompareOperation(
+ left=ast.Call(name="toDateTime", args=[field("cost_date")]),
+ op=ast.CompareOperationOp.LtEq,
+ right=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_to_str)]),
+ ),
+ ]
+ ),
+ )
+
def _build_campaign_cost_select(self, union_subquery: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery:
"""Build the campaign_costs CTE SELECT query"""
# Build GROUP BY using configuration - this will be overridden in aggregated queries
@@ -609,8 +821,18 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
# Get marketing source adapters
adapters = self._get_marketing_source_adapters(date_range=self.query_date_range)
- # Build the union query using the factory (AST form to skip parse_select).
- union_subquery = self._factory(date_range=self.query_date_range).build_union_query_ast(adapters)
+ # Build the cost source. When cost precompute is enabled, read the native materialized table
+ # (no S3); fall back to the live S3 adapter union if not enabled or jobs aren't ready.
+ union_subquery: ast.SelectQuery | ast.SelectSetQuery | None = None
+ if self.config.costs_precomputation_enabled:
+ try:
+ union_subquery = self._build_costs_from_precompute(self.query_date_range)
+ except Exception:
+ logger.exception("cost_precompute_failed", team_id=self.team.pk)
+ union_subquery = None
+ if union_subquery is None:
+ # AST form to skip parse_select.
+ union_subquery = self._factory(date_range=self.query_date_range).build_union_query_ast(adapters)
# Get conversion goals and filter out invalid ones
conversion_goals = self._get_team_conversion_goals()
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
index 74fdad436419..2774894fba4e 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
@@ -104,6 +104,7 @@ class MarketingAnalyticsConfig:
attribution_mode: AttributionMode = AttributionMode.LAST_TOUCH
conversion_goal_precomputation_enabled: bool = False
+ costs_precomputation_enabled: bool = False
@classmethod
def from_team(cls, team: "Team") -> "MarketingAnalyticsConfig":
@@ -122,6 +123,15 @@ class MarketingAnalyticsConfig:
group_properties={"organization": {"id": str(team.organization.id)}},
)
+ # Gate cost precomputation (reads native CH instead of the S3 cost tables) behind its own flag,
+ # so it rolls out independently of the conversion/touchpoint precompute.
+ config.costs_precomputation_enabled = posthoganalytics.feature_enabled(
+ "marketing-analytics-costs-precomputation",
+ str(team.uuid),
+ groups={"organization": str(team.organization.id)},
+ group_properties={"organization": {"id": str(team.organization.id)}},
+ )
+
# Gate multi-touch attribution behind feature flag
if config.attribution_mode in MULTI_TOUCH_MODES:
has_multi_touch = posthoganalytics.feature_enabled(
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
index 4520d362157b..2b861afbbabf 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
@@ -18,8 +18,6 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
-
from .constants import (
BASE_COLUMN_MAPPING,
DEFAULT_LIMIT,
@@ -44,8 +42,7 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
self.paginator = HogQLHasMorePaginator.from_limit_context(
limit_context=self.limit_context, limit=self.query.limit, offset=self.query.offset
)
- # Initialize configuration with team-specific settings
- self.config = MarketingAnalyticsConfig.from_team(self.team)
+ # self.config is built from team in the base runner's __init__.
# Implementation of abstract methods from base class
@@ -72,6 +69,7 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
+ context=self._shared_hogql_context,
)
results = response.results or []
@@ -258,6 +256,9 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
modifiers=self.modifiers,
limit_context=self.limit_context,
)
+ # Share the prebuilt HogQL database across both periods so the compare query pays the ~1s
+ # Database.create_for once, not twice. Pre-populates the previous runner's cached_property.
+ previous_runner.__dict__["_shared_hogql_database"] = self._shared_hogql_database
previous_period_query = previous_runner.to_query()
current_period_query = self.to_query()
diff --git a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
index 9d6d3044ecd8..f964f61695fa 100644
--- a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
@@ -17,8 +17,6 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
-
from .constants import DEFAULT_LIMIT, PAGINATION_EXTRA, UNIFIED_CONVERSION_GOALS_CTE_ALIAS, to_marketing_analytics_data
from .conversion_goals_aggregator import ConversionGoalsAggregator
from .marketing_analytics_base_query_runner import MarketingAnalyticsBaseQueryRunner
@@ -43,7 +41,7 @@ class NonIntegratedConversionsTableQueryRunner(
self.paginator = HogQLHasMorePaginator.from_limit_context(
limit_context=self.limit_context, limit=self.query.limit, offset=self.query.offset
)
- self.config = MarketingAnalyticsConfig.from_team(self.team)
+ # self.config is built from team in the base runner's __init__.
def _get_marketing_source_adapters(self, date_range):
"""
@@ -334,11 +332,18 @@ class NonIntegratedConversionsTableQueryRunner(
),
)
- # WHERE clause: only rows where campaign_costs has no match (IS NULL)
- where_clause = ast.CompareOperation(
- left=ast.Field(chain=[campaign_costs_alias, self.config.campaign_field]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value=None),
+ # Keep only conversions with no matching campaign cost. The LEFT JOIN leaves the cost columns
+ # empty for non-matches: NULL when costs come from the live S3 union (nullable), '' when they
+ # come from the native precompute table (non-nullable String). Match both so the precompute
+ # path returns the same rows as S3.
+ campaign_cost_field = ast.Field(chain=[campaign_costs_alias, self.config.campaign_field])
+ where_clause = ast.Or(
+ exprs=[
+ ast.Call(name="isNull", args=[campaign_cost_field]),
+ ast.CompareOperation(
+ left=campaign_cost_field, op=ast.CompareOperationOp.Eq, right=ast.Constant(value="")
+ ),
+ ]
)
return ast.SelectQuery(
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
new file mode 100644
index 000000000000..87457c5ca8e8
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py
@@ -0,0 +1,136 @@
+from datetime import datetime
+from pathlib import Path
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from django.test import override_settings
+
+from posthog.schema import DateRange, MarketingAnalyticsDrillDownLevel
+
+from posthog.hogql import ast
+from posthog.hogql.placeholders import replace_placeholders
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+
+from 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.google_ads import GoogleAdsAdapter
+
+TEST_BUCKET = "test_marketing_costs"
+
+# Wide range so we capture every CSV row; the direct read uses the same range.
+WIDE_FROM = "2000-01-01"
+WIDE_TO = "2100-01-01"
+
+GOOGLE_CAMPAIGN_COLUMNS: dict[str, dict[str, str | bool]] = {
+ "campaign_id": {"hogql": "StringDatabaseField", "clickhouse": "String", "schema_valid": True},
+ "campaign_name": {"hogql": "StringDatabaseField", "clickhouse": "String", "schema_valid": True},
+ "campaign_status": {"hogql": "StringDatabaseField", "clickhouse": "String", "schema_valid": True},
+}
+GOOGLE_STATS_COLUMNS: dict[str, dict[str, str | bool]] = {
+ "campaign_id": {"hogql": "StringDatabaseField", "clickhouse": "String", "schema_valid": True},
+ "segments_date": {"hogql": "StringDatabaseField", "clickhouse": "String", "schema_valid": True},
+ "metrics_clicks": {"hogql": "FloatDatabaseField", "clickhouse": "Float64", "schema_valid": True},
+ "metrics_cost_micros": {"hogql": "FloatDatabaseField", "clickhouse": "Float64", "schema_valid": True},
+ "metrics_impressions": {"hogql": "FloatDatabaseField", "clickhouse": "Float64", "schema_valid": True},
+ "metrics_conversions": {"hogql": "FloatDatabaseField", "clickhouse": "Float64", "schema_valid": True},
+ "metrics_conversions_value": {"hogql": "FloatDatabaseField", "clickhouse": "Float64", "schema_valid": True},
+}
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self):
+ super().setUp()
+ base = Path(__file__).parent
+ campaign_table, *_rest, cleanup_c = create_data_warehouse_table_from_csv(
+ base / "test/google_ads/campaign.csv",
+ "google_ads_campaign_table",
+ GOOGLE_CAMPAIGN_COLUMNS,
+ f"{TEST_BUCKET}.campaign",
+ self.team,
+ )
+ stats_table, *_rest2, cleanup_s = create_data_warehouse_table_from_csv(
+ base / "test/google_ads/campaign_stats.csv",
+ "google_ads_stats_table",
+ GOOGLE_STATS_COLUMNS,
+ f"{TEST_BUCKET}.stats",
+ self.team,
+ )
+ self.addCleanup(cleanup_c)
+ self.addCleanup(cleanup_s)
+ self._campaign_table = campaign_table
+ self._stats_table = stats_table
+
+ def _adapter(self) -> GoogleAdsAdapter:
+ config = GoogleAdsConfig(
+ campaign_table=self._campaign_table,
+ stats_table=self._stats_table,
+ source_type="GoogleAds",
+ source_id="google_test",
+ )
+ context = QueryContext(
+ date_range=QueryDateRange(
+ date_range=DateRange(date_from=WIDE_FROM, date_to=WIDE_TO),
+ team=self.team,
+ interval=None,
+ now=datetime.now(),
+ ),
+ team=self.team,
+ base_currency=self.team.base_currency or "USD",
+ drill_down_level=MarketingAnalyticsDrillDownLevel.CAMPAIGN,
+ )
+ return GoogleAdsAdapter(config=config, context=context)
+
+ def _execute(self, query: ast.Expr) -> tuple[list, list[str]]:
+ result = execute_hogql_query(query.to_hogql(), self.team)
+ return (result.results or [], list(result.columns or []))
+
+ def _col(self, columns: list[str], name: str) -> int:
+ return columns.index(name)
+
+ def test_materialization_total_matches_direct_read(self):
+ adapter = self._adapter()
+
+ direct_query = adapter.build_query()
+ assert direct_query is not None
+ direct_rows, direct_cols = self._execute(direct_query)
+
+ mat = adapter.build_materialization_query("google_test")
+ assert mat is not None
+ mat_query = replace_placeholders(
+ mat,
+ {"time_window_min": ast.Constant(value=WIDE_FROM), "time_window_max": ast.Constant(value=WIDE_TO)},
+ )
+ mat_rows, mat_cols = self._execute(mat_query)
+
+ assert direct_rows, "direct read returned no rows — seed/CSV problem"
+ assert mat_rows, "materialization returned no rows"
+
+ # Per-day materialized cost, summed, must equal the direct (already campaign-summed) cost.
+ direct_cost = sum(float(r[self._col(direct_cols, "cost")]) for r in direct_rows)
+ mat_cost = sum(float(r[self._col(mat_cols, "cost")]) for r in mat_rows)
+ assert abs(direct_cost - mat_cost) < 1e-6, f"cost diverged: direct={direct_cost} mat={mat_cost}"
+
+ def test_materialization_populates_source_id_grain_and_date(self):
+ adapter = self._adapter()
+ mat = adapter.build_materialization_query("google_test")
+ assert mat is not None
+ mat_query = replace_placeholders(
+ mat,
+ {"time_window_min": ast.Constant(value=WIDE_FROM), "time_window_max": ast.Constant(value=WIDE_TO)},
+ )
+ rows, cols = self._execute(mat_query)
+ assert rows
+
+ source_ids = {r[self._col(cols, "source_id")] for r in rows}
+ grains = {r[self._col(cols, "grain")] for r in rows}
+ sources = {r[self._col(cols, "source_name")] for r in rows}
+ assert source_ids == {"google_test"}
+ assert grains == {"campaign"}
+ 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)