: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(cdp): count the first interval of app metrics trends (#123308)
Harley Alexander466531d07406
diff --git a/posthog/api/app_metrics2.py b/posthog/api/app_metrics2.pyindex e9723a7c9d8d..eed004bb2fe5 100644--- a/posthog/api/app_metrics2.py+++ b/posthog/api/app_metrics2.py@@ -106,9 +106,11 @@ def fetch_app_metrics_trends(clickhouse_kwargs: dict[str, Any] = {}+ # The bucket alias must not be `timestamp`. ClickHouse resolves SELECT aliases inside WHERE, so the+ # range filter would compare the bucket start to `after` and drop the first, partial bucket.clickhouse_query = f"""SELECT- toStartOfInterval(timestamp, INTERVAL 1 {interval}) as timestamp,+ toStartOfInterval(timestamp, INTERVAL 1 {interval}) as bucket,metric_{breakdown_by} as breakdown,sum(count) as countFROM app_metrics2@@ -120,8 +122,8 @@ def fetch_app_metrics_trends({"AND instance_id = %(instance_id)s" if instance_id else ""}{"AND metric_name IN %(name)s" if name else ""}{"AND metric_kind IN %(kind)s" if kind else ""}- GROUP BY timestamp, breakdown- ORDER BY timestamp ASC+ GROUP BY bucket, breakdown+ ORDER BY bucket ASC"""clickhouse_kwargs["team_id"] = team_id@@ -129,8 +131,9 @@ def fetch_app_metrics_trends(clickhouse_kwargs["app_source_id"] = app_source_id# 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")+ # Keep the microseconds: a `before` of "now" truncated to the second excludes rows written earlier in that second.+ clickhouse_kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")+ clickhouse_kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")clickhouse_kwargs["instance_id"] = instance_idclickhouse_kwargs["name"] = nameclickhouse_kwargs["kind"] = kind@@ -210,12 +213,13 @@ def fetch_app_metric_totals(# 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.+ # Keep the microseconds: a `before` of "now" truncated to the second excludes rows written earlier in that second.clickhouse_kwargs: dict[str, Any] = {"team_id": team_id,"app_source": app_source,"app_source_id": app_source_id,- "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,+ "after": after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f") if after else None,+ "before": before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f") if before else None,"instance_id": instance_id,"name": name,"kind": kind,diff --git a/posthog/api/test/test_app_metrics2.py b/posthog/api/test/test_app_metrics2.pyindex 885c8258d7ca..786bb39b4947 100644--- a/posthog/api/test/test_app_metrics2.py+++ b/posthog/api/test/test_app_metrics2.py@@ -6,7 +6,7 @@ from posthog.test.base import BaseTest, ClickhouseTestMixinfrom parameterized import parameterized-from posthog.api.app_metrics2 import fetch_app_metric_totals+from posthog.api.app_metrics2 import fetch_app_metric_totals, fetch_app_metrics_trendsfrom posthog.test.fixtures import create_app_metric2@@ -65,3 +65,37 @@ class TestAppMetrics2Timezone(ClickhouseTestMixin, BaseTest):# 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++ @parameterized.expand(+ [+ ("day", datetime(2026, 6, 8, 12, 0, tzinfo=UTC), datetime(2026, 6, 8, 13, 0, 0, 500000, tzinfo=UTC), [2]),+ (+ "hour",+ datetime(2026, 6, 8, 9, 30, tzinfo=UTC),+ datetime(2026, 6, 8, 11, 30, 0, 500000, tzinfo=UTC),+ [1, 0, 1],+ ),+ ]+ )+ def test_trends_and_totals_count_rows_at_the_range_edges(+ self, interval: str, after: datetime, before: datetime, expected: list[int]+ ) -> None:+ # The rows sit in different clock hours because the table can merge rows of one hour into one row.+ self._seed(after - timedelta(hours=1)) # before `after`: excluded+ self._seed(after + timedelta(minutes=15)) # in range, in a bucket that starts before `after`: included+ self._seed(before - timedelta(microseconds=250000)) # in the same second as `before`, but earlier: included++ trends = fetch_app_metrics_trends(+ team_id=self.team.pk,+ app_source="hog_function",+ app_source_id="fn-1",+ after=after,+ before=before,+ interval=interval,+ )+ totals = fetch_app_metric_totals(+ team_id=self.team.pk, app_source="hog_function", app_source_id="fn-1", after=after, before=before+ )++ assert [(series.name, series.values) for series in trends.series] == [("success", expected)]+ assert totals.totals == {"success": sum(expected)}