: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(marketing): add session retention summary table (#101370)
Javier Bahamondes7806f2c39dae
diff --git a/docs/internal/marketing-retention-summary.md b/docs/internal/marketing-retention-summary.mdnew file mode 100644index 000000000000..e4c976e1d792--- /dev/null+++ b/docs/internal/marketing-retention-summary.md@@ -0,0 +1,21 @@+# 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.++## Definitions++Acquisition uses the exact selected date range and the first qualifying session. Retention defaults to the last 30 days and offers presets up to 90 days. The backend rejects longer summary ranges. Source means normalized UTM source; referring domain remains a separate breakdown. Untagged sessions keep the existing source fallback. Only new users uses the existing 90-day lookback, with the query's existing configurable maximum of 365 days.++Each return rate divides returning users by acquired users who completed the full corresponding window. A second session must start after the first session and within the return window. Further pageviews in the first session do not count. Returns are observed up to 30 days after acquisition, capped at the current time. A dash means nobody completed the window.++Days to return is the estimated median elapsed time to the second session among observed returners within 30 days. Recent users with incomplete windows participate in this median, so it may change as they return. The median uses the shared comparison arrow and tooltip, with neutral colors and displays a dash when no return is observed. Compare rates within a column: the 7-day and 30-day denominators can differ.++Comparison is enabled by default and can be disabled with the comparison selector in the toolbar. The previous acquisition period uses the shared date comparison rules, including relative ranges and calendar periods. Each period uses its own new-user lookback. Missing previous data does not produce a change indicator.++## Query and compatibility++Summary 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.++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/snapshots.yml b/frontend/snapshots.ymlindex b34e7ab35467..44e0c2192f2e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5104,6 +5104,26 @@ snapshots:hash: v1.k794b7964.fda088b86665fa1e7f42ac158d9c5acf12b2afc030a90ad385d3d0fe16170d46.WqmQ9-wSSHQj0J-kUbJKkFI8DhDljOP6queW3e6jxDQmarketing-analytics-customer-acquisition-cards--unconfigured--light:hash: v1.k794b7964.40240d162f715f3da0d8363e08797fb8a9c131852a5d6356c892424e25dfa35c.yeHaH7ecKHVh7IOwmerxuVPzSGclQrUDBwWnoPV0rmw+ marketing-analytics-retention-return-table--all-users--dark:+ hash: v1.k794b7964.6264efbb674f1d2ad948b6e8856f69a094d69e17470207337238c52738d18184.joOXUxWScKUZyVj5-taM4nWB9gqzB22I8iJwgRauNOA+ marketing-analytics-retention-return-table--all-users--light:+ hash: v1.k794b7964.0a973ec5c9d94ed2ee1f27fc8a4c413a4e6fad4e5d680feb6261ecb0b453bfc5.68pa0YliERtpe8_vooGChjNDotzdaAyCJISwOQhQQCc+ marketing-analytics-retention-return-table--default--dark:+ hash: v1.k794b7964.10eab46ec9f4b1ab6c0e0498982027ca451613de6a5ea37cdf9d8ce79c5095eb.T7Q483dORAWSLxcHH1-RJKXoIMORzWToVbXG9NWnH-o+ marketing-analytics-retention-return-table--default--light:+ hash: v1.k794b7964.9d6ff8a78cbd4f810f13b52e75d22b678cdcd2c010759549320925170b33e178.dsdL6bi8UEmgPTT-jxSNxEq_YNbF4N2zy1TduLsuP48+ marketing-analytics-retention-return-table--empty--dark:+ hash: v1.k794b7964.340da8ad1ed4d91b6472e7d0215f0295b10602067d123d4484f0fe09c7e0826f.bS8-9AzKCXQ3Ix-27-wnVZVQ-wBS6f2w_UOxMz807Js+ marketing-analytics-retention-return-table--empty--light:+ hash: v1.k794b7964.12d9c04519b4fe33eb084b9bf5e8f53ceaa40b26d72afc84d5ded8d9451cfabd.pc7H0RaMxKWFfVOC732sIVNsuUfsjW4w38I4ZE1esEo+ marketing-analytics-retention-return-table--loading--dark:+ hash: v1.k794b7964.4c5e4473e31b1954db9a041ce022e6a92c629e454852cf218bddac0e276996bc.X7-47Ixxi7BCYLdzTO-QV84Aphv2l2O8_hnePWNOsXs+ marketing-analytics-retention-return-table--loading--light:+ hash: v1.k794b7964.bbd1f61aa361508eb73402430de6089089a7fb8a70159eb5870a1a52f062f8cd.bEjl2HcNNGwb28FByp5V9ElTvVwcKt1aM7X95MK6qhM+ marketing-analytics-retention-return-table--narrow--dark:+ hash: v1.k794b7964.67019271111dca09ef78b22f652cf4be578fbc74f62881191546aa0b87ca1f22.OklZvNuLCnUMgEpeiqSv1xX4BjoPdpG9UznSvj3oMUY+ marketing-analytics-retention-return-table--narrow--light:+ hash: v1.k794b7964.dfae60d8f5ec1e691c1d49e8da9c7d72cb260dd0be46e20c58497786d4a338b9.fdcRFY9rIoQ9yxTtOAwwv1iSidqzbGlYHbaWTDbVlKomcp-apps-actions--list--light:hash: v1.k794b7964.7bdc20fc1da4e4a172e15101a23f9e72b257280598a56a9883080d8af7a12614.Wz5K1jifC5KxYKDSFTcNkoO4TiCkjFVZxxeVsObrZfomcp-apps-actions--multi-step--light:diff --git a/frontend/src/lib/components/CompareFilter/CompareFilter.tsx b/frontend/src/lib/components/CompareFilter/CompareFilter.tsxindex bdc48082d515..902473acd409 100644--- a/frontend/src/lib/components/CompareFilter/CompareFilter.tsx+++ b/frontend/src/lib/components/CompareFilter/CompareFilter.tsx@@ -10,6 +10,7 @@ import { dateFromToText } from 'lib/utils/dateFilters'import { CompareFilter as CompareFilterType } from '~/queries/schema/schema-general'type CompareFilterProps = {+ allowCustomComparison?: booleancompareFilter?: CompareFilterType | nullupdateCompareFilter: (compareFilter: CompareFilterType) => voiddisabled?: boolean@@ -24,6 +25,7 @@ export function CompareFilter({disabled,disableReason,tooltip,+ allowCustomComparison = true,}: CompareFilterProps): JSX.Element | null {// This keeps the state of the rolling date range filter, even when different drop down options are selected// The default value for this is one month@@ -111,7 +113,7 @@ export function CompareFilter({}}}data-attr="compare-filter"- options={options}+ options={options.filter((option) => allowCustomComparison || option.value !== 'compareTo')}size="small"disabled={disabled}disabledReason={disableReason}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex dedf418a8abb..9f00a8a2cb9e 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -12365,6 +12365,13 @@},"type": "array"},+ "summary": {+ "description": "Only populated in summary mode. Rates use the corresponding eligible population.",+ "items": {+ "$ref": "#/definitions/MarketingAnalyticsRetentionSummaryRow"+ },+ "type": "array"+ },"timezone": {"type": "string"},@@ -34584,6 +34591,10 @@"$ref": "#/definitions/integer","description": "Breakdown values kept before the rest roll into 'Other'. Defaults to 20."},+ "comparePreviousPeriod": {+ "description": "Include the previous acquisition period in summary mode. Defaults to false.",+ "type": "boolean"+ },"dataColorTheme": {"description": "Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility","type": ["number", "null"]@@ -34632,6 +34643,10 @@"$ref": "#/definitions/MarketingAnalyticsRetentionInterval","description": "Period for both the cohort rows and the return columns. Defaults to week."},+ "summary": {+ "description": "Return session-based 7/30-day metrics instead of the cohort matrix. Defaults to false.",+ "type": "boolean"+ },"tags": {"$ref": "#/definitions/QueryLogTags"},@@ -34702,6 +34717,13 @@},"type": "array"},+ "summary": {+ "description": "Only populated in summary mode. Rates use the corresponding eligible population.",+ "items": {+ "$ref": "#/definitions/MarketingAnalyticsRetentionSummaryRow"+ },+ "type": "array"+ },"timings": {"description": "Measured timings for different parts of the query generation process","items": {@@ -34780,6 +34802,52 @@"required": ["breakdownValue", "cohortDate", "cohortIndex", "cohortSize", "values"],"type": "object"},+ "MarketingAnalyticsRetentionSummaryRow": {+ "additionalProperties": false,+ "properties": {+ "acquired": {+ "$ref": "#/definitions/integer"+ },+ "breakdownValue": {+ "type": "string"+ },+ "eligible30d": {+ "$ref": "#/definitions/integer"+ },+ "eligible7d": {+ "$ref": "#/definitions/integer"+ },+ "medianReturnDays": {+ "description": "Median elapsed days to a second session within 30 days, among observed returners.",+ "type": ["number", "null"]+ },+ "previous": {+ "type": "boolean"+ },+ "returned30d": {+ "$ref": "#/definitions/integer"+ },+ "returned7d": {+ "$ref": "#/definitions/integer"+ },+ "returners": {+ "$ref": "#/definitions/integer",+ "description": "People with an observed second session within 30 days, including incomplete windows."+ }+ },+ "required": [+ "breakdownValue",+ "previous",+ "acquired",+ "eligible7d",+ "returned7d",+ "eligible30d",+ "returned30d",+ "medianReturnDays",+ "returners"+ ],+ "type": "object"+ },"MarketingAnalyticsSchemaField": {"additionalProperties": false,"properties": {@@ -42471,6 +42539,13 @@},"type": "array"},+ "summary": {+ "description": "Only populated in summary mode. Rates use the corresponding eligible population.",+ "items": {+ "$ref": "#/definitions/MarketingAnalyticsRetentionSummaryRow"+ },+ "type": "array"+ },"timings": {"description": "Measured timings for different parts of the query generation process","items": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 56427c43c983..6c28a95f5d26 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -7757,6 +7757,10 @@ export interface MarketingAnalyticsRetentionQuery extends Omit<'orderBy' | 'compareFilter' | 'interval' | 'conversionGoal' | 'doPathCleaning' | 'sampling' | 'samplingFactor'> {kind: NodeKind.MarketingAnalyticsRetentionQuery+ /** Return session-based 7/30-day metrics instead of the cohort matrix. Defaults to false. */+ summary?: boolean+ /** Include the previous acquisition period in summary mode. Defaults to false. */+ comparePreviousPeriod?: boolean/** Cohort dimension, read off each person's first session. Defaults to channel. */breakdownBy?: MarketingAnalyticsAttributionBreakdown/** Period for both the cohort rows and the return columns. Defaults to week. */@@ -7803,8 +7807,24 @@ export interface MarketingAnalyticsRetentionRow {values: MarketingAnalyticsRetentionCell[]}+export interface MarketingAnalyticsRetentionSummaryRow {+ breakdownValue: string+ previous: boolean+ acquired: integer+ eligible7d: integer+ returned7d: integer+ eligible30d: integer+ returned30d: integer+ /** Median elapsed days to a second session within 30 days, among observed returners. */+ medianReturnDays: number | null+ /** People with an observed second session within 30 days, including incomplete windows. */+ returners: integer+}+export interface MarketingAnalyticsRetentionQueryResponse extends AnalyticsQueryResponseBase {results: MarketingAnalyticsRetentionRow[]+ /** Only populated in summary mode. Rates use the corresponding eligible population. */+ summary?: MarketingAnalyticsRetentionSummaryRow[]/** Column count. Every row's values array has this length. */intervalCount: integerinterval: MarketingAnalyticsRetentionIntervaldiff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsxindex 0bd7be52ed64..ab085a6cf9f3 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx@@ -12,7 +12,10 @@ import { initKeaTests } from '~/test/init'import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'-jest.mock('scenes/web-analytics/tiles/WebAnalyticsTile', () => ({ webAnalyticsDataTableQueryContext: {} }))+jest.mock('scenes/web-analytics/tiles/WebAnalyticsTile', () => ({+ VariationCell: () => () => null,+ webAnalyticsDataTableQueryContext: {},+}))jest.mock('~/queries/Query/Query', () => ({ Query: () => null }))jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable', () => ({AttributionTable: () => null,diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsxindex 26ac5a266798..4fc525277655 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx@@ -56,7 +56,10 @@ jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketinjest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/shared', () => ({MarketingAnalyticsCell: () => null,}))-jest.mock('scenes/web-analytics/tiles/WebAnalyticsTile', () => ({ webAnalyticsDataTableQueryContext: {} }))+jest.mock('scenes/web-analytics/tiles/WebAnalyticsTile', () => ({+ VariationCell: () => () => null,+ webAnalyticsDataTableQueryContext: {},+}))jest.mock('~/queries/nodes/DataNode/dataNodeLogic', () => ({ dataNodeLogic: () => ({}) }))jest.mock('~/queries/nodes/OverviewGrid/OverviewMetricCardGrid', () => ({ OverviewMetricCardGrid: () => null }))jest.mock('~/queries/nodes/WebOverview/WebOverview', () => ({ labelFromKey: () => '' }))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.tsxindex 41462086d44e..303e6d88844e 100644--- 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.tsx@@ -18,6 +18,8 @@ import {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,@@ -91,6 +93,18 @@ export function RetentionCohortTable({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',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 f05d5ab9e293..d81df9cce31c 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@@ -3,8 +3,10 @@ import { BindLogic, useActions, useValues } from 'kea'import { IconGear } from '@posthog/icons'import { LemonButton, LemonDivider, LemonSelect, LemonSwitch, Popover } from '@posthog/lemon-ui'+import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { FilterBar } from 'lib/components/FilterBar'+import { dateMapping } from 'lib/utils/dateFilters'import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'import { ReloadAll } from '~/queries/nodes/DataNode/Reload'@@ -23,9 +25,13 @@ import {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] ?? '')+)export function RetentionTab(): JSX.Element {const {+ dateFilter,breakdownBy,retentionInterval,totalIntervals,@@ -33,9 +39,11 @@ export function RetentionTab(): JSX.Element {excludeUnattributed,onlyNewUsers,optionsOpen,+ comparePreviousPeriod,query,} = useValues(marketingRetentionLogic)const {+ setDates,setBreakdownBy,setRetentionInterval,setTotalIntervals,@@ -43,40 +51,50 @@ export function RetentionTab(): JSX.Element {setExcludeUnattributed,setOnlyNewUsers,setOptionsOpen,+ setComparePreviousPeriod,} = useActions(marketingRetentionLogic)- const { dateFilter } = useValues(marketingAnalyticsLogic)- const { setDates } = useActions(marketingAnalyticsLogic)-+ const showCohorts = falseconst optionsContent = (<div className="flex w-80 max-w-[90vw] flex-col gap-4 p-3"><div><div className="text-muted mb-2 text-xs font-semibold uppercase">Acquisition period</div>- <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />+ <DateFilter+ dateFrom={dateFilter.dateFrom}+ dateTo={dateFilter.dateTo}+ dateOptions={RETENTION_DATE_OPTIONS}+ showRollingRangePicker={false}+ showCustomRangeOptions={false}+ onChange={setDates}+ /><div className="text-muted mt-1 text-xs">- People who arrived in this period become the cohorts. Each cohort is then followed forward.+ People acquired in this period are followed for return visits.</div></div>- <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>+ {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@@ -130,7 +148,12 @@ export function RetentionTab(): JSX.Element {</div>}right={- <div className="flex items-center gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <CompareFilter+ compareFilter={{ compare: comparePreviousPeriod }}+ updateCompareFilter={({ compare }) => setComparePreviousPeriod(!!compare)}+ allowCustomComparison={false}+ /><ReloadAll iconOnly /><Popovervisible={optionsOpen}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 3bdb0cd97f51..2e9b438f1b65 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@@ -1,4 +1,6 @@-import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'++import { getDefaultInterval } from 'lib/utils/dateFilters'import {MarketingAnalyticsAttributionBreakdown,@@ -8,8 +10,6 @@ import {} from '~/queries/schema/schema-general'import { IntervalType } from '~/types'-import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'-/** 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'@@ -29,12 +29,9 @@ interface DateFilter {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface marketingRetentionLogicValues {- dateFilter: {- dateFrom: string | null- dateTo: string | null- interval: IntervalType- } // marketingAnalyticsLogicbreakdownBy: MarketingAnalyticsAttributionBreakdown+ comparePreviousPeriod: boolean+ dateFilter: DateFilterexcludeDirectTraffic: booleanexcludeUnattributed: booleanonlyNewUsers: boolean@@ -49,6 +46,16 @@ export interface marketingRetentionLogicActions {setBreakdownBy: (breakdownBy: MarketingAnalyticsAttributionBreakdown) => {breakdownBy: MarketingAnalyticsAttributionBreakdown}+ setComparePreviousPeriod: (comparePreviousPeriod: boolean) => {+ comparePreviousPeriod: boolean+ }+ setDates: (+ dateFrom: string | null,+ dateTo: string | null+ ) => {+ dateFrom: string | null+ dateTo: string | null+ }setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => {excludeDirectTraffic: boolean}@@ -79,11 +86,8 @@ export interface marketingRetentionLogicMeta {excludeDirectTraffic: boolean,excludeUnattributed: boolean,onlyNewUsers: boolean,- dateFilter: {- dateFrom: string | null- dateTo: string | null- interval: IntervalType- }+ dateFilter: DateFilter,+ comparePreviousPeriod: boolean) => MarketingAnalyticsRetentionQuery}}@@ -97,10 +101,9 @@ export type marketingRetentionLogicType = MakeLogicType<export const marketingRetentionLogic = kea<marketingRetentionLogicType>([path(['scenes', 'webAnalytics', 'marketingRetentionLogic']),- connect(() => ({- values: [marketingAnalyticsLogic, ['dateFilter']],- })),actions({+ 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 }),@@ -110,8 +113,22 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([setOptionsOpen: (optionsOpen: boolean) => ({ optionsOpen }),}),reducers({+ dateFilter: [+ { dateFrom: '-30d', dateTo: null, interval: getDefaultInterval('-30d', null) } as DateFilter,+ {+ setDates: (_, { dateFrom, dateTo }) => ({+ dateFrom,+ dateTo,+ interval: getDefaultInterval(dateFrom, dateTo),+ }),+ },+ ],+ comparePreviousPeriod: [+ true,+ { setComparePreviousPeriod: (_, { comparePreviousPeriod }) => comparePreviousPeriod },+ ],breakdownBy: [- MarketingAnalyticsAttributionBreakdown.Channel as MarketingAnalyticsAttributionBreakdown,+ MarketingAnalyticsAttributionBreakdown.Source as MarketingAnalyticsAttributionBreakdown,{ setBreakdownBy: (_, { breakdownBy }) => breakdownBy },],retentionInterval: [@@ -138,6 +155,7 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([s.excludeUnattributed,s.onlyNewUsers,s.dateFilter,+ s.comparePreviousPeriod,],(breakdownBy: MarketingAnalyticsAttributionBreakdown,@@ -146,9 +164,12 @@ export const marketingRetentionLogic = kea<marketingRetentionLogicType>([excludeDirectTraffic: boolean,excludeUnattributed: boolean,onlyNewUsers: boolean,- dateFilter: DateFilter+ dateFilter: DateFilter,+ comparePreviousPeriod: boolean): MarketingAnalyticsRetentionQuery => ({kind: NodeKind.MarketingAnalyticsRetentionQuery,+ summary: true,+ comparePreviousPeriod,dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },breakdownBy,retentionInterval,diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsxindex 1a1464ed1c5c..cd5a8959cdba 100644--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx@@ -219,15 +219,47 @@ const UrlValueCell: QueryContextColumnComponent = ({ value }) => {)}-type VariationCellProps = { isPercentage?: boolean; reverseColors?: boolean; isDuration?: boolean }-const VariationCell = (- { isPercentage, reverseColors, isDuration }: VariationCellProps = {+type VariationCellProps = {+ isPercentage?: boolean+ reverseColors?: boolean+ isDuration?: boolean+ reserveTrendSpace?: boolean+ neutral?: boolean+ formatValue?: (value: number) => string+}++export function comparisonTooltipText(+ current: number,+ previous: number | null,+ compare: boolean,+ formatNumber: (value: number) => string+): string | null {+ if (!compare || previous === null) {+ return null+ }+ if (current === previous) {+ return `No change since last period (${formatNumber(current)})`+ }+ if (previous === 0) {+ return `Increased from ${formatNumber(previous)} to ${formatNumber(current)} since last period`+ }+ return `${current > previous ? 'Increased' : 'Decreased'} by ${percentage(+ Math.abs(current / previous - 1),+ 0+ )} since last period (from ${formatNumber(previous)} to ${formatNumber(current)})`+}++export const VariationCell = (+ { isPercentage, reverseColors, isDuration, reserveTrendSpace = true, neutral, formatValue }: VariationCellProps = {isPercentage: false,reverseColors: false,isDuration: false,}-): QueryContextColumnComponent => {+) => {const formatNumber = (value: number): string => {+ if (formatValue) {+ return formatValue(value)+ }if (isPercentage) {return `${(value * 100).toFixed(1)}%`} else if (isDuration) {@@ -236,7 +268,15 @@ const VariationCell = (return value?.toLocaleString() ?? '(empty)'}- return function Cell({ value, context }) {+ return function Cell({+ value,+ context,+ tooltipContent,+ }: {+ value: unknown+ context?: QueryContext+ tooltipContent?: React.ReactNode+ }) {const compareFilter = context?.compareFilterif (!value) {@@ -247,23 +287,16 @@ const VariationCell = (return <span>{String(value)}</span>}- const [current, previous] = value as [number, number]-- const pctChangeFromPrevious =- previous === 0 && current === 0 // Special case, render as flatline- ? 0- : current === null || !compareFilter || compareFilter.compare === false- ? null- : previous === null || previous === 0- ? Infinity- : current / previous - 1+ const [current, previous] = value as [number, number | null]+ const hasComparison = previous !== null && compareFilter?.compare === true+ const difference = hasComparison ? current - previous : nullconst trend =- pctChangeFromPrevious === null+ difference === null? null- : pctChangeFromPrevious === 0+ : difference === 0? { Icon: IconTrendingFlat, color: getColorVar('muted') }- : pctChangeFromPrevious > 0+ : difference > 0? {Icon: IconTrending,color: reverseColors ? getColorVar('danger') : getColorVar('success'),@@ -273,24 +306,29 @@ const VariationCell = (color: reverseColors ? getColorVar('success') : getColorVar('danger'),}- // If current === previous, say "increased by 0%"+ const trendColor = neutral ? getColorVar('muted') : trend?.color++ const comparisonTooltip = comparisonTooltipText(current, previous, hasComparison, formatNumber)const tooltip =- pctChangeFromPrevious !== null- ? `${current >= previous ? 'Increased' : 'Decreased'} by ${percentage(- Math.abs(pctChangeFromPrevious),- 0- )} since last period (from ${formatNumber(previous)} to ${formatNumber(current)})`- : null+ comparisonTooltip && tooltipContent ? (+ <div className="flex flex-col gap-1">+ <div>{comparisonTooltip}</div>+ <div>{tooltipContent}</div>+ </div>+ ) : (+ (comparisonTooltip ?? tooltipContent)+ )return (- <div className={clsx({ 'pr-4': !trend })}>+ <div className={clsx({ 'pr-4': !trend && reserveTrendSpace })}><Tooltip title={tooltip}><span>- {formatNumber(current)} + {formatNumber(current)}+ {(reserveTrendSpace || trend) && '\u00a0'}{trend && (// eslint-disable-next-line react/forbid-dom-props- <span style={{ color: trend.color }}>- <trend.Icon color={trend.color} className="ml-1" />+ <span style={{ color: trendColor }}>+ <trend.Icon color={trendColor} className="ml-1" /></span>)}</span>diff --git a/frontend/src/scenes/web-analytics/tiles/webAnalyticsTile.test.ts b/frontend/src/scenes/web-analytics/tiles/webAnalyticsTile.test.tsindex 0823f972b583..4136c8e89bcb 100644--- a/frontend/src/scenes/web-analytics/tiles/webAnalyticsTile.test.ts+++ b/frontend/src/scenes/web-analytics/tiles/webAnalyticsTile.test.ts@@ -1,16 +1,33 @@-import { toUtcOffsetFormat } from './WebAnalyticsTile'+import { comparisonTooltipText, toUtcOffsetFormat } from './WebAnalyticsTile'-describe('toUtcOffsetFormat', () => {- it.each([- [0, 'UTC'],- [0.25, 'UTC+0:15'],- [1, 'UTC+1'],- [1.5, 'UTC+1:30'],- [-0, 'UTC'],- [-0.25, 'UTC-0:15'],- [-1, 'UTC-1'],- [-1.5, 'UTC-1:30'],- ])('should format %d to %s', (minutes, expected) => {- expect(toUtcOffsetFormat(minutes)).toEqual(expected)+describe('WebAnalyticsTile helpers', () => {+ describe('toUtcOffsetFormat', () => {+ it.each([+ [0, 'UTC'],+ [0.25, 'UTC+0:15'],+ [1, 'UTC+1'],+ [1.5, 'UTC+1:30'],+ [-0, 'UTC'],+ [-0.25, 'UTC-0:15'],+ [-1, 'UTC-1'],+ [-1.5, 'UTC-1:30'],+ ])('should format %d to %s', (minutes, expected) => {+ expect(toUtcOffsetFormat(minutes)).toEqual(expected)+ })+ })++ describe('comparisonTooltipText', () => {+ const formatNumber = (value: number): string => `${value}`++ it.each([+ [10, 0, true, 'Increased from 0 to 10 since last period'],+ [10, 5, true, 'Increased by 100% since last period (from 5 to 10)'],+ [5, 10, true, 'Decreased by 50% since last period (from 10 to 5)'],+ [5, 5, true, 'No change since last period (5)'],+ [10, null, true, null],+ [10, 5, false, null],+ ])('formats %s compared with %s', (current, previous, compare, expected) => {+ expect(comparisonTooltipText(current, previous, compare, formatNumber)).toEqual(expected)+ })})})diff --git a/posthog/schema.py b/posthog/schema.pyindex 61740a1a63fe..d219929af95d 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -6116,6 +6116,27 @@ class MarketingAnalyticsRetentionRow(BaseModel):)+class MarketingAnalyticsRetentionSummaryRow(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ acquired: int+ breakdownValue: str+ eligible30d: int+ eligible7d: int+ medianReturnDays: float | None = Field(+ ...,+ description=("Median elapsed days to a second session within 30 days, among observed returners."),+ )+ previous: bool+ returned30d: int+ returned7d: int+ returners: int = Field(+ ...,+ description=("People with an observed second session within 30 days, including incomplete windows."),+ )++class MarketingAnalyticsSchemaField(BaseModel):model_config = ConfigDict(extra="forbid",@@ -13544,6 +13565,10 @@ class CachedMarketingAnalyticsRetentionQueryResponse(BaseModel):default=None, description="The date range used for the query")results: list[MarketingAnalyticsRetentionRow]+ summary: list[MarketingAnalyticsRetentionSummaryRow] | None = Field(+ default=None,+ description=("Only populated in summary mode. Rates use the corresponding eligible population."),+ )timezone: strtimings: list[QueryTiming] | None = Field(default=None,@@ -19200,6 +19225,10 @@ class MarketingAnalyticsRetentionQueryResponse(BaseModel):default=None, description="The date range used for the query")results: list[MarketingAnalyticsRetentionRow]+ summary: list[MarketingAnalyticsRetentionSummaryRow] | None = Field(+ default=None,+ description=("Only populated in summary mode. Rates use the corresponding eligible population."),+ )timings: list[QueryTiming] | None = Field(default=None,description=("Measured timings for different parts of the query generation process"),@@ -20965,6 +20994,10 @@ class QueryResponseAlternative37(BaseModel):default=None, description="The date range used for the query")results: list[MarketingAnalyticsRetentionRow]+ summary: list[MarketingAnalyticsRetentionSummaryRow] | None = Field(+ default=None,+ description=("Only populated in summary mode. Rates use the corresponding eligible population."),+ )timings: list[QueryTiming] | None = Field(default=None,description=("Measured timings for different parts of the query generation process"),@@ -27733,6 +27766,10 @@ class MarketingAnalyticsRetentionQuery(BaseModel):default=None,description=("Breakdown values kept before the rest roll into 'Other'. Defaults to 20."),)+ comparePreviousPeriod: bool | None = Field(+ default=None,+ description=("Include the previous acquisition period in summary mode. Defaults to false."),+ )dataColorTheme: float | None = Field(default=None,description=(@@ -27769,6 +27806,10 @@ class MarketingAnalyticsRetentionQuery(BaseModel):default=None,description=("Period for both the cohort rows and the return columns. Defaults to week."),)+ summary: bool | None = Field(+ default=None,+ description=("Return session-based 7/30-day metrics instead of the cohort matrix. Defaults to false."),+ )tags: QueryLogTags | None = NonetotalIntervals: int | None = Field(default=None,diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_retention_query_runner.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_retention_query_runner.ambrindex ec238d0f886f..69f09f1213df 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_retention_query_runner.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_retention_query_runner.ambr@@ -391,3 +391,80 @@LIMIT 421'''# ---+# name: TestMarketingAnalyticsRetentionQueryRunner.test_retention_sql_4_summary+ '''+ WITH acquisition AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id, min(events__session.`$start_timestamp`) AS first_session_at, argMin(if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_30)s)), events__session.`$entry_utm_source`, %(hogql_val_31)s)), [%(hogql_val_32)s, %(hogql_val_33)s, %(hogql_val_34)s]), %(hogql_val_35)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_36)s)), events__session.`$entry_utm_source`, %(hogql_val_37)s)), [%(hogql_val_38)s, %(hogql_val_39)s, %(hogql_val_40)s, %(hogql_val_41)s, %(hogql_val_42)s, %(hogql_val_43)s, %(hogql_val_44)s, %(hogql_val_45)s]), %(hogql_val_46)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_47)s)), events__session.`$entry_utm_source`, %(hogql_val_48)s)), [%(hogql_val_49)s]), %(hogql_val_50)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_51)s)), events__session.`$entry_utm_source`, %(hogql_val_52)s)), [%(hogql_val_53)s, %(hogql_val_54)s, %(hogql_val_55)s, %(hogql_val_56)s, %(hogql_val_57)s, %(hogql_val_58)s, %(hogql_val_59)s, %(hogql_val_60)s, %(hogql_val_61)s]), %(hogql_val_62)s, if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_63)s)), events__session.`$entry_utm_source`, %(hogql_val_64)s))))), events__session.`$start_timestamp`) AS breakdown_value, 0 AS previous, %(hogql_val_65)s AS observation_end, argMin(events.`$session_id`, events__session.`$start_timestamp`) AS first_session_id+ FROM events LEFT JOIN (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_22)s)) AS `$start_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_23)s), %(hogql_val_24)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_25)s, %(hogql_val_26)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_27)s, %(hogql_val_28)s), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_29)s)), events__session.session_id_v7) LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_66)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_67)s, %(hogql_val_68)s)), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_69)s, %(hogql_val_70)s)), ifNull(greaterOrEquals(events__session.`$start_timestamp`, toDateTime(%(hogql_val_71)s, %(hogql_val_72)s)), 0), ifNull(lessOrEquals(events__session.`$start_timestamp`, toDateTime(%(hogql_val_73)s, %(hogql_val_74)s)), 0), globalNotIn(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), (+ SELECT DISTINCT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_75)s), notEmpty(events.`$session_id`), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_76)s, %(hogql_val_77)s), toIntervalDay(90))), less(events.timestamp, toDateTime(%(hogql_val_78)s, %(hogql_val_79)s))))))+ GROUP BY actor_id UNION ALL+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id, min(events__session.`$start_timestamp`) AS first_session_at, argMin(if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_88)s)), events__session.`$entry_utm_source`, %(hogql_val_89)s)), [%(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s]), %(hogql_val_93)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_94)s)), events__session.`$entry_utm_source`, %(hogql_val_95)s)), [%(hogql_val_96)s, %(hogql_val_97)s, %(hogql_val_98)s, %(hogql_val_99)s, %(hogql_val_100)s, %(hogql_val_101)s, %(hogql_val_102)s, %(hogql_val_103)s]), %(hogql_val_104)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_105)s)), events__session.`$entry_utm_source`, %(hogql_val_106)s)), [%(hogql_val_107)s]), %(hogql_val_108)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_109)s)), events__session.`$entry_utm_source`, %(hogql_val_110)s)), [%(hogql_val_111)s, %(hogql_val_112)s, %(hogql_val_113)s, %(hogql_val_114)s, %(hogql_val_115)s, %(hogql_val_116)s, %(hogql_val_117)s, %(hogql_val_118)s, %(hogql_val_119)s]), %(hogql_val_120)s, if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_121)s)), events__session.`$entry_utm_source`, %(hogql_val_122)s))))), events__session.`$start_timestamp`) AS breakdown_value, 1 AS previous, %(hogql_val_123)s AS observation_end, argMin(events.`$session_id`, events__session.`$start_timestamp`) AS first_session_id+ FROM events LEFT JOIN (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_80)s)) AS `$start_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_81)s), %(hogql_val_82)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_83)s, %(hogql_val_84)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_85)s, %(hogql_val_86)s), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_87)s)), events__session.session_id_v7) LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_124)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_125)s, %(hogql_val_126)s)), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_127)s, %(hogql_val_128)s)), ifNull(greaterOrEquals(events__session.`$start_timestamp`, toDateTime(%(hogql_val_129)s, %(hogql_val_130)s)), 0), ifNull(lessOrEquals(events__session.`$start_timestamp`, toDateTime(%(hogql_val_131)s, %(hogql_val_132)s)), 0), globalNotIn(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), (+ SELECT DISTINCT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_133)s), notEmpty(events.`$session_id`), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_134)s, %(hogql_val_135)s), toIntervalDay(90))), less(events.timestamp, toDateTime(%(hogql_val_136)s, %(hogql_val_137)s))))))+ GROUP BY actor_id), activity AS (+ SELECT acquisition.actor_id AS actor_id, acquisition.previous AS previous, min(events__session.`$start_timestamp`) AS returned_at+ FROM events LEFT JOIN (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_138)s)) AS `$start_timestamp`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_139)s, %(hogql_val_140)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_141)s, %(hogql_val_142)s), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_143)s)), events__session.session_id_v7) LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) GLOBAL INNER JOIN acquisition ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), acquisition.actor_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_144)s), notEmpty(events.`$session_id`), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_145)s, %(hogql_val_146)s)), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_147)s, %(hogql_val_148)s)), notEquals(events.`$session_id`, acquisition.first_session_id), greater(events__session.`$start_timestamp`, acquisition.first_session_at), lessOrEquals(events__session.`$start_timestamp`, plus(toTimeZone(acquisition.first_session_at, %(hogql_val_149)s), toIntervalDay(30))), ifNull(lessOrEquals(events__session.`$start_timestamp`, parseDateTime64BestEffortOrNull(acquisition.observation_end, 6, %(hogql_val_150)s)), 0))+ GROUP BY actor_id, previous), people AS MATERIALIZED (+ SELECT acquisition.actor_id AS actor_id, acquisition.breakdown_value AS breakdown_value, acquisition.previous AS previous, toTimeZone(acquisition.first_session_at, %(hogql_val_151)s) AS first_session_at, parseDateTime64BestEffortOrNull(acquisition.observation_end, 6, %(hogql_val_152)s) AS observation_end, toTimeZone(activity.returned_at, %(hogql_val_153)s) AS returned_at+ FROM acquisition LEFT JOIN activity ON and(equals(acquisition.actor_id, activity.actor_id), equals(acquisition.previous, activity.previous)))+ SELECT if(globalIn(people.breakdown_value, (+ SELECT people.breakdown_value AS breakdown_value+ FROM people+ GROUP BY people.breakdown_value+ ORDER BY countIf(not(people.previous)) DESC, count() DESC, people.breakdown_value ASC+ LIMIT 20)), people.breakdown_value, %(hogql_val_0)s) AS breakdownValue, people.previous AS previous, count() AS acquired, countIf(ifNull(lessOrEquals(plus(toTimeZone(people.first_session_at, %(hogql_val_1)s), toIntervalDay(7)), toTimeZone(people.observation_end, %(hogql_val_2)s)), 0)) AS eligible7d, countIf(and(ifNull(lessOrEquals(plus(toTimeZone(people.first_session_at, %(hogql_val_3)s), toIntervalDay(7)), toTimeZone(people.observation_end, %(hogql_val_4)s)), 0), greater(toTimeZone(people.returned_at, %(hogql_val_5)s), toTimeZone(people.first_session_at, %(hogql_val_6)s)), lessOrEquals(toTimeZone(people.returned_at, %(hogql_val_7)s), plus(toTimeZone(people.first_session_at, %(hogql_val_8)s), toIntervalDay(7))))) AS returned7d, countIf(ifNull(lessOrEquals(plus(toTimeZone(people.first_session_at, %(hogql_val_9)s), toIntervalDay(30)), toTimeZone(people.observation_end, %(hogql_val_10)s)), 0)) AS eligible30d, countIf(and(ifNull(lessOrEquals(plus(toTimeZone(people.first_session_at, %(hogql_val_11)s), toIntervalDay(30)), toTimeZone(people.observation_end, %(hogql_val_12)s)), 0), greater(toTimeZone(people.returned_at, %(hogql_val_13)s), toTimeZone(people.first_session_at, %(hogql_val_14)s)))) AS returned30d, countIf(greater(toTimeZone(people.returned_at, %(hogql_val_15)s), toTimeZone(people.first_session_at, %(hogql_val_16)s))) AS returners, if(greater(returners, 0), medianIf(divide(dateDiff(%(hogql_val_17)s, toTimeZone(people.first_session_at, %(hogql_val_18)s), toTimeZone(people.returned_at, %(hogql_val_19)s)), 86400.0), greater(toTimeZone(people.returned_at, %(hogql_val_20)s), toTimeZone(people.first_session_at, %(hogql_val_21)s))), NULL) AS medianReturnDays+ FROM people+ GROUP BY breakdownValue, people.previous+ ORDER BY people.previous ASC, acquired DESC, breakdownValue ASC+ LIMIT 42+ '''+# ---diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_retention_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_retention_query_runner.pyindex 2a26255d806d..994272673421 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_retention_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_retention_query_runner.py@@ -46,6 +46,7 @@ MAX_TOTAL_INTERVALS = 40MAX_COHORTS = 60MAX_BREAKDOWN_LIMIT = 40MAX_NEW_USER_LOOKBACK_DAYS = 365+MAX_SUMMARY_ACQUISITION_DAYS = 90# Shared with core retention so both surfaces print the same label for the folded tail._OTHER = BREAKDOWN_OTHER_STRING_LABEL@@ -214,6 +215,8 @@ class MarketingAnalyticsRetentionQueryRunner(@propertydef _cohort_window_start_str(self) -> str:+ if self.query.summary:+ return self.query_date_range.date_from_strreturn self.query_date_range.format_date(self.cohort_starts[0])@property@@ -585,6 +588,10 @@ class MarketingAnalyticsRetentionQueryRunner(# ------------------------------------------------------------------ main querydef to_query(self) -> ast.SelectQuery:+ if self.query.summary:+ from .marketing_retention_summary import build_summary_query++ return build_summary_query(self)ctes: dict[str, ast.CTE] = {}# Materialized because both `cohort_sizes` and `matrix` read it, and ClickHouse re-evaluates an@@ -622,13 +629,22 @@ class MarketingAnalyticsRetentionQueryRunner(# ------------------------------------------------------------------ executiondef _calculate(self) -> MarketingAnalyticsRetentionQueryResponse:- if self._period_count <= 0:+ if self.query_date_range.date_from() > self.query_date_range.date_to():# An inverted range spans no periods. `cohort_starts` still floors itself at one entry so the# expressions have an anchor to read, and that lone cohort opens at the aligned start of# `date_to`, which sits BEFORE `date_to` itself. Running the query would report whoever# arrived in that gap, so a range ending before it starts would return real retention data.return self._empty_response()+ if (+ self.query.summary+ and (self.query_date_range.date_to().date() - self.query_date_range.date_from().date()).days+ > MAX_SUMMARY_ACQUISITION_DAYS+ ):+ raise ValueError(+ f"Retention summary supports acquisition periods of up to {MAX_SUMMARY_ACQUISITION_DAYS} days."+ )+query = self.to_query()response = execute_hogql_query(@@ -647,6 +663,19 @@ class MarketingAnalyticsRetentionQueryRunner(columns = response.columns or []named_results = [dict(zip(columns, row)) for row in response.results or []]+ if self.query.summary:+ from posthog.schema import MarketingAnalyticsRetentionSummaryRow++ summary = [MarketingAnalyticsRetentionSummaryRow(**row) for row in named_results]+ return self._empty_response().model_copy(+ update={+ "summary": summary,+ "totalCohortSize": sum(row.acquired for row in summary if not row.previous),+ "hogql": response.hogql,+ "timings": response.timings,+ }+ )+# The CROSS JOIN puts the same pre-folding count on every row, so read it off the first one.distinct_breakdowns = int(named_results[0].get(_DISTINCT_BREAKDOWNS) or 0) if named_results else 0rows = self._build_rows(named_results)@@ -674,6 +703,7 @@ class MarketingAnalyticsRetentionQueryRunner(otherBreakdownCount=0,truncatedCohorts=0,totalCohortSize=0,+ summary=[] if self.query.summary else None,modifiers=self.modifiers,)diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_retention_summary.py b/products/marketing_analytics/backend/hogql_queries/marketing_retention_summary.pynew file mode 100644index 000000000000..bf0f3ffd4bb2--- /dev/null+++ b/products/marketing_analytics/backend/hogql_queries/marketing_retention_summary.py@@ -0,0 +1,155 @@+from datetime import timedelta+from typing import TYPE_CHECKING++from posthog.schema import DateRange, IntervalType++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.hogql_queries.utils.breakdowns import BREAKDOWN_OTHER_STRING_LABEL+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange++if TYPE_CHECKING:+ from .marketing_retention_query_runner import MarketingAnalyticsRetentionQueryRunner+++def build_summary_query(runner: "MarketingAnalyticsRetentionQueryRunner") -> ast.SelectQuery:+ periods = [runner]+ date_range = runner.query_date_range+ if runner.query.comparePreviousPeriod:+ previous_range = QueryPreviousPeriodDateRange(+ date_range=runner.query.dateRange,+ team=runner.team,+ interval=IntervalType.DAY,+ now=date_range.now_with_timezone,+ )+ start, end = previous_range.date_from(), previous_range.date_to()+ periods.append(+ type(runner)(+ query=runner.query.model_copy(+ update={+ "dateRange": DateRange(date_from=start.isoformat(), date_to=end.isoformat(), explicitDate=True)+ }+ ),+ team=runner.team,+ user=runner.user,+ )+ )++ ctes: dict[str, ast.CTE] = {}+ acquisitions: list[ast.SelectQuery] = []+ for index, period in enumerate(periods):+ acquired = period._build_first_session_select()+ acquired.select.extend(+ [+ ast.Alias(alias="previous", expr=ast.Constant(value=bool(index))),+ ast.Alias(+ alias="observation_end",+ expr=ast.Constant(+ value=period.query_date_range.format_date(+ min(+ period.query_date_range.date_to() + timedelta(days=30),+ date_range.now_with_timezone,+ )+ )+ ),+ ),+ ast.Alias(+ alias="first_session_id",+ expr=ast.Call(+ name="argMin",+ args=[+ ast.Field(chain=["events", "$session_id"]),+ ast.Field(chain=["events", "session", "$start_timestamp"]),+ ],+ ),+ ),+ ]+ )+ acquisitions.append(acquired)+ ctes["acquisition"] = ast.CTE(+ name="acquisition",+ expr=ast.SelectSetQuery.create_from_queries(acquisitions, set_operator="UNION ALL")+ if len(acquisitions) > 1+ else acquisitions[0],+ cte_type="subquery",+ materialized=True,+ )+ activity = parse_select(+ """+ SELECT acquisition.actor_id AS actor_id, acquisition.previous AS previous,+ min(events.session.$start_timestamp) AS returned_at+ FROM events+ INNER JOIN acquisition ON events.person_id = acquisition.actor_id+ WHERE events.event = '$pageview' AND notEmpty(events.$session_id)+ AND events.timestamp >= toDateTime({start})+ AND events.timestamp <= toDateTime({end})+ AND events.$session_id != acquisition.first_session_id+ AND events.session.$start_timestamp > acquisition.first_session_at+ AND events.session.$start_timestamp <= acquisition.first_session_at + INTERVAL 30 DAY+ AND events.session.$start_timestamp <= toDateTime(acquisition.observation_end)+ AND {filters}+ GROUP BY actor_id, previous+ """,+ {+ "start": ast.Constant(value=periods[-1]._cohort_window_start_str),+ "end": ast.Constant(+ value=date_range.format_date(+ min(date_range.date_to() + timedelta(days=30), date_range.now_with_timezone)+ )+ ),+ "filters": ast.And(exprs=runner._event_filters()) if runner._event_filters() else ast.Constant(value=True),+ },+ )+ assert isinstance(activity, ast.SelectQuery)+ assert activity.select_from and activity.select_from.next_join+ activity.select_from.next_join.join_type = "GLOBAL INNER JOIN"+ ctes["activity"] = ast.CTE(name="activity", expr=activity, cte_type="subquery")+ people = parse_select(+ """+ SELECT acquisition.actor_id AS actor_id, acquisition.breakdown_value AS breakdown_value,+ acquisition.previous AS previous, acquisition.first_session_at AS first_session_at,+ toDateTime(acquisition.observation_end) AS observation_end,+ activity.returned_at AS returned_at+ FROM acquisition+ LEFT JOIN activity ON acquisition.actor_id = activity.actor_id+ AND acquisition.previous = activity.previous+ """+ )+ ctes["people"] = ast.CTE(name="people", expr=people, cte_type="subquery", materialized=True)+ query = parse_select(+ """+ SELECT+ if(breakdown_value IN (+ SELECT breakdown_value FROM people GROUP BY breakdown_value+ ORDER BY countIf(NOT previous) DESC, count() DESC, breakdown_value ASC LIMIT {limit}+ ), breakdown_value, {other}) AS breakdownValue,+ previous,+ count() AS acquired,+ countIf(first_session_at + INTERVAL 7 DAY <= observation_end) AS eligible7d,+ countIf(first_session_at + INTERVAL 7 DAY <= observation_end+ AND returned_at > first_session_at+ AND returned_at <= first_session_at + INTERVAL 7 DAY) AS returned7d,+ countIf(first_session_at + INTERVAL 30 DAY <= observation_end) AS eligible30d,+ countIf(first_session_at + INTERVAL 30 DAY <= observation_end+ AND returned_at > first_session_at) AS returned30d,+ countIf(returned_at > first_session_at) AS returners,+ if(returners > 0,+ medianIf(+ dateDiff('second', first_session_at, returned_at) / 86400.0,+ returned_at > first_session_at),+ NULL) AS medianReturnDays+ FROM people+ GROUP BY breakdownValue, previous+ ORDER BY previous ASC, acquired DESC, breakdownValue ASC+ LIMIT {row_limit}+ """,+ {+ "limit": ast.Constant(value=runner.breakdown_limit),+ "other": ast.Constant(value=BREAKDOWN_OTHER_STRING_LABEL),+ "row_limit": ast.Constant(value=(runner.breakdown_limit + 1) * len(periods)),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ query.ctes = ctes+ return querydiff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.pyindex 9fc85e6cbacf..278b6560ddb8 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_retention_query_runner.py@@ -25,6 +25,7 @@ from posthog.test.persons import create_personfrom products.marketing_analytics.backend.hogql_queries.marketing_retention_query_runner import (MAX_BREAKDOWN_LIMIT,MAX_COHORTS,+ MAX_SUMMARY_ACQUISITION_DAYS,MAX_TOTAL_INTERVALS,MarketingAnalyticsRetentionQueryRunner,)@@ -54,17 +55,18 @@ class TestMarketingAnalyticsRetentionQueryRunner(ClickhouseTestMixin, BaseTest):utm_campaign: str | None = None,referring_domain: str | None = "$direct",path: str = "/",- ) -> None:+ ) -> str:# uuid7 seeds the session id so `$start_timestamp` lands on `started_at`, which is what the# acquisition window filters against. `$referring_domain` defaults to the `$direct` sentinel the# SDKs send when there is no referrer, without which `$channel_type` classifies as Unknown.+ session_id = str(uuid7(started_at))_create_event(team=self.team,event="$pageview",distinct_id=distinct_id,timestamp=started_at,properties={- "$session_id": str(uuid7(started_at)),+ "$session_id": session_id,"$current_url": f"https://example.com{path}","$pathname": path,**({"$referring_domain": referring_domain} if referring_domain is not None else {}),@@ -73,6 +75,8 @@ class TestMarketingAnalyticsRetentionQueryRunner(ClickhouseTestMixin, BaseTest):},)+ return session_id+def _query(self,breakdown: MarketingAnalyticsAttributionBreakdown = MarketingAnalyticsAttributionBreakdown.SOURCE,@@ -105,6 +109,97 @@ class TestMarketingAnalyticsRetentionQueryRunner(ClickhouseTestMixin, BaseTest):flush_persons_and_events()return MarketingAnalyticsRetentionQueryRunner(query=self._query(*args, **kwargs), team=self.team).calculate()+ @parameterized.expand([("unfolded", 20), ("folded", 1)])+ @time_machine.travel("2023-03-15T12:00:00Z", tick=False)+ def test_summary_counts_second_sessions_and_pools_return_times(self, _name: str, limit: int) -> None:+ for person in ["fast", "slow", "never", "tail"]:+ create_person(team=self.team, distinct_ids=[person])+ session_id = self._session(person, WEEK_0, utm_source="other-source" if person == "tail" else "newsletter")+ if person == "never":+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=person,+ timestamp="2023-01-04T12:05:00Z",+ properties={"$session_id": session_id},+ )+ self._session("fast", "2023-01-06T12:00:00Z", utm_source="different-source")+ self._session("fast", "2023-01-07T12:00:00Z", utm_source="different-source")+ self._session("slow", "2023-01-24T12:00:00Z")+ self._session("tail", "2023-02-03T12:00:00Z")+ self._session("never", "2023-02-04T12:00:00Z")+ flush_persons_and_events()+ query = self._query(date_from="2023-01-04", date_to="2023-01-04", breakdown_limit=limit)+ query.summary = True+ response = MarketingAnalyticsRetentionQueryRunner(query=query, team=self.team).calculate()+ rows = {row.breakdownValue: row for row in response.summary or []}+ row = rows["newsletter"]+ self.assertEqual(+ (row.acquired, row.eligible7d, row.returned7d, row.eligible30d, row.returned30d), (3, 3, 1, 3, 2)+ )+ self.assertEqual(row.returners, 2)+ assert row.medianReturnDays is not None+ self.assertAlmostEqual(row.medianReturnDays, 11)+ tail = rows["other-source" if limit == 20 else BREAKDOWN_OTHER_STRING_LABEL]+ self.assertEqual((tail.returned7d, tail.returned30d, tail.medianReturnDays), (0, 1, 30))+ self.assertEqual(response.totalCohortSize, 4)++ @time_machine.travel("2023-02-05T12:00:00Z", tick=False)+ def test_summary_eligibility_and_previous_period(self) -> None:+ for person, started, returned in [+ ("mature", "2023-01-04T12:00:00Z", "2023-01-11T12:00:00Z"),+ ("recent", "2023-02-04T12:00:00Z", "2023-02-05T10:00:00Z"),+ ("previous", "2022-12-20T12:00:00Z", "2022-12-21T12:00:00Z"),+ ]:+ create_person(team=self.team, distinct_ids=[person])+ self._session(person, started, utm_source="newsletter")+ self._session(person, returned)+ create_person(team=self.team, distinct_ids=["no-return"])+ self._session("no-return", "2023-02-04T12:00:00Z", utm_source="new-source")+ flush_persons_and_events()+ query = self._query(date_from="2023-01-04", date_to="2023-02-04")+ query.summary = True+ query.comparePreviousPeriod = True+ response = MarketingAnalyticsRetentionQueryRunner(query=query, team=self.team).calculate()+ current = next(row for row in response.summary or [] if not row.previous)+ previous = next(row for row in response.summary or [] if row.previous)+ self.assertEqual(+ (current.acquired, current.eligible7d, current.returned7d, current.eligible30d, current.returned30d),+ (2, 1, 1, 1, 1),+ )+ self.assertEqual(current.returners, 2)+ self.assertEqual((previous.acquired, previous.returned7d, previous.returned30d), (1, 1, 1))+ no_return = next(row for row in response.summary or [] if row.breakdownValue == "new-source")+ self.assertEqual((no_return.eligible7d, no_return.eligible30d, no_return.returners), (0, 0, 0))+ self.assertIsNone(no_return.medianReturnDays)++ @parameterized.expand(+ [+ ("relative_week", "-7d", "2023-02-19T12:00:00Z", "2023-02-20T12:00:00Z"),+ ("calendar_month", "mStart", "2023-01-31T12:00:00Z", "2023-02-01T12:00:00Z"),+ ]+ )+ @time_machine.travel("2023-03-06T12:00:00Z", tick=False)+ def test_summary_previous_period_boundaries(self, _name: str, date_from: str, outside: str, inside: str) -> None:+ for person, timestamp in [("outside", outside), ("inside", inside)]:+ create_person(team=self.team, distinct_ids=[person])+ self._session(person, timestamp, utm_source="newsletter")+ flush_persons_and_events()+ query = self._query(date_from=date_from)+ query.dateRange = DateRange(date_from=date_from)+ query.summary = True+ query.comparePreviousPeriod = True+ response = MarketingAnalyticsRetentionQueryRunner(query=query, team=self.team).calculate()+ previous = [row for row in response.summary or [] if row.previous]+ self.assertEqual([(row.breakdownValue, row.acquired) for row in previous], [("newsletter", 1)])++ def test_summary_rejects_acquisition_periods_over_the_limit(self) -> None:+ query = self._query(date_from="2023-01-01", date_to="2023-04-02")+ query.summary = True++ with pytest.raises(ValueError, match=f"up to {MAX_SUMMARY_ACQUISITION_DAYS} days"):+ MarketingAnalyticsRetentionQueryRunner(query=query, team=self.team).calculate()+@staticmethoddef _rows_by_value(response) -> dict[str, list]:rows: dict[str, list] = {}@@ -404,12 +499,18 @@ class TestMarketingAnalyticsRetentionQueryRunner(ClickhouseTestMixin, BaseTest):assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshotdef _printed_sql(self, **kwargs) -> str:- runner = MarketingAnalyticsRetentionQueryRunner(query=self._query(**kwargs), team=self.team)+ summary = kwargs.pop("summary", False)+ compare_previous_period = kwargs.pop("compare_previous_period", False)+ query = self._query(**kwargs)+ query.summary = summary+ query.comparePreviousPeriod = compare_previous_period+ runner = MarketingAnalyticsRetentionQueryRunner(query=query, team=self.team)context = runner._shared_hogql_context# execute_hogql_query flips this on the context it is handed; do the same to print the real query.context.enable_select_queries = Trueprinted = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")- return pretty_print_in_tests(printed[0] if isinstance(printed, tuple) else printed, self.team.pk)+ pretty = pretty_print_in_tests(printed[0] if isinstance(printed, tuple) else printed, self.team.pk)+ return "\n".join(line.rstrip() for line in pretty.splitlines()) if summary else pretty# `test_query_shape` snapshots the HogQL, which cannot show what the printer does with it. These# snapshot the ClickHouse the database actually runs, one case per query shape rather than one per@@ -421,6 +522,7 @@ class TestMarketingAnalyticsRetentionQueryRunner(ClickhouseTestMixin, BaseTest):("source", {"breakdown": MarketingAnalyticsAttributionBreakdown.SOURCE}),("channel", {"breakdown": MarketingAnalyticsAttributionBreakdown.CHANNEL}),("all_users", {"only_new_users": False}),+ ("summary", {"summary": True, "compare_previous_period": True}),])@pytest.mark.usefixtures("unittest_snapshot")diff --git a/products/marketing_analytics/frontend/retention/RetentionReturnTable.stories.tsx b/products/marketing_analytics/frontend/retention/RetentionReturnTable.stories.tsxnew file mode 100644index 000000000000..7c70d9e42144--- /dev/null+++ b/products/marketing_analytics/frontend/retention/RetentionReturnTable.stories.tsx@@ -0,0 +1,86 @@+import type { Meta, StoryObj } from '@storybook/react'++import { RetentionReturnTable } from './RetentionReturnTable'++const meta: Meta<typeof RetentionReturnTable> = {+ title: 'Marketing analytics/Retention return table',+ component: RetentionReturnTable,+ decorators: [+ (Story) => (+ <div className="w-[1100px] max-w-full">+ <Story />+ </div>+ ),+ ],+ args: {+ dimensionLabel: 'Source',+ loading: false,+ compare: true,+ onlyNewUsers: true,+ rows: [+ {+ breakdownValue: 'newsletter',+ previous: false,+ acquired: 400,+ eligible7d: 320,+ returned7d: 80,+ eligible30d: 200,+ returned30d: 70,+ returners: 130,+ medianReturnDays: 3.5,+ },+ {+ breakdownValue: 'newsletter',+ previous: true,+ acquired: 350,+ eligible7d: 350,+ returned7d: 70,+ eligible30d: 350,+ returned30d: 105,+ returners: 105,+ medianReturnDays: 4.8,+ },+ {+ breakdownValue: 'search',+ previous: false,+ acquired: 600,+ eligible7d: 480,+ returned7d: 48,+ eligible30d: 300,+ returned30d: 60,+ returners: 95,+ medianReturnDays: 8.2,+ },+ {+ breakdownValue: 'recent-source',+ previous: false,+ acquired: 20,+ eligible7d: 0,+ returned7d: 0,+ eligible30d: 0,+ returned30d: 0,+ returners: 0,+ medianReturnDays: null,+ },+ ],+ },+}+export default meta++type Story = StoryObj<typeof meta>+export const Default: Story = {}+export const AllUsers: Story = { args: { onlyNewUsers: false } }+export const Narrow: Story = {+ decorators: [+ (Story) => (+ <div className="w-[512px] max-w-full">+ <Story />+ </div>+ ),+ ],+}+export const Loading: Story = {+ args: { loading: true, rows: [] },+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+}+export const Empty: Story = { args: { rows: [] } }diff --git a/products/marketing_analytics/frontend/retention/RetentionReturnTable.tsx b/products/marketing_analytics/frontend/retention/RetentionReturnTable.tsxnew file mode 100644index 000000000000..3817000b82b9--- /dev/null+++ b/products/marketing_analytics/frontend/retention/RetentionReturnTable.tsx@@ -0,0 +1,147 @@+import { LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'++import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'+import { displayBreakdownValue } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'+import { VariationCell } from 'scenes/web-analytics/tiles/WebAnalyticsTile'++import { MarketingAnalyticsRetentionSummaryRow } from '~/queries/schema/schema-general'++const CountCell = VariationCell({ reserveTrendSpace: false })+const RateCell = VariationCell({ isPercentage: true })+const DaysCell = VariationCell({ neutral: true, formatValue: (value) => value.toFixed(1) })++type ReturnRow = MarketingAnalyticsRetentionSummaryRow & { comparison?: MarketingAnalyticsRetentionSummaryRow }++function returnRate(row: MarketingAnalyticsRetentionSummaryRow | undefined, days: 7 | 30): number | null {+ const eligible = days === 7 ? row?.eligible7d : row?.eligible30d+ const returned = days === 7 ? row?.returned7d : row?.returned30d+ return eligible ? (returned ?? 0) / eligible : null+}++export function RetentionReturnTable({+ rows,+ dimensionLabel,+ loading,+ compare,+ onlyNewUsers,+}: {+ rows: MarketingAnalyticsRetentionSummaryRow[]+ dimensionLabel: string+ loading: boolean+ compare: boolean+ onlyNewUsers: boolean+}): JSX.Element {+ const previous = new Map(rows.filter((row) => row.previous).map((row) => [row.breakdownValue, row]))+ const current = rows.filter((row) => !row.previous)+ const total = current.reduce((sum, row) => sum + row.acquired, 0)+ const data: ReturnRow[] = current.map((row) => ({ ...row, comparison: previous.get(row.breakdownValue) }))+ const columns: LemonTableColumn<ReturnRow, keyof ReturnRow | undefined>[] = [+ {+ title: dimensionLabel,+ dataIndex: 'breakdownValue',+ render: (_, row) => (+ <span className="block truncate" title={displayBreakdownValue(row.breakdownValue, dimensionLabel)}>+ {displayBreakdownValue(row.breakdownValue, dimensionLabel)}+ </span>+ ),+ },+ {+ title: <span className="whitespace-normal">{onlyNewUsers ? 'New users' : 'Users'}</span>,+ key: 'acquired',+ align: 'right',+ tooltip: onlyNewUsers+ ? 'People whose first qualifying session was in the selected date range.'+ : 'People with a qualifying session in the selected date range.',+ sorter: (a, b) => a.acquired - b.acquired,+ render: (_, row) => (+ <div className="flex flex-col items-end tabular-nums @min-[40rem]:flex-row @min-[40rem]:justify-end @min-[40rem]:gap-3">+ <CountCell+ value={[row.acquired, row.comparison?.acquired ?? null]}+ context={{ compareFilter: { compare: compare && row.comparison !== undefined } }}+ tooltipContent={`${percentage(total ? row.acquired / total : 0, 1)} of ${onlyNewUsers ? 'new users' : 'users'}`}+ />+ <span className="text-secondary text-xs w-12 shrink-0 text-right">+ {percentage(total ? row.acquired / total : 0, 1)}+ </span>+ </div>+ ),+ },+ ...([7, 30] as const).map(+ (days): LemonTableColumn<ReturnRow, keyof ReturnRow | undefined> => ({+ title: (+ <span className="whitespace-normal">+ <span className="hidden @min-[40rem]:inline">{`${days}-day return rate`}</span>+ <span className="@min-[40rem]:hidden">{`${days}d return`}</span>+ </span>+ ),+ key: `return${days}`,+ align: 'right',+ tooltip: `People with a second session within ${days} days of acquisition. Only users who have had the full ${days} days are eligible.`,+ sorter: (a, b) => (returnRate(a, days) ?? -1) - (returnRate(b, days) ?? -1),+ render: (_, row) => {+ const rate = returnRate(row, days)+ const eligible = days === 7 ? row.eligible7d : row.eligible30d+ const returned = days === 7 ? row.returned7d : row.returned30d+ return rate === null ? (+ <Tooltip title={`No users have completed ${days} days since acquisition yet.`}>+ <span className="text-muted">–</span>+ </Tooltip>+ ) : (+ <RateCell+ value={[rate, returnRate(row.comparison, days)]}+ context={{+ compareFilter: {+ compare: compare && returnRate(row.comparison, days) !== null,+ },+ }}+ tooltipContent={`${humanFriendlyNumber(returned)} returned out of ${humanFriendlyNumber(eligible)} eligible users.`}+ />+ )+ },+ })+ ),+ {+ title: <span className="whitespace-normal">Days to return</span>,+ dataIndex: 'medianReturnDays',+ align: 'right',+ tooltip:+ 'Estimated median days from the first to the second session, among people observed returning within 30 days. Recent users have had less time to return.',+ sorter: (a, b) => (a.medianReturnDays ?? Infinity) - (b.medianReturnDays ?? Infinity),+ render: (_, row) =>+ row.medianReturnDays === null ? (+ <Tooltip title="No second sessions observed within 30 days.">+ <span className="text-muted">–</span>+ </Tooltip>+ ) : (+ <DaysCell+ value={[row.medianReturnDays, row.comparison?.medianReturnDays ?? null]}+ context={{+ compareFilter: { compare: compare && row.comparison?.medianReturnDays != null },+ }}+ tooltipContent={`Based on ${humanFriendlyNumber(row.returners)} returning users.`}+ />+ ),+ },+ ]+ return (+ <div className="@container flex flex-col gap-2">+ {compare && <div className="text-secondary text-xs">Compared with the previous acquisition period</div>}+ <LemonTable+ className="@max-[40rem]:[&_.sorting-indicator]:hidden"+ tableLayout="fixed"+ columns={columns}+ dataSource={loading ? [] : data}+ loading={loading}+ rowKey="breakdownValue"+ defaultSorting={{ columnKey: 'acquired', order: -1 }}+ firstColumnSticky+ size="small"+ emptyState='No users match this acquisition period. Widen the date range or turn off "Only new users".'+ />+ <div className="text-secondary text-xs">+ Return rates include only users who completed each window. Days to return includes observed returns+ within 30 days and may change as recent users return.+ </div>+ </div>+ )+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1548b73cedd1..54ebbe5be2e4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46383,6 +46383,20 @@ export namespace Schemas {values: MarketingAnalyticsRetentionCell[];}+ export interface MarketingAnalyticsRetentionSummaryRow {+ acquired: number;+ breakdownValue: string;+ eligible30d: number;+ eligible7d: number;+ /** Median elapsed days to a second session within 30 days, among observed returners. */+ medianReturnDays: number | null;+ previous: boolean;+ returned30d: number;+ returned7d: number;+ /** People with an observed second session within 30 days, including incomplete windows. */+ returners: number;+ }+export interface MarketingAnalyticsRetentionQueryResponse {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -46404,6 +46418,8 @@ export namespace Schemas {/** The date range used for the query */resolved_date_range?: ResolvedDateRangeResponse | null;results: MarketingAnalyticsRetentionRow[];+ /** Only populated in summary mode. Rates use the corresponding eligible population. */+ summary?: MarketingAnalyticsRetentionSummaryRow[] | null;/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;/** Distinct persons acquired across every cohort and breakdown value. */@@ -46423,6 +46439,8 @@ export namespace Schemas {breakdownBy?: MarketingAnalyticsAttributionBreakdown | null;/** Breakdown values kept before the rest roll into 'Other'. Defaults to 20. */breakdownLimit?: number | null;+ /** Include the previous acquisition period in summary mode. Defaults to false. */+ comparePreviousPeriod?: boolean | null;/** Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility */dataColorTheme?: number | null;dateRange?: DateRange | null;@@ -46443,6 +46461,8 @@ export namespace Schemas {response?: MarketingAnalyticsRetentionQueryResponse | null;/** Period for both the cohort rows and the return columns. Defaults to week. */retentionInterval?: MarketingAnalyticsRetentionInterval | null;+ /** Return session-based 7/30-day metrics instead of the cohort matrix. Defaults to false. */+ summary?: boolean | null;tags?: QueryLogTags | null;/** Return columns, counting period 0. Defaults to 8, clamped to 40. */totalIntervals?: number | null;@@ -76996,6 +77016,8 @@ export namespace Schemas {/** The date range used for the query */resolved_date_range?: ResolvedDateRangeResponse | null;results: MarketingAnalyticsRetentionRow[];+ /** Only populated in summary mode. Rates use the corresponding eligible population. */+ summary?: MarketingAnalyticsRetentionSummaryRow[] | null;/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;/** Distinct persons acquired across every cohort and breakdown value. */