: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(hogql): bound the property name autocomplete read by type (#115904)
Thomas Obermüller9ecc60f416b5
diff --git a/posthog/hogql/autocomplete.py b/posthog/hogql/autocomplete.pyindex cb3999fb7251..1b62acb901e8 100644--- a/posthog/hogql/autocomplete.py+++ b/posthog/hogql/autocomplete.py@@ -5,8 +5,7 @@ from enum import Enum, autofrom functools import lru_cachefrom typing import Optional, cast-from django.db import models-from django.db.models.functions.comparison import Coalesce+from django.db.models import Ffrom posthog.schema import (AutocompleteCompletionItem,@@ -20,6 +19,7 @@ from posthog.hogql import astfrom posthog.hogql.base import AST, CTE, ConstantTypefrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import HOGQL_CHARACTERS_TO_BE_WRAPPED, Database+from posthog.hogql.database.lazy_join_tags import GROUP_Nfrom posthog.hogql.database.models import (BooleanDatabaseField,DatabaseField,@@ -61,7 +61,11 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.taxonomy.taxonomy import QUERY_DEPRECATED_EVENT_PROPERTIES-from products.event_definitions.backend.models.property_definition import PropertyDefinition+from products.event_definitions.backend.models.property_definition import (+ PropertyDefinition,+ effective_project_id_expr,+ group_type_index_key_expr,+)from products.product_analytics.backend.facade.api import insight_variables_for_teamfrom common.hogvm.python.stl import STL@@ -744,10 +748,30 @@ def _property_definition_type(table: Table, field: StringJSONDatabaseField) -> Oreturn None+def _group_type_index_key(+ table: Table, property_type: PropertyDefinition.Type, joined_group_index: Optional[int]+) -> Optional[int]:+ if property_type != PropertyDefinition.Type.GROUP:+ return -1+ if isinstance(table, EventsGroupSubTable):+ return table.group_index+ # `groups` holds every group type. Without a join that names one, suggest the properties of all of them.+ return joined_group_index+++def _joined_group_index(field: FieldOrTable) -> Optional[int]:+ # `events.group_N` joins the whole `groups` table. Only the join's resolver params name the group type.+ if isinstance(field, LazyJoin) and field.resolver == GROUP_N:+ group_index = field.resolver_params.get("group_index")+ return group_index if isinstance(group_index, int) else None+ return None++def _suggest_property_names(*,table: Table,field: StringJSONDatabaseField,+ joined_group_index: Optional[int],match_term: str,context: HogQLContext,timings: HogQLTimings,@@ -759,23 +783,38 @@ def _suggest_property_names(with timings.measure("property_filter"):property_query = PropertyDefinition.objects.alias(- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())+ effective_project_id=effective_project_id_expr(),+ group_type_index_key=group_type_index_key_expr(),).filter(effective_project_id=context.team.project_id, # type: ignorename__contains=match_term,type=property_type,)+ group_type_index_key = _group_type_index_key(table, property_type, joined_group_index)+ if group_type_index_key is not None:+ property_query = property_query.filter(group_type_index_key=group_type_index_key)if property_type == PropertyDefinition.Type.EVENT:property_query = property_query.exclude(name__in=QUERY_DEPRECATED_EVENT_PROPERTIES)# One row past the limit sets `incomplete_list` without an unbounded COUNT(*):# an empty match_term makes the filter `LIKE '%%'`, so that count walked the- # project's whole taxonomy. `posthog_propdef_proj_uniq` is keyed on (project,- # name, ...), so ordering by name reads it in index order and stops at the limit.+ # project's whole taxonomy.+ # The order is the key of `index_property_def_query_proj`, which leads with (project, type,+ # group type). Postgres reads only the rows of this type in index order and stops at the limit.+ # Do not order by name. That walks `posthog_propdef_proj_uniq`, which leads with (project, name),+ # through every type in the project, and a type with fewer rows than the limit never stops it.+ # A non-empty match_term filters on top of the walk, so a rare term still reads every row of the type.+ # The editor sorts suggestions by label, so this order only selects which rows fit in the limit.with timings.measure("property_get_values"):properties = list(- property_query.order_by("name")[: PROPERTY_DEFINITION_LIMIT + 1].values("name", "property_type")+ property_query.order_by(+ "effective_project_id",+ "type",+ "group_type_index_key",+ F("query_usage_30_day").desc(nulls_last=True),+ "name",+ )[: PROPERTY_DEFINITION_LIMIT + 1].values("name", "property_type"))response.incomplete_list = len(properties) > PROPERTY_DEFINITION_LIMITproperties = properties[:PROPERTY_DEFINITION_LIMIT]@@ -827,6 +866,7 @@ def _suggest_select_fields(table_has_alias = select_from.alias is not Nonechain_len = len(node.chain)last_table: Table = table+ joined_group_index: Optional[int] = Nonefor index, chain_part in enumerate(node.chain):# Return just the table aliasif table_has_alias and index == 0 and chain_len == 1:@@ -873,6 +913,7 @@ def _suggest_select_fields(_suggest_property_names(table=last_table,field=field,+ joined_group_index=joined_group_index,match_term=match_term,context=context,timings=timings,@@ -885,6 +926,7 @@ def _suggest_select_fields(breakelse:field = last_table.fields[str(chain_part)]+ joined_group_index = _joined_group_index(field)if isinstance(field, Table):last_table = fieldelif isinstance(field, LazyJoin):diff --git a/posthog/hogql/test/test_autocomplete.py b/posthog/hogql/test/test_autocomplete.pyindex 2ad02ab71a75..c6cc183e7254 100644--- a/posthog/hogql/test/test_autocomplete.py+++ b/posthog/hogql/test/test_autocomplete.py@@ -243,6 +243,26 @@ class TestAutocomplete(ClickhouseTestMixin, APIBaseTest):assert len(results.suggestions) == 1assert results.suggestions[0].label == "some_person_value"+ @parameterized.expand(+ [+ ("group_join", "select group_1.properties. from events", 26, ["group_1_value"]),+ ("group_subtable", "select goe_1.properties. from events", 24, ["group_1_value"]),+ ("groups_table", "select properties. from groups", 18, ["group_0_value", "group_1_value"]),+ ]+ )+ def test_autocomplete_group_properties(self, _name: str, query: str, cursor: int, expected: list[str]):+ for group_type_index in (0, 1):+ PropertyDefinition.objects.create(+ team=self.team,+ name=f"group_{group_type_index}_value",+ property_type="String",+ type=PropertyDefinition.Type.GROUP,+ group_type_index=group_type_index,+ )++ results = self._select(query=query, start=cursor, end=cursor)+ assert [suggestion.label for suggestion in results.suggestions] == expected+def test_autocomplete_lazy_join(self):query = "select pdi. from events"results = self._select(query=query, start=11, end=11)