: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(taxonomic-filter): pin current url and email filters by default (#68164)
Paul D'Ambra1ea0202beb04
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex 2b46cd32ce16..f12b3950bdd5 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -13,6 +13,7 @@ export const getStorybookAppContext = (): AppContext => ({default_event_name: '$pageview',has_pageview: true,has_screen: true,+ has_person_email: false,persisted_feature_flags: [],commit_sha: undefined,preflight: null as any, // `null` triggers a fetch and lets us mock the datadiff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.tsindex 3f0015b5b98c..236bfdf0b059 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts@@ -20,6 +20,7 @@ import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsimport { infiniteListLogic } from './infiniteListLogic'import { taxonomicFilterLogic } from './taxonomicFilterLogic'+import { hasPinnedContext, taxonomicFilterPinnedPropertiesLogic } from './taxonomicFilterPinnedPropertiesLogic'window.POSTHOG_APP_CONTEXT = {current_team: { id: MOCK_TEAM_ID },@@ -912,6 +913,84 @@ describe('infiniteListLogic', () => {})})+ describe('suggested list dedupes pinned against recents', () => {+ beforeEach(() => {+ localStorage.clear()+ })++ afterEach(() => {+ localStorage.clear()+ })++ const seedRecentAndPins = (): void => {+ const recentLogic = recentTaxonomicFiltersLogic.build()+ recentLogic.mount()+ recentLogic.actions.recordRecentFilter({+ groupType: TaxonomicFilterGroupType.EventProperties,+ groupName: 'Event properties',+ value: '$current_url',+ item: { name: '$current_url' },+ })+ const pinnedLogic = taxonomicFilterPinnedPropertiesLogic.build()+ pinnedLogic.mount()+ pinnedLogic.actions.togglePin(+ TaxonomicFilterGroupType.EventProperties,+ 'Event properties',+ '$current_url',+ {+ name: '$current_url',+ }+ )+ pinnedLogic.actions.togglePin(TaxonomicFilterGroupType.EventProperties, 'Event properties', '$browser', {+ name: '$browser',+ })+ // Guards against default-pin seeding turning the first togglePin into an+ // unpin, which would make the dedupe assertions pass vacuously.+ expect(pinnedLogic.values.pinnedFilters.map((f) => f.value)).toEqual(['$current_url', '$browser'])+ }++ const mountSuggestedList = (): ReturnType<typeof infiniteListLogic.build> => {+ const listLogic = infiniteListLogic({+ taxonomicFilterLogicKey: 'recents-pinned-dedupe-test',+ listGroupType: TaxonomicFilterGroupType.SuggestedFilters,+ taxonomicGroupTypes: [+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.SuggestedFilters,+ ],+ showNumericalPropsOnly: false,+ })+ listLogic.mount()+ return listLogic+ }++ const pinnedValues = (results: unknown[]): unknown[] =>+ results.filter((item) => hasPinnedContext(item)).map((item) => item._pinnedContext.value)++ it.each([+ { description: 'in the idle prefix', searchQuery: '', expectedPinned: ['$browser'] },+ { description: 'in search matches', searchQuery: 'current', expectedPinned: [] },+ ])(+ 'shows an item that is both recent and pinned once, under recents: $description',+ async ({ searchQuery, expectedPinned }) => {+ seedRecentAndPins()+ const listLogic = mountSuggestedList()++ if (searchQuery) {+ listLogic.actions.setSearchQuery(searchQuery)+ await expectLogic(listLogic).toDispatchActions(['setSearchQuery'])+ }++ const results = listLogic.values.items.results+ expect(pinnedValues(results)).toEqual(expectedPinned)+ expect(+ results.filter(+ (item) => hasRecentContext(item) && item._recentContext.sourceValue === '$current_url'+ )+ ).toHaveLength(1)+ }+ )+ })+describe('contextFilteredRecentItems', () => {// Generic wrapper around hasRecentContext so .filter() preserves the input type// (the production type guard uses `unknown` which TS can't narrow through Array.filter).diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.tsindex d7da66ff0042..87538c09fecb 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts@@ -87,6 +87,34 @@ function recentItemMatchesSearch(return false}+// The two key builders must stay format-aligned: recent and pinned rows dedupe+// against each other only because both produce `sourceGroupType::value`.+function recentSourceKey(item: TaxonomicDefinitionTypes): string | null {+ return hasRecentContext(item) && item._recentContext.sourceValue != null+ ? `${item._recentContext.sourceGroupType}::${item._recentContext.sourceValue}`+ : null+}++function pinnedSourceKey(item: TaxonomicDefinitionTypes): string | null {+ return hasPinnedContext(item) && item._pinnedContext.value != null+ ? `${item._pinnedContext.sourceGroupType}::${item._pinnedContext.value}`+ : null+}++function withoutPinnedDuplicatesOfRecents(+ pinnedItems: TaxonomicDefinitionTypes[],+ recentItems: TaxonomicDefinitionTypes[]+): TaxonomicDefinitionTypes[] {+ const recentKeys = new Set(recentItems.map(recentSourceKey).filter((key): key is string => key != null))+ if (recentKeys.size === 0) {+ return pinnedItems+ }+ return pinnedItems.filter((item) => {+ const key = pinnedSourceKey(item)+ return key == null || !recentKeys.has(key)+ })+}+export interface RowInfo {startIndex: numberstopIndex: number@@ -819,17 +847,21 @@ export const infiniteListLogic = kea<infiniteListLogicType>([return []}const recentPrefix = !searchQuery ? (contextFilteredRecentItems || []).slice(0, 3) : []- const pinnedPrefix = !searchQuery ? (contextFilteredPinnedItems || []).slice(0, 3) : []+ const pinnedPrefix = !searchQuery+ ? withoutPinnedDuplicatesOfRecents(contextFilteredPinnedItems || [], recentPrefix).slice(0, 3)+ : []const dedupeKeys = new Set<string>()const addRecentKey = (item: TaxonomicDefinitionTypes): void => {- if (hasRecentContext(item) && item._recentContext.sourceValue != null) {- dedupeKeys.add(`${item._recentContext.sourceGroupType}::${item._recentContext.sourceValue}`)+ const key = recentSourceKey(item)+ if (key != null) {+ dedupeKeys.add(key)}}const addPinnedKey = (item: TaxonomicDefinitionTypes): void => {- if (hasPinnedContext(item) && item._pinnedContext.value != null) {- dedupeKeys.add(`${item._pinnedContext.sourceGroupType}::${item._pinnedContext.value}`)+ const key = pinnedSourceKey(item)+ if (key != null) {+ dedupeKeys.add(key)}}recentPrefix.forEach(addRecentKey)@@ -906,7 +938,13 @@ export const infiniteListLogic = kea<infiniteListLogicType>([}const isSuggested = listGroupType === TaxonomicFilterGroupType.SuggestedFiltersconst recentPrefix = isSuggested && !searchQuery ? (contextFilteredRecentItems || []).slice(0, 3) : []- const pinnedPrefix = isSuggested && !searchQuery ? (contextFilteredPinnedItems || []).slice(0, 3) : []+ // An item that is both recent and pinned shows once, under the section that+ // renders first — recents (mirrors the rebuild Combobox's prefix dedupe).+ const pinnedPrefix =+ isSuggested && !searchQuery+ ? withoutPinnedDuplicatesOfRecents(contextFilteredPinnedItems || [], recentPrefix).slice(0, 3)+ : []+ const pinnedMatches = withoutPinnedDuplicatesOfRecents(suggestedPinnedMatches, suggestedRecentMatches)const topMatches = isSuggested ? dedupedTopMatches : []// Shortcuts lead the list so users searching for the verb they mean (e.g. "click")@@ -920,7 +958,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([...recentPrefix,...pinnedPrefix,...suggestedRecentMatches,- ...suggestedPinnedMatches,+ ...pinnedMatches,...localItems.results,...remoteItems.results,...topMatches,@@ -940,7 +978,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([recentPrefix.length +pinnedPrefix.length +suggestedRecentMatches.length +- suggestedPinnedMatches.length ++ pinnedMatches.length +localItems.count +remoteItems.count +topMatches.filter((item) => !isSkeletonItem(item)).length,diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.tsindex 9ee66be0a30e..1084fbcb4976 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.test.ts@@ -1,4 +1,10 @@+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { initKeaTests } from '~/test/init'+import { AppContext } from '~/types'import {hasPinnedContext,@@ -9,6 +15,7 @@ import {import { TaxonomicFilterGroupType } from './types'const MIGRATION_KEY = 'taxonomicFilterPinnedProperties__migrated__default'+const DEFAULTS_SEEDED_KEY = 'taxonomicFilterPinnedProperties__defaultsSeeded__default'const OLD_PERSIST_KEY = 'scenes.session-recordings.player.playerSettingsLogic.quickFilterProperties'describe('taxonomicFilterPinnedPropertiesLogic', () => {@@ -281,6 +288,136 @@ describe('taxonomicFilterPinnedPropertiesLogic', () => {})})+ describe('seeding default pinned filters', () => {+ const seededState = (seeded: string[], touched = false): string => JSON.stringify({ seeded, touched })++ const mountWith = (+ hasPageview: boolean,+ hasPersonEmail: boolean,+ { flagEnabled = true, freshStorage = true }: { flagEnabled?: boolean; freshStorage?: boolean } = {}+ ): void => {+ logic.unmount()+ if (freshStorage) {+ localStorage.clear()+ }+ window.POSTHOG_APP_CONTEXT = {+ has_pageview: hasPageview,+ has_person_email: hasPersonEmail,+ } as unknown as AppContext+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags(+ [],+ flagEnabled ? { [FEATURE_FLAGS.TAXONOMIC_FILTER_DEFAULT_PINS]: true } : {}+ )+ logic = taxonomicFilterPinnedPropertiesLogic.build()+ logic.mount()+ }++ afterEach(() => {+ window.POSTHOG_APP_CONTEXT = undefined as unknown as AppContext+ })++ it.each([+ {+ description: 'pins both $current_url and email when the team sends both',+ hasPageview: true,+ hasPersonEmail: true,+ expected: [+ { value: '$current_url', groupType: TaxonomicFilterGroupType.EventProperties },+ { value: 'email', groupType: TaxonomicFilterGroupType.PersonProperties },+ ],+ },+ {+ description: 'pins only email when the team sends no pageviews',+ hasPageview: false,+ hasPersonEmail: true,+ expected: [{ value: 'email', groupType: TaxonomicFilterGroupType.PersonProperties }],+ },+ {+ description: 'pins only $current_url when the team does not send email',+ hasPageview: true,+ hasPersonEmail: false,+ expected: [{ value: '$current_url', groupType: TaxonomicFilterGroupType.EventProperties }],+ },+ {+ description: 'pins nothing when the team sends neither',+ hasPageview: false,+ hasPersonEmail: false,+ expected: [],+ },+ ])('$description', ({ hasPageview, hasPersonEmail, expected }) => {+ mountWith(hasPageview, hasPersonEmail)++ expect(logic.values.pinnedFilters.map((f) => ({ value: f.value, groupType: f.groupType }))).toEqual(+ expected+ )+ expect(localStorage.getItem(DEFAULTS_SEEDED_KEY)).toBe(+ expected.length > 0 ? seededState(expected.map((e) => e.value)) : null+ )+ })++ it('seeds nothing when the feature flag is disabled', () => {+ mountWith(true, true, { flagEnabled: false })++ expect(logic.values.pinnedFilters).toEqual([])+ expect(localStorage.getItem(DEFAULTS_SEEDED_KEY)).toBeNull()+ })++ it('tops up a default that becomes available on a later mount', () => {+ const captureSpy = jest.spyOn(posthog, 'capture')+ mountWith(true, false)+ expect(logic.values.pinnedFilters.map((f) => f.value)).toEqual(['$current_url'])++ mountWith(true, true, { freshStorage: false })++ expect(logic.values.pinnedFilters.map((f) => f.value)).toEqual(['$current_url', 'email'])+ expect(localStorage.getItem(DEFAULTS_SEEDED_KEY)).toBe(seededState(['$current_url', 'email']))+ expect(captureSpy).toHaveBeenCalledWith('taxonomic filter default pins seeded', { values: ['email'] })+ })++ it('any pin interaction opts the user out of all future seeding', () => {+ mountWith(true, false)+ logic.actions.togglePin(TaxonomicFilterGroupType.EventProperties, 'Event properties', '$current_url', {+ name: '$current_url',+ })+ expect(logic.values.pinnedFilters).toEqual([])++ mountWith(true, true, { freshStorage: false })++ expect(logic.values.pinnedFilters).toEqual([])+ })++ it('does not seed over pins that predate the seeded-state record', () => {+ mountWith(false, false)+ logic.actions.togglePin(TaxonomicFilterGroupType.EventProperties, 'Event properties', '$browser', {+ name: '$browser',+ })+ localStorage.removeItem(DEFAULTS_SEEDED_KEY)++ mountWith(true, true, { freshStorage: false })++ expect(logic.values.pinnedFilters.map((f) => f.value)).toEqual(['$browser'])+ expect(localStorage.getItem(DEFAULTS_SEEDED_KEY)).toBe(seededState([], true))+ })++ it('does not seed over quick filters migrated in the same mount', () => {+ logic.unmount()+ localStorage.clear()+ localStorage.setItem(OLD_PERSIST_KEY, JSON.stringify(['name', '$os']))+ window.POSTHOG_APP_CONTEXT = { has_pageview: true, has_person_email: true } as unknown as AppContext++ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TAXONOMIC_FILTER_DEFAULT_PINS]: true })+ logic = taxonomicFilterPinnedPropertiesLogic.build()+ logic.mount()++ expect(logic.values.pinnedFilters.map((f) => f.value)).toEqual(['name', '$os'])+ expect(localStorage.getItem(DEFAULTS_SEEDED_KEY)).toBe(seededState([], true))+ })+ })+describe('hasPinnedContext', () => {it.each([{diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.tsindex eeb18a92ff4e..b3dd509f9bff 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterPinnedPropertiesLogic.ts@@ -1,5 +1,9 @@-import { actions, events, kea, path, reducers, selectors } from 'kea'+import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'+import posthog from 'posthog-js'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { getAppContext } from 'lib/utils/getAppContext'import { permanentlyMount } from 'lib/utils/kea-logic-builders'import type { taxonomicFilterPinnedPropertiesLogicType } from './taxonomicFilterPinnedPropertiesLogicType'@@ -66,9 +70,71 @@ const OLD_PERSIST_KEY = 'scenes.session-recordings.player.playerSettingsLogic.quconst teamId = typeof window !== 'undefined' ? window.POSTHOG_APP_CONTEXT?.current_team?.id : undefinedconst MIGRATION_KEY = `taxonomicFilterPinnedProperties__migrated__${teamId ?? 'default'}`+const DEFAULTS_SEEDED_KEY = `taxonomicFilterPinnedProperties__defaultsSeeded__${teamId ?? 'default'}`++function makeDefaultPinnedFilter(+ groupType: TaxonomicFilterGroupType,+ groupName: string,+ value: string+): PinnedTaxonomicFilter {+ return { groupType, groupName, value, item: { name: value }, timestamp: Date.now() }+}++const DEFAULT_PIN_CANDIDATES = [+ {+ contextFlag: 'has_pageview' as const,+ groupType: TaxonomicFilterGroupType.EventProperties,+ groupName: 'Event properties',+ value: '$current_url',+ },+ {+ contextFlag: 'has_person_email' as const,+ groupType: TaxonomicFilterGroupType.PersonProperties,+ groupName: 'Person properties',+ value: 'email',+ },+]++function buildDefaultPinnedFilters(): PinnedTaxonomicFilter[] {+ const appContext = getAppContext()+ return DEFAULT_PIN_CANDIDATES.filter((candidate) => appContext?.[candidate.contextFlag]).map((candidate) =>+ makeDefaultPinnedFilter(candidate.groupType, candidate.groupName, candidate.value)+ )+}++/**+ * Which default values have been offered to this user, and whether they have+ * ever touched a pin themselves. `seeded` lets a later mount top up a default+ * that wasn't available yet (e.g. `email` arriving days after `$pageview`);+ * `touched` opts the user out of all future seeding the moment they pin or+ * unpin anything.+ */+interface SeededDefaultsState {+ seeded: string[]+ touched: boolean+}++function readSeededDefaultsState(): SeededDefaultsState {+ try {+ const parsed = JSON.parse(localStorage.getItem(DEFAULTS_SEEDED_KEY) ?? '')+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.seeded)) {+ return { seeded: parsed.seeded, touched: !!parsed.touched }+ }+ } catch {+ // fall through to the fresh state+ }+ return { seeded: [], touched: false }+}++function writeSeededDefaultsState(state: SeededDefaultsState): void {+ localStorage.setItem(DEFAULTS_SEEDED_KEY, JSON.stringify(state))+}export const taxonomicFilterPinnedPropertiesLogic = kea<taxonomicFilterPinnedPropertiesLogicType>([path(['lib', 'components', 'TaxonomicFilter', 'taxonomicFilterPinnedPropertiesLogic']),+ connect(() => ({+ values: [featureFlagLogic, ['featureFlags']],+ })),actions({togglePin: (groupType: TaxonomicFilterGroupType,@@ -138,42 +204,93 @@ export const taxonomicFilterPinnedPropertiesLogic = kea<taxonomicFilterPinnedPropinnedFilters.some((f) => f.groupType === groupType && f.value === value),],}),+ listeners(({ values }) => ({+ togglePin: ({ groupType, value }) => {+ if (META_GROUP_TYPES.has(groupType) || value == null) {+ return+ }+ const state = readSeededDefaultsState()+ if (!state.touched) {+ writeSeededDefaultsState({ ...state, touched: true })+ }+ posthog.capture('taxonomic filter pin toggled', {+ groupType,+ value: String(value),+ pinned: values.isPinned(groupType, value),+ })+ },+ })),events(({ actions, values }) => ({afterMount: () => {if (typeof window === 'undefined') {return}- const alreadyMigrated = localStorage.getItem(MIGRATION_KEY)- if (alreadyMigrated) {- return- }- if (values.pinnedFilters.length > 0) {+ const migrateOldQuickFilters = (): void => {+ if (localStorage.getItem(MIGRATION_KEY)) {+ return+ }+ if (values.pinnedFilters.length > 0) {+ localStorage.setItem(MIGRATION_KEY, '1')+ return+ }+ try {+ const raw = localStorage.getItem(OLD_PERSIST_KEY)+ if (raw) {+ const oldProperties: string[] = JSON.parse(raw)+ if (Array.isArray(oldProperties) && oldProperties.length > 0) {+ const migrated: PinnedTaxonomicFilter[] = oldProperties.map((prop) =>+ makeDefaultPinnedFilter(+ TaxonomicFilterGroupType.PersonProperties,+ 'Person properties',+ prop+ )+ )+ actions.setPinnedFilters(migrated)+ localStorage.removeItem(OLD_PERSIST_KEY)+ writeSeededDefaultsState({ seeded: [], touched: true })+ }+ }+ } catch {+ // ignore parse errors from old data+ }localStorage.setItem(MIGRATION_KEY, '1')- return}- try {- const raw = localStorage.getItem(OLD_PERSIST_KEY)- if (raw) {- const oldProperties: string[] = JSON.parse(raw)- if (Array.isArray(oldProperties) && oldProperties.length > 0) {- const migrated: PinnedTaxonomicFilter[] = oldProperties.map((prop) => ({- groupType: TaxonomicFilterGroupType.PersonProperties,- groupName: 'Person properties',- value: prop,- item: { name: prop },- timestamp: Date.now(),- }))- actions.setPinnedFilters(migrated)- localStorage.removeItem(OLD_PERSIST_KEY)- }+ const seedDefaultPinnedFilters = (): void => {+ if (!values.featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_DEFAULT_PINS]) {+ return+ }+ const state = readSeededDefaultsState()+ if (state.touched) {+ return+ }+ if (values.pinnedFilters.length > 0 && state.seeded.length === 0) {+ writeSeededDefaultsState({ seeded: [], touched: true })+ return+ }+ const toSeed = buildDefaultPinnedFilters().filter(+ (candidate) =>+ !state.seeded.includes(candidate.value as string) &&+ !values.pinnedFilters.some(+ (f) => f.groupType === candidate.groupType && f.value === candidate.value+ )+ )+ if (toSeed.length === 0) {+ return}- } catch {- // ignore parse errors from old data+ actions.setPinnedFilters([...values.pinnedFilters, ...toSeed])+ writeSeededDefaultsState({+ seeded: [...state.seeded, ...toSeed.map((candidate) => candidate.value as string)],+ touched: false,+ })+ posthog.capture('taxonomic filter default pins seeded', {+ values: toSeed.map((candidate) => candidate.value),+ })}- localStorage.setItem(MIGRATION_KEY, '1')+ migrateOldQuickFilters()+ seedDefaultPinnedFilters()},})),permanentlyMount(),diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 5f47c4c8f629..20570f14bc7e 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -483,6 +483,7 @@ export const FEATURE_FLAGS = {TASKS: 'tasks', // owner: #team-ai-observabilityTASKS_STREAM_VIA_PROXY: 'tasks-stream-via-proxy', // owner: #team-ai-observabilityTAXONOMIC_FILTER_CATEGORY_DROPDOWN: 'taxonomic-filter-category-dropdown', // owner: @pauldambra #team-product-analytics multivariate=control,pill+ TAXONOMIC_FILTER_DEFAULT_PINS: 'taxonomic-filter-default-pins', // owner: @pauldambra #team-product-analytics, seeds $current_url/email default pinned filtersTAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)TOGGLE_PROPERTY_ARRAYS: 'toggle-property-arrays', // owner: @arthurdedeus #team-customer-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 774e7d31b117..6e940358a849 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4966,6 +4966,7 @@ export interface AppContext {default_event_name: string | nullhas_pageview: booleanhas_screen: boolean+ has_person_email: boolean/*** Flags the server bootstraps as enabled (a list of keys). Storybook may instead pass a* record to pin specific multivariate variants (e.g. an experiment arm) for a story.diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex e4fabb980365..6ad75c701924 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -152,6 +152,7 @@ post_save:products.conversations.backend.signals.update_ticket_on_messagepost_save:products.data_modeling.backend.signals.sync_saved_query_name_to_nodepost_save:products.data_warehouse.backend.models.revenue_analytics_config.create_external_data_source_revenue_analytics_configpost_save:products.event_definitions.backend.models.event_definition._invalidate_default_event_info_on_save+post_save:products.event_definitions.backend.models.property_definition._invalidate_has_person_email_on_savepost_save:products.exports.backend.models.subscription.subscription_savedpost_save:products.feature_flags.backend.flags_cache.cohort_changed_flags_cachepost_save:products.feature_flags.backend.flags_cache.evaluation_context_changed_flags_cachediff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex e23b7f80d7be..27d3428f2931 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -15,18 +15,22 @@ from django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpRequestfrom django.test import TestCase, override_settingsfrom django.test.client import RequestFactory+from django.utils.timezone import nowfrom parameterized import parameterizedfrom rest_framework.request import Requestfrom posthog.exceptions import RequestParsingError, UnspecifiedCompressionFallbackParsingError-from posthog.models import EventDefinition, Organization, Team, User+from posthog.models import EventDefinition, Organization, PropertyDefinition, Team, Userfrom posthog.settings.utils import get_from_envif TYPE_CHECKING:from posthog.models.group_type_mapping import GroupTypeMappingfrom posthog.utils import (+ HAS_PERSON_EMAIL_ABSENT_TTL_SECONDS,+ HAS_PERSON_EMAIL_ABSENT_YOUNG_PROJECT_TTL_SECONDS,+ HAS_PERSON_EMAIL_PRESENT_TTL_SECONDS,PotentialSecurityProblemException,_build_flag_provider,absolute_uri,@@ -39,6 +43,7 @@ from posthog.utils import (get_default_event_info,get_default_event_name,get_dogfood_flags_team_id,+ get_has_person_email,get_ip_address,get_js_url,get_self_capture_team_id,@@ -562,6 +567,83 @@ class TestDefaultEventName(BaseTest):with self.assertNumQueries(0):get_default_event_info(self.team)+ @parameterized.expand(+ [+ ("person_email_present", "email", PropertyDefinition.Type.PERSON, True),+ ("dollar_email_ignored", "$email", PropertyDefinition.Type.PERSON, False),+ ("event_email_ignored", "email", PropertyDefinition.Type.EVENT, False),+ ("other_person_property_ignored", "name", PropertyDefinition.Type.PERSON, False),+ ]+ )+ def test_get_has_person_email(self, _name, prop_name, prop_type, expected):+ PropertyDefinition.objects.create(name=prop_name, type=prop_type, team=self.team)+ assert get_has_person_email(self.team) is expected++ def test_has_person_email_is_project_scoped_not_team_scoped(self):+ other_team = Team.objects.create(organization=self.organization, project=self.team.project)+ PropertyDefinition.objects.create(+ name="email", type=PropertyDefinition.Type.PERSON, team=other_team, project=self.team.project+ )+ assert get_has_person_email(self.team) is True++ @parameterized.expand(+ [+ ("present_young_project", True, 0, HAS_PERSON_EMAIL_PRESENT_TTL_SECONDS),+ ("present_old_project", True, 30, HAS_PERSON_EMAIL_PRESENT_TTL_SECONDS),+ ("absent_young_project", False, 0, HAS_PERSON_EMAIL_ABSENT_YOUNG_PROJECT_TTL_SECONDS),+ ("absent_old_project", False, 30, HAS_PERSON_EMAIL_ABSENT_TTL_SECONDS),+ ]+ )+ def test_has_person_email_cache_ttl_depends_on_presence_and_project_age(+ self, _name, create_email, project_age_days, expected_ttl+ ):+ if create_email:+ PropertyDefinition.objects.create(name="email", type=PropertyDefinition.Type.PERSON, team=self.team)+ self.team.project.created_at = now() - timedelta(days=project_age_days)+ self.team.project.save()+ with patch("posthog.utils.safe_cache_set") as mock_set:+ get_has_person_email(self.team)+ mock_set.assert_called_once()+ _, kwargs = mock_set.call_args+ assert kwargs["timeout"] == expected_ttl++ @parameterized.expand([("present", True), ("absent", False)])+ def test_has_person_email_result_is_cached(self, _name, create_email):+ if create_email:+ PropertyDefinition.objects.create(name="email", type=PropertyDefinition.Type.PERSON, team=self.team)+ assert self.team.project is not None+ with self.assertNumQueries(1):+ assert get_has_person_email(self.team) is create_email+ with self.assertNumQueries(0):+ assert get_has_person_email(self.team) is create_email++ def test_has_person_email_cache_invalidated_when_email_property_created(self):+ assert get_has_person_email(self.team) is False+ with self.assertNumQueries(0):+ assert get_has_person_email(self.team) is False++ with self.captureOnCommitCallbacks(execute=True):+ PropertyDefinition.objects.create(name="email", type=PropertyDefinition.Type.PERSON, team=self.team)+ assert get_has_person_email(self.team) is True++ def test_delete_does_not_invalidate_so_cascade_fast_delete_stays_enabled(self):+ pd = PropertyDefinition.objects.create(name="email", type=PropertyDefinition.Type.PERSON, team=self.team)+ assert get_has_person_email(self.team) is True++ with self.captureOnCommitCallbacks(execute=True):+ pd.delete()+ with self.assertNumQueries(0):+ assert get_has_person_email(self.team) is True++ def test_has_person_email_cache_not_invalidated_when_unrelated_property_created(self):+ PropertyDefinition.objects.create(name="email", type=PropertyDefinition.Type.PERSON, team=self.team)+ assert get_has_person_email(self.team) is True++ with self.captureOnCommitCallbacks(execute=True):+ PropertyDefinition.objects.create(name="plan", type=PropertyDefinition.Type.PERSON, team=self.team)+ with self.assertNumQueries(0):+ assert get_has_person_email(self.team) is True+class TestLoadDataFromRequest(TestCase):def _create_request_with_headers(self, origin: str, referer: str) -> WSGIRequest:diff --git a/posthog/utils.py b/posthog/utils.pyindex 2a3ec6ec265a..360088837d44 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -26,8 +26,8 @@ from zoneinfo import ZoneInfofrom django.apps import appsfrom django.conf import settingsfrom django.core.cache import cache-from django.db import ProgrammingError-from django.db.models.functions import Lower+from django.db import ProgrammingError, models+from django.db.models.functions import Coalesce, Lowerfrom django.db.utils import DatabaseErrorfrom django.http import HttpRequest, HttpResponsefrom django.template.loader import get_template@@ -572,6 +572,7 @@ def _build_template_context(posthog_app_context["default_event_name"] = event_info["default_event_name"]posthog_app_context["has_pageview"] = event_info["has_pageview"]posthog_app_context["has_screen"] = event_info["has_screen"]+ posthog_app_context["has_person_email"] = get_has_person_email(user.team)with tracer.start_as_current_span("template.user_product_list"):user_product_list = UserProductListSerializer(@@ -844,6 +845,58 @@ def get_default_event_name(team: "Team") -> str | None:return get_default_event_info(team)["default_event_name"]+HAS_PERSON_EMAIL_PRESENT_TTL_SECONDS = 24 * 60 * 60+HAS_PERSON_EMAIL_ABSENT_TTL_SECONDS = 30 * 60+HAS_PERSON_EMAIL_ABSENT_YOUNG_PROJECT_TTL_SECONDS = 60+YOUNG_PROJECT_AGE = datetime.timedelta(days=7)+++def _has_person_email_cache_key(project_id: int) -> str:+ return f"has_person_email:project:{project_id}"+++def _has_person_email_ttl(team: "Team", has_person_email: bool) -> int:+ if has_person_email:+ return HAS_PERSON_EMAIL_PRESENT_TTL_SECONDS+ # Most writes bypass the invalidation signal (raw-SQL ingestion via+ # property-defs-rs, bulk_create/queryset.update, renames, the EE subclass), so+ # these TTLs are the real freshness bound — for a project still setting up, the+ # only thing standing between "started sending email" and the flag flipping.+ if timezone.now() - team.project.created_at < YOUNG_PROJECT_AGE:+ return HAS_PERSON_EMAIL_ABSENT_YOUNG_PROJECT_TTL_SECONDS+ return HAS_PERSON_EMAIL_ABSENT_TTL_SECONDS++[email protected]_as_current_span("template.has_person_email")+def get_has_person_email(team: "Team") -> bool:+ from posthog.models import PropertyDefinition++ from products.event_definitions.backend.models.property_definition import PERSON_EMAIL_PROPERTY_NAME++ cache_key = _has_person_email_cache_key(team.project_id)+ cached = get_safe_cache(cache_key)+ if cached is not None:+ return cached++ has_person_email = (+ PropertyDefinition.objects.alias(+ effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())+ )+ .filter(+ effective_project_id=team.project_id, type=PropertyDefinition.Type.PERSON, name=PERSON_EMAIL_PROPERTY_NAME+ )+ .exists()+ )++ safe_cache_set(cache_key, has_person_email, timeout=_has_person_email_ttl(team, has_person_email))++ return has_person_email+++def invalidate_has_person_email_cache(project_id: int) -> None:+ safe_cache_delete(_has_person_email_cache_key(project_id))++@tracer.start_as_current_span("template.frontend_apps")def get_frontend_apps(team_id: int) -> dict[int, dict[str, Any]]:from products.cdp.backend.models.plugin import Plugin, PluginSourceFilediff --git a/products/event_definitions/backend/models/property_definition.py b/products/event_definitions/backend/models/property_definition.pyindex 1cbf932ee5f4..2e893e90aa04 100644--- a/products/event_definitions/backend/models/property_definition.py+++ b/products/event_definitions/backend/models/property_definition.py@@ -1,11 +1,16 @@from django.contrib.postgres.indexes import GinIndex-from django.db import models+from django.db import models, transactionfrom django.db.models.expressions import Ffrom django.db.models.functions import Coalesce+from django.db.models.signals import post_save+from django.dispatch import receiverfrom posthog.clickhouse.table_engines import ReplacingMergeTree, ReplicationSchemefrom posthog.models.utils import UniqueConstraintByExpression, UUIDTModelfrom posthog.settings.data_stores import CLICKHOUSE_DATABASE+from posthog.utils import invalidate_has_person_email_cache++PERSON_EMAIL_PROPERTY_NAME = "email"class PropertyType(models.TextChoices):@@ -131,6 +136,18 @@ class PropertyDefinition(UUIDTModel):return None+# Deliberately no post_delete receiver: any delete listener on PropertyDefinition would+# disable Django's fast-path cascade delete for this very large table (team/project/org+# deletion), and delete staleness is already bounded by the cache TTLs.+@receiver(post_save, sender=PropertyDefinition)+def _invalidate_has_person_email_on_save(+ sender: type[PropertyDefinition], instance: PropertyDefinition, **kwargs+) -> None:+ if instance.type == PropertyDefinition.Type.PERSON and instance.name == PERSON_EMAIL_PROPERTY_NAME:+ project_id = instance.project_id or instance.team_id+ transaction.on_commit(lambda: invalidate_has_person_email_cache(project_id))++# ClickHouse Table DDLPROPERTY_DEFINITIONS_TABLE_SQL = lambda: (