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): match comparison periods to the elapsed current one (#95416)

Jordan Mryyan3e9d67b5eb56
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 6d71f3125ef9..5711a42258a1 100644
--- a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
+++ b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
@@ -132,6 +132,7 @@ class TrendsActorsQueryBuilder:
now=datetime.now(),
compare_to=typing.cast(str, typing.cast(CompareFilter, self.trends_query.compareFilter).compare_to),
exact_timerange=self.exact_timerange,
+ full_comparison_period=True,
)
return QueryPreviousPeriodDateRange(
date_range=self.trends_query.dateRange,
@@ -139,6 +140,7 @@ class TrendsActorsQueryBuilder:
interval=self.trends_query.interval,
now=datetime.now(),
exact_timerange=self.exact_timerange,
+ full_comparison_period=True,
)
@cached_property
diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.py
index af2cb784e48c..bd92cccc7a43 100644
--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py
@@ -822,6 +822,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
now=datetime.now(),
compare_to=self.query.compareFilter.compare_to,
exact_timerange=self.exact_timerange,
+ full_comparison_period=True,
)
return QueryPreviousPeriodDateRange(
date_range=self.query.dateRange,
@@ -829,6 +830,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
interval=self.query.interval,
now=datetime.now(),
exact_timerange=self.exact_timerange,
+ full_comparison_period=True,
)
def series_event(self, series: Union[EventsNode, ActionsNode, DataWarehouseNode, GroupNode]) -> str | None:
diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.py
index ea40c78f5955..4d99ec368ac7 100644
--- a/posthog/hogql_queries/utils/query_date_range.py
+++ b/posthog/hogql_queries/utils/query_date_range.py
@@ -57,6 +57,7 @@ class QueryDateRange:
interval_count: Optional[int] = None,
timezone_info: Optional[ZoneInfo] = None,
exact_timerange: bool = False, # Setting this to true stops a relative time range from including the time between the intervalStart and the date_range start, as well as cuts off the interval at precisely now()
+ full_comparison_period: bool = False,
) -> None:
self._team = team
self._date_range = date_range
@@ -66,6 +67,7 @@ class QueryDateRange:
self._earliest_timestamp_fallback = earliest_timestamp_fallback
self._timezone_info = timezone_info or self._team.timezone_info
self._exact_timerange = exact_timerange
+ self._full_comparison_period = full_comparison_period
# Hour intervals have strange behaviour in clickhouse:
# From the docs:
@@ -215,6 +217,8 @@ class QueryDateRange:
granularity match the coarser intervals. Rolling sub-day windows ("-24h", "-30m") keep their
real end, since their previous period is just the window before them.
"""
+ if not self._full_comparison_period:
+ return current_period_date_to
if self.interval_name not in ("hour", "minute"):
return current_period_date_to
if self._exact_timerange or self.explicit:
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 516c79a6f06b..46357ce4beb2 100644
--- a/posthog/hogql_queries/utils/query_previous_period_date_range.py
+++ b/posthog/hogql_queries/utils/query_previous_period_date_range.py
@@ -10,9 +10,9 @@ from posthog.models.team import Team
from posthog.utils import get_compare_period_dates, relative_date_parse_with_delta_mapping
# Calendar-anchored ranges that run to now ("This week/month/quarter/year"). Their previous period
-# is the full prior calendar unit, so the length is a calendar delta rather than a fixed span of
-# days — months, quarters and years vary in length, so sizing by elapsed days can't express them.
-_FULL_PREVIOUS_CALENDAR_UNITS = {
+# sits one calendar unit back, so the offset is a calendar delta rather than a fixed span of days,
+# because months, quarters and years vary in length and elapsed days cannot express them.
+_PREVIOUS_CALENDAR_UNITS = {
"wStart": {"weeks": 1},
"mStart": {"months": 1},
"qStart": {"months": 3},
@@ -70,31 +70,40 @@ class QueryPreviousPeriodDateRange(QueryDateRange):
return delta_mapping
return None
- def full_previous_calendar_period(self, current_period_date_from: datetime) -> Optional[DateRangeBounds]:
- """The full prior calendar unit for a "This week/month/quarter/year" range that runs to now.
+ def previous_calendar_period(
+ self, current_period_date_from: datetime, current_period_date_to: datetime
+ ) -> Optional[DateRangeBounds]:
+ """The prior calendar unit for a "This week/month/quarter/year" range that runs to now.
- A partial current period (e.g. this month so far) is then charted against the complete
- previous one, matching how hour/minute day-anchored ranges already behave. The end is the
- moment before the current period starts and the start is one calendar unit before that, so
- months, quarters and years come back whole regardless of their varying lengths.
+ Both ends move back by one calendar unit, so the previous period keeps its position inside
+ that unit: the same weekday of the previous week, the same day of the previous month. Sizing
+ the previous period by elapsed duration instead would end it at the close of the prior unit,
+ which puts a Sunday-to-Wednesday week against a Wednesday-to-Saturday one.
+
+ Chart paths set full_comparison_period and run the previous period to the end of that unit,
+ so the comparison line spans the canvas. Aggregate paths keep the shortened end, so a partial
+ current period is scored against an equally partial previous one.
"""
if not self._date_range or self._date_range.date_to:
return None
- unit = _FULL_PREVIOUS_CALENDAR_UNITS.get(self._date_range.date_from) if self._date_range.date_from else None
+ unit = _PREVIOUS_CALENDAR_UNITS.get(self._date_range.date_from) if self._date_range.date_from else None
if unit is None:
return None
+ shift = relativedelta(**unit) # type: ignore[arg-type]
return DateRangeBounds(
- date_from=current_period_date_from - relativedelta(**unit), # type: ignore[arg-type]
- date_to=current_period_date_from - timedelta(microseconds=1),
+ date_from=current_period_date_from - shift,
+ date_to=current_period_date_from - timedelta(microseconds=1)
+ if self._full_comparison_period
+ else current_period_date_to - shift,
)
def dates(self) -> DateRangeBounds:
current_period_date_from = super().date_from()
current_period_date_to = super().date_to()
- full_previous = self.full_previous_calendar_period(current_period_date_from)
- if full_previous is not None:
- return full_previous
+ previous_calendar = self.previous_calendar_period(current_period_date_from, current_period_date_to)
+ if previous_calendar is not None:
+ return previous_calendar
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
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 99e679cc214c..55f10a748d56 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
@@ -64,53 +64,169 @@ class TestQueryPreviousPeriodDateRange(APIBaseTest):
@parameterized.expand(
[
- # A day-anchored range at hour granularity used to size the previous period from the
- # elapsed part of today (ending 12:59), truncating it. It now spans the full previous
- # day, matching how day/week/month intervals already behave.
- ("today_hour", "dStart", IntervalType.HOUR, "2021-08-24T00:00:00Z", "2021-08-24T23:59:59.999999Z"),
- ("today_minute", "dStart", IntervalType.MINUTE, "2021-08-24T00:00:00.000001Z", "2021-08-25T00:00:00Z"),
- ("last_7d_hour", "-7d", IntervalType.HOUR, "2021-08-10T00:00:00Z", "2021-08-17T23:59:59.999999Z"),
- # A rolling sub-day window is unchanged: its previous period is just the window before it.
- ("last_24h_hour", "-24h", IntervalType.HOUR, "2021-08-23T12:00:00Z", "2021-08-24T12:59:59.999999Z"),
+ ("today_hour", "dStart", IntervalType.HOUR, False, "2021-08-24T00:00:00Z", "2021-08-24T12:59:59.999999Z"),
+ (
+ "today_hour_full_period",
+ "dStart",
+ IntervalType.HOUR,
+ True,
+ "2021-08-24T00:00:00Z",
+ "2021-08-24T23:59:59.999999Z",
+ ),
+ (
+ "today_minute",
+ "dStart",
+ IntervalType.MINUTE,
+ False,
+ "2021-08-24T11:25:00.000001Z",
+ "2021-08-25T00:00:00Z",
+ ),
+ (
+ "today_minute_full_period",
+ "dStart",
+ IntervalType.MINUTE,
+ True,
+ "2021-08-24T00:00:00.000001Z",
+ "2021-08-25T00:00:00Z",
+ ),
+ ("last_7d_hour", "-7d", IntervalType.HOUR, False, "2021-08-10T00:00:00Z", "2021-08-17T12:59:59.999999Z"),
+ (
+ "last_7d_hour_full_period",
+ "-7d",
+ IntervalType.HOUR,
+ True,
+ "2021-08-10T00:00:00Z",
+ "2021-08-17T23:59:59.999999Z",
+ ),
+ (
+ "last_24h_hour_full_period",
+ "-24h",
+ IntervalType.HOUR,
+ True,
+ "2021-08-23T12:00:00Z",
+ "2021-08-24T12:59:59.999999Z",
+ ),
]
)
def test_previous_period_hourly_range_sizing(
- self, _name: str, date_from: str, interval: IntervalType, expected_from: str, expected_to: str
+ self,
+ _name: str,
+ date_from: str,
+ interval: IntervalType,
+ full_comparison_period: bool,
+ expected_from: str,
+ expected_to: str,
):
now = parser.isoparse("2021-08-25T12:34:00.000Z")
query_date_range = QueryPreviousPeriodDateRange(
- team=self.team, date_range=DateRange(date_from=date_from), interval=interval, now=now
+ team=self.team,
+ date_range=DateRange(date_from=date_from),
+ interval=interval,
+ now=now,
+ full_comparison_period=full_comparison_period,
)
self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_from))
self.assertEqual(query_date_range.date_to(), parser.isoparse(expected_to))
@parameterized.expand(
[
- # "This week/month/quarter/year" run to now, so the current period is partial. The previous
- # period is the full prior calendar unit (weekday/day-of-month aligned, complete), matching
- # how day-anchored hour/minute ranges already behave — not the trailing slice of it.
- ("this_week", "2021-08-25T12:34:00Z", "wStart", "2021-08-15T00:00:00Z", "2021-08-21T23:59:59.999999Z"),
- ("this_month", "2021-08-25T12:34:00Z", "mStart", "2021-07-01T00:00:00Z", "2021-07-31T23:59:59.999999Z"),
- # A shorter previous month must still come back whole: diff-in-days sizing can't express this.
(
- "this_month_february",
+ "this_week",
+ "2021-08-25T12:34:00Z",
+ "wStart",
+ False,
+ "2021-08-15T00:00:00Z",
+ "2021-08-18T23:59:59.999999Z",
+ ),
+ (
+ "this_week_full_period",
+ "2021-08-25T12:34:00Z",
+ "wStart",
+ True,
+ "2021-08-15T00:00:00Z",
+ "2021-08-21T23:59:59.999999Z",
+ ),
+ (
+ "this_month",
+ "2021-08-25T12:34:00Z",
+ "mStart",
+ False,
+ "2021-07-01T00:00:00Z",
+ "2021-07-25T23:59:59.999999Z",
+ ),
+ (
+ "this_month_ending_past_the_previous_month",
+ "2021-03-31T12:34:00Z",
+ "mStart",
+ False,
+ "2021-02-01T00:00:00Z",
+ "2021-02-28T23:59:59.999999Z",
+ ),
+ (
+ "this_quarter",
+ "2021-08-25T12:34:00Z",
+ "qStart",
+ False,
+ "2021-04-01T00:00:00Z",
+ "2021-05-25T23:59:59.999999Z",
+ ),
+ (
+ "this_month_full_period",
+ "2021-08-25T12:34:00Z",
+ "mStart",
+ True,
+ "2021-07-01T00:00:00Z",
+ "2021-07-31T23:59:59.999999Z",
+ ),
+ (
+ "this_month_february_full_period",
"2021-03-15T12:34:00Z",
"mStart",
+ True,
"2021-02-01T00:00:00Z",
"2021-02-28T23:59:59.999999Z",
),
- ("this_quarter", "2021-08-25T12:34:00Z", "qStart", "2021-04-01T00:00:00Z", "2021-06-30T23:59:59.999999Z"),
- ("this_year", "2021-08-25T12:34:00Z", "yStart", "2020-01-01T00:00:00Z", "2020-12-31T23:59:59.999999Z"),
+ (
+ "this_quarter_full_period",
+ "2021-08-25T12:34:00Z",
+ "qStart",
+ True,
+ "2021-04-01T00:00:00Z",
+ "2021-06-30T23:59:59.999999Z",
+ ),
+ (
+ "this_year",
+ "2021-08-25T12:34:00Z",
+ "yStart",
+ False,
+ "2020-01-01T00:00:00Z",
+ "2020-08-25T23:59:59.999999Z",
+ ),
+ (
+ "this_year_full_period",
+ "2021-08-25T12:34:00Z",
+ "yStart",
+ True,
+ "2020-01-01T00:00:00Z",
+ "2020-12-31T23:59:59.999999Z",
+ ),
]
)
- def test_previous_period_for_calendar_anchored_range_is_full_prior_unit(
- self, _name: str, now: str, date_from: str, expected_from: str, expected_to: str
+ def test_previous_period_for_calendar_anchored_range(
+ self,
+ _name: str,
+ now: str,
+ date_from: str,
+ full_comparison_period: bool,
+ expected_from: str,
+ expected_to: str,
):
query_date_range = QueryPreviousPeriodDateRange(
team=self.team,
date_range=DateRange(date_from=date_from),
interval=IntervalType.DAY,
now=parser.isoparse(now),
+ full_comparison_period=full_comparison_period,
)
self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_from))
self.assertEqual(query_date_range.date_to(), parser.isoparse(expected_to))
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
index 59f5e26e06b5..f0f71dec2814 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
@@ -1034,6 +1034,34 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
runner = WebOverviewQueryRunner(team=self.team, query=query)
assert runner.query_date_range._interval == expected_interval
+ @parameterized.expand(
+ [
+ ("today_by_hour", "dStart", IntervalType.HOUR),
+ ("month_to_date_by_day", "mStart", IntervalType.DAY),
+ ("last_7_days_by_hour", "-7d", IntervalType.HOUR),
+ ]
+ )
+ @freeze_time("2024-05-16T14:20:00Z")
+ def test_compare_window_is_sized_to_the_elapsed_current_period(
+ self, _name: str, date_from: str, interval: IntervalType
+ ) -> None:
+ runner = WebOverviewQueryRunner(
+ team=self.team,
+ query=WebOverviewQuery(
+ dateRange=DateRange(date_from=date_from),
+ interval=interval,
+ properties=[],
+ compareFilter=CompareFilter(compare=True),
+ ),
+ )
+
+ current = runner.query_date_range
+ previous = runner.query_compare_to_date_range
+ assert previous is not None
+
+ assert previous.date_to() - previous.date_from() == current.date_to() - current.date_from()
+ assert previous.date_to() < current.date_from()
+
@parameterized.expand(
[
# (name, hours_delta, explicit_date_to, expected_is_recent)