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.

fix(web-analytics): don't compare all-time ranges to a previous period (#81305)

Lucas Ricoy3ef678831894
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
index 52d7fb66243a..bedca8b99137 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
@@ -526,14 +526,24 @@ const WebVitalsPercentileToggle = (): JSX.Element | null => {
}
export const WebAnalyticsCompareFilter = (): JSX.Element | null => {
- const { compareFilter, productTab } = useValues(webAnalyticsLogic)
+ const { compareFilter, dateFilter, productTab } = useValues(webAnalyticsLogic)
const { setCompareFilter } = useActions(webAnalyticsLogic)
if (![ProductTab.ANALYTICS, ProductTab.PAGE_REPORTS].includes(productTab)) {
return null
}
- return <CompareFilter compareFilter={compareFilter} updateCompareFilter={setCompareFilter} />
+ return (
+ <CompareFilter
+ compareFilter={compareFilter}
+ updateCompareFilter={setCompareFilter}
+ disableReason={
+ dateFilter.dateFrom === 'all'
+ ? "All time starts at your first event, so there's no earlier period to compare to. Pick a date range to compare."
+ : null
+ }
+ />
+ )
}
const ShareButton = (): JSX.Element => {
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
index f73597af9bfe..6ce7e8e77d82 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
@@ -319,6 +319,40 @@ describe('webAnalyticsLogic precompute payload', () => {
})
})
+describe('webAnalyticsLogic compare filter', () => {
+ let logic: ReturnType<typeof webAnalyticsLogic.build>
+
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ jest.spyOn(api.propertyDefinitions, 'list').mockResolvedValue({ results: [] } as any)
+ jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({ results: [] } as any)
+ jest.spyOn(api, 'update').mockResolvedValue({} as any)
+ ;(posthog as any).setPersonProperties = jest.fn()
+ featureFlagLogic.mount()
+ logic = webAnalyticsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ // An all-time range has no earlier period, and comparing against one made the tiles report the
+ // first day of data as the previous period's total. The stored preference has to survive the
+ // switch, so that returning to a bounded range compares again without the user re-enabling it.
+ it('drops the comparison for an all-time range and applies it again for a bounded one', async () => {
+ logic.actions.setCompareFilter({ compare: true })
+
+ logic.actions.setDates('all', null)
+ await expectLogic(logic).toMatchValues({ compareFilter: { compare: false } })
+
+ logic.actions.setDates('-7d', null)
+ await expectLogic(logic).toMatchValues({ compareFilter: { compare: true } })
+ })
+})
+
describe('webAnalyticsLogic URL restoration', () => {
let logic: ReturnType<typeof webAnalyticsLogic.build>
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 517e0f01da19..465a056ec095 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -156,11 +156,11 @@ export interface webAnalyticsLogicValues {
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
user: UserType | null // userLogic
authorizedDomains: string[] // webAnalyticsFilterLogic
- compareFilter: CompareFilter // webAnalyticsFilterLogic
countryFilter: string | null // webAnalyticsFilterLogic
deviceTypeFilter: DeviceType | null // webAnalyticsFilterLogic
domainFilter: string | null // webAnalyticsFilterLogic
hasHostFilter: boolean // webAnalyticsFilterLogic
+ rawCompareFilter: CompareFilter // webAnalyticsFilterLogic
rawWebAnalyticsFilters: WebAnalyticsPropertyFilters // webAnalyticsFilterLogic
referrerFilter: string | null // webAnalyticsFilterLogic
selectedHost: string | null // webAnalyticsFilterLogic
@@ -174,6 +174,7 @@ export interface webAnalyticsLogicValues {
_sourceTab: string | null
activeHoursTab: string
breadcrumbs: Breadcrumb[]
+ compareFilter: CompareFilter
controls: {
filterTestAccounts: boolean
includeHostPath: boolean
@@ -521,6 +522,7 @@ export interface webAnalyticsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webAnalyticsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ compareFilter: (rawCompareFilter: CompareFilter, dateFilter: DateFilterState) => CompareFilter
preAggregatedEnabled: (
featureFlags: FeatureFlagsSet,
currentTeam: TeamPublicType | TeamType | null
@@ -712,7 +714,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
'deviceTypeFilter',
'countryFilter',
'referrerFilter',
- 'compareFilter',
+ 'compareFilter as rawCompareFilter',
'hasHostFilter',
'validatedDomainFilter',
'selectedHost',
@@ -1143,6 +1145,14 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
isGreaterThanMd: (window: Window) => window.innerWidth > 768,
}),
selectors({
+ compareFilter: [
+ (s) => [s.rawCompareFilter, s.dateFilter],
+ (rawCompareFilter: CompareFilter, dateFilter: DateFilterState): CompareFilter =>
+ // An all-time range starts at the first event, so there is no earlier period left to
+ // compare it against. The stored preference is left untouched so that it applies
+ // again as soon as the range becomes a bounded one.
+ dateFilter.dateFrom === 'all' ? { compare: false } : rawCompareFilter,
+ ],
preAggregatedEnabled: [
(s) => [s.featureFlags, s.currentTeam],
(featureFlags: Record<string, boolean>, currentTeam: TeamPublicType | TeamType | null) => {
@@ -3066,7 +3076,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
_graphsTab,
isPathCleaningEnabled,
shouldFilterTestAccounts,
- compareFilter,
+ rawCompareFilter,
productTab,
webVitalsPercentile,
domainFilter,
@@ -3139,8 +3149,10 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
if (shouldFilterTestAccounts != null) {
urlParams.set('filter_test_accounts', shouldFilterTestAccounts.toString())
}
- if (compareFilter) {
- urlParams.set('compare_filter', JSON.stringify(compareFilter))
+ // The stored preference goes in the URL rather than the effective value, so that an
+ // all-time range does not overwrite it with the comparison it suppresses.
+ if (rawCompareFilter) {
+ urlParams.set('compare_filter', JSON.stringify(rawCompareFilter))
} else {
urlParams.delete('compare_filter')
}
@@ -3347,7 +3359,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
if (
compare_filter &&
isCompareFilter(compare_filter) &&
- !objectsEqual(compare_filter, values.compareFilter)
+ !objectsEqual(compare_filter, values.rawCompareFilter)
) {
actions.setCompareFilter(compare_filter)
}
diff --git a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
index 31ff390881d6..a51045faed7b 100644
--- a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
+++ b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
@@ -432,11 +432,14 @@ class TrendsActorsQueryBuilder:
# use previous day/week/... for time_frame
if self.is_compare_previous:
- if self.is_compare_to:
+ delta_mappings = None if self.is_compare_to else date_range.date_from_delta_mappings() # type: ignore
+ if delta_mappings is None:
+ # Either an explicit compare_to offset, or an "all time" range, which starts at the
+ # earliest event and so has no relative delta to step back by. Both shift the frame
+ # by the gap between the two periods' starts instead.
self.time_frame = query_from + (self.time_frame - self.trends_date_range.date_from())
else:
- relative_delta = relativedelta(**date_range.date_from_delta_mappings()) # type: ignore
- previous_time_frame = self.time_frame - relative_delta
+ previous_time_frame = self.time_frame - relativedelta(**delta_mappings)
if self.is_hourly:
self.time_frame = previous_time_frame
else:
diff --git a/posthog/hogql_queries/utils/query_previous_period_date_range.py b/posthog/hogql_queries/utils/query_previous_period_date_range.py
index 9e0d9c43f7a1..c6cc2d0be51c 100644
--- a/posthog/hogql_queries/utils/query_previous_period_date_range.py
+++ b/posthog/hogql_queries/utils/query_previous_period_date_range.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Optional
from posthog.schema import DateRange, IntervalType
@@ -28,9 +28,16 @@ class QueryPreviousPeriodDateRange(QueryDateRange):
super().__init__(date_range, team, interval, now, **kwargs)
def date_from_delta_mappings(self) -> dict[str, int] | None:
- if self._date_range and isinstance(self._date_range.date_from, str) and self._date_range.date_from != "all":
+ if self._date_range and self._date_range.date_from == "all":
+ # "All time" resolves to the earliest event rather than a relative offset, so there is no
+ # delta to report. Reporting a 7-day one triggers the "-7d is really 8 days" correction in
+ # get_compare_period_dates, which shifts the whole previous period a day later.
+ return None
+
+ if self._date_range and isinstance(self._date_range.date_from, str):
date_from = self._date_range.date_from
else:
+ # No date_from means the default range, which is DEFAULT_DATE_FROM_DAYS long.
date_from = "-7d"
delta_mapping = relative_date_parse_with_delta_mapping(
@@ -55,6 +62,17 @@ class QueryPreviousPeriodDateRange(QueryDateRange):
current_period_date_from = super().date_from()
current_period_date_to = super().date_to()
+ if self._date_range and self._date_range.date_from == "all":
+ # "All time" starts at the earliest event, whose time of day is arbitrary, while
+ # get_compare_period_dates ends the previous period at date_to's time of day. Those two
+ # land on the same calendar day here, so the generic path leaves the rest of the first
+ # day inside both periods. Size the previous period directly instead, ending it just
+ # before the first event.
+ previous_period_date_to = current_period_date_from - timedelta(microseconds=1)
+ return previous_period_date_to - (
+ current_period_date_to - current_period_date_from
+ ), previous_period_date_to
+
previous_period_date_from, previous_period_date_to = get_compare_period_dates(
current_period_date_from,
current_period_date_to,
diff --git a/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py b/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py
index 1d5206306ae0..75856b5c003b 100644
--- a/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py
+++ b/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py
@@ -1,8 +1,10 @@
+from datetime import timedelta
from zoneinfo import ZoneInfo
from posthog.test.base import APIBaseTest
from dateutil import parser
+from parameterized import parameterized
from posthog.schema import DateRange, IntervalType
@@ -34,6 +36,32 @@ class TestQueryPreviousPeriodDateRange(APIBaseTest):
self.assertEqual(query_date_range.date_from(), parser.isoparse("2021-08-11T00:00:00Z"))
self.assertEqual(query_date_range.date_to(), parser.isoparse("2021-08-17T23:59:59.999999Z"))
+ @parameterized.expand(
+ [
+ ("earliest event at midnight", "2021-07-06T00:00:00Z", "2021-05-16T00:00:00Z"),
+ ("earliest event mid-day", "2021-07-06T12:34:00Z", "2021-05-17T01:08:00Z"),
+ ]
+ )
+ def test_previous_period_for_all_time_ends_before_the_earliest_event(
+ self, _name: str, earliest_timestamp: str, expected_date_from: str
+ ):
+ # The previous period has to stop before the first event, or the comparison counts part of the
+ # first day twice and reports it as the previous period's total. Two ways that happened: the
+ # "-7d is really 8 days" correction in get_compare_period_dates shifted the whole period a day
+ # later, and its end takes date_to's time of day, which for a mid-day first event lands after
+ # the current period already started.
+ now = parser.isoparse("2021-08-25T12:34:00.000Z")
+ date_range = DateRange(date_from="all")
+ query_date_range = QueryPreviousPeriodDateRange(
+ team=self.team,
+ date_range=date_range,
+ interval=IntervalType.DAY,
+ now=now,
+ earliest_timestamp_fallback=parser.isoparse(earliest_timestamp),
+ )
+ self.assertEqual(query_date_range.date_to(), parser.isoparse(earliest_timestamp) - timedelta(microseconds=1))
+ self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_date_from))
+
def test_explicit_timezone_info_overrides_team_timezone(self):
# The previous-period delta parsing used to read directly from
# `self._team.timezone_info`, so a `timezone_info=UTC` override on the constructor