: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
refactor(insights): make retention chart transforms bundle-neutral (#62633)
Sam Penningtonfa152dbeceae
diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.tsindex fd64071ce37c..fa7ca1da7e97 100644--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts@@ -1,15 +1,32 @@import type { Series, TooltipConfig } from '@posthog/quill-charts'+import type { RetentionTrendPayload } from 'scenes/retention/types'+import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'+import type { GoalLineLike } from 'products/product_analytics/frontend/insights/trends/shared/trendsChartDisplayOptions'+import {buildRetentionBarChartConfig,+ buildRetentionChartModel,buildRetentionLineChartConfig,buildRetentionSeries,+ type RetentionCohortLike,+ computeRetentionSeriesValue,+ formatRetentionCohortLabel,+ type RetentionResultLike,type RetentionSeriesMeta,type RetentionTrendSeriesEntry,+ sortRetentionCohorts,} from './retentionChartTransforms'+// The neutral structural types in retentionChartTransforms.ts exist so the shared chart code stays+// free of `~/` and `scenes/` imports (the MCP Vite bundle can't resolve them). These helpers' return+// types enforce that the real schema types stay assignable to the neutral ones — if a schema field+// ever changes shape, the returns fail to compile and flag the drift here rather than at a call site.+const asNeutralRetentionResult = (r: RetentionTrendPayload): RetentionResultLike => r+const asNeutralGoalLine = (g: SchemaGoalLine): GoalLineLike => g+const makeEntry = (overrides: Partial<RetentionTrendSeriesEntry> = {}): RetentionTrendSeriesEntry => ({count: 100,data: [100, 80, 60, 40, 20],@@ -23,6 +40,21 @@ const makeEntry = (overrides: Partial<RetentionTrendSeriesEntry> = {}): Retentioconst TOOLTIP: TooltipConfig = { pinnable: true, placement: 'top' }describe('retentionChartTransforms', () => {+ describe('schema type firewall', () => {+ it('keeps the schema RetentionTrendPayload / GoalLine assignable to the neutral structural types', () => {+ expect(+ asNeutralRetentionResult({+ count: 100,+ data: [100, 50],+ days: ['2024-01-01', '2024-01-02'],+ labels: ['Day 0', 'Day 1'],+ index: 0,+ })+ ).toMatchObject({ count: 100 })+ expect(asNeutralGoalLine({ label: 'goal', value: 10 })).toMatchObject({ label: 'goal', value: 10 })+ })+ })+describe('buildRetentionSeries', () => {it('builds one series per payload, keyed by row index', () => {const series = buildRetentionSeries([makeEntry({ index: 0 }), makeEntry({ index: 1 })], {@@ -199,4 +231,162 @@ describe('retentionChartTransforms', () => {expect(config.tooltip).toBe(TOOLTIP)})})++ describe('computeRetentionSeriesValue', () => {+ const values = [{ count: 100 }, { count: 50 }, { count: 0 }]++ it.each([+ { intervalIndex: 0, reference: 'total', expected: 100, desc: 'total: interval 0 is 100%' },+ { intervalIndex: 1, reference: 'total', expected: 50, desc: 'total: percentage of baseline' },+ { intervalIndex: 0, reference: 'previous', expected: 100, desc: 'previous: interval 0 is 100%' },+ { intervalIndex: 1, reference: 'previous', expected: 50, desc: 'previous: percentage of prior interval' },+ ])('count aggregation — $desc', ({ intervalIndex, reference, expected }) => {+ expect(computeRetentionSeriesValue(values, intervalIndex, 'count', reference)).toBe(expected)+ })++ it.each([+ { values: [{ count: 0 }, { count: 5 }], desc: 'baseline of 0' },+ { values: [{ count: 100 }], desc: 'missing interval' },+ ])('count aggregation returns 0 for $desc', ({ values: vals }) => {+ expect(computeRetentionSeriesValue(vals, 1, 'count', 'total')).toBe(0)+ })++ it('non-count aggregation surfaces aggregation_value directly', () => {+ expect(computeRetentionSeriesValue([{ count: 1, aggregation_value: 42 }], 0, 'sum', 'total')).toBe(42)+ })+ })++ describe('sortRetentionCohorts', () => {+ it('orders cohorts chronologically and keeps dateless cohorts last in original order', () => {+ const cohorts: RetentionCohortLike[] = [+ { date: '2024-03-01', values: [] },+ { date: null, values: [], breakdown_value: 'first-dateless' },+ { date: '2024-01-01', values: [] },+ { date: null, values: [], breakdown_value: 'second-dateless' },+ ]+ expect(sortRetentionCohorts(cohorts).map((c) => c.date ?? c.breakdown_value)).toEqual([+ '2024-01-01',+ '2024-03-01',+ 'first-dateless',+ 'second-dateless',+ ])+ })+ })++ describe('buildRetentionChartModel', () => {+ const colorAt = (i: number): string => `c${i}`+ const cohort = (date: string, counts: number[]): RetentionCohortLike => ({+ date,+ values: counts.map((count) => ({ count })),+ })++ it('caps to maxCohorts but reports the full total, and labels by period', () => {+ const cohorts = [+ cohort('2024-01-01', [100, 50]),+ cohort('2024-01-02', [80, 40]),+ cohort('2024-01-03', [60, 30]),+ ]+ const model = buildRetentionChartModel(cohorts, {+ aggregationType: 'count',+ reference: 'total',+ period: 'Day',+ getColor: colorAt,+ maxCohorts: 2,+ })++ expect(model.totalCohorts).toBe(3)+ expect(model.series).toHaveLength(2)+ expect(model.series.map((s) => s.color)).toEqual(['c0', 'c1'])+ expect(model.labels).toEqual(['Day 0', 'Day 1'])+ expect(model.series[0].data).toEqual([100, 50])+ })++ it.each([+ { aggregationType: 'count', expectedLabel: 'Retention %', expectedFormat: 'percentage' },+ { aggregationType: 'sum', expectedLabel: 'Sum', expectedFormat: 'numeric' },+ { aggregationType: 'avg', expectedLabel: 'Avg', expectedFormat: 'numeric' },+ ])('labels the y-axis for $aggregationType', ({ aggregationType, expectedLabel, expectedFormat }) => {+ const model = buildRetentionChartModel([cohort('2024-01-01', [100, 50])], {+ aggregationType,+ reference: 'total',+ period: 'Day',+ getColor: colorAt,+ maxCohorts: 6,+ })+ expect(model.lineConfig.yAxis?.label).toBe(expectedLabel)+ expect(model.barConfig.yAxis?.label).toBe(expectedLabel)+ expect(model.lineConfig.yAxis?.format).toBe(expectedFormat)+ })+ })++ describe('formatRetentionCohortLabel', () => {+ const withDate = (date: string | null, breakdown?: string | number | null): RetentionCohortLike => ({+ date,+ breakdown_value: breakdown,+ values: [{ count: 1 }],+ })++ // TZ is pinned to UTC in jest.config, so these locale strings are deterministic.+ it.each([+ {+ name: 'Day period',+ cohort: withDate('2024-03-15'),+ num: 1,+ period: 'Day',+ expected: 'Cohort 1 (Mar 15)',+ },+ {+ name: 'Week falls back to day format',+ cohort: withDate('2024-03-15'),+ num: 2,+ period: 'Week',+ expected: 'Cohort 2 (Mar 15)',+ },+ {+ name: 'Month period',+ cohort: withDate('2024-03-15'),+ num: 3,+ period: 'Month',+ expected: 'Cohort 3 (Mar 2024)',+ },+ {+ name: 'Hour period',+ cohort: withDate('2024-03-15T13:00:00Z'),+ num: 4,+ period: 'Hour',+ expected: 'Cohort 4 (Mar 15, 1 PM)',+ },+ {+ name: 'breakdown + date',+ cohort: withDate('2024-03-15', 'Chrome'),+ num: 1,+ period: 'Day',+ expected: 'Cohort 1 (Chrome, Mar 15)',+ },+ {+ name: 'breakdown, no date',+ cohort: withDate(null, 'Chrome'),+ num: 1,+ period: 'Day',+ expected: 'Cohort 1 (Chrome)',+ },+ {+ name: 'empty-string breakdown is ignored',+ cohort: withDate('2024-03-15', ''),+ num: 1,+ period: 'Day',+ expected: 'Cohort 1 (Mar 15)',+ },+ {+ name: 'invalid date, no breakdown',+ cohort: withDate('not-a-date'),+ num: 1,+ period: 'Day',+ expected: 'Cohort 1',+ },+ { name: 'null date, no breakdown', cohort: withDate(null), num: 7, period: 'Day', expected: 'Cohort 7' },+ ])('formats $name', ({ cohort, num, period, expected }) => {+ expect(formatRetentionCohortLabel(cohort, num, period)).toBe(expected)+ })+ })})diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.tsindex 5523f6059db2..79972cfcab85 100644--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts@@ -7,15 +7,26 @@ import type {TrendLineConfig,} from '@posthog/quill-charts'-import type { RetentionTrendPayload } from 'scenes/retention/types'--import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'-import { schemaGoalLinesToConfigs } from 'products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter'+import type { GoalLineLike } from 'products/product_analytics/frontend/insights/trends/shared/trendsChartDisplayOptions'++// Dependency-neutral shape both the kea `RetentionTrendPayload` and lighter fixtures (e.g. the MCP+// UI app) satisfy. Declared structurally rather than imported from `scenes/retention/types` so this+// module stays free of `~/`/`scenes/` deps and compiles in the MCP Vite bundle, which only resolves+// `products/*` and `@posthog/*`. The real `RetentionTrendPayload` is assignable to this (asserted in+// retentionChartTransforms.test.ts), so web callers pass it unchanged.+export interface RetentionResultLike {+ count: number+ data: number[]+ days?: string[]+ labels?: string[]+ index?: number+ breakdown_value?: string | number | null+}// `retentionGraphLogic.trendSeries` spreads `cohortRetention` onto each entry, so the// runtime shape includes a cohort `label` field that the declared type doesn't list.-export type RetentionTrendSeriesEntry = RetentionTrendPayload & { label?: string }+export type RetentionTrendSeriesEntry = RetentionResultLike & { label?: string }export interface RetentionSeriesMeta {/** Original row index from the unfiltered results — drives modal opens in non-interval view. */@@ -68,7 +79,7 @@ export function buildRetentionSeries(export interface BuildRetentionChartConfigOpts {isPercentage: boolean- goalLines?: SchemaGoalLine[] | null+ goalLines?: GoalLineLike[] | nullshowTrendLines?: booleanseries: Series<RetentionSeriesMeta>[]tooltip?: TooltipConfig@@ -84,7 +95,7 @@ function buildTrendLines(return series.map((s) => ({ seriesKey: s.key, kind: 'linear' }))}-function buildGoalLines(goalLines: SchemaGoalLine[] | null | undefined): GoalLineConfig[] | undefined {+function buildGoalLines(goalLines: GoalLineLike[] | null | undefined): GoalLineConfig[] | undefined {return schemaGoalLinesToConfigs(goalLines)}@@ -114,3 +125,177 @@ export function buildRetentionBarChartConfig(opts: BuildRetentionChartConfigOptstooltip: opts.tooltip,}}++// --- Cohort shaping ----------------------------------------------------------------------------+// Turns a raw retention query result into chart entries. Lives here (not in the MCP host) so the+// cohort math is unit-tested. Structural/neutral so it stays MCP-bundle-safe.++/** Structural cohort shape the MCP `RetentionResultItem` satisfies. */+export interface RetentionCohortLike {+ date?: string | null+ breakdown_value?: string | number | null+ values: { count: number; aggregation_value?: number | null }[]+}++function formatCohortStartDate(date: string | null | undefined, period: string): string | null {+ if (!date) {+ return null+ }+ const d = new Date(date)+ if (Number.isNaN(d.getTime())) {+ return null+ }+ if (period === 'Hour') {+ return d.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric' })+ }+ if (period === 'Month') {+ return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' })+ }+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })+}++export function formatRetentionCohortLabel(cohort: RetentionCohortLike, cohortNumber: number, period: string): string {+ const startDate = formatCohortStartDate(cohort.date, period)+ const breakdown =+ cohort.breakdown_value !== undefined && cohort.breakdown_value !== null && cohort.breakdown_value !== ''+ ? String(cohort.breakdown_value)+ : null+ const base = `Cohort ${cohortNumber}`+ if (breakdown) {+ return startDate ? `${base} (${breakdown}, ${startDate})` : `${base} (${breakdown})`+ }+ return startDate ? `${base} (${startDate})` : base+}++/** Mirrors retentionLogic: `count` aggregation → percentage of the reference cohort size+ * (`total` = interval 0, `previous` = preceding interval); other aggregations surface+ * `aggregation_value` directly. */+export function computeRetentionSeriesValue(+ values: RetentionCohortLike['values'],+ intervalIndex: number,+ aggregationType: string,+ reference: string+): number {+ const current = values[intervalIndex]+ if (!current) {+ return 0+ }+ if (aggregationType !== 'count') {+ return current.aggregation_value ?? 0+ }+ if (reference === 'previous') {+ if (intervalIndex === 0) {+ // referenceCount at interval 0 is the cohort's own size, so an empty cohort is 0%, not+ // 100% — mirrors retentionLogic's `referenceCount > 0 ? ... : 0`.+ return current.count > 0 ? 100 : 0+ }+ const prev = values[intervalIndex - 1]+ if (!prev || prev.count === 0) {+ return 0+ }+ return (current.count / prev.count) * 100+ }+ const baseline = values[0]?.count ?? 0+ if (baseline === 0) {+ return 0+ }+ return (current.count / baseline) * 100+}++/** Sorts cohorts chronologically; cohorts with a missing/invalid date keep their order at the end. */+export function sortRetentionCohorts<C extends RetentionCohortLike>(cohorts: C[]): C[] {+ return [...cohorts].sort((a, b) => {+ const ta = a.date ? new Date(a.date).getTime() : Number.POSITIVE_INFINITY+ const tb = b.date ? new Date(b.date).getTime() : Number.POSITIVE_INFINITY+ const aMissing = Number.isNaN(ta) || !Number.isFinite(ta)+ const bMissing = Number.isNaN(tb) || !Number.isFinite(tb)+ if (aMissing && bMissing) {+ return 0+ }+ if (aMissing) {+ return 1+ }+ if (bMissing) {+ return -1+ }+ return ta - tb+ })+}++// Known retention aggregations (`RetentionAggregationType`): 'count' (unique users, shown as a+// percentage), 'sum', and 'avg'. Any future/unknown aggregation falls back to 'Avg' rather than+// throwing — keep this in sync if the backend adds an aggregation type.+const RETENTION_Y_AXIS_LABELS: Record<string, string> = {+ count: 'Retention %',+ sum: 'Sum',+ avg: 'Avg',+}++function retentionYAxisLabel(aggregationType: string): string {+ return RETENTION_Y_AXIS_LABELS[aggregationType] ?? 'Avg'+}++export interface BuildRetentionChartModelOpts {+ aggregationType: string+ reference: string+ period: string+ showTrendLines?: boolean+ getColor: (index: number) => string+ tooltip?: TooltipConfig+ /** Cohorts beyond this are dropped so each line keeps a distinct palette color. */+ maxCohorts: number+}++export interface RetentionChartModel {+ series: Series<RetentionSeriesMeta>[]+ labels: string[]+ lineConfig: TimeSeriesLineChartConfig+ barConfig: TimeSeriesBarChartConfig+ /** Cohort count before the `maxCohorts` cap — lets the host show a truncation notice. */+ totalCohorts: number+}++/** Assembles the full retention chart model (sort → cap → per-interval values → series → line/bar+ * configs) so the MCP visualizer stays presentational and the cohort math is tested here. */+export function buildRetentionChartModel<C extends RetentionCohortLike>(+ cohorts: C[],+ opts: BuildRetentionChartModelOpts+): RetentionChartModel {+ const sorted = sortRetentionCohorts(cohorts)+ const limited = sorted.slice(0, opts.maxCohorts)+ const numIntervals = limited.reduce((max, c) => Math.max(max, c.values.length), 0)+ const labels = Array.from({ length: numIntervals }, (_, i) => `${opts.period} ${i}`)++ const entries: RetentionTrendSeriesEntry[] = limited.map((cohort, idx) => ({+ count: cohort.values[0]?.count ?? 0,+ data: Array.from({ length: numIntervals }, (_, i) =>+ computeRetentionSeriesValue(cohort.values, i, opts.aggregationType, opts.reference)+ ),+ labels,+ index: idx,+ label: formatRetentionCohortLabel(cohort, idx + 1, opts.period),+ }))++ const series = buildRetentionSeries(entries, { isIntervalView: false }).map((s, i) => ({+ ...s,+ color: opts.getColor(i),+ }))++ const isPercentage = opts.aggregationType === 'count'+ const yAxisLabel = retentionYAxisLabel(opts.aggregationType)+ const lineBase = buildRetentionLineChartConfig({+ isPercentage,+ showTrendLines: opts.showTrendLines,+ series,+ tooltip: opts.tooltip,+ })+ const barBase = buildRetentionBarChartConfig({ isPercentage, series, tooltip: opts.tooltip })++ return {+ series,+ labels,+ lineConfig: { ...lineBase, yAxis: { ...lineBase.yAxis, label: yAxisLabel } },+ barConfig: { ...barBase, yAxis: { ...barBase.yAxis, label: yAxisLabel } },+ totalCohorts: sorted.length,+ }+}