: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(retention): explain all-empty results with property filters (#78614)
jake sciotto1805924a6a3a
diff --git a/frontend/src/scenes/retention/RetentionContainer.tsx b/frontend/src/scenes/retention/RetentionContainer.tsxindex 1b090bc01e48..b92f4b23a44e 100644--- a/frontend/src/scenes/retention/RetentionContainer.tsx+++ b/frontend/src/scenes/retention/RetentionContainer.tsx@@ -8,6 +8,7 @@ import { InsightVizNode, VizSpecificOptions } from '~/queries/schema/schema-geneimport { QueryContext } from '~/queries/types'import { InsightType, RetentionDashboardDisplayType } from '~/types'+import { RetentionEmptyResultsBanner } from './RetentionEmptyResultsBanner'import { RetentionGraph } from './RetentionGraph'import { retentionLogic } from './retentionLogic'import { RetentionModal } from './RetentionModal'@@ -38,6 +39,7 @@ export function RetentionContainer({return (<div className="RetentionContainer">+ {!inCardView && !inSharedMode && <RetentionEmptyResultsBanner />}{showLineGraph && (<div className="RetentionContainer__graph"><RetentionGraph inSharedMode={inSharedMode} />diff --git a/frontend/src/scenes/retention/RetentionEmptyResultsBanner.tsx b/frontend/src/scenes/retention/RetentionEmptyResultsBanner.tsxnew file mode 100644index 000000000000..7404b42e8cb5--- /dev/null+++ b/frontend/src/scenes/retention/RetentionEmptyResultsBanner.tsx@@ -0,0 +1,56 @@+import { useValues } from 'kea'++import { LemonBanner } from '@posthog/lemon-ui'++import {+ RETENTION_FIRST_EVER_OCCURRENCE,+ RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS,+ RETENTION_RECURRING,+} from 'lib/constants'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { retentionOptions } from './constants'+import { retentionLogic } from './retentionLogic'++/** Explains why every cohort is empty when the events have property filters, which is+ * usually filter values matching no events, or first-time retention anchoring semantics. */+export function RetentionEmptyResultsBanner(): JSX.Element | null {+ const { insightProps } = useValues(insightLogic)+ const { insightDataLoading } = useValues(insightVizDataLogic(insightProps))+ const { allCohortsEmpty, hasEntityPropertyFilters, retentionFilter } = useValues(retentionLogic(insightProps))++ if (insightDataLoading || !allCohortsEmpty || !hasEntityPropertyFilters) {+ return null+ }++ const retentionType = retentionFilter?.retentionType ?? RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS+ const firstMatchingLabel = retentionOptions[RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS]+ const firstEverLabel = retentionOptions[RETENTION_FIRST_EVER_OCCURRENCE]+ const recurringLabel = retentionOptions[RETENTION_RECURRING]++ let message: string+ if (retentionType === RETENTION_FIRST_EVER_OCCURRENCE) {+ message =+ `No users match these filters. With "${firstEverLabel}" retention, a user only counts if the very ` ++ `first time they ever performed the event matches your property filters. Users whose first ` ++ `occurrence didn't match are excluded entirely. Switch the retention type to "${firstMatchingLabel}" ` ++ `to count users from when your filters first match, or check that your property values match your data.`+ } else if (retentionType === RETENTION_RECURRING) {+ message =+ 'No users match these filters in this date range. Check that your property values match your data, ' ++ 'or widen the date range.'+ } else {+ message =+ `No users match these filters. With "${firstMatchingLabel}" retention, users are counted from their ` ++ `first event that matches your property filters. If that first match happened before this date range, ` ++ `they won't appear here. Widen the date range, switch the retention type to "${recurringLabel}" to ` ++ `count every matching event, or check that your property values match your data.`+ }++ return (+ <LemonBanner type="info" className="mb-4">+ {message}+ </LemonBanner>+ )+}diff --git a/frontend/src/scenes/retention/retentionLogic.test.ts b/frontend/src/scenes/retention/retentionLogic.test.tsnew file mode 100644index 000000000000..c3beb5e0b177--- /dev/null+++ b/frontend/src/scenes/retention/retentionLogic.test.ts@@ -0,0 +1,130 @@+import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { DataNode, NodeKind, RetentionQuery } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import {+ AnyPropertyFilter,+ InsightLogicProps,+ InsightModel,+ PropertyFilterType,+ PropertyOperator,+ RetentionPeriod,+} from '~/types'++import { retentionLogic } from './retentionLogic'++const insightProps: InsightLogicProps = {+ dashboardItemId: undefined,+}++const browserFilter: AnyPropertyFilter = {+ key: '$browser',+ value: ['Chrome'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+}++const cohortRow = (date: string, counts: number[]): Record<string, any> => ({+ date,+ label: 'Day 0',+ values: counts.map((count) => ({ count })),+})++const retentionQuery = ({+ targetProperties,+ returningProperties,+}: {+ targetProperties?: AnyPropertyFilter[]+ returningProperties?: AnyPropertyFilter[]+} = {}): RetentionQuery => ({+ kind: NodeKind.RetentionQuery,+ retentionFilter: {+ period: RetentionPeriod.Day,+ targetEntity: { id: '$pageview', type: 'events', properties: targetProperties },+ returningEntity: { id: '$pageview', type: 'events', properties: returningProperties },+ },+})++let logic: ReturnType<typeof retentionLogic.build>++describe('retentionLogic', () => {+ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/cohorts/': { count: 0, results: [] },+ '/api/environments/:team_id/data_color_themes/': [],+ },+ })+ initKeaTests(false)+ teamLogic.mount()+ await expectLogic(teamLogic).toFinishAllListeners()++ dataNodeLogic({ key: 'InsightViz.new', query: {} as DataNode }).mount()++ logic = retentionLogic(insightProps)+ logic.mount()+ })++ async function loadResults(query: RetentionQuery, result: Record<string, any>[]): Promise<void> {+ await expectLogic(logic, () => {+ logic.actions.updateQuerySource(query)+ // Rebuilding with the query as props mirrors how InsightViz passes the source query+ // down; retentionLogic.results gates on it. cachedResults set the response without+ // a network round-trip.+ dataNodeLogic({+ key: 'InsightViz.new',+ query: query as DataNode,+ cachedResults: { result } as Partial<InsightModel>,+ })+ }).toFinishAllListeners()+ }++ // These two selectors gate RetentionEmptyResultsBanner: a regression in either silently+ // removes the explanation shown when property filters empty out every cohort.+ it.each([+ {+ name: 'all-zero cohorts with a target entity property filter',+ query: retentionQuery({ targetProperties: [browserFilter] }),+ rows: [cohortRow('2024-01-01T00:00:00Z', [0, 0]), cohortRow('2024-01-02T00:00:00Z', [0, 0])],+ allCohortsEmpty: true,+ hasEntityPropertyFilters: true,+ },+ {+ name: 'a non-empty cohort with a target entity property filter',+ query: retentionQuery({ targetProperties: [browserFilter] }),+ rows: [cohortRow('2024-01-01T00:00:00Z', [100, 50]), cohortRow('2024-01-02T00:00:00Z', [0, 0])],+ allCohortsEmpty: false,+ hasEntityPropertyFilters: true,+ },+ {+ name: 'all-zero cohorts without entity property filters',+ query: retentionQuery(),+ rows: [cohortRow('2024-01-01T00:00:00Z', [0, 0])],+ allCohortsEmpty: true,+ hasEntityPropertyFilters: false,+ },+ {+ name: 'a returning entity property filter only',+ query: retentionQuery({ returningProperties: [browserFilter] }),+ rows: [cohortRow('2024-01-01T00:00:00Z', [0, 0])],+ allCohortsEmpty: true,+ hasEntityPropertyFilters: true,+ },+ {+ name: 'no results',+ query: retentionQuery({ targetProperties: [browserFilter] }),+ rows: [],+ allCohortsEmpty: false,+ hasEntityPropertyFilters: true,+ },+ ])('$name', async ({ query, rows, allCohortsEmpty, hasEntityPropertyFilters }) => {+ await loadResults(query, rows)++ expect(logic.values.allCohortsEmpty).toBe(allCohortsEmpty)+ expect(logic.values.hasEntityPropertyFilters).toBe(hasEntityPropertyFilters)+ })+})diff --git a/frontend/src/scenes/retention/retentionLogic.ts b/frontend/src/scenes/retention/retentionLogic.tsindex 1fb75a3ebdba..a6b97d1f04d5 100644--- a/frontend/src/scenes/retention/retentionLogic.ts+++ b/frontend/src/scenes/retention/retentionLogic.ts@@ -77,6 +77,7 @@ export interface retentionLogicValues {| null // insightVizDataLogicretentionFilter: RetentionFilter | null // insightVizDataLogictimezone: string // teamLogic+ allCohortsEmpty: booleanbreakdownDisplayNames: Record<string, string>breakdownValues: (number | string | null | undefined)[]dateMappings: DateMappingOption[]@@ -89,6 +90,7 @@ export interface retentionLogicValues {rawBreakdownValue: number | string | null | undefined,seriesIndex: number) => [DataColorTheme | null, DataColorToken | null]+ hasEntityPropertyFilters: booleanhasValidBreakdown: booleanisPropertyValueAggregation: booleanisRetentionDWHEnabled: boolean@@ -142,6 +144,8 @@ export interface retentionLogicMeta {hasValidBreakdown: (breakdownFilter: BreakdownFilter | null | undefined) => booleanisRetentionDWHEnabled: (featureFlags: FeatureFlagsSet) => booleanisPropertyValueAggregation: (retentionFilter: RetentionFilter | null) => boolean+ hasEntityPropertyFilters: (retentionFilter: RetentionFilter | null) => boolean+ allCohortsEmpty: (results: ProcessedRetentionPayload[]) => booleanresults: (insightQuery: DataNode<Record<string, any>>,insightData: Record<string, any>,@@ -339,6 +343,19 @@ export const retentionLogic = kea<retentionLogicType>([(retentionFilter: RetentionFilter | undefined) =>retentionFilter?.aggregationType === 'sum' || retentionFilter?.aggregationType === 'avg',],+ hasEntityPropertyFilters: [+ (s) => [s.retentionFilter],+ (retentionFilter: RetentionFilter | null): boolean =>+ [retentionFilter?.targetEntity, retentionFilter?.returningEntity].some(+ (entity) => (entity?.properties?.length ?? 0) > 0+ ),+ ],+ allCohortsEmpty: [+ (s) => [s.results],+ // values[0] is interval 0, i.e. the cohort's size+ (results: ProcessedRetentionPayload[]): boolean =>+ results.length > 0 && results.every((result) => (result.values[0]?.count ?? 0) === 0),+ ],results: [(s) => [s.insightQuery, s.insightData, s.retentionFilter, s.timezone, s.isPropertyValueAggregation],(