: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
perf(metrics): read the hourly projection in the overview services query (#110789)
Frank Hamand1fe1a85a9763
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.pyindex 1baa49239c68..c5ce49c77d89 100644--- a/posthog/hogql/constants.py+++ b/posthog/hogql/constants.py@@ -182,6 +182,7 @@ class HogQLQuerySettings(BaseModel):join_algorithm: Optional[str] = Nonegrace_hash_join_initial_buckets: Optional[int] = Noneforce_data_skipping_indices: Optional[list[str]] = None+ force_optimize_projection: Optional[bool] = Noneload_balancing: Optional[str] = Noneformat_csv_allow_double_quotes: Optional[bool] = Noneoptimize_skip_unused_shards: Optional[bool] = Nonediff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.pyindex 2ec8d870e7db..8062d9772a78 100644--- a/posthog/hogql/database/schema/metrics.py+++ b/posthog/hogql/database/schema/metrics.py@@ -274,6 +274,9 @@ class MetricSeriesTable(Table):"last_seen": DateTimeDatabaseField(name="timestamp", nullable=False, description="Most recent sample timestamp seen for this series."),+ "time_bucket": DateTimeDatabaseField(+ name="time_bucket", nullable=False, description="Start of the UTC hour that contains `last_seen`."+ ),"original_expiry_timestamp": DateTimeDatabaseField(name="original_expiry_timestamp", nullable=False, description="When the series leaves retention."),diff --git a/products/metrics/backend/metrics_overview_query_runner.py b/products/metrics/backend/metrics_overview_query_runner.pyindex 90289bb0be84..c64f82909769 100644--- a/products/metrics/backend/metrics_overview_query_runner.py+++ b/products/metrics/backend/metrics_overview_query_runner.py@@ -1,4 +1,4 @@-"""No FINAL: `uniqExact` and `max(last_seen)` give the same result on unmerged duplicate rows."""+"""No FINAL: the distinct counts and `max(last_seen)` give the same result on unmerged duplicate rows."""import datetime as dtimport contextvars@@ -7,7 +7,7 @@ from concurrent.futures import ThreadPoolExecutorfrom opentelemetry import tracefrom opentelemetry.trace import Span-from posthog.schema import HogQLQueryResponse+from posthog.schema import HogQLQueryModifiers, HogQLQueryResponsefrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings@@ -112,18 +112,20 @@ class MetricsOverviewQueryRunner:def _run_services(self) -> _ServicesRollup:with tracer.start_as_current_span("metrics.overview.services") as span:span.set_attribute("team_id", self.team.pk)- # Each series has one service, so the sum of the service counts is exact.+ # The services_by_hour projection answers this query only while it filters on time_bucket, uses uniq,+ # and aggregates the bare last_seen column. The time zone conversion stays outside max() for that reason.+ # Each series has one service, so the sum of the service counts counts each series once.query = parse_select("""SELECTservice_name,uniqExact(metric_name) AS metric_names,- uniqExact(series_fingerprint) AS series,- max(last_seen) AS last_seen_at,- sum(uniqExact(series_fingerprint)) OVER () AS total_series,- max(max(last_seen)) OVER () AS total_last_seen_at+ uniq(series_fingerprint) AS series,+ toTimeZone(max(last_seen), 'UTC') AS last_seen_at,+ sum(uniq(series_fingerprint)) OVER () AS total_series,+ toTimeZone(max(max(last_seen)) OVER (), 'UTC') AS total_last_seen_atFROM posthog.metric_series- WHERE last_seen > now() - {lookback}+ WHERE time_bucket >= toStartOfHour(toTimeZone(now() - {lookback}, 'UTC'))GROUP BY service_nameORDER BY series DESC, service_name ASCLIMIT {limit}@@ -138,6 +140,7 @@ class MetricsOverviewQueryRunner:team=self.team,workload=Workload.LOGS,settings=_QUERY_SETTINGS,+ modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),)_set_query_timing_attributes(span, response)span.set_attribute("services.count", len(response.results))diff --git a/products/metrics/backend/tests/test_metrics_overview_query_runner.py b/products/metrics/backend/tests/test_metrics_overview_query_runner.pyindex f3d59195110c..7bfdfb8ac7da 100644--- a/products/metrics/backend/tests/test_metrics_overview_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_overview_query_runner.py@@ -1,4 +1,5 @@import datetime as dt+from typing import Anyfrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import patch@@ -8,6 +9,10 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.schema import HogQLQueryResponse++from posthog.hogql.query import execute_hogql_query+from products.metrics.backend import metrics_overview_query_runnerfrom products.metrics.backend.metrics_overview_query_runner import MetricsOverviewQueryRunnerfrom products.metrics.backend.tests._seeder import seed_metric, seed_metric_event, truncate_metrics_tables@@ -65,6 +70,20 @@ class TestMetricsOverviewQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(api_row.series, 3)self.assertEqual(dt.datetime.fromisoformat(api_row.last_seen), anchor)+ def test_services_query_reads_the_hourly_projection(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ seed_metric(team_id=self.team.id, metric_name="http.duration", points=[(anchor, 1.0)], service_name="api")++ def force_projection(**kwargs: Any) -> HogQLQueryResponse:+ if kwargs["query_type"] == "MetricsOverviewServicesQuery":+ kwargs["settings"] = kwargs["settings"].model_copy(update={"force_optimize_projection": True})+ return execute_hogql_query(**kwargs)++ with patch.object(metrics_overview_query_runner, "execute_hogql_query", side_effect=force_projection):+ overview = MetricsOverviewQueryRunner(team=self.team).run()++ self.assertEqual([(s.service_name, s.series) for s in overview.services], [("api", 1)])+def test_quiet_project_keeps_overall_last_seen_but_lists_no_services(self):stale = timezone.now().replace(microsecond=0) - dt.timedelta(days=3)seed_metric(team_id=self.team.id, metric_name="http.duration", points=[(stale, 1.0)], service_name="api")