:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): filter out test users in cohorts and persons list (#73736)
Arno Hillen954ab27e10b2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a99cf33edac1..2523fb551d87 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6617,15 +6617,15 @@ snapshots:scenes-app-people-cohorts--cohort-edit-dynamic--dark:hash: v1.k794b7964.29528fe9c6743a11a17bf839e152d3ed0d45a571dc704b0fbeafc0e469213d61.u8BPurAlJ3JdThf5TpcoGw-6KWkWwHlFETCXvt2Y6usscenes-app-people-cohorts--cohort-edit-dynamic--light:- hash: v1.k794b7964.68a8f57efed3143da4feec04312c071aa8d6bb92e475945589b843ad881b69e9.v7QDELbVd7iBn4lZs6VDsX1slTQVBZb3w8z6sO3BNJ4+ hash: v1.k794b7964.af17394f32809d5fb7e65e8f3298be02447f4481ff41645350514a7f16ac8545.f1AXZKpaB9lZ6zPTIYL6gMPVqdUbN_T7QdgB-doywX8scenes-app-people-cohorts--cohort-edit-static--dark:hash: v1.k794b7964.02d0747e4c10c736c348f8ec64e6c40f7613e9b3c750802c707e807f8d513199.uayJO_46qM2XEfrPzVhPHBxuAi1bH7wTaAc41c-PngYscenes-app-people-cohorts--cohort-edit-static--light:hash: v1.k794b7964.ccfdd12041c23093f9dfdea3d74a8be8672f017b838ca9171c9713eb49418899.NFNZNNezQtqlEbBSbXoGbIKJQllVOfqNMGJgCYdKRGcscenes-app-people-cohorts--cohort-new--dark:- hash: v1.k794b7964.ad06461fec9e86b589fdd27f1dc1ea74c673c06dd2945d7d95d96fd6db03bc60.hilKwZIabJOnPepZU0WRMVrsNXbq7LLFr-2wmF4g7OM+ hash: v1.k794b7964.0c0b9da85f85dac4c299d0527725f192c0c07d204e28462a64736552aaba735b.aX2s9DQu-pQIZHJDYBeZXL9lyni7w6PSMh3u3b_cvhAscenes-app-people-cohorts--cohort-new--light:- hash: v1.k794b7964.d1c3a92efe91c712053a6902aba48fb73c4cea5d60cf859b3ac8e77bf8059858.YtZMc4vBSnh9Bw6VkBOGXTefiEiqMVkE8NEE2RuMAZE+ hash: v1.k794b7964.b7e34e37161bbc571400f8c8e4cf210f1e8e08a901f0194b25700de2447b6544.if6FtZPEEaSX6nWtoSmOeZM_PNYQz7bFqj7123_mQjMscenes-app-people-cohorts--cohorts-empty--dark:hash: v1.k794b7964.036e2f8323a54221ffdfb2807d0c9df42ae3d0969d15912c7fa7c6f6b51691c0.A0HlqNJEUOMVyy81_QznYrkUeMiQ8Ch6HmU0HgIUA8Mscenes-app-people-cohorts--cohorts-empty--light:@@ -6663,13 +6663,13 @@ snapshots:scenes-app-people-person--person-not-found--light:hash: v1.k794b7964.a3a657862b2bd2cb2f1e0a795c2089816cd3a3add75d63f3c1d17c3dfaf99e58.7nKFbvFDTWKtPh8oT1khOtMFENiy8AKBKvg2bhR1z8kscenes-app-people-persons--persons--dark:- hash: v1.k794b7964.7dca6e6ef2fbbaf88a8643258ac08e5023bd4e029cd27bb5a8dd759d9eeeb874.82-2FT_JXe5lV6BgFjLOEHSpzpXz1AI9jNUbwFoW0TA+ hash: v1.k794b7964.bbcde823907d0a6561afe40e363d67f53cf9fc88a6bc3d7b8e303b78c465f089.CNT0CyRUG-yut-MJbs-By27E6VxqHPp3dsKxT0dQrN4scenes-app-people-persons--persons--light:- hash: v1.k794b7964.30f0cfd43969eea6f10f8e9d542aa97ce3011e6c45b33bf76b74839e6c3472f8.CdW2YRmHDkTVQIAphHjze_aPJ3ZMNK5tDUiE8p5V32Q+ hash: v1.k794b7964.ba8c5f8760919e5bc6a62d587599f9d18b1699177e1a553122ddef7bb1d1ba2f.1mP2Hl4Y9F_TTBdpLx0z2FWvDoEe8ttr3JOSP4XJoMgscenes-app-people-persons--persons-empty--dark:- hash: v1.k794b7964.018f90390ce1abe0b0f96d9963f54163d1abec92c37a71d057e08f288b4e3cc0.cfsa-xhzG6F4I-po54D1rW_xUUtV-5CvPh3HUEmqAFA+ hash: v1.k794b7964.eaa71c50ae2ed7a81333458b1174a80885e621c9f293de0367e2a4d65294b398.8uMKPXYZ943_ncEtmg592_sXacuRN3Fux9hJ4G1qcscscenes-app-people-persons--persons-empty--light:- hash: v1.k794b7964.6d33664880233181a1bdd548af368a71cfe902c955a8fd065c357405463dfee8._CXXkKx2YPfH59z1AtHnDabjXIrp6Osdk9uqTG9U3Mw+ hash: v1.k794b7964.10c9878a4b0790830b0e0074a903686b0576a2fa385833673d7ee4abe113c57d.f7bzPSLBvs3XksPwPMuXolugbN1cNkOf-fxikxTqlGAscenes-app-persons-modal--empty--dark:hash: v1.k794b7964.00a95f7411a59b96d96cd23b8f4da1eca9053e7c391a2c4db52f27526fc842d2.OhWCw6o84czmOJ-2Q_tWWo_OmFLiEf7hCAfs9UWltcoscenes-app-persons-modal--empty--light:diff --git a/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsx b/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsxindex 3d702ef24a98..9c3852b3b5b6 100644--- a/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsx+++ b/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsx@@ -6,24 +6,62 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { initKeaTests } from '~/test/init'-import { TestAccountFilterSwitch } from './TestAccountFiltersSwitch'+import { TestAccountFilterSwitch, getUnusedTestAccountFilterReason } from './TestAccountFiltersSwitch'-describe('TestAccountFilterSwitch — gear icon links to internal test filtering settings', () => {- beforeEach(() => {- initKeaTests()- featureFlagLogic.mount()- })+describe('TestAccountFilterSwitch', () => {+ describe('gear icon links to internal test filtering settings', () => {+ beforeEach(() => {+ initKeaTests()+ featureFlagLogic.mount()+ })++ afterEach(() => {+ cleanup()+ })++ it('navigates to the customization settings, scrolled to internal-user-filtering', () => {+ render(<TestAccountFilterSwitch checked={false} onChange={jest.fn()} />)- afterEach(() => {- cleanup()+ // The LemonSwitch itself has role="switch"; the gear is rendered as a link.+ // The router prepends a `/project/<id>` prefix to the href, so match the suffix.+ const gear = screen.getByRole('link')+ expect(gear.getAttribute('href')).toMatch(/\/settings\/environment-customization#internal-user-filtering$/)+ })})- it('navigates to the customization settings, scrolled to internal-user-filtering', () => {- render(<TestAccountFilterSwitch checked={false} onChange={jest.fn()} />)+ describe('getUnusedTestAccountFilterReason', () => {+ // Guards that the toggle isn't a silent no-op: it should report "unused" (a non-null reason,+ // which disables the switch) exactly when the team has filters but none apply to the surface.+ it.each([+ ['cohort surface, only event filters', [{ type: 'event' }], ['person'], true],+ ['cohort surface, only a cohort filter', [{ type: 'cohort' }], ['person'], true],+ [+ 'persons surface, only event + hogql filters',+ [{ type: 'event' }, { type: 'hogql' }],+ ['person', 'cohort'],+ true,+ ],+ ['cohort surface, a person filter applies', [{ type: 'person' }], ['person'], false],+ [+ 'cohort surface, at least one person filter among others',+ [{ type: 'event' }, { type: 'person' }],+ ['person'],+ false,+ ],+ ['persons surface, a cohort filter applies', [{ type: 'cohort' }], ['person', 'cohort'], false],+ ['no filters configured', [], ['person'], false],+ ])('%s', (_name, filters, applicableTypes, expectUnused) => {+ const reason = getUnusedTestAccountFilterReason(filters, applicableTypes)+ expect(reason !== null).toBe(expectUnused)+ })- // The LemonSwitch itself has role="switch"; the gear is rendered as a link.- // The router prepends a `/project/<id>` prefix to the href, so match the suffix.- const gear = screen.getByRole('link')- expect(gear.getAttribute('href')).toMatch(/\/settings\/environment-customization#internal-user-filtering$/)+ it('names the applicable filter types in the reason', () => {+ expect(getUnusedTestAccountFilterReason([{ type: 'event' }], ['person'])).toBe(+ 'Only person property filters from your internal and test account settings apply here.'+ )+ expect(getUnusedTestAccountFilterReason([{ type: 'event' }], ['person', 'cohort'])).toBe(+ 'Only person property and cohort filters from your internal and test account settings apply here.'+ )+ })})})diff --git a/frontend/src/lib/components/TestAccountFiltersSwitch.tsx b/frontend/src/lib/components/TestAccountFiltersSwitch.tsxindex f66977fcd8ea..f52252a87b7c 100644--- a/frontend/src/lib/components/TestAccountFiltersSwitch.tsx+++ b/frontend/src/lib/components/TestAccountFiltersSwitch.tsx@@ -6,14 +6,46 @@ import { LemonButton, LemonSwitch, LemonSwitchProps } from '@posthog/lemon-ui'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+const TEST_ACCOUNT_FILTER_TYPE_LABELS: Record<string, string> = {+ person: 'person property',+ cohort: 'cohort',+}++/**+ * Reason to disable the switch when the team has test account filters configured but none of them+ * apply to the current surface (e.g. only event-based filters, on a person-level cohort). Returns+ * null when the toggle is meaningful (a filter applies, or none are configured, which the empty+ * state handles separately). Keeps the toggle from being a silent no-op.+ */+export function getUnusedTestAccountFilterReason(+ filters: readonly { type?: string | null }[],+ applicableTypes: string[]+): string | null {+ if (filters.length === 0 || filters.some((filter) => filter.type && applicableTypes.includes(filter.type))) {+ return null+ }+ const labels = applicableTypes.map((type) => TEST_ACCOUNT_FILTER_TYPE_LABELS[type] ?? type)+ return `Only ${labels.join(' and ')} filters from your internal and test account settings apply here.`+}+type TestAccountFilterProps = Partial<LemonSwitchProps> & {checked: booleanonChange: (checked: boolean) => void+ /** When set, the toggle is disabled with an explanatory reason unless the team has at least one+ * test account filter of one of these types. Omit to accept every filter type (events etc.). */+ applicableFilterTypes?: string[]}-export function TestAccountFilterSwitch({ checked, onChange, ...props }: TestAccountFilterProps): JSX.Element | null {+export function TestAccountFilterSwitch({+ checked,+ onChange,+ applicableFilterTypes,+ ...props+}: TestAccountFilterProps): JSX.Element | null {const { currentTeam } = useValues(teamLogic)- const hasFilters = (currentTeam?.test_account_filters || []).length > 0+ const filters = currentTeam?.test_account_filters || []+ const hasFilters = filters.length > 0+ const unusedReason = applicableFilterTypes ? getUnusedTestAccountFilterReason(filters, applicableFilterTypes) : nullreturn (<LemonSwitchid="test-account-filter"@@ -22,7 +54,7 @@ export function TestAccountFilterSwitch({ checked, onChange, ...props }: TestAccdisabledReason={!hasFilters? "You haven't set any internal test filters. Click the gear icon to configure."- : props.disabledReason+ : (unusedReason ?? props.disabledReason)}checked={checked}onChange={onChange}diff --git a/frontend/src/queries/nodes/DataNode/TestAccountFilters.tsx b/frontend/src/queries/nodes/DataNode/TestAccountFilters.tsxindex f72426c06561..3a163d726bfe 100644--- a/frontend/src/queries/nodes/DataNode/TestAccountFilters.tsx+++ b/frontend/src/queries/nodes/DataNode/TestAccountFilters.tsx@@ -4,25 +4,42 @@ import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitchimport { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'import { teamLogic } from 'scenes/teamLogic'-import { DataNode, EventsQuery, HogQLQuery, SessionsQuery, TracesQuery } from '~/queries/schema/schema-general'-import { isEventsQuery, isHogQLQuery, isSessionsQuery, isTracesQuery } from '~/queries/utils'+import {+ ActorsQuery,+ DataNode,+ EventsQuery,+ HogQLQuery,+ SessionsQuery,+ TracesQuery,+} from '~/queries/schema/schema-general'+import { isActorsQuery, isEventsQuery, isHogQLQuery, isSessionsQuery, isTracesQuery } from '~/queries/utils'interface TestAccountFiltersProps {query: DataNode- setQuery?: (query: EventsQuery | HogQLQuery | SessionsQuery | TracesQuery) => void+ setQuery?: (query: ActorsQuery | EventsQuery | HogQLQuery | SessionsQuery | TracesQuery) => void}export function TestAccountFilters({ query, setQuery }: TestAccountFiltersProps): JSX.Element | null {const { currentTeam } = useValues(teamLogic)const hasFilters = (currentTeam?.test_account_filters || []).length > 0const { setLocalDefault } = useActions(filterTestAccountsDefaultsLogic)- if (!isEventsQuery(query) && !isHogQLQuery(query) && !isSessionsQuery(query) && !isTracesQuery(query)) {+ // A source-less ActorsQuery is the persons list, which carries its own filterTestAccounts flag+ // (like EventsQuery). Actors queries with an insight source use the source query's toggle instead.+ const isSourcelessActorsQuery = isActorsQuery(query) && !query.source++ if (+ !isEventsQuery(query) &&+ !isHogQLQuery(query) &&+ !isSessionsQuery(query) &&+ !isTracesQuery(query) &&+ !isSourcelessActorsQuery+ ) {return null}const checked = hasFilters? !!(isHogQLQuery(query)? query.filters?.filterTestAccounts- : isEventsQuery(query) || isSessionsQuery(query) || isTracesQuery(query)+ : isEventsQuery(query) || isSessionsQuery(query) || isTracesQuery(query) || isSourcelessActorsQuery? query.filterTestAccounts: false): false@@ -37,9 +54,9 @@ export function TestAccountFilters({ query, setQuery }: TestAccountFiltersProps)}setQuery?.(newQuery)}- : isEventsQuery(query) || isSessionsQuery(query) || isTracesQuery(query)+ : isEventsQuery(query) || isSessionsQuery(query) || isTracesQuery(query) || isSourcelessActorsQuery? (checked: boolean) => {- const newQuery: EventsQuery | SessionsQuery | TracesQuery = {+ const newQuery: ActorsQuery | EventsQuery | SessionsQuery | TracesQuery = {...query,filterTestAccounts: checked,}@@ -54,6 +71,8 @@ export function TestAccountFilters({ query, setQuery }: TestAccountFiltersProps)onChange?.(checked)setLocalDefault(checked)}}+ // The persons list is a person-level query: only person and cohort test filters apply.+ applicableFilterTypes={isSourcelessActorsQuery ? ['person', 'cohort'] : undefined}/>)}diff --git a/frontend/src/queries/nodes/DataTable/queryFeatures.test.ts b/frontend/src/queries/nodes/DataTable/queryFeatures.test.tsindex 21a31dea1d51..4c939467c3f3 100644--- a/frontend/src/queries/nodes/DataTable/queryFeatures.test.ts+++ b/frontend/src/queries/nodes/DataTable/queryFeatures.test.ts@@ -31,4 +31,20 @@ describe('getQueryFeatures', () => {}})})++ describe('testAccountFilters', () => {+ // The persons list is a source-less ActorsQuery and must expose the toggle. An ActorsQuery+ // with an insight source uses that source's own toggle instead, so it must not.+ it.each([+ ['source-less ActorsQuery (persons list)', { kind: NodeKind.ActorsQuery }, true],+ [+ 'ActorsQuery with an insight source',+ { kind: NodeKind.ActorsQuery, source: { kind: NodeKind.InsightActorsQuery } },+ false,+ ],+ ])('%s testAccountFilters enabled = %s', (_, query, expected) => {+ const features = getQueryFeatures(query as any)+ expect(features.has(QueryFeature.testAccountFilters)).toBe(expected)+ })+ })})diff --git a/frontend/src/queries/nodes/DataTable/queryFeatures.ts b/frontend/src/queries/nodes/DataTable/queryFeatures.tsindex c5f2f126fb6b..359b4a2f1a48 100644--- a/frontend/src/queries/nodes/DataTable/queryFeatures.ts+++ b/frontend/src/queries/nodes/DataTable/queryFeatures.ts@@ -89,6 +89,12 @@ export function getQueryFeatures(query: Node): Set<QueryFeature> {features.add(QueryFeature.resultIsArrayOfArrays)features.add(QueryFeature.showCount)features.add(QueryFeature.displayResponseError)++ if (!query.source) {+ // A source-less ActorsQuery is the persons list. When there's an insight+ // source, that source query carries its own filterTestAccounts toggle.+ features.add(QueryFeature.testAccountFilters)+ }}}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 9eef8ef148e9..82174f33c4e7 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -456,6 +456,10 @@"ActorsQuery": {"additionalProperties": false,"properties": {+ "filterTestAccounts": {+ "description": "Exclude persons matching the team's \"internal and test account\" filters. Only person-scoped filters (person properties, cohorts) are applied. Event-scoped test account filters have no meaning in a persons query and are ignored.",+ "type": "boolean"+ },"fixedProperties": {"description": "Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py.","items": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex f75e76ba7df0..74d2f8e78485 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2471,6 +2471,12 @@ export interface ActorsQuery extends DataNode<ActorsQueryResponse> {| HogQLQueryselect?: HogQLExpression[]search?: string+ /**+ * Exclude persons matching the team's "internal and test account" filters.+ * Only person-scoped filters (person properties, cohorts) are applied. Event-scoped+ * test account filters have no meaning in a persons query and are ignored.+ */+ filterTestAccounts?: boolean/** Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py. */properties?: AnyPersonScopeFilter[] | PropertyGroupFilterValue/** Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py. */diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsxindex cb5beab1ad98..aab4b6a86e00 100644--- a/frontend/src/scenes/cohorts/CohortEdit.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx@@ -9,6 +9,7 @@ import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { NotFound } from 'lib/components/NotFound'import { SceneAddToNotebookDropdownMenu } from 'lib/components/Scenes/InsightOrDashboard/SceneAddToNotebookDropdownMenu'import { SceneFile } from 'lib/components/Scenes/SceneFile'+import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'import { TZLabel } from 'lib/components/TZLabel'import { CohortTypeEnum, FEATURE_FLAGS } from 'lib/constants'import { useFileSystemLogView } from 'lib/hooks/useFileSystemLogView'@@ -141,6 +142,7 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {deleteCohort,restoreCohort,setOuterGroupsType,+ setFilterTestAccounts,setQuery,duplicateCohort,setCohortValue,@@ -698,14 +700,25 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {className={cn('flex items-start justify-between')}hideTitleAndDescription>- <AndOrFilterSelect- value={cohort.filters.properties.type}- onChange={(value) => {- setOuterGroupsType(value)- }}- topLevelFilter={true}- suffix={['criterion', 'criteria']}- />+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <AndOrFilterSelect+ value={cohort.filters.properties.type}+ onChange={(value) => {+ setOuterGroupsType(value)+ }}+ topLevelFilter={true}+ suffix={['criterion', 'criteria']}+ />+ <Tooltip title="Only person property filters from your internal and test account settings apply to cohorts. Event-based filters do not apply to person-level criteria.">+ <div>+ <TestAccountFilterSwitch+ checked={!!cohort.filters.filterTestAccounts}+ onChange={setFilterTestAccounts}+ applicableFilterTypes={['person']}+ />+ </div>+ </Tooltip>+ </div><div className={cn('w-full [&>div]:my-0 [&>div]:w-full')}><CohortCriteriaGroups id={logicProps.id} /></div>diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.tsindex 75944575ab9c..9dfe509c07b3 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts@@ -1304,4 +1304,32 @@ describe('cohortEditLogic', () => {expect(logic.values.activeTab).toBe('overview')})})++ describe('filter out test accounts', () => {+ it('setFilterTestAccounts toggles the flag in filters', async () => {+ await initCohortLogic({ id: 'new' })+ await expectLogic(logic, () => {+ logic.actions.setFilterTestAccounts(true)+ }).toMatchValues({+ cohort: partial({ filters: partial({ filterTestAccounts: true }) }),+ })+ })++ it('setOuterGroupsType preserves the filterTestAccounts flag', async () => {+ // Regression guard: setOuterGroupsType used to rebuild `filters` from scratch, dropping+ // sibling keys like filterTestAccounts.+ await initCohortLogic({ id: 'new' })+ await expectLogic(logic, () => {+ logic.actions.setFilterTestAccounts(true)+ logic.actions.setOuterGroupsType(FilterLogicalOperator.And)+ }).toMatchValues({+ cohort: partial({+ filters: partial({+ filterTestAccounts: true,+ properties: partial({ type: FilterLogicalOperator.And }),+ }),+ }),+ })+ })+ })})diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.tsindex 9c9e250e5480..5e10dd4af8fd 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts@@ -361,6 +361,9 @@ export interface cohortEditLogicActions {groupIndex: numbernewCriteria: AnyCohortCriteriaType}+ setFilterTestAccounts: (filterTestAccounts: boolean) => {+ filterTestAccounts: boolean+ }setInnerGroupType: (type: FilterLogicalOperator,groupIndex: number@@ -422,6 +425,7 @@ export interface cohortEditLogicActions {errors_calculating?: number | undefinedexperiment_set?: number[] | undefinedfilters: {+ filterTestAccounts?: boolean | undefinedproperties: CohortCriteriaGroupFilter}groups: CohortGroupType[]@@ -450,6 +454,7 @@ export interface cohortEditLogicActions {errors_calculating?: number | undefinedexperiment_set?: number[] | undefinedfilters: {+ filterTestAccounts?: boolean | undefinedproperties: CohortCriteriaGroupFilter}groups: CohortGroupType[]@@ -508,6 +513,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([checkIfFinishedCalculating: (cohort: CohortType) => ({ cohort }),setOuterGroupsType: (type: FilterLogicalOperator) => ({ type }),+ setFilterTestAccounts: (filterTestAccounts: boolean) => ({ filterTestAccounts }),setInnerGroupType: (type: FilterLogicalOperator, groupIndex: number) => ({ type, groupIndex }),duplicateFilter: (groupIndex: number, criteriaIndex?: number) => ({ groupIndex, criteriaIndex }),addFilter: (groupIndex?: number) => ({ groupIndex }),@@ -537,12 +543,20 @@ export const cohortEditLogic = kea<cohortEditLogicType>([setOuterGroupsType: (state, { type }) => ({...state,filters: {+ ...state.filters,properties: {...state.filters.properties,type,},},}),+ setFilterTestAccounts: (state, { filterTestAccounts }) => ({+ ...state,+ filters: {+ ...state.filters,+ filterTestAccounts,+ },+ }),setInnerGroupType: (state, { type, groupIndex }) =>applyAllCriteriaGroup(state,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 63c3ff224519..82fa26883ce1 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1824,6 +1824,8 @@ export interface CohortType {groups: CohortGroupType[] // To be deprecated once `filter` takes overfilters: {properties: CohortCriteriaGroupFilter+ /** Exclude internal and test users (person-scoped team filters) at calculation time */+ filterTestAccounts?: boolean}experiment_set?: number[]_create_in_folder?: string | nulldiff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 68e23ae34bf1..5f0ea5042af9 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -154,7 +154,10 @@ def validate_filters_and_compute_realtime_support(logger.warning(error_msg)return filters_dict, current_cohort_type, [error_msg]- validated_filters = CohortFilters.model_validate({"properties": properties}, context={"team": team})+ validated_filters = CohortFilters.model_validate(+ {"properties": properties, "filterTestAccounts": filters_dict.get("filterTestAccounts")},+ context={"team": team},+ )clean_filters = validated_filters.model_dump(exclude_none=True)@@ -169,6 +172,11 @@ def validate_filters_and_compute_realtime_support(if cohort_count > REALTIME_COHORT_MAX_PERSON_COUNT:cohort_type = None+ # Realtime evaluation compiles bytecode from the cohort's own leaf filters and can't see the+ # test account filters injected at calculation time, so force the batch path for these cohorts.+ if clean_filters.get("filterTestAccounts"):+ cohort_type = None+return clean_filters, cohort_type, Noneexcept Exception as e:@@ -413,6 +421,9 @@ def _calculate_realtime_support(group: CohortFilterGroup) -> bool:class CohortFilters(BaseModel, extra="forbid"):properties: CohortFilterGroup+ # When true, the team's person-scoped "internal and test account" filters are ANDed+ # into the cohort criteria at calculation time (see hogql_cohort_query.py).+ filterTestAccounts: Optional[bool] = NoneAPI_COHORT_PERSON_BYTES_READ_FROM_POSTGRES_COUNTER = Counter(diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 0d7c6c8de676..ac93e31dc23c 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -6442,6 +6442,69 @@ class TestCohortTypeIntegration(APIBaseTest):self.assertEqual(cohort.condition_type, expected_condition_type)self.assertEqual(response.data["condition_type"], expected_condition_type)+ def test_filter_test_accounts_persists_and_forces_batch_calculation(self):+ # Forced off the realtime path because realtime bytecode can't see the injected test account filters.+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts/",+ {+ "name": "Real users only",+ "filters": {+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "person",+ "key": "email",+ "operator": "icontains",+ "value": "@posthog.com",+ }+ ],+ },+ "filterTestAccounts": True,+ },+ },+ format="json",+ )++ self.assertEqual(response.status_code, 201, response.data)+ cohort = Cohort.objects.get(id=response.data["id"])+ assert cohort.filters is not None+ self.assertIs(cohort.filters.get("filterTestAccounts"), True)+ self.assertNotEqual(cohort.cohort_type, CohortType.REALTIME)++ def test_filter_test_accounts_patch_toggles_realtime_routing(self):+ person_property_filters = {+ "type": "AND",+ "values": [{"type": "person", "key": "email", "operator": "icontains", "value": "@posthog.com"}],+ }+ create = self.client.post(+ f"/api/projects/{self.team.id}/cohorts/",+ {"name": "Real users only", "filters": {"properties": person_property_filters}},+ format="json",+ )+ self.assertEqual(create.status_code, 201, create.data)+ cohort_id = create.data["id"]+ self.assertEqual(Cohort.objects.get(id=cohort_id).cohort_type, CohortType.REALTIME)++ turn_on = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}/",+ {"filters": {"properties": person_property_filters, "filterTestAccounts": True}},+ format="json",+ )+ self.assertEqual(turn_on.status_code, 200, turn_on.data)+ cohort = Cohort.objects.get(id=cohort_id)+ assert cohort.filters is not None+ self.assertIs(cohort.filters.get("filterTestAccounts"), True)+ self.assertNotEqual(cohort.cohort_type, CohortType.REALTIME)++ turn_off = self.client.patch(+ f"/api/projects/{self.team.id}/cohorts/{cohort_id}/",+ {"filters": {"properties": person_property_filters, "filterTestAccounts": False}},+ format="json",+ )+ self.assertEqual(turn_off.status_code, 200, turn_off.data)+ self.assertEqual(Cohort.objects.get(id=cohort_id).cohort_type, CohortType.REALTIME)+def test_person_metadata_cohort_not_classified_realtime(self):"""person_metadata cohorts must route to the non-realtime path: the realtimeprecalculated_person_properties table only carries JSON-blob values, not top-leveldiff --git a/posthog/hogql_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.pyindex 8d62f1f5b67d..d36a93f84b14 100644--- a/posthog/hogql_queries/actor_strategies.py+++ b/posthog/hogql_queries/actor_strategies.py@@ -56,6 +56,11 @@ class ActorStrategy:return None+# Test account filters authored against events (event/element/hogql/session types) have no+# meaning in a person-level query, so only these types are applied on the persons list.+PERSON_SCOPE_TEST_ACCOUNT_FILTER_TYPES = ("person", "cohort")++class PersonStrategy(ActorStrategy):field = "person"origin = "persons"@@ -128,6 +133,15 @@ class PersonStrategy(ActorStrategy):if self.query.fixedProperties:where_exprs.append(property_to_expr(self.query.fixedProperties, self.team, scope="person"))+ if self.query.filterTestAccounts:+ applicable_test_filters = [+ prop+ for prop in (self.team.test_account_filters or [])+ if isinstance(prop, dict) and prop.get("type") in PERSON_SCOPE_TEST_ACCOUNT_FILTER_TYPES+ ]+ if applicable_test_filters:+ where_exprs.append(property_to_expr(applicable_test_filters, self.team, scope="person"))+search = self.query.search.strip() if self.query.search else Noneif search:where_exprs.append(diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.pyindex a3cc816779c1..5bef8659a85a 100644--- a/posthog/hogql_queries/hogql_cohort_query.py+++ b/posthog/hogql_queries/hogql_cohort_query.py@@ -245,6 +245,20 @@ def convert(prop: PropertyGroup) -> PropertyGroupFilterValue:return r+def _person_test_account_properties(team: Team) -> list[Property]:+ """Person-property filters from team.test_account_filters.++ Event/element/hogql-scoped test filters can't be standalone cohort conditions, and+ cohort-typed ones are excluded here to avoid self-referential cohorts (a team test+ filter can point at the very cohort being calculated).+ """+ return [+ Property(**prop)+ for prop in (team.test_account_filters or [])+ if isinstance(prop, dict) and prop.get("type") == "person"+ ]++class HogQLCohortQuery:def __init__(self,@@ -265,7 +279,18 @@ class HogQLCohortQuery:self.team,cohort,)- self.property_groups = unwrapped.property_groups+ property_groups = unwrapped.property_groups+ if (cohort.filters or {}).get("filterTestAccounts"):+ test_props = _person_test_account_properties(self.team)+ if test_props:+ property_groups = PropertyGroup(+ type=PropertyOperatorType.AND,+ values=[+ property_groups,+ PropertyGroup(type=PropertyOperatorType.AND, values=test_props),+ ],+ )+ self.property_groups = property_groupselif filter is not None:if team is None:raise ValueError("HogQLCohortQuery requires a team when constructed from a filter")diff --git a/posthog/hogql_queries/test/test_actors_query_runner.py b/posthog/hogql_queries/test/test_actors_query_runner.pyindex ea1a235cef2d..798fbe19b7e7 100644--- a/posthog/hogql_queries/test/test_actors_query_runner.py+++ b/posthog/hogql_queries/test/test_actors_query_runner.py@@ -147,6 +147,60 @@ class TestActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(len(runner.calculate().results), 2)+ def _create_internal_and_external_persons(self) -> None:+ for index in range(3):+ _create_person(+ properties={"email": f"employee{index}@posthog.com"},+ team=self.team,+ distinct_ids=[f"internal-{index}"],+ is_identified=True,+ )+ for index in range(2):+ _create_person(+ properties={"email": f"customer{index}@example.com"},+ team=self.team,+ distinct_ids=[f"external-{index}"],+ is_identified=True,+ )+ flush_persons_and_events()++ @parameterized.expand(+ [+ # Person-scoped filter applied: the 3 internal persons are excluded, leaving 2.+ (+ "person_filter_on_excludes_internal",+ True,+ [{"key": "email", "value": "@posthog.com", "operator": "not_icontains", "type": "person"}],+ 2,+ ),+ # Flag off: the filter is not applied, so all 5 persons are returned.+ (+ "person_filter_off_keeps_all",+ False,+ [{"key": "email", "value": "@posthog.com", "operator": "not_icontains", "type": "person"}],+ 5,+ ),+ # Event-scoped filters have no meaning on a persons query. They must be skipped, not raise.+ (+ "event_scoped_filter_is_ignored",+ True,+ [{"key": "$host", "value": "localhost", "operator": "is_not", "type": "event"}],+ 5,+ ),+ # No configured filters means the flag is a no-op.+ ("empty_test_account_filters_is_noop", True, [], 5),+ ]+ )+ def test_filter_test_accounts_applies_only_person_scoped_filters(+ self, _name: str, filter_test_accounts: bool, test_account_filters: list, expected_count: int+ ) -> None:+ self._create_internal_and_external_persons()+ self.team.test_account_filters = test_account_filters+ self.team.save()++ runner = self._create_runner(ActorsQuery(filterTestAccounts=filter_test_accounts))+ self.assertEqual(len(runner.calculate().results), expected_count)+def test_persons_query_search_email(self):self.random_uuid = self._create_random_persons()self._create_random_persons()diff --git a/posthog/hogql_queries/test/test_hogql_cohort_query.py b/posthog/hogql_queries/test/test_hogql_cohort_query.pyindex 66d41e5f5ab1..0682ca017576 100644--- a/posthog/hogql_queries/test/test_hogql_cohort_query.py+++ b/posthog/hogql_queries/test/test_hogql_cohort_query.py@@ -541,6 +541,68 @@ class TestHogQLCohortQuery(ClickhouseTestMixin, APIBaseTest):self.assertIn(str(new_person.uuid), member_ids)self.assertNotIn(str(old_person.uuid), member_ids)+ def _cohort_member_ids(self, cohort: Cohort, version: int) -> set[str]:+ rows = sync_execute(+ "SELECT person_id FROM cohortpeople WHERE cohort_id = %(cohort_id)s AND team_id = %(team_id)s "+ "AND version = %(version)s GROUP BY person_id, cohort_id, team_id, version HAVING sum(sign) > 0",+ {"cohort_id": cohort.pk, "team_id": self.team.pk, "version": version},+ )+ return {str(row[0]) for row in rows}++ def test_filter_test_accounts_excludes_person_matches_and_tracks_team_settings(self) -> None:+ internal = _create_person(+ team=self.team,+ distinct_ids=["internal"],+ properties={"email": "[email protected]", "plan": "paid"},+ immediate=True,+ )+ external = _create_person(+ team=self.team,+ distinct_ids=["external"],+ properties={"email": "[email protected]", "plan": "paid"},+ immediate=True,+ )+ flush_persons_and_events()++ self.team.test_account_filters = [+ {"key": "email", "value": "@posthog.com", "operator": "not_icontains", "type": "person"}+ ]+ self.team.save()++ cohort = cast(+ Cohort,+ Cohort.objects.create(+ team=self.team,+ name="paid users",+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [{"key": "plan", "type": "person", "value": "paid", "operator": "exact"}],+ }+ ],+ },+ "filterTestAccounts": True,+ },+ ),+ )++ cohort.calculate_people_ch(pending_version=0)+ members = self._cohort_member_ids(cohort, version=0)+ self.assertIn(str(external.uuid), members)+ self.assertNotIn(str(internal.uuid), members)++ # The team's filters are read at calculation time, not copied into the cohort, so clearing+ # them re-includes the internal person on the next recalculation.+ self.team.test_account_filters = []+ self.team.save()+ cohort.calculate_people_ch(pending_version=1)+ members = self._cohort_member_ids(cohort, version=1)+ self.assertIn(str(external.uuid), members)+ self.assertIn(str(internal.uuid), members)+def test_person_metadata_cohort_membership_negated_end_to_end(self) -> None:# Mirror of the is_date_after test with is_date_before, so membership inverts: the OLD# person should be in the cohort and the NEW person should not. Covers the operator whosediff --git a/posthog/schema.py b/posthog/schema.pyindex 894bf88851f6..c1c2857c2a87 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -26702,6 +26702,15 @@ class ActorsQuery(BaseModel):model_config = ConfigDict(extra="forbid",)+ filterTestAccounts: bool | None = Field(+ default=None,+ description=(+ 'Exclude persons matching the team\'s "internal and test account" filters.'+ " Only person-scoped filters (person properties, cohorts) are applied."+ " Event-scoped test account filters have no meaning in a persons query and"+ " are ignored."+ ),+ )fixedProperties: (list[PersonPropertyFilterdiff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.tsindex f2f96bb5ba6b..5ff099d4e04b 100644--- a/products/cohorts/frontend/generated/api.schemas.ts+++ b/products/cohorts/frontend/generated/api.schemas.ts@@ -213,6 +213,7 @@ export interface CohortFilterGroupApi {export interface CohortFiltersApi {properties: CohortFilterGroupApi+ filterTestAccounts?: boolean | null}/**diff --git a/products/cohorts/frontend/generated/api.zod.ts b/products/cohorts/frontend/generated/api.zod.tsindex c8acd8e4ca8b..c6de9d3519eb 100644--- a/products/cohorts/frontend/generated/api.zod.ts+++ b/products/cohorts/frontend/generated/api.zod.ts@@ -48,6 +48,7 @@ export const CohortsCreateBody = /* @__PURE__ */ zod.object({properties: zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'),+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),}),zod.null(),])@@ -89,6 +90,7 @@ export const CohortsUpdateBody = /* @__PURE__ */ zod.object({properties: zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'),+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),}),zod.null(),])@@ -130,6 +132,7 @@ export const CohortsPartialUpdateBody = /* @__PURE__ */ zod.object({properties: zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)'),+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),}),zod.null(),])diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 2c7f2e821bcd..48902479d908 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -5903,6 +5903,8 @@ export interface HogQLQueryApi {}export interface ActorsQueryApi {+ /** Exclude persons matching the team's "internal and test account" filters. Only person-scoped filters (person properties, cohorts) are applied. Event-scoped test account filters have no meaning in a persons query and are ignored. */+ filterTestAccounts?: boolean | null/** Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py. */fixedProperties?:| (diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 763c3fe06f3f..801c5ff1c9f9 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -5235,6 +5235,8 @@ export interface HogQLQueryApi {}export interface ActorsQueryApi {+ /** Exclude persons matching the team's "internal and test account" filters. Only person-scoped filters (person properties, cohorts) are applied. Event-scoped test account filters have no meaning in a persons query and are ignored. */+ filterTestAccounts?: boolean | null/** Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py. */fixedProperties?:| (diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex be4c4dcba733..81e583d0708b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -4553,6 +4553,8 @@ export namespace Schemas {}export interface ActorsQuery {+ /** Exclude persons matching the team's "internal and test account" filters. Only person-scoped filters (person properties, cohorts) are applied. Event-scoped test account filters have no meaning in a persons query and are ignored. */+ filterTestAccounts?: boolean | null;/** Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py. */fixedProperties?: (PersonPropertyFilter | PersonMetadataPropertyFilter | CohortPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter)[] | null;kind?: 'ActorsQuery';@@ -13949,6 +13951,7 @@ export namespace Schemas {export interface CohortFilters {properties: CohortFilterGroup;+ filterTestAccounts?: boolean | null;}/**diff --git a/services/mcp/src/generated/cohorts/api.ts b/services/mcp/src/generated/cohorts/api.tsindex b9ba9d4a7fef..c2080ba4dea3 100644--- a/services/mcp/src/generated/cohorts/api.ts+++ b/services/mcp/src/generated/cohorts/api.ts@@ -160,6 +160,7 @@ export const CohortsCreateBody = /* @__PURE__ */ zod.object({.describe('AND\/OR group containing cohort filters. Named to avoid collision with analytics Group model.'),+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),}),zod.null(),])@@ -321,6 +322,7 @@ export const CohortsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('AND\/OR group containing cohort filters. Named to avoid collision with analytics Group model.'),+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),}),zod.null(),])diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-create.jsonindex 45be844959bf..7b4f151e77ba 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-create.json@@ -26,6 +26,16 @@"anyOf": [{"properties": {+ "filterTestAccounts": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"properties": {"description": "AND/OR group containing cohort filters. Named to avoid collision with analytics Group model.","properties": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-partial-update.jsonindex 130a5686031c..a5857fd07e5b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-partial-update.json@@ -29,6 +29,16 @@"anyOf": [{"properties": {+ "filterTestAccounts": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"properties": {"description": "AND/OR group containing cohort filters. Named to avoid collision with analytics Group model.","properties": {