:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(insights): stop insight type switches landing on a hard error (#83677)
posthog[bot]c1b281e85303
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.tsindex 601d3d026a3e..9c7a1263d4cc 100644--- a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts+++ b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts@@ -95,7 +95,7 @@ const insightTypeToNodeKind: Record<[InsightType.LIFECYCLE]: NodeKind.LifecycleQuery,}-const actorsOnlyMathTypes = [+export const actorsOnlyMathTypes = [BaseMathType.UniqueUsers,BaseMathType.WeeklyActiveUsers,BaseMathType.MonthlyActiveUsers,diff --git a/frontend/src/queries/nodes/InsightViz/StickinessCriteria.tsx b/frontend/src/queries/nodes/InsightViz/StickinessCriteria.tsxindex 7b42bb473d07..a7f6fbd293ff 100644--- a/frontend/src/queries/nodes/InsightViz/StickinessCriteria.tsx+++ b/frontend/src/queries/nodes/InsightViz/StickinessCriteria.tsx@@ -41,9 +41,14 @@ export function StickinessCriteria({ insightProps }: EditorFilterProps): JSX.EledefaultValue={currentValue}min={1}onChange={(newValue: number | undefined) => {- if (newValue !== undefined) {- updateInsightFilter({ stickinessCriteria: { operator: currentOperator, value: newValue } })+ // A cleared or half-typed number field reports NaN, which would serialize to null and+ // fail the backend's integer validation, so drop any non-finite value.+ if (newValue === undefined || !Number.isFinite(newValue)) {+ return}+ // The backend requires an integer of at least 1, so never post 0 or a negative value.+ const value = Math.max(1, Math.floor(newValue))+ updateInsightFilter({ stickinessCriteria: { operator: currentOperator, value } })}}/><span className="@min-[0px]/editor-panel:whitespace-nowrap">time(s) per interval</span>diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex fc9de62458ab..ffc310840ea1 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -474,7 +474,7 @@ export const getInterval = (query: InsightQueryNode): IntervalType | undefined =// For trends/stickiness, ActionsStackedBar is a deprecated alias of ActionsBar (which renders stacked):// the UI never emits it, but the API and MCP accept it. Normalizing here — the point all `display`// selectors derive from — makes such insights behave exactly like their UI-created equivalents.-const normalizeDisplay = (display: ChartDisplayType | undefined): ChartDisplayType | undefined =>+export const normalizeDisplay = (display: ChartDisplayType | undefined): ChartDisplayType | undefined =>display === ChartDisplayType.ActionsStackedBar ? ChartDisplayType.ActionsBar : displayexport const getDisplay = (query: InsightQueryNode): ChartDisplayType | undefined => {diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.tsindex 52192691e9c8..daf26971d45e 100644--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts@@ -18,6 +18,8 @@ import {NodeKind,Node,ProductKey,+ RetentionQuery,+ StickinessQuery,TrendsQuery,} from '~/queries/schema/schema-general'import { setLatestVersionsOnQuery } from '~/queries/utils'@@ -32,6 +34,7 @@ import {PropertyFilterType,PropertyOperator,QueryBasedInsightModel,+ RetentionEntity,StepOrderValue,} from '~/types'@@ -784,6 +787,256 @@ describe('insightNavLogic', () => {})})+ it('SCRATCH count+math', async () => {+ const trendsQuery: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ name: 'a_event',+ event: 'a_event',+ math: BaseMathType.UniqueUsers,+ },+ { kind: NodeKind.EventsNode, name: 'b_event', event: 'b_event' },+ { kind: NodeKind.EventsNode, name: 'c_event', event: 'c_event' },+ ],+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(trendsQuery)+ })+ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.RETENTION)+ }).toFinishAllListeners()+ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.TRENDS)+ }).toFinishAllListeners()++ const back = (builtInsightDataLogic.values.query as InsightVizNode).source as TrendsQuery+ // eslint-disable-next-line no-console+ console.log('SCRATCH after round trip:', JSON.stringify(back.series))+ expect(back.series).toHaveLength(3)+ })++ it('keeps every trends series and its math through a retention round trip', async () => {+ const trendsQuery: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ name: 'a_event',+ event: 'a_event',+ math: BaseMathType.UniqueUsers,+ },+ { kind: NodeKind.EventsNode, name: 'b_event', event: 'b_event' },+ { kind: NodeKind.EventsNode, name: 'c_event', event: 'c_event' },+ ],+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(trendsQuery)+ })++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.RETENTION)+ }).toFinishAllListeners()++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.TRENDS)+ }).toFinishAllListeners()++ // Retention holds a single target entity, so the series beyond the first only survive+ // in the cache — dropping them here silently deleted the rest of the insight.+ const backToTrends = (builtInsightDataLogic.values.query as InsightVizNode).source as TrendsQuery+ expect(backToTrends.series).toMatchObject([+ { event: 'a_event', math: BaseMathType.UniqueUsers },+ { event: 'b_event' },+ { event: 'c_event' },+ ])+ })++ it('carries a funnel event into retention as a targetEntity in the right shape', async () => {+ const funnelsQuery: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.FunnelsQuery,+ series: [+ { kind: NodeKind.EventsNode, name: 'signed_up', event: 'signed_up' },+ { kind: NodeKind.EventsNode, name: '$pageview', event: '$pageview' },+ ],+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(funnelsQuery)+ })++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.RETENTION)+ }).toFinishAllListeners()++ const retentionSource = (builtInsightDataLogic.values.query as InsightVizNode).source as RetentionQuery+ expect(retentionSource.retentionFilter?.targetEntity).toEqual({+ kind: NodeKind.EventsNode,+ type: 'events',+ id: 'signed_up',+ name: 'signed_up',+ })+ // A RetentionEntity forbids the EventsNode `event` key, which was a 400 before+ expect(retentionSource.retentionFilter?.targetEntity).not.toHaveProperty('event')+ })++ it('carries a retention target entity back into a series on switch away', async () => {+ const retentionQuery: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.RetentionQuery,+ retentionFilter: {+ targetEntity: {+ kind: NodeKind.EventsNode,+ type: 'events',+ id: 'purchase',+ name: 'purchase',+ },+ returningEntity: {+ kind: NodeKind.EventsNode,+ type: 'events',+ id: 'purchase',+ name: 'purchase',+ },+ },+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(retentionQuery)+ })++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.TRENDS)+ }).toFinishAllListeners()++ const trendsSource = (builtInsightDataLogic.values.query as InsightVizNode).source as TrendsQuery+ expect(trendsSource.series).toMatchObject([+ { kind: NodeKind.EventsNode, event: 'purchase', name: 'purchase' },+ ])+ })++ it('preserves a data warehouse retention target through a trends round trip', async () => {+ const dwhEntity: RetentionEntity = {+ type: 'data_warehouse',+ id: 'stripe_customers',+ name: 'stripe_customers',+ table_name: 'stripe_customers',+ timestamp_field: 'created_at',+ aggregation_target_field: 'customer_id',+ }+ const retentionDwh: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.RetentionQuery,+ retentionFilter: { targetEntity: dwhEntity, returningEntity: dwhEntity },+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(retentionDwh)+ })++ // Switching to trends must not fabricate a series event named after the warehouse table.+ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.TRENDS)+ }).toFinishAllListeners()+ const trendsSource = (builtInsightDataLogic.values.query as InsightVizNode).source as TrendsQuery+ expect(trendsSource.series).not.toContainEqual(expect.objectContaining({ event: 'stripe_customers' }))++ // Switching back must keep the warehouse target intact rather than replacing it with an event.+ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.RETENTION)+ }).toFinishAllListeners()+ const retentionSource = (builtInsightDataLogic.values.query as InsightVizNode).source as RetentionQuery+ expect(retentionSource.retentionFilter?.targetEntity).toMatchObject({+ type: 'data_warehouse',+ table_name: 'stripe_customers',+ })+ expect(retentionSource.retentionFilter?.returningEntity).toMatchObject({+ type: 'data_warehouse',+ table_name: 'stripe_customers',+ })+ })++ it('keeps event property filters on a retention target through a trends round trip', async () => {+ const targetEntity: RetentionEntity = {+ kind: NodeKind.EventsNode,+ type: 'events',+ id: 'purchase',+ name: 'purchase',+ properties: [+ {+ key: '$browser',+ type: PropertyFilterType.Event,+ value: 'Chrome',+ operator: PropertyOperator.Exact,+ },+ ],+ }+ const retentionFiltered: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.RetentionQuery,+ retentionFilter: { targetEntity, returningEntity: targetEntity },+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(retentionFiltered)+ })++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.TRENDS)+ }).toFinishAllListeners()++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.RETENTION)+ }).toFinishAllListeners()++ // Without copying `properties` across the conversion the target would return unfiltered,+ // silently widening the retention count.+ const retentionSource = (builtInsightDataLogic.values.query as InsightVizNode).source as RetentionQuery+ expect(retentionSource.retentionFilter?.targetEntity?.properties).toEqual([+ expect.objectContaining({ key: '$browser', value: 'Chrome' }),+ ])+ })++ it('does not carry a trends-only display into stickiness', async () => {+ const trendsPie: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, name: '$pageview', event: '$pageview' }],+ trendsFilter: { display: ChartDisplayType.ActionsPie },+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(trendsPie)+ })++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.STICKINESS)+ }).toFinishAllListeners()++ const stickinessSource = (builtInsightDataLogic.values.query as InsightVizNode)+ .source as StickinessQuery+ expect(stickinessSource.stickinessFilter?.display).toBeUndefined()+ })+it('preserves multiple breakdowns through round-trip via single-breakdown type', async () => {const trendsWithMultipleBreakdowns: InsightVizNode = setLatestVersionsOnQuery({kind: NodeKind.InsightVizNode,@@ -1173,6 +1426,36 @@ describe('insightNavLogic', () => {})})+ it('normalizes the ActionsStackedBar alias when switching from trends to stickiness', async () => {+ const trendsQueryWithAlias: InsightVizNode = setLatestVersionsOnQuery({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ name: '$pageview',+ event: '$pageview',+ },+ ],+ // ActionsStackedBar reaches this path only via the API/MCP; the UI never emits it.+ trendsFilter: { display: ChartDisplayType.ActionsStackedBar },+ },+ })++ await expectLogic(logic, () => {+ builtInsightDataLogic.actions.setQuery(trendsQueryWithAlias)+ })++ await expectLogic(builtInsightDataLogic, () => {+ logic.actions.setActiveView(InsightType.STICKINESS)+ }).toFinishAllListeners()++ const stickinessSource = (builtInsightDataLogic.values.query as InsightVizNode)+ .source as StickinessQuery+ expect(stickinessSource.stickinessFilter?.display).toEqual(ChartDisplayType.ActionsBar)+ })+const dataWarehouseTestCases: {label: stringsource: InsightVizNode['source']diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsxindex 829077ce5644..d90acbe9333e 100644--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx@@ -10,7 +10,7 @@ import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'import { urls } from 'scenes/urls'-import { expandGroupNodes } from '~/queries/nodes/InsightQuery/utils/filtersToQueryNode'+import { actorsOnlyMathTypes, expandGroupNodes } from '~/queries/nodes/InsightQuery/utils/filtersToQueryNode'import { nodeKindToInsightType } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'import {@@ -67,8 +67,17 @@ import {isStickinessQuery,isTrendsQuery,isWebAnalyticsInsightQuery,+ normalizeDisplay,} from '~/queries/utils'-import { BaseMathType, InsightLogicProps, InsightType, IntervalType } from '~/types'+import {+ BaseMathType,+ ChartDisplayType,+ EntityTypes,+ InsightLogicProps,+ InsightType,+ IntervalType,+ RetentionEntity,+} from '~/types'import { PRODUCT_ANALYTICS_DEFAULT_QUERY_TAGS } from 'products/product_analytics/frontend/constants'@@ -130,7 +139,8 @@ const cleanSeriesEntityMath = (}return { ...baseEntity, math: BaseMathType.TotalCount }} else if (mathAvailability === MathAvailability.ActorsOnly) {- if (math != null) {+ // Stickiness and lifecycle only count actors, so a carried-over count math would be rejected.+ if (math != null && actorsOnlyMathTypes.includes(math as any)) {return { ...baseEntity, math, math_property, math_group_type_index, math_hogql }}return { ...baseEntity, math: BaseMathType.UniqueUsers }@@ -272,6 +282,64 @@ const filterRetentionBreakdowns = (bf: BreakdownFilter): BreakdownFilter => {return { ...bf, breakdowns: bf.breakdowns.filter((b) => b.type === 'person' || b.type === 'event') }}+// Retention has no `series`; it carries a single target/returning entity. These helpers map between+// a series entity and a RetentionEntity so a switch to or from Retention keeps the configured event+// in the shape each kind accepts (a RetentionEntity takes `id`/`type`, never an EventsNode `event`).+const seriesEntityToRetentionEntity = (+ entity: AnyEntityNode<AnyDataWarehouseNode> | GroupNode+): RetentionEntity | undefined => {+ if (entity.kind === NodeKind.EventsNode) {+ return {+ kind: NodeKind.EventsNode,+ type: EntityTypes.EVENTS,+ ...(entity.event != null ? { id: entity.event } : {}),+ ...(entity.name ? { name: entity.name } : {}),+ ...(entity.custom_name ? { custom_name: entity.custom_name } : {}),+ ...(entity.properties?.length ? { properties: entity.properties } : {}),+ }+ }+ if (entity.kind === NodeKind.ActionsNode) {+ return {+ kind: NodeKind.ActionsNode,+ type: EntityTypes.ACTIONS,+ id: entity.id,+ ...(entity.name ? { name: entity.name } : {}),+ ...(entity.custom_name ? { custom_name: entity.custom_name } : {}),+ ...(entity.properties?.length ? { properties: entity.properties } : {}),+ }+ }+ return undefined+}++const retentionEntityToSeriesEntity = (entity: RetentionEntity | undefined): EventsNode | ActionsNode | undefined => {+ if (!entity) {+ return undefined+ }+ if (entity.type === EntityTypes.ACTIONS || entity.kind === NodeKind.ActionsNode) {+ return {+ kind: NodeKind.ActionsNode,+ id: typeof entity.id === 'string' ? parseInt(entity.id, 10) : (entity.id ?? 0),+ ...(entity.name ? { name: entity.name } : {}),+ ...(entity.custom_name ? { custom_name: entity.custom_name } : {}),+ ...(entity.properties?.length ? { properties: entity.properties } : {}),+ }+ }+ // A data warehouse target carries table_name/timestamp_field that no EventsNode can hold, and a+ // RetentionEntity lacks the id_field/distinct_id_field a DataWarehouseNode needs, so it can't map to+ // a series. Drop it rather than fabricate an event named after the table; the retentionFilter cache+ // still holds the intact entity, so it survives a round trip.+ if (entity.type === EntityTypes.DATA_WAREHOUSE) {+ return undefined+ }+ return {+ kind: NodeKind.EventsNode,+ ...(entity.id != null ? { event: String(entity.id) } : {}),+ ...(entity.name ? { name: entity.name } : {}),+ ...(entity.custom_name ? { custom_name: entity.custom_name } : {}),+ ...(entity.properties?.length ? { properties: entity.properties } : {}),+ }+}+const carryForwardSeriesMath = (newSeries: SeriesArray, cachedSeries: SeriesArray | undefined): SeriesArray => {if (!cachedSeries) {return newSeries@@ -309,8 +377,8 @@ const FIELD_CAPABILITIES: Partial<Record<NodeKind, InsightTypeCapabilities>> = {aggregationGroupTypeIndex: true,},[NodeKind.RetentionQuery]: {- // TODO: map series to/from retentionFilter.targetEntity/returningEntity so switching- // between Retention and other insight types preserves configured events.+ // Series maps to retentionFilter.targetEntity/returningEntity rather than a `series` field,+ // so it is handled directly in buildInsightFilter and cachePropertiesFromQuery.breakdownFilter: filterRetentionBreakdowns,},[NodeKind.PathsQuery]: {@@ -338,6 +406,16 @@ const FIELD_CAPABILITIES: Partial<Record<NodeKind, InsightTypeCapabilities>> = {},}+// Display types Stickiness can render. Trends supports more (pie, world map, number, …), so a+// display carried over from Trends is only kept when Stickiness also supports it.+const STICKINESS_DISPLAY_TYPES: ChartDisplayType[] = [+ ChartDisplayType.ActionsLineGraph,+ ChartDisplayType.ActionsAreaGraph,+ ChartDisplayType.ActionsUnstackedBar,+ ChartDisplayType.ActionsBar,+ ChartDisplayType.ActionsTable,+]+type TrendsCommonVisualizationProperties = Pick<TrendsFilter, 'showValuesOnSeries' | 'showPercentStackView' | 'display'>type StickinessCommonVisualizationProperties = Pick<StickinessFilter, 'showValuesOnSeries' | 'display'>type FunnelsCommonVisualizationProperties = Pick<FunnelsFilter, 'showValuesOnSeries'>@@ -377,6 +455,9 @@ function getCommonVisualizationProperties(| Partial<FunnelsCommonVisualizationProperties>| Partial<LifecycleCommonVisualizationProperties>| Partial<EmptyCommonVisualizationProperties> {+ // ActionsStackedBar is a deprecated alias of ActionsBar the API/MCP still accept, so normalize it+ // before the allowlist check — otherwise a carried-over alias fails the check and resets the chart.+ const display = normalizeDisplay(commonFilter.display)const sharedProperties = {...((isLifecycleQuery(query) || isStickinessQuery(query) || isTrendsQuery(query) || isFunnelsQuery(query)) &&commonFilter.showValuesOnSeries@@ -385,8 +466,9 @@ function getCommonVisualizationProperties(...(isTrendsQuery(query) && commonFilter.showPercentStackView? { showPercentStackView: commonFilter.showPercentStackView }: {}),- ...((isTrendsQuery(query) || isStickinessQuery(query)) && commonFilter.display- ? { display: commonFilter.display }+ ...(display &&+ (isTrendsQuery(query) || (isStickinessQuery(query) && STICKINESS_DISPLAY_TYPES.includes(display)))+ ? { display }: {}),}@@ -706,6 +788,23 @@ const cachePropertiesFromQuery = (query: InsightQueryNode, cache: QueryPropertyCif (caps?.series && !caps?.seriesMath && cache?.series && newCache.series) {newCache.series = carryForwardSeriesMath(newCache.series, cache.series)}+ // Retention has no series field, so mirror its target entity into the shared series cache.+ // This keeps the configured event when switching from Retention to a series-based type.+ if (isRetentionQuery(query)) {+ const seriesEntity = retentionEntityToSeriesEntity(query.retentionFilter?.targetEntity)+ if (seriesEntity) {+ // Only the first series maps to the target entity, so the rest of a multi-series cache survives.+ const [firstCached, ...restCached] = newCache.series ?? []+ // A target that still points at the cached entity keeps it whole, math included; a target+ // edited on retention replaces it.+ const targetIsCachedEntity =+ firstCached?.kind === seriesEntity.kind &&+ (seriesEntity.kind === NodeKind.ActionsNode+ ? (firstCached as ActionsNode).id === seriesEntity.id+ : (firstCached as EventsNode).event === seriesEntity.event)+ newCache.series = [targetIsCachedEntity ? firstCached : seriesEntity, ...restCached]+ }+ }/** store the insight specific filter in commonFilter */const insightFilter = filterForQuery(query)@@ -831,7 +930,21 @@ const buildInsightFilter = (}if (isRetentionQuery(query)) {const vizProps = getCommonVisualizationProperties(query, cache.commonFilter)- return { retentionFilter: { ...query.retentionFilter, ...cache.retentionFilter, ...vizProps } }+ const seriesEntity = cache.series?.length ? seriesEntityToRetentionEntity(cache.series[0]) : undefined+ // A data warehouse retention target can't ride the series channel, so an intervening trends/funnels+ // visit would otherwise overwrite it with an event. Keep the cached warehouse target instead.+ const cachedTarget = cache.retentionFilter?.targetEntity+ const targetEntity = cachedTarget?.type === EntityTypes.DATA_WAREHOUSE ? cachedTarget : seriesEntity+ const retentionEntities = targetEntity+ ? {+ targetEntity,+ // Keep a separately configured returning entity; otherwise mirror the target.+ returningEntity: cache.retentionFilter?.returningEntity ?? targetEntity,+ }+ : {}+ return {+ retentionFilter: { ...query.retentionFilter, ...cache.retentionFilter, ...retentionEntities, ...vizProps },+ }}if (isPathsQuery(query)) {const vizProps = getCommonVisualizationProperties(query, cache.commonFilter)diff --git a/posthog/schema_migrations/0001_retention_query_show_mean.py b/posthog/schema_migrations/0001_retention_query_show_mean.pyindex 48624f28e47c..e273c7b4b1c1 100644--- a/posthog/schema_migrations/0001_retention_query_show_mean.py+++ b/posthog/schema_migrations/0001_retention_query_show_mean.py@@ -10,7 +10,7 @@ class Migration(SchemaMigration):if query["kind"] != "RetentionQuery":return query- if query["retentionFilter"] is None:+ if query.get("retentionFilter") is None:return queryif "showMean" in query["retentionFilter"]:diff --git a/posthog/schema_migrations/test/test_0001_retention_query_show_mean.py b/posthog/schema_migrations/test/test_0001_retention_query_show_mean.pyindex df073d591408..24d9c04fb022 100644--- a/posthog/schema_migrations/test/test_0001_retention_query_show_mean.py+++ b/posthog/schema_migrations/test/test_0001_retention_query_show_mean.py@@ -13,6 +13,10 @@ def test_retention_query_show_mean_migration():no_filter_query = {"kind": "RetentionQuery", "retentionFilter": None}assert migration.transform(no_filter_query) == no_filter_query+ # Test query missing the retentionFilter key entirely does not raise (previously a KeyError → 500)+ missing_filter_query = {"kind": "RetentionQuery"}+ assert migration.transform(missing_filter_query) == missing_filter_query+# Test showMean=True converts to simplequery_show_mean_true = {"kind": "RetentionQuery", "retentionFilter": {"showMean": True}}assert migration.transform(query_show_mean_true) == {