: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
fix(retention): stop the persons modal crashing on a stale cohort row (#82001)
Christiaan Hendriksenbcef214681ad
diff --git a/frontend/src/scenes/retention/RetentionModal.tsx b/frontend/src/scenes/retention/RetentionModal.tsxindex 2fd5d29d131b..b7dae7a0f760 100644--- a/frontend/src/scenes/retention/RetentionModal.tsx+++ b/frontend/src/scenes/retention/RetentionModal.tsx@@ -23,20 +23,19 @@ import { MAX_SELECT_RETURNED_ROWS, startDownload } from '~/queries/nodes/DataTabimport { DataTableNode, NodeKind } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, ExporterFormat } from '~/types'-import { retentionLogic } from './retentionLogic'import { retentionModalLogic } from './retentionModalLogic'import { retentionPeopleLogic } from './retentionPeopleLogic'import { formatRetentionCohortLabel } from './utils'export function RetentionModal(): JSX.Element | null {const { insightProps } = useValues(insightLogic)- const { results } = useValues(retentionLogic(insightProps))const { people, peopleLoading, peopleLoadingMore } = useValues(retentionPeopleLogic(insightProps))const { loadMorePeople } = useActions(retentionPeopleLogic(insightProps))const {aggregationTargetLabel,selectedInterval,selectedBreakdownValue,+ selectedRow: row,exploreUrl,insightEventsQueryUrl,actorsQuery,@@ -62,23 +61,10 @@ export function RetentionModal(): JSX.Element | null {}: undefined- if (!results || selectedInterval === null) {+ if (selectedInterval === null || !row) {return null}- // Find the correct row based on both selectedInterval and selectedBreakdownValue- const row =- selectedBreakdownValue !== null- ? (() => {- // Get the target date from the selected interval in the non-breakdown results- const targetLabel = results[selectedInterval]?.label- // Find the row with matching breakdown value and date label- return (- results.find((r) => r.breakdown_value === selectedBreakdownValue && r.label === targetLabel) ||- results[selectedInterval]- )- })()- : results[selectedInterval]const rowLength = row.values.lengthconst isEmpty = row.values[0]?.count === 0diff --git a/frontend/src/scenes/retention/retentionModalLogic.test.ts b/frontend/src/scenes/retention/retentionModalLogic.test.tsnew file mode 100644index 000000000000..10ce7800c378--- /dev/null+++ b/frontend/src/scenes/retention/retentionModalLogic.test.ts@@ -0,0 +1,191 @@+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 { InsightLogicProps, InsightModel, RetentionPeriod } from '~/types'++import { retentionLogic } from './retentionLogic'+import { retentionModalLogic } from './retentionModalLogic'++const insightProps: InsightLogicProps = {+ dashboardItemId: undefined,+}++const retentionQuery: RetentionQuery = {+ kind: NodeKind.RetentionQuery,+ retentionFilter: {+ period: RetentionPeriod.Day,+ targetEntity: { id: '$pageview', type: 'events' },+ returningEntity: { id: '$pageview', type: 'events' },+ },+}++const cohortRow = (+ label: string,+ count: number,+ breakdownValue?: string+): Record<string, string | number | Record<string, number>[]> => ({+ date: '2024-01-01T00:00:00Z',+ label,+ values: [{ count }, { count }],+ ...(breakdownValue !== undefined ? { breakdown_value: breakdownValue } : {}),+})++const fourCohorts = [cohortRow('Day 0', 100), cohortRow('Day 1', 90), cohortRow('Day 2', 80), cohortRow('Day 3', 70)]++// Two breakdown groups, each with the same interval labels, as the query runner emits them+const twoBreakdownGroups = [+ cohortRow('Day 0', 100, 'Chrome'),+ cohortRow('Day 1', 90, 'Chrome'),+ cohortRow('Day 0', 50, 'Firefox'),+ cohortRow('Day 1', 40, 'Firefox'),+]++let logic: ReturnType<typeof retentionModalLogic.build>++describe('retentionModalLogic', () => {+ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/cohorts/': { count: 0, results: [] },+ '/api/environments/:team_id/data_color_themes/': [],+ },+ post: {+ '/api/environments/:team_id/query/': { results: [], columns: [] },+ },+ })+ initKeaTests(false)+ teamLogic.mount()+ await expectLogic(teamLogic).toFinishAllListeners()++ dataNodeLogic({ key: 'InsightViz.new', query: {} as DataNode }).mount()++ logic = retentionModalLogic(insightProps)+ logic.mount()+ })++ async function loadResults(result: Record<string, any>[]): Promise<void> {+ await expectLogic(logic, () => {+ retentionLogic(insightProps).actions.updateQuerySource(retentionQuery)+ // 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: retentionQuery as DataNode,+ cachedResults: { result } as Partial<InsightModel>,+ })+ }).toFinishAllListeners()+ }++ it.each([+ {+ name: 'resolves the row at the selected index',+ rows: fourCohorts,+ rowIndex: 1,+ breakdownValue: undefined,+ expectedCount: 90,+ },+ {+ name: 'resolves null when the selected index is past the end of the results',+ rows: [cohortRow('Day 0', 100), cohortRow('Day 1', 90)],+ rowIndex: 3,+ breakdownValue: undefined,+ expectedCount: null,+ },+ {+ name: 'resolves null when the results are empty',+ rows: [],+ rowIndex: 0,+ breakdownValue: undefined,+ expectedCount: null,+ },+ {+ name: 'resolves the row at the selected index within the breakdown group',+ rows: twoBreakdownGroups,+ rowIndex: 1,+ breakdownValue: 'Firefox',+ expectedCount: 40,+ },+ {+ name: 'resolves null when the index is past the end of the breakdown group',+ rows: twoBreakdownGroups,+ rowIndex: 3,+ breakdownValue: 'Firefox',+ expectedCount: null,+ },+ {+ name: 'resolves null when the selected breakdown value is absent',+ rows: twoBreakdownGroups,+ rowIndex: 0,+ breakdownValue: 'Safari',+ expectedCount: null,+ },+ ])('$name', async ({ rows, rowIndex, breakdownValue, expectedCount }) => {+ await loadResults(rows)++ await expectLogic(logic, () => {+ logic.actions.openModal(rowIndex, breakdownValue)+ }).toFinishAllListeners()++ if (expectedCount === null) {+ expect(logic.values.selectedRow).toBeNull()+ } else {+ expect(logic.values.selectedRow?.values[0].count).toBe(expectedCount)+ }+ })++ it('closes the modal when the reloaded results no longer contain the selected row', async () => {+ await loadResults(fourCohorts)+ await expectLogic(logic, () => {+ logic.actions.openModal(3)+ }).toFinishAllListeners()+ expect(logic.values.selectedRow?.values[0].count).toBe(70)++ await loadResults([cohortRow('Day 0', 100), cohortRow('Day 1', 90)])++ expect(logic.values.selectedInterval).toBeNull()+ expect(logic.values.selectedRow).toBeNull()+ })++ it('keeps the modal open when the reloaded results still contain the selected row', async () => {+ await loadResults(fourCohorts)+ await expectLogic(logic, () => {+ logic.actions.openModal(1)+ }).toFinishAllListeners()++ await loadResults([cohortRow('Day 0', 10), cohortRow('Day 1', 9), cohortRow('Day 2', 8)])++ expect(logic.values.selectedInterval).toBe(1)+ expect(logic.values.selectedRow?.values[0].count).toBe(9)+ })++ it('closes the modal when the results come back empty', async () => {+ await loadResults(fourCohorts)+ await expectLogic(logic, () => {+ logic.actions.openModal(3)+ }).toFinishAllListeners()++ await loadResults([])++ expect(logic.values.selectedInterval).toBeNull()+ expect(logic.values.selectedRow).toBeNull()+ })++ it('closes the modal when the selected breakdown value disappears', async () => {+ await loadResults(twoBreakdownGroups)+ await expectLogic(logic, () => {+ logic.actions.openModal(1, 'Firefox')+ }).toFinishAllListeners()+ expect(logic.values.selectedRow?.values[0].count).toBe(40)++ await loadResults([cohortRow('Day 0', 100, 'Chrome'), cohortRow('Day 1', 90, 'Chrome')])++ expect(logic.values.selectedInterval).toBeNull()+ expect(logic.values.selectedRow).toBeNull()+ })+})diff --git a/frontend/src/scenes/retention/retentionModalLogic.ts b/frontend/src/scenes/retention/retentionModalLogic.tsindex be30a1ceb8dc..63e0048a025c 100644--- a/frontend/src/scenes/retention/retentionModalLogic.ts+++ b/frontend/src/scenes/retention/retentionModalLogic.ts@@ -1,5 +1,6 @@import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { router } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'import { lemonToast } from '@posthog/lemon-ui'@@ -8,6 +9,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { retentionToActorsQuery } from 'scenes/retention/queries'+import { ProcessedRetentionPayload } from 'scenes/retention/types'import { urls } from 'scenes/urls'import { cohortsModel } from '~/models/cohortsModel'@@ -35,6 +37,7 @@ import type {WebStatsTableQuery,} from '../../queries/schema/schema-general'import type { PathsV2Query } from '../../queries/schema/schema-general'+import { retentionLogic } from './retentionLogic'import { retentionPeopleLogic } from './retentionPeopleLogic'const DEFAULT_RETENTION_LOGIC_KEY = 'default_retention_key'@@ -56,6 +59,7 @@ export interface retentionModalLogicValues {| null // insightVizDataLogicretentionFilter: RetentionFilter | null // insightVizDataLogictheme: DataColorTheme | null // insightVizDataLogic+ results: ProcessedRetentionPayload[] // retentionLogicactorsQuery: ActorsQuery | nullaggregationTargetLabel: NounexploreUrl: string | null@@ -64,6 +68,7 @@ export interface retentionModalLogicValues {selectedBreakdownValue: number | string | nullselectedColumnIndex: number | nullselectedInterval: number | null+ selectedRow: ProcessedRetentionPayload | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -130,6 +135,11 @@ export interface retentionModalLogicMeta {) => ActorsQuery | nullinsightEventsQueryUrl: (actorsQuery: ActorsQuery | null) => string | nullexploreUrl: (actorsQuery: ActorsQuery | null) => string | null+ selectedRow: (+ results: ProcessedRetentionPayload[],+ selectedInterval: number | null,+ selectedBreakdownValue: number | string | null+ ) => ProcessedRetentionPayload | null}}@@ -148,6 +158,8 @@ export const retentionModalLogic = kea<retentionModalLogicType>([values: [insightVizDataLogic(props),['querySource', 'retentionFilter', 'theme'],+ retentionLogic(props),+ ['results'],groupsModel,['aggregationLabel'],featureFlagLogic,@@ -294,7 +306,32 @@ export const retentionModalLogic = kea<retentionModalLogicType>([return urls.insightNew({ query })},],+ selectedRow: [+ (s) => [s.results, s.selectedInterval, s.selectedBreakdownValue],+ (+ results: ProcessedRetentionPayload[],+ selectedInterval: number | null,+ selectedBreakdownValue: number | string | null+ ): ProcessedRetentionPayload | null => {+ if (selectedInterval === null) {+ return null+ }+ // The clicked index is relative to the rows of one breakdown, not to the flat results+ const rows =+ selectedBreakdownValue === null+ ? results+ : results.filter((r) => r.breakdown_value === selectedBreakdownValue)+ return rows[selectedInterval] ?? null+ },+ ],}),+ subscriptions(({ actions, values }) => ({+ results: () => {+ if (values.selectedInterval !== null && !values.selectedRow) {+ actions.closeModal()+ }+ },+ })),listeners(({ actions, values }) => ({openModal: ({ rowIndex, breakdownValue }: { rowIndex: number; breakdownValue?: string | number | null }) => {actions.loadPeople(rowIndex, breakdownValue)