: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(max): stop read_taxonomy timing out on large projects (#87270)
posthog[bot]5d550940227e
diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.pyindex d596da8a2cc3..38725e8c36c0 100644--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py@@ -5,8 +5,11 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, _create_personfrom unittest.mock import patch+from parameterized import parameterized+from posthog.schema import CachedActorsPropertyTaxonomyQueryResponse, CachedEventTaxonomyQueryResponse+from posthog.models import Teamfrom posthog.models.group.util import create_groupfrom posthog.models.group_type_mapping import invalidate_group_types_cachefrom posthog.test.test_utils import create_group_type_mapping_without_created_at@@ -111,6 +114,73 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):result,)+ def test_retrieve_entity_properties_pages_person_definitions(self):+ # The person branch used to read every stored definition, so a team with millions of them+ # walked its whole index range. The group branch already paged.+ for i in range(4):+ PropertyDefinition.objects.create(+ team=self.team,+ type=PropertyDefinition.Type.PERSON,+ name=f"person_prop_{i}",+ property_type=PropertyType.String,+ )+ toolkit = DummyToolkit(self.team, self.user)++ result = toolkit.retrieve_entity_properties("person", max_properties=2)++ listed = [name for name in (f"person_prop_{i}" for i in range(4)) if f"- {name}" in result]+ self.assertEqual(len(listed), 2)+ self.assertIn("This list stops at 2 properties and person has more.", result)++ @parameterized.expand(+ [+ ["person", "person"],+ ["group", "group"],+ ]+ )+ def test_retrieve_entity_properties_omits_truncation_note_when_under_limit(self, _name: str, entity: str):+ create_group_type_mapping_without_created_at(+ team=self.team, project_id=self.team.project_id, group_type_index=0, group_type="group"+ )+ invalidate_group_types_cache(self.team.project_id)+ PropertyDefinition.objects.create(+ team=self.team,+ type=PropertyDefinition.Type.PERSON,+ name="only_person_prop",+ property_type=PropertyType.String,+ )+ PropertyDefinition.objects.create(+ team=self.team,+ type=PropertyDefinition.Type.GROUP,+ group_type_index=0,+ name="only_group_prop",+ property_type=PropertyType.String,+ )+ toolkit = DummyToolkit(self.team, self.user)++ result = toolkit.retrieve_entity_properties(entity, max_properties=500)++ self.assertNotIn("This list stops at", result)++ def test_retrieve_entity_properties_notes_truncation_for_groups(self):+ create_group_type_mapping_without_created_at(+ team=self.team, project_id=self.team.project_id, group_type_index=0, group_type="group"+ )+ invalidate_group_types_cache(self.team.project_id)+ for i in range(3):+ PropertyDefinition.objects.create(+ team=self.team,+ type=PropertyDefinition.Type.GROUP,+ group_type_index=0,+ name=f"group_prop_{i}",+ property_type=PropertyType.String,+ )+ toolkit = DummyToolkit(self.team, self.user)++ result = toolkit.retrieve_entity_properties("group", max_properties=1)++ self.assertIn("This list stops at 1 properties and group has more.", result)+def test_retrieve_entity_properties_lists_virtual_properties_without_stored_definitions(self):toolkit = DummyToolkit(self.team, self.user)result = toolkit.retrieve_entity_properties("person")@@ -357,6 +427,37 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):# Virtual properties are surfaced even though they never appear in stored event data.self.assertIn("- $virt_is_bot", prompt)+ def test_fetch_event_property_types_resolves_all_names(self):+ names = [f"prop_{i}" for i in range(5)]+ for name in names:+ PropertyDefinition.objects.create(+ team=self.team, type=PropertyDefinition.Type.EVENT, name=name, property_type=PropertyType.String+ )+ toolkit = DummyToolkit(self.team, self.user)++ resolved = toolkit._fetch_event_property_types(names)++ self.assertEqual(resolved, dict.fromkeys(names, PropertyType.String))++ def test_fetch_event_property_types_resolves_sibling_environment_definitions(self):+ # Definitions are project-scoped: a property defined under a sibling environment of the+ # same project resolves, matching what the taxonomy REST API returns for this team.+ sibling = Team.objects.create(organization=self.organization, project=self.team.project)+ # project is set explicitly, as the production writers do — a definition row with a NULL+ # project_id is scoped to its own team only under COALESCE(project_id, team_id).+ PropertyDefinition.objects.create(+ team=sibling,+ project=self.team.project,+ type=PropertyDefinition.Type.EVENT,+ name="sibling_prop",+ property_type=PropertyType.Numeric,+ )+ toolkit = DummyToolkit(self.team, self.user)++ resolved = toolkit._fetch_event_property_types(["sibling_prop"])++ self.assertEqual(resolved, {"sibling_prop": PropertyType.Numeric})+def test_retrieve_event_or_action_property_values(self):self._create_taxonomy()toolkit = DummyToolkit(self.team, self.user)diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.pyindex 8ddde2df1eca..06d91c69b969 100644--- a/ee/hogai/chat_agent/query_planner/toolkit.py+++ b/ee/hogai/chat_agent/query_planner/toolkit.py@@ -25,7 +25,11 @@ from posthog.taxonomy.property_access import restricted_property_namesfrom posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinitionfrom products.actions.backend.models.action import Action-from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType+from products.event_definitions.backend.models.property_definition import (+ PropertyDefinition,+ PropertyType,+ effective_project_id_expr,+)from ee.hogai.chat_agent.taxonomy.format import enrich_props_with_descriptionsfrom ee.hogai.chat_agent.taxonomy.tools import (@@ -213,15 +217,12 @@ class TaxonomyAgentToolkit:if entity not in ("person", "session", *[g["group_type"] for g in self._groups]):return f"Entity {entity} does not exist in the taxonomy."+ truncated = Falseif entity == "person":restricted = self._restricted_property_names(PropertyDefinition.Type.PERSON)- stored_props = [- p- for p in PropertyDefinition.objects.filter(- team=self._team, type=PropertyDefinition.Type.PERSON- ).values_list("name", "property_type")- if p[0] not in restricted- ]+ stored_props, truncated = self._stored_property_page(+ PropertyDefinition.Type.PERSON, restricted, max_properties+ )stored_props += list_virtual_properties("person_properties", exclude={name for name, _ in stored_props} | restricted)@@ -245,13 +246,9 @@ class TaxonomyAgentToolkit:if group_type_index is None:return f"Group {entity} does not exist in the taxonomy."restricted = self._restricted_property_names(PropertyDefinition.Type.GROUP)- stored_props = [- p- for p in PropertyDefinition.objects.filter(- team=self._team, type=PropertyDefinition.Type.GROUP, group_type_index=group_type_index- ).values_list("name", "property_type")[:max_properties]- if p[0] not in restricted- ]+ stored_props, truncated = self._stored_property_page(+ PropertyDefinition.Type.GROUP, restricted, max_properties, group_type_index=group_type_index+ )stored_props += list_virtual_properties("groups", exclude={name for name, _ in stored_props} | restricted)stored_descriptions = self._get_stored_property_descriptions(PropertyDefinition.Type.GROUP,@@ -263,7 +260,33 @@ class TaxonomyAgentToolkit:if not props:return f"Properties do not exist in the taxonomy for the entity {entity}."- return format_prompt_string(PROPERTIES_EXAMPLE_PROMPT, result=self._generate_properties_output(props))+ result = format_prompt_string(PROPERTIES_EXAMPLE_PROMPT, result=self._generate_properties_output(props))+ if truncated:+ result += (+ f"\n\nThis list stops at {max_properties} properties and {entity} has more. "+ "Ask for a property by name before you treat it as missing."+ )+ return result++ def _stored_property_page(+ self,+ property_type: PropertyDefinition.Type,+ restricted: set[str],+ max_properties: int,+ group_type_index: int | None = None,+ ) -> tuple[list[tuple[str, str | None]], bool]:+ """+ Read one page of stored definitions, and report whether more were left behind.++ Reads one row past the page to detect the overflow. A COUNT would answer the same+ question by walking the team's whole definition range, which is the cost the page+ limit is here to avoid.+ """+ qs = PropertyDefinition.objects.filter(team=self._team, type=property_type)+ if group_type_index is not None:+ qs = qs.filter(group_type_index=group_type_index)+ rows = list(qs.values_list("name", "property_type")[: max_properties + 1])+ return [row for row in rows[:max_properties] if row[0] not in restricted], len(rows) > max_propertiesdef _retrieve_event_or_action_taxonomy(self, event_name_or_action_id: str | int):is_event = isinstance(event_name_or_action_id, str)@@ -287,6 +310,32 @@ class TaxonomyAgentToolkit:)return response, verbose_name+ def _fetch_event_property_types(self, names: list[str]) -> dict[str, str | None]:+ """+ Fetch the stored type for each event property name.++ Filters on COALESCE(project_id, team_id) rather than team_id: no index on this table+ contains (team_id, name), so a plain team_id predicate makes Postgres walk the team's+ entire index range — multi-second to statement-timeout on teams with millions of+ property definitions. The coalesce expression matches the posthog_propdef_proj_uniq+ index (COALESCE(project_id, team_id), name, type, ...), turning the lookup into one+ index seek per name. It is also the same project-level scoping the taxonomy REST API+ applies to this table.++ That index also keys on COALESCE(group_type_index, -1), which this filter leaves open.+ Event definitions never carry a group type index, so each (project, name) resolves to+ one row and the dict build below cannot drop a value.+ """+ return dict(+ PropertyDefinition.objects.alias(effective_project_id=effective_project_id_expr())+ .filter(+ effective_project_id=self._team.project_id,+ type=PropertyDefinition.Type.EVENT,+ name__in=names,+ )+ .values_list("name", "property_type")+ )+def retrieve_event_or_action_properties(self, event_name_or_action_id: str | int) -> str:"""Retrieve properties for an event.@@ -306,13 +355,12 @@ class TaxonomyAgentToolkit:# Intersect properties with their types.restricted = self._restricted_property_names(PropertyDefinition.Type.EVENT)- qs = PropertyDefinition.objects.filter(- team=self._team, type=PropertyDefinition.Type.EVENT, name__in=[item.property for item in response.results]- )property_to_type = {- property_definition.name: property_definition.property_type- for property_definition in qs- if property_definition.name not in restricted+ name: property_type+ for name, property_type in self._fetch_event_property_types(+ [item.property for item in response.results]+ ).items()+ if name not in restricted}props: list[tuple[str, str | None]] = [(item.property, property_to_type.get(item.property))diff --git a/ee/hogai/tools/read_taxonomy/mcp_tool.py b/ee/hogai/tools/read_taxonomy/mcp_tool.pyindex b2a5adb1f26a..9cf7a9a2b1e3 100644--- a/ee/hogai/tools/read_taxonomy/mcp_tool.py+++ b/ee/hogai/tools/read_taxonomy/mcp_tool.py@@ -1,11 +1,22 @@+from django.db import OperationalError++from prometheus_client import Counter+from posthog.sync import database_sync_to_async+from posthog.taxonomy.property_definition_api import is_query_canceledfrom ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkitfrom ee.hogai.mcp_tool import MCPTool, mcp_tool_registry-from ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolRetryableError, MaxToolTransientErrorfrom .core import ReadTaxonomyToolArgs, execute_taxonomy_query+READ_TAXONOMY_TIMED_OUT_COUNTER = Counter(+ "read_taxonomy_timed_out_total",+ "read_taxonomy reads cancelled by the statement timeout.",+ labelnames=["query_kind"],+)+@mcp_tool_registry.register(scopes=["action:read", "property_definition:read", "event_definition:read"])class ReadTaxonomyMCPTool(MCPTool[ReadTaxonomyToolArgs]):@@ -32,3 +43,16 @@ class ReadTaxonomyMCPTool(MCPTool[ReadTaxonomyToolArgs]):return await _execute_query()except ValueError as e:raise MaxToolRetryableError(str(e))+ except OperationalError as e:+ # Only a statement cancelled by statement_timeout (SQLSTATE 57014) is worth a retry.+ # Let connection loss, shutdown, deadlocks, and the like reach the generic handler so+ # they are logged and captured instead of mislabeled as a timeout.+ if not is_query_canceled(e):+ raise+ # The MCP transport answers a MaxToolError without logging or capturing it, so a timeout+ # that reaches the caller as one leaves no trace. Count it here, or the rate this change+ # is meant to drive to zero becomes unmeasurable the moment it stops being an exception.+ READ_TAXONOMY_TIMED_OUT_COUNTER.labels(query_kind=args.query.kind).inc()+ # MaxToolError appends its own retry hint and a period, so this ends bare. The hint for+ # a transient error offers one unchanged retry, so do not suggest narrowing the read.+ raise MaxToolTransientError("Reading the taxonomy timed out. This can happen on large projects") from ediff --git a/ee/hogai/tools/read_taxonomy/test/test_mcp_tool.py b/ee/hogai/tools/read_taxonomy/test/test_mcp_tool.pyindex 855512d5de70..a12b5a353c40 100644--- a/ee/hogai/tools/read_taxonomy/test/test_mcp_tool.py+++ b/ee/hogai/tools/read_taxonomy/test/test_mcp_tool.py@@ -1,5 +1,11 @@from posthog.test.base import NonAtomicBaseTest+from unittest.mock import patch+from django.db import OperationalError++from parameterized import parameterized++from ee.hogai.tool_errors import MaxToolTransientErrorfrom ee.hogai.tools.read_taxonomy.core import ReadEventProperties, ReadEvents, ReadTaxonomyToolArgsfrom ee.hogai.tools.read_taxonomy.mcp_tool import ReadTaxonomyMCPTool@@ -28,6 +34,26 @@ class TestReadTaxonomyMCPTool(NonAtomicBaseTest):self.assertIsNotNone(content)+ @parameterized.expand(+ [+ ["statement timeout is retryable", "57014", MaxToolTransientError],+ ["connection loss is not a timeout", "08006", OperationalError],+ ]+ )+ async def test_operational_error_only_treats_statement_timeout_as_transient(+ self, _name: str, sqlstate: str, expected_exception: type[Exception]+ ):+ error = OperationalError("database failure")+ error.sqlstate = sqlstate # type: ignore[attr-defined]+ with patch(+ "ee.hogai.tools.read_taxonomy.mcp_tool.execute_taxonomy_query",+ side_effect=error,+ ):+ with self.assertRaises(expected_exception):+ await self.tool.execute(+ ReadTaxonomyToolArgs(query={"kind": "event_properties", "event_name": "$pageview"}),+ )+async def test_schema_validates_query(self):validated = self.tool.args_schema.model_validate({"query": {"kind": "events"}})self.assertEqual(validated.query.kind, "events")diff --git a/posthog/taxonomy/property_definition_api.py b/posthog/taxonomy/property_definition_api.pyindex e30bb0633016..2ba834055026 100644--- a/posthog/taxonomy/property_definition_api.py+++ b/posthog/taxonomy/property_definition_api.py@@ -3,9 +3,8 @@ import uuidimport dataclassesfrom typing import Any, Optional, Self, Union, cast-from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, models, router, transaction+from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, router, transactionfrom django.db.models import Manager, QuerySet-from django.db.models.functions import Coalescefrom django.http import Http404from django.shortcuts import get_object_or_404@@ -33,6 +32,8 @@ from posthog.taxonomy.taxonomy import (PROPERTY_NAME_ALIASES_BY_TYPE,)+from products.event_definitions.backend.models.property_definition import effective_project_id_expr+tracer = trace.get_tracer(__name__)# list of all event properties defined in the taxonomy, that don't start with $@@ -813,9 +814,7 @@ class PropertyDefinitionViewSet(except ValueError:raise Http404("Property definition not found.")non_enterprise_property = get_object_or_404(- PropertyDefinition.objects.alias(- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())- ),+ PropertyDefinition.objects.alias(effective_project_id=effective_project_id_expr()),id=id,effective_project_id=self.project_id,)@@ -823,9 +822,7 @@ class PropertyDefinitionViewSet(from ee.models.property_definition import EnterprisePropertyDefinitionenterprise_property = (- EnterprisePropertyDefinition.objects.alias(- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())- )+ EnterprisePropertyDefinition.objects.alias(effective_project_id=effective_project_id_expr()).filter(id=id, effective_project_id=self.project_id).first())@@ -980,9 +977,7 @@ class PropertyDefinitionViewSet(serializer.is_valid(raise_exception=True)event_names = serializer.validated_data["event_names"]- matches = EventProperty.objects.alias(- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())- ).filter(+ matches = EventProperty.objects.alias(effective_project_id=effective_project_id_expr()).filter(effective_project_id=self.project_id,event__in=event_names,property=serializer.validated_data["property_name"],diff --git a/products/event_definitions/backend/models/__init__.py b/products/event_definitions/backend/models/__init__.pyindex ceda9cfe8476..2d8a575cd55f 100644--- a/products/event_definitions/backend/models/__init__.py+++ b/products/event_definitions/backend/models/__init__.py@@ -6,6 +6,7 @@ from .property_definition import (PropertyDefinition,PropertyFormat,PropertyType,+ effective_project_id_expr,)from .schema import EventSchema, SchemaPropertyGroup, SchemaPropertyGroupProperty, SchemaPropertyType@@ -22,4 +23,5 @@ __all__ = ["SchemaPropertyType","PROPERTY_DEFINITIONS_TABLE_SQL","DROP_PROPERTY_DEFINITIONS_TABLE_SQL",+ "effective_project_id_expr",]diff --git a/products/event_definitions/backend/models/property_definition.py b/products/event_definitions/backend/models/property_definition.pyindex 0e5861b4c058..eda8db0dbaa2 100644--- a/products/event_definitions/backend/models/property_definition.py+++ b/products/event_definitions/backend/models/property_definition.py@@ -17,6 +17,20 @@ from products.event_definitions.backend.property_type import PropertyTypePERSON_EMAIL_PROPERTY_NAME = "email"+def effective_project_id_expr() -> Coalesce:+ """+ The project scope this table is indexed by, for `.alias(effective_project_id=...)`.++ It has to stay identical to the leading column of `posthog_propdef_proj_uniq` and of+ `index_property_def_query_proj` below, or a filter on it stops being a seek and becomes a+ range walk. Keep it next to those index definitions for that reason. `EventProperty` carries+ the same pair of columns and the same expression indexes, so it uses this too.++ Returns a new expression per call, so callers never share one instance across querysets.+ """+ return Coalesce(F("project_id"), F("team_id"), output_field=models.BigIntegerField())++class PropertyFormat(models.TextChoices):UnixTimestamp = "unix_timestamp", "Unix Timestamp in seconds"UnixTimestampMilliseconds = (