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): add channel x source breakdown with sessions (#73421)

Javier Bahamondesc812142628dc
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index ca80fd55d289..8c7e6fb38a3a 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -30798,7 +30798,7 @@
"type": "object"
},
"MarketingAnalyticsDrillDownLevel": {
- "enum": ["channel", "source", "campaign", "ad_group", "ad", "medium", "content", "term"],
+ "enum": ["channel", "channel_source", "source", "campaign", "ad_group", "ad", "medium", "content", "term"],
"type": "string"
},
"MarketingAnalyticsItem": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 2e5a70b99d66..86a75d7f3e8d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -6482,6 +6482,7 @@ export interface MarketingAnalyticsConfig {
export enum MarketingAnalyticsDrillDownLevel {
Channel = 'channel',
+ ChannelSource = 'channel_source',
Source = 'source',
Campaign = 'campaign',
AdGroup = 'ad_group',
@@ -6548,6 +6549,12 @@ export const MARKETING_ANALYTICS_DRILL_DOWN_CONFIG: Record<
MarketingAnalyticsBaseColumns.Source,
],
},
+ [MarketingAnalyticsDrillDownLevel.ChannelSource]: {
+ // Channel is the grouping alias; Source survives as the second column so a channel's
+ // rows break down into the sources that make it up.
+ columnAlias: 'Channel',
+ excludedBaseColumns: [MarketingAnalyticsBaseColumns.Id, MarketingAnalyticsBaseColumns.Campaign],
+ },
[MarketingAnalyticsDrillDownLevel.Source]: {
columnAlias: 'Source',
excludedBaseColumns: [
diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.tsx
index b075f7ec9137..21b6659f393b 100644
--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.tsx
+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.tsx
@@ -1,12 +1,75 @@
-import { LemonBanner } from '@posthog/lemon-ui'
+import { MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS } from 'scenes/web-analytics/common'
+import { MarketingAnalyticsCell } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/shared'
+import { webAnalyticsDataTableQueryContext } from 'scenes/web-analytics/tiles/WebAnalyticsTile'
+
+import { Query } from '~/queries/Query/Query'
+import {
+ DataTableNode,
+ MarketingAnalyticsBaseColumns,
+ MarketingAnalyticsDrillDownLevel,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import { QueryContext, QueryContextColumn } from '~/queries/types'
+
+// Channel is the top level because it covers all traffic, not just the platforms with a
+// connected ad source. Source is the second column so a channel breaks down into the
+// sources that make it up.
+const COLUMNS: string[] = [
+ 'Channel',
+ MarketingAnalyticsBaseColumns.Source,
+ // Sessions comes from the sessions table, so it's the only column that has a value for
+ // traffic with no ad spend behind it (organic, direct, referral).
+ 'Sessions',
+ MarketingAnalyticsBaseColumns.Cost,
+ MarketingAnalyticsBaseColumns.Clicks,
+ MarketingAnalyticsBaseColumns.Impressions,
+ MarketingAnalyticsBaseColumns.CPC,
+ MarketingAnalyticsBaseColumns.CTR,
+]
+
+const CHANNEL_SOURCE_BREAKDOWN: DataTableNode = {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.MarketingAnalyticsTableQuery,
+ dateRange: { date_from: '-30d', date_to: null },
+ drillDownLevel: MarketingAnalyticsDrillDownLevel.ChannelSource,
+ select: COLUMNS,
+ // Sort by channel first so every source of a channel lands together, then by traffic
+ // within the channel — sessions is the one metric every row has.
+ orderBy: [
+ ['Channel', 'ASC'],
+ ['Sessions', 'DESC'],
+ ],
+ properties: [],
+ limit: 200,
+ tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ full: true,
+ embedded: false,
+ showOpenEditorButton: false,
+ showElapsedTime: true,
+ showTimings: true,
+}
+
+// Every cell is a MarketingAnalyticsItem, not a scalar — without a render fn the table falls
+// through to the raw JSON viewer.
+const QUERY_CONTEXT: QueryContext = {
+ ...webAnalyticsDataTableQueryContext,
+ columns: COLUMNS.reduce(
+ (acc, column) => {
+ acc[column] = { render: MarketingAnalyticsCell }
+ return acc
+ },
+ {} as Record<string, QueryContextColumn>
+ ),
+}
// Scaffold for the redesigned marketing analytics dashboard, gated behind the
-// `new-marketing-analytics-dashboard` feature flag. Intentionally a placeholder for now so the tab can
-// merge early; the real content lands in follow-up PRs.
+// `new-marketing-analytics-dashboard` feature flag.
export function NewMarketingAnalyticsDashboard(): JSX.Element {
return (
<div className="mt-4">
- <LemonBanner type="info">The redesigned marketing analytics dashboard is coming soon.</LemonBanner>
+ <Query query={CHANNEL_SOURCE_BREAKDOWN} context={QUERY_CONTEXT} readOnly />
</div>
)
}
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index bd26e7eb8b35..0616ba690792 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2951,6 +2951,7 @@ class MarketingAnalyticsConstants(StrEnum):
class MarketingAnalyticsDrillDownLevel(StrEnum):
CHANNEL = "channel"
+ CHANNEL_SOURCE = "channel_source"
SOURCE = "source"
CAMPAIGN = "campaign"
AD_GROUP = "ad_group"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 7f8b0bd4bacf..977c7d9e8ecc 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -6732,6 +6732,7 @@ export type MarketingAnalyticsDrillDownLevelApi =
export const MarketingAnalyticsDrillDownLevelApi = {
Channel: 'channel',
+ ChannelSource: 'channel_source',
Source: 'source',
Campaign: 'campaign',
AdGroup: 'ad_group',
diff --git a/products/marketing_analytics/backend/hogql_queries/constants.py b/products/marketing_analytics/backend/hogql_queries/constants.py
index 5144ad0f029b..6e2de5cd4366 100644
--- a/products/marketing_analytics/backend/hogql_queries/constants.py
+++ b/products/marketing_analytics/backend/hogql_queries/constants.py
@@ -9,6 +9,7 @@ from posthog.schema import (
BingAdsDefaultSources,
BingAdsTableExclusions,
BingAdsTableKeywords,
+ DefaultChannelTypes,
GoogleAdsDefaultSources,
GoogleAdsTableExclusions,
GoogleAdsTableKeywords,
@@ -70,6 +71,7 @@ DEFAULT_DISTINCT_ID_FIELD = "distinct_id"
# CTE names
CAMPAIGN_COST_CTE_NAME = "campaign_costs"
UNIFIED_CONVERSION_GOALS_CTE_ALIAS = "ucg"
+CHANNEL_SESSIONS_CTE_NAME = "channel_sessions"
# Prefixes for table names
CONVERSION_GOAL_PREFIX_ABBREVIATION = "cg_"
@@ -81,6 +83,15 @@ TOTAL_CLICKS_FIELD = "total_clicks"
TOTAL_IMPRESSIONS_FIELD = "total_impressions"
TOTAL_REPORTED_CONVERSION_FIELD = "total_reported_conversions"
TOTAL_REPORTED_CONVERSION_VALUE_FIELD = "total_reported_conversion_value"
+TOTAL_SESSIONS_FIELD = "total_sessions"
+
+# Sessions come from the sessions table, not from an ad platform, so this column is only
+# available at levels that can be derived from session data (channel_source).
+SESSIONS_COLUMN_ALIAS = "Sessions"
+
+# The label every side of the query falls back to when channel can't be derived. Sourced from the
+# enum so the sides can't drift apart and split one row in two.
+UNKNOWN_CHANNEL = DefaultChannelTypes.UNKNOWN.value
# Field used for joining with conversion goals
MATCH_KEY_FIELD = "match_key"
@@ -360,6 +371,17 @@ DRILL_DOWN_LEVEL_CONFIG: dict[MarketingAnalyticsDrillDownLevel, DrillDownLevelCo
}
),
},
+ MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE: {
+ # Channel is the grouping alias; Source survives as the second column so a channel's
+ # rows break down into the sources that make it up.
+ "column_alias": "Channel",
+ "excluded_base_columns": frozenset(
+ {
+ MarketingAnalyticsBaseColumns.ID,
+ MarketingAnalyticsBaseColumns.CAMPAIGN,
+ }
+ ),
+ },
MarketingAnalyticsDrillDownLevel.SOURCE: {
"column_alias": MarketingAnalyticsBaseColumns.SOURCE,
"excluded_base_columns": frozenset(
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
index a0e8e850dbcc..360beedbad9d 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -40,6 +40,7 @@ from .adapters.factory import MarketingSourceFactory
from .marketing_analytics_config import MarketingAnalyticsConfig
from .marketing_lazy_precompute import marketing_ensure_precomputed
from .metrics import CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTER
+from .utils import build_source_normalization_expr
DAY_IN_SECONDS = 86400
LN2 = math.log(2) # ≈ 0.693, used in half-life formula: weight = exp(-ln(2) * t / half_life)
@@ -1997,38 +1998,10 @@ class ConversionGoalProcessor:
Case-insensitive matching - 'YouTube', 'youtube', 'YOUTUBE' all map to 'google'.
Includes both adapter-defined sources and team-configured custom sources.
"""
- # Convert source to lowercase for case-insensitive matching
- lowercase_source = ast.Call(name="lower", args=[source_expr])
-
- # Build nested if expressions for each mapping
- normalized_expr = source_expr
-
- # Get combined source mappings (adapter defaults + team custom sources)
source_mappings = MarketingSourceFactory.get_all_source_identifier_mappings(
team_config=self.team.marketing_analytics_config
)
- for primary_source, alternative_sources in source_mappings.items():
- # Skip the primary source itself in the alternatives list
- alternatives_only = [s.lower() for s in alternative_sources if s != primary_source]
-
- if alternatives_only:
- # If lowercase source is in alternatives, return primary; otherwise continue
- normalized_expr = ast.Call(
- name="if",
- args=[
- ast.Call(
- name="in",
- args=[
- lowercase_source,
- ast.Array(exprs=[ast.Constant(value=alt) for alt in alternatives_only]),
- ],
- ),
- ast.Constant(value=primary_source),
- normalized_expr,
- ],
- )
-
- return normalized_expr
+ return build_source_normalization_expr(source_expr, source_mappings)
def _build_final_aggregation_query(self, attribution_query: ast.SelectQuery) -> ast.SelectQuery:
"""Build final aggregation query with organic defaults"""
@@ -2064,6 +2037,19 @@ class ConversionGoalProcessor:
),
]
group_by: list[ast.Expr] = [channel_type_expr]
+ elif level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ channel_type_expr = self._build_channel_type_expr(field_exprs=field_exprs)
+ select_columns = [
+ ast.Alias(alias=self.config.match_key_field, expr=ast.Constant(value="")),
+ ast.Alias(alias=self.config.campaign_field, expr=channel_type_expr),
+ ast.Alias(alias=self.config.id_field, expr=ast.Constant(value="")),
+ ast.Alias(alias=self.config.source_field, expr=source_expr),
+ ast.Alias(
+ alias=self.config.get_conversion_goal_column_name(self.index),
+ expr=self._get_aggregation_expr(),
+ ),
+ ]
+ group_by = [channel_type_expr, source_expr]
elif level == MarketingAnalyticsDrillDownLevel.SOURCE:
# At source level, group by source_name only
select_columns = [
@@ -2242,6 +2228,16 @@ class ConversionGoalProcessor:
ast.Alias(alias=self.config.get_conversion_goal_column_name(self.index), expr=select_field),
]
group_by: list[ast.Expr] = [channel_type_expr]
+ elif level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ channel_type_expr = self._build_channel_type_expr(field_exprs=field_exprs)
+ select_columns = [
+ ast.Alias(alias=self.config.match_key_field, expr=ast.Constant(value="")),
+ ast.Alias(alias=self.config.campaign_field, expr=channel_type_expr),
+ ast.Alias(alias=self.config.id_field, expr=ast.Constant(value="")),
+ ast.Alias(alias=self.config.source_field, expr=source_expr),
+ ast.Alias(alias=self.config.get_conversion_goal_column_name(self.index), expr=select_field),
+ ]
+ group_by = [channel_type_expr, source_expr]
elif level == MarketingAnalyticsDrillDownLevel.SOURCE:
select_columns = [
ast.Alias(alias=self.config.match_key_field, expr=ast.Constant(value="")),
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py
index 2f55b9d40841..678023430e1f 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py
@@ -10,7 +10,10 @@ from posthog.hogql import ast
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.settings import TEST
-from products.marketing_analytics.backend.hogql_queries.constants import UNIFIED_CONVERSION_GOALS_CTE_ALIAS
+from products.marketing_analytics.backend.hogql_queries.constants import (
+ UNIFIED_CONVERSION_GOALS_CTE_ALIAS,
+ UNKNOWN_CHANNEL,
+)
from .adapters.factory import MarketingSourceFactory
from .conversion_goal_processor import ConversionGoalProcessor, SharedTouchpointsPrecompute
@@ -164,6 +167,16 @@ class ConversionGoalsAggregator:
ast.Alias(alias=self.config.match_key_field, expr=ast.Constant(value="")),
]
group_by_exprs: list[ast.Expr] = [campaign_field_expr]
+ elif level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ # campaign_field holds the channel; source stays a real key. No campaign name
+ # mappings here — they key off campaign, which this level doesn't group by.
+ final_select = [
+ ast.Alias(alias=self.config.campaign_field, expr=campaign_field_expr),
+ ast.Alias(alias=self.config.id_field, expr=ast.Constant(value="")),
+ ast.Alias(alias=self.config.source_field, expr=source_field_expr),
+ ast.Alias(alias=self.config.match_key_field, expr=ast.Constant(value="")),
+ ]
+ group_by_exprs = [campaign_field_expr, source_field_expr]
else:
# Campaign level — apply campaign name mappings
mapped_campaign_expr, mapped_id_expr = self._apply_campaign_name_mappings(
@@ -399,17 +412,21 @@ class ConversionGoalsAggregator:
level = self.config.drill_down_level
group_by_fields = self.config.group_by_fields
+ # CHANNEL_SOURCE only needs the grouping alias here; `_append_sessions_join` overwrites it
+ # with a coalesce that also spans the sessions side.
if level in (
MarketingAnalyticsDrillDownLevel.CHANNEL,
+ MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,
MarketingAnalyticsDrillDownLevel.SOURCE,
MarketingAnalyticsDrillDownLevel.MEDIUM,
MarketingAnalyticsDrillDownLevel.CONTENT,
MarketingAnalyticsDrillDownLevel.TERM,
):
campaign_field = self.config.campaign_field
- # "Unknown" = DefaultChannelTypes.UNKNOWN; "(none)" = BREAKDOWN_NULL_DISPLAY for UTM fields.
+ # "(none)" = BREAKDOWN_NULL_DISPLAY for UTM fields.
fallback_map = {
- MarketingAnalyticsDrillDownLevel.CHANNEL: "Unknown",
+ MarketingAnalyticsDrillDownLevel.CHANNEL: UNKNOWN_CHANNEL,
+ MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE: UNKNOWN_CHANNEL,
MarketingAnalyticsDrillDownLevel.SOURCE: self.config.organic_source,
MarketingAnalyticsDrillDownLevel.MEDIUM: "(none)",
MarketingAnalyticsDrillDownLevel.CONTENT: "(none)",
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 813c5d5e355d..a95c1624406c 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
@@ -32,8 +32,11 @@ from posthog.models.team.team import DEFAULT_CURRENCY
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationTable
from products.analytics_platform.backend.lazy_computation.stale_policy import is_background_warming_request
from products.marketing_analytics.backend.hogql_queries.constants import (
+ CHANNEL_SESSIONS_CTE_NAME,
DRILL_DOWN_LEVEL_CONFIG,
+ TOTAL_SESSIONS_FIELD,
UNIFIED_CONVERSION_GOALS_CTE_ALIAS,
+ UNKNOWN_CHANNEL,
)
from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (
BACKGROUND_WARMING_TRIGGERS,
@@ -47,7 +50,7 @@ from .adapters.factory import MarketingSourceFactory
from .conversion_goal_processor import ConversionGoalProcessor
from .conversion_goals_aggregator import ConversionGoalsAggregator
from .marketing_analytics_config import MarketingAnalyticsConfig
-from .utils import convert_team_conversion_goals_to_objects
+from .utils import build_source_normalization_expr, convert_team_conversion_goals_to_objects
logger = structlog.get_logger(__name__)
@@ -65,6 +68,16 @@ COMPARE_PERIOD_PREVIOUS = "previous"
COSTS_PRECOMPUTE_TTL_SECONDS = {"0d": 6 * 60 * 60, "1d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}
+def _session_start_day(expr: ast.Expr) -> ast.Expr:
+ """Truncate to the day, via a function the sessions timestamp pushdown recognizes.
+
+ `toStartOfDay` is on the allowlist in posthog/hogql/helpers/timestamp_visitor.py — `toDate` is
+ NOT, and using it silently drops the inner `raw_sessions` WHERE, making the CTE aggregate the
+ team's entire session history on every load.
+ """
+ return ast.Call(name="toStartOfDay", args=[expr])
+
+
class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC, Generic[ResponseType]):
"""Base class for marketing analytics query runners with shared functionality."""
@@ -447,6 +460,17 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
ast.Alias(alias=self.config.match_key_field, expr=ast.Constant(value="")),
]
)
+ elif level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ # Repurpose campaign_name to hold the channel, but keep the real source
+ # so each channel breaks down into its sources.
+ select_columns.extend(
+ [
+ ast.Alias(alias=self.config.campaign_field, expr=self._build_channel_type_expr()),
+ ast.Alias(alias=self.config.id_field, expr=ast.Constant(value="")),
+ ast.Alias(alias=self.config.source_field, expr=ast.Field(chain=[self.config.source_field])),
+ ast.Alias(alias=self.config.match_key_field, expr=ast.Constant(value="")),
+ ]
+ )
elif level == MarketingAnalyticsDrillDownLevel.SOURCE:
# Repurpose campaign_name to hold the source
select_columns.extend(
@@ -828,6 +852,72 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
now=datetime.now(),
)
+ def _build_sessions_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
+ """Session counts per channel x source, straight off the sessions table.
+
+ This is the only side of the query that sees untagged traffic: costs come from ad platforms
+ and conversions from UTM-tagged events, so without this a team with no connected ad source
+ sees an empty table. `$channel_type` is already derived on the sessions table, and the source
+ is normalized the same way the conversion side normalizes it so both sides agree on a row key.
+ """
+ source_mappings = MarketingSourceFactory.get_all_source_identifier_mappings(
+ team_config=self.team.marketing_analytics_config
+ )
+ source_expr = build_source_normalization_expr(
+ ast.Call(
+ name="if",
+ args=[
+ ast.Call(name="notEmpty", args=[ast.Field(chain=["sessions", "$entry_utm_source"])]),
+ ast.Field(chain=["sessions", "$entry_utm_source"]),
+ ast.Constant(value=self.config.organic_source),
+ ],
+ ),
+ source_mappings,
+ )
+ channel_expr = ast.Call(
+ name="if",
+ args=[
+ ast.Call(name="notEmpty", args=[ast.Field(chain=["sessions", "$channel_type"])]),
+ ast.Field(chain=["sessions", "$channel_type"]),
+ ast.Constant(value=UNKNOWN_CHANNEL),
+ ],
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias=self.config.campaign_field, expr=channel_expr),
+ ast.Alias(alias=self.config.source_field, expr=source_expr),
+ ast.Alias(
+ alias=TOTAL_SESSIONS_FIELD,
+ expr=ast.Call(name="uniq", args=[ast.Field(chain=["sessions", "session_id"])]),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["sessions"])),
+ # Bounded by day, not by datetime: `$start_timestamp` is an aggregate (min of the
+ # session's timestamps), and a raw datetime upper bound gets pushed down to the raw rows
+ # in a way that prunes the whole bucket the session lives in — the session silently
+ # disappears. Marketing date ranges are day-granular anyway.
+ where=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=_session_start_day(ast.Field(chain=["sessions", "$start_timestamp"])),
+ op=ast.CompareOperationOp.GtEq,
+ right=_session_start_day(
+ ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_from_str)])
+ ),
+ ),
+ ast.CompareOperation(
+ left=_session_start_day(ast.Field(chain=["sessions", "$start_timestamp"])),
+ op=ast.CompareOperationOp.LtEq,
+ right=_session_start_day(
+ ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_to_str)])
+ ),
+ ),
+ ]
+ ),
+ group_by=[channel_expr, source_expr],
+ )
+
def _build_complete_query_ast(
self,
union_subquery: ast.SelectQuery | ast.SelectSetQuery,
@@ -881,6 +971,14 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
if unified_cte:
ctes[UNIFIED_CONVERSION_GOALS_CTE_ALIAS] = unified_cte
+ if self.config.drill_down_level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ with self.timings.measure("ma_channel_sessions_cte"):
+ ctes[CHANNEL_SESSIONS_CTE_NAME] = ast.CTE(
+ name=CHANNEL_SESSIONS_CTE_NAME,
+ expr=self._build_sessions_select(date_range),
+ cte_type="subquery",
+ )
+
# Add CTEs to the main query
main_query.ctes = ctes
@@ -1061,6 +1159,8 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
if self.config.drill_down_level == MarketingAnalyticsDrillDownLevel.CHANNEL:
# channel is a computed alias, so GROUP BY the same expression
return [self._build_channel_type_expr()]
+ if self.config.drill_down_level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ return [self._build_channel_type_expr(), ast.Field(chain=[self.config.source_field])]
return [ast.Field(chain=[field]) for field in self.config.group_by_fields]
def _build_compare_pivot(
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 888aaaec02fb..bcf36af6db9b 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
@@ -214,6 +214,9 @@ class MarketingAnalyticsConfig:
if self.drill_down_level == MarketingAnalyticsDrillDownLevel.CHANNEL:
# CTE repurposes campaign_name to hold the channel value
return [self.campaign_field]
+ elif self.drill_down_level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ # Same repurposing as CHANNEL, but source stays a real grouping key
+ return [self.campaign_field, self.source_field]
elif self.drill_down_level == MarketingAnalyticsDrillDownLevel.SOURCE:
return [self.source_field]
elif self.drill_down_level == MarketingAnalyticsDrillDownLevel.AD_GROUP:
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 df130352926a..39588185461b 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
@@ -20,10 +20,14 @@ from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from .constants import (
BASE_COLUMN_MAPPING,
+ CHANNEL_SESSIONS_CTE_NAME,
DEFAULT_LIMIT,
DRILL_DOWN_LEVEL_CONFIG,
PAGINATION_EXTRA,
+ SESSIONS_COLUMN_ALIAS,
+ TOTAL_SESSIONS_FIELD,
UNIFIED_CONVERSION_GOALS_CTE_ALIAS,
+ UNKNOWN_CHANNEL,
get_effective_excluded_columns,
to_marketing_analytics_data,
)
@@ -33,6 +37,20 @@ from .marketing_analytics_base_query_runner import MarketingAnalyticsBaseQueryRu
logger = structlog.get_logger(__name__)
+def _coalesce_non_empty(chains: list[list[str | int]], fallback: str | None = None) -> ast.Expr:
+ """coalesce(nullif(a, ''), nullif(b, ''), …[, fallback]) — pick the first side that has a value.
+
+ A FULL OUTER JOIN leaves the grouping columns NULL on whichever side didn't match, and the CTEs
+ emit '' rather than NULL for a missing key, so both have to be treated as absent.
+ """
+ args: list[ast.Expr] = [
+ ast.Call(name="nullif", args=[ast.Field(chain=chain), ast.Constant(value="")]) for chain in chains
+ ]
+ if fallback is not None:
+ args.append(ast.Constant(value=fallback))
+ return args[0] if len(args) == 1 else ast.Call(name="coalesce", args=args)
+
+
class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[MarketingAnalyticsTableQueryResponse]):
query: MarketingAnalyticsTableQuery
cached_response: CachedMarketingAnalyticsTableQueryResponse
@@ -149,7 +167,7 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
# (channel type / source / utm value). Names are stable identifiers here.
return [campaign_alias]
else:
- # Campaign level keys on both Campaign + Source.
+ # Campaign and channel_source both key on their alias + Source.
return [campaign_alias, MarketingAnalyticsBaseColumns.SOURCE.value]
def _build_paginated_query(
@@ -305,23 +323,32 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
# Create the FROM clause with base table
from_clause = ast.JoinExpr(table=ast.Field(chain=[self.config.campaign_costs_cte_name]))
+ joined_ctes = [self.config.campaign_costs_cte_name]
# Add single unified conversion goals join if we have conversion goals
# (skip at ad-group / ad levels — no event attribution possible there).
if conversion_aggregator and not skip_conversion_goals_join:
if level in (
MarketingAnalyticsDrillDownLevel.CHANNEL,
+ MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,
MarketingAnalyticsDrillDownLevel.SOURCE,
):
join_type = "FULL OUTER JOIN"
- join_constraint = ast.JoinConstraint(
- expr=ast.CompareOperation(
- left=ast.Field(chain=self.config.get_campaign_cost_field_chain(self.config.campaign_field)),
+ # The grouping key is the join key. CHANNEL_SOURCE groups by two columns,
+ # so both have to match or a channel's sources would fan out.
+ join_fields = [self.config.campaign_field]
+ if level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ join_fields.append(self.config.source_field)
+ key_comparisons: list[ast.Expr] = [
+ ast.CompareOperation(
+ left=ast.Field(chain=self.config.get_campaign_cost_field_chain(join_field)),
op=ast.CompareOperationOp.Eq,
- right=ast.Field(
- chain=self.config.get_unified_conversion_field_chain(self.config.campaign_field)
- ),
- ),
+ right=ast.Field(chain=self.config.get_unified_conversion_field_chain(join_field)),
+ )
+ for join_field in join_fields
+ ]
+ join_constraint = ast.JoinConstraint(
+ expr=key_comparisons[0] if len(key_comparisons) == 1 else ast.And(exprs=key_comparisons),
constraint_type="ON",
)
# Replace grouping columns with COALESCE to handle NULLs from FULL OUTER JOIN
@@ -359,12 +386,68 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
constraint=join_constraint,
)
from_clause.next_join = unified_join
+ joined_ctes.append(self.config.unified_conversion_goals_cte_alias)
+
+ if level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
+ self._append_sessions_join(from_clause, joined_ctes, conversion_columns_mapping)
return ast.SelectQuery(
select=list(conversion_columns_mapping.values()),
select_from=from_clause,
)
+ def _append_sessions_join(
+ self,
+ from_clause: ast.JoinExpr,
+ joined_ctes: list[str],
+ columns: dict[str, ast.Expr],
+ ) -> None:
+ """FULL OUTER JOIN the sessions CTE and re-derive the grouping columns across every side.
+
+ Sessions is the only side that carries untagged traffic, so it contributes rows (organic,
+ direct, referral) the other sides never have. Its join key is the coalesce of the preceding
+ sides rather than one of them — keying off campaign_costs alone would drop the sessions of a
+ row that only exists on the conversion side.
+ """
+
+ def across(ctes: list[str], field: str, fallback: str | None = None) -> ast.Expr:
+ return _coalesce_non_empty([[cte, field] for cte in ctes], fallback)
+
+ sessions_join = ast.JoinExpr(
+ join_type="FULL OUTER JOIN",
+ table=ast.Field(chain=[CHANNEL_SESSIONS_CTE_NAME]),
+ alias=CHANNEL_SESSIONS_CTE_NAME,
+ constraint=ast.JoinConstraint(
+ expr=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=across(joined_ctes, field),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=[CHANNEL_SESSIONS_CTE_NAME, field]),
+ )
+ for field in (self.config.campaign_field, self.config.source_field)
+ ]
+ ),
+ constraint_type="ON",
+ ),
+ )
+ self._append_joins(from_clause, [sessions_join])
+
+ all_sides = [*joined_ctes, CHANNEL_SESSIONS_CTE_NAME]
+ campaign_alias = self.config.get_campaign_column_alias()
+ columns[campaign_alias] = ast.Alias(
+ alias=campaign_alias,
+ expr=across(all_sides, self.config.campaign_field, UNKNOWN_CHANNEL),
+ )
+ columns[self.config.source_column_alias] = ast.Alias(
+ alias=self.config.source_column_alias,
+ expr=across(all_sides, self.config.source_field, self.config.organic_source),
+ )
+ columns[SESSIONS_COLUMN_ALIAS] = ast.Alias(
+ alias=SESSIONS_COLUMN_ALIAS,
+ expr=ast.Field(chain=[CHANNEL_SESSIONS_CTE_NAME, TOTAL_SESSIONS_FIELD]),
+ )
+
def _append_joins(self, initial_join: ast.JoinExpr, joins: list[ast.JoinExpr]) -> ast.JoinExpr:
"""Recursively append joins to the initial join by using the next_join field"""
base_join = initial_join
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
index 6ba18880235a..36998ad8d016 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
@@ -1,5 +1,5 @@
import pytest
-from posthog.test.base import BaseTest, ClickhouseTestMixin
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import Mock, patch
from parameterized import parameterized
@@ -23,9 +23,14 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.clickhouse.query_tagging import Feature, reset_query_tags, tags_context
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.models.utils import uuid7
from products.marketing_analytics.backend.hogql_queries.adapters.base import MarketingSourceAdapter
-from products.marketing_analytics.backend.hogql_queries.constants import DEFAULT_LIMIT, DRILL_DOWN_LEVEL_CONFIG
+from products.marketing_analytics.backend.hogql_queries.constants import (
+ DEFAULT_LIMIT,
+ DRILL_DOWN_LEVEL_CONFIG,
+ SESSIONS_COLUMN_ALIAS,
+)
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (
MarketingAnalyticsTableQueryRunner,
)
@@ -438,6 +443,7 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
@parameterized.expand(
[
(MarketingAnalyticsDrillDownLevel.CHANNEL, "Channel"),
+ (MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE, "Channel"),
(MarketingAnalyticsDrillDownLevel.SOURCE, MarketingAnalyticsBaseColumns.SOURCE),
(MarketingAnalyticsDrillDownLevel.CAMPAIGN, MarketingAnalyticsBaseColumns.CAMPAIGN),
(MarketingAnalyticsDrillDownLevel.MEDIUM, "Medium"),
@@ -460,6 +466,7 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
@parameterized.expand(
[
(MarketingAnalyticsDrillDownLevel.CHANNEL,),
+ (MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,),
(MarketingAnalyticsDrillDownLevel.SOURCE,),
(MarketingAnalyticsDrillDownLevel.CAMPAIGN,),
(MarketingAnalyticsDrillDownLevel.MEDIUM,),
@@ -492,6 +499,7 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
@parameterized.expand(
[
(MarketingAnalyticsDrillDownLevel.CHANNEL,),
+ (MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,),
(MarketingAnalyticsDrillDownLevel.SOURCE,),
(MarketingAnalyticsDrillDownLevel.CAMPAIGN,),
(MarketingAnalyticsDrillDownLevel.MEDIUM,),
@@ -581,6 +589,141 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
f"source={source!r} expected channel={expected_channel!r}, got {channels}"
)
+ def test_channel_source_drill_down_keeps_sources_separate_within_a_channel(self):
+ """CHANNEL_SOURCE is the composite level: google and bing both classify as Paid Search,
+ but must stay separate rows. If source drops out of the grouping key they collapse into
+ one row and the level becomes indistinguishable from CHANNEL."""
+ query = MarketingAnalyticsTableQuery(
+ dateRange=self.default_date_range,
+ limit=DEFAULT_LIMIT,
+ offset=0,
+ properties=[],
+ drillDownLevel=MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,
+ )
+ runner = self._create_query_runner(query)
+ runner._apply_drill_down_level()
+
+ union_subquery = _build_synthetic_adapter_union(["google", "bing"])
+ cte_select = runner._build_campaign_cost_select(union_subquery)
+ response = execute_hogql_query(query=cte_select, team=self.team)
+
+ column_names = [col.alias if isinstance(col, ast.Alias) else str(col) for col in cte_select.select]
+ channel_idx = column_names.index(MarketingSourceAdapter.campaign_name_field)
+ source_idx = column_names.index(MarketingSourceAdapter.source_name_field)
+ rows = {(row[channel_idx], row[source_idx]) for row in response.results}
+
+ assert rows == {("Paid Search", "google"), ("Paid Search", "bing")}
+
+ def test_channel_source_drill_down_surfaces_untagged_traffic(self):
+ """Sessions is the only side of the query that sees traffic with no UTM tags and no ad spend.
+ Without it a team with nothing connected gets an empty table — which is the whole reason the
+ redesigned dashboard can drop the onboarding gate. A direct visit has to produce a row."""
+ # Timestamped uuid7: the sessions table prunes on the timestamp embedded in the session id,
+ # so a "now" id with a backdated event would be filtered out of the query's date range.
+ session_id = str(uuid7("2023-01-15"))
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=session_id,
+ timestamp="2023-01-15",
+ properties={"$session_id": session_id, "$referring_domain": "$direct", "$current_url": "http://x.com/"},
+ )
+ flush_persons_and_events()
+
+ query = MarketingAnalyticsTableQuery(
+ dateRange=self.default_date_range,
+ limit=DEFAULT_LIMIT,
+ offset=0,
+ properties=[],
+ drillDownLevel=MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,
+ )
+ result = self._create_query_runner(query).calculate()
+
+ assert result.columns is not None
+ assert SESSIONS_COLUMN_ALIAS in result.columns
+
+ channel_idx = result.columns.index("Channel")
+ sessions_idx = result.columns.index(SESSIONS_COLUMN_ALIAS)
+ source_idx = result.columns.index(MarketingAnalyticsBaseColumns.SOURCE)
+ direct_rows = [row for row in result.results if row[channel_idx].value == "Direct"]
+
+ assert len(direct_rows) == 1
+ assert direct_rows[0][sessions_idx].value == 1
+ # Untagged traffic has no utm_source, so the sessions side has to supply the organic default
+ # rather than an empty key — an empty one wouldn't join and would render as a blank cell.
+ assert direct_rows[0][source_idx].value == "organic"
+
+ def test_channel_source_drill_down_joins_three_sides_with_a_conversion_goal(self):
+ """With a conversion goal the sessions CTE joins on a key spanning two other tables
+ (coalesce over campaign_costs and the conversion CTE). ClickHouse rejects some multi-table
+ FULL JOIN keys outright, and no other test builds this shape — every one of them runs with
+ zero conversion goals, where the key collapses to a single-table reference."""
+ session_id = str(uuid7("2023-01-15"))
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=session_id,
+ timestamp="2023-01-15",
+ properties={
+ "$session_id": session_id,
+ "utm_source": "google",
+ "utm_medium": "cpc",
+ "utm_campaign": "brand",
+ },
+ )
+ _create_event(
+ team=self.team,
+ event="purchase",
+ distinct_id=session_id,
+ timestamp="2023-01-16",
+ properties={
+ "$session_id": session_id,
+ "utm_source": "google",
+ "utm_medium": "cpc",
+ "utm_campaign": "brand",
+ },
+ )
+ flush_persons_and_events()
+
+ query = MarketingAnalyticsTableQuery(
+ dateRange=self.default_date_range,
+ limit=DEFAULT_LIMIT,
+ offset=0,
+ properties=[],
+ drillDownLevel=MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,
+ draftConversionGoal=self._create_test_conversion_goal(goal_id="channel_source_goal"),
+ )
+ result = self._create_query_runner(query).calculate()
+
+ assert result.columns is not None
+ channel_idx = result.columns.index("Channel")
+ source_idx = result.columns.index(MarketingAnalyticsBaseColumns.SOURCE)
+ rows = [(row[channel_idx].value, row[source_idx].value) for row in result.results]
+
+ # One row per (channel, source) — a broken join key would fan this out into duplicates.
+ assert len(rows) == len(set(rows))
+ assert ("Paid Search", "google") in rows
+
+ def test_channel_source_drill_down_emits_both_channel_and_source_columns(self):
+ """The whole point of the composite level: Source survives as a column (it's excluded at
+ CHANNEL). Losing it would silently turn the table back into a flat channel breakdown."""
+ query = MarketingAnalyticsTableQuery(
+ dateRange=self.default_date_range,
+ limit=DEFAULT_LIMIT,
+ offset=0,
+ properties=[],
+ drillDownLevel=MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE,
+ )
+ runner = self._create_query_runner(query)
+
+ with patch.object(MarketingAnalyticsTableQueryRunner, "_get_marketing_source_adapters") as mock_get_adapters:
+ mock_get_adapters.return_value = []
+ ast_query = runner.to_query()
+
+ column_names = [col.alias if isinstance(col, ast.Alias) else str(col) for col in ast_query.select]
+
+ assert column_names[:2] == ["Channel", MarketingAnalyticsBaseColumns.SOURCE.value]
+
@pytest.mark.usefixtures("unittest_snapshot")
def test_channel_drill_down_meta_to_facebook_mapping_snapshot(self):
"""Channel drill-down rewrites adapter source 'meta' to 'facebook' before lookupPaidSourceType."""
@@ -603,6 +746,7 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
@parameterized.expand(
[
(MarketingAnalyticsDrillDownLevel.CHANNEL, True),
+ (MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE, True),
(MarketingAnalyticsDrillDownLevel.SOURCE, True),
(MarketingAnalyticsDrillDownLevel.CAMPAIGN, True),
(MarketingAnalyticsDrillDownLevel.MEDIUM, False),
diff --git a/products/marketing_analytics/backend/hogql_queries/utils.py b/products/marketing_analytics/backend/hogql_queries/utils.py
index dcaf2bddaaf9..450dfdd7c8f6 100644
--- a/products/marketing_analytics/backend/hogql_queries/utils.py
+++ b/products/marketing_analytics/backend/hogql_queries/utils.py
@@ -7,9 +7,46 @@ from pydantic import BaseModel
from posthog.schema import ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3, NodeKind
+from posthog.hogql import ast
+
logger = structlog.get_logger(__name__)
+def build_source_normalization_expr(source_expr: ast.Expr, source_mappings: dict[str, list[str]]) -> ast.Expr:
+ """Map alternative UTM sources onto their primary source ('YouTube' -> 'google'), case-insensitively.
+
+ Shared by the conversion-goal side and the sessions side so both collapse a source the same way —
+ otherwise the two sides of the join would disagree on what 'youtube' is and split into two rows.
+ """
+ lowercase_source = ast.Call(name="lower", args=[source_expr])
+ normalized_expr = source_expr
+
+ # Known gap: the primary is excluded from its own alternatives, so a differently-cased spelling
+ # of it ("Google") passes through unnormalized while the cost side emits "google" — the same
+ # source then splits into two rows. Fixing it changes the SQL at every drill-down level, so it
+ # belongs in its own change.
+ for primary_source, alternative_sources in source_mappings.items():
+ alternatives_only = [s.lower() for s in alternative_sources if s != primary_source]
+ if not alternatives_only:
+ continue
+ normalized_expr = ast.Call(
+ name="if",
+ args=[
+ ast.Call(
+ name="in",
+ args=[
+ lowercase_source,
+ ast.Array(exprs=[ast.Constant(value=alt) for alt in alternatives_only]),
+ ],
+ ),
+ ast.Constant(value=primary_source),
+ normalized_expr,
+ ],
+ )
+
+ return normalized_expr
+
+
def _filter_to_model_fields(goal_dict: dict[str, Any], model: type[BaseModel]) -> dict[str, Any]:
"""Keep only keys the target pydantic model declares, so extra fields (e.g. data-warehouse-only
fields on a saved goal) don't trip the model's ``extra="forbid"`` validation."""
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 389a64f5ff18..034e7f04908d 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -6064,6 +6064,7 @@ export type MarketingAnalyticsDrillDownLevelApi =
export const MarketingAnalyticsDrillDownLevelApi = {
Channel: 'channel',
+ ChannelSource: 'channel_source',
Source: 'source',
Campaign: 'campaign',
AdGroup: 'ad_group',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6e565ad5e208..b862fbd3da6c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -6511,6 +6511,7 @@ export namespace Schemas {
export const MarketingAnalyticsDrillDownLevel = {
Channel: 'channel',
+ ChannelSource: 'channel_source',
Source: 'source',
Campaign: 'campaign',
AdGroup: 'ad_group',