: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
feat(marketing-analytics): read cost precompute in dashboard trend tile (#62785)
Javier Bahamondesabcf05962f8b
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex f4ffba26874f..1e0531afa8cd 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -362,6 +362,7 @@ export const FEATURE_FLAGS = {MANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analyticsMARKDOWN_NOTEBOOKS: 'markdown-notebooks', // owner: #team-platform-features, enables Markdown notebooks upgrade pathMARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics+ MARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute tableMARKETING_ANALYTICS_DRILL_DOWN: 'marketing-analytics-drill-down', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_EXTENDED_DRILL_DOWN: 'marketing-analytics-extended-drill-down', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_MCP: 'marketing-analytics-mcp', // owner: @jabahamondes #team-web-analytics — gates MCP tool exposure (read-only marketing-analytics tools)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.tsindex d96be3f82910..fa0d1e59eb0d 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@@ -1,5 +1,7 @@import { connect, kea, path, selectors } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getCurrencySymbol } from 'lib/utils/currency'import { isNotNil } from 'lib/utils/guards'import { MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS, QueryTile, TileId, loadPriorityMap } from 'scenes/web-analytics/common'@@ -21,17 +23,26 @@ import {NodeKind,getEffectiveExcludedColumns,} from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType, InsightLogicProps, IntervalType } from '~/types'+import {+ BaseMathType,+ ChartDisplayType,+ DataWarehousePropertyFilter,+ HogQLMathType,+ InsightLogicProps,+ IntervalType,+ PropertyFilterType,+ PropertyOperator,+} from '~/types'import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'import { marketingAnalyticsTableLogic } from './marketingAnalyticsTableLogic'import type { marketingAnalyticsTilesLogicType } from './marketingAnalyticsTilesLogicType'import {getOrderBy,- rawColumnsForTiles,getSortedColumnsByArray,isDraftConversionGoalColumn,orderArrayByPreference,+ rawColumnsForTiles,validColumnsForTiles,} from './utils'@@ -40,6 +51,18 @@ export const MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID = 'marketing-analytics'const isSchemaBackedMarketingColumn = (column: validColumnsForTiles): column is rawColumnsForTiles =>column !== 'roas' && column !== 'cost_per_reported_conversion'+// Maps a chart column to a HogQL aggregate over the native cost precompute table. Costs are already+// converted to the team's base currency at materialization time, so no convertCurrency() is needed.+const PRECOMPUTE_METRIC_EXPR: Record<validColumnsForTiles, string> = {+ cost: 'sum(cost)',+ clicks: 'sum(clicks)',+ impressions: 'sum(impressions)',+ reported_conversion: 'sum(reported_conversions)',+ reported_conversion_value: 'sum(reported_conversion_value)',+ roas: 'sum(reported_conversion_value) / nullIf(sum(cost), 0)',+ cost_per_reported_conversion: 'sum(cost) / nullIf(sum(reported_conversions), 0)',+}+const createInsightProps = (tile: TileId, tab?: string): InsightLogicProps => ({dashboardItemId: getDashboardItemId(tile, tab, false),loadPriority: loadPriorityMap[tile],@@ -65,6 +88,8 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType],marketingAnalyticsTableLogic,['query', 'defaultColumns'],+ featureFlagLogic,+ ['featureFlags'],],})),selectors({@@ -108,6 +133,8 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicTypes.chartDisplayType,s.tileColumnSelection,s.baseCurrency,+ s.integrationFilter,+ s.featureFlags,],(compareFilter: CompareFilter | null,@@ -115,14 +142,98 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicTypecreateMarketingDataWarehouseNodes: DataWarehouseNode[],chartDisplayType: ChartDisplayType,tileColumnSelection: validColumnsForTiles,- baseCurrency: CurrencyCode+ baseCurrency: CurrencyCode,+ integrationFilter: IntegrationFilter,+ featureFlags: FeatureFlagsSet): QueryTile => {+ const tileColumnSelectionName = tileColumnSelection?.split('_').join(' ')+ const hasSources = createMarketingDataWarehouseNodes.length > 0+ const metricExpr = PRECOMPUTE_METRIC_EXPR[tileColumnSelection] ?? 'sum(cost)'const isCurrency =tileColumnSelection && isSchemaBackedMarketingColumn(tileColumnSelection)? MARKETING_ANALYTICS_SCHEMA[tileColumnSelection].isCurrency: falseconst { symbol: currencySymbol, isPrefix: currencyIsPrefix } = getCurrencySymbol(baseCurrency)- const tileColumnSelectionName = tileColumnSelection?.split('_').join(' ')++ // 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+ // 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.+ 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+ // integration_sources URL param, so embedding them in a HogQL string would allow+ // injection. PropertyOperator.Exact over a list compiles to a parameterized `IN (...)`.+ const sourceFilters: DataWarehousePropertyFilter[] =+ selectedSourceIds.length > 0+ ? [+ {+ type: PropertyFilterType.DataWarehouse,+ key: 'source_id',+ operator: PropertyOperator.Exact,+ value: selectedSourceIds,+ },+ ]+ : []+ const costSeriesNode: DataWarehouseNode = {+ kind: NodeKind.DataWarehouseNode,+ id: 'marketing_costs_preaggregated',+ name: tileColumnSelectionName,+ custom_name: tileColumnSelectionName,+ table_name: 'posthog.marketing_costs_preaggregated',+ id_field: 'campaign_id',+ distinct_id_field: 'campaign_id',+ timestamp_field: 'timestamp',+ math: HogQLMathType.HogQL,+ math_hogql: metricExpr,+ properties: [+ {+ type: PropertyFilterType.HogQL,+ key: `grain = 'campaign' AND expires_at > today()`,+ },+ ...sourceFilters,+ ],+ }+ const chartQuery: QueryTile['query'] = {+ kind: NodeKind.InsightVizNode,+ embedded: true,+ hidePersonsModal: true,+ hideTooltipOnScroll: true,+ source: {+ kind: NodeKind.TrendsQuery,+ series: !hasSources+ ? [+ {+ kind: NodeKind.EventsNode,+ event: 'no_sources_configured',+ custom_name: 'No marketing sources configured',+ math: BaseMathType.TotalCount,+ },+ ]+ : costsPrecomputeEnabled+ ? [costSeriesNode]+ : createMarketingDataWarehouseNodes,+ compareFilter: compareFilter || undefined,+ // The precompute path reads a single node, so split by source here; the S3 adapters+ // are already per-source series and need no breakdown.+ breakdownFilter:+ costsPrecomputeEnabled && hasSources+ ? { breakdowns: [{ type: 'data_warehouse', property: 'source_name' }] }+ : undefined,+ interval: dateFilter.interval,+ dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },+ trendsFilter: {+ display: chartDisplayType,+ aggregationAxisFormat: 'numeric',+ aggregationAxisPrefix: isCurrency && currencyIsPrefix ? currencySymbol : undefined,+ aggregationAxisPostfix: isCurrency && !currencyIsPrefix ? ` ${currencySymbol}` : undefined,+ },+ tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,+ },+ }return {kind: 'query',tileId: TileId.MARKETING,@@ -131,41 +242,7 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicTypeorderWhenLargeClassName: '2xl:order-1',},title: `Marketing ${tileColumnSelectionName}`,- query: {- kind: NodeKind.InsightVizNode,- embedded: true,- hidePersonsModal: true,- hideTooltipOnScroll: true,- source: {- kind: NodeKind.TrendsQuery,- compareFilter: compareFilter || undefined,- series:- createMarketingDataWarehouseNodes.length > 0- ? createMarketingDataWarehouseNodes- : [- // Fallback when no sources are configured- {- kind: NodeKind.EventsNode,- event: 'no_sources_configured',- custom_name: 'No marketing sources configured',- math: BaseMathType.TotalCount,- },- ],- interval: dateFilter.interval,- dateRange: {- date_from: dateFilter.dateFrom,- date_to: dateFilter.dateTo,- },- trendsFilter: {- display: chartDisplayType,- aggregationAxisFormat: 'numeric',- aggregationAxisPrefix: isCurrency && currencyIsPrefix ? currencySymbol : undefined,- aggregationAxisPostfix:- isCurrency && !currencyIsPrefix ? ` ${currencySymbol}` : undefined,- },- tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,- },- },+ query: chartQuery,showIntervalSelect: true,insightProps: createInsightProps(TileId.MARKETING, `${chartDisplayType}-${tileColumnSelection}`),canOpenInsight: true,diff --git a/posthog/hogql/database/schema/marketing_costs_preaggregated.py b/posthog/hogql/database/schema/marketing_costs_preaggregated.pyindex 768c31561919..ee0c2b316f6d 100644--- a/posthog/hogql/database/schema/marketing_costs_preaggregated.py+++ b/posthog/hogql/database/schema/marketing_costs_preaggregated.py@@ -1,9 +1,11 @@from pydantic import Field+from posthog.hogql import astfrom posthog.hogql.constants import HogQLQuerySettingsfrom posthog.hogql.database.models import (DateDatabaseField,DateTimeDatabaseField,+ ExpressionField,FieldOrTable,FloatDatabaseField,IntegerDatabaseField,@@ -71,6 +73,13 @@ class MarketingCostsPreaggregatedTable(Table):"expires_at": DateDatabaseField(name="expires_at", description="Date when this row expires and is dropped via TTL."),+ # Virtual `timestamp` lets a TrendsQuery DataWarehouseNode target this native table — the trends+ # builder references a hardcoded `timestamp` field. cost_date is a Date; expose it as a DateTime.+ "timestamp": ExpressionField(+ name="timestamp",+ expr=ast.Call(name="toDateTime", args=[ast.Field(chain=["cost_date"])]),+ isolate_scope=True,+ ),}def to_printed_clickhouse(self, context):diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.pyindex e94c54b6b5d0..d4f2d15a26b5 100644--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py@@ -1148,9 +1148,9 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):table_or_view = get_view_or_table_by_name(self.team, series.table_name)- if not table_or_view:- raise ValueError(f"Table {series.table_name} not found")- if table_or_view.columns is None:+ # A DataWarehouseNode may target a native HogQL table (e.g. a preaggregated table) that has+ # no warehouse-catalog entry — it's simply not a boolean breakdown field, so fall through.+ if not table_or_view or table_or_view.columns is None:return Falsebreakdown_key = breakdown_value[0] if isinstance(breakdown_value, list) else breakdown_value