Skip to content

: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.

feat(retention): warn on dashboards when insights exceed data retention (#82141)

Mike Warren30972fafa14a
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx
index 1c8026cd59a5..748186978c4f 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx
@@ -2,7 +2,9 @@ import '@testing-library/jest-dom'
import { render } from '@testing-library/react'
-import { getEffectiveDateOverride, InsightMetaContent } from './InsightMeta'
+import { getEffectiveDateOverride } from 'scenes/dashboard/dashboardUtils'
+
+import { InsightMetaContent } from './InsightMeta'
describe('InsightMeta', () => {
describe('getEffectiveDateOverride', () => {
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index ccdd8a09b8d0..29d7df9cb53c 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import React, { useCallback, useEffect, useRef, useState } from 'react'
-import { IconInfo, IconPulse, IconThumbsDown, IconThumbsUp } from '@posthog/icons'
+import { IconInfo, IconPulse, IconThumbsDown, IconThumbsUp, IconWarning } from '@posthog/icons'
import { lemonToast } from '@posthog/lemon-ui'
import { CardMeta } from 'lib/components/Cards/CardMeta'
@@ -24,11 +24,15 @@ import { Link } from 'lib/lemon-ui/Link'
import { Popover } from 'lib/lemon-ui/Popover'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { Splotch, SplotchColor } from 'lib/lemon-ui/Splotch'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { getEffectiveDateOverride } from 'scenes/dashboard/dashboardUtils'
+import { dataRetentionBannerLogic } from 'scenes/insights/dataRetention/dataRetentionBannerLogic'
+import { exceedsRetention } from 'scenes/insights/dataRetention/exceedsRetention'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
@@ -42,7 +46,7 @@ import { urls } from 'scenes/urls'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'
-import { DashboardFilter, Node, ProductKey, TileFilters } from '~/queries/schema/schema-general'
+import { Node, ProductKey } from '~/queries/schema/schema-general'
import { isDataVisualizationNode } from '~/queries/utils'
import {
AccessControlLevel,
@@ -54,7 +58,6 @@ import {
InsightLogicProps,
InsightShortId,
QueryBasedInsightModel,
- InsightFilterOverrideContext,
} from '~/types'
import {
@@ -108,24 +111,6 @@ interface InsightMetaProps extends Pick<
onCreateAnomalyAlert?: () => void
}
-export function getEffectiveDateOverride(
- filterOverrideContext: InsightFilterOverrideContext | null | undefined,
- filtersOverride: DashboardFilter | undefined,
- tileFiltersOverride: TileFilters | undefined
-): { dateFromOverride: string | null | undefined; dateToOverride: string | null | undefined } {
- // The backend context already resolves the ignore flag into an empty dashboard layer; the raw-props
- // fallback has to apply it itself.
- const dashboardFilters = filterOverrideContext
- ? filterOverrideContext.dashboard
- : tileFiltersOverride?.ignoreDashboardFilters
- ? undefined
- : filtersOverride
- const tileFilters = filterOverrideContext ? filterOverrideContext.tile : tileFiltersOverride
- const tileHasDate = tileFilters?.date_from != null || tileFilters?.date_to != null
- const source = tileHasDate ? tileFilters : dashboardFilters
- return { dateFromOverride: source?.date_from, dateToOverride: source?.date_to }
-}
-
export function InsightMeta({
tile,
insight,
@@ -182,6 +167,7 @@ export function InsightMeta({
})
)
const { samplingFactor, hasDataWarehouseSeries } = useValues(insightVizDataLogic(insightLogicProps))
+ const { retentionApplies, retentionMonths, retentionPeriodLabel } = useValues(dataRetentionBannerLogic)
const { nameSortedDashboards } = useValues(dashboardsModel)
const { copyToDestinations } = useValues(
dashboardWidgetMenusLogic({
@@ -210,6 +196,20 @@ export function InsightMeta({
// The ignore flag is surfaced by its own notice, so it alone shouldn't trigger the overrides warning.
const hasTileOverrides = Object.keys(tileFiltersOverride ?? {}).some((key) => key !== 'ignoreDashboardFilters')
const dateOverride = getEffectiveDateOverride(insight.filter_override_context, filtersOverride, tileFiltersOverride)
+ const showsDataRetentionWarning =
+ retentionApplies &&
+ placement !== DashboardPlacement.Public &&
+ placement !== DashboardPlacement.Export &&
+ exceedsRetention({
+ query: insight.query,
+ dateFromOverride: dateOverride.dateFromOverride,
+ resolvedDateFrom: insightData?.resolved_date_range?.date_from,
+ retentionMonths,
+ })
+ const dataRetentionWarning =
+ showsDataRetentionWarning && retentionPeriodLabel
+ ? `This insight's date range goes beyond your ${retentionPeriodLabel} data retention, so events older than that aren't included.`
+ : null
const topHeadingProps = {
query: insight.query,
lastRefresh: insight.last_refresh,
@@ -423,6 +423,7 @@ export function InsightMeta({
tags={insight.tags}
compact={showCompactTile}
showDescription={tile?.show_description !== false}
+ dataRetentionWarning={dataRetentionWarning}
infoPopover={
showCompactTile ? (
<CompactInfoPopover
@@ -738,6 +739,7 @@ export function InsightMetaContent({
compact,
showDescription,
infoPopover,
+ dataRetentionWarning,
}: {
title: string
fallbackTitle?: string
@@ -749,10 +751,16 @@ export function InsightMetaContent({
compact?: boolean
showDescription?: boolean
infoPopover?: JSX.Element | null
+ dataRetentionWarning?: string | null
}): JSX.Element {
+ const dataRetentionIndicator = dataRetentionWarning ? (
+ <Tooltip title={dataRetentionWarning}>
+ <IconWarning className="ml-1.5 text-base shrink-0 text-warning" />
+ </Tooltip>
+ ) : null
const titleContent = (
<>
- <span className={clsx('text-primary', infoPopover && 'truncate')}>
+ <span className={clsx('text-primary', (infoPopover || dataRetentionIndicator) && 'truncate')}>
{title || <i>{fallbackTitle || 'Untitled'}</i>}
</span>
{(loading || loadingQueued) && (
@@ -768,7 +776,7 @@ export function InsightMetaContent({
<h4
title={!compact ? title : undefined}
data-attr="insight-card-title"
- className={clsx(infoPopover && 'inline-flex items-center overflow-visible')}
+ className={clsx((infoPopover || dataRetentionIndicator) && 'inline-flex items-center overflow-visible')}
>
{link ? (
<Link to={link} className="max-w-full truncate">
@@ -777,6 +785,7 @@ export function InsightMetaContent({
) : (
titleContent
)}
+ {dataRetentionIndicator}
{infoPopover}
</h4>
)
diff --git a/frontend/src/scenes/billing/PlanComparison.tsx b/frontend/src/scenes/billing/PlanComparison.tsx
index 47b7944a7368..4ae3045b0eba 100644
--- a/frontend/src/scenes/billing/PlanComparison.tsx
+++ b/frontend/src/scenes/billing/PlanComparison.tsx
@@ -13,7 +13,13 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getProductIcon } from 'scenes/onboarding/shared/utils'
-import { BillingFeatureType, BillingPlanType, BillingProductV2AddonType, BillingProductV2Type } from '~/types'
+import {
+ AvailableFeature,
+ BillingFeatureType,
+ BillingPlanType,
+ BillingProductV2AddonType,
+ BillingProductV2Type,
+} from '~/types'
import { convertLargeNumberToWords, getProration } from './billing-utils'
import { billingLogic } from './billingLogic'
@@ -126,6 +132,16 @@ export const PlanComparison = ({
}
const fullyFeaturedPlan = plans[plans.length - 1]
+ const productAnalyticsPlans = billing?.products?.find((product) => product.type === 'product_analytics')?.plans
+ const eventsRetentionOf = (plan?: BillingPlanType): BillingFeatureType | undefined =>
+ plan?.features?.find((feature) => feature.key === AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION)
+ const freeEventsRetention = eventsRetentionOf(
+ productAnalyticsPlans?.find((plan) => !!plan.free_allocation && !plan.tiers)
+ )
+ const paidEventsRetention = eventsRetentionOf(productAnalyticsPlans?.at(-1))
+ const showEventsRetention =
+ product.type === 'platform_and_support' && !!freeEventsRetention && !!paidEventsRetention
+
return (
<table className="PlanComparison w-full table-fixed" ref={planComparisonRef}>
<thead>
@@ -269,7 +285,9 @@ export const PlanComparison = ({
<tr
key={`tr-${feature.key}`}
className={clsx(
- i == fullyFeaturedPlan?.features?.length - 1 && !billing?.has_active_subscription
+ i == fullyFeaturedPlan?.features?.length - 1 &&
+ !showEventsRetention &&
+ !billing?.has_active_subscription
? 'PlanTable__tr__border'
: ''
)}
@@ -278,7 +296,9 @@ export const PlanComparison = ({
className={clsx(
'PlanTable__th__feature',
width && width < 600 && 'PlanTable__th__feature--reduced_padding',
- i == fullyFeaturedPlan?.features?.length - 1 && 'PlanTable__th__last-feature'
+ i == fullyFeaturedPlan?.features?.length - 1 &&
+ !showEventsRetention &&
+ 'PlanTable__th__last-feature'
)}
>
<Tooltip title={feature.description}>
@@ -305,6 +325,33 @@ export const PlanComparison = ({
))}
</tr>
))}
+ {showEventsRetention && (
+ <tr className={clsx(!billing?.has_active_subscription && 'PlanTable__tr__border')}>
+ <th
+ className={clsx(
+ 'PlanTable__th__feature',
+ width && width < 600 && 'PlanTable__th__feature--reduced_padding',
+ 'PlanTable__th__last-feature'
+ )}
+ >
+ <Tooltip title="How far back your insights can query events. Older events aren't included in the results.">
+ <span>Events data retention</span>
+ </Tooltip>
+ </th>
+ {plans?.map((plan) => (
+ <td key={`${plan.plan_key}-events-data-retention`}>
+ <PlanIcon
+ feature={
+ plan.included_if === 'no_active_subscription'
+ ? freeEventsRetention
+ : paidEventsRetention
+ }
+ className="text-base"
+ />
+ </td>
+ ))}
+ </tr>
+ )}
{!billing?.has_active_subscription && !product.inclusion_only && (
<>
<tr>
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index 19bbf592cc66..e07a1a00b10c 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -29,6 +29,7 @@ import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'
import { DashboardHeader } from './DashboardHeader'
import { DashboardOverridesBanner } from './DashboardOverridesBanner'
import { DashboardPublicAccessBanner } from './DashboardPublicAccessBanner'
+import { DashboardRetentionBanner } from './DashboardRetentionBanner'
import { dashboardSubscribeNudgeLogic } from './dashboardSubscribeNudgeLogic'
import { DashboardZoomControl } from './DashboardZoomControl'
import { EmptyDashboardComponent } from './EmptyDashboardComponent'
@@ -172,6 +173,7 @@ function DashboardScene({
})}
>
<DashboardOverridesBanner />
+ <DashboardRetentionBanner />
<SceneStickyBar showBorderBottom={false} className="flex gap-2 space-y-0">
<DashboardFilterBar backTo={backTo} />
diff --git a/frontend/src/scenes/dashboard/DashboardRetentionBanner.tsx b/frontend/src/scenes/dashboard/DashboardRetentionBanner.tsx
new file mode 100644
index 000000000000..fbb9d9b10b28
--- /dev/null
+++ b/frontend/src/scenes/dashboard/DashboardRetentionBanner.tsx
@@ -0,0 +1,29 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { dataRetentionBannerLogic } from '../insights/dataRetention/dataRetentionBannerLogic'
+import { dashboardLogic } from './dashboardLogic'
+
+export const DashboardRetentionBanner = (): JSX.Element | null => {
+ const { showRetentionBanner, retentionPeriodLabel } = useValues(dashboardLogic)
+ const { snooze } = useActions(dataRetentionBannerLogic)
+
+ if (!showRetentionBanner || !retentionPeriodLabel) {
+ return null
+ }
+
+ return (
+ <LemonBanner
+ type="warning"
+ className="mt-4 mb-2"
+ onClose={snooze}
+ action={{ children: 'Upgrade plan', to: urls.organizationBilling() }}
+ >
+ Some insights on this dashboard have date ranges that go beyond your {retentionPeriodLabel} data retention,
+ so events older than that aren't included.
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 93b04a1230e0..49044f805e5a 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -68,6 +68,8 @@ import {
} from 'scenes/dashboard/widgetFetchUtils'
import { createDashboardWidgetTileRefreshScheduler } from 'scenes/dashboard/widgetTileRefreshScheduler'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
+import { dataRetentionBannerLogic } from 'scenes/insights/dataRetention/dataRetentionBannerLogic'
+import { exceedsRetention } from 'scenes/insights/dataRetention/exceedsRetention'
import { MaxContextInput, createMaxContextHelpers } from 'scenes/max/maxTypes'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -142,6 +144,7 @@ import {
encodeURLFilters,
encodeURLVariables,
getDashboardWidgetType,
+ getEffectiveDateOverride,
getInsightQueryError,
getInsightWithRetry,
isLayoutEditEventSource,
@@ -239,6 +242,9 @@ function mergeUpdatedWidgetTileIntoDashboard(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardLogicValues {
+ retentionMonths: number | null // dataRetentionBannerLogic
+ retentionPeriodLabel: string | null // dataRetentionBannerLogic
+ warningEligible: boolean // dataRetentionBannerLogic
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null // dataThemeLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
currentTeamId: number | null // teamLogic
@@ -248,6 +254,7 @@ export interface dashboardLogicValues {
addWidgetModalOpen: boolean
addWidgetSelectedTypes: string[]
addWidgetTileLoading: boolean
+ anyInsightExceedsRetention: boolean
apiUrl: (
refresh?: RefreshType | undefined,
filtersOverride?: DashboardFilter | undefined,
@@ -344,6 +351,7 @@ export interface dashboardLogicValues {
shouldUseStreaming: boolean
showApplyFiltersBanner: boolean
showButtonTileModal: boolean
+ showRetentionBanner: boolean
showSubscriptions: boolean
showTextTileModal: boolean
sidePanelContext: SidePanelSceneContext | null
@@ -1012,6 +1020,16 @@ export interface dashboardLogicMeta {
urlFilters: DashboardFilter,
intermittentFilters: DashboardFilter
) => DashboardFilter
+ anyInsightExceedsRetention: (
+ insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[],
+ effectiveEditBarFilters: DashboardFilter,
+ retentionMonths: number | null
+ ) => boolean
+ showRetentionBanner: (
+ warningEligible: boolean,
+ anyInsightExceedsRetention: boolean,
+ placement: DashboardPlacement
+ ) => boolean
effectiveRefreshFilters: (
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
externalFilters: DashboardFilter,
@@ -1190,6 +1208,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
['variables'],
dataThemeLogic,
['getTheme'],
+ dataRetentionBannerLogic,
+ ['warningEligible', 'retentionMonths', 'retentionPeriodLabel'],
],
logic: [dashboardsModel, insightsModel, eventUsageLogic, addInsightToDashboardLogic],
})),
@@ -2557,6 +2577,37 @@ export const dashboardLogic = kea<dashboardLogicType>([
return effectiveEditBarFilters
},
],
+ // Does any tile on this dashboard reach past the team's events retention window? Runs the same date
+ // precedence and the same rule the tiles do, so the banner and a tile's icon can't disagree.
+ anyInsightExceedsRetention: [
+ (s) => [s.insightTiles, s.effectiveEditBarFilters, s.retentionMonths],
+ (
+ insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[],
+ dashboardFilters: DashboardFilter,
+ retentionMonths: number | null
+ ): boolean =>
+ (insightTiles || []).some((tile) =>
+ exceedsRetention({
+ query: tile.insight?.query,
+ dateFromOverride: getEffectiveDateOverride(
+ tile.insight?.filter_override_context,
+ dashboardFilters,
+ tile.filters_overrides
+ ).dateFromOverride,
+ resolvedDateFrom: tile.insight?.resolved_date_range?.date_from,
+ retentionMonths,
+ })
+ ),
+ ],
+ showRetentionBanner: [
+ (s) => [s.warningEligible, s.anyInsightExceedsRetention, s.placement],
+ (warningEligible: boolean, anyInsightExceedsRetention: boolean, placement: DashboardPlacement): boolean =>
+ warningEligible &&
+ anyInsightExceedsRetention &&
+ // Shared and exported views have no upgrade path for the viewer, and a public viewer isn't our customer.
+ placement !== DashboardPlacement.Public &&
+ placement !== DashboardPlacement.Export,
+ ],
effectiveRefreshFilters: [
(s) => [s.dashboard, s.externalFilters, s.urlFilters],
(
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index e94258db787e..eaefb3049327 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -25,6 +25,7 @@ import {
DashboardTile,
DashboardType,
DashboardWidgetType,
+ InsightFilterOverrideContext,
InsightModel,
QueryBasedInsightModel,
TileLayout,
@@ -466,6 +467,24 @@ export function combineDashboardFilters(...filters: DashboardFilter[]): Dashboar
}, {} as DashboardFilter)
}
+export function getEffectiveDateOverride(
+ filterOverrideContext: InsightFilterOverrideContext | null | undefined,
+ filtersOverride: DashboardFilter | undefined,
+ tileFiltersOverride: TileFilters | undefined
+): { dateFromOverride: string | null | undefined; dateToOverride: string | null | undefined } {
+ // The backend context already resolves the ignore flag into an empty dashboard layer; the raw-props
+ // fallback has to apply it itself.
+ const dashboardFilters = filterOverrideContext
+ ? filterOverrideContext.dashboard
+ : tileFiltersOverride?.ignoreDashboardFilters
+ ? undefined
+ : filtersOverride
+ const tileFilters = filterOverrideContext ? filterOverrideContext.tile : tileFiltersOverride
+ const tileHasDate = tileFilters?.date_from != null || tileFilters?.date_to != null
+ const source = tileHasDate ? tileFilters : dashboardFilters
+ return { dateFromOverride: source?.date_from, dateToOverride: source?.date_to }
+}
+
const LAYOUT_EDIT_EVENT_SOURCES = new Set<DashboardEventSource>([
DashboardEventSource.SceneCommonButtons,
DashboardEventSource.CardEdgeHover,
diff --git a/frontend/src/scenes/insights/dataRetention/InsightRetentionBanner.tsx b/frontend/src/scenes/insights/dataRetention/InsightRetentionBanner.tsx
index 2a75e4dc4e04..67cf3b2580eb 100644
--- a/frontend/src/scenes/insights/dataRetention/InsightRetentionBanner.tsx
+++ b/frontend/src/scenes/insights/dataRetention/InsightRetentionBanner.tsx
@@ -21,10 +21,10 @@ export function InsightRetentionBanner({ insightProps }: { insightProps: Insight
<LemonBanner
type="warning"
onClose={snooze}
- action={{ children: 'Upgrade to unlock past data', to: urls.organizationBilling() }}
+ action={{ children: 'Upgrade plan', to: urls.organizationBilling() }}
>
- This insight has the potential to go back further than your {retentionPeriodLabel} of events data retention.
- Older events aren't included in the results.
+ This insight's date range goes beyond your {retentionPeriodLabel} data retention, so events older than that
+ aren't included.
</LemonBanner>
)
}
diff --git a/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts b/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts
index 1f4d747eb880..4b2d808bd193 100644
--- a/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts
+++ b/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts
@@ -13,13 +13,14 @@ const SNOOZE_DAYS = 30
// retention horizon (or past it).
const WARN_WITHIN_DAYS = 90
-// Humanize a retention window in months: whole years read as "N year(s)", otherwise "N month(s)".
+// Humanize a retention window in months into the attributive form the banner uses ("your 7-year data retention"),
+// which stays singular and hyphenated because it modifies a noun: whole years read as "N-year", anything else
+// as "N-month".
function retentionMonthsLabel(months: number): string {
if (months % 12 === 0) {
- const years = months / 12
- return `${years} year${years === 1 ? '' : 's'}`
+ return `${months / 12}-year`
}
- return `${months} month${months === 1 ? '' : 's'}`
+ return `${months}-month`
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -28,6 +29,7 @@ export interface dataRetentionBannerLogicValues {
currentTeam: TeamPublicType | TeamType | null // teamLogic
accountAgeEligible: boolean
isSnoozed: boolean
+ retentionApplies: boolean
retentionEnforced: boolean
retentionMonths: number | null
retentionPeriodLabel: string | null
@@ -50,7 +52,8 @@ export interface dataRetentionBannerLogicMeta {
retentionPeriodLabel: (retentionMonths: number | null) => string | null
isSnoozed: (snoozedUntil: string | null) => boolean
accountAgeEligible: (currentOrganization: OrganizationType | null, retentionMonths: number | null) => boolean
- warningEligible: (retentionEnforced: boolean, accountAgeEligible: boolean, isSnoozed: boolean) => boolean
+ retentionApplies: (retentionEnforced: boolean, accountAgeEligible: boolean) => boolean
+ warningEligible: (retentionApplies: boolean, isSnoozed: boolean) => boolean
}
}
@@ -116,10 +119,14 @@ export const dataRetentionBannerLogic = kea<dataRetentionBannerLogicType>([
return dayjs(currentOrganization.created_at).isBefore(horizon)
},
],
+ retentionApplies: [
+ (s) => [s.retentionEnforced, s.accountAgeEligible],
+ (retentionEnforced: boolean, accountAgeEligible: boolean): boolean =>
+ retentionEnforced && accountAgeEligible,
+ ],
warningEligible: [
- (s) => [s.retentionEnforced, s.accountAgeEligible, s.isSnoozed],
- (retentionEnforced: boolean, accountAgeEligible: boolean, isSnoozed: boolean): boolean =>
- retentionEnforced && accountAgeEligible && !isSnoozed,
+ (s) => [s.retentionApplies, s.isSnoozed],
+ (retentionApplies: boolean, isSnoozed: boolean): boolean => retentionApplies && !isSnoozed,
],
}),
])
diff --git a/frontend/src/scenes/insights/dataRetention/exceedsRetention.test.ts b/frontend/src/scenes/insights/dataRetention/exceedsRetention.test.ts
new file mode 100644
index 000000000000..59ac42c0c84b
--- /dev/null
+++ b/frontend/src/scenes/insights/dataRetention/exceedsRetention.test.ts
@@ -0,0 +1,90 @@
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import { exceedsRetention } from './exceedsRetention'
+
+const RETENTION_MONTHS = 12
+
+const insightViz = (dateFrom: string | null, series: any[] = [{ kind: NodeKind.EventsNode }]): any => ({
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, dateRange: { date_from: dateFrom }, series },
+})
+
+const WAREHOUSE_SERIES = { kind: NodeKind.DataWarehouseNode }
+
+const sqlInsight = (query: string): any => ({
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query },
+})
+
+describe('exceedsRetention', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ jest.setSystemTime(new Date('2026-06-15T12:00:00.000Z'))
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it.each([
+ ['a team with no enforced window never warns', insightViz('-3y'), undefined, '2023-06-15', null, false],
+ [
+ 'a resolved range inside the window is fine',
+ insightViz('-30d'),
+ undefined,
+ '2026-05-16',
+ RETENTION_MONTHS,
+ false,
+ ],
+ ['a resolved range past the window warns', insightViz('-3y'), undefined, '2023-06-15', RETENTION_MONTHS, true],
+ ['no resolved range yet stays quiet', insightViz('-3y'), undefined, undefined, RETENTION_MONTHS, false],
+ // "All time" resolves to the earliest event the floored query can see, so the resolved range never reaches
+ // past the window; the requested range has to carry the warning.
+ ['"all time" warns however recent the resolved range', insightViz('all'), undefined, '2026-01-01', 84, true],
+ [
+ 'an "all time" override warns over a short saved range',
+ insightViz('-7d'),
+ 'all',
+ '2026-06-08',
+ RETENTION_MONTHS,
+ true,
+ ],
+ [
+ 'an override narrower than a saved "all time" defers to the resolved range',
+ insightViz('all'),
+ '-7d',
+ '2026-06-08',
+ RETENTION_MONTHS,
+ false,
+ ],
+ ['SQL warns whenever retention applies', sqlInsight('select 1'), undefined, undefined, RETENTION_MONTHS, true],
+ [
+ 'a warehouse-only insight never warns',
+ insightViz('all', [WAREHOUSE_SERIES]),
+ undefined,
+ '2023-06-15',
+ RETENTION_MONTHS,
+ false,
+ ],
+ [
+ 'a mixed events and warehouse insight warns',
+ insightViz('-3y', [{ kind: NodeKind.EventsNode }, WAREHOUSE_SERIES]),
+ undefined,
+ '2023-06-15',
+ RETENTION_MONTHS,
+ true,
+ ],
+ ])(
+ '%s',
+ (
+ _label: string,
+ query: any,
+ dateFromOverride: string | undefined,
+ resolvedDateFrom: string | undefined,
+ retentionMonths: number | null,
+ expected: boolean
+ ) => {
+ expect(exceedsRetention({ query, dateFromOverride, resolvedDateFrom, retentionMonths })).toBe(expected)
+ }
+ )
+})
diff --git a/frontend/src/scenes/insights/dataRetention/exceedsRetention.ts b/frontend/src/scenes/insights/dataRetention/exceedsRetention.ts
new file mode 100644
index 000000000000..0fe290fd5adc
--- /dev/null
+++ b/frontend/src/scenes/insights/dataRetention/exceedsRetention.ts
@@ -0,0 +1,52 @@
+import { dayjs } from 'lib/dayjs'
+
+import { Node } from '~/queries/schema/schema-general'
+import {
+ isAnyDataWarehouseNode,
+ isDataVisualizationNode,
+ isHogQLQuery,
+ isInsightQueryWithSeries,
+ isInsightVizNode,
+} from '~/queries/utils'
+
+/** Whether one insight's date range reaches past the team's events retention window.
+ *
+ * Shared by the per-insight banner, the dashboard-level banner and the tile icon so every surface answers the
+ * question the same way, from the range the backend resolved for the results being shown.
+ */
+export function exceedsRetention({
+ query,
+ dateFromOverride,
+ resolvedDateFrom,
+ retentionMonths,
+}: {
+ query?: Node | null
+ /** Effective range from a surface that overrides the query's own: a dashboard or tile filter, or the live editor. */
+ dateFromOverride?: string | null
+ /** `resolved_date_range.date_from` from the query response the surface is showing. */
+ resolvedDateFrom?: string | null
+ retentionMonths: number | null
+}): boolean {
+ if (!retentionMonths) {
+ return false
+ }
+ // A SQL insight can scan arbitrary history and has no resolved range, so warn whenever retention applies.
+ if (isHogQLQuery(query) || (isDataVisualizationNode(query) && isHogQLQuery(query.source))) {
+ return true
+ }
+ const source = isInsightVizNode(query) ? query.source : undefined
+ // Retention floors only the events table, so an insight reading warehouse tables alone can't be truncated.
+ if (isInsightQueryWithSeries(source) && source.series.length > 0 && source.series.every(isAnyDataWarehouseNode)) {
+ return false
+ }
+ const dateFrom = dateFromOverride ?? source?.dateRange?.date_from
+ // "All time" resolves to the earliest event the floored query can still see, which is never older than the
+ // window, so the resolved range alone can't reveal that older events were cut off.
+ if (dateFrom === 'all') {
+ return true
+ }
+ if (!resolvedDateFrom) {
+ return false
+ }
+ return dayjs(resolvedDateFrom).isBefore(dayjs().subtract(retentionMonths, 'month'))
+}
diff --git a/frontend/src/scenes/insights/dataRetention/insightRetentionBannerLogic.ts b/frontend/src/scenes/insights/dataRetention/insightRetentionBannerLogic.ts
index 31500ea19d59..ac86fba5efb9 100644
--- a/frontend/src/scenes/insights/dataRetention/insightRetentionBannerLogic.ts
+++ b/frontend/src/scenes/insights/dataRetention/insightRetentionBannerLogic.ts
@@ -1,15 +1,14 @@
import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'
-import { dayjs } from 'lib/dayjs'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
-import { isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'
import { InsightLogicProps } from '~/types'
import type { DateRange, Node } from '../../../queries/schema/schema-general'
import { dataRetentionBannerLogic } from './dataRetentionBannerLogic'
+import { exceedsRetention } from './exceedsRetention'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightRetentionBannerLogicValues {
@@ -44,8 +43,7 @@ export type insightRetentionBannerLogicType = MakeLogicType<
>
// Per-insight half of the retention warning: does this insight's range reach past the team's retention window?
-// "All time" is treated as exceeding (it resolves to the earliest event, so a team with only recent data wouldn't
-// otherwise trip it); every other range uses the resolved date range straight from the query response.
+// The rule itself lives in exceedsRetention so the dashboard-level banner answers the question identically.
export const insightRetentionBannerLogic = kea<insightRetentionBannerLogicType>([
props({} as InsightLogicProps),
key(keyForInsightLogicProps('new')),
@@ -68,24 +66,14 @@ export const insightRetentionBannerLogic = kea<insightRetentionBannerLogicType>(
insightData: Record<string, any>,
retentionMonths: number | null,
query: null | import('../../../queries/schema').Node
- ): boolean => {
- if (!retentionMonths) {
- return false
- }
- // SQL/HogQL insights can scan arbitrary history with no resolvable range, so warn whenever eligible.
- if (query && (isHogQLQuery(query) || (isDataVisualizationNode(query) && isHogQLQuery(query.source)))) {
- return true
- }
- // "All time" is an unbounded intent: warn even when the team's data doesn't yet reach that far back.
- if (dateRange?.date_from === 'all') {
- return true
- }
- const dateFrom = insightData?.resolved_date_range?.date_from
- if (!dateFrom) {
- return false
- }
- return dayjs(dateFrom).isBefore(dayjs().subtract(retentionMonths, 'month'))
- },
+ ): boolean =>
+ exceedsRetention({
+ query,
+ // The live editor range wins over whatever the saved query declares.
+ dateFromOverride: dateRange?.date_from,
+ resolvedDateFrom: insightData?.resolved_date_range?.date_from,
+ retentionMonths,
+ }),
],
shouldShowBanner: [
(s) => [s.warningEligible, s.rangeExceedsRetention],
diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsx
index 94bdca204c86..ed560d6f009a 100644
--- a/frontend/src/scenes/insights/insightDataLogic.tsx
+++ b/frontend/src/scenes/insights/insightDataLogic.tsx
@@ -67,6 +67,7 @@ import type {
QuerySchema,
QueryStatus,
RefreshType,
+ ResolvedDateRangeResponse,
SessionsQueryResponse,
TraceSpansAggregationQueryResponse,
TraceSpansAttributeBreakdownQueryResponse,
@@ -272,6 +273,7 @@ export interface insightDataLogicActions {
order: number | null
query: Node<Record<string, any>> | null
query_status?: QueryStatus | undefined
+ resolved_date_range?: ResolvedDateRangeResponse | null | undefined
result: any
saved: boolean
short_id: InsightShortId
@@ -318,6 +320,7 @@ export interface insightDataLogicActions {
order: number | null
query: Node<Record<string, any>> | null
query_status?: QueryStatus | undefined
+ resolved_date_range?: ResolvedDateRangeResponse | null | undefined
result: any
saved: boolean
short_id: InsightShortId
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index c380380b3ec0..0e11604c14f0 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -80,7 +80,7 @@ import type { InsightFilterOverrideContextApi } from '../../../../products/produ
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { ProductIntentProperties } from '../../lib/utils/product-intents'
import type { Noun } from '../../models/groupsModel'
-import type { QueryStatus } from '../../queries/schema/schema-general'
+import type { QueryStatus, ResolvedDateRangeResponse } from '../../queries/schema/schema-general'
import type { CohortType, DashboardTileBasicType, TeamPublicType, TeamType, UserBasicType, UserType } from '../../types'
import { teamLogic } from '../teamLogic'
import type { MathDefinition } from '../trends/mathsLogic'
@@ -208,6 +208,7 @@ export interface insightLogicActions {
order: number | null
query: Node<Record<string, any>> | null
query_status?: QueryStatus | undefined
+ resolved_date_range?: ResolvedDateRangeResponse | null | undefined
result: any
saved: boolean
short_id: InsightShortId
@@ -252,6 +253,7 @@ export interface insightLogicActions {
order: number | null
query: Node<Record<string, any>> | null
query_status?: QueryStatus | undefined
+ resolved_date_range?: ResolvedDateRangeResponse | null | undefined
result: any
saved: boolean
short_id: InsightShortId
@@ -373,6 +375,7 @@ export interface insightLogicActions {
order?: number | null | undefined
query?: Node<Record<string, any>> | null | undefined
query_status?: QueryStatus | undefined
+ resolved_date_range?: ResolvedDateRangeResponse | null | undefined
result?: any
saved?: boolean | undefined
short_id?: InsightShortId | undefined
@@ -416,6 +419,7 @@ export interface insightLogicActions {
order?: number | null | undefined
query?: Node<Record<string, any>> | null | undefined
query_status?: QueryStatus | undefined
+ resolved_date_range?: ResolvedDateRangeResponse | null | undefined
result?: any
saved?: boolean | undefined
short_id?: InsightShortId | undefined
diff --git a/frontend/src/scenes/saved-insights/activityDescriptions.tsx b/frontend/src/scenes/saved-insights/activityDescriptions.tsx
index 39417818d666..67657637e5ec 100644
--- a/frontend/src/scenes/saved-insights/activityDescriptions.tsx
+++ b/frontend/src/scenes/saved-insights/activityDescriptions.tsx
@@ -259,6 +259,7 @@ const insightActionsMapping: Record<
view_count: () => null,
is_cached: () => null,
filter_override_context: () => null,
+ resolved_date_range: () => null,
}
function summarizeQueryChanges(query: InsightQueryNode | HogQLQuery): ChangeMapping {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 05520dc9a9ee..b03b42825f3b 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -71,6 +71,7 @@ import type {
QuickFilterType,
RecordingOrder,
RecordingsQuery,
+ ResolvedDateRangeResponse,
RevenueAnalyticsConfig,
SharingConfigurationSettings,
TileFilters,
@@ -2641,6 +2642,7 @@ export interface InsightModel extends Cacheable, WithAccessControl {
query_status?: QueryStatus
is_cached?: boolean
filter_override_context?: InsightFilterOverrideContextApi | null
+ resolved_date_range?: ResolvedDateRangeResponse | null
/** Only used when creating objects */
_create_in_folder?: string | null
}