: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
chore(marketing): remove unused cohort explorer frontend (#101570)
Javier Bahamondescfb50fa1c036
diff --git a/docs/internal/marketing-retention-summary.md b/docs/internal/marketing-retention-summary.mdindex e4c976e1d792..717e0bcbcaf0 100644--- a/docs/internal/marketing-retention-summary.md+++ b/docs/internal/marketing-retention-summary.md@@ -1,6 +1,6 @@# Marketing retention summary-Retention opens with a source table of users, return rates within 7 and 30 days, and median days to a second session. The volume column is labeled New users when Only new users is enabled and Users otherwise. It displays its count and share on one line at wider widths. The interface exposes only the summary. The cohort implementation remains in code temporarily, without a navigation control.+Retention opens with a source table of users, return rates within 7 and 30 days, and median days to a second session. The volume column is labeled New users when Only new users is enabled and Users otherwise. It displays its count and share on one line at wider widths. The interface exposes only the summary. The legacy cohort frontend is removed.## Definitions@@ -16,6 +16,6 @@ Comparison is enabled by default and can be disabled with the comparison selectoSummary mode adds optional fields to the existing retention query and response. Callers that omit summary mode retain the cohort response. The summary materializes acquisition and per-person return results within one query, including comparison. Return events are joined to each acquisition window before aggregation, and the median uses ClickHouse's bounded reservoir. The table defaults to current acquisition volume, and sources are selected by that volume; the tail is folded before computing the median. User shares include the folded Other row.-The cohort renderer and query mode remain in code temporarily. A separate draft can remove the unused frontend while retaining the backend contract for existing query callers. That cleanup must be reviewed independently.+The legacy cohort renderer, summary helpers, and frontend controls are removed. The backend cohort query mode remains compatible with existing callers. This cleanup is a separate draft and must be reviewed independently before merging.This mode measures session returns. Conversion-goal retention is a separate behavior and needs an explicit definition before sharing these fixed-window summary metrics. There is no dedicated retention precompute path.diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionCohortTable.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionCohortTable.tsxdeleted file mode 100644index 303e6d88844e..000000000000--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionCohortTable.tsx+++ /dev/null@@ -1,260 +0,0 @@-import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'--import { IconInfo } from '@posthog/icons'-import { LemonCollapse, LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'--import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'-import { gradateColor } from 'lib/utils/colors'-import { parseDateInTimezone } from 'lib/utils/datetime'-import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'-import { InsightErrorState } from 'scenes/insights/EmptyStates'-import { teamLogic } from 'scenes/teamLogic'--import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import {- MarketingAnalyticsRetentionInterval,- MarketingAnalyticsRetentionQuery,- MarketingAnalyticsRetentionQueryResponse,- MarketingAnalyticsRetentionRow,-} from '~/queries/schema/schema-general'--import { RetentionReturnTable } from 'products/marketing_analytics/frontend/retention/RetentionReturnTable'--import { BREAKDOWN_LABELS, displayBreakdownValue, isFoldedBreakdownValue } from '../../logic/marketingBreakdown'-import {- MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,- marketingRetentionLogic,-} from '../../logic/marketingRetentionLogic'-import { RetentionSummaryTable } from './RetentionSummaryTable'--const EXPANDED_BY_DEFAULT = 3--/** Same values as PostHog's retention table, so a rate reads as the same shade on both. */-const CELL_COLOR = '#1d4aff'-const CELL_COLOR_FLOOR = 0.1-/** Past this the background is dark enough that the theme's text fails WCAG AA. */-const CELL_TEXT_LIGHT_THRESHOLD = 0.4--/** In the team's timezone: a UTC cohort read from New York would be labelled with the previous day. */-const cohortLabel = (isoDate: string, interval: MarketingAnalyticsRetentionInterval, timezone: string): string => {- const date = parseDateInTimezone(isoDate, timezone)- switch (interval) {- case MarketingAnalyticsRetentionInterval.Month:- return date.format('MMM YYYY')- case MarketingAnalyticsRetentionInterval.Week:- return `${date.format('MMM D')} to ${date.add(6, 'day').format('MMM D')}`- default:- return date.format('ddd, MMM D')- }-}--// Stable, because `useAttachedLogic` only detaches when the scene unmounts. An incrementing key leaves-// a fresh dataNodeLogic attached on every visit to the tab, and the filter bar's ReloadAll then re-runs-// each earlier visit's stale query on top of the live one.-const RETENTION_DATA_NODE_KEY = 'MarketingRetention'--export function RetentionCohortTable({- query,- attachTo,-}: {- query: MarketingAnalyticsRetentionQuery- attachTo?: LogicWrapper | BuiltLogic-}): JSX.Element {- const logic = dataNodeLogic({- query,- key: RETENTION_DATA_NODE_KEY,- dataNodeCollectionId: MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,- })- const { response, responseLoading, responseError } = useValues(logic)- const { loadData } = useActions(logic)- const { breakdownBy } = useValues(marketingRetentionLogic)- const { timezone } = useValues(teamLogic)- useAttachedLogic(logic, attachTo)-- const retentionResponse = response as MarketingAnalyticsRetentionQueryResponse | undefined- const rows = retentionResponse?.results ?? []- const labels = retentionResponse?.labels ?? []- const interval = retentionResponse?.interval ?? MarketingAnalyticsRetentionInterval.Week- const dimensionLabel = BREAKDOWN_LABELS[breakdownBy]-- const caveats: string[] = []- if (retentionResponse?.truncatedCohorts) {- caveats.push(- `The ${humanFriendlyNumber(retentionResponse.truncatedCohorts)} earliest periods in your date range aren't included. Narrow the range, or group by a longer period, to see them.`- )- }- if (retentionResponse?.otherBreakdownCount) {- caveats.push(- `"Other" groups the smallest ${humanFriendlyNumber(retentionResponse.otherBreakdownCount)} values.`- )- }-- if (responseError) {- return <InsightErrorState query={query} onRetry={loadData} />- }-- if (query.summary) {- return (- <RetentionReturnTable- rows={retentionResponse?.summary ?? []}- dimensionLabel={dimensionLabel}- loading={responseLoading || !retentionResponse}- compare={query.comparePreviousPeriod ?? false}- onlyNewUsers={query.onlyNewUsers ?? true}- />- )- }-- const columns: LemonTableColumn<MarketingAnalyticsRetentionRow, any>[] = [- {- title: 'Cohort',- tooltip: "The period a person's first session landed in. People stay in the same row for the whole table.",- dataIndex: 'cohortDate',- render: (_, row) => cohortLabel(row.cohortDate, interval, timezone),- },- {- title: 'Acquired',- tooltip: `How many people had their first session of the date range in this period, credited to that session's ${dimensionLabel.toLowerCase()}. Each person is counted once. Options changes which sessions qualify and who counts as new.`,- dataIndex: 'cohortSize',- align: 'right',- render: (_, row) => humanFriendlyNumber(row.cohortSize),- },- ...labels.map((label, index) => ({- title: label,- tooltip:- "The share of this cohort seen again in this period, measured against the cohort's original size, not against the period before.",- key: label,- align: 'center' as const,- render: (_: any, row: MarketingAnalyticsRetentionRow) => {- const cell = row.values[index]- if (!cell) {- return null- }- if (!cell.complete) {- return (- <Tooltip title="This period hasn't finished yet, so there's nothing to measure.">- <span className="text-muted">–</span>- </Tooltip>- )- }- return (- <Tooltip title={`${humanFriendlyNumber(cell.count)} of ${humanFriendlyNumber(row.cohortSize)}`}>- <div- className="rounded px-2 py-1"- // eslint-disable-next-line react/forbid-dom-props- style={{- backgroundColor: gradateColor(CELL_COLOR, cell.rate ?? 0, CELL_COLOR_FLOOR),- color: (cell.rate ?? 0) > CELL_TEXT_LIGHT_THRESHOLD ? '#fff' : 'var(--text-3000)',- }}- >- {cell.rate === null ? '–' : percentage(cell.rate, 1)}- </div>- </Tooltip>- )- },- })),- ]-- const byBreakdown = new Map<string, MarketingAnalyticsRetentionRow[]>()- for (const row of rows) {- byBreakdown.set(row.breakdownValue, [...(byBreakdown.get(row.breakdownValue) ?? []), row])- }- // "Other" is a sum of the tail, so ranking it by size floats it above real channels.- const breakdownValues = [...byBreakdown.keys()].sort((a, b) => {- if (isFoldedBreakdownValue(a) !== isFoldedBreakdownValue(b)) {- return isFoldedBreakdownValue(a) ? 1 : -1- }- return totalAcquired(byBreakdown.get(b)) - totalAcquired(byBreakdown.get(a))- })-- if (responseLoading || !breakdownValues.length) {- return (- <LemonTable- columns={columns}- dataSource={[]}- loading={responseLoading}- emptyState='No new users arrived in this period. Widen the date range, or turn off "Only new users" to include people who were already here.'- />- )- }-- return (- <div className="flex flex-col gap-4">- {caveats.length > 0 && <div className="text-secondary text-xs">{caveats.join(' ')}</div>}- <RetentionSummaryTable rows={rows} labels={labels} dimensionLabel={dimensionLabel} />- <div>- <div className="text-muted mb-1 flex flex-wrap items-center gap-1 text-xs font-semibold uppercase">- <span>All {dimensionLabel.toLowerCase()}s</span>- <Tooltip- title={`Every ${dimensionLabel.toLowerCase()} added together. People and returns are summed per cohort and the rate is recalculated, so a ${dimensionLabel.toLowerCase()} with ten thousand people counts for more than one with ten. It is not an average of the rates below.`}- >- <IconInfo className="text-base" />- </Tooltip>- </div>- <LemonTable columns={columns} dataSource={baselineRows(rows)} size="small" firstColumnSticky />- </div>- <LemonCollapse- multiple- defaultActiveKeys={breakdownValues.slice(0, EXPANDED_BY_DEFAULT)}- panels={breakdownValues.map((value) => ({- key: value,- header: (- <div className="flex items-center gap-2">- <span className="font-semibold">{displayBreakdownValue(value, dimensionLabel)}</span>- <span className="text-secondary text-xs">- {humanFriendlyNumber(totalAcquired(byBreakdown.get(value)))} acquired- </span>- </div>- ),- content: (- <LemonTable- columns={columns}- dataSource={byBreakdown.get(value) ?? []}- loading={responseLoading}- size="small"- firstColumnSticky- />- ),- }))}- />- </div>- )-}--const totalAcquired = (rows: MarketingAnalyticsRetentionRow[] | undefined): number =>- (rows ?? []).reduce((total, row) => total + row.cohortSize, 0)--/**- * Rates are recomputed from the summed counts, because averaging per-channel rates would weight a- * channel with ten people the same as one with ten thousand.- */-export function baselineRows(rows: MarketingAnalyticsRetentionRow[]): MarketingAnalyticsRetentionRow[] {- const byCohort = new Map<number, MarketingAnalyticsRetentionRow>()- for (const row of rows) {- const merged = byCohort.get(row.cohortIndex)- if (!merged) {- byCohort.set(row.cohortIndex, {- ...row,- breakdownValue: '',- values: row.values.map((cell) => ({ ...cell })),- })- continue- }- merged.cohortSize += row.cohortSize- row.values.forEach((cell, index) => {- const into = merged.values[index]- if (into) {- into.count += cell.count- }- })- }- return [...byCohort.values()]- .sort((a, b) => a.cohortIndex - b.cohortIndex)- .map((row) => ({- ...row,- values: row.values.map((cell) => ({- ...cell,- rate: row.cohortSize ? cell.count / row.cohortSize : null,- })),- }))-}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionSummaryTable.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionSummaryTable.tsxdeleted file mode 100644index d7ef7675233c..000000000000--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionSummaryTable.tsx+++ /dev/null@@ -1,99 +0,0 @@-import { IconInfo } from '@posthog/icons'-import { LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'--import { gradateColor } from 'lib/utils/colors'-import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'--import { MarketingAnalyticsRetentionRow } from '~/queries/schema/schema-general'--import { displayBreakdownValue } from '../../logic/marketingBreakdown'-import { SUMMARY_PERIODS, SummaryRow, summarizeByBreakdown } from './summarizeByBreakdown'--/** Same values as the per-cohort tables, so a rate reads as the same shade in both. */-const CELL_COLOR = '#1d4aff'-const CELL_COLOR_FLOOR = 0.1-const CELL_TEXT_LIGHT_THRESHOLD = 0.4--export function RetentionSummaryTable({- rows,- labels,- dimensionLabel,-}: {- rows: MarketingAnalyticsRetentionRow[]- labels: string[]- dimensionLabel: string-}): JSX.Element {- const summary = summarizeByBreakdown(rows)-- const columns: LemonTableColumn<SummaryRow, any>[] = [- {- title: dimensionLabel,- dataIndex: 'breakdownValue',- render: (_, row) => (- <span className="font-semibold">{displayBreakdownValue(row.breakdownValue, dimensionLabel)}</span>- ),- },- {- title: 'Acquired',- tooltip: `How many people this ${dimensionLabel.toLowerCase()} acquired, added up across the cohorts shown in the tables below.`,- dataIndex: 'acquired',- align: 'right',- sorter: (a, b) => a.acquired - b.acquired,- render: (_, row) => humanFriendlyNumber(row.acquired),- },- ...labels.slice(0, SUMMARY_PERIODS).map((label, period) => ({- title: label,- tooltip:- 'The share of people who came back this many periods after arriving, pooled across cohorts and weighted by cohort size.',- key: label,- align: 'center' as const,- // -1 puts a period no cohort has reached below every real rate, rather than level with 0%.- defaultSortOrder: -1 as const,- sorter: (a: SummaryRow, b: SummaryRow) => (a.cells[period].rate ?? -1) - (b.cells[period].rate ?? -1),- render: (_: any, row: SummaryRow) => {- const cell = row.cells[period]- if (cell.rate === null) {- return (- <Tooltip title="No cohort has finished this period yet.">- <span className="text-muted">–</span>- </Tooltip>- )- }- return (- <Tooltip- title={`${humanFriendlyNumber(cell.returned)} of ${humanFriendlyNumber(cell.eligible)}, across ${cell.cohorts} ${cell.cohorts === 1 ? 'cohort' : 'cohorts'}`}- >- <div- className="rounded px-2 py-1"- // eslint-disable-next-line react/forbid-dom-props- style={{- backgroundColor: gradateColor(CELL_COLOR, cell.rate, CELL_COLOR_FLOOR),- color: cell.rate > CELL_TEXT_LIGHT_THRESHOLD ? '#fff' : 'var(--text-3000)',- }}- >- {percentage(cell.rate, 1)}- </div>- </Tooltip>- )- },- })),- ]-- return (- <div>- <div className="text-muted mb-1 flex flex-wrap items-center gap-1 text-xs font-semibold uppercase">- <span>Compare {dimensionLabel.toLowerCase()}s</span>- <Tooltip- title={`Every cohort of a ${dimensionLabel.toLowerCase()} blended into one row. People and returns are summed and the rate is recalculated, so this is not an average of the percentages below. A cohort of five thousand counts for more than one of fifty. "Other" is left out here.`}- >- <IconInfo className="text-base" />- </Tooltip>- </div>- <LemonTable columns={columns} dataSource={summary} size="small" firstColumnSticky />- <div className="text-secondary mt-1 text-xs">- Each column only counts cohorts that finished that period, so later columns rest on fewer people.- Compare within a column, not across.- </div>- </div>- )-}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab.tsxindex d81df9cce31c..ba10ccc2066c 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab.tsx@@ -10,21 +10,17 @@ import { dateMapping } from 'lib/utils/dateFilters'import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'import { ReloadAll } from '~/queries/nodes/DataNode/Reload'-import {- MarketingAnalyticsAttributionBreakdown,- MarketingAnalyticsRetentionInterval,-} from '~/queries/schema/schema-general'+import { MarketingAnalyticsAttributionBreakdown } from '~/queries/schema/schema-general'++import { RetentionResults } from 'products/marketing_analytics/frontend/retention/RetentionResults'import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { BREAKDOWN_LABELS } from '../../logic/marketingBreakdown'import {MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,- RETENTION_INTERVAL_LABELS,marketingRetentionLogic,} from '../../logic/marketingRetentionLogic'-import { RetentionCohortTable } from './RetentionCohortTable'-const COLUMN_COUNT_OPTIONS = [4, 6, 8, 12, 16, 24]const RETENTION_DATE_OPTIONS = dateMapping.filter(({ values }) =>['-7d', '-14d', '-30d', '-90d'].includes(values[0] ?? ''))@@ -33,8 +29,6 @@ export function RetentionTab(): JSX.Element {const {dateFilter,breakdownBy,- retentionInterval,- totalIntervals,excludeDirectTraffic,excludeUnattributed,onlyNewUsers,@@ -45,15 +39,12 @@ export function RetentionTab(): JSX.Element {const {setDates,setBreakdownBy,- setRetentionInterval,- setTotalIntervals,setExcludeDirectTraffic,setExcludeUnattributed,setOnlyNewUsers,setOptionsOpen,setComparePreviousPeriod,} = useActions(marketingRetentionLogic)- const showCohorts = falseconst optionsContent = (<div className="flex w-80 max-w-[90vw] flex-col gap-4 p-3"><div>@@ -70,31 +61,6 @@ export function RetentionTab(): JSX.Element {People acquired in this period are followed for return visits.</div></div>- {showCohorts && (- <>- <div>- <div className="text-muted mb-2 text-xs font-semibold uppercase">Period length</div>- <LemonSelect- fullWidth- value={retentionInterval}- onChange={(value) => value && setRetentionInterval(value)}- options={Object.values(MarketingAnalyticsRetentionInterval).map((value) => ({- value,- label: RETENTION_INTERVAL_LABELS[value],- }))}- />- </div>- <div>- <div className="text-muted mb-2 text-xs font-semibold uppercase">Periods to follow</div>- <LemonSelect- fullWidth- value={totalIntervals}- onChange={(value) => value && setTotalIntervals(value)}- options={COLUMN_COUNT_OPTIONS.map((count) => ({ value: count, label: `${count} periods` }))}- />- </div>- </>- )}<LemonDivider className="my-0" /><LemonSwitchfullWidth@@ -175,7 +141,7 @@ export function RetentionTab(): JSX.Element {}/><div className="mt-4 flex flex-col gap-4 pb-8">- <RetentionCohortTable query={query} attachTo={marketingAnalyticsLogic} />+ <RetentionResults query={query} attachTo={marketingAnalyticsLogic} /></div></div></BindLogic>diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/baselineRows.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/baselineRows.test.tsdeleted file mode 100644index 9af60e3179ce..000000000000--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/baselineRows.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { MarketingAnalyticsRetentionRow } from '~/queries/schema/schema-general'--import { baselineRows } from './RetentionCohortTable'--const row = (- breakdownValue: string,- cohortIndex: number,- cohortSize: number,- counts: number[]-): MarketingAnalyticsRetentionRow => ({- breakdownValue,- cohortDate: '2023-01-04T00:00:00Z',- cohortIndex,- cohortSize,- values: counts.map((count) => ({ count, rate: count / cohortSize, complete: true })),-})--describe('baselineRows', () => {- it('weights the combined rate by cohort size instead of averaging the channels', () => {- // A channel with 10 people retaining 100% and one with 1000 retaining 10% is a 10.9% baseline,- // not the 55% an average of the two rates would report.- const combined = baselineRows([row('small', 0, 10, [10]), row('big', 0, 1000, [100])])-- expect(combined).toHaveLength(1)- expect(combined[0].cohortSize).toBe(1010)- expect(combined[0].values[0].count).toBe(110)- expect(combined[0].values[0].rate).toBeCloseTo(110 / 1010)- })-- it('keeps cohorts apart while merging the channels within each one', () => {- const combined = baselineRows([- row('google', 0, 5, [5, 2]),- row('bing', 0, 5, [5, 4]),- row('google', 1, 8, [8, 1]),- ])-- expect(combined.map((r) => [r.cohortIndex, r.cohortSize])).toEqual([- [0, 10],- [1, 8],- ])- expect(combined[0].values[1].count).toBe(6)- })-- it('does not mutate the rows it was handed', () => {- // The same array backs the per-channel tables rendered next to the baseline, so merging in- // place would silently double the counts they show.- const source = [row('google', 0, 5, [5, 2]), row('bing', 0, 5, [5, 4])]-- baselineRows(source)-- expect(source[0].cohortSize).toBe(5)- expect(source[0].values[1].count).toBe(2)- })-})diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/summarizeByBreakdown.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/summarizeByBreakdown.test.tsdeleted file mode 100644index a6f92d9543af..000000000000--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/summarizeByBreakdown.test.ts+++ /dev/null@@ -1,81 +0,0 @@-import { BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'--import { MarketingAnalyticsRetentionRow } from '~/queries/schema/schema-general'--import { SUMMARY_PERIODS, summarizeByBreakdown } from './summarizeByBreakdown'--const row = (- breakdownValue: string,- cohortIndex: number,- cohortSize: number,- /** One entry per period. `null` is a period the cohort has not finished living through. */- counts: (number | null)[]-): MarketingAnalyticsRetentionRow => ({- breakdownValue,- cohortDate: '2026-08-02T00:00:00Z',- cohortIndex,- cohortSize,- values: Array.from({ length: SUMMARY_PERIODS }, (_, period) => {- const count = counts[period] ?? null- return {- count: count ?? 0,- rate: count === null ? null : count / cohortSize,- complete: count !== null,- }- }),-})--describe('summarizeByBreakdown', () => {- it('weights each period by cohort size rather than averaging the cohorts', () => {- // A 100-person cohort retaining 50% and a 900-person cohort retaining 10% is 14%, not the 30%- // an unweighted average of the two cohort rates would report.- const [summary] = summarizeByBreakdown([row('google', 0, 100, [100, 50]), row('google', 1, 900, [900, 90])])-- expect(summary.cells[1].returned).toBe(140)- expect(summary.cells[1].eligible).toBe(1000)- expect(summary.cells[1].rate).toBeCloseTo(0.14)- })-- it('leaves cohorts that have not finished a period out of that period entirely', () => {- // A zero from the unfinished cohort would deflate the column instead of being absent from it.- const [summary] = summarizeByBreakdown([row('google', 0, 100, [100, 40]), row('google', 1, 100, [100, null])])-- expect(summary.cells[0].cohorts).toBe(2)- expect(summary.cells[1].cohorts).toBe(1)- expect(summary.cells[1].eligible).toBe(100)- expect(summary.cells[1].rate).toBeCloseTo(0.4)- })-- it('reports no rate for a period no cohort has reached', () => {- const [summary] = summarizeByBreakdown([row('google', 0, 100, [100, null])])-- expect(summary.cells[2].rate).toBeNull()- expect(summary.cells[2].cohorts).toBe(0)- })-- it('ranks by how many people the value brought in', () => {- const summary = summarizeByBreakdown([row('small', 0, 10, [10]), row('big', 0, 500, [500])])-- expect(summary.map((s) => s.breakdownValue)).toEqual(['big', 'small'])- expect(summary[0].acquired).toBe(500)- })-- it('leaves the folded "Other" row out of the ranking', () => {- // Its 5000 would outrank every real channel, and it is a sum of the tail, not a channel.- const summary = summarizeByBreakdown([- row(BREAKDOWN_OTHER_STRING_LABEL, 0, 5000, [5000, 4000]),- row('google', 0, 100, [100, 50]),- ])-- expect(summary.map((s) => s.breakdownValue)).toEqual(['google'])- })-- it('does not mutate the rows the per-cohort tables also render', () => {- const source = [row('google', 0, 100, [100, 40])]-- summarizeByBreakdown(source)-- expect(source[0].cohortSize).toBe(100)- expect(source[0].values[1].count).toBe(40)- })-})diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/summarizeByBreakdown.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/summarizeByBreakdown.tsdeleted file mode 100644index 0ecfea302fb5..000000000000--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/summarizeByBreakdown.ts+++ /dev/null@@ -1,70 +0,0 @@-import { MarketingAnalyticsRetentionRow } from '~/queries/schema/schema-general'--import { isFoldedBreakdownValue } from '../../logic/marketingBreakdown'--export const SUMMARY_PERIODS = 5--export interface SummaryCell {- returned: number- /** Only cohorts that fully lived through this period, so an unfinished one can't deflate it. */- eligible: number- rate: number | null- cohorts: number-}--export interface SummaryRow {- breakdownValue: string- acquired: number- /** Always SUMMARY_PERIODS long. */- cells: SummaryCell[]-}--/**- * Rates are weighted by cohort size, so a week that acquired 50 people cannot swing a column as hard- * as one that acquired 5,000. The folded "Other" row is left out: it is a sum of the long tail, so- * ranking it against real channels floats a row nobody can act on above them.- */-export function summarizeByBreakdown(rows: MarketingAnalyticsRetentionRow[]): SummaryRow[] {- const byValue = new Map<string, SummaryRow>()-- for (const row of rows) {- if (isFoldedBreakdownValue(row.breakdownValue)) {- continue- }- let summary = byValue.get(row.breakdownValue)- if (!summary) {- summary = {- breakdownValue: row.breakdownValue,- acquired: 0,- cells: Array.from({ length: SUMMARY_PERIODS }, () => ({- returned: 0,- eligible: 0,- rate: null,- cohorts: 0,- })),- }- byValue.set(row.breakdownValue, summary)- }-- summary.acquired += row.cohortSize- row.values.slice(0, SUMMARY_PERIODS).forEach((cell, period) => {- if (!cell.complete) {- return- }- const into = summary.cells[period]- into.returned += cell.count- into.eligible += row.cohortSize- into.cohorts += 1- })- }-- return [...byValue.values()]- .map((summary) => ({- ...summary,- cells: summary.cells.map((cell) => ({- ...cell,- rate: cell.eligible ? cell.returned / cell.eligible : null,- })),- }))- .sort((a, b) => b.acquired - a.acquired)-}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic.tsindex 2e9b438f1b65..4fa8f346a214 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic.ts@@ -4,7 +4,6 @@ import { getDefaultInterval } from 'lib/utils/dateFilters'import {MarketingAnalyticsAttributionBreakdown,- MarketingAnalyticsRetentionInterval,MarketingAnalyticsRetentionQuery,NodeKind,} from '~/queries/schema/schema-general'@@ -13,14 +12,6 @@ import { IntervalType } from '~/types'/** Keeps the tab's refresh button off the dashboard tiles, which sit in the scene-level collection. */export const MARKETING_ANALYTICS_RETENTION_COLLECTION_ID = 'marketing-analytics-retention'-export const DEFAULT_TOTAL_INTERVALS: number = 8--export const RETENTION_INTERVAL_LABELS: Record<MarketingAnalyticsRetentionInterval, string> = {- [MarketingAnalyticsRetentionInterval.Day]: 'Daily',- [MarketingAnalyticsRetentionInterval.Week]: 'Weekly',- [MarketingAnalyticsRetentionInterval.Month]: 'Monthly',-}-interface DateFilter {dateFrom: string | nulldateTo: string | null@@ -37,8 +28,6 @@ export interface marketingRetentionLogicValues {onlyNewUsers: booleanoptionsOpen: booleanquery: MarketingAnalyticsRetentionQuery- retentionInterval: MarketingAnalyticsRetentionInterval- totalIntervals: number}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -68,12 +57,6 @@ export interface marketingRetentionLogicActions {setOptionsOpen: (optionsOpen: boolean) => {optionsOpen: boolean}- setRetentionInterval: (retentionInterval: MarketingAnalyticsRetentionInterval) => {- retentionInterval: MarketingAnalyticsRetentionInterval- }- setTotalIntervals: (totalIntervals: number) => {- totalIntervals: number- }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -81,8 +64,6 @@ export interface marketingRetentionLogicMeta {__keaTypeGenInternalSelectorTypes: {query: (breakdownBy: MarketingAnalyticsAttributionBreakdown,- retentionInterval: MarketingAnalyticsRetentionInterval,- totalIntervals: number,excludeDirectTraffic: boolean,excludeUnattributed: boolean,onlyNewUsers: boolean,@@ -105,8 +86,6 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setComparePreviousPeriod: (comparePreviousPeriod: boolean) => ({ comparePreviousPeriod }),setBreakdownBy: (breakdownBy: MarketingAnalyticsAttributionBreakdown) => ({ breakdownBy }),- setRetentionInterval: (retentionInterval: MarketingAnalyticsRetentionInterval) => ({ retentionInterval }),- setTotalIntervals: (totalIntervals: number) => ({ totalIntervals }),setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => ({ excludeDirectTraffic }),setExcludeUnattributed: (excludeUnattributed: boolean) => ({ excludeUnattributed }),setOnlyNewUsers: (onlyNewUsers: boolean) => ({ onlyNewUsers }),@@ -131,11 +110,6 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([MarketingAnalyticsAttributionBreakdown.Source as MarketingAnalyticsAttributionBreakdown,{ setBreakdownBy: (_, { breakdownBy }) => breakdownBy },],- retentionInterval: [- MarketingAnalyticsRetentionInterval.Week as MarketingAnalyticsRetentionInterval,- { setRetentionInterval: (_, { retentionInterval }) => retentionInterval },- ],- totalIntervals: [DEFAULT_TOTAL_INTERVALS, { setTotalIntervals: (_, { totalIntervals }) => totalIntervals }],excludeDirectTraffic: [false,{ setExcludeDirectTraffic: (_, { excludeDirectTraffic }) => excludeDirectTraffic },@@ -149,8 +123,6 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([query: [(s) => [s.breakdownBy,- s.retentionInterval,- s.totalIntervals,s.excludeDirectTraffic,s.excludeUnattributed,s.onlyNewUsers,@@ -159,8 +131,6 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([],(breakdownBy: MarketingAnalyticsAttributionBreakdown,- retentionInterval: MarketingAnalyticsRetentionInterval,- totalIntervals: number,excludeDirectTraffic: boolean,excludeUnattributed: boolean,onlyNewUsers: boolean,@@ -172,8 +142,6 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([comparePreviousPeriod,dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },breakdownBy,- retentionInterval,- totalIntervals,excludeDirectTraffic,excludeUnattributed,onlyNewUsers,diff --git a/products/marketing_analytics/frontend/retention/RetentionResults.tsx b/products/marketing_analytics/frontend/retention/RetentionResults.tsxnew file mode 100644index 000000000000..d688aa814fae--- /dev/null+++ b/products/marketing_analytics/frontend/retention/RetentionResults.tsx@@ -0,0 +1,50 @@+import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'++import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { InsightErrorState } from 'scenes/insights/EmptyStates'+import { BREAKDOWN_LABELS } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'+import {+ MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,+ marketingRetentionLogic,+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import {+ MarketingAnalyticsRetentionQuery,+ MarketingAnalyticsRetentionQueryResponse,+} from '~/queries/schema/schema-general'++import { RetentionReturnTable } from './RetentionReturnTable'++export function RetentionResults({+ query,+ attachTo,+}: {+ query: MarketingAnalyticsRetentionQuery+ attachTo?: LogicWrapper | BuiltLogic+}): JSX.Element {+ const logic = dataNodeLogic({+ query,+ key: 'MarketingRetention',+ dataNodeCollectionId: MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,+ })+ const { response, responseLoading, responseError } = useValues(logic)+ const { loadData } = useActions(logic)+ const { breakdownBy, onlyNewUsers } = useValues(marketingRetentionLogic)+ useAttachedLogic(logic, attachTo)+ const retentionResponse = response as MarketingAnalyticsRetentionQueryResponse | undefined++ if (responseError) {+ return <InsightErrorState query={query} onRetry={loadData} />+ }++ return (+ <RetentionReturnTable+ rows={retentionResponse?.summary ?? []}+ dimensionLabel={BREAKDOWN_LABELS[breakdownBy]}+ loading={responseLoading || !retentionResponse}+ compare={query.comparePreviousPeriod ?? false}+ onlyNewUsers={onlyNewUsers}+ />+ )+}