: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
feat(persons): measure person search latency (#87833)
Thomas Obermüllercbd6a2cc02b4
diff --git a/posthog/api/person.py b/posthog/api/person.pyindex dcdf4a3638f3..33be1d236193 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -5,6 +5,8 @@ import dataclassesfrom datetime import UTC, datetimefrom typing import Any, Optional, Union, cast # noqa: UP035+from django.conf import settings+import structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import (@@ -67,6 +69,8 @@ from posthog.queries.actor_base_query import get_serialized_peoplefrom posthog.queries.properties_timeline import PropertiesTimelinefrom posthog.rate_limit import ClickHouseBurstRateThrottle, PersonalApiKeyRateThrottle, UserOrEmailRateThrottlefrom posthog.renderers import SafeJSONRenderer+from posthog.slo.context import JsonValue, SloSpec, slo_operation+from posthog.slo.types import SloArea, SloOperationfrom posthog.tasks.split_person import split_personfrom posthog.utils import (format_query_params_absolute_url,@@ -595,38 +599,65 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):limit=filter.limit,offset=filter.offset,)- # Use .calculate() (not .run()) — it applies the limit/offset paginator but skips the- # insight-caching wrapper. With an id-only select there's no actor-column hydration, so- # we still hydrate the person objects ourselves via get_serialized_people.- actors_runner = ActorsQueryRunner(team=team, query=actors_query)- actor_ids = [row[0] for row in actors_runner.calculate().results]- with personhog_caller_tag("persons/list"):- serialized_actors = get_serialized_people(team, actor_ids)-- restricted_person_properties = self.get_serializer_context().get("restricted_person_properties")- if restricted_person_properties:- for person_dict in serialized_actors:- properties = person_dict.get("properties")- if isinstance(properties, dict):- person_dict["properties"] = {- k: v for k, v in properties.items() if k not in restricted_person_properties- }+ include_total = "include_total" in request.GET+ # This endpoint bypasses `QueryRunner.run()`, so nothing else measures how long it takes.+ # The search path is the slow one, so the shape of the request is recorded alongside the+ # duration. The search term itself is never recorded - it is user data.+ slo_properties: dict[str, JsonValue] = {+ "query_type": "ActorsQuery",+ "has_search": bool(filter.search),+ "has_properties": bool(person_properties),+ "has_distinct_id": bool(filter.distinct_id),+ "include_total": include_total,+ "is_csv": is_csv_request,+ "limit": filter.limit,+ "offset": filter.offset,+ }+ with slo_operation(+ spec=SloSpec(+ # `User.distinct_id` is nullable, so fall back to the team like the query service does.+ distinct_id=request.user.distinct_id or str(team.uuid),+ area=SloArea.ANALYTIC_PLATFORM,+ operation=SloOperation.PERSONS_LIST,+ team_id=team.pk,+ sample_rate=settings.PERSONS_LIST_SLO_SAMPLE_RATE,+ ),+ properties=slo_properties,+ ) as slo:+ # Use .calculate() (not .run()) — it applies the limit/offset paginator but skips the+ # insight-caching wrapper. With an id-only select there's no actor-column hydration, so+ # we still hydrate the person objects ourselves via get_serialized_people.+ actors_runner = ActorsQueryRunner(team=team, query=actors_query)+ actor_ids = [row[0] for row in actors_runner.calculate().results]+ with personhog_caller_tag("persons/list"):+ serialized_actors = get_serialized_people(team, actor_ids)++ restricted_person_properties = self.get_serializer_context().get("restricted_person_properties")+ if restricted_person_properties:+ for person_dict in serialized_actors:+ properties = person_dict.get("properties")+ if isinstance(properties, dict):+ person_dict["properties"] = {+ k: v for k, v in properties.items() if k not in restricted_person_properties+ }++ _should_paginate = len(actor_ids) >= filter.limit++ # If the undocumented include_total param is set to true, we'll return the total count of people+ # This is extra time and DB load, so we only do this when necessary, which is in PostHog 3000 navigation+ # TODO: Use a more scalable solution before PostHog 3000 navigation is released, and remove this param+ total_count: Optional[int] = None+ if include_total:+ count_inner = actors_runner.to_query()+ count_inner.limit = None+ count_inner.offset = None+ count_query = ast.SelectQuery(+ select=[ast.Call(name="count", args=[])],+ select_from=ast.JoinExpr(table=count_inner),+ )+ total_count = execute_hogql_query(count_query, team=team).results[0][0]- _should_paginate = len(actor_ids) >= filter.limit-- # If the undocumented include_total param is set to true, we'll return the total count of people- # This is extra time and DB load, so we only do this when necessary, which is in PostHog 3000 navigation- # TODO: Use a more scalable solution before PostHog 3000 navigation is released, and remove this param- total_count: Optional[int] = None- if "include_total" in request.GET:- count_inner = actors_runner.to_query()- count_inner.limit = None- count_inner.offset = None- count_query = ast.SelectQuery(- select=[ast.Call(name="count", args=[])],- select_from=ast.JoinExpr(table=count_inner),- )- total_count = execute_hogql_query(count_query, team=team).results[0][0]+ slo.tag(result_count=len(actor_ids))next_url = format_query_params_absolute_url(request, filter.offset + filter.limit) if _should_paginate else Noneprevious_url = (diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex b1b694b3fae6..bae43b977447 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -85,6 +85,32 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(len(response.json()["results"]), 1)+ @parameterized.expand([("?search=another@gm", True), ("", False)])+ def test_person_list_emits_slo_event(self, query: str, expected_has_search: bool) -> None:+ _create_person(+ team=self.team,+ distinct_ids=["distinct_id"],+ properties={"email": "[email protected]"},+ )+ flush_persons_and_events()++ with mock.patch("posthog.slo.events.posthoganalytics.capture") as capture:+ response = self.client.get(f"/api/person/{query}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ completed = [+ call.kwargs["properties"]+ for call in capture.call_args_list+ if call.kwargs["event"] == "slo_operation_completed"+ and call.kwargs["properties"]["operation"] == "persons_list"+ ]+ self.assertEqual(len(completed), 1)+ self.assertEqual(completed[0]["has_search"], expected_has_search)+ self.assertEqual(completed[0]["actor_type"], "person")+ self.assertEqual(completed[0]["outcome"], "success")+ self.assertEqual(completed[0]["result_count"], 1)+ self.assertGreater(completed[0]["duration_ms"], 0)+@also_test_with_materialized_columns(event_properties=["email"], person_properties=["email"])@snapshot_clickhouse_queriesdef test_search_person_id(self) -> None:diff --git a/posthog/hogql_queries/actors_query_runner.py b/posthog/hogql_queries/actors_query_runner.pyindex 16fa1ccdcf7a..cb3c6032d5a0 100644--- a/posthog/hogql_queries/actors_query_runner.py+++ b/posthog/hogql_queries/actors_query_runner.py@@ -33,6 +33,7 @@ from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode, QueryRunner, get_query_runnerfrom posthog.hogql_queries.utils.person_display_name import person_display_name_property_exprsfrom posthog.models import User+from posthog.slo.context import tag_current_sloclass ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):@@ -264,6 +265,10 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):# `hogql_cohort_query._actors_query_from_source`) that invoke `to_query()` with# platform-constant select lists are not mis-attributed.tag_contains_user_hogql()+ # Search is the expensive arm of an actors query, so the surrounding SLO event needs to+ # separate it from a plain listing. Works for both entry points: `run()` opens a+ # query-service SLO, `/api/persons/` opens a persons-list one.+ tag_current_slo(has_search=bool(self.query.search), actor_type=self.strategy.field)try:self.calculating = Truereturn self._calculate_internal()diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 4414d9daa5f0..04035874cd96 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1149,6 +1149,12 @@ API_ENVIRONMENTS_SUNSET_DATE = get_from_env("API_ENVIRONMENTS_SUNSET_DATE", "202# Defaults to 1.0 under TEST so assertions on emitted SLO events are deterministic.QUERY_SERVICE_SLO_SAMPLE_RATE = get_from_env("QUERY_SERVICE_SLO_SAMPLE_RATE", 1.0 if TEST else 0.01, type_cast=float)+# Persons list SLO sampling rate. That endpoint runs its ActorsQuery through `calculate()`,+# not `run()`, so it emits no query-service SLO events at all. It is lower volume than the+# query service and its slow tail is the point of the measurement, so it samples ten times+# higher. Same weighting rule: divide counts by `properties.sample_rate`.+PERSONS_LIST_SLO_SAMPLE_RATE = get_from_env("PERSONS_LIST_SLO_SAMPLE_RATE", 1.0 if TEST else 0.1, type_cast=float)+##### Livestreamdiff --git a/posthog/slo/types.py b/posthog/slo/types.pyindex b21750dc6aad..e91bffab4f9b 100644--- a/posthog/slo/types.py+++ b/posthog/slo/types.py@@ -16,6 +16,7 @@ class SloOperation(StrEnum):ALERT_CHECK = "alert_check"ALERT_DELIVERY = "alert_delivery"QUERY_SERVICE = "query_service"+ PERSONS_LIST = "persons_list"DASHBOARD_WIDGET_DELIVERY = "dashboard_widget_delivery"PULSE_BRIEF_GENERATION = "pulse-brief-generation"SYNC_EVENTS_RETENTION = "sync_events_retention"