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(insights): quarter and year interval selection behind a feature flag (#68297)

Sam Penningtond936a173a143
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index e4db8b5512b7..8fbe027fdd53 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -428,6 +428,7 @@ export const FEATURE_FLAGS = {
PRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics
PRODUCT_ANALYTICS_INSIGHTS_TOOLTIPS: 'product-analytics-insights-tooltips', // owner: #team-product-analytics, gates the unified quill DefaultTooltip for trends/retention/stickiness insight charts
PRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analytics
+ PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS: 'product-analytics-quarter-year-intervals', // owner: @sampennington #team-product-analytics, gates quarter/year interval selection on insights
PRODUCT_ANALYTICS_QUILL_LEGEND: 'product-analytics-quill-legend', // owner: #team-product-analytics, gates the in-chart quill legend replacing the legacy side InsightLegend
PRODUCT_ANALYTICS_QUILL_SQL_CHARTS: 'product-analytics-quill-sql-charts', // owner: #team-data-tools, gates rendering DataVisualization line/area charts via @posthog/quill-charts
PRODUCT_ANALYTICS_RETENTION_AGGREGATION: 'retention-aggregation', // owner: @anirudhpillai #team-product-analytics
diff --git a/frontend/src/lib/utils/datetime.test.ts b/frontend/src/lib/utils/datetime.test.ts
index abb29371f6fb..9f25fd68353e 100644
--- a/frontend/src/lib/utils/datetime.test.ts
+++ b/frontend/src/lib/utils/datetime.test.ts
@@ -418,6 +418,24 @@ describe('datetime utils', () => {
})
})
+ it.each([
+ ['quarter' as const, '2025-04-01T00:00:00+00:00', '2026-06-30T23:59:59+00:00'],
+ ['year' as const, '2025-01-01T00:00:00+00:00', '2026-12-31T23:59:59+00:00'],
+ ])('expands to full periods when grouping by %s', (interval, expectedFrom, expectedTo) => {
+ expect(
+ alignResolvedDateRangeToInterval(
+ {
+ date_from: '2025-04-07T00:00:00+00:00',
+ date_to: '2026-04-07T23:59:59+00:00',
+ },
+ interval
+ )
+ ).toEqual({
+ date_from: expectedFrom,
+ date_to: expectedTo,
+ })
+ })
+
it('preserves a non-UTC timezone offset', () => {
expect(
alignResolvedDateRangeToInterval(
diff --git a/frontend/src/lib/utils/datetime.ts b/frontend/src/lib/utils/datetime.ts
index e262c8fbb76d..4c9ce016174f 100644
--- a/frontend/src/lib/utils/datetime.ts
+++ b/frontend/src/lib/utils/datetime.ts
@@ -194,12 +194,11 @@ export function getConstrainedWeekRange(
}
}
-// When an insight is grouped by month, the query's WHERE clause uses
-// toStartOfInterval(date_from, month), so the first and last chart buckets cover the
-// whole month. Expand the resolved range we show in the tooltip to match — otherwise
+// When an insight is grouped by month/quarter/year, the query's WHERE clause uses
+// toStartOfInterval(date_from, <interval>), so the first and last chart buckets cover the
+// whole period. Expand the resolved range we show in the tooltip to match — otherwise
// "Last 12 months" from April 7 looks like it excludes April 1–6, which it doesn't.
-// Scoped to month for now; weekly grouping has the same drift but is less visually
-// jarring and isn't handled here.
+// Weekly grouping has the same drift but is less visually jarring and isn't handled here.
const TZ_SUFFIX_RE = /([+-]\d{2}:\d{2}|Z)$/
function splitTimezoneSuffix(iso: string): [string, string] {
@@ -218,14 +217,14 @@ export function alignResolvedDateRangeToInterval(
if (!resolvedDateRange?.date_from || !resolvedDateRange?.date_to) {
return undefined
}
- if (interval !== 'month') {
+ if (interval !== 'month' && interval !== 'quarter' && interval !== 'year') {
return resolvedDateRange
}
// Parse the wall-clock portion only, so manipulation stays in the original tz.
const [fromWall, fromTz] = splitTimezoneSuffix(resolvedDateRange.date_from)
const [toWall, toTz] = splitTimezoneSuffix(resolvedDateRange.date_to)
- const from = dayjs.utc(fromWall).startOf('month')
- const to = dayjs.utc(toWall).endOf('month')
+ const from = dayjs.utc(fromWall).startOf(interval)
+ const to = dayjs.utc(toWall).endOf(interval)
return {
date_from: from.format('YYYY-MM-DDTHH:mm:ss') + fromTz,
date_to: to.format('YYYY-MM-DDTHH:mm:ss') + toTz,
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
index 3b2e9a480891..58f416d817e5 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
@@ -361,6 +361,56 @@ describe('insightVizDataLogic', () => {
explicitDate: false,
})
})
+
+ it('auto-selects quarter interval for >36-month range when flag is on', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS]: true,
+ })
+
+ await expectLogic(builtInsightDataLogic, () => {
+ builtInsightVizDataLogic.actions.updateDateRange({
+ date_from: '2020-01-01',
+ date_to: '2024-01-01',
+ explicitDate: true,
+ })
+ })
+ .toFinishAllListeners()
+ .toMatchValues({
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: expect.objectContaining({
+ interval: 'quarter',
+ }),
+ },
+ })
+
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS]: false,
+ })
+ })
+
+ it('auto-selects month interval for >36-month range when flag is off', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS]: false,
+ })
+
+ await expectLogic(builtInsightDataLogic, () => {
+ builtInsightVizDataLogic.actions.updateDateRange({
+ date_from: '2020-01-01',
+ date_to: '2024-01-01',
+ explicitDate: true,
+ })
+ })
+ .toFinishAllListeners()
+ .toMatchValues({
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: expect.objectContaining({
+ interval: 'month',
+ }),
+ },
+ })
+ })
})
describe('updateBreakdownFilter', () => {
@@ -590,6 +640,27 @@ describe('insightVizDataLogic', () => {
})
})
+ it('unhides quarter and year when the flag is enabled', () => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS]: true,
+ })
+
+ expect(builtInsightVizDataLogic.values.enabledIntervals.quarter).toEqual({
+ label: 'quarter',
+ newDateFrom: '-3y',
+ hidden: false,
+ })
+ expect(builtInsightVizDataLogic.values.enabledIntervals.year).toEqual({
+ label: 'year',
+ newDateFrom: '-5y',
+ hidden: false,
+ })
+
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS]: false,
+ })
+ })
+
it('adds a disabled reason with active users math', () => {
expectLogic(builtInsightVizDataLogic, () => {
builtInsightVizDataLogic.actions.updateQuerySource({
@@ -622,12 +693,45 @@ describe('insightVizDataLogic', () => {
'Grouping by month is not supported on insights with weekly active users series.',
},
week: { label: 'week', newDateFrom: '-30d' },
- quarter: { label: 'quarter', newDateFrom: '-3y', hidden: true },
- year: { label: 'year', newDateFrom: '-5y', hidden: true },
+ quarter: {
+ label: 'quarter',
+ newDateFrom: '-3y',
+ hidden: true,
+ disabledReason:
+ 'Grouping by quarter is not supported on insights with weekly active users series.',
+ },
+ year: {
+ label: 'year',
+ newDateFrom: '-5y',
+ hidden: true,
+ disabledReason:
+ 'Grouping by year is not supported on insights with weekly active users series.',
+ },
},
})
})
+ it('snaps interval to week when switching series to WAU on a quarter-grouped query', () => {
+ builtInsightVizDataLogic.actions.updateQuerySource({
+ interval: 'quarter',
+ } as Partial<TrendsQuery>)
+
+ expectLogic(builtInsightVizDataLogic, () => {
+ builtInsightVizDataLogic.actions.updateQuerySource({
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ name: '$pageview',
+ event: '$pageview',
+ math: BaseMathType.WeeklyActiveUsers,
+ },
+ ],
+ } as Partial<TrendsQuery>)
+ }).toMatchValues({
+ querySource: expect.objectContaining({ interval: 'week' }),
+ })
+ })
+
it('clears smoothing when switching between intervals', async () => {
const trendsQuery = { ...trendsQueryDefault, interval: 'minute' }
trendsQuery.trendsFilter = { ...trendsQuery.trendsFilter, smoothingIntervals: 2 }
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index c839955ed7b5..33992124f845 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -518,10 +518,15 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
getActiveUsersMath(series),
],
enabledIntervals: [
- (s) => [s.activeUsersMath, s.isTrends],
- (activeUsersMath, isTrends): Intervals => {
+ (s) => [s.activeUsersMath, s.isTrends, s.featureFlags],
+ (activeUsersMath, isTrends, featureFlags): Intervals => {
const enabledIntervals: Intervals = { ...intervals }
+ if (featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS]) {
+ enabledIntervals.quarter = { ...enabledIntervals.quarter, hidden: false }
+ enabledIntervals.year = { ...enabledIntervals.year, hidden: false }
+ }
+
if (activeUsersMath) {
enabledIntervals.hour = {
...enabledIntervals.hour,
@@ -535,6 +540,16 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
disabledReason:
'Grouping by month is not supported on insights with weekly active users series.',
}
+ enabledIntervals.quarter = {
+ ...enabledIntervals.quarter,
+ disabledReason:
+ 'Grouping by quarter is not supported on insights with weekly active users series.',
+ }
+ enabledIntervals.year = {
+ ...enabledIntervals.year,
+ disabledReason:
+ 'Grouping by year is not supported on insights with weekly active users series.',
+ }
}
}
@@ -841,14 +856,18 @@ const handleQuerySourceUpdateSideEffects = (
// to an appropriate allowed interval and inform them of the change via a toast
if (
maybeChangedActiveUsersMath !== null &&
- (interval === 'hour' || interval === 'month' || interval === 'minute')
+ (interval === 'hour' ||
+ interval === 'month' ||
+ interval === 'minute' ||
+ interval === 'quarter' ||
+ interval === 'year')
) {
if (interval === 'hour' || interval === 'minute') {
lemonToast.info(
`Switched to grouping by day, because "${BASE_MATH_DEFINITIONS[maybeChangedActiveUsersMath].name}" does not support grouping by ${interval}.`
)
;(mergedUpdate as TrendsQuery).interval = 'day'
- } else if (interval === 'month' && maybeChangedActiveUsersMath === BaseMathType.WeeklyActiveUsers) {
+ } else if (maybeChangedActiveUsersMath === BaseMathType.WeeklyActiveUsers) {
lemonToast.info(
`Switched to grouping by week, because "${BASE_MATH_DEFINITIONS[maybeChangedActiveUsersMath].name}" does not support grouping by ${interval}.`
)
@@ -923,10 +942,21 @@ const handleQuerySourceUpdateSideEffects = (
const { date_from, date_to } = { ...currentState.dateRange, ...update.dateRange }
if (date_from && date_to && dayjs(date_from).isValid() && dayjs(date_to).isValid()) {
- if (dayjs(date_to).diff(dayjs(date_from), 'day') <= 3) {
+ const quarterYearEnabled =
+ !!featureFlagLogic.findMounted()?.values.featureFlags[
+ FEATURE_FLAGS.PRODUCT_ANALYTICS_QUARTER_YEAR_INTERVALS
+ ]
+ const parsedFrom = dayjs(date_from)
+ const parsedTo = dayjs(date_to)
+ const monthDiff = parsedTo.diff(parsedFrom, 'month')
+ // 3 years in months; quarter auto-interval kicks in beyond this threshold
+ const QUARTER_AUTO_INTERVAL_THRESHOLD_MONTHS = 36
+ if (parsedTo.diff(parsedFrom, 'day') <= 3) {
;(mergedUpdate as TrendsQuery).interval = 'hour'
- } else if (dayjs(date_to).diff(dayjs(date_from), 'month') <= 3) {
+ } else if (monthDiff <= 3) {
;(mergedUpdate as TrendsQuery).interval = 'day'
+ } else if (quarterYearEnabled && monthDiff > QUARTER_AUTO_INTERVAL_THRESHOLD_MONTHS) {
+ ;(mergedUpdate as TrendsQuery).interval = 'quarter'
} else {
;(mergedUpdate as TrendsQuery).interval = 'month'
}
diff --git a/packages/quill/packages/charts/src/utils/dates.test.ts b/packages/quill/packages/charts/src/utils/dates.test.ts
index 52b10719cccf..0db1b698e0d3 100644
--- a/packages/quill/packages/charts/src/utils/dates.test.ts
+++ b/packages/quill/packages/charts/src/utils/dates.test.ts
@@ -29,6 +29,12 @@ describe('createXAxisTickCallback', () => {
allDays: ['2025-01-01', '2025-02-01', '2025-03-01'],
expected: ['2025', 'February', 'March'],
},
+ {
+ scenario: 'inferred quarter interval from ~90 day gaps',
+ interval: undefined,
+ allDays: ['2025-04-01', '2025-07-01', '2025-10-01'],
+ expected: ['Q2', 'Q3', 'Q4'],
+ },
{
scenario: 'inferred day interval from 1 day gaps',
interval: undefined,
@@ -77,6 +83,18 @@ describe('createXAxisTickCallback', () => {
allDays: ['2025-11-01', '2025-12-01', '2026-01-01', '2026-02-01'],
expected: ['November', 'December', '2026', 'February'],
},
+ {
+ scenario: 'quarterly, cross year → year at Q1 boundary, [Q]Q otherwise',
+ interval: 'quarter' as const,
+ allDays: ['2025-07-01', '2025-10-01', '2026-01-01', '2026-04-01'],
+ expected: ['Q3', 'Q4', '2026', 'Q2'],
+ },
+ {
+ scenario: 'yearly → plain years',
+ interval: 'year' as const,
+ allDays: ['2024-01-01', '2025-01-01', '2026-01-01'],
+ expected: ['2024', '2025', '2026'],
+ },
{
scenario: 'daily, short span → full month name on 1st, MMM D otherwise',
interval: 'day' as const,
diff --git a/packages/quill/packages/charts/src/utils/dates.ts b/packages/quill/packages/charts/src/utils/dates.ts
index fba97de22bab..3e240792d152 100644
--- a/packages/quill/packages/charts/src/utils/dates.ts
+++ b/packages/quill/packages/charts/src/utils/dates.ts
@@ -12,6 +12,8 @@ interface CreateXAxisTickCallbackArgs {
type TickMode =
| { type: 'month' }
+ | { type: 'quarter' }
+ | { type: 'year' }
| { type: 'day' }
| { type: 'monthly'; visibleBoundaries: Set<number> }
| { type: 'hourly' }
@@ -90,7 +92,13 @@ function pickMode(interval: TimeInterval, parsedDates: Dayjs[], first: Dayjs, la
const spanMonths = (last.year() - first.year()) * 12 + last.month() - first.month()
const spanDays = last.diff(first, 'day')
- if (interval === 'month' || interval === 'quarter' || interval === 'year') {
+ if (interval === 'quarter') {
+ return { type: 'quarter' }
+ }
+ if (interval === 'year') {
+ return { type: 'year' }
+ }
+ if (interval === 'month') {
return { type: 'month' }
}
if ((interval === 'day' || interval === 'week') && spanMonths >= 3) {
@@ -127,6 +135,10 @@ function formatTick(mode: TickMode, date: Dayjs, index: number): string {
case 'month':
case 'monthly':
return formatMonthLabel(date)
+ case 'quarter':
+ return formatQuarterLabel(date)
+ case 'year':
+ return String(date.year())
case 'day':
return date.date() === 1 ? formatMonthLabel(date) : date.format('MMM D')
case 'hourly-multi-day':
@@ -143,6 +155,14 @@ function formatMonthLabel(date: Dayjs): string {
return date.format('MMMM')
}
+// Mirrors formatMonthLabel's convention: the year marks the year boundary, "Q2".."Q4" otherwise.
+function formatQuarterLabel(date: Dayjs): string {
+ if (date.month() === 0) {
+ return String(date.year())
+ }
+ return `Q${Math.floor(date.month() / 3) + 1}`
+}
+
function inferInterval(parsedDates: Dayjs[]): TimeInterval {
if (parsedDates.length < 2) {
return 'day'
@@ -155,6 +175,12 @@ function inferInterval(parsedDates: Dayjs[]): TimeInterval {
return 'hour'
}
const diffDays = parsedDates[1].diff(parsedDates[0], 'day')
+ if (diffDays >= 300) {
+ return 'year'
+ }
+ if (diffDays >= 80) {
+ return 'quarter'
+ }
if (diffDays >= 25) {
return 'month'
}