: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(search): stop the person search query when the palette closes (#87751)
Thomas Obermüllerbb608fe5d501
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 51b070320257..b693ca787ce6 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1745,6 +1745,10 @@ export class ApiRequest {return this.query(teamId).addPathComponent(queryId).addPathComponent('log')}+ public queryCancel(clientQueryId: string, teamId?: TeamType['id']): ApiRequest {+ return this.query(teamId).addPathComponent(clientQueryId)+ }+// Endpointspublic endpoint(teamId?: TeamType['id']): ApiRequest {return this.environmentsDetail(teamId).addPathComponent('endpoints')@@ -3728,8 +3732,11 @@ const api = {},})},- async list(params: PersonListParams = {}): Promise<CountedPaginatedResponse<PersonType>> {- return await new ApiRequest().persons().withQueryString(toParams(params)).get()+ async list(+ params: PersonListParams = {},+ options?: ApiMethodOptions+ ): Promise<CountedPaginatedResponse<PersonType>> {+ return await new ApiRequest().persons().withQueryString(toParams(params)).get(options)},determineListUrl(params: PersonListParams = {}): string {return new ApiRequest().persons().withQueryString(toParams(params)).assembleFullUrl()@@ -3804,8 +3811,8 @@ const api = {},search: {- async list(params: SearchListParams): Promise<SearchResponse> {- return await new ApiRequest().search().withQueryString(toParams(params, true)).get()+ async list(params: SearchListParams, options?: ApiMethodOptions): Promise<SearchResponse> {+ return await new ApiRequest().search().withQueryString(toParams(params, true)).get(options)},},@@ -6812,6 +6819,14 @@ const api = {return new ApiRequest().query(undefined, queryKind).assembleFullUrl(true)},+ /**+ * Stop the ClickHouse query that a request named with its `client_query_id`. Dropping the HTTP+ * request does not reach ClickHouse, which keeps working on the query until it finishes.+ */+ async cancelQuery(clientQueryId: string): Promise<void> {+ await new ApiRequest().queryCancel(clientQueryId).delete()+ },+async query<T extends Record<string, any> = QuerySchema>(query: T,queryOptions?: {diff --git a/frontend/src/lib/components/Search/searchLogic.test.ts b/frontend/src/lib/components/Search/searchLogic.test.tsnew file mode 100644index 000000000000..ed2eca64f2a8--- /dev/null+++ b/frontend/src/lib/components/Search/searchLogic.test.ts@@ -0,0 +1,97 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { searchLogic } from './searchLogic'++describe('searchLogic', () => {+ let logic: ReturnType<typeof searchLogic.build>+ let personSearchCalls: { clientQueryId?: string; signal?: AbortSignal }[]+ let cancelledQueryIds: string[]+ let personListMock: jest.SpyInstance++ const neverResolvingPersonSearch = (): void => {+ personListMock.mockImplementation((params, options) => {+ personSearchCalls.push({ clientQueryId: params?.client_query_id, signal: options?.signal })+ return new Promise((_resolve, reject) => {+ options?.signal?.addEventListener('abort', () => {+ reject(Object.assign(new Error('The user aborted a request.'), { name: 'AbortError' }))+ })+ })+ })+ }++ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/search/': { results: [], counts: {} },+ '/api/projects/:team_id/file_system/': { results: [], count: 0 },+ },+ })+ initKeaTests()++ personSearchCalls = []+ cancelledQueryIds = []+ personListMock = jest.spyOn(api.persons, 'list')+ jest.spyOn(api, 'cancelQuery').mockImplementation(async (clientQueryId: string) => {+ cancelledQueryIds.push(clientQueryId)+ })++ logic = searchLogic({ logicKey: 'test' })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ it('aborts and cancels the in-flight person search when the term is cleared', async () => {+ neverResolvingPersonSearch()++ await expectLogic(logic, () => logic.actions.setSearch('alice')).toDispatchActions(['loadPersonSearchResults'])+ expect(personSearchCalls).toHaveLength(1)+ const { clientQueryId, signal } = personSearchCalls[0]+ expect(clientQueryId).toBeTruthy()+ expect(signal?.aborted).toBe(false)++ await expectLogic(logic, () => logic.actions.setSearch('')).toDispatchActions([+ 'loadPersonSearchResultsFailure',+ ])+ expect(signal?.aborted).toBe(true)+ expect(cancelledQueryIds).toEqual([clientQueryId])+ expect(logic.values.personSearchResultsLoading).toBe(false)+ })++ it('cancels the previous person search on a new term without clearing the loading state', async () => {+ neverResolvingPersonSearch()++ await expectLogic(logic, () => logic.actions.setSearch('alice')).toDispatchActions(['loadPersonSearchResults'])+ await expectLogic(logic, () => logic.actions.setSearch('alice b')).toDispatchActions([+ 'loadPersonSearchResults',+ ])++ expect(personSearchCalls).toHaveLength(2)+ expect(personSearchCalls[0].signal?.aborted).toBe(true)+ expect(personSearchCalls[1].signal?.aborted).toBe(false)+ expect(cancelledQueryIds).toEqual([personSearchCalls[0].clientQueryId])++ // The superseded run must not settle the loader the newer run now owns.+ await expectLogic(logic).toNotHaveDispatchedActions(['loadPersonSearchResultsFailure'])+ expect(logic.values.personSearchResultsLoading).toBe(true)+ })++ it('does not cancel a person search that already returned', async () => {+ personListMock.mockResolvedValue({ results: [] })++ await expectLogic(logic, () => logic.actions.setSearch('alice')).toDispatchActions([+ 'loadPersonSearchResultsSuccess',+ ])+ await expectLogic(logic, () => logic.actions.setSearch('')).toFinishAllListeners()++ expect(cancelledQueryIds).toEqual([])+ })+})diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex 3f07d40bf727..8328187cf4c9 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -1,15 +1,17 @@import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import type { BreakPointFunction } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'import { IconBell, IconBuilding, IconClock, IconDownload, IconLeave, IconNotification } from '@posthog/icons'-import api from 'lib/api'+import api, { isAbortError } from 'lib/api'import { commandLogic } from 'lib/components/Command/commandLogic'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'lib/logic/preflightLogic'import { getEntryAccessDisabledReason, getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'+import { uuid } from 'lib/utils/dom'import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { newInternalTab } from 'lib/utils/newInternalTab'@@ -148,6 +150,19 @@ const SEARCH_LIMIT = 5/** Safely extract a string — returns undefined for objects/arrays to avoid rendering [object Object]. */const safeString = (val: unknown): string | undefined => (typeof val === 'string' ? val : undefined)+/**+ * Re-throw a search error, first handing a run we aborted over to whatever superseded it. A+ * superseded run must not settle its loader: kea-loaders keeps one loading flag per loader, so+ * clearing it here would drop the skeleton the newer run just raised. An abort with nothing behind+ * it falls through to the failure path, which stays silent: initKea's onFailure skips AbortError.+ */+const rethrowSearchError = (error: unknown, breakpoint: BreakPointFunction): never => {+ if (isAbortError(error)) {+ breakpoint()+ }+ throw error+}+/*** Lean projection of SETTINGS_MAP for search. The full map statically imports every* settings component (the whole configuration UI graph), so it is loaded dynamically@@ -510,7 +525,7 @@ export const searchLogic = kea<searchLogicType>([setSearch: (search: string) => ({ search }),setSettingsSections: (sections: SettingsSectionSummary[]) => ({ sections }),}),- loaders(({ values }) => ({+ loaders(({ values, cache }) => ({searchedRecents: [null as FileSystemEntry[] | null,{@@ -519,14 +534,19 @@ export const searchLogic = kea<searchLogicType>([if (!searchTerm) {return null}- const response = await api.fileSystem.list({- search: searchTerm,- limit: RECENTS_LIMIT + 1,- orderBy: '-last_viewed_at',- notType: 'folder',- })- breakpoint()- return response.results.slice(0, RECENTS_LIMIT)+ try {+ const response = await api.fileSystem.list({+ search: searchTerm,+ limit: RECENTS_LIMIT + 1,+ orderBy: '-last_viewed_at',+ notType: 'folder',+ signal: cache.searchAbortController?.signal,+ })+ breakpoint()+ return response.results.slice(0, RECENTS_LIMIT)+ } catch (error) {+ return rethrowSearchError(error, breakpoint)+ }},},],@@ -540,13 +560,20 @@ export const searchLogic = kea<searchLogicType>([return null}- const response = await api.search.list({- q: trimmed,- include_counts: false,- })- breakpoint()+ try {+ const response = await api.search.list(+ {+ q: trimmed,+ include_counts: false,+ },+ { signal: cache.searchAbortController?.signal }+ )+ breakpoint()- return response+ return response+ } catch (error) {+ return rethrowSearchError(error, breakpoint)+ }},},],@@ -567,14 +594,19 @@ export const searchLogic = kea<searchLogicType>([const results = await Promise.allSettled(groupTypesList.map((groupType) =>- api.groups.listClickhouse({- group_type_index: groupType.group_type_index,- search: trimmed,- limit: SEARCH_LIMIT,- })+ api.groups.listClickhouse(+ {+ group_type_index: groupType.group_type_index,+ search: trimmed,+ limit: SEARCH_LIMIT,+ },+ { signal: cache.searchAbortController?.signal }+ )))+ // allSettled never rejects, so an abort lands here instead of in a catch: the+ // breakpoint hands a superseded run over, and the filter below drops the rest.breakpoint()return Object.fromEntries(@@ -599,10 +631,23 @@ export const searchLogic = kea<searchLogicType>([return []}- const response = await api.persons.list({ search: trimmed, limit: SEARCH_LIMIT })- breakpoint()-- return response.results+ const clientQueryId: string | null = cache.personSearchQueryId+ try {+ const response = await api.persons.list(+ { search: trimmed, limit: SEARCH_LIMIT, client_query_id: clientQueryId ?? undefined },+ { signal: cache.searchAbortController?.signal }+ )+ breakpoint()++ return response.results+ } catch (error) {+ return rethrowSearchError(error, breakpoint)+ } finally {+ // The request is over, so there is no ClickHouse query left to cancel.+ if (cache.personSearchQueryId === clientQueryId) {+ cache.personSearchQueryId = null+ }+ }},},],@@ -616,13 +661,21 @@ export const searchLogic = kea<searchLogicType>([return []}- const response = await accountsList(String(values.currentTeamId), {- search: trimmed,- limit: SEARCH_LIMIT,- })- breakpoint()+ try {+ const response = await accountsList(+ String(values.currentTeamId),+ {+ search: trimmed,+ limit: SEARCH_LIMIT,+ },+ { signal: cache.searchAbortController?.signal }+ )+ breakpoint()- return response.results+ return response.results+ } catch (error) {+ return rethrowSearchError(error, breakpoint)+ }},},],@@ -636,14 +689,19 @@ export const searchLogic = kea<searchLogicType>([return []}- const response = await api.fileSystem.list({- search: trimmed,- type: 'session_recording_playlist',- limit: SEARCH_LIMIT,- })- breakpoint()+ try {+ const response = await api.fileSystem.list({+ search: trimmed,+ type: 'session_recording_playlist',+ limit: SEARCH_LIMIT,+ signal: cache.searchAbortController?.signal,+ })+ breakpoint()- return response.results+ return response.results+ } catch (error) {+ return rethrowSearchError(error, breakpoint)+ }},},],@@ -1621,20 +1679,54 @@ export const searchLogic = kea<searchLogicType>([},],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({setSearch: async ({ search }, breakpoint) => {+ if (search.trim() === '') {+ // An empty term means the palette closed or the box was cleared, so no later run+ // will replace what is in flight. Stop it now, because a person search can run for+ // a minute and nobody is waiting on the answer.+ cache.disposables.dispose('searchAbortController')+ return+ }+await breakpoint(150)- if (search.trim() !== '') {- actions.searchRecents({ search })- actions.loadUnifiedSearchResults({ searchTerm: search })- actions.loadPersonSearchResults({ searchTerm: search })- actions.loadGroupSearchResults({ searchTerm: search })- if (values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {- actions.loadAccountSearchResults({ searchTerm: search })- }- actions.loadPlaylistSearchResults({ searchTerm: search })+ // Registering under the same key aborts the previous term's requests. The new ones go+ // out in the same tick, so each superseded run sees its replacement when it wakes up.+ cache.disposables.add(+ () => {+ const controller = new AbortController()+ const clientQueryId = uuid()+ cache.searchAbortController = controller+ cache.personSearchQueryId = clientQueryId+ return () => {+ const personSearchRunning = cache.personSearchQueryId === clientQueryId+ cache.searchAbortController = null+ cache.personSearchQueryId = null+ controller.abort()+ if (personSearchRunning) {+ // Dropping the request does not reach ClickHouse, so the person search+ // would keep scanning and holding a query slot. Kill it by name.+ api.cancelQuery(clientQueryId).catch((error) =>+ console.warn('Failed cancelling person search', error)+ )+ }+ }+ },+ 'searchAbortController',+ // This controller belongs to one set of requests. Hiding the tab must not abort+ // them, or showing it again would arm a fresh controller over nothing.+ { pauseOnPageHidden: false }+ )++ actions.searchRecents({ search })+ actions.loadUnifiedSearchResults({ searchTerm: search })+ actions.loadPersonSearchResults({ searchTerm: search })+ actions.loadGroupSearchResults({ searchTerm: search })+ if (values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {+ actions.loadAccountSearchResults({ searchTerm: search })}+ actions.loadPlaylistSearchResults({ searchTerm: search })},})),afterMount(({ actions }) => {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 4fe2ccf858a5..05520dc9a9ee 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1733,6 +1733,8 @@ export interface PersonListParams {distinct_id?: stringinclude_total?: boolean // PostHog 3000-onlylimit?: number+ /** Names the ClickHouse query so `api.cancelQuery` can stop it. Up to 128 characters. */+ client_query_id?: string}export type SearchableEntity =diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 33be1d236193..0b4e0ae4fab4 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -42,6 +42,7 @@ from posthog.api.utils import actionfrom posthog.auth import PersonalAPIKeyAuthenticationfrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.constants import LIMIT, OFFSET+from posthog.errors import QueryErrorCategory, classify_query_errorfrom posthog.event_usage import get_request_analytics_propertiesfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.metrics import LABEL_TEAM_ID@@ -92,6 +93,26 @@ logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)DEFAULT_PAGE_LIMIT = 100++# The id reaches the ClickHouse query id and every query_log row for the request, so bound it.+# Cancelling matches on `query_id LIKE '<team_id>_<client_query_id>%'`, which makes an id holding+# `%` or `_` reach the team's other queries. The cancel endpoint takes any id with or without this+# param, so restricting the charset here would buy nothing and would reject ids like `req_1`.+CLIENT_QUERY_ID_MAX_LENGTH = 128++# Nginx's "Client Closed Request". Django and DRF have no name for it.+HTTP_CLIENT_CLOSED_REQUEST = 499+++def tag_client_query_id(client_query_id: str | None) -> None:+ """Name this request's ClickHouse queries so the caller can cancel them by that id."""+ if not client_query_id:+ return+ if len(client_query_id) > CLIENT_QUERY_ID_MAX_LENGTH:+ raise ValidationError({"client_query_id": f"Must be at most {CLIENT_QUERY_ID_MAX_LENGTH} characters."})+ tag_queries(client_query_id=client_query_id)++# Sync with .../lib/constants.tsx and .../cdp/utils.ts# It's almost certainly wrong to add more properties to this list, instead convince the user to send data to use with# these properties, or use e.g. a CDP transformation to rewrite their events.@@ -543,11 +564,22 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):OpenApiTypes.STR,description="Search persons, either by email (full text search) or distinct_id (exact match).",),+ OpenApiParameter(+ "client_query_id",+ OpenApiTypes.STR,+ description=(+ "Names the ClickHouse query this request runs. Send the same id to "+ "`DELETE /api/projects/:project_id/query/:client_query_id/` to stop a search that is still "+ "running. Up to 128 characters."+ ),+ ),PersonPropertiesSerializer(required=False),],)def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:tag_queries(product=ProductKey.PERSONS, feature=Feature.QUERY)+ client_query_id = request.GET.get("client_query_id")+ tag_client_query_id(client_query_id)team = self.teamfilter = Filter(request=request, team=self.team)@@ -608,6 +640,9 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"has_search": bool(filter.search),"has_properties": bool(person_properties),"has_distinct_id": bool(filter.distinct_id),+ # Only a caller that can cancel sends an id, which is what separates the command+ # palette's searches from the persons page's on the dashboard.+ "has_client_query_id": bool(client_query_id),"include_total": include_total,"is_csv": is_csv_request,"limit": filter.limit,@@ -628,34 +663,50 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# 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]+ # A cancel kills every ClickHouse query the request has in flight, so both queries below+ # sit inside one handler. Anything that is not a cancellation is re-raised untouched.+ try:+ 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]+ except Exception as err:+ if classify_query_error(err) is not QueryErrorCategory.CANCELLED:+ raise+ # The caller killed this search, so there is no body to return and nothing went+ # wrong. Raising would report a server error for every cancelled search.+ #+ # Returning also leaves the SLO block without an exception, so it records a+ # success with however long the kill took. A cancel is not a failure, so the+ # outcome stays as it is and this tag is what keeps an abandoned search from+ # reading as a fast one in the latency percentiles.+ slo.tag(cancelled=True)+ return Response(status=HTTP_CLIENT_CLOSED_REQUEST)slo.tag(result_count=len(actor_ids))diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex bae43b977447..08c176887026 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -18,13 +18,18 @@ from posthog.test.base import ()from unittest import mock+from django.test import SimpleTestCasefrom django.utils import timezone+from clickhouse_driver.errors import ServerExceptionfrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.exceptions import ValidationErrorimport posthog.models.person.deletion+from posthog.api.person import tag_client_query_idfrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.query_tagging import get_query_tag_value, reset_query_tagsfrom posthog.constants import AvailableFeaturefrom posthog.models import Organization, Person, PropertyDefinition, Teamfrom posthog.models.async_deletion import AsyncDeletion, DeletionType@@ -85,8 +90,25 @@ 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:+ @staticmethod+ def _persons_list_slo_events(capture: mock.MagicMock) -> list[dict]:+ return [+ call.kwargs["properties"]+ for call in capture.call_args_list+ if call.kwargs["event"] == "slo_operation_completed"+ and call.kwargs["properties"]["operation"] == "persons_list"+ ]++ @parameterized.expand(+ [+ ("?search=another@gm", True, False),+ ("", False, False),+ ("?search=another@gm&client_query_id=abc-123", True, True),+ ]+ )+ def test_person_list_emits_slo_event(+ self, query: str, expected_has_search: bool, expected_has_client_query_id: bool+ ) -> None:_create_person(team=self.team,distinct_ids=["distinct_id"],@@ -98,19 +120,64 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):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"- ]+ completed = self._persons_list_slo_events(capture)self.assertEqual(len(completed), 1)self.assertEqual(completed[0]["has_search"], expected_has_search)+ self.assertEqual(completed[0]["has_client_query_id"], expected_has_client_query_id)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)+ def test_cancelled_search_is_marked_on_the_slo_event(self) -> None:+ with (+ mock.patch(+ "posthog.hogql_queries.actors_query_runner.ActorsQueryRunner.calculate",+ side_effect=ServerException("Query was cancelled", code=394),+ ),+ mock.patch("posthog.slo.events.posthoganalytics.capture") as capture,+ ):+ response = self.client.get("/api/person/?search=someone&client_query_id=abc-123")+ self.assertEqual(response.status_code, 499)++ completed = self._persons_list_slo_events(capture)+ self.assertEqual(len(completed), 1)+ self.assertTrue(completed[0]["cancelled"])+ # Returning is not an error, so the operation still reports success. `cancelled` is what+ # keeps an abandoned search from reading as a fast one in the latency percentiles.+ self.assertEqual(completed[0]["outcome"], "success")++ @parameterized.expand(+ [+ ("accepts a uuid", "5d92fb51-5088-45e8-91b2-843aef3d69bd", status.HTTP_200_OK),+ ("rejects an over long id", "a" * 129, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_search_with_client_query_id(self, _name: str, client_query_id: str, expected_status: int) -> None:+ response = self.client.get(f"/api/person/?search=someone&client_query_id={client_query_id}")+ self.assertEqual(response.status_code, expected_status)++ @parameterized.expand(+ [+ ("actors query", "posthog.hogql_queries.actors_query_runner.ActorsQueryRunner.calculate", ""),+ ("total count query", "posthog.hogql.query.execute_hogql_query", "&include_total=true"),+ ]+ )+ def test_search_answers_499_when_the_query_was_cancelled(+ self, _name: str, patch_target: str, extra_params: str+ ) -> None:+ with mock.patch(patch_target, side_effect=ServerException("Query was cancelled", code=394)):+ response = self.client.get(f"/api/person/?search=someone{extra_params}")+ self.assertEqual(response.status_code, 499)++ def test_search_still_fails_on_a_query_error_that_is_not_a_cancellation(self) -> None:+ with mock.patch(+ "posthog.hogql_queries.actors_query_runner.ActorsQueryRunner.calculate",+ side_effect=ServerException("Boom", code=999),+ ):+ response = self.client.get("/api/person/?search=someone")+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)+@also_test_with_materialized_columns(event_properties=["email"], person_properties=["email"])@snapshot_clickhouse_queriesdef test_search_person_id(self) -> None:@@ -2185,6 +2252,32 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertNotIn(distinct_ids[200], results)+class TestTagClientQueryId(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ reset_query_tags()++ @parameterized.expand(+ [+ ("uuid", "5d92fb51-5088-45e8-91b2-843aef3d69bd"),+ ("underscores", "req_1_alice"),+ ("at the length limit", "a" * 128),+ ]+ )+ def test_names_the_clickhouse_query(self, _name: str, client_query_id: str) -> None:+ tag_client_query_id(client_query_id)+ self.assertEqual(get_query_tag_value("client_query_id"), client_query_id)++ def test_ignores_a_missing_id(self) -> None:+ tag_client_query_id(None)+ self.assertIsNone(get_query_tag_value("client_query_id"))++ def test_rejects_an_id_past_the_length_limit(self) -> None:+ with self.assertRaises(ValidationError):+ tag_client_query_id("a" * 129)+ self.assertIsNone(get_query_tag_value("client_query_id"))++class TestPersonFromClickhouse(TestPerson):@override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=False)def test_pagination_limit(self):diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex 8289d85bedbe..8fc97f973117 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -406,6 +406,10 @@ export interface PersonPropertiesAtTimeResponseApi {}export type PersonsListParams = {+ /**+ * Names the ClickHouse query this request runs. Send the same id to `DELETE /api/projects/:project_id/query/:client_query_id/` to stop a search that is still running. Up to 128 characters.+ */+ client_query_id?: string/*** Filter list by distinct id.*/diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8c54a465c9ac..1eb4062961b4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -93869,6 +93869,10 @@ export namespace Schemas {};export type PersonsListParams = {+ /**+ * Names the ClickHouse query this request runs. Send the same id to `DELETE /api/projects/:project_id/query/:client_query_id/` to stop a search that is still running. Up to 128 characters.+ */+ client_query_id?: string;/*** Filter list by distinct id.*/diff --git a/services/mcp/src/generated/persons/api.ts b/services/mcp/src/generated/persons/api.tsindex f5b39a4e1960..eb1c1d039eb8 100644--- a/services/mcp/src/generated/persons/api.ts+++ b/services/mcp/src/generated/persons/api.ts@@ -24,6 +24,12 @@ export const personsListQueryPropertiesItemValuesItemOperatorDefault = `exact`export const personsListQueryPropertiesItemValuesItemTypeDefault = `event`export const PersonsListQueryParams = /* @__PURE__ */ zod.object({+ client_query_id: zod+ .string()+ .optional()+ .describe(+ 'Names the ClickHouse query this request runs. Send the same id to `DELETE \/api\/projects\/:project_id\/query\/:client_query_id\/` to stop a search that is still running. Up to 128 characters.'+ ),distinct_id: zod.string().optional().describe('Filter list by distinct id.'),email: zod.string().optional().describe('Filter persons by email (exact match)'),format: zod.enum(['csv', 'json']).optional(),diff --git a/services/mcp/src/tools/generated/persons.ts b/services/mcp/src/tools/generated/persons.tsindex 6c5b4be8d3e2..ba5bd69a3f77 100644--- a/services/mcp/src/tools/generated/persons.ts+++ b/services/mcp/src/tools/generated/persons.ts@@ -81,6 +81,7 @@ const personsList = (): ToolBase<typeof PersonsListSchema, WithPostHogUrl<Schemamethod: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/persons/`,query: {+ client_query_id: params.client_query_id,distinct_id: params.distinct_id,email: params.email,limit: params.limit,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.jsonindex a62f87292ae5..11704cf0ed6e 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-list.json@@ -1,6 +1,10 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "client_query_id": {+ "description": "Names the ClickHouse query this request runs. Send the same id to `DELETE /api/projects/:project_id/query/:client_query_id/` to stop a search that is still running. Up to 128 characters.",+ "type": "string"+ },"distinct_id": {"description": "Filter list by distinct id.","type": "string"