: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: convert app metrics window bounds to UTC before querying ClickHouse (#62357)
Harley Alexandered260e66956b
diff --git a/posthog/api/app_metrics2.py b/posthog/api/app_metrics2.pyindex a4bc90b9f959..fc7d81565a47 100644--- a/posthog/api/app_metrics2.py+++ b/posthog/api/app_metrics2.py@@ -1,5 +1,5 @@from dataclasses import dataclass-from datetime import datetime, timedelta+from datetime import UTC, datetime, timedeltafrom typing import Any, Optional, castfrom drf_spectacular.utils import extend_schema@@ -127,8 +127,10 @@ def fetch_app_metrics_trends(clickhouse_kwargs["team_id"] = team_idclickhouse_kwargs["app_source"] = app_sourceclickhouse_kwargs["app_source_id"] = app_source_id- clickhouse_kwargs["after"] = after.strftime("%Y-%m-%dT%H:%M:%S")- clickhouse_kwargs["before"] = before.strftime("%Y-%m-%dT%H:%M:%S")+ # Convert to UTC before formatting — the naive string is read as UTC by toDateTime64, so a+ # team-timezone-aware bound would otherwise shift the window by the team's offset.+ clickhouse_kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ clickhouse_kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")clickhouse_kwargs["instance_id"] = instance_idclickhouse_kwargs["name"] = nameclickhouse_kwargs["kind"] = kind@@ -205,12 +207,14 @@ def fetch_app_metric_totals(name = name or []kind = kind or []+ # Convert to UTC before formatting — the naive string is read as UTC by toDateTime64, so a+ # team-timezone-aware bound would otherwise shift the window by the team's offset.clickhouse_kwargs: dict[str, Any] = {"team_id": team_id,"app_source": app_source,"app_source_id": app_source_id,- "after": after.strftime("%Y-%m-%dT%H:%M:%S") if after else None,- "before": before.strftime("%Y-%m-%dT%H:%M:%S") if before else None,+ "after": after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if after else None,+ "before": before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if before else None,}clickhouse_query = f"""diff --git a/posthog/api/test/test_app_metrics2.py b/posthog/api/test/test_app_metrics2.pynew file mode 100644index 000000000000..68d64a61d9cf--- /dev/null+++ b/posthog/api/test/test_app_metrics2.py@@ -0,0 +1,50 @@+from datetime import UTC, datetime, timedelta+from zoneinfo import ZoneInfo++from posthog.test.base import BaseTest, ClickhouseTestMixin++from parameterized import parameterized++from posthog.api.app_metrics2 import fetch_app_metric_totals+from posthog.test.fixtures import create_app_metric2+++class TestAppMetrics2Timezone(ClickhouseTestMixin, BaseTest):+ def _seed(self, when_utc: datetime):+ create_app_metric2(+ team_id=self.team.pk,+ app_source="hog_function",+ app_source_id="fn-1",+ metric_kind="success",+ metric_name="succeeded",+ timestamp=when_utc,+ )++ @parameterized.expand(+ [+ ("America/Los_Angeles",), # -07:00 (PDT in June)+ ("Asia/Kolkata",), # +05:30 (half-hour offset)+ ("Pacific/Auckland",), # +12:00 (wraps to the previous UTC day)+ ]+ )+ def test_totals_window_bound_is_utc_not_team_local(self, tz_name: str):+ tz = ZoneInfo(tz_name)+ after_local = datetime(2026, 6, 8, 0, 0, 0, tzinfo=tz)+ before_local = datetime(2026, 6, 9, 0, 0, 0, tzinfo=tz)+ bound_utc = after_local.astimezone(UTC)+ self._seed(bound_utc - timedelta(hours=1)) # an hour before the true bound — excluded+ self._seed(bound_utc + timedelta(hours=1)) # an hour after — included++ result = fetch_app_metric_totals(+ team_id=self.team.pk,+ app_source="hog_function",+ app_source_id="fn-1",+ after=after_local,+ before=before_local,+ )++ # Local-midnight `after` must resolve to its true UTC instant. A naive bound (the offset+ # dropped, read as UTC) would shift the window and miscount the row near the boundary —+ # for negative offsets it pulls in the earlier row, for positive ones it drops both.+ # `fetch_app_metrics_trends` shares the identical conversion, so this guards it too.+ assert result.totals == {"success": 1}, tz_name