: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(persons): serve person property values via HogQL instead of raw SQL (#87282)
Sandy Spicer4659f4fc111c
diff --git a/ee/benchmarks/benchmarks.py b/ee/benchmarks/benchmarks.pyindex b6f0772cefcb..b513d8d386e7 100644--- a/ee/benchmarks/benchmarks.py+++ b/ee/benchmarks/benchmarks.py@@ -7,9 +7,6 @@ from ee.clickhouse.materialized_columns.analyze import (materialize,)from ee.clickhouse.materialized_columns.columns import MaterializedColumn-from posthog.queries.property_values import (- get_person_property_values_for_key,-)from posthog.hogql_queries.property_values_query_runner import PropertyValuesQueryRunnerfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.hogql_queries.utils.timestamp_utils import get_earliest_timestamp_unfiltered@@ -60,11 +57,17 @@ class QuerySuite:@benchmark_clickhousedef track_person_property_values(self):with no_materialized_columns():- get_person_property_values_for_key("$browser", self.team)+ self._run_person_property_values("$browser")@benchmark_clickhousedef track_person_property_values_materialized(self):- get_person_property_values_for_key("$browser", self.team)+ self._run_person_property_values("$browser")++ def _run_person_property_values(self, key: str) -> None:+ PropertyValuesQueryRunner(+ team=self.team,+ query=PropertyValuesQuery(property_type=PropertyType.PERSON, property_key=key),+ ).run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)def setup(self):for table, properties in MATERIALIZED_PROPERTIES.items():diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 0ce03b6b6d67..a68c2ca49739 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -43,7 +43,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_error+from posthog.errors import ExposedCHQueryError, QueryErrorCategory, classify_query_errorfrom posthog.event_usage import get_request_analytics_propertiesfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.metrics import LABEL_TEAM_ID@@ -1035,6 +1035,8 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return resprefresh = refresh_requested_by_client(request)+ # The user rides along so HogQL property masking resolves their explicit+ # grants instead of the team-default rules, matching /api/query.runner = PropertyValuesQueryRunner(team=self.team,query=PropertyValuesQuery(@@ -1042,11 +1044,21 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):property_key=key,search_value=value,),+ user=user,)execution_mode = execution_mode_from_refresh(refresh)if execution_mode == ExecutionMode.CACHE_ONLY_NEVER_CALCULATE and not refresh:execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS- result = runner.run(execution_mode, analytics_props=get_request_analytics_properties(request))+ # Convert here rather than in the runner, so QueryRunner.run() sees the original+ # ClickHouse error and can classify it and record it in the failure cache.+ # The failure cache serves remembered failures as APIException subclasses with+ # their own status codes, so they pass through uncaught. Matches /api/query.+ try:+ result = runner.run(+ execution_mode, user=user, analytics_props=get_request_analytics_properties(request)+ )+ except ExposedCHQueryError as e:+ raise ValidationError(str(e), e.code_name)assert isinstance(result, (PropertyValuesQueryResponse, CachedPropertyValuesQueryResponse))is_refreshing = (isinstance(result, CachedPropertyValuesQueryResponse)diff --git a/posthog/api/test/__snapshots__/test_person.ambr b/posthog/api/test/__snapshots__/test_person.ambrindex 0cf69b677367..8386801f0835 100644--- a/posthog/api/test/__snapshots__/test_person.ambr+++ b/posthog/api/test/__snapshots__/test_person.ambr@@ -142,42 +142,61 @@# name: TestPerson.test_person_property_values'''/* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c+ SELECT value AS value,+ minus(uniq(id), uniqIf(id, notEquals(is_deleted, 0))) AS cFROM- (SELECT replaceRegexpAll(JSONExtractRaw(properties, 'random_prop'), '^"|"$', '') as value,- is_deleted,- id+ (SELECT toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'random_prop'), ''), 'null'), '^"|"$', '')) AS value,+ person.is_deleted AS is_deleted,+ person.id AS idFROM person- WHERE team_id = 99999- AND value IS NOT NULL- AND value != ''- ORDER BY id DESC+ WHERE and(equals(person.team_id, 99999), isNotNull(value), ifNull(notEquals(value, ''), 1))+ ORDER BY person.id DESCLIMIT 100000)GROUP BY value- HAVING c > 0+ HAVING greater(c, 0)ORDER BY c DESC- LIMIT 20+ LIMIT 20 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestPerson.test_person_property_values.1'''/* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c+ SELECT value AS value,+ minus(uniq(id), uniqIf(id, notEquals(is_deleted, 0))) AS cFROM- (SELECT replaceRegexpAll(JSONExtractRaw(properties, 'random_prop'), '^"|"$', '') as value,- is_deleted,- id+ (SELECT toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'random_prop'), ''), 'null'), '^"|"$', '')) AS value,+ person.is_deleted AS is_deleted,+ person.id AS idFROM person- WHERE team_id = 99999- AND value ILIKE '%qw%'- ORDER BY id DESC+ WHERE and(equals(person.team_id, 99999), ifNull(ilike(value, '%qw%'), 0))+ ORDER BY person.id DESCLIMIT 100000)GROUP BY value- HAVING c > 0+ HAVING greater(c, 0)ORDER BY c DESC- LIMIT 20+ LIMIT 20 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestPerson.test_properties@@ -497,42 +516,61 @@# name: TestPersonFromClickhouse.test_person_property_values'''/* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c+ SELECT value AS value,+ minus(uniq(id), uniqIf(id, notEquals(is_deleted, 0))) AS cFROM- (SELECT replaceRegexpAll(JSONExtractRaw(properties, 'random_prop'), '^"|"$', '') as value,- is_deleted,- id+ (SELECT toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'random_prop'), ''), 'null'), '^"|"$', '')) AS value,+ person.is_deleted AS is_deleted,+ person.id AS idFROM person- WHERE team_id = 99999- AND value IS NOT NULL- AND value != ''- ORDER BY id DESC+ WHERE and(equals(person.team_id, 99999), isNotNull(value), ifNull(notEquals(value, ''), 1))+ ORDER BY person.id DESCLIMIT 100000)GROUP BY value- HAVING c > 0+ HAVING greater(c, 0)ORDER BY c DESC- LIMIT 20+ LIMIT 20 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestPersonFromClickhouse.test_person_property_values.1'''/* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c+ SELECT value AS value,+ minus(uniq(id), uniqIf(id, notEquals(is_deleted, 0))) AS cFROM- (SELECT replaceRegexpAll(JSONExtractRaw(properties, 'random_prop'), '^"|"$', '') as value,- is_deleted,- id+ (SELECT toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'random_prop'), ''), 'null'), '^"|"$', '')) AS value,+ person.is_deleted AS is_deleted,+ person.id AS idFROM person- WHERE team_id = 99999- AND value ILIKE '%qw%'- ORDER BY id DESC+ WHERE and(equals(person.team_id, 99999), ifNull(ilike(value, '%qw%'), 0))+ ORDER BY person.id DESCLIMIT 100000)GROUP BY value- HAVING c > 0+ HAVING greater(c, 0)ORDER BY c DESC- LIMIT 20+ LIMIT 20 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0'''# ---# name: TestPersonFromClickhouse.test_propertiesdiff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 46e11ecbc370..56cad6c7b5fc 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -626,6 +626,10 @@ def tag_queries(**kwargs) -> None:The purpose of tag_queries is to pass additional context for ClickHouse executed queries. The tagsare serialized into ClickHouse' system.query_log.log_comment column.+ Tags are last-write-wins, and HogQLQueryExecutor calls tag_queries(query_type=...) itself+ immediately before execution. So a query_type set here before execute_hogql_query() never+ reaches query_log; pass query_type= to execute_hogql_query() instead.+:param kwargs: Key->value pairs of tags to be set."""current_tags = get_query_tags()diff --git a/posthog/hogql_queries/property_values_query_runner.py b/posthog/hogql_queries/property_values_query_runner.pyindex 5e1697a28153..6c53b1c7b3e2 100644--- a/posthog/hogql_queries/property_values_query_runner.py+++ b/posthog/hogql_queries/property_values_query_runner.py@@ -18,6 +18,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.caching.utils import (@@ -27,10 +28,7 @@ from posthog.caching.utils import (from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.models import PropertyDefinitionfrom posthog.models.event.new_events_schema import use_new_events_schema-from posthog.queries.property_values import (- get_event_property_values_from_aggregated_table,- get_person_property_values_for_key,-)+from posthog.queries.property_values import get_event_property_values_from_aggregated_tablefrom posthog.utils import convert_property_value, flatten, get_instance_region, relative_date_parsefrom products.access_control.backend.property_access_control import get_restricted_property_names@@ -54,8 +52,9 @@ class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponsedef to_query(self) -> ast.SelectQuery:if self.query.property_type == PropertyType.EVENT:return self._event_query()- # Person queries use raw SQL for speed (4s vs 30s) — move here when HogQL persons table gets faster- raise NotImplementedError("Person property values use raw SQL via _calculate_person()")+ if self.query.property_key == "distinct_id":+ return self._distinct_id_query()+ return self._person_query()def _calculate(self) -> PropertyValuesQueryResponse:if self.query.property_type == PropertyType.PERSON:@@ -143,19 +142,117 @@ class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponse)def _calculate_person(self) -> PropertyValuesQueryResponse:- # Use the raw SQL person query — the HogQL persons virtual table does full argMax dedup- # which is correct but much slower (30s vs 4s on large teams). The raw SQL approximates- # dedup with uniq(id) - uniqIf(id, is_deleted != 0) and caps at 100k rows, which is- # fast enough and good enough for autocomplete.- rows = cast(- list, get_person_property_values_for_key(self.query.property_key, self.team, self.query.search_value)+ # HogQL masking covers properties-blob reads only; distinct_id is a plain+ # column on the mapping table, so its restriction is enforced here.+ if self.query.property_key == "distinct_id" and self._is_restricted_person_property_key:+ return PropertyValuesQueryResponse(+ results=[],+ timings=self.timings.to_list(),+ modifiers=self.modifiers,+ )+ # query_type must go through execute_hogql_query: the executor re-tags it right+ # before execution, so a tag_queries() call here would be overwritten.+ if self.query.property_key == "distinct_id":+ query_type = "get_person_distinct_id_values"+ elif self.query.search_value:+ query_type = "get_person_property_values_with_value"+ else:+ query_type = "get_person_property_values"+ result = execute_hogql_query(+ self.to_query(),+ query_type=query_type,+ team=self.team,+ user=self.user,+ context=HogQLContext(team_id=self.team.pk, user=self.user),+ timings=self.timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,)return PropertyValuesQueryResponse(- results=self._format_person_results(rows),+ results=self._format_person_results(result.results),timings=self.timings.to_list(),+ hogql=result.hogql,modifiers=self.modifiers,)+ @cached_property+ def _is_restricted_person_property_key(self) -> bool:+ restricted = get_restricted_property_names(+ team_id=self.team.pk, user=self.user, property_type=PropertyDefinition.Type.PERSON+ )+ return self.query.property_key in restricted++ def get_cache_payload(self) -> dict:+ payload = super().get_cache_payload()+ # Person values cached before the HogQL port were computed without property+ # masking; the version marker keeps them from being served.+ payload["property_values_version"] = 2+ return payload++ def _person_query(self) -> ast.SelectQuery:+ # `persons` resolves every person to its latest version first, far too slow+ # for autocomplete, so this samples raw rows instead. Deletion hiding is+ # best-effort: a deletion row only hides values it carries itself.+ if self.query.search_value:+ inner_where = parse_expr(+ "value ILIKE {pattern}",+ {"pattern": ast.Constant(value=self._ilike_pattern(self.query.search_value))},+ )+ else:+ inner_where = parse_expr("isNotNull(value) AND value != ''")+ return cast(+ ast.SelectQuery,+ parse_select(+ """+ SELECT value, uniq(id) - uniqIf(id, is_deleted != 0) AS c+ FROM (+ SELECT toString({property_expr}) AS value, is_deleted, id+ FROM raw_persons+ WHERE {inner_where}+ ORDER BY id DESC+ LIMIT 100000+ )+ GROUP BY value+ HAVING c > 0+ ORDER BY c DESC+ LIMIT 20+ """,+ placeholders={+ "property_expr": ast.Field(chain=["properties", self.query.property_key]),+ "inner_where": inner_where,+ },+ ),+ )++ def _distinct_id_query(self) -> ast.SelectQuery:+ # distinct_id lives in the distinct_id-to-person mapping table, not in person+ # properties, so the generic person query would return nothing. c is always 1+ # because the GROUP BY already deduplicates.+ query = cast(+ ast.SelectQuery,+ parse_select(+ """+ SELECT distinct_id AS value, 1 AS c+ FROM raw_person_distinct_ids+ GROUP BY distinct_id+ HAVING argMax(is_deleted, version) = 0+ ORDER BY value ASC+ LIMIT 20+ """+ ),+ )+ if self.query.search_value:+ query.where = parse_expr(+ "distinct_id ILIKE {pattern}",+ {"pattern": ast.Constant(value=self._ilike_pattern(self.query.search_value))},+ )+ return query++ @staticmethod+ def _ilike_pattern(search_value: str) -> str:+ escaped = search_value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+ return f"%{escaped}%"+def _event_query(self) -> ast.SelectQuery:key = self.query.property_keyis_virtual = key.startswith("$virt_")@@ -202,12 +299,11 @@ class PropertyValuesQueryRunner(AnalyticsQueryRunner[PropertyValuesQueryResponseconditions.append(ast.Or(exprs=event_conditions) if len(event_conditions) > 1 else event_conditions[0])if self.query.search_value:- escaped = self.query.search_value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")conditions.append(ast.CompareOperation(op=ast.CompareOperationOp.ILike,left=string_expr,- right=ast.Constant(value=f"%{escaped}%"),+ right=ast.Constant(value=self._ilike_pattern(self.query.search_value)),))diff --git a/posthog/hogql_queries/test/__snapshots__/test_property_values_query_runner.ambr b/posthog/hogql_queries/test/__snapshots__/test_property_values_query_runner.ambrnew file mode 100644index 000000000000..3c2cb8ce9ff9--- /dev/null+++ b/posthog/hogql_queries/test/__snapshots__/test_property_values_query_runner.ambr@@ -0,0 +1,53 @@+# serializer version: 1+# name: TestPropertyValuesQueryRunner.test_person_property_values_basic+ '''+ SELECT value AS value,+ minus(uniq(id), uniqIf(id, notEquals(is_deleted, 0))) AS c+ FROM+ (SELECT toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'country'), ''), 'null'), '^"|"$', '')) AS value,+ person.is_deleted AS is_deleted,+ person.id AS id+ FROM person+ WHERE and(equals(person.team_id, 99999), isNotNull(value), ifNull(notEquals(value, ''), 1))+ ORDER BY person.id DESC+ LIMIT 100000)+ GROUP BY value+ HAVING greater(c, 0)+ ORDER BY c DESC+ LIMIT 20 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPropertyValuesQueryRunner.test_person_property_values_distinct_id_suggestions+ '''+ SELECT person_distinct_id2.distinct_id AS value,+ 1 AS c+ FROM person_distinct_id2+ WHERE equals(person_distinct_id2.team_id, 99999)+ GROUP BY person_distinct_id2.distinct_id+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0)+ ORDER BY value ASC+ LIMIT 20 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/posthog/hogql_queries/test/test_property_values_query_runner.py b/posthog/hogql_queries/test/test_property_values_query_runner.pyindex 99bc7a6bf43e..81eecf27eca2 100644--- a/posthog/hogql_queries/test/test_property_values_query_runner.py+++ b/posthog/hogql_queries/test/test_property_values_query_runner.py@@ -1,6 +1,13 @@from datetime import datetime, timedelta-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from posthog.test.base import (+ APIBaseTest,+ ClickhouseTestMixin,+ _create_event,+ _create_person,+ flush_persons_and_events,+ snapshot_clickhouse_queries,+)from unittest.mock import patchfrom django.test import override_settings@@ -136,6 +143,7 @@ class TestPropertyValuesQueryRunner(ClickhouseTestMixin, APIBaseTest):results = self._run(PropertyValuesQuery(property_type=PropertyType.EVENT, property_key="browser"))assert results[0].count is None+ @snapshot_clickhouse_queriesdef test_person_property_values_basic(self):_create_person(distinct_ids=["u1"], team=self.team, properties={"country": "US"})_create_person(distinct_ids=["u2"], team=self.team, properties={"country": "UK"})@@ -184,6 +192,7 @@ class TestPropertyValuesQueryRunner(ClickhouseTestMixin, APIBaseTest):)assert {r.name for r in results} == expected_names+ @snapshot_clickhouse_queriesdef test_person_property_values_distinct_id_suggestions(self):_create_person(distinct_ids=["alice", "alice-alias"], team=self.team, properties={})_create_person(distinct_ids=["bob"], team=self.team, properties={})diff --git a/posthog/models/person/sql.py b/posthog/models/person/sql.pyindex fbd1d98ebb2a..2a061c7a55ab 100644--- a/posthog/models/person/sql.py+++ b/posthog/models/person/sql.py@@ -679,59 +679,6 @@ COMMENT_DISTINCT_ID_COLUMN_SQL = lambda: ()-# Tricky: the person table uses a ReplacingMergeTree, but it is not guaranteed by Clickhouse that the replacement has-# actually happened. This means we can have multiple rows for a particular person ID. This can happen if a property has-# changed, or if the user was deleted.-# The following query will make an attempt to hide values that come from deleted users, however it will only hide the-# values that are set at the time of deletion (or after). This is to avoid needing to GROUP BY id on the persons table,-# which would make this query take ~20x as long and be unacceptable in the UI.-SELECT_PERSON_PROP_VALUES_SQL = """-SELECT- value,- uniq(id) - uniqIf(id, is_deleted != 0) as c-FROM (- SELECT- {property_field} as value,- is_deleted,- id- FROM- person- WHERE- team_id = %(team_id)s AND- value IS NOT NULL AND- value != ''- ORDER BY id DESC- LIMIT 100000-)-GROUP BY value-HAVING c > 0-ORDER BY c DESC-LIMIT 20-"""--SELECT_PERSON_PROP_VALUES_SQL_WITH_FILTER = """-SELECT- value,- uniq(id) - uniqIf(id, is_deleted != 0) as c-FROM (- SELECT- {property_field} as value,- is_deleted,- id- FROM- person- WHERE- team_id = %(team_id)s AND- value ILIKE %(value)s- ORDER BY id DESC- LIMIT 100000-)-GROUP BY value-HAVING c > 0-ORDER BY c DESC-LIMIT 20-"""-GET_PERSON_COUNT_FOR_TEAM = "SELECT count() AS count FROM person WHERE team_id = %(team_id)s"GET_PERSON_DISTINCT_ID2_COUNT_FOR_TEAM = "SELECT count() AS count FROM person_distinct_id2 WHERE team_id = %(team_id)s"diff --git a/posthog/queries/property_values.py b/posthog/queries/property_values.pyindex 4b4ee9dca501..7d1d4a5b29ab 100644--- a/posthog/queries/property_values.py+++ b/posthog/queries/property_values.py@@ -2,8 +2,6 @@ from typing import Optionalfrom opentelemetry import trace-from posthog.models.person.sql import SELECT_PERSON_PROP_VALUES_SQL, SELECT_PERSON_PROP_VALUES_SQL_WITH_FILTER-from posthog.models.property.util import get_property_string_exprfrom posthog.models.team import Teamfrom posthog.queries.insight import insight_sync_execute@@ -44,65 +42,3 @@ def get_event_property_values_from_aggregated_table(key: str, team: Team, value:)span.set_attribute("result_count", len(result))return result---def get_person_property_values_for_key(key: str, team: Team, value: Optional[str] = None):- with tracer.start_as_current_span("get_person_property_values_for_key") as span:- span.set_attribute("team_id", team.pk)- span.set_attribute("property_key", key)- span.set_attribute("has_value_filter", value is not None)-- if key == "distinct_id":- result = _get_distinct_id_values(team, value)- span.set_attribute("result_count", len(result))- return result-- property_field, _ = get_property_string_expr("person", key, "%(key)s", "properties")-- if value:- escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")- result = insight_sync_execute(- SELECT_PERSON_PROP_VALUES_SQL_WITH_FILTER.format(property_field=property_field),- {"team_id": team.pk, "key": key, "value": "%{}%".format(escaped)},- query_type="get_person_property_values_with_value",- team_id=team.pk,- )- else:- result = insight_sync_execute(- SELECT_PERSON_PROP_VALUES_SQL.format(property_field=property_field),- {"team_id": team.pk, "key": key},- query_type="get_person_property_values",- team_id=team.pk,- )- span.set_attribute("result_count", len(result))- return result---# distinct_id lives in person_distinct_id2, not in person.properties — so the generic-# SELECT_PERSON_PROP_VALUES_SQL path would always return an empty list. We query the-# distinct-id table directly and let argMax hide tombstoned rows. The count is always 1-# per distinct_id since GROUP BY already deduplicates.-_SELECT_DISTINCT_IDS_SQL = """-SELECT distinct_id AS value, 1 AS c-FROM person_distinct_id2-WHERE team_id = %(team_id)s{value_filter}-GROUP BY distinct_id-HAVING argMax(is_deleted, version) = 0-ORDER BY value ASC-LIMIT 20-"""---def _get_distinct_id_values(team: Team, value: Optional[str]) -> list:- params: dict = {"team_id": team.pk}- value_filter = ""- if value:- escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")- value_filter = " AND distinct_id ILIKE %(value)s"- params["value"] = f"%{escaped}%"- return insight_sync_execute(- _SELECT_DISTINCT_IDS_SQL.format(value_filter=value_filter),- params,- query_type="get_person_distinct_id_values",- team_id=team.pk,- )diff --git a/products/web_analytics/backend/max_tools.py b/products/web_analytics/backend/max_tools.pyindex 5900c3eeac70..477503acec5d 100644--- a/products/web_analytics/backend/max_tools.py+++ b/products/web_analytics/backend/max_tools.py@@ -23,7 +23,6 @@ from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.job_owners import JobOwnersfrom posthog.models import Team, Userfrom posthog.models.health_issue import HealthIssue-from posthog.queries.property_values import get_person_property_values_for_keyfrom posthog.scopes import APIScopeObjectfrom posthog.sync import database_sync_to_async, database_sync_to_async_poolfrom posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP@@ -118,24 +117,22 @@ class WebAnalyticsFilterOptionsToolkit(TaxonomyAgentToolkit):self, property_name: str, property_type: Literal["event", "session", "person"]) -> str:if property_type == "person":- with tags_context(product=Product.MAX_AI, team_id=self._team.pk, org_id=self._team.organization_id):- values = await database_sync_to_async(get_person_property_values_for_key)(- property_name, self._team, value=None- )+ runner_type = PropertyType.PERSONelif property_type in ("event", "session"):- with tags_context(product=Product.MAX_AI, team_id=self._team.pk, org_id=self._team.organization_id):- values = await database_sync_to_async(self._retrieve_event_property_values)(property_name)+ # Session property values live on events.properties too, so they share the+ # EVENT path of PropertyValuesQueryRunner (there is no SESSION property type).+ runner_type = PropertyType.EVENTelse:return TaxonomyErrorMessages.property_not_found(property_name, property_type)+ with tags_context(product=Product.MAX_AI, team_id=self._team.pk, org_id=self._team.organization_id):+ values = await database_sync_to_async(self._retrieve_property_values)(property_name, runner_type)return self._format_property_values(property_name, values, sample_count=len(values))- def _retrieve_event_property_values(self, property_name: str) -> list:- # Web analytics event and session property values both live on events.properties, so they- # share the EVENT path of PropertyValuesQueryRunner (there is no SESSION property type).+ def _retrieve_property_values(self, property_name: str, property_type: PropertyType) -> list[str | int | float]:runner = PropertyValuesQueryRunner(team=self._team,- query=PropertyValuesQuery(property_type=PropertyType.EVENT, property_key=property_name),+ query=PropertyValuesQuery(property_type=property_type, property_key=property_name),user=self._user,)response = runner.run(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE, user=self._user)diff --git a/products/web_analytics/backend/test/test_max_tools.py b/products/web_analytics/backend/test/test_max_tools.pyindex 1c4fae9d623d..7f423a727271 100644--- a/products/web_analytics/backend/test/test_max_tools.py+++ b/products/web_analytics/backend/test/test_max_tools.py@@ -1,9 +1,16 @@-from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events+from posthog.test.base import (+ APIBaseTest,+ ClickhouseDestroyTablesMixin,+ _create_event,+ _create_person,+ flush_persons_and_events,+)from posthog.schema import (CompareFilter,EventPropertyFilter,PropertyOperator,+ PropertyType,SessionPropertyFilter,WebAnalyticsAssistantFilters,)@@ -36,10 +43,20 @@ class TestWebAnalyticsPropertyValues(ClickhouseDestroyTablesMixin, APIBaseTest):flush_persons_and_events()toolkit = WebAnalyticsFilterOptionsToolkit(self.team, self.user)- values = toolkit._retrieve_event_property_values("$browser")+ values = toolkit._retrieve_property_values("$browser", PropertyType.EVENT)assert set(values) == {"Chrome", "Firefox"}+ def test_retrieve_person_property_values_returns_plain_names(self):+ _create_person(distinct_ids=["u1"], team=self.team, properties={"country": "US"})+ _create_person(distinct_ids=["u2"], team=self.team, properties={"country": "UK"})+ flush_persons_and_events()++ toolkit = WebAnalyticsFilterOptionsToolkit(self.team, self.user)+ values = toolkit._retrieve_property_values("country", PropertyType.PERSON)++ assert set(values) == {"US", "UK"}+class TestWebAnalyticsAssistantFilters(APIBaseTest):def test_filters_validation(self):