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): filter traffic no integration reports cost for (#96943)

Javier Bahamondese44215970ce5
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 047a22f9e66d..207b83da3752 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -30814,6 +30814,10 @@
"IntegrationFilter": {
"additionalProperties": false,
"properties": {
+ "includeNonIntegrated": {
+ "description": "Keep rows that no integration reports cost for, such as organic, email or an unmapped source. Defaults to true.",
+ "type": "boolean"
+ },
"integrationSourceIds": {
"description": "Selected integration source IDs to filter by (e.g., table IDs or source map IDs)",
"items": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 2ffbbb4f4578..dc959a145172 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1921,6 +1921,8 @@ export interface CompareFilter {
export interface IntegrationFilter {
/** Selected integration source IDs to filter by (e.g., table IDs or source map IDs) */
integrationSourceIds?: string[]
+ /** Keep rows that no integration reports cost for, such as organic, email or an unmapped source. Defaults to true. */
+ includeNonIntegrated?: boolean
}
/** `FunnelsFilterType` minus everything inherited from `FilterType` and persons modal related params */
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx
index c660a38113c5..22c35e3c736e 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/IntegrationFilter.tsx
@@ -20,12 +20,14 @@ export function IntegrationFilter(): JSX.Element {
const allSourceIds = allAvailableSourcesWithStatus.map((s) => s.id)
const isAllSelected = selectedIds.length === allSourceIds.length && allSourceIds.length > 0
const isSomeSelected = selectedIds.length > 0 && selectedIds.length < allSourceIds.length
+ // Absent means included, so only an explicit false hides these rows.
+ const includeNonIntegrated = integrationFilter.includeNonIntegrated !== false
const handleToggleAll = (): void => {
if (isAllSelected || isSomeSelected) {
- setIntegrationFilter({ integrationSourceIds: [] })
+ setIntegrationFilter({ integrationSourceIds: [], includeNonIntegrated })
} else {
- setIntegrationFilter({ integrationSourceIds: allSourceIds })
+ setIntegrationFilter({ integrationSourceIds: allSourceIds, includeNonIntegrated })
}
}
@@ -34,7 +36,11 @@ export function IntegrationFilter(): JSX.Element {
? selectedIds.filter((id) => id !== sourceId)
: [...selectedIds, sourceId]
- setIntegrationFilter({ integrationSourceIds: newIds })
+ setIntegrationFilter({ integrationSourceIds: newIds, includeNonIntegrated })
+ }
+
+ const handleToggleNonIntegrated = (): void => {
+ setIntegrationFilter({ integrationSourceIds: selectedIds, includeNonIntegrated: !includeNonIntegrated })
}
const formatSourceLabel = (source: { name: string; type: string; prefix?: string }): string => {
@@ -43,14 +49,17 @@ export function IntegrationFilter(): JSX.Element {
}
const displayValue = (): string => {
+ // Hiding the non-integrated rows changes what the table reports, so the button says so at
+ // every selection, not only when the sources are all in or all out.
+ const suffix = includeNonIntegrated ? '' : ', integrated only'
if (selectedIds.length === 0 || isAllSelected) {
- return 'All integrations'
+ return includeNonIntegrated ? 'All integrations' : 'Integrated only'
}
if (selectedIds.length === 1) {
const source = allAvailableSourcesWithStatus.find((s) => s.id === selectedIds[0])
- return source ? formatSourceLabel(source) : '1 integration'
+ return `${source ? formatSourceLabel(source) : '1 integration'}${suffix}`
}
- return `${selectedIds.length} integrations`
+ return `${selectedIds.length} integrations${suffix}`
}
// Don't show the filter if there are no available sources
@@ -101,6 +110,19 @@ export function IntegrationFilter(): JSX.Element {
</span>
</LemonButton>
))}
+ <div className="border-t border-border my-1" />
+ <LemonButton
+ fullWidth
+ size="small"
+ onClick={handleToggleNonIntegrated}
+ className="justify-start"
+ tooltip="Traffic no integration reports cost for, like organic, email, or a source you haven't mapped yet."
+ >
+ <span className="flex items-center gap-2">
+ <LemonCheckbox checked={includeNonIntegrated} className="pointer-events-none" />
+ <span className="flex-1">No integration</span>
+ </span>
+ </LemonButton>
</div>
}
>
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index bd27d6bf4530..3c0daeaed76b 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -460,6 +460,7 @@ export interface marketingAnalyticsLogicActions {
dateFrom?: string | null
dateTo?: string | null
drillDownLevel?: MarketingAnalyticsDrillDownLevel
+ includeNonIntegrated?: boolean
integrationSourceIds?: string[]
interval?: IntervalType
tileColumnSelection?: string
@@ -471,6 +472,7 @@ export interface marketingAnalyticsLogicActions {
dateFrom?: string | null | undefined
dateTo?: string | null | undefined
drillDownLevel?: MarketingAnalyticsDrillDownLevel | undefined
+ includeNonIntegrated?: boolean | undefined
integrationSourceIds?: string[] | undefined
interval?: IntervalType | undefined
tileColumnSelection?: string | undefined
@@ -654,6 +656,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
compare?: boolean
compare_to?: string
integrationSourceIds?: string[]
+ includeNonIntegrated?: boolean
chartDisplayType?: ChartDisplayType
tileColumnSelection?: string
drillDownLevel?: MarketingAnalyticsDrillDownLevel
@@ -728,8 +731,15 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
persistConfig,
{
setIntegrationFilter: (_, { integrationFilter }) => integrationFilter,
- syncFromUrl: (state, { params }) =>
- params.integrationSourceIds ? { integrationSourceIds: params.integrationSourceIds } : state,
+ syncFromUrl: (state, { params }) => {
+ if (!params.integrationSourceIds && params.includeNonIntegrated === undefined) {
+ return state
+ }
+ return {
+ integrationSourceIds: params.integrationSourceIds ?? state.integrationSourceIds,
+ includeNonIntegrated: params.includeNonIntegrated ?? state.includeNonIntegrated,
+ }
+ },
},
],
dateFilter: [
@@ -1310,6 +1320,10 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
if (values.integrationFilter?.integrationSourceIds?.length) {
searchParams.set('integration_sources', values.integrationFilter.integrationSourceIds.join(','))
}
+ // Only the cleared state travels: absent means included, which is the default.
+ if (values.integrationFilter?.includeNonIntegrated === false) {
+ searchParams.set('include_non_integrated', 'false')
+ }
// Chart display type
if (values.chartDisplayType) {
@@ -1479,6 +1493,9 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
if (integrationSources) {
params.integrationSourceIds = integrationSources.split(',').filter(Boolean)
}
+ if (searchParams.get('include_non_integrated') === 'false') {
+ params.includeNonIntegrated = false
+ }
const chartDisplayType = searchParams.get('chart_display_type') as ChartDisplayType | null
if (chartDisplayType && Object.values(ChartDisplayType).includes(chartDisplayType)) {
params.chartDisplayType = chartDisplayType
diff --git a/posthog/schema.py b/posthog/schema.py
index 38d1a1a32805..ebf548e6d2a8 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -1721,6 +1721,13 @@ class IntegrationFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ includeNonIntegrated: bool | None = Field(
+ default=None,
+ description=(
+ "Keep rows that no integration reports cost for, such as organic, email or"
+ " an unmapped source. Defaults to true."
+ ),
+ )
integrationSourceIds: list[str] | None = Field(
default=None,
description=("Selected integration source IDs to filter by (e.g., table IDs or source map IDs)"),
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 89549e813f5d..24526588d6d1 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -7705,6 +7705,8 @@ export const MarketingAnalyticsDrillDownLevelApi = {
} as const
export interface IntegrationFilterApi {
+ /** Keep rows that no integration reports cost for, such as organic, email or an unmapped source. Defaults to true. */
+ includeNonIntegrated?: boolean | null
/** Selected integration source IDs to filter by (e.g., table IDs or source map IDs) */
integrationSourceIds?: string[] | null
}
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 83e0cbcfd93e..cd401bcd9d2b 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
@@ -167,7 +167,11 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
return [campaign_alias, MarketingAnalyticsBaseColumns.SOURCE.value]
def _build_paginated_query(
- self, select_columns: list[ast.Expr], select_from: ast.JoinExpr | None, ctes=None
+ self,
+ select_columns: list[ast.Expr],
+ select_from: ast.JoinExpr | None,
+ ctes=None,
+ where: ast.Expr | None = None,
) -> ast.SelectQuery:
"""Build a paginated SelectQuery with common logic"""
# Extract column names for order by
@@ -183,6 +187,7 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
select=select_columns,
select_from=select_from,
ctes=ctes,
+ where=where,
order_by=order_by_exprs,
limit=ast.Constant(value=actual_limit),
offset=ast.Constant(value=offset),
@@ -192,7 +197,7 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
"""Execute the query and return results with pagination support"""
query = self.to_query()
filtered_select = self._get_filtered_select_columns(query)
- return self._build_paginated_query(filtered_select, query.select_from, query.ctes)
+ return self._build_paginated_query(filtered_select, query.select_from, query.ctes, query.where)
def calculate_with_compare(self) -> ast.SelectQuery:
"""Execute the query and return results with pagination support"""
@@ -376,9 +381,16 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
if level == MarketingAnalyticsDrillDownLevel.CHANNEL_SOURCE:
self._append_sessions_join(from_clause, joined_ctes, conversion_columns_mapping)
+ where = (
+ ast.Call(name="notEmpty", args=[self._cost_side_grouping_value()])
+ if self._non_integrated_rows_excluded()
+ else None
+ )
+
return ast.SelectQuery(
select=list(conversion_columns_mapping.values()),
select_from=from_clause,
+ where=where,
)
def _append_sessions_join(
@@ -442,6 +454,22 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
base_join.next_join = current_join
return initial_join
+ def _cost_side_grouping_value(self) -> ast.Expr:
+ """The cost side's grouping value, which is empty exactly when no cost row matched.
+
+ Every level puts its grouping value in this column — the campaign name at campaign level,
+ the channel or source at the others. Under `join_use_nulls = 0` an unmatched side returns
+ the type default, so an empty string here means the row came from the conversion side only.
+ """
+ return ast.Call(
+ name="toString",
+ args=[
+ ast.Field(
+ chain=self.config.get_campaign_cost_field_chain(MarketingAnalyticsColumnsSchemaNames.CAMPAIGN)
+ )
+ ],
+ )
+
def _null_without_cost_row(self, column: ast.Expr) -> ast.Expr:
"""Wrap a cost-side metric so it reads as absent, not as zero, when no cost row matched.
@@ -454,27 +482,18 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
guarded = ast.Call(
name="if",
args=[
- ast.Call(
- name="empty",
- args=[
- ast.Call(
- name="toString",
- args=[
- ast.Field(
- chain=self.config.get_campaign_cost_field_chain(
- MarketingAnalyticsColumnsSchemaNames.CAMPAIGN
- )
- )
- ],
- )
- ],
- ),
+ ast.Call(name="empty", args=[self._cost_side_grouping_value()]),
ast.Constant(value=None),
expr,
],
)
return ast.Alias(alias=alias, expr=guarded) if alias else guarded
+ def _non_integrated_rows_excluded(self) -> bool:
+ """True when the user cleared the filter's non-integrated option."""
+ integration_filter = getattr(self.query, "integrationFilter", None)
+ return integration_filter is not None and integration_filter.includeNonIntegrated is False
+
def _build_order_by_exprs(self, select_columns: list[str]) -> list[ast.OrderExpr]:
"""Build ORDER BY expressions from query orderBy with proper null handling"""
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 d0f62408786a..5eb3b2f3cf33 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
@@ -10,6 +10,7 @@ from posthog.schema import (
ConversionGoalFilter1,
ConversionGoalFilter3,
DateRange,
+ IntegrationFilter,
MarketingAnalyticsBaseColumns,
MarketingAnalyticsDrillDownLevel,
MarketingAnalyticsTableQuery,
@@ -757,6 +758,41 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
assert no_spend_row[cost_idx].value is None
assert no_spend_row[clicks_idx].value is None
+ def test_integration_filter_can_exclude_campaigns_with_no_ad_spend(self) -> None:
+ session_id = str(uuid7("2023-01-15"))
+ for event in ("$pageview", "purchase"):
+ _create_event(
+ team=self.team,
+ event=event,
+ distinct_id=session_id,
+ timestamp="2023-01-15",
+ properties={
+ "$session_id": session_id,
+ "utm_source": "newsletter",
+ "utm_campaign": "fall_sale_newsletter",
+ },
+ )
+ flush_persons_and_events()
+
+ def campaigns_for(integration_filter: IntegrationFilter | None) -> set[str]:
+ query = MarketingAnalyticsTableQuery(
+ dateRange=self.default_date_range,
+ limit=DEFAULT_LIMIT,
+ offset=0,
+ properties=[],
+ drillDownLevel=MarketingAnalyticsDrillDownLevel.CAMPAIGN,
+ draftConversionGoal=self._create_test_conversion_goal(goal_id="filter_goal"),
+ integrationFilter=integration_filter,
+ )
+ result = self._create_query_runner(query).calculate()
+ assert result.columns is not None
+ campaign_idx = result.columns.index(MarketingAnalyticsBaseColumns.CAMPAIGN)
+ return {str(row[campaign_idx].value) for row in result.results}
+
+ assert "fall_sale_newsletter" in campaigns_for(None)
+ assert "fall_sale_newsletter" in campaigns_for(IntegrationFilter(includeNonIntegrated=True))
+ assert "fall_sale_newsletter" not in campaigns_for(IntegrationFilter(includeNonIntegrated=False))
+
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."""
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 2070b65ab9af..cc20e3fe6459 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -6699,6 +6699,8 @@ export const MarketingAnalyticsDrillDownLevelApi = {
} as const
export interface IntegrationFilterApi {
+ /** Keep rows that no integration reports cost for, such as organic, email or an unmapped source. Defaults to true. */
+ includeNonIntegrated?: boolean | null
/** Selected integration source IDs to filter by (e.g., table IDs or source map IDs) */
integrationSourceIds?: string[] | null
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 41c2a52404ac..bbc3ef1f822d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8190,6 +8190,8 @@ export namespace Schemas {
} as const;
export interface IntegrationFilter {
+ /** Keep rows that no integration reports cost for, such as organic, email or an unmapped source. Defaults to true. */
+ includeNonIntegrated?: boolean | null;
/** Selected integration source IDs to filter by (e.g., table IDs or source map IDs) */
integrationSourceIds?: string[] | null;
}