: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(insights): customize trends compare periods as one base series (#70406)
Thomas Obermüller6d3b3db75537
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4c67a06b4d06..0cb835af6798 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2725,9 +2725,9 @@ snapshots:insights-insightstable--compare-previous--light:hash: v1.k794b7964.28fa002817466cdc38906e70bc568a02c9d4080d4e696ec4013a2a538907b56d.yFhGtvxHTdLkBaBTudbBvH9CQbI3uANS3b2ycEIeKRYinsights-insightstable--compare-previous-detailed-results--dark:- hash: v1.k794b7964.a64b2e50f805705bbc9b8d2ebd207cebcd1202dc578004ab1e9dc477f02ff9aa.E8oFRn7xnK_56vtfgxYZuC1XNdTAUAc-aRld_poFGNk+ hash: v1.k794b7964.c99318f81cdc4a1e9d7dae8dba5d0727a84aa19c41036114fe8a395922db110b.tjGLu_ipVC3nNz-pebdemSE04ce-00kEzGbs7lRfKSoinsights-insightstable--compare-previous-detailed-results--light:- hash: v1.k794b7964.95d186cac16aa659249c098d76264c71a4f75af27fe8ddc458fb452371f4c584.gcfzOx0i14MOBQ7nvtxNXdOhyrG3zuxGFX1MY8SnYCY+ hash: v1.k794b7964.3981b9428cb05f4f8eab902d95a0900cb9a724309b124db04091a84ae2c5e90a.cL_ZiS6mBEh0i59RySIuPM6oT0zETFIc1u4glGzvzjIinsights-insightstable--default--dark:hash: v1.k794b7964.585aa3b95a71f83db72c958f68b5b9b28c05047625904238a18d840fd4abe38b.kbYrG-uIZ1A_25STyJcDiz6Ph7-N7rkj2HWE6g6eoy8insights-insightstable--default--light:diff --git a/frontend/src/queries/latest-versions.json b/frontend/src/queries/latest-versions.jsonindex bb55747963d1..542cc33843c3 100644--- a/frontend/src/queries/latest-versions.json+++ b/frontend/src/queries/latest-versions.json@@ -1,6 +1,6 @@{"//": "THIS FILE IS AUTOGENERATED. DO NOT EDIT MANUALLY. To update: pnpm run schema:build","RetentionQuery": 2,- "StickinessQuery": 2,- "TrendsQuery": 2+ "StickinessQuery": 3,+ "TrendsQuery": 3}diff --git a/frontend/src/scenes/data-management/events/propertyGroupTrendsQuery.ts b/frontend/src/scenes/data-management/events/propertyGroupTrendsQuery.tsindex bceb1e59f195..e529964a8e2e 100644--- a/frontend/src/scenes/data-management/events/propertyGroupTrendsQuery.ts+++ b/frontend/src/scenes/data-management/events/propertyGroupTrendsQuery.ts@@ -1,6 +1,7 @@import { dayjs } from 'lib/dayjs'import { EventsNode, InsightVizNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { setLatestVersionsOnQuery } from '~/queries/utils'import { BaseMathType, PropertyFilterType, PropertyOperator } from '~/types'import { SchemaPropertyGroupProperty } from '../schema/schemaManagementLogic'@@ -75,7 +76,6 @@ export function buildPropertyGroupTrendsQuery(const trendsQuery: TrendsQuery = {kind: NodeKind.TrendsQuery,series,- version: 2,interval: 'week',dateRange: {date_to: null,@@ -90,14 +90,14 @@ export function buildPropertyGroupTrendsQuery(}return {- query: {+ query: setLatestVersionsOnQuery<InsightVizNode>({kind: NodeKind.InsightVizNode,source: trendsQuery,showHeader: false,showTable: false,showFilters: false,embedded: true,- },+ }),isTruncated,totalProperties: properties.length,displayedProperties: limitedProperties.length,diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.tsindex 93bd378fdcfb..05f910107d45 100644--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts@@ -7,6 +7,7 @@ import { insightNavLogic } from 'scenes/insights/InsightNav/insightNavLogic'import { useMocks } from '~/mocks/jest'import { examples } from '~/queries/examples'+import { LATEST_VERSIONS } from '~/queries/latest-versions'import { nodeKindToDefaultQuery } from '~/queries/nodes/InsightQuery/defaults'import {EventsQuery,@@ -17,6 +18,7 @@ import {ProductKey,TrendsQuery,} from '~/queries/schema/schema-general'+import { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'import {BaseMathType,@@ -75,15 +77,14 @@ describe('insightNavLogic', () => {await expectLogic(builtInsightDataLogic, () => {logic.actions.setActiveView(InsightType.TRENDS)}).toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...nodeKindToDefaultQuery[NodeKind.TrendsQuery],filterTestAccounts: true,- version: 2,tags: PRODUCT_ANALYTICS_DEFAULT_QUERY_TAGS,},- },+ }),})})@@ -200,13 +201,12 @@ describe('insightNavLogic', () => {it('is initialized on mount', async () => {await expectLogic(logic).toMatchValues({- queryPropertyCache: {+ queryPropertyCache: setLatestVersionsOnQuery({...nodeKindToDefaultQuery[NodeKind.TrendsQuery],commonFilter: {},commonFilterTrendsStickiness: {},filterTestAccounts: true,- version: 2,- },+ }),})})@@ -550,6 +550,8 @@ describe('insightNavLogic', () => {await expectLogic(builtInsightDataLogic, () => {logic.actions.setActiveView(InsightType.TRENDS)}).toDispatchActions([+ // can't use setLatestVersionsOnQuery here: toDispatchActions compares actions via+ // JSON.stringify, so `version` must sit exactly where the logic inserts itbuiltInsightDataLogic.actionCreators.setQuery({kind: 'InsightVizNode',source: {@@ -560,7 +562,7 @@ describe('insightNavLogic', () => {],trendsFilter: {},filterTestAccounts: true,- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery],breakdownFilter: {breakdowns: [{ property: 'num', type: 'person' },@@ -574,7 +576,7 @@ describe('insightNavLogic', () => {})it('keeps breakdowns when switching between trends and funnels', async () => {- trendsQuery.source = {+ trendsQuery.source = setLatestVersionsOnQuery({...trendsQuery.source,breakdownFilter: {breakdowns: [@@ -582,8 +584,7 @@ describe('insightNavLogic', () => {{ property: '$device_type', type: 'event' },],},- version: 2,- } as TrendsQuery+ } as TrendsQuery)await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsQuery)@@ -625,7 +626,7 @@ describe('insightNavLogic', () => {})it('does not carry trends-only display settings into funnels', async () => {- const trendsQueryWithDisplay: InsightVizNode = {+ const trendsQueryWithDisplay: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -637,14 +638,13 @@ describe('insightNavLogic', () => {},],interval: 'hour',- version: 2,trendsFilter: {display: ChartDisplayType.ActionsBar,showPercentStackView: true,showValuesOnSeries: true,},},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsQueryWithDisplay)@@ -713,7 +713,7 @@ describe('insightNavLogic', () => {})it('preserves multiple breakdowns through round-trip via single-breakdown type', async () => {- const trendsWithMultipleBreakdowns: InsightVizNode = {+ const trendsWithMultipleBreakdowns: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -724,7 +724,6 @@ describe('insightNavLogic', () => {event: '$pageview',},],- version: 2,breakdownFilter: {breakdowns: [{ property: '$browser', type: 'event' },@@ -733,7 +732,7 @@ describe('insightNavLogic', () => {],},},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithMultipleBreakdowns)@@ -760,12 +759,11 @@ describe('insightNavLogic', () => {})it('restores original breakdowns on round-trip even after edits on intermediate type', async () => {- const trendsWithMultipleBreakdowns: InsightVizNode = {+ const trendsWithMultipleBreakdowns: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,series: [{ kind: NodeKind.EventsNode, name: '$pageview', event: '$pageview' }],- version: 2,breakdownFilter: {breakdowns: [{ property: '$browser', type: 'event' },@@ -773,7 +771,7 @@ describe('insightNavLogic', () => {],},},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithMultipleBreakdowns)@@ -808,15 +806,14 @@ describe('insightNavLogic', () => {})it('restores minute interval on round-trip even after edits on intermediate type', async () => {- const trendsWithMinute: InsightVizNode = {+ const trendsWithMinute: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,series: [{ kind: NodeKind.EventsNode, name: '$pageview', event: '$pageview' }],interval: 'minute',- version: 2,},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithMinute)@@ -844,7 +841,7 @@ describe('insightNavLogic', () => {})it('preserves breakdownFilter through round-trip via unsupported type', async () => {- const trendsWithBreakdown: InsightVizNode = {+ const trendsWithBreakdown: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -855,13 +852,12 @@ describe('insightNavLogic', () => {event: '$pageview',},],- version: 2,breakdownFilter: {breakdown: '$browser',breakdown_type: 'event',},},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithBreakdown)@@ -891,7 +887,7 @@ describe('insightNavLogic', () => {})it('truncates multi-breakdowns on multi-hop transition through unsupported type back to funnels', async () => {- const trendsWithMultipleBreakdowns: InsightVizNode = {+ const trendsWithMultipleBreakdowns: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -902,7 +898,6 @@ describe('insightNavLogic', () => {event: '$pageview',},],- version: 2,breakdownFilter: {breakdowns: [{ property: '$browser', type: 'event' },@@ -910,7 +905,7 @@ describe('insightNavLogic', () => {],},},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithMultipleBreakdowns)@@ -941,7 +936,7 @@ describe('insightNavLogic', () => {})it('preserves compareFilter through round-trip via unsupported type', async () => {- const trendsWithCompare: InsightVizNode = {+ const trendsWithCompare: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -952,10 +947,9 @@ describe('insightNavLogic', () => {event: '$pageview',},],- version: 2,compareFilter: { compare: true },},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithCompare)@@ -982,7 +976,7 @@ describe('insightNavLogic', () => {})it('preserves interval through round-trip via type with no interval support', async () => {- const trendsWithInterval: InsightVizNode = {+ const trendsWithInterval: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -993,10 +987,9 @@ describe('insightNavLogic', () => {event: '$pageview',},],- version: 2,interval: 'week',},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithInterval)@@ -1025,7 +1018,7 @@ describe('insightNavLogic', () => {})it('filters breakdowns to person/event types when switching to retention', async () => {- const trendsWithGroupBreakdown: InsightVizNode = {+ const trendsWithGroupBreakdown: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -1036,7 +1029,6 @@ describe('insightNavLogic', () => {event: '$pageview',},],- version: 2,breakdownFilter: {breakdowns: [{ property: '$browser', type: 'event' },@@ -1045,7 +1037,7 @@ describe('insightNavLogic', () => {],},},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsWithGroupBreakdown)@@ -1068,7 +1060,7 @@ describe('insightNavLogic', () => {})it('keeps display when switching from trends to stickiness', async () => {- const trendsQueryForStickiness: InsightVizNode = {+ const trendsQueryForStickiness: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {kind: NodeKind.TrendsQuery,@@ -1080,13 +1072,12 @@ describe('insightNavLogic', () => {},],interval: 'hour',- version: 2,trendsFilter: {display: ChartDisplayType.ActionsBar,showValuesOnSeries: true,},},- }+ })await expectLogic(logic, () => {builtInsightDataLogic.actions.setQuery(trendsQueryForStickiness)diff --git a/frontend/src/scenes/insights/insightDataLogic.test.ts b/frontend/src/scenes/insights/insightDataLogic.test.tsindex 6c903962b4c0..7384bd693619 100644--- a/frontend/src/scenes/insights/insightDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightDataLogic.test.ts@@ -24,6 +24,7 @@ import {ResultCustomizationBy,TrendsQuery,} from '~/queries/schema/schema-general'+import { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'import { FunnelVizType, InsightShortId, InsightType } from '~/types'@@ -298,7 +299,7 @@ describe('insightDataLogic', () => {}).toDispatchActions(['setQuery']).toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {breakdownFilter: {@@ -358,9 +359,8 @@ describe('insightDataLogic', () => {trendsFilter: {display: 'ActionsAreaGraph',},- version: 2,},- },+ }),})})it('does not set query override is not set', async () => {diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.tsindex 1ccab3d9c557..8dc546e61755 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts@@ -6,8 +6,10 @@ import { funnelInvalidExclusionError, funnelResult } from 'scenes/funnels/__mockimport { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { useMocks } from '~/mocks/jest'+import { LATEST_VERSIONS } from '~/queries/latest-versions'import { funnelsQueryDefault, trendsQueryDefault } from '~/queries/nodes/InsightQuery/defaults'import { FunnelsQuery, LifecycleQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'import {BaseMathType,@@ -56,14 +58,13 @@ describe('insightVizDataLogic', () => {expectLogic(builtInsightDataLogic, () => {builtInsightVizDataLogic.actions.updateQuerySource({ filterTestAccounts: true })}).toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,filterTestAccounts: true,- version: 2,},- },+ }),})expect(builtInsightVizDataLogic.values.querySource).toMatchObject({ filterTestAccounts: true })@@ -72,23 +73,23 @@ describe('insightVizDataLogic', () => {expectLogic(builtInsightDataLogic, () => {builtInsightVizDataLogic.actions.updateQuerySource({ samplingFactor: 0.1 })}).toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,filterTestAccounts: true,samplingFactor: 0.1,- version: 2,},- },+ }),})- expect(builtInsightVizDataLogic.values.querySource).toEqual({- ...trendsQueryDefault,- filterTestAccounts: true,- samplingFactor: 0.1,- version: 2,- })+ expect(builtInsightVizDataLogic.values.querySource).toEqual(+ setLatestVersionsOnQuery({+ ...trendsQueryDefault,+ filterTestAccounts: true,+ samplingFactor: 0.1,+ })+ )})it('handles funnel step range side effects', () => {@@ -120,7 +121,7 @@ describe('insightVizDataLogic', () => {funnelToStep: 1,},trendsFilter: {}, // we currently don't remove insight filters of previous query kinds- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery], // carried over from the initial trends source, like the stale trendsFilter},},})@@ -169,7 +170,7 @@ describe('insightVizDataLogic', () => {],},trendsFilter: {},- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery], // carried over from the initial trends source, like the stale trendsFilter},},})@@ -219,7 +220,7 @@ describe('insightVizDataLogic', () => {},],trendsFilter: {},- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery], // carried over from the initial trends source, like the stale trendsFilter},},})@@ -284,7 +285,7 @@ describe('insightVizDataLogic', () => {},],trendsFilter: {},- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery], // carried over from the initial trends source, like the stale trendsFilter},},})@@ -360,7 +361,7 @@ describe('insightVizDataLogic', () => {}).toFinishAllListeners().toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,@@ -370,9 +371,8 @@ describe('insightVizDataLogic', () => {date_to: null,explicitDate: false,},- version: 2,},- },+ }),})expect(builtInsightVizDataLogic.values.dateRange).toEqual({@@ -389,7 +389,7 @@ describe('insightVizDataLogic', () => {}).toFinishAllListeners().toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,@@ -399,9 +399,8 @@ describe('insightVizDataLogic', () => {date_to: '-3d',explicitDate: false,},- version: 2,},- },+ }),})expect(builtInsightVizDataLogic.values.dateRange).toEqual({@@ -513,7 +512,7 @@ describe('insightVizDataLogic', () => {}).toFinishAllListeners().toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,@@ -521,9 +520,8 @@ describe('insightVizDataLogic', () => {breakdown_type: 'event',breakdown: '$current_url',},- version: 2,},- },+ }),})expect(builtInsightVizDataLogic.values.breakdownFilter).toEqual({@@ -539,7 +537,7 @@ describe('insightVizDataLogic', () => {}).toFinishAllListeners().toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,@@ -547,9 +545,8 @@ describe('insightVizDataLogic', () => {breakdown_type: 'event',breakdown: '$browser',},- version: 2,},- },+ }),})expect(builtInsightVizDataLogic.values.breakdownFilter).toEqual({@@ -567,16 +564,15 @@ describe('insightVizDataLogic', () => {}).toFinishAllListeners().toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,trendsFilter: {display: 'ActionsAreaGraph',},- version: 2,},- },+ }),})expect(builtInsightVizDataLogic.values.insightFilter).toEqual({ display: 'ActionsAreaGraph' })@@ -589,7 +585,7 @@ describe('insightVizDataLogic', () => {}).toFinishAllListeners().toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQueryDefault,@@ -597,9 +593,8 @@ describe('insightVizDataLogic', () => {display: 'ActionsAreaGraph',showValuesOnSeries: true,},- version: 2,},- },+ }),})expect(builtInsightVizDataLogic.values.insightFilter).toEqual({@@ -627,7 +622,7 @@ describe('insightVizDataLogic', () => {layout: FunnelLayout.horizontal,},trendsFilter: {}, // we currently don't remove insight filters of previous query kinds- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery], // carried over from the initial trends source, like the stale trendsFilter},},})@@ -834,7 +829,7 @@ describe('insightVizDataLogic', () => {}).toFinishAllListeners().toMatchValues({- query: {+ query: setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,source: {...trendsQuery,@@ -844,9 +839,8 @@ describe('insightVizDataLogic', () => {date_to: undefined,},trendsFilter: { smoothingIntervals: undefined },- version: 2,},- },+ }),})})})diff --git a/frontend/src/scenes/insights/utils.test.ts b/frontend/src/scenes/insights/utils.test.tsindex a5458ea40e1b..ed44a28153b7 100644--- a/frontend/src/scenes/insights/utils.test.ts+++ b/frontend/src/scenes/insights/utils.test.ts@@ -621,8 +621,8 @@ describe('getTrendDatasetKey()', () => {)})- it('handles insights with compare against previous', () => {- const dataset: Partial<IndexedTrendResult> = {+ it('ignores compare periods, so that current and previous share a key', () => {+ const current: Partial<IndexedTrendResult> = {label: '$pageview',action: {id: '$pageview',@@ -632,8 +632,10 @@ describe('getTrendDatasetKey()', () => {compare: true,compare_label: CompareLabelType.Current,}+ const previous: Partial<IndexedTrendResult> = { ...current, compare_label: CompareLabelType.Previous }- expect(getTrendDatasetKey(dataset as IndexedTrendResult)).toEqual('{"series":0,"compare_label":"current"}')+ expect(getTrendDatasetKey(current as IndexedTrendResult)).toEqual('{"series":0}')+ expect(getTrendDatasetKey(previous as IndexedTrendResult)).toEqual('{"series":0}')})it('handles insights with formulas', () => {@@ -645,6 +647,22 @@ describe('getTrendDatasetKey()', () => {expect(getTrendDatasetKey(dataset as IndexedTrendResult)).toEqual('{"series":"formula"}')})+ it('keys compare periods of a formula by their shared position, not the raw series index', () => {+ // with compare enabled, previous-period datasets have offset series indexes+ // (e.g. 2 for the previous period of the first of two formulas), but share+ // the colorIndex with their current-period counterpart+ const previous: Partial<IndexedTrendResult> = {+ label: 'Formula (A+B)',+ action: undefined,+ seriesIndex: 2,+ colorIndex: 0,+ compare: true,+ compare_label: CompareLabelType.Previous,+ }++ expect(getTrendDatasetKey(previous as IndexedTrendResult)).toEqual('{"series":"formula"}')+ })+it('handles insights with non-array breakdown values', () => {const dataset: Partial<IndexedTrendResult> = {label: 'Opera',diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsxindex 73f04f3ec8ab..307136df08d4 100644--- a/frontend/src/scenes/insights/utils.tsx+++ b/frontend/src/scenes/insights/utils.tsx@@ -588,25 +588,32 @@ export function getFunnelDatasetKey(dataset: { breakdown_value?: BreakdownKeyTypreturn JSON.stringify(payload)}+/** Identifies the base series — deliberately excludes `compare_label`, so that current and+ * previous period datasets share a single result customization. */export function getTrendDatasetKey(dataset: IndexedTrendResult): string {+ // for formulas, the position (not seriesIndex) identifies the base series: with compare+ // enabled, previous-period datasets have offset series indexes, but share the position+ // with their current-period counterpart+ const formulaPosition = getTrendDatasetPosition(dataset)const payload = {series: Number.isInteger(dataset.action?.order)? dataset.action?.order- : dataset.seriesIndex > 0- ? `formula${dataset.seriesIndex + 1}`+ : formulaPosition > 0+ ? `formula${formulaPosition + 1}`: 'formula',breakdown_value:dataset.breakdown_value !== undefined && !Array.isArray(dataset.breakdown_value)? [dataset.breakdown_value]: dataset.breakdown_value,- compare_label: dataset.compare_label,}return JSON.stringify(payload)}export function getTrendDatasetPosition(dataset: IndexedTrendResult): number {- return dataset.seriesIndex ?? dataset.colorIndex ?? ((dataset as any).index as number)+ // colorIndex is shared by current/previous period pairs, so position-based+ // customizations apply to the base series rather than each period separately+ return dataset.colorIndex ?? dataset.seriesIndex ?? ((dataset as any).index as number)}/** Type guard to determine whether we have a FunnelStepWithConversionMetrics or a FlattenedFunnelStepByBreakdown */@@ -675,15 +682,9 @@ export function getTrendResultCustomizationColorToken(const resultCustomization = getTrendResultCustomization(resultCustomizationBy, dataset, resultCustomizations)// for result customizations without a configuration, the color is determined- // by the position in the dataset. colors repeat after all options- // have been exhausted.- // For comparison data (current vs previous periods), use colorIndex to ensure- // they get the same base color when customizing by value- const isValueBasedCustomization = !resultCustomizationBy || resultCustomizationBy === ResultCustomizationBy.Value- const datasetPosition =- isValueBasedCustomization && dataset.colorIndex !== undefined- ? dataset.colorIndex- : getTrendDatasetPosition(dataset)+ // by the position in the dataset (shared by current/previous period pairs).+ // colors repeat after all options have been exhausted.+ const datasetPosition = getTrendDatasetPosition(dataset)const tokenIndex = (datasetPosition % Object.keys(theme).length) + 1return resultCustomization && resultCustomization.colordiff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.tsindex 599eb5235852..dfe82ad8f5cf 100644--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts@@ -2,6 +2,8 @@ import { JSONContent } from 'lib/components/RichContentEditor/types'import { NotebookType } from 'scenes/notebooks/types'import { useMocks } from '~/mocks/jest'+import { LATEST_VERSIONS } from '~/queries/latest-versions'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { AccessControlLevel } from '~/types'@@ -14,7 +16,21 @@ describe('migrate()', () => {post: {'/api/environments/:team_id/query/upgrade': async ({ request }) => {const data = (await request.json()) as any- if (data?.query?.source?.kind === 'RetentionQuery') {+ const kind = data?.query?.source?.kind+ // These fixtures have no result customizations, so the trends/stickiness+ // migration past v2 is a no-op beyond the version bump the backend applies.+ if (kind === 'TrendsQuery' || kind === 'StickinessQuery') {+ return [+ 200,+ {+ query: {+ ...data.query,+ source: { ...data.query.source, version: LATEST_VERSIONS[kind as NodeKind] },+ },+ },+ ]+ }+ if (kind === 'RetentionQuery') {return [200,{@@ -150,7 +166,7 @@ describe('migrate()', () => {breakdownFilter: { breakdown_type: 'event', breakdown: '$referring_domain' },trendsFilter: { display: 'ActionsBar' },compareFilter: { compare: true },- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery],},},title: 'SEO trend last 90 days',@@ -447,7 +463,7 @@ describe('migrate()', () => {showLegend: true,},filterTestAccounts: false,- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery],},},title: 'Rollout of users on 3000',@@ -570,7 +586,7 @@ describe('migrate()', () => {trendsFilter: { display: 'ActionsBar' },compareFilter: { compare: true, compare_to: '-4w' },filterTestAccounts: true,- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery],},},title: 'SEO trend last 90 days',@@ -892,7 +908,7 @@ describe('migrate()', () => {},compareFilter: { compare: true },filterTestAccounts: false,- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery],},},title: 'Weekly Org Signups',@@ -955,7 +971,7 @@ describe('migrate()', () => {compareFilter: {compare: true,},- version: 2,+ version: LATEST_VERSIONS[NodeKind.TrendsQuery],},},title: 'Some insight',@@ -1019,7 +1035,7 @@ describe('migrate()', () => {compareFilter: {compare: true,},- version: 2,+ version: LATEST_VERSIONS[NodeKind.StickinessQuery],},},title: 'Some insight',diff --git a/posthog/schema_migrations/0003_trends_result_customizations_compare.py b/posthog/schema_migrations/0003_trends_result_customizations_compare.pynew file mode 100644index 000000000000..4ac40ba1f3d2--- /dev/null+++ b/posthog/schema_migrations/0003_trends_result_customizations_compare.py@@ -0,0 +1,145 @@+import json+from typing import Any, Optional++from posthog.schema_migrations.base import SchemaMigration++KIND_TO_FILTER_KEY = {+ "TrendsQuery": "trendsFilter",+ "StickinessQuery": "stickinessFilter",+}+++class Migration(SchemaMigration):+ """Merge per-compare-period result customizations into a single base-series entry.++ Customization keys used to include `compare_label`, giving the current and previous+ period of a series independent entries. The frontend now keys customizations by the+ base series only, so both periods share one entry:+ - by value: `compare_label` is stripped from the key. When entries conflict, the one+ matching the stored compare state wins ("current" if compare is on, the unlabelled+ one otherwise). "previous"-labelled entries are dropped — carrying e.g. `hidden`+ over to the pair would hide the current period too.+ - by position: with compare on, previous-period datasets used to occupy positions+ offset by the number of base series. Offset entries are shifted back, existing+ base entries win. Skipped with breakdowns, where the offset is data-dependent.+ """++ targets = {"TrendsQuery": 2, "StickinessQuery": 2}++ def transform(self, query: dict) -> dict:+ filter_key = KIND_TO_FILTER_KEY.get(str(query.get("kind")))+ if not filter_key:+ return query++ insight_filter = query.get(filter_key)+ if not isinstance(insight_filter, dict):+ return query++ result_customizations = insight_filter.get("resultCustomizations")+ if not isinstance(result_customizations, dict) or not result_customizations:+ return query++ compare_on = self._has_compare(query)++ if insight_filter.get("resultCustomizationBy") == "position":+ new_result_customizations = self._transform_by_position(query, insight_filter, result_customizations)+ else:+ new_result_customizations = self._transform_by_value(result_customizations, compare_on)++ if new_result_customizations == result_customizations:+ return query++ new_insight_filter = dict(insight_filter)+ new_insight_filter["resultCustomizations"] = new_result_customizations+ query = dict(query)+ query[filter_key] = new_insight_filter+ return query++ def _transform_by_value(self, result_customizations: dict, compare_on: bool) -> dict:+ merged: dict[str, Any] = {}+ for key, value in result_customizations.items():+ parsed = self._parse_value_key(key)+ if parsed is None or "compare_label" not in parsed:+ # already a base key; an earlier "current" entry wins when compare is on+ if key in merged and compare_on:+ continue+ merged[key] = value+ continue++ label = parsed.pop("compare_label")+ if label != "current":+ continue++ base_key = json.dumps(parsed, separators=(",", ":"), ensure_ascii=False)+ if base_key in merged and not compare_on:+ continue+ merged[base_key] = value+ return merged++ def _transform_by_position(self, query: dict, insight_filter: dict, result_customizations: dict) -> dict:+ if not self._has_compare(query) or self._has_breakdown(query):+ return result_customizations++ base_series_count = self._base_series_count(query, insight_filter)+ if not base_series_count:+ return result_customizations++ remapped: dict[str, Any] = {}+ offset_entries: list[tuple[int, Any]] = []+ for key, value in result_customizations.items():+ position = self._parse_position_key(key)+ if position is None or position < base_series_count:+ remapped[key] = value+ else:+ offset_entries.append((position, value))++ for position, value in offset_entries:+ target = str(position - base_series_count)+ if target not in remapped:+ remapped[target] = value+ return remapped++ @staticmethod+ def _parse_value_key(key: str) -> Optional[dict]:+ try:+ parsed = json.loads(key)+ except (ValueError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else None++ @staticmethod+ def _parse_position_key(key: str) -> Optional[int]:+ try:+ return int(key)+ except (ValueError, TypeError):+ return None++ @staticmethod+ def _base_series_count(query: dict, insight_filter: dict) -> int:+ formula_nodes = insight_filter.get("formulaNodes")+ if isinstance(formula_nodes, list) and formula_nodes:+ return len(formula_nodes)+ formulas = insight_filter.get("formulas")+ if isinstance(formulas, list) and formulas:+ return len(formulas)+ if insight_filter.get("formula"):+ return 1+ series = query.get("series")+ return len(series) if isinstance(series, list) else 0++ @staticmethod+ def _has_breakdown(query: dict) -> bool:+ breakdown_filter = query.get("breakdownFilter")+ if not breakdown_filter:+ return False+ if breakdown_filter.get("breakdown_type") and breakdown_filter.get("breakdown"):+ return True+ breakdowns = breakdown_filter.get("breakdowns")+ return isinstance(breakdowns, list) and len(breakdowns) > 0++ @staticmethod+ def _has_compare(query: dict) -> bool:+ compare_filter = query.get("compareFilter")+ if not compare_filter:+ return False+ return compare_filter.get("compare") is Truediff --git a/posthog/schema_migrations/test/test_0003_trends_result_customizations_compare.py b/posthog/schema_migrations/test/test_0003_trends_result_customizations_compare.pynew file mode 100644index 000000000000..62f153a74d55--- /dev/null+++ b/posthog/schema_migrations/test/test_0003_trends_result_customizations_compare.py@@ -0,0 +1,183 @@+import importlib++import pytest++COMPARE_ON = {"compareFilter": {"compare": True}}++BASE_KEY = '{"series":0}'+CURRENT_KEY = '{"series":0,"compare_label":"current"}'+PREVIOUS_KEY = '{"series":0,"compare_label":"previous"}'++BASE_ENTRY = {"assignmentBy": "value", "color": "preset-1"}+CURRENT_ENTRY = {"assignmentBy": "value", "color": "preset-2"}+PREVIOUS_ENTRY = {"assignmentBy": "value", "color": "preset-3", "hidden": True}+++def _get_migration():+ migration_module = importlib.import_module("posthog.schema_migrations.0003_trends_result_customizations_compare")+ return migration_module.Migration()+++def _trends_query(result_customizations, compare=False, filter_extra=None, **query_extra):+ query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "trendsFilter": {"resultCustomizations": result_customizations, **(filter_extra or {})},+ **(COMPARE_ON if compare else {}),+ **query_extra,+ }+ return query+++ "compare,result_customizations,expected",+ [+ # compare on: the "current" entry is what the user sees, it wins over a stale base entry+ (+ True,+ {BASE_KEY: BASE_ENTRY, CURRENT_KEY: CURRENT_ENTRY, PREVIOUS_KEY: PREVIOUS_ENTRY},+ {BASE_KEY: CURRENT_ENTRY},+ ),+ # compare off: the base entry is what the user sees, stale labelled entries are dropped+ (+ False,+ {BASE_KEY: BASE_ENTRY, CURRENT_KEY: CURRENT_ENTRY, PREVIOUS_KEY: PREVIOUS_ENTRY},+ {BASE_KEY: BASE_ENTRY},+ ),+ # current-only: renamed to the base key+ (True, {CURRENT_KEY: CURRENT_ENTRY}, {BASE_KEY: CURRENT_ENTRY}),+ (False, {CURRENT_KEY: CURRENT_ENTRY}, {BASE_KEY: CURRENT_ENTRY}),+ # previous-only: dropped — adopting e.g. hidden=true would hide the current period too+ (True, {PREVIOUS_KEY: PREVIOUS_ENTRY}, {}),+ # order independence: current after base still wins when compare is on+ (+ True,+ {CURRENT_KEY: CURRENT_ENTRY, BASE_KEY: BASE_ENTRY},+ {BASE_KEY: CURRENT_ENTRY},+ ),+ ],+)+def test_value_mode_merges_compare_entries(compare, result_customizations, expected):+ migration = _get_migration()+ query = _trends_query(result_customizations, compare=compare)+ assert migration.transform(query)["trendsFilter"]["resultCustomizations"] == expected+++def test_value_mode_compare_to_without_compare_is_compare_off():+ # compare_to alone never enables comparison (runners and UI gate on compare being+ # true), so the unlabelled entry is the one in effect and must win+ migration = _get_migration()+ query = _trends_query(+ {BASE_KEY: BASE_ENTRY, CURRENT_KEY: CURRENT_ENTRY},+ compareFilter={"compare_to": "-1w"},+ )+ assert migration.transform(query)["trendsFilter"]["resultCustomizations"] == {BASE_KEY: BASE_ENTRY}+++def test_value_mode_preserves_breakdown_key_bytes():+ migration = _get_migration()+ labelled_key = '{"series":1,"breakdown_value":["Ö",null,1],"compare_label":"current"}'+ query = _trends_query({labelled_key: CURRENT_ENTRY}, compare=True)+ assert migration.transform(query)["trendsFilter"]["resultCustomizations"] == {+ '{"series":1,"breakdown_value":["Ö",null,1]}': CURRENT_ENTRY+ }+++def test_value_mode_keeps_unparseable_keys():+ migration = _get_migration()+ result_customizations = {"not-json": BASE_ENTRY, CURRENT_KEY: CURRENT_ENTRY}+ query = _trends_query(result_customizations, compare=True)+ assert migration.transform(query)["trendsFilter"]["resultCustomizations"] == {+ "not-json": BASE_ENTRY,+ BASE_KEY: CURRENT_ENTRY,+ }+++POSITION_FILTER = {"resultCustomizationBy": "position"}+POSITION_ENTRY_0 = {"assignmentBy": "position", "color": "preset-1"}+POSITION_ENTRY_2 = {"assignmentBy": "position", "color": "preset-2"}+POSITION_ENTRY_3 = {"assignmentBy": "position", "hidden": True}+TWO_SERIES = [{"kind": "EventsNode", "event": "$pageview"}, {"kind": "EventsNode", "event": "$autocapture"}]+++ "result_customizations,expected",+ [+ # offset previous-period entries shift back by the series count where the slot is free+ ({"0": POSITION_ENTRY_0, "3": POSITION_ENTRY_3}, {"0": POSITION_ENTRY_0, "1": POSITION_ENTRY_3}),+ # existing base entries win over shifted ones+ ({"0": POSITION_ENTRY_0, "2": POSITION_ENTRY_2}, {"0": POSITION_ENTRY_0}),+ # non-numeric keys are preserved+ ({"0": POSITION_ENTRY_0, "junk": POSITION_ENTRY_2}, {"0": POSITION_ENTRY_0, "junk": POSITION_ENTRY_2}),+ ],+)+def test_position_mode_remaps_offset_entries(result_customizations, expected):+ migration = _get_migration()+ query = _trends_query(result_customizations, compare=True, filter_extra=POSITION_FILTER, series=TWO_SERIES)+ assert migration.transform(query)["trendsFilter"]["resultCustomizations"] == expected+++ "filter_extra,expected_shifted_key",+ [+ ({"formulaNodes": [{"formula": "A"}, {"formula": "B"}]}, "1"),+ ({"formulas": ["A", "B"]}, "1"),+ ({"formula": "A+B"}, "2"),+ ],+)+def test_position_mode_uses_formula_count_over_series_count(filter_extra, expected_shifted_key):+ migration = _get_migration()+ query = _trends_query(+ {"3": POSITION_ENTRY_3},+ compare=True,+ filter_extra={**POSITION_FILTER, **filter_extra},+ series=TWO_SERIES + TWO_SERIES,+ )+ assert migration.transform(query)["trendsFilter"]["resultCustomizations"] == {+ expected_shifted_key: POSITION_ENTRY_3+ }+++ "compare,query_extra",+ [+ (False, {}),+ (True, {"breakdownFilter": {"breakdown_type": "event", "breakdown": "$browser"}}),+ (True, {"breakdownFilter": {"breakdowns": [{"type": "event", "property": "$browser"}]}}),+ ],+)+def test_position_mode_skipped_when_compare_off_or_breakdown(compare, query_extra):+ migration = _get_migration()+ result_customizations = {"0": POSITION_ENTRY_0, "3": POSITION_ENTRY_3}+ query = _trends_query(+ result_customizations, compare=compare, filter_extra=POSITION_FILTER, series=TWO_SERIES, **query_extra+ )+ assert migration.transform(query)["trendsFilter"]["resultCustomizations"] == result_customizations+++def test_stickiness_filter_is_migrated():+ migration = _get_migration()+ query = {+ "kind": "StickinessQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "stickinessFilter": {"resultCustomizations": {CURRENT_KEY: CURRENT_ENTRY, PREVIOUS_KEY: PREVIOUS_ENTRY}},+ **COMPARE_ON,+ }+ assert migration.transform(query)["stickinessFilter"]["resultCustomizations"] == {BASE_KEY: CURRENT_ENTRY}+++ "query",+ [+ {"kind": "NotTrendsQuery"},+ {"kind": "TrendsQuery", "trendsFilter": None},+ {"kind": "TrendsQuery", "trendsFilter": {}},+ {"kind": "TrendsQuery", "trendsFilter": {"resultCustomizations": None}},+ {"kind": "TrendsQuery", "trendsFilter": {"resultCustomizations": {}}},+ # new-shape query (base keys only) must pass through unchanged+ _trends_query({BASE_KEY: BASE_ENTRY}, compare=True),+ ],+)+def test_noop_queries_are_unchanged(query):+ migration = _get_migration()+ assert migration.transform(query) == query