: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(metrics): align the chart window to the bucket grid (#89908)
Frank Hamande4a701ce0c27
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex 17e60eeba3d9..ea81e0b3b2d6 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -18,6 +18,7 @@ import mathimport datetime as dtfrom collections.abc import Sequencefrom typing import Any, Literal+from zoneinfo import ZoneInfofrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings@@ -262,13 +263,7 @@ def _interval_step(name: str) -> dt.timedelta:raise ValueError(f"Unknown interval: {name!r}")-# The grids `toStartOfInterval` produces: intervals count from the epoch,-# except weeks, which count from a Monday.-_EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)-_WEEK_EPOCH = dt.datetime(1970, 1, 5, tzinfo=dt.UTC)---def _align_to_interval(timestamp: dt.datetime, interval: str) -> dt.datetime:+def _align_to_interval(timestamp: dt.datetime, interval: str, *, tzinfo: ZoneInfo) -> dt.datetime:"""Floor `timestamp` onto the bucket grid `toStartOfInterval` uses.The bucket labels come from `toStartOfInterval(sample_timestamp)`, so a@@ -278,6 +273,15 @@ def _align_to_interval(timestamp: dt.datetime, interval: str) -> dt.datetime:its full interval. Relative ranges like "-1h" resolve to now-minus-offsetwith second precision, which makes the unaligned case the normal one.+ The grid lives in `tzinfo`, the project's timezone, not in UTC. HogQL+ rewrites a `DateTime` column read into `toTimeZone(<column>, <project+ timezone>)` (`PropertySwapper.visit_field`), so `toStartOfInterval` sees a+ local-time value and counts every step from local midnight. Flooring in UTC+ instead lands on the same instant for the sub-hour steps, but drifts for+ `hour_6`, `day` and `week`, and for `hour` in a zone whose offset is not a+ whole number of hours (Asia/Kolkata is +05:30, so its hour boundaries sit+ at :30 past each UTC hour).+Not `posthog.interval_specs.align`: that grid honors the team's`week_start_day` and lacks the sub-hour steps, where `toStartOfInterval`always counts weeks from Monday — the two would disagree exactly where@@ -285,9 +289,20 @@ def _align_to_interval(timestamp: dt.datetime, interval: str) -> dt.datetime:"""if timestamp.tzinfo is None:timestamp = timestamp.replace(tzinfo=dt.UTC)- epoch = _WEEK_EPOCH if interval == "week" else _EPOCH+ local = timestamp.astimezone(tzinfo)+ midnight = local.replace(hour=0, minute=0, second=0, microsecond=0)+ if interval == "week":+ # ClickHouse's week interval starts on Monday, unlike its own+ # `toStartOfWeek`, which defaults to Sunday.+ return (midnight - dt.timedelta(days=midnight.weekday())).astimezone(dt.UTC)+ if interval == "day":+ return midnight.astimezone(dt.UTC)+ # ClickHouse counts elapsed seconds from the midnight instant, so this adds+ # a real duration rather than doing wall-clock arithmetic. A day shortened+ # or lengthened by a DST transition then keeps both grids on the same+ # boundaries.step = _interval_step(interval)- return epoch + ((timestamp - epoch) // step) * step+ return midnight.astimezone(dt.UTC) + (local.astimezone(dt.UTC) - midnight.astimezone(dt.UTC)) // step * step# Prometheus's default lookback delta. One interval step on its own is not@@ -388,7 +403,7 @@ class MetricQueryRunner:if interval is not None and interval not in {name for name, _, _ in _INTERVAL_LADDER}:raise ValueError(f"Unknown interval: {interval!r}")if interval is not None:- step = next(step for name, step, _ in _INTERVAL_LADDER if name == interval)+ step = _interval_step(interval)if (date_to - date_from) / step > _ROW_LIMIT:raise ValueError(f"interval {interval!r} produces more than {_ROW_LIMIT} buckets over this range; "@@ -404,7 +419,7 @@ class MetricQueryRunner:self.interval = interval or _pick_interval(date_from, date_to)# Validation above bounds the requested range; the scan then starts at# the bucket boundary so the first bucket covers its whole interval.- self.date_from = _align_to_interval(date_from, self.interval)+ self.date_from = _align_to_interval(date_from, self.interval, tzinfo=team.timezone_info)self.date_to = date_toself.filters = tuple(filters)self.group_by = tuple(group_by)diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex 1d41eaeb76a3..5b7c2bf2d207 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -1,5 +1,6 @@import datetime as dtfrom typing import Any+from zoneinfo import ZoneInfoimport pytestfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin@@ -49,27 +50,36 @@ class TestPickInterval:class TestAlignToInterval(ClickhouseTestMixin, APIBaseTest):- @parameterized.expand([(name,) for name, _, _ in _INTERVAL_LADDER])- def test_matches_clickhouse_bucket_boundaries(self, interval: str) -> None:+ @parameterized.expand(+ [+ (project_timezone, interval)+ for project_timezone in ("UTC", "Asia/Kolkata")+ for interval, _, _ in _INTERVAL_LADDER+ ]+ )+ def test_matches_clickhouse_bucket_boundaries(self, project_timezone: str, interval: str) -> None:# The runner snaps date_from onto the bucket grid before querying; if# this floor ever disagrees with toStartOfInterval, first buckets go- # partial again.+ # partial again. The queries read `timestamp` through the project's+ # timezone, because HogQL wraps a DateTime column in toTimeZone, so the+ # grid that has to match is the project's. Asia/Kolkata is +05:30, which+ # puts every boundary from `hour` up where a UTC floor never lands.awkward = dt.datetime(2026, 3, 11, 17, 47, 33, 123456, tzinfo=dt.UTC)- aligned = _align_to_interval(awkward, interval)+ aligned = _align_to_interval(awkward, interval, tzinfo=ZoneInfo(project_timezone))interval_call = next(expr for name, _, expr in _INTERVAL_LADDER if name == interval)interval_arg = interval_call.args[0]assert isinstance(interval_arg, ast.Constant)interval_sql = f"{interval_call.name}({interval_arg.value})"- ((clickhouse_aligned,),) = sync_execute(- f"SELECT toStartOfInterval(toDateTime64(%(ts)s, 6, 'UTC'), {interval_sql})",- {"ts": awkward.strftime("%Y-%m-%d %H:%M:%S.%f")},+ ((bucket_label,),) = sync_execute(+ f"SELECT toString(toStartOfInterval(toTimeZone(toDateTime64(%(ts)s, 6, 'UTC'), %(tz)s), {interval_sql}))",+ {"ts": awkward.strftime("%Y-%m-%d %H:%M:%S.%f"), "tz": project_timezone},)- if not isinstance(clickhouse_aligned, dt.datetime):- # Week intervals come back as a bare Date.- clickhouse_aligned = dt.datetime.combine(clickhouse_aligned, dt.time(), tzinfo=dt.UTC)- elif clickhouse_aligned.tzinfo is None:- clickhouse_aligned = clickhouse_aligned.replace(tzinfo=dt.UTC)+ # Rendering the bucket as a string keeps the comparison free of the+ # driver's datetime conversion, and covers the `week` interval, which+ # ClickHouse truncates to a bare Date. Either shape names a wall-clock+ # reading in the project's timezone.+ clickhouse_aligned = dt.datetime.fromisoformat(bucket_label).replace(tzinfo=ZoneInfo(project_timezone))self.assertEqual(aligned, clickhouse_aligned)self.assertLessEqual(aligned, awkward)@@ -269,6 +279,34 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)self.assertEqual(earliest, anchor)+ def test_first_bucket_is_whole_on_a_project_away_from_utc(self):+ # A project at +05:30 has its hourly buckets at :30 past each UTC hour,+ # so a date_from floored in UTC can start the scan after the bucket+ # ClickHouse labels the rows with. The 07:45 sample belongs to the+ # 07:30 bucket, and a UTC floor to 08:00 would drop it.+ self.team.timezone = "Asia/Kolkata"+ self.team.save()+ bucket_start = dt.datetime(2026, 3, 17, 7, 30, tzinfo=dt.UTC)+ seed_metric(+ team_id=self.team.id,+ metric_name="m1",+ points=[(bucket_start + dt.timedelta(minutes=15), 3.0)],+ )++ rows = MetricQueryRunner(+ team=self.team,+ metric_name="m1",+ aggregation="sum",+ date_from=bucket_start + dt.timedelta(minutes=45),+ date_to=bucket_start + dt.timedelta(hours=1),+ interval="hour",+ ).run()++ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]["value"], 3.0)+ earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)+ self.assertEqual(earliest, bucket_start)+def test_synthetic_original_timestamp_does_not_split_a_series(self):anchor = timezone.now().replace(second=0, microsecond=0)bucket = anchor - dt.timedelta(minutes=5)