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): let marketing analytics exclude test accounts (#89551)

Javier Bahamondes3ab16c5fe8e4
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index b67061d61ade..7367f3d1334a 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -1756,6 +1756,8 @@ export interface TeamMarketingAnalyticsConfigApi {
* * `time_decay` - Time Decay
* * `position_based` - Position Based */
attribution_mode?: AttributionModeEnumApi
+ /** Whether marketing analytics drops traffic matching the project's test-account filters. Off by default. */
+ filter_test_accounts?: boolean
/** Manual campaign name aliases, keyed by integration type then by canonical campaign name, with the list of names that should be folded into it. Applied before automatic matching. */
campaign_name_mappings?: MarketingAnalyticsCampaignNameMappingsApi
/** Custom UTM source values to fold into an integration, keyed by integration type. A UTM source can only belong to one integration. */
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 91b4ea62b815..448b248eb88a 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -35385,6 +35385,9 @@
},
"type": "object"
},
+ "filter_test_accounts": {
+ "type": "boolean"
+ },
"sources_map": {
"additionalProperties": {
"$ref": "#/definitions/SourceMap"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 1b044410b9d6..1968f496cd62 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -7867,6 +7867,7 @@ export interface MarketingAnalyticsConfig {
conversion_goals?: ConversionGoalFilter[]
attribution_window_days?: number
attribution_mode?: AttributionMode
+ filter_test_accounts?: boolean
campaign_name_mappings?: Record<string, Record<string, string[]>>
custom_source_mappings?: Record<string, string[]>
campaign_field_preferences?: Record<string, CampaignFieldPreference>
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx
index 581cab70cfda..cbd373b04ed5 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx
@@ -1,12 +1,19 @@
import { BindLogic } from 'kea'
import { useActions, useValues } from 'kea'
+import { IconGear } from '@posthog/icons'
+import { LemonButton, LemonDivider, Popover } from '@posthog/lemon-ui'
+
import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { FilterBar } from 'lib/components/FilterBar'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
+import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
+import { OrganizationMembershipLevel } from 'lib/constants'
import { Scene } from 'scenes/sceneTypes'
+import { teamLogic } from 'scenes/teamLogic'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
import { ReloadAll } from '~/queries/nodes/DataNode/Reload'
@@ -19,8 +26,14 @@ import { ConversionGoalModal } from './ConversionGoalModal'
import { IntegrationFilter } from './IntegrationFilter'
export const MarketingAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Element => {
- const { compareFilter, dateFilter } = useValues(marketingAnalyticsLogic)
- const { setCompareFilter, setDates } = useActions(marketingAnalyticsLogic)
+ const { compareFilter, dateFilter, shouldFilterTestAccounts, optionsOpen } = useValues(marketingAnalyticsLogic)
+ const { currentTeamLoading } = useValues(teamLogic)
+ const { setCompareFilter, setDates, updateFilterTestAccounts, setOptionsOpen } = useActions(marketingAnalyticsLogic)
+ // The setting lives on the project, so flipping it changes what everyone sees.
+ const editRestrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
+ })
return (
<BindLogic logic={dataNodeCollectionLogic} props={{ key: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID }}>
@@ -51,14 +64,63 @@ export const MarketingAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.
>
<AddIntegrationButton />
</Shortcut>
- <IntegrationFilter />
- <DateFilter
- allowTimePrecision
- dateFrom={dateFilter.dateFrom}
- dateTo={dateFilter.dateTo}
- onChange={setDates}
- />
- <CompareFilter compareFilter={compareFilter} updateCompareFilter={setCompareFilter} />
+ <Popover
+ visible={optionsOpen}
+ onClickOutside={() => setOptionsOpen(false)}
+ placement="bottom-end"
+ overlay={
+ // Ordered by how often they get touched, so the rarely-changed
+ // project setting sits last.
+ <div className="flex w-80 max-w-[90vw] flex-col gap-4 p-3">
+ <div>
+ <div className="text-muted mb-2 text-xs font-semibold uppercase">
+ Date range
+ </div>
+ <DateFilter
+ allowTimePrecision
+ dateFrom={dateFilter.dateFrom}
+ dateTo={dateFilter.dateTo}
+ onChange={setDates}
+ />
+ </div>
+ <div>
+ <div className="text-muted mb-2 text-xs font-semibold uppercase">
+ Comparison
+ </div>
+ <CompareFilter
+ compareFilter={compareFilter}
+ updateCompareFilter={setCompareFilter}
+ />
+ </div>
+ <div>
+ <div className="text-muted mb-2 text-xs font-semibold uppercase">
+ Integrations
+ </div>
+ <IntegrationFilter />
+ </div>
+ <LemonDivider className="my-0" />
+ {/* Only the event side honors this: ad spend comes from the platforms. */}
+ <TestAccountFilterSwitch
+ fullWidth
+ checked={shouldFilterTestAccounts}
+ onChange={updateFilterTestAccounts}
+ disabledReason={
+ editRestrictionReason ?? (currentTeamLoading ? 'Saving…' : undefined)
+ }
+ />
+ </div>
+ }
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconGear />}
+ onClick={() => setOptionsOpen(!optionsOpen)}
+ data-attr="marketing-analytics-options"
+ >
+ Options
+ </LemonButton>
+ </Popover>
</>
}
/>
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 bd4f2b1bd6c7..bd27d6bf4530 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
@@ -241,6 +241,7 @@ const INITIAL_INTERVAL = getDefaultInterval(INITIAL_DATE_FROM, INITIAL_DATE_TO)
export interface marketingAnalyticsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
conversion_goals: ConversionGoalFilter[] // marketingAnalyticsSettingsLogic
+ filter_test_accounts: boolean // marketingAnalyticsSettingsLogic
sources_map: Record<string, SourceMap> // marketingAnalyticsSettingsLogic
dataWarehouseSources: PaginatedResponse<ExternalDataSource> | null // sourceManagementLogic
dataWarehouseSourcesLoading: boolean // sourceManagementLogic
@@ -305,8 +306,10 @@ export interface marketingAnalyticsLogicValues {
loading: boolean
nativeSources: ExternalDataSource[]
nativeSourcesHierarchyStatus: NativeSourceHierarchyStatus[]
+ optionsOpen: boolean
overviewQuery: MarketingAnalyticsAggregatedQuery
setupSection: SetupSection
+ shouldFilterTestAccounts: boolean
tileColumnSelection: validColumnsForTiles
uniqueConversionGoalName: string
validExternalTables: ExternalTable[]
@@ -322,6 +325,9 @@ export interface marketingAnalyticsLogicActions {
addOrUpdateConversionGoal: (conversionGoal: ConversionGoalFilter) => {
conversionGoal: ConversionGoalFilter
} // marketingAnalyticsSettingsLogic
+ updateFilterTestAccounts: (filterTestAccounts: boolean) => {
+ filterTestAccounts: boolean
+ } // marketingAnalyticsSettingsLogic
loadDatabase: (
args_0?:
| {
@@ -432,6 +438,9 @@ export interface marketingAnalyticsLogicActions {
setIntegrationFilter: (integrationFilter: IntegrationFilter) => {
integrationFilter: IntegrationFilter
}
+ setOptionsOpen: (optionsOpen: boolean) => {
+ optionsOpen: boolean
+ }
setSetupSection: (section: SetupSection) => {
section: SetupSection
}
@@ -567,6 +576,7 @@ export interface marketingAnalyticsLogicMeta {
tileColumnSelection: validColumnsForTiles,
integrationFilter: IntegrationFilter
) => DataWarehouseNode[]
+ shouldFilterTestAccounts: (filter_test_accounts: boolean) => boolean
overviewQuery: (
dateFilter: {
dateFrom: string | null
@@ -575,7 +585,8 @@ export interface marketingAnalyticsLogicMeta {
},
compareFilter: CompareFilter,
draftConversionGoal: ConversionGoalFilter | null,
- integrationFilter: IntegrationFilter
+ integrationFilter: IntegrationFilter,
+ shouldFilterTestAccounts: boolean
) => MarketingAnalyticsAggregatedQuery
}
}
@@ -594,7 +605,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
teamLogic,
['baseCurrency'],
marketingAnalyticsSettingsLogic,
- ['sources_map', 'conversion_goals'],
+ ['sources_map', 'conversion_goals', 'filter_test_accounts'],
sourceManagementLogic,
['dataWarehouseTables', 'dataWarehouseSourcesLoading', 'dataWarehouseSources'],
featureFlagLogic,
@@ -606,7 +617,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
dataNodeCollectionLogic({ key: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID }),
['reloadAll'],
marketingAnalyticsSettingsLogic,
- ['addOrUpdateConversionGoal'],
+ ['addOrUpdateConversionGoal', 'updateFilterTestAccounts'],
teamLogic,
['addProductIntent'],
],
@@ -634,6 +645,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
interval,
}),
setIntegrationFilter: (integrationFilter: IntegrationFilter) => ({ integrationFilter }),
+ setOptionsOpen: (optionsOpen: boolean) => ({ optionsOpen }),
// Internal action for URL sync - updates state without triggering actionToUrl
syncFromUrl: (params: {
dateFrom?: string | null
@@ -710,6 +722,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
},
},
],
+ optionsOpen: [false as boolean, { setOptionsOpen: (_, { optionsOpen }) => optionsOpen }],
integrationFilter: [
{ integrationSourceIds: [] } as IntegrationFilter,
persistConfig,
@@ -1224,8 +1237,18 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return [...nativeNodeList, ...nonNativeNodeList]
},
],
+ shouldFilterTestAccounts: [
+ (s) => [s.filter_test_accounts],
+ (filter_test_accounts: boolean): boolean => filter_test_accounts,
+ ],
overviewQuery: [
- (s) => [s.dateFilter, s.compareFilter, s.draftConversionGoal, s.integrationFilter],
+ (s) => [
+ s.dateFilter,
+ s.compareFilter,
+ s.draftConversionGoal,
+ s.integrationFilter,
+ s.shouldFilterTestAccounts,
+ ],
(
dateFilter: {
dateFrom: string | null
@@ -1234,7 +1257,8 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
},
compareFilter: CompareFilter,
draftConversionGoal: ConversionGoalFilter | null,
- integrationFilter: IntegrationFilter
+ integrationFilter: IntegrationFilter,
+ shouldFilterTestAccounts: boolean
): MarketingAnalyticsAggregatedQuery => ({
kind: NodeKind.MarketingAnalyticsAggregatedQuery,
dateRange: {
@@ -1243,6 +1267,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
},
compareFilter,
properties: [],
+ filterTestAccounts: shouldFilterTestAccounts,
draftConversionGoal: draftConversionGoal || undefined,
integrationFilter,
}),
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.ts
index 261472bb66ba..02321cf102e2 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.ts
@@ -52,6 +52,7 @@ const createEmptyConfig = (): MarketingAnalyticsConfig => ({
conversion_goals: [],
attribution_window_days: DEFAULT_ATTRIBUTION_WINDOW_DAYS,
attribution_mode: AttributionMode.LastTouch,
+ filter_test_accounts: false,
campaign_name_mappings: {},
custom_source_mappings: {},
campaign_field_preferences: {},
@@ -69,6 +70,7 @@ export interface marketingAnalyticsSettingsLogicValues {
attribution_mode: AttributionMode
attribution_window_days: number
conversion_goals: ConversionGoalFilter[]
+ filter_test_accounts: boolean
integrationCampaignTables: Record<string, string>
integrationCampaigns: Record<
string,
@@ -181,6 +183,9 @@ export interface marketingAnalyticsSettingsLogicActions {
updateCustomSourceMappings: (customSourceMappings: Record<string, string[]>) => {
customSourceMappings: Record<string, string[]>
}
+ updateFilterTestAccounts: (filterTestAccounts: boolean) => {
+ filterTestAccounts: boolean
+ }
updateSourceMapping: (
tableId: string,
fieldName: MarketingAnalyticsColumnsSchemaNames,
@@ -199,6 +204,7 @@ export interface marketingAnalyticsSettingsLogicMeta {
conversion_goals: (marketingAnalyticsConfig: MarketingAnalyticsConfig | null) => ConversionGoalFilter[]
attribution_window_days: (marketingAnalyticsConfig: MarketingAnalyticsConfig | null) => number
attribution_mode: (marketingAnalyticsConfig: MarketingAnalyticsConfig | null) => AttributionMode
+ filter_test_accounts: (marketingAnalyticsConfig: MarketingAnalyticsConfig | null) => boolean
integrationCampaignTables: (
dataWarehouseTables: DatabaseSchemaDataWarehouseTable[],
dataWarehouseSources: PaginatedResponse<ExternalDataSource> | null
@@ -249,6 +255,9 @@ export const marketingAnalyticsSettingsLogic = kea<marketingAnalyticsSettingsLog
updateAttributionMode: (mode: AttributionMode) => ({
mode,
}),
+ updateFilterTestAccounts: (filterTestAccounts: boolean) => ({
+ filterTestAccounts,
+ }),
updateCampaignNameMappings: (campaignNameMappings: Record<string, Record<string, string[]>>) => ({
campaignNameMappings,
}),
@@ -363,6 +372,12 @@ export const marketingAnalyticsSettingsLogic = kea<marketingAnalyticsSettingsLog
}
return { ...state, attribution_mode: mode }
},
+ updateFilterTestAccounts: (state: MarketingAnalyticsConfig | null, { filterTestAccounts }) => {
+ if (!state) {
+ return { ...createEmptyConfig(), filter_test_accounts: filterTestAccounts }
+ }
+ return { ...state, filter_test_accounts: filterTestAccounts }
+ },
updateCampaignNameMappings: (state: MarketingAnalyticsConfig | null, { campaignNameMappings }) => {
if (!state) {
return { ...createEmptyConfig(), campaign_name_mappings: campaignNameMappings }
@@ -481,6 +496,12 @@ export const marketingAnalyticsSettingsLogic = kea<marketingAnalyticsSettingsLog
return marketingAnalyticsConfig?.attribution_mode ?? AttributionMode.LastTouch
},
],
+ filter_test_accounts: [
+ (s) => [s.marketingAnalyticsConfig],
+ (marketingAnalyticsConfig: MarketingAnalyticsConfig | null) => {
+ return marketingAnalyticsConfig?.filter_test_accounts ?? false
+ },
+ ],
integrationCampaignTables: [
(s) => [s.dataWarehouseTables, s.dataWarehouseSources],
(
@@ -553,6 +574,8 @@ export const marketingAnalyticsSettingsLogic = kea<marketingAnalyticsSettingsLog
removeConversionGoal: trackSettingsUpdated,
updateAttributionWindowDays: trackSettingsUpdated,
updateAttributionMode: trackSettingsUpdated,
+ // Persist only: this one is a dashboard filter, not a trip to the settings screen.
+ updateFilterTestAccounts: () => updateCurrentTeam(),
updateCampaignNameMappings: trackSettingsUpdated,
updateCustomSourceMappings: trackSettingsUpdated,
updateCampaignFieldPreferences: trackSettingsUpdated,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
index 0906e6532c86..ebd9403f4a1f 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
@@ -84,6 +84,7 @@ export interface marketingAnalyticsTilesLogicValues {
drillDownLevel: MarketingAnalyticsDrillDownLevel // marketingAnalyticsLogic
integrationFilter: IntegrationFilter // marketingAnalyticsLogic
loading: boolean // marketingAnalyticsLogic
+ shouldFilterTestAccounts: boolean // marketingAnalyticsLogic
tileColumnSelection: validColumnsForTiles // marketingAnalyticsLogic
defaultColumns: string[] // marketingAnalyticsTableLogic
query: DataTableNode | null // marketingAnalyticsTableLogic
@@ -105,7 +106,8 @@ export interface marketingAnalyticsTilesLogicMeta {
interval: IntervalType
},
draftConversionGoal: ConversionGoalFilter | null,
- integrationFilter: IntegrationFilter
+ integrationFilter: IntegrationFilter,
+ shouldFilterTestAccounts: boolean
) => QueryTile
marketingChartTile: (
compareFilter: CompareFilter,
@@ -142,7 +144,8 @@ export interface marketingAnalyticsTilesLogicMeta {
defaultColumns: string[],
compareFilter: CompareFilter,
integrationFilter: IntegrationFilter,
- drillDownLevel: MarketingAnalyticsDrillDownLevel
+ drillDownLevel: MarketingAnalyticsDrillDownLevel,
+ shouldFilterTestAccounts: boolean
) => DataTableNode | null
}
}
@@ -168,6 +171,7 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
'chartDisplayType',
'tileColumnSelection',
'integrationFilter',
+ 'shouldFilterTestAccounts',
'drillDownLevel',
'baseCurrency',
],
@@ -181,12 +185,19 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
// One selector per tile so an input change only invalidates the tile that uses
// it — entries keep identity in `tiles` below, so `dataNodeLogic` doesn't refetch.
overviewTile: [
- (s) => [s.compareFilter, s.dateFilter, s.draftConversionGoal, s.integrationFilter],
+ (s) => [
+ s.compareFilter,
+ s.dateFilter,
+ s.draftConversionGoal,
+ s.integrationFilter,
+ s.shouldFilterTestAccounts,
+ ],
(
compareFilter: CompareFilter | null,
dateFilter: { dateFrom: string | null; dateTo: string | null; interval: IntervalType },
draftConversionGoal: ConversionGoalFilter | null,
- integrationFilter: IntegrationFilter
+ integrationFilter: IntegrationFilter,
+ shouldFilterTestAccounts: boolean
): QueryTile => ({
kind: 'query',
tileId: TileId.MARKETING_OVERVIEW,
@@ -202,6 +213,7 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
},
compareFilter: compareFilter || undefined,
properties: [],
+ filterTestAccounts: shouldFilterTestAccounts,
draftConversionGoal: draftConversionGoal || undefined,
integrationFilter: integrationFilter,
tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,
@@ -392,6 +404,7 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
s.compareFilter,
s.integrationFilter,
s.drillDownLevel,
+ s.shouldFilterTestAccounts,
],
(
loading: boolean,
@@ -401,7 +414,8 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
defaultColumns: string[],
compareFilter: CompareFilter,
integrationFilter: IntegrationFilter,
- drillDownLevel: MarketingAnalyticsDrillDownLevel
+ drillDownLevel: MarketingAnalyticsDrillDownLevel,
+ shouldFilterTestAccounts: boolean
): DataTableNode | null => {
if (loading) {
return null
@@ -481,6 +495,7 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
date_to: dateFilter.dateTo,
},
properties: [],
+ filterTestAccounts: shouldFilterTestAccounts,
draftConversionGoal: draftConversionGoal,
limit: 200,
orderBy,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts
index e2c948159d0d..650038534e02 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts
@@ -79,6 +79,7 @@ export interface marketingAttributionLogicValues {
dateTo: string | null
interval: IntervalType
} // marketingAnalyticsLogic
+ shouldFilterTestAccounts: boolean // marketingAnalyticsLogic
attribution_window_days: number // marketingAnalyticsSettingsLogic
conversion_goals: ConversionGoalFilter[] // marketingAnalyticsSettingsLogic
allowMultipleConversionsPerVisitor: boolean | null
@@ -147,7 +148,8 @@ export interface marketingAttributionLogicMeta {
dateFrom: string | null
dateTo: string | null
interval: IntervalType
- }
+ },
+ shouldFilterTestAccounts: boolean
) => MarketingAnalyticsAttributionQuery | null
pathsQuery: (
query: MarketingAnalyticsAttributionQuery | null,
@@ -170,7 +172,7 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
// The tab renders under the scene's shared filter bar, so it reuses that date range rather
// than owning a second date control the user would have to keep in sync.
marketingAnalyticsLogic,
- ['dateFilter'],
+ ['dateFilter', 'shouldFilterTestAccounts'],
marketingAnalyticsSettingsLogic,
['conversion_goals', 'attribution_window_days'],
],
@@ -272,6 +274,7 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
s.lookbackWindowDays,
s.allowMultipleConversionsPerVisitor,
s.dateFilter,
+ s.shouldFilterTestAccounts,
],
(
selectedGoalId: string | null,
@@ -280,7 +283,8 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
excludeUnattributed: boolean,
lookbackWindowDays: number | null,
allowMultipleConversionsPerVisitor: boolean | null,
- dateFilter: DateFilter
+ dateFilter: DateFilter,
+ shouldFilterTestAccounts: boolean
): MarketingAnalyticsAttributionQuery | null => {
if (!selectedGoalId) {
return null
@@ -297,6 +301,7 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
...(allowMultipleConversionsPerVisitor !== null ? { allowMultipleConversionsPerVisitor } : {}),
limit: ATTRIBUTION_ROW_LIMIT,
properties: [],
+ filterTestAccounts: shouldFilterTestAccounts,
}
},
],
@@ -329,6 +334,7 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([
: {}),
limit: PATHS_ROW_LIMIT,
properties: [],
+ filterTestAccounts: query.filterTestAccounts,
}
},
],
diff --git a/posthog/api/project.py b/posthog/api/project.py
index bcf20d264ac9..588410b76f01 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -202,6 +202,7 @@ def update_team_marketing_analytics_config(team: Team, validated_data: dict[str,
),
"attribution_window_days": team.marketing_analytics_config.attribution_window_days,
"attribution_mode": team.marketing_analytics_config.attribution_mode,
+ "filter_test_accounts": team.marketing_analytics_config.filter_test_accounts,
}
marketing_serializer = TeamMarketingAnalyticsConfigSerializer(
@@ -219,6 +220,7 @@ def update_team_marketing_analytics_config(team: Team, validated_data: dict[str,
"sources_map": validated_data.get("sources_map", {}),
"attribution_window_days": validated_data.get("attribution_window_days"),
"attribution_mode": validated_data.get("attribution_mode"),
+ "filter_test_accounts": validated_data.get("filter_test_accounts"),
}
capture_team_config_diff(team, "marketing_analytics_config", old_config, new_config, context=context)
diff --git a/posthog/api/team.py b/posthog/api/team.py
index c9c45b48512d..dfe4a2df0700 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -746,6 +746,12 @@ class TeamMarketingAnalyticsConfigSerializer(serializers.ModelSerializer, UserAc
required=False,
help_text="How credit is split across touchpoints when a person saw several campaigns before converting.",
)
+ filter_test_accounts = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Whether marketing analytics drops traffic matching the project's test-account filters. Off by default."
+ ),
+ )
campaign_name_mappings = MarketingAnalyticsCampaignNameMappingsField(
required=False,
help_text=(
@@ -775,6 +781,7 @@ class TeamMarketingAnalyticsConfigSerializer(serializers.ModelSerializer, UserAc
"conversion_goals",
"attribution_window_days",
"attribution_mode",
+ "filter_test_accounts",
"campaign_name_mappings",
"custom_source_mappings",
"campaign_field_preferences",
@@ -818,6 +825,9 @@ class TeamMarketingAnalyticsConfigSerializer(serializers.ModelSerializer, UserAc
if "attribution_mode" in validated_data:
instance.attribution_mode = validated_data["attribution_mode"]
+ if "filter_test_accounts" in validated_data:
+ instance.filter_test_accounts = validated_data["filter_test_accounts"]
+
if "campaign_name_mappings" in validated_data:
instance.campaign_name_mappings = validated_data["campaign_name_mappings"]
@@ -2143,6 +2153,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
),
"attribution_window_days": instance.marketing_analytics_config.attribution_window_days,
"attribution_mode": instance.marketing_analytics_config.attribution_mode,
+ "filter_test_accounts": instance.marketing_analytics_config.filter_test_accounts,
# Add other fields as they're added to the model
# "conversion_goals": instance.marketing_analytics_config.conversion_goals.copy() if instance.marketing_analytics_config.conversion_goals else [],
}
@@ -2163,6 +2174,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
"sources_map": validated_data.get("sources_map", {}),
"attribution_window_days": validated_data.get("attribution_window_days"),
"attribution_mode": validated_data.get("attribution_mode"),
+ "filter_test_accounts": validated_data.get("filter_test_accounts"),
# Add other fields as they're added to the model
# "conversion_goals": validated_data.get("conversion_goals", []),
}
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 4384c14b970e..f74f6f23f2c8 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -409,6 +409,7 @@ class TestQueryRunner(BaseTest):
"custom_source_mappings": {},
"campaign_field_preferences": {},
"costs_dedup_v2": False,
+ "filter_test_accounts": False,
"sources_map": {
"01977f7b-7f29-0000-a028-7275d1a767a4": {
"cost": "cost",
@@ -494,7 +495,7 @@ class TestQueryRunner(BaseTest):
runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)
cache_key = runner.get_cache_key()
- assert cache_key == "cache_42_c034c5f92d23cb2399f6c087694175b7e6950739ea60b0ec7cf2665d2ae82d50"
+ assert cache_key == "cache_42_13361de10d0c3c79451b288eb57ca1147331e86a8b8e63a0a815adf5a2d7bcbb"
@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_cache_key_runner_subclass(self):
@@ -509,7 +510,7 @@ class TestQueryRunner(BaseTest):
runner = TestSubclassQueryRunner(query={"some_attr": "bla"}, team=team)
cache_key = runner.get_cache_key()
- assert cache_key == "cache_42_916dab3186430d61979f436fca08d88c23559c270894cf8c96a19e2c18a8ae4f"
+ assert cache_key == "cache_42_9dcfced89edfbfcd1e0fd380380c7a5e4a9957386fc22172c1b83548a9af6d02"
@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_cache_key_different_timezone(self):
@@ -521,7 +522,7 @@ class TestQueryRunner(BaseTest):
runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)
cache_key = runner.get_cache_key()
- assert cache_key == "cache_42_032f9a7be3ea1fc4451f1e5a77841bb79f9b9ef65ad949f251ee0e68e8ee5fb0"
+ assert cache_key == "cache_42_580a20072d3930f66666356574843255ba9418ff58cc0fc92d019bf8bf1cf972"
def test_cache_payload_omits_object_restrictions_when_unrestricted(self):
TestQueryRunner = self.setup_test_query_runner_class()
diff --git a/posthog/migrations/1343_teammarketinganalyticsconfig_filter_test_accounts.py b/posthog/migrations/1343_teammarketinganalyticsconfig_filter_test_accounts.py
new file mode 100644
index 000000000000..b72d3ab584f8
--- /dev/null
+++ b/posthog/migrations/1343_teammarketinganalyticsconfig_filter_test_accounts.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.17 on 2026-09-07 16:53
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1342_drop_cimd_blocklist_table"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teammarketinganalyticsconfig",
+ name="filter_test_accounts",
+ field=models.BooleanField(
+ db_default=False,
+ default=False,
+ help_text="Whether marketing analytics queries drop traffic matching the project's test-account filters",
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index e30a1468d400..73243bde303d 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1342_drop_cimd_blocklist_table
+1343_teammarketinganalyticsconfig_filter_test_accounts
diff --git a/posthog/models/team/team_marketing_analytics_config.py b/posthog/models/team/team_marketing_analytics_config.py
index e90cc5a5fddd..777a831639bf 100644
--- a/posthog/models/team/team_marketing_analytics_config.py
+++ b/posthog/models/team/team_marketing_analytics_config.py
@@ -299,6 +299,19 @@ class TeamMarketingAnalyticsConfig(models.Model):
"admin",
)
+ # Server-side because the Dagster warmer reads it: the test-account filter is baked into the
+ # precompute's insert query, so a job warmed for the wrong variant is never read.
+ filter_test_accounts = field_access_control(
+ models.BooleanField(
+ default=False,
+ db_default=False,
+ null=False,
+ help_text="Whether marketing analytics queries drop traffic matching the project's test-account filters",
+ ),
+ "project",
+ "admin",
+ )
+
# Mangled fields incoming:
# Because we want to validate the schema for these fields, we'll have mangled DB fields/columns
# that are then wrapped by schema-validation getters/setters
@@ -476,6 +489,7 @@ class TeamMarketingAnalyticsConfig(models.Model):
"sources_map": self.sources_map,
"attribution_window_days": self.attribution_window_days,
"attribution_mode": self.attribution_mode,
+ "filter_test_accounts": self.filter_test_accounts,
"campaign_name_mappings": self.campaign_name_mappings,
"custom_source_mappings": self.custom_source_mappings,
"campaign_field_preferences": self.campaign_field_preferences,
diff --git a/posthog/schema.py b/posthog/schema.py
index e28b0d65aa3d..95d5b2a16951 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -27378,6 +27378,7 @@ class MarketingAnalyticsConfig(BaseModel):
campaign_name_mappings: dict[str, dict[str, list[str]]] | None = None
conversion_goals: list[ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3] | None = None
custom_source_mappings: dict[str, list[str]] | None = None
+ filter_test_accounts: bool | None = None
sources_map: dict[str, SourceMap] | None = None
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
index 2b85326be6b6..e41931ff564d 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_base.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
@@ -224,6 +224,7 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
exprs=[
self.conversion_condition,
*self._get_where_conditions(date_range, date_field="events.timestamp"),
+ *self._test_account_conditions(),
]
),
group_by=[ast.Field(chain=["events", "person_id"])],
@@ -414,6 +415,9 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
),
]
),
+ # Outside the OR on purpose. Internal traffic is internal on both arms, and putting
+ # this inside each branch would say the same thing twice.
+ *self._test_account_conditions(),
]
),
group_by=[ast.Field(chain=["events", "person_id"])],
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
index b8bdf42f5f77..9575619e0c60 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
@@ -117,6 +117,7 @@ class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[Market
exprs=[
self._touchpoint_condition(),
*self._lookback_date_conditions(date_range),
+ *self._test_account_conditions(),
]
),
group_by=[ast.Field(chain=[_BREAKDOWN_VALUE])],
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 181a4f77647f..2a2c2a386f79 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -29,7 +29,10 @@ from posthog.hogql.timings import HogQLTimings
from posthog.dataclasses import frozen
from posthog.models import PropertyDefinition, Team, User
-from products.access_control.backend.property_access_control import get_restricted_property_names
+from products.access_control.backend.property_access_control import (
+ get_restricted_properties_for_team,
+ get_restricted_property_names,
+)
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationResult,
LazyComputationTable,
@@ -50,7 +53,7 @@ from .conversion_goal_conditions import (
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
+from .utils import build_source_normalization_expr, test_account_conditions
# Freshness windows for the precompute read path. The Dagster warmer
# (products/marketing_analytics/dags/marketing_precompute.py) MUST drive ensure_precomputed with this
@@ -153,12 +156,19 @@ def build_pageview_touchpoint_condition(source_field: str) -> ast.Expr:
return ast.Or(exprs=[not_empty(source_field), *[not_empty(p) for p in CLICK_ID_PROPERTIES]])
-def build_touchpoints_precompute_query() -> ast.SelectQuery:
- """Config-agnostic touchpoint precompute: one row per UTM-tagged pageview, independent of any
+def build_touchpoints_precompute_query(
+ team: Optional[Team] = None, filter_test_accounts: bool = False
+) -> ast.SelectQuery:
+ """Goal-agnostic touchpoint precompute: one row per UTM-tagged pageview, independent of any
goal, attribution mode or window. Every attribution query reuses the same materialized rows
(identical query hash → one shared lazy-computation job per team); attribution happens at read
time. Columns are aliased to the marketing_touchpoints_preaggregated schema — the lazy framework
prepends team_id/job_id and appends expires_at, and resolves the time_window placeholders per job.
+
+ Test-account filtering is the one thing that splits that shared job in two. It has to be baked in
+ rather than applied on read, because the framework keys the job on this query's AST, and the rows
+ it materializes would otherwise already have the internal traffic in them. A team that never turns
+ the toggle on keeps exactly one job, since the arguments then add nothing to the query.
"""
def _prop_to_string(event_property: str) -> ast.Expr:
@@ -202,6 +212,7 @@ def build_touchpoints_precompute_query() -> ast.SelectQuery:
right=ast.Placeholder(expr=ast.Field(chain=["time_window_max"])),
),
build_pageview_touchpoint_condition("utm_source"),
+ *(test_account_conditions(team, filter_test_accounts) if team else []),
]
),
)
@@ -219,9 +230,10 @@ class SharedTouchpointsPrecompute:
the lock.
"""
- def __init__(self, team: Team, config: MarketingAnalyticsConfig) -> None:
+ def __init__(self, team: Team, config: MarketingAnalyticsConfig, filter_test_accounts: bool = False) -> None:
self._team = team
self._config = config
+ self._filter_test_accounts = filter_test_accounts
self._lock = threading.Lock()
self._result: Optional[LazyComputationResult] = None
self._range: Optional[tuple[datetime, datetime]] = None
@@ -233,7 +245,7 @@ class SharedTouchpointsPrecompute:
self._range = (date_from, date_to)
self._result = marketing_ensure_precomputed(
team=self._team,
- insert_query=build_touchpoints_precompute_query(),
+ insert_query=build_touchpoints_precompute_query(self._team, self._filter_test_accounts),
time_range_start=date_from - window,
time_range_end=date_to,
ttl_seconds=PRECOMPUTE_TTL_SECONDS,
@@ -287,6 +299,8 @@ class ConversionGoalProcessor:
# Set when this goal's precompute was served from expired-within-grace rows instead of rebuilt. Read
# by the runner after the goal pool joins, to schedule one background revalidation for the read.
precompute_stale: bool = False
+ # Passed down by the runner, since a processor has no query of its own to read it from.
+ filter_test_accounts: bool = False
_UTM_LEVEL_FIELD_MAP: ClassVar[dict[MarketingAnalyticsDrillDownLevel, str]] = {
MarketingAnalyticsDrillDownLevel.MEDIUM: "medium",
@@ -577,8 +591,23 @@ class ConversionGoalProcessor:
# per-user masking. When any is restricted for THIS user, fall back to the masked direct path.
if self._precompute_properties_restricted_for_user():
return False
+ if self._test_account_filters_restricted_for_user():
+ return False
return True
+ def _test_account_filters_restricted_for_user(self) -> bool:
+ """True when dropping test accounts inside the precompute could leak a property this user can't read.
+
+ The precompute evaluates the rules with no user attached, so they compare against real values
+ rather than masked ones, and toggling the filter would report how many rows match.
+
+ Coarse on purpose: it asks whether the user has any restriction, not which properties the rules
+ name, since reading those means walking arbitrary filter trees where a miss fails open.
+ """
+ if not self.filter_test_accounts or not self.team.test_account_filters:
+ return False
+ return bool(get_restricted_properties_for_team(team_id=self.team.pk, user=self.user))
+
def _precompute_materialized_event_properties(self) -> set[str]:
"""Event property names the precompute path resolves into scalar columns of the preagg table."""
# $session_id is materialized into the session_id column (see build_conversions_precompute_query),
@@ -659,6 +688,10 @@ class ConversionGoalProcessor:
),
]
where_exprs = add_conversion_goal_property_filters(where_exprs, self.goal, self.team)
+ # Baked into the precompute rather than applied when it is read. The lazy framework hashes this
+ # query's AST for the job key, so a filtered read gets its own materialization instead of
+ # reusing the unfiltered team's rows.
+ where_exprs.extend(test_account_conditions(self.team, self.filter_test_accounts))
return ast.SelectQuery(
select=select_columns,
@@ -686,7 +719,9 @@ class ConversionGoalProcessor:
# Touchpoints are config-agnostic, so a multi-goal read shares one materialization. Without a
# shared handle each goal materializes the same window itself, which is what a standalone
# caller gets.
- shared_touchpoints = touchpoints or SharedTouchpointsPrecompute(self.team, self.config)
+ shared_touchpoints = touchpoints or SharedTouchpointsPrecompute(
+ self.team, self.config, self.filter_test_accounts
+ )
with self.timings.measure("ma_ensure_touchpoints"):
touchpoints_result = shared_touchpoints.get(date_from, date_to)
if not touchpoints_result.ready:
@@ -1094,8 +1129,12 @@ class ConversionGoalProcessor:
# For general queries, apply date conditions to all events
event_filter = self._build_general_event_filter(date_conditions)
- # Combine all conditions
- all_conditions = [event_filter, *non_event_conditions]
+ # Test accounts sit outside `event_filter`, which is an OR over the conversion and pageview arms.
+ all_conditions = [
+ event_filter,
+ *non_event_conditions,
+ *test_account_conditions(self.team, self.filter_test_accounts),
+ ]
return ast.And(exprs=all_conditions) if len(all_conditions) > 1 else all_conditions[0]
def _build_action_event_filter(
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 b5f38cdd1893..25770949b093 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py
@@ -71,10 +71,11 @@ class ConversionGoalsAggregator:
if not self.processors:
raise ValueError("Cannot create unified CTE without conversion goal processors")
- # The touchpoints precompute is config-agnostic: every goal drives the exact same
- # ensure_precomputed for the same window. Share one handle so it is materialized once for the
- # whole read instead of once per goal.
- touchpoints = SharedTouchpointsPrecompute(self.processors[0].team, self.config)
+ # Goal-agnostic, so one handle materializes it once per read rather than once per goal. Reading
+ # processor 0 for the flag is safe: every processor in a read came from the same query.
+ touchpoints = SharedTouchpointsPrecompute(
+ self.processors[0].team, self.config, self.processors[0].filter_test_accounts
+ )
# Step 1: Generate individual conversion goal queries, parallelised across goals
# so ensure_precomputed's PG+Redis+ClickHouse round-trips collapse to max(overhead).
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 024470ee94ce..385955661498 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
@@ -60,7 +60,7 @@ from .adapters.factory import MarketingSourceFactory
from .conversion_goal_processor import ConversionGoalProcessor, goal_sums_a_property
from .conversion_goals_aggregator import ConversionGoalsAggregator
from .marketing_analytics_config import MarketingAnalyticsConfig
-from .utils import build_source_normalization_expr, convert_team_conversion_goals_to_objects
+from .utils import build_source_normalization_expr, convert_team_conversion_goals_to_objects, test_account_conditions
@dataclass(frozen=True)
@@ -883,10 +883,28 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
# Goals are built in parallel and HogQLTimings is not thread safe, so hand each
# processor its own clone. Merged back in _build_complete_query_ast once joined.
timings=self.timings.clone_for_subquery(index),
+ filter_test_accounts=self.filter_test_accounts,
)
processors.append(processor)
return processors
+ @property
+ def filter_test_accounts(self) -> bool:
+ """The query decides, and the project's setting answers when it says nothing.
+
+ The setting is also what the Dagster warmer reads. A read that fell back to a different value
+ would ask for a job the warmer never builds, and pay the materialization inline.
+ """
+ requested = getattr(self.query, "filterTestAccounts", None)
+ if requested is None:
+ return self.team.marketing_analytics_config.filter_test_accounts
+ return bool(requested)
+
+ def _test_account_conditions(self) -> list[ast.Expr]:
+ """Applied at every `events` scan, never at a warehouse one. Test-account filters are written
+ against event and person properties, which a cost table does not have."""
+ return test_account_conditions(self.team, self.filter_test_accounts)
+
def _get_where_conditions(
self,
date_range: QueryDateRange,
@@ -1223,6 +1241,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
date_field="events.timestamp",
use_date_not_datetime=False,
)
+ where_conditions.extend(self._test_account_conditions())
# Add conversion goal specific conditions
if processor.goal.kind == "EventsNode":
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
index c024b92f0b8b..3f2808f56cd5 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
@@ -28,6 +28,7 @@ from posthog.models.utils import uuid7
from posthog.test.persons import create_person
from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
MarketingAnalyticsAttributionQueryRunner,
)
@@ -129,6 +130,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
date_to: str = "2023-01-31",
lookback_days: int | None = None,
allow_multiple_conversions: bool | None = None,
+ filter_test_accounts: bool | None = False,
):
flush_persons_and_events()
query = MarketingAnalyticsAttributionQuery(
@@ -139,6 +141,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
excludeUnattributed=exclude_unattributed,
lookbackWindowDays=lookback_days,
allowMultipleConversionsPerVisitor=allow_multiple_conversions,
+ filterTestAccounts=filter_test_accounts,
properties=[],
)
return MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).calculate()
@@ -148,6 +151,57 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
"""{breakdown value: {model: conversions}} — the shape every weight assertion needs."""
return {row.breakdownValue: {cell.model: cell.conversions for cell in row.models} for row in response.results}
+ @parameterized.expand(
+ [
+ ("query says off", False, False, 2.0),
+ ("query says on", True, False, 1.0),
+ # A query that says nothing takes the project's answer, which is also the one the warmer
+ # materializes. Disagreeing here would read a job nothing warms.
+ ("query silent, project on", None, True, 1.0),
+ ]
+ )
+ def test_filter_test_accounts_drops_internal_traffic(
+ self, _name, filter_test_accounts, project_setting, expected_conversions
+ ):
+ # The conversion count catches either arm being missed: filtering only the conversion scan leaves
+ # the internal person's touchpoints diluting the weights, only the touchpoint scan leaves their
+ # conversion unattributed.
+ self.team.test_account_filters = [
+ {"key": "email", "value": "@internal.example.com", "operator": "not_icontains", "type": "person"}
+ ]
+ self.team.save()
+ self.team.marketing_analytics_config.filter_test_accounts = project_setting
+ self.team.marketing_analytics_config.save()
+ create_person(team=self.team, distinct_ids=["customer"], properties={"email": "[email protected]"})
+ create_person(team=self.team, distinct_ids=["staff"], properties={"email": "[email protected]"})
+ for distinct_id in ("customer", "staff"):
+ self._session(distinct_id, "2023-01-10T12:00:00Z", utm_source="google")
+ self._conversion(distinct_id, "2023-01-11T12:00:00Z")
+
+ rows = self._by_breakdown(
+ self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, filter_test_accounts=filter_test_accounts)
+ )
+
+ self.assertEqual(rows["google"][AttributionMode.LAST_TOUCH], expected_conversions)
+
+ def test_a_cohort_test_account_filter_does_not_make_the_query_ambiguous(self):
+ # A cohort filter resolves to a bare `person_id`, and the touchpoint scan joins the converters
+ # subquery, which has one too. Unqualified, that combination fails to resolve at all.
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="Internal users",
+ groups=[{"properties": [{"key": "email", "value": "@internal.example.com", "type": "person"}]}],
+ )
+ self.team.test_account_filters = [{"key": "id", "type": "cohort", "value": cohort.pk, "operator": "in"}]
+ self.team.save()
+ create_person(team=self.team, distinct_ids=["customer"], properties={"email": "[email protected]"})
+ self._session("customer", "2023-01-10T12:00:00Z", utm_source="google")
+ self._conversion("customer", "2023-01-11T12:00:00Z")
+
+ response = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, filter_test_accounts=True)
+
+ self.assertIsNotNone(response.results)
+
def test_visitors_include_lookback_arrivals_that_can_earn_credit(self):
# Credit looks back attribution_window_days before the date range, so reach must too: a visitor
# whose only touch predates the range used to be missing from the denominator, which reported
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
index c3d51b1f0a68..6cea02ee9ef5 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
@@ -21,6 +21,8 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.test.utils import pretty_print_in_tests
+from posthog.models import PropertyDefinition
+
from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import ConversionGoalProcessor
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
@@ -58,12 +60,13 @@ class TestConversionGoalProcessorRefactor(BaseTest):
CLASS_DATA_LEVEL_SETUP = False
snapshot: Any
- def _processor(self, **goal_overrides) -> ConversionGoalProcessor:
+ def _processor(self, filter_test_accounts: bool = False, **goal_overrides) -> ConversionGoalProcessor:
return ConversionGoalProcessor(
goal=_make_event_goal(**goal_overrides),
index=0,
team=self.team,
config=MarketingAnalyticsConfig(),
+ filter_test_accounts=filter_test_accounts,
)
def _print_sql(self, node: ast.SelectQuery) -> str:
@@ -142,6 +145,36 @@ class TestConversionGoalProcessorRefactor(BaseTest):
with patch(target, return_value={restricted_property}):
assert processor._should_use_precompute(date_from, date_to) is False
+ @parameterized.expand(
+ [
+ ("filtering_and_restricted", True, {("email", PropertyDefinition.Type.PERSON)}, False),
+ # Nothing is masked for this user, so evaluating the rules userless reveals nothing.
+ ("filtering_but_unrestricted", True, set(), True),
+ # The rules never reach the precompute, so there is nothing to leak through.
+ ("restricted_but_not_filtering", False, {("email", PropertyDefinition.Type.PERSON)}, True),
+ ]
+ )
+ def test_precompute_skipped_when_dropping_test_accounts_could_leak_a_restricted_property(
+ self, _name: str, filter_test_accounts: bool, restricted: set, expected: bool
+ ):
+ # The precompute evaluates the team's test-account rules with no user attached, so a rule reading
+ # a property this user can't see is compared against real values. Without this guard, toggling the
+ # filter and diffing the aggregates reports how many rows match it. The person-typed property here
+ # is the case the existing guard misses entirely: it only inspects event properties.
+ self.team.test_account_filters = [
+ {"key": "email", "value": "@internal.example.com", "operator": "not_icontains", "type": "person"}
+ ]
+ self.team.save()
+ processor = self._processor(filter_test_accounts=filter_test_accounts)
+ processor.config.conversion_goal_precomputation_enabled = True
+ target = "products.marketing_analytics.backend.hogql_queries.conversion_goal_processor.get_restricted_properties_for_team"
+
+ with patch(target, return_value=restricted):
+ assert (
+ processor._should_use_precompute(datetime(2025, 1, 1, tzinfo=UTC), datetime(2025, 1, 31, tzinfo=UTC))
+ is expected
+ )
+
def test_tracked_fields_match_touchpoints_table_schema(self):
from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import (
MARKETING_TOUCHPOINTS_TRACKED_FIELD_NAMES,
diff --git a/products/marketing_analytics/backend/hogql_queries/utils.py b/products/marketing_analytics/backend/hogql_queries/utils.py
index dea06a0c4a94..bf3dd2e88d24 100644
--- a/products/marketing_analytics/backend/hogql_queries/utils.py
+++ b/products/marketing_analytics/backend/hogql_queries/utils.py
@@ -8,10 +8,39 @@ from pydantic import BaseModel
from posthog.schema import ConversionGoalFilter1, ConversionGoalFilter2, ConversionGoalFilter3, NodeKind
from posthog.hogql import ast
+from posthog.hogql.property import property_to_expr
+from posthog.hogql.visitor import CloningVisitor
+
+from posthog.models.team.team import Team
logger = structlog.get_logger(__name__)
+class _QualifyBarePersonId(CloningVisitor):
+ """Points a bare `person_id` at the events table.
+
+ A cohort filter emits one, which is ambiguous wherever the scan joins something that also has a
+ `person_id` — the converters join in the attribution CTEs is one such place.
+ """
+
+ def visit_field(self, node: ast.Field) -> ast.Field:
+ if node.chain == ["person_id"]:
+ return ast.Field(chain=["events", "person_id"])
+ return super().visit_field(node)
+
+
+def test_account_conditions(team: Team, enabled: bool) -> list[ast.Expr]:
+ """The team's test-account filters, for an `events` scan that opted into them.
+
+ Empty when the toggle is off, which keeps the query shape byte-identical: the lazy precompute hashes
+ the insert query's AST, so an unconditional wrapper would repoint every team at a cold job.
+ """
+ if not enabled or not team.test_account_filters:
+ return []
+ qualify = _QualifyBarePersonId()
+ return [qualify.visit(property_to_expr(prop, team)) for prop in team.test_account_filters]
+
+
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.
diff --git a/products/marketing_analytics/dags/marketing_precompute.py b/products/marketing_analytics/dags/marketing_precompute.py
index 19ba3a8e0147..bdddbc77adcd 100644
--- a/products/marketing_analytics/dags/marketing_precompute.py
+++ b/products/marketing_analytics/dags/marketing_precompute.py
@@ -194,14 +194,19 @@ def _ensure_chunks(
def _ensure_touchpoints_for_team(
context: dagster.OpExecutionContext, team: Team, start: datetime, end: datetime, chunk_days: int
) -> int:
- """Warm the config-agnostic touchpoints table over [start, end] (start already reaches back past the
+ """Warm the goal-agnostic touchpoints table over [start, end] (start already reaches back past the
attribution window). One warmed window serves every conversion goal / attribution mode.
+
+ Test-account filtering is the one thing that splits it: the filter is baked into the insert query,
+ which the framework hashes for the job key, so warming the wrong variant leaves every read to
+ materialize inline. The team's own setting is what the dashboard sends, so warm that one.
"""
+ filter_test_accounts = team.marketing_analytics_config.filter_test_accounts
return _ensure_chunks(
context,
team,
LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,
- build_touchpoints_precompute_query,
+ partial(build_touchpoints_precompute_query, team, filter_test_accounts),
PRECOMPUTE_TTL_SECONDS,
start,
end,
@@ -225,7 +230,14 @@ def _ensure_conversions_for_team(
goals_warmed = 0
failures = 0
for index, goal in enumerate(goals):
- processor = ConversionGoalProcessor(goal=goal, index=index, team=team, config=config, user=None)
+ processor = ConversionGoalProcessor(
+ goal=goal,
+ index=index,
+ team=team,
+ config=config,
+ user=None,
+ filter_test_accounts=team.marketing_analytics_config.filter_test_accounts,
+ )
if not processor.is_goal_precomputable():
continue
goals_warmed += 1
diff --git a/products/marketing_analytics/dags/tests/test_marketing_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_precompute.py
index c49b7e8da3ef..a8ab98713dfa 100644
--- a/products/marketing_analytics/dags/tests/test_marketing_precompute.py
+++ b/products/marketing_analytics/dags/tests/test_marketing_precompute.py
@@ -13,6 +13,12 @@ from posthog.dags.common import chunk_ranges
from posthog.models import Organization, Team
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationTable
+from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import (
+ ConversionGoalProcessor,
+ build_touchpoints_precompute_query,
+)
+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
+from products.marketing_analytics.backend.hogql_queries.utils import convert_team_conversion_goals_to_objects
from products.marketing_analytics.dags.marketing_precompute import (
COST_MATERIALIZATION_GRAINS,
DEFAULT_ROLLOUT_TEAM_IDS,
@@ -174,6 +180,43 @@ class TestConversionWarming(APIBaseTest):
assert LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED in tables
assert LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED in tables
+ @patch(_ENSURE, new_callable=_ready_mock)
+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)
+ def test_warms_the_filtered_variant_a_team_that_drops_test_accounts_reads(self, ensure_mock):
+ # The framework keys each job on its insert query's AST, so warming the unfiltered variant for a
+ # team that reads the filtered one leaves every read to materialize inline.
+ team = self._make_team("A", goals=[_PRECOMPUTABLE_GOAL])
+ team.test_account_filters = [{"key": "$host", "value": "localhost", "operator": "exact", "type": "event"}]
+ team.save()
+ team.marketing_analytics_config.filter_test_accounts = True
+ team.marketing_analytics_config.save()
+
+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):
+ ensure_marketing_precompute_op(dagster.build_op_context())
+
+ warmed = {
+ call.kwargs["table"]: call.kwargs["insert_query"]
+ for call in ensure_mock.call_args_list
+ if call.kwargs["table"]
+ in (
+ LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,
+ LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,
+ )
+ }
+ expected_touchpoints = build_touchpoints_precompute_query(team, True)
+ assert repr(warmed[LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED]) == repr(expected_touchpoints)
+
+ goal = convert_team_conversion_goals_to_objects(team.marketing_analytics_config.conversion_goals, team.pk)[0]
+ expected_conversions = ConversionGoalProcessor(
+ goal=goal,
+ index=0,
+ team=team,
+ config=MarketingAnalyticsConfig.from_team(team),
+ user=None,
+ filter_test_accounts=True,
+ ).build_conversions_precompute_query()
+ assert repr(warmed[LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED]) == repr(expected_conversions)
+
@patch(_ENSURE, new_callable=_ready_mock)
@patch(_SINGLE_CHUNK, _BIG_CHUNK)
def test_only_precomputable_goals_warm_conversions(self, ensure_mock):
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ed79603f60f9..a17f2f29461c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -65967,6 +65967,8 @@ export namespace Schemas {
* * `time_decay` - Time Decay
* * `position_based` - Position Based */
attribution_mode?: AttributionModeEnum;
+ /** Whether marketing analytics drops traffic matching the project's test-account filters. Off by default. */
+ filter_test_accounts?: boolean;
/** Manual campaign name aliases, keyed by integration type then by canonical campaign name, with the list of names that should be folded into it. Applied before automatic matching. */
campaign_name_mappings?: MarketingAnalyticsCampaignNameMappings;
/** Custom UTM source values to fold into an integration, keyed by integration type. A UTM source can only belong to one integration. */
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index 36d00b88a7ec..f9457f5d4990 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -2400,6 +2400,12 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod
.describe(
'How credit is split across touchpoints when a person saw several campaigns before converting.\n\n\* `first_touch` - First Touch\n\* `last_touch` - Last Touch\n\* `linear` - Linear\n\* `time_decay` - Time Decay\n\* `position_based` - Position Based'
),
+ filter_test_accounts: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Whether marketing analytics drops traffic matching the project's test-account filters. Off by default."
+ ),
campaign_name_mappings: zod
.record(zod.string(), zod.record(zod.string(), zod.array(zod.string())))
.describe('Mapping of integration type to canonical campaign name to the aliases folded into it.')
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
index ac6fdd78aa69..30fa8f00273f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
@@ -3642,6 +3642,10 @@
},
"type": "object"
},
+ "filter_test_accounts": {
+ "description": "Whether marketing analytics drops traffic matching the project's test-account filters. Off by default.",
+ "type": "boolean"
+ },
"sources_map": {
"additionalProperties": {
"properties": {