: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(llma): surface virtual fields to the sql agent (#60627)
posthog[bot]1d017a50854e
diff --git a/ee/hogai/chat_agent/query_planner/nodes.py b/ee/hogai/chat_agent/query_planner/nodes.pyindex 4cef4ea2dbce..783a5a9e62a6 100644--- a/ee/hogai/chat_agent/query_planner/nodes.py+++ b/ee/hogai/chat_agent/query_planner/nodes.py@@ -244,7 +244,7 @@ class QueryPlannerToolsNode(AssistantNode, ABC):"""def run(self, state: AssistantState, config: RunnableConfig) -> PartialAssistantState:- toolkit = TaxonomyAgentToolkit(self._team)+ toolkit = TaxonomyAgentToolkit(self._team, self._user)intermediate_steps = state.intermediate_steps or []action, _output = intermediate_steps[-1]diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.pyindex 7852ea5b288c..5df5d8a96e5b 100644--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py@@ -1,8 +1,11 @@-from datetime import datetime+from datetime import UTC, datetimefrom textwrap import dedentfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, _create_person+from unittest.mock import patch++from posthog.schema import CachedActorsPropertyTaxonomyQueryResponse, CachedEventTaxonomyQueryResponsefrom posthog.models.group.util import create_groupfrom posthog.models.group_type_mapping import invalidate_group_types_cache@@ -76,7 +79,7 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):)def test_retrieve_entity_properties(self):- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)PropertyDefinition.objects.create(team=self.team, type=PropertyDefinition.Type.PERSON, name="test", property_type="String"@@ -94,7 +97,7 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):PropertyDefinition.objects.create(team=self.team, type=PropertyDefinition.Type.GROUP, group_type_index=0, name="test", property_type="Numeric")- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)result = toolkit.retrieve_entity_properties("group")self.assertIn("The data format is as follows:", result)self.assertIn("<Numeric>", result)@@ -108,15 +111,14 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):result,)- def test_retrieve_entity_properties_returns_descriptive_feedback_without_properties(self):- toolkit = DummyToolkit(self.team)- self.assertEqual(- toolkit.retrieve_entity_properties("person"),- "Properties do not exist in the taxonomy for the entity person.",- )+ def test_retrieve_entity_properties_lists_virtual_properties_without_stored_definitions(self):+ toolkit = DummyToolkit(self.team, self.user)+ result = toolkit.retrieve_entity_properties("person")+ self.assertIn("$virt_initial_channel_type", result)+ self.assertIn("$virt_revenue", result)def test_retrieve_entity_property_values(self):- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)self.assertEqual(toolkit.retrieve_entity_property_values("session", "$session_duration"),"30, 146, 2 and many more distinct values.",@@ -164,7 +166,7 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):team=self.team, project_id=self.team.project_id, group_type_index=1, group_type="org")invalidate_group_types_cache(self.team.project_id)- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)PropertyDefinition.objects.create(team=self.team, type=PropertyDefinition.Type.GROUP, group_type_index=0, name="test", property_type="Numeric")@@ -195,6 +197,63 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(toolkit.retrieve_entity_property_values("org", "test"), '"7"')+ def test_retrieve_entity_property_values_virtual_person_property_with_examples(self):+ toolkit = DummyToolkit(self.team, self.user)+ self.assertEqual(+ toolkit.retrieve_entity_property_values("person", "$virt_initial_channel_type"),+ '"Paid Search", "Organic Video", "Direct" and many more distinct values.',+ )++ def test_retrieve_entity_property_values_virtual_property_without_examples(self):+ create_group_type_mapping_without_created_at(+ team=self.team, project_id=self.team.project_id, group_type_index=0, group_type="proj"+ )+ invalidate_group_types_cache(self.team.project_id)+ toolkit = DummyToolkit(self.team, self.user)+ for entity in ("person", "proj"):+ self.assertEqual(+ toolkit.retrieve_entity_property_values(entity, "$virt_mrr"),+ "The property $virt_mrr is a virtual property computed at query time, "+ "so the taxonomy does not have stored sample values.",+ )++ @patch("ee.hogai.chat_agent.query_planner.toolkit.ActorsPropertyTaxonomyQueryRunner")+ def test_retrieve_entity_property_values_virtual_person_property_with_empty_runner_results(self, mock_runner_class):+ now = datetime(2024, 1, 1, tzinfo=UTC)+ mock_runner_class.return_value.run.return_value = CachedActorsPropertyTaxonomyQueryResponse(+ cache_key="test",+ is_cached=True,+ last_refresh=now,+ next_allowed_client_refresh=now,+ results=[],+ timezone="UTC",+ )+ toolkit = DummyToolkit(self.team, self.user)+ self.assertEqual(+ toolkit.retrieve_entity_property_values("person", "$virt_initial_channel_type"),+ '"Paid Search", "Organic Video", "Direct" and many more distinct values.',+ )++ @patch("ee.hogai.chat_agent.query_planner.toolkit.ActorsPropertyTaxonomyQueryRunner")+ def test_retrieve_entity_property_values_virtual_group_property_with_empty_runner_results(self, mock_runner_class):+ now = datetime(2024, 1, 1, tzinfo=UTC)+ mock_runner_class.return_value.run.return_value = CachedActorsPropertyTaxonomyQueryResponse(+ cache_key="test",+ is_cached=True,+ last_refresh=now,+ next_allowed_client_refresh=now,+ results=[],+ timezone="UTC",+ )+ toolkit = DummyToolkit(self.team, self.user)+ # Bypass the personhog-backed _groups lookup so the group entity is recognized.+ toolkit.__dict__["_groups"] = [{"group_type": "proj", "group_type_index": 0}]+ self.assertEqual(+ toolkit.retrieve_entity_property_values("proj", "$virt_mrr"),+ "The property $virt_mrr is a virtual property computed at query time, "+ "so the taxonomy does not have stored sample values.",+ )+def test_group_names(self):create_group_type_mapping_without_created_at(team=self.team, project_id=self.team.project_id, group_type_index=0, group_type="proj"@@ -203,18 +262,18 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):team=self.team, project_id=self.team.project_id, group_type_index=1, group_type="org")invalidate_group_types_cache(self.team.project_id)- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)self.assertEqual(toolkit._entity_names, ["person", "session", "proj", "org"])def test_retrieve_event_properties_returns_descriptive_feedback_without_properties(self):- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)self.assertEqual(toolkit.retrieve_event_or_action_properties("pageview"),"Properties do not exist in the taxonomy for the event pageview.",)def test_empty_events(self):- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)self.assertEqual(toolkit.retrieve_event_or_action_properties("test"),"Properties do not exist in the taxonomy for the event test.",@@ -232,7 +291,7 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):team=self.team,)- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)self.assertEqual(toolkit.retrieve_event_or_action_properties("event1"),"Properties do not exist in the taxonomy for the event event1.",@@ -240,7 +299,7 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):def test_retrieve_event_or_action_properties(self):self._create_taxonomy()- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)for item in ("event1", self.action.id):prompt = toolkit.retrieve_event_or_action_properties(item)self.assertIn("The data format is as follows:", prompt)@@ -256,10 +315,12 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):self.assertIn("<Boolean>", prompt)self.assertIn("- bool", prompt)self.assertIn("</Boolean>", prompt)+ # Virtual properties are surfaced even though they never appear in stored event data.+ self.assertIn("- $virt_is_bot", prompt)def test_retrieve_event_or_action_property_values(self):self._create_taxonomy()- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)for item in ("event1", self.action.id):self.assertIn('"Chrome"', toolkit.retrieve_event_or_action_property_values(item, "$browser"))@@ -273,8 +334,26 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):toolkit.retrieve_event_or_action_property_values(item, "date"), f'"{datetime(2024, 1, 1).isoformat()}"')+ @patch.object(DummyToolkit, "_retrieve_event_or_action_taxonomy")+ def test_retrieve_event_or_action_property_values_accepts_virtual_event_properties(self, mock_retrieve):+ toolkit = DummyToolkit(self.team, self.user)+ now = datetime(2024, 1, 1, tzinfo=UTC)+ mock_retrieve.return_value = (+ CachedEventTaxonomyQueryResponse(+ cache_key="virtual-event-property",+ is_cached=True,+ last_refresh=now,+ next_allowed_client_refresh=now,+ results=[],+ timezone="UTC",+ ),+ "event event1",+ )++ assert toolkit.retrieve_event_or_action_property_values("event1", "$virt_is_bot") == "true, false"+def test_retrieve_event_or_action_properties_when_actions_exist_but_action_id_incorrect(self):- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)incorrect_action_id = self.action.id + 999 # Ensure it doesn't existresult = toolkit.retrieve_event_or_action_properties(incorrect_action_id)@@ -286,14 +365,14 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):def test_retrieve_event_or_action_properties_when_no_actions_exist_and_action_id_incorrect(self):Action.objects.all().delete()- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)incorrect_action_id = 9999result = toolkit.retrieve_event_or_action_properties(incorrect_action_id)self.assertEqual(result, "No actions exist in the project.")def test_enrich_props_with_descriptions(self):- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)res = toolkit._enrich_props_with_descriptions("event", [("$geoip_city_name", "String")])self.assertEqual(len(res), 1)prop, type, description = res[0]@@ -302,7 +381,7 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):self.assertIsNotNone(description)def test_generate_properties_output_replaces_newlines_in_descriptions(self):- toolkit = DummyToolkit(self.team)+ toolkit = DummyToolkit(self.team, self.user)props: list[tuple[str, str | None, str | None]] = [("test_prop", "String", "This is a description\nwith multiple\nlines")]@@ -310,6 +389,38 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):self.assertIn("- test_prop – This is a description with multiple lines", output)self.assertNotIn("description\nwith", output)+ @patch("ee.hogai.chat_agent.query_planner.toolkit.restricted_property_names")+ def test_retrieve_entity_properties_excludes_restricted_properties(self, mock_restricted):+ mock_restricted.return_value = {"secret"}+ PropertyDefinition.objects.create(+ team=self.team, type=PropertyDefinition.Type.PERSON, name="secret", property_type="String"+ )+ PropertyDefinition.objects.create(+ team=self.team, type=PropertyDefinition.Type.PERSON, name="visible", property_type="String"+ )+ toolkit = DummyToolkit(self.team, self.user)+ result = toolkit.retrieve_entity_properties("person")+ self.assertIn("- visible", result)+ self.assertNotIn("- secret", result)++ @patch("ee.hogai.chat_agent.query_planner.toolkit.restricted_property_names")+ def test_retrieve_entity_property_values_hides_restricted_property(self, mock_restricted):+ mock_restricted.return_value = {"secret"}+ PropertyDefinition.objects.create(+ team=self.team, type=PropertyDefinition.Type.PERSON, name="secret", property_type="String"+ )+ toolkit = DummyToolkit(self.team, self.user)+ result = toolkit.retrieve_entity_property_values("person", "secret")+ self.assertIn("does not exist", result)++ @patch("ee.hogai.chat_agent.query_planner.toolkit.restricted_property_names")+ def test_retrieve_event_property_values_hides_restricted_property(self, mock_restricted):+ mock_restricted.return_value = {"$browser"}+ # The restriction guard short-circuits before any taxonomy query, so no stored data is needed.+ toolkit = DummyToolkit(self.team, self.user)+ result = toolkit.retrieve_event_or_action_property_values("event1", "$browser")+ self.assertIn("does not exist", result)+class TestFinalAnswerTool(BaseTest):def test_normalize_plan(self):diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.pyindex 63834d0fe463..3f0485f61bb3 100644--- a/ee/hogai/chat_agent/query_planner/toolkit.py+++ b/ee/hogai/chat_agent/query_planner/toolkit.py@@ -19,12 +19,14 @@ from posthog.event_usage import EventSourcefrom posthog.hogql_queries.ai.actors_property_taxonomy_query_runner import ActorsPropertyTaxonomyQueryRunnerfrom posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQueryRunnerfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Team-from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP+from posthog.models import Team, User+from posthog.taxonomy.property_access import restricted_property_names+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinitionfrom products.actions.backend.models.action import Actionfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType+from ee.hogai.chat_agent.taxonomy.format import enrich_props_with_descriptionsfrom ee.hogai.chat_agent.taxonomy.tools import (ask_user_for_help,retrieve_action_properties,@@ -34,6 +36,15 @@ from ee.hogai.chat_agent.taxonomy.tools import (retrieve_event_properties,retrieve_event_property_values,)+from ee.hogai.chat_agent.taxonomy.virtual_properties import (+ PropertyDefinitionOrVirtual,+ get_virtual_property_definition,+ get_virtual_property_sample_values,+ list_virtual_properties,+ property_is_string_like,+ virtual_group_for_entity,+ virtual_property_no_values_message,+)from ee.hogai.utils.prompt import format_prompt_stringMaxSupportedQueryKind = Literal["trends", "funnel", "retention", "sql"]@@ -92,9 +103,14 @@ Results:class TaxonomyAgentToolkit:_team: Team+ _user: User- def __init__(self, team: Team):+ def __init__(self, team: Team, user: User):self._team = team+ self._user = user++ def _restricted_property_names(self, property_type: PropertyDefinition.Type) -> set[str]:+ return restricted_property_names(self._team, self._user, property_type)@cached_propertydef _groups(self) -> list[dict]:@@ -146,20 +162,7 @@ class TaxonomyAgentToolkit:return "\n".join(output_parts)def _enrich_props_with_descriptions(self, entity: str, props: Iterable[tuple[str, str | None]]):- enriched_props = []- mapping = {- "session": CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"],- "person": CORE_FILTER_DEFINITIONS_BY_GROUP["person_properties"],- "event": CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"],- }- for prop_name, prop_type in props:- description = None- if entity_definition := mapping.get(entity, {}).get(prop_name):- if entity_definition.get("system") or entity_definition.get("ignored_in_assistant"):- continue- description = entity_definition.get("description_llm") or entity_definition.get("description")- enriched_props.append((prop_name, prop_type, description))- return enriched_props+ return enrich_props_with_descriptions(entity, props)def retrieve_entity_properties(self, entity: str, max_properties: int = 500) -> str:"""@@ -170,10 +173,18 @@ class TaxonomyAgentToolkit:return f"Entity {entity} does not exist in the taxonomy."if entity == "person":- qs = PropertyDefinition.objects.filter(team=self._team, type=PropertyDefinition.Type.PERSON).values_list(- "name", "property_type"+ 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 += list_virtual_properties(+ "person_properties", exclude={name for name, _ in stored_props} | restricted)- props = self._enrich_props_with_descriptions("person", qs)+ props = self._enrich_props_with_descriptions("person", stored_props)elif entity == "session":# Session properties are not in the DB.props = self._enrich_props_with_descriptions(@@ -189,10 +200,16 @@ class TaxonomyAgentToolkit:group_type_index = next((g["group_type_index"] for g in self._groups if g["group_type"] == entity), None)if group_type_index is None:return f"Group {entity} does not exist in the taxonomy."- qs = PropertyDefinition.objects.filter(- team=self._team, type=PropertyDefinition.Type.GROUP, group_type_index=group_type_index- ).values_list("name", "property_type")[:max_properties]- props = self._enrich_props_with_descriptions(entity, qs)+ 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 += list_virtual_properties("groups", exclude={name for name, _ in stored_props} | restricted)+ props = self._enrich_props_with_descriptions(entity, stored_props)if not props:return f"Properties do not exist in the taxonomy for the entity {entity}."@@ -238,16 +255,23 @@ class TaxonomyAgentToolkit:return f"Properties do not exist in the taxonomy for the {verbose_name}."# 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}- props = [+ property_to_type = {+ property_definition.name: property_definition.property_type+ for property_definition in qs+ if property_definition.name not in restricted+ }+ props: list[tuple[str, str | None]] = [(item.property, property_to_type.get(item.property))for item in response.results# Exclude properties that exist in the taxonomy, but don't have a type.if item.property in property_to_type]+ # Virtual properties are computed at query time, so they never appear in stored event data.+ props += list_virtual_properties("event_properties", exclude=property_to_type.keys() | restricted)if not props:return f"Properties do not exist in the taxonomy for the {verbose_name}."@@ -285,28 +309,46 @@ class TaxonomyAgentToolkit:return prop_values+ def _format_virtual_property_values(self, property_name: str, property_definition: CoreFilterDefinition) -> str:+ sample_values, sample_count = get_virtual_property_sample_values(property_definition)+ if not sample_values:+ return virtual_property_no_values_message(property_name)+ return self._format_property_values(+ sample_values, sample_count, format_as_string=property_is_string_like(property_definition)+ )+def retrieve_event_or_action_property_values(self, event_name_or_action_id: str | int, property_name: str) -> str:+ # Restricted properties are indistinguishable from non-existent ones, so we don't leak their values.+ if property_name in self._restricted_property_names(PropertyDefinition.Type.EVENT):+ return f"The property {property_name} does not exist in the taxonomy."+ virtual_definition = get_virtual_property_definition("event_properties", property_name)+ property_definition: PropertyDefinitionOrVirtualtry:property_definition = PropertyDefinition.objects.get(team=self._team, name=property_name, type=PropertyDefinition.Type.EVENT)except PropertyDefinition.DoesNotExist:- return f"The property {property_name} does not exist in the taxonomy."+ if virtual_definition is None:+ return f"The property {property_name} does not exist in the taxonomy."+ property_definition = virtual_definitionresponse, verbose_name = self._retrieve_event_or_action_taxonomy(event_name_or_action_id)if not isinstance(response, CachedEventTaxonomyQueryResponse):return f"The {verbose_name} does not exist in the taxonomy."- if not response.results:- return f"Property values for {property_name} do not exist in the taxonomy for the {verbose_name}."- prop = next((item for item in response.results if item.property == property_name), None)+ prop = next((item for item in response.results or [] if item.property == property_name), None)if not prop:+ # Virtual properties never appear in stored event data, so fall back to taxonomy examples.+ if virtual_definition is not None:+ return self._format_virtual_property_values(property_name, virtual_definition)+ if not response.results:+ return f"Property values for {property_name} do not exist in the taxonomy for the {verbose_name}."return f"The property {property_name} does not exist in the taxonomy for the {verbose_name}."return self._format_property_values(prop.sample_values,prop.sample_count,- format_as_string=property_definition.property_type in (PropertyType.String, PropertyType.Datetime),+ format_as_string=property_is_string_like(property_definition),)def _retrieve_session_properties(self, property_name: str) -> str:@@ -341,6 +383,12 @@ class TaxonomyAgentToolkit:if entity == "session":return self._retrieve_session_properties(property_name)++ # Restricted properties are indistinguishable from non-existent ones, so we don't leak their values.+ restricted_type = PropertyDefinition.Type.PERSON if entity == "person" else PropertyDefinition.Type.GROUP+ if property_name in self._restricted_property_names(restricted_type):+ return f"The property {property_name} does not exist in the taxonomy for the entity {entity}."+if entity == "person":query = ActorsPropertyTaxonomyQuery(properties=[property_name], maxPropertyValues=25)elif entity == "event":@@ -353,6 +401,8 @@ class TaxonomyAgentToolkit:groupTypeIndex=group_index, properties=[property_name], maxPropertyValues=25)+ virtual_definition = get_virtual_property_definition(virtual_group_for_entity(entity), property_name)+ property_definition: PropertyDefinitionOrVirtualtry:if query.groupTypeIndex is not None:prop_type = PropertyDefinition.Type.GROUP@@ -370,7 +420,9 @@ class TaxonomyAgentToolkit:group_type_index=group_type_index,)except PropertyDefinition.DoesNotExist:- return f"The property {property_name} does not exist in the taxonomy for the entity {entity}."+ if virtual_definition is None:+ return f"The property {property_name} does not exist in the taxonomy for the entity {entity}."+ property_definition = virtual_definitionwith tags_context(product=Product.MAX_AI,@@ -387,6 +439,8 @@ class TaxonomyAgentToolkit:return f"The entity {entity} does not exist in the taxonomy."if not response.results:+ if virtual_definition is not None:+ return self._format_virtual_property_values(property_name, virtual_definition)return f"Property values for {property_name} do not exist in the taxonomy for the entity {entity}."# TRICKY. Remove when the toolkit supports multiple results.@@ -395,10 +449,14 @@ class TaxonomyAgentToolkit:else:unpacked_results = response.results+ # Virtual properties never appear in stored actor data, so fall back to taxonomy examples.+ if not unpacked_results.sample_values and virtual_definition is not None:+ return self._format_virtual_property_values(property_name, virtual_definition)+return self._format_property_values(unpacked_results.sample_values,unpacked_results.sample_count,- format_as_string=property_definition.property_type in (PropertyType.String, PropertyType.Datetime),+ format_as_string=property_is_string_like(property_definition),)def handle_incorrect_response(self, response: BaseModel) -> str:diff --git a/ee/hogai/chat_agent/taxonomy/format.py b/ee/hogai/chat_agent/taxonomy/format.pyindex d326c5156e97..b3fc609cdb06 100644--- a/ee/hogai/chat_agent/taxonomy/format.py+++ b/ee/hogai/chat_agent/taxonomy/format.py@@ -1,4 +1,4 @@-from collections.abc import Iterable+from collections.abc import Iterable, Sequencefrom typing import Optional# nosemgrep: python.lang.security.use-defused-xml.use-defused-xml (XML generation only, no parsing - no XXE risk)@@ -10,7 +10,10 @@ from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUPdef format_property_values(- property_name: str, sample_values: list, sample_count: Optional[int] = 0, format_as_string: bool = False+ property_name: str,+ sample_values: Sequence[str | int | float],+ sample_count: Optional[int] = 0,+ format_as_string: bool = False,) -> str:if len(sample_values) == 0 or sample_count == 0:data = {@@ -87,9 +90,11 @@ def enrich_props_with_descriptions(entity: str, props: Iterable[tuple[str, str |"person": CORE_FILTER_DEFINITIONS_BY_GROUP["person_properties"],"event": CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"],}+ # Entities other than the well-known ones are group types.+ entity_definitions = mapping.get(entity, CORE_FILTER_DEFINITIONS_BY_GROUP["groups"])for prop_name, prop_type in props:description = None- if entity_definition := mapping.get(entity, {}).get(prop_name):+ if entity_definition := entity_definitions.get(prop_name):if entity_definition.get("system") or entity_definition.get("ignored_in_assistant"):continuedescription = entity_definition.get("description_llm") or entity_definition.get("description")diff --git a/ee/hogai/chat_agent/taxonomy/test/test_entities.py b/ee/hogai/chat_agent/taxonomy/test/test_entities.pyindex cbb7195dc980..124b434b409c 100644--- a/ee/hogai/chat_agent/taxonomy/test/test_entities.py+++ b/ee/hogai/chat_agent/taxonomy/test/test_entities.py@@ -59,10 +59,11 @@ class TestEntities(ClickhouseTestMixin, NonAtomicBaseTest):async def test_retrieve_entity_properties(self):result = await self.toolkit.retrieve_entity_properties_parallel(["person"])- assert (- "<properties><String><prop><name>name</name></prop><prop><name>property_no_values</name></prop></String></properties>"- == result["person"]- )+ assert "<prop><name>name</name></prop>" in result["person"]+ assert "<prop><name>property_no_values</name></prop>" in result["person"]+ # Virtual person properties are surfaced even though they have no stored definitions.+ assert "<name>$virt_initial_channel_type</name>" in result["person"]+ assert "<name>$virt_revenue</name>" in result["person"]async def test_retrieve_entity_properties_entity_not_found(self):result = await self.toolkit.retrieve_entity_properties_parallel(["test"])@@ -71,9 +72,8 @@ class TestEntities(ClickhouseTestMixin, NonAtomicBaseTest):async def test_retrieve_entity_properties_entity_with_group(self):result = await self.toolkit.retrieve_entity_properties_parallel(["organization", "session"])assert "session" in result- assert (- "<properties><String><prop><name>name_group</name></prop></String></properties>" == result["organization"]- )+ assert "<prop><name>name_group</name></prop>" in result["organization"]+ assert "<name>$virt_revenue</name>" in result["organization"]assert "<properties>" in result["session"]async def test_person_property_values_exists(self):@@ -101,6 +101,18 @@ class TestEntities(ClickhouseTestMixin, NonAtomicBaseTest):))+ async def test_person_property_values_virtual(self):+ property_vals = await self.toolkit.retrieve_entity_property_values(+ {"person": ["$virt_initial_channel_type", "$virt_revenue"]}+ )++ # Virtual person properties are computed by the actors taxonomy query, so real values come back.+ values = property_vals["person"]+ assert "$virt_initial_channel_type" in values[0]+ assert "Unknown" in values[0]+ assert "$virt_revenue" in values[1]+ assert "'0'" in values[1]+async def test_person_property_values_mixed(self):result = await self.toolkit._get_entity_names()expected = ["person", "session", "organization", "project"]diff --git a/ee/hogai/chat_agent/taxonomy/test/test_events.py b/ee/hogai/chat_agent/taxonomy/test/test_events.pyindex b1251b3c5746..9cbfa8cc845f 100644--- a/ee/hogai/chat_agent/taxonomy/test/test_events.py+++ b/ee/hogai/chat_agent/taxonomy/test/test_events.py@@ -1,4 +1,9 @@+from datetime import UTC, datetime+from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_event, flush_persons_and_events+from unittest.mock import AsyncMock, patch++from posthog.schema import CachedEventTaxonomyQueryResponsefrom posthog.models.group_type_mapping import invalidate_group_types_cachefrom posthog.test.test_utils import create_group_type_mapping_without_created_at@@ -105,6 +110,26 @@ class TestEvents(ClickhouseTestMixin, NonAtomicBaseTest):property_vals.get("event1", []))+ async def test_events_property_values_virtual_property_without_property_definition(self):+ now = datetime(2024, 1, 1, tzinfo=UTC)+ response = CachedEventTaxonomyQueryResponse(+ cache_key="virtual-event-property",+ is_cached=True,+ last_refresh=now,+ next_allowed_client_refresh=now,+ results=[],+ timezone="UTC",+ )++ with patch.object(+ DummyToolkit,+ "_retrieve_event_or_action_taxonomy",+ AsyncMock(return_value=(response, "event event1")),+ ):+ property_vals = await self.toolkit.retrieve_event_or_action_property_values({"event1": ["$virt_is_bot"]})++ assert property_vals == {"event1": ["property: $virt_is_bot\nvalues:\n- 'true'\n- 'false'\n"]}+async def test_events_property_values_action_values_not_found(self):result = await self.toolkit._get_entity_names()expected = ["person", "session", "organization", "project"]@@ -147,10 +172,13 @@ class TestEvents(ClickhouseTestMixin, NonAtomicBaseTest):result = await self.toolkit.retrieve_event_or_action_properties_parallel([232, "event1"])assert "event1" in result+ assert "<prop><name>id</name></prop>" in result["event1"]assert (- "<properties><String><prop><name>id</name></prop><prop><name>$browser</name><description>Name of the browser the user has used.</description></prop></String></properties>"- == result["event1"]+ "<prop><name>$browser</name><description>Name of the browser the user has used.</description></prop>"+ in result["event1"])+ # Virtual event properties are surfaced even though they never appear in stored event data.+ assert "<name>$virt_is_bot</name>" in result["event1"]assert "<properties>" in result["232"]async def test_retrieve_event_or_action_properties_action_no_properties(self):diff --git a/ee/hogai/chat_agent/taxonomy/test/test_groups.py b/ee/hogai/chat_agent/taxonomy/test/test_groups.pyindex bc0e57cca88b..bb67a72a34a0 100644--- a/ee/hogai/chat_agent/taxonomy/test/test_groups.py+++ b/ee/hogai/chat_agent/taxonomy/test/test_groups.py@@ -112,10 +112,11 @@ class TestGroups(ClickhouseTestMixin, NonAtomicBaseTest):async def test_retrieve_entity_properties_group(self):result = await self.toolkit.retrieve_entity_properties_parallel(["organization"])- assert (- "<properties><String><prop><name>name</name></prop><prop><name>industry</name></prop><prop><name>name_group</name></prop></String></properties>"- == result["organization"]- )+ for name in ("name", "industry", "name_group"):+ assert f"<prop><name>{name}</name></prop>" in result["organization"]+ # Virtual group properties are surfaced even though they have no stored definitions.+ assert "<name>$virt_revenue</name>" in result["organization"]+ assert "<name>$virt_mrr</name>" in result["organization"]async def test_retrieve_entity_properties_group_not_found(self):result = await self.toolkit.retrieve_entity_properties_parallel(["test"])@@ -128,13 +129,21 @@ class TestGroups(ClickhouseTestMixin, NonAtomicBaseTest):async def test_retrieve_entity_properties_group_nothing_found(self):result = await self.toolkit.retrieve_entity_properties_parallel(["no_properties"])- assert "Properties do not exist in the taxonomy for the entity no_properties." == result["no_properties"]+ # A group without stored definitions still lists virtual group properties.+ assert "<name>$virt_revenue</name>" in result["no_properties"]+ assert "<name>$virt_mrr</name>" in result["no_properties"]async def test_retrieve_entity_properties_group_mixed(self):result = await self.toolkit.retrieve_entity_properties_parallel(["organization", "no_properties", "project"])assert "organization" in resultassert "<properties>" in result["organization"]- assert "Properties do not exist in the taxonomy for the entity no_properties." == result["no_properties"]+ assert "<name>$virt_revenue</name>" in result["no_properties"]assert "project" in resultassert "<properties>" in result["project"]++ async def test_retrieve_entity_property_values_virtual_group_property(self):+ property_vals = await self.toolkit.retrieve_entity_property_values({"organization": ["$virt_mrr"]})++ # Virtual group properties are computed by the actors taxonomy query, so real values come back.+ assert property_vals["organization"] == ["property: $virt_mrr\nvalues:\n- '0'\n"]diff --git a/ee/hogai/chat_agent/taxonomy/test/test_toolkit.py b/ee/hogai/chat_agent/taxonomy/test/test_toolkit.pyindex aa17c9a77aad..b30a971e5ec1 100644--- a/ee/hogai/chat_agent/taxonomy/test/test_toolkit.py+++ b/ee/hogai/chat_agent/taxonomy/test/test_toolkit.py@@ -5,6 +5,10 @@ from langchain_core.agents import AgentActionfrom parameterized import parameterizedfrom pydantic import BaseModel+from posthog.schema import AssistantToolCall++from products.event_definitions.backend.models.property_definition import PropertyDefinition+from ee.hogai.chat_agent.taxonomy.toolkit import TaxonomyAgentToolkit, TaxonomyToolNotFoundErrorfrom ee.hogai.chat_agent.taxonomy.tools import TaxonomyTool@@ -274,3 +278,24 @@ class TestTaxonomyAgentToolkit(BaseTest):self.assertIn(expected_tool, tool_names)self.assertEqual(len(tools), len(expected_default_tools) + len(expected_custom_tools))++ @patch("ee.hogai.chat_agent.taxonomy.toolkit.restricted_property_names")+ async def test_handle_entity_properties_excludes_restricted(self, mock_restricted):+ mock_restricted.return_value = {"secret"}+ await PropertyDefinition.objects.acreate(+ team=self.team, type=PropertyDefinition.Type.PERSON, name="secret", property_type="String"+ )+ await PropertyDefinition.objects.acreate(+ team=self.team, type=PropertyDefinition.Type.PERSON, name="visible", property_type="String"+ )+ task = AssistantToolCall(id="1", name="retrieve_entity_properties", args={"entity": "person"})+ result = await self.toolkit._handle_entity_properties_task({"task": task})+ self.assertIn("<name>visible</name>", result.result)+ self.assertNotIn("<name>secret</name>", result.result)++ @patch("ee.hogai.chat_agent.taxonomy.toolkit.restricted_property_names")+ async def test_retrieve_multiple_entity_property_values_hides_restricted(self, mock_restricted):+ mock_restricted.return_value = {"secret"}+ results = await self.toolkit._retrieve_multiple_entity_property_values("person", ["secret"])+ self.assertEqual(len(results), 1)+ self.assertIn("No values found for property secret", results[0])diff --git a/ee/hogai/chat_agent/taxonomy/toolkit.py b/ee/hogai/chat_agent/taxonomy/toolkit.pyindex 55a05ee1fe21..11c6694e265b 100644--- a/ee/hogai/chat_agent/taxonomy/toolkit.py+++ b/ee/hogai/chat_agent/taxonomy/toolkit.py@@ -1,5 +1,5 @@import asyncio-from collections.abc import Iterable+from collections.abc import Iterable, Sequencefrom functools import cached_propertyfrom typing import Optional, Union, castfrom uuid import uuid4@@ -30,7 +30,8 @@ from posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQufrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Team, Userfrom posthog.sync import database_sync_to_async-from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP+from posthog.taxonomy.property_access import restricted_property_names+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinitionfrom products.actions.backend.models.action import Actionfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType@@ -41,6 +42,17 @@ from ee.hogai.chat_agent.taxonomy.format import (format_properties_yaml,format_property_values,)+from ee.hogai.chat_agent.taxonomy.virtual_properties import (+ PropertyDefinitionOrVirtual,+ VirtualPropertyGroup,+ get_virtual_property_definition,+ get_virtual_property_sample_values,+ list_virtual_properties,+ merge_virtual_property_definitions,+ property_is_string_like,+ virtual_group_for_entity,+ virtual_property_no_values_message,+)from ee.hogai.utils.types.base import AssistantState, BaseStateWithTasks, TaskArtifact, TaskResultfrom ..parallel_task_execution.nodes import BaseTaskExecutorNode, TaskExecutionInputTuple@@ -172,6 +184,10 @@ class TaxonomyAgentToolkit:]return entities+ @database_sync_to_async(thread_sensitive=False)+ def _restricted_property_names(self, property_type: PropertyDefinition.Type) -> set[str]:+ return restricted_property_names(self._team, self._user, property_type)+@database_sync_to_async(thread_sensitive=False)def _get_groups(self) -> list[dict]:return self._groups@@ -188,10 +204,22 @@ class TaxonomyAgentToolkit:return enrich_props_with_descriptions(entity, props)def _format_property_values(- self, property_name: str, sample_values: list, sample_count: Optional[int] = 0, format_as_string: bool = False+ self,+ property_name: str,+ sample_values: Sequence[str | int | float],+ sample_count: Optional[int] = 0,+ format_as_string: bool = False,) -> str:return format_property_values(property_name, sample_values, sample_count, format_as_string)+ def _format_virtual_property_values(self, property_name: str, property_definition: CoreFilterDefinition) -> str:+ sample_values, sample_count = get_virtual_property_sample_values(property_definition)+ if not sample_values:+ return virtual_property_no_values_message(property_name)+ return self._format_property_values(+ property_name, sample_values, sample_count, format_as_string=property_is_string_like(property_definition)+ )+def _retrieve_session_properties(self, property_name: str) -> str:"""Sessions properties example property values are hardcoded.@@ -337,6 +365,21 @@ class TaxonomyAgentToolkit:for property_name in property_names:results.append(self._retrieve_session_properties(property_name))return results++ # Restricted properties are indistinguishable from non-existent ones, so we don't leak their values.+ prop_type = PropertyDefinition.Type.PERSON if entity == "person" else PropertyDefinition.Type.GROUP+ restricted = await self._restricted_property_names(prop_type)+ if restricted:+ allowed_names = []+ for property_name in property_names:+ if property_name in restricted:+ results.append(TaxonomyErrorMessages.property_values_not_found(property_name, entity))+ else:+ allowed_names.append(property_name)+ if not allowed_names:+ return results+ property_names = allowed_names+groups = await self._get_groups()query = self._build_query(entity, property_names, groups)if query is None:@@ -347,9 +390,13 @@ class TaxonomyAgentToolkit:results.append(TaxonomyErrorMessages.entity_not_found(entity))return results+ virtual_group = virtual_group_for_entity(entity)if not property_values_response.results:for property_name in property_names:- results.append(TaxonomyErrorMessages.property_values_not_found(property_name, entity))+ if virtual_definition := get_virtual_property_definition(virtual_group, property_name):+ results.append(self._format_virtual_property_values(property_name, virtual_definition))+ else:+ results.append(TaxonomyErrorMessages.property_values_not_found(property_name, entity))return resultsif isinstance(property_values_response.results, list):@@ -357,13 +404,13 @@ class TaxonomyAgentToolkit:else:property_values_results = [property_values_response.results]- property_definitions: dict[str, PropertyDefinition] = await self._get_definitions_for_entity(+ property_definitions: dict[str, PropertyDefinitionOrVirtual] = await self._get_definitions_for_entity(entity, property_names, query)results.extend(self._process_property_values(- property_names, property_values_results, property_definitions, entity, is_indexed=True+ property_names, property_values_results, property_definitions, entity, virtual_group, is_indexed=True))return results@@ -454,19 +501,24 @@ class TaxonomyAgentToolkit:status=TaskExecutionStatus.FAILED,)+ restricted = await 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_definitions = [prop async for prop in qs]property_to_type = {- property_definition.name: property_definition.property_type for property_definition in property_definitions+ property_definition.name: property_definition.property_type+ for property_definition in property_definitions+ if property_definition.name not in restricted}- props = [+ props: list[tuple[str, str | None]] = [(item.property, property_to_type.get(item.property))for item in response.results# Exclude properties that exist in the taxonomy, but don't have a type.if item.property in property_to_type]+ # Virtual properties are computed at query time, so they never appear in stored event data.+ props += list_virtual_properties("event_properties", exclude=property_to_type.keys() | restricted)if not props:result = TaxonomyErrorMessages.event_properties_not_found(verbose_name)@@ -508,6 +560,7 @@ class TaxonomyAgentToolkit:continueif entity_to_group_index.values():+ restricted = await self._restricted_property_names(PropertyDefinition.Type.GROUP)# Single query for all group typesgroup_qs = PropertyDefinition.objects.filter(team=self._team,@@ -520,8 +573,13 @@ class TaxonomyAgentToolkit:if entity in entity_to_group_index.keys():group_index = entity_to_group_index[entity]properties = [- (name, prop_type) for name, prop_type, gti in group_qs_definitions if gti == group_index+ (name, prop_type)+ for name, prop_type, gti in group_qs_definitions+ if gti == group_index and name not in restricted]+ properties += list_virtual_properties(+ "groups", exclude={name for name, _ in properties} | restricted+ )result = (self._format_properties(self._enrich_props_with_descriptions(entity, properties))if properties@@ -546,10 +604,14 @@ class TaxonomyAgentToolkit:task = cast(AssistantToolCall, input_dict["task"])entity = task.args["entity"]if entity == "person":+ restricted = await self._restricted_property_names(PropertyDefinition.Type.PERSON)person_qs = PropertyDefinition.objects.filter(team=self._team, type=PropertyDefinition.Type.PERSON).values_list("name", "property_type")- person_definitions = [prop async for prop in person_qs]+ person_definitions = [prop async for prop in person_qs if prop[0] not in restricted]+ person_definitions += list_virtual_properties(+ "person_properties", exclude={name for name, _ in person_definitions} | restricted+ )if person_definitions:result = self._format_properties(self._enrich_props_with_descriptions("person", person_definitions))status = TaskExecutionStatus.COMPLETED@@ -592,7 +654,7 @@ class TaxonomyAgentToolkit:@database_sync_to_async(thread_sensitive=False)def _get_definitions_for_entity(self, entity: str, property_names: list[str], query: ActorsPropertyTaxonomyQuery- ) -> dict[str, PropertyDefinition]:+ ) -> dict[str, PropertyDefinitionOrVirtual]:"""Get property definitions for one entity and properties."""if not property_names:return {}@@ -613,7 +675,8 @@ class TaxonomyAgentToolkit:type=prop_type,group_type_index=group_type_index,)- return {prop.name: prop for prop in property_definitions}+ definitions: dict[str, PropertyDefinition] = {prop.name: prop for prop in property_definitions}+ return merge_virtual_property_definitions(virtual_group_for_entity(entity), definitions, property_names)def _build_query(self, entity: str, properties: list[str], groups: list[dict]@@ -683,8 +746,8 @@ class TaxonomyAgentToolkit:return dict(zip(event_properties.keys(), results))@database_sync_to_async(thread_sensitive=False)- def _get_definitions_for_event_or_action(self, property_names: list[str]) -> dict[str, PropertyDefinition]:- return {+ def _get_definitions_for_event_or_action(self, property_names: list[str]) -> dict[str, PropertyDefinitionOrVirtual]:+ definitions = {prop.name: propfor prop in PropertyDefinition.objects.filter(team=self._team,@@ -692,6 +755,7 @@ class TaxonomyAgentToolkit:type=PropertyDefinition.Type.EVENT,)}+ return merge_virtual_property_definitions("event_properties", definitions, property_names)async def _retrieve_multiple_event_or_action_property_values(self, event_name_or_action_id: str | int, property_names: list[str]@@ -699,12 +763,17 @@ class TaxonomyAgentToolkit:"""Retrieve property values for multiple events/actions and properties efficiently."""results = []try:- definitions_map: dict[str, PropertyDefinition] = await self._get_definitions_for_event_or_action(+ definitions_map: dict[str, PropertyDefinitionOrVirtual] = await self._get_definitions_for_event_or_action(property_names)except PropertyDefinition.DoesNotExist:definitions_map = {}+ # Restricted properties are indistinguishable from non-existent ones, so we don't leak their values.+ # Dropping them from the definitions map makes _process_property_values report them as not found.+ restricted = await self._restricted_property_names(PropertyDefinition.Type.EVENT)+ definitions_map = {name: definition for name, definition in definitions_map.items() if name not in restricted}+response, verbose_name = await self._retrieve_event_or_action_taxonomy(event_name_or_action_id, property_names)if not isinstance(response, CachedEventTaxonomyQueryResponse):@@ -712,7 +781,10 @@ class TaxonomyAgentToolkit:return resultsif not response.results:for property_name in property_names:- results.append(TaxonomyErrorMessages.property_values_not_found(property_name, verbose_name))+ if virtual_definition := get_virtual_property_definition("event_properties", property_name):+ results.append(self._format_virtual_property_values(property_name, virtual_definition))+ else:+ results.append(TaxonomyErrorMessages.property_values_not_found(property_name, verbose_name))return results# Create a map of property name to taxonomy result for efficient lookup@@ -720,7 +792,12 @@ class TaxonomyAgentToolkit:results.extend(self._process_property_values(- property_names, list(taxonomy_results_map.values()), definitions_map, verbose_name, is_indexed=False+ property_names,+ list(taxonomy_results_map.values()),+ definitions_map,+ verbose_name,+ "event_properties",+ is_indexed=False,))@@ -730,8 +807,9 @@ class TaxonomyAgentToolkit:self,property_names: list[str],property_results: list,- property_definitions: dict[str, PropertyDefinition],+ property_definitions: dict[str, PropertyDefinitionOrVirtual],entity_name: str,+ virtual_group: VirtualPropertyGroup,is_indexed: bool = False,) -> list[str]:"""Common logic for processing property values from taxonomy results."""@@ -745,21 +823,24 @@ class TaxonomyAgentToolkit:continueif is_indexed:- if i >= len(property_results):- results.append(TaxonomyErrorMessages.property_not_found(property_name, entity_name))- continue- prop_result = property_results[i]+ prop_result = property_results[i] if i < len(property_results) else Noneelse:prop_result = next((r for r in property_results if r.property == property_name), None)- if prop_result is None:- results.append(TaxonomyErrorMessages.property_not_found(property_name, entity_name))- continue++ # Virtual properties never appear in stored data, so fall back to taxonomy examples.+ virtual_definition = get_virtual_property_definition(virtual_group, property_name)+ if (prop_result is None or not prop_result.sample_values) and virtual_definition is not None:+ results.append(self._format_virtual_property_values(property_name, virtual_definition))+ continue+ if prop_result is None:+ results.append(TaxonomyErrorMessages.property_not_found(property_name, entity_name))+ continueresult = self._format_property_values(property_name,prop_result.sample_values,prop_result.sample_count,- format_as_string=property_definition.property_type in (PropertyType.String, PropertyType.Datetime),+ format_as_string=property_is_string_like(property_definition),)results.append(result)diff --git a/ee/hogai/chat_agent/taxonomy/virtual_properties.py b/ee/hogai/chat_agent/taxonomy/virtual_properties.pynew file mode 100644index 000000000000..e21b22ff2dd7--- /dev/null+++ b/ee/hogai/chat_agent/taxonomy/virtual_properties.py@@ -0,0 +1,77 @@+from collections.abc import Container, Iterable+from typing import Literal++from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinition++from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType++type VirtualPropertyGroup = Literal["event_properties", "person_properties", "groups"]+type PropertyDefinitionOrVirtual = PropertyDefinition | CoreFilterDefinition+++def virtual_group_for_entity(entity: str) -> VirtualPropertyGroup:+ """Map a taxonomy entity name (event, person, or a group type name) to its virtual property group."""+ if entity == "event":+ return "event_properties"+ if entity == "person":+ return "person_properties"+ return "groups"+++def get_virtual_property_definition(group: VirtualPropertyGroup, property_name: str) -> CoreFilterDefinition | None:+ definition = CORE_FILTER_DEFINITIONS_BY_GROUP[group].get(property_name)+ if definition is None or definition.get("virtual") is not True:+ return None+ return definition+++def list_virtual_properties(group: VirtualPropertyGroup, exclude: Container[str] = ()) -> list[tuple[str, str | None]]:+ """(name, type) pairs for the group's virtual properties, for inclusion in property listings."""+ return [+ (name, definition.get("type"))+ for name, definition in CORE_FILTER_DEFINITIONS_BY_GROUP[group].items()+ if definition.get("virtual") is True and name not in exclude+ ]+++def merge_virtual_property_definitions(+ group: VirtualPropertyGroup,+ property_definitions: dict[str, PropertyDefinition],+ property_names: Iterable[str],+) -> dict[str, PropertyDefinitionOrVirtual]:+ merged: dict[str, PropertyDefinitionOrVirtual] = dict(property_definitions)+ for property_name in property_names:+ if property_name in merged:+ continue+ if virtual_definition := get_virtual_property_definition(group, property_name):+ merged[property_name] = virtual_definition+ return merged+++def get_property_definition_type(property_definition: PropertyDefinitionOrVirtual) -> str | None:+ if isinstance(property_definition, PropertyDefinition):+ return property_definition.property_type+ return property_definition.get("type")+++def property_is_string_like(property_definition: PropertyDefinitionOrVirtual) -> bool:+ return get_property_definition_type(property_definition) in (PropertyType.String, PropertyType.Datetime)+++def get_virtual_property_sample_values(+ property_definition: CoreFilterDefinition,+) -> tuple[list[str | int | float], int | None]:+ """Sample values for a virtual property, sourced from the static taxonomy instead of stored data."""+ examples = property_definition.get("examples")+ if examples:+ return examples, None+ if property_definition.get("type") == "Boolean":+ return ["true", "false"], 2+ return [], None+++def virtual_property_no_values_message(property_name: str) -> str:+ return (+ f"The property {property_name} is a virtual property computed at query time, "+ "so the taxonomy does not have stored sample values."+ )diff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.pyindex 035a26eedb46..8b22538f46bc 100644--- a/ee/hogai/tools/read_data/test/test_tool.py+++ b/ee/hogai/tools/read_data/test/test_tool.py@@ -515,6 +515,8 @@ class TestReadDataTool(BaseTest):assert "## Table `persons`" in resultassert "## Table `sessions`" in resultassert "## Table `groups`" in result+ assert "- index (integer, aliased from group_type_index)" in result+ assert "- key (string, aliased from group_key)" in resultassert artifact is Noneasync def test_list_tables_includes_warehouse_tables(self):@@ -734,6 +736,25 @@ class TestReadDataTool(BaseTest):assert "- event (string)" in resultassert "- timestamp (datetime)" in result+ async def test_table_schema_returns_posthog_field_aliases(self):+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))+ context_manager = MagicMock()+ context_manager.check_user_has_billing_access = AsyncMock(return_value=False)+ context_manager.check_has_audit_logs_access = AsyncMock(return_value=False)++ tool = await ReadDataTool.create_tool_class(+ team=self.team,+ user=self.user,+ state=state,+ context_manager=context_manager,+ )++ result, _ = await tool._arun_impl({"kind": "data_warehouse_table", "table_name": "groups"})++ assert "Table `groups` with fields:" in result+ assert "- index (integer, aliased from group_type_index)" in result+ assert "- key (string, aliased from group_key)" in result+async def test_table_schema_returns_error_when_table_not_found(self):"""Test that data_warehouse_table returns an error message for unknown tables."""state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.pyindex b2a9f094c1a5..1dcbd3d036f0 100644--- a/ee/hogai/tools/read_data/tool.py+++ b/ee/hogai/tools/read_data/tool.py@@ -13,6 +13,7 @@ from pydantic import BaseModel, Field, create_modelfrom posthog.schema import (ArtifactContentType,AssistantToolCallMessage,+ DatabaseSchemaField,LLMTrace,NotebookArtifactContent,TraceQuery,@@ -21,6 +22,7 @@ from posthog.schema import (from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Database+from posthog.hogql.database.models import FieldOrTablefrom posthog.models import Team, Userfrom posthog.sync import database_sync_to_async@@ -456,8 +458,9 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):system_table_lines: list[str] = []for table_name, table in serialized.items():system_table_lines.append(f"## Table `{table_name}`")+ raw_fields = database.get_table(table_name).fieldsfor field in table.fields.values():- system_table_lines.append(f"- {field.name} ({field.type})")+ system_table_lines.append(self._format_schema_field(field, raw_fields.get(field.name)))system_table_lines.append("")warehouse_tables = database.get_warehouse_table_names()@@ -505,11 +508,21 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):table = serialized[table_name]lines = [f"Table `{table_name}` with fields:"]+ raw_fields = database.get_table(table_name).fieldsfor field in table.fields.values():- lines.append(f"- {field.name} ({field.type})")+ lines.append(self._format_schema_field(field, raw_fields.get(field.name)))return "\n".join(lines)+ @staticmethod+ def _format_schema_field(field: DatabaseSchemaField, raw_field: FieldOrTable | None) -> str:+ source_name = getattr(raw_field, "name", None)+ alias_suffix = ""+ if isinstance(source_name, str) and source_name and source_name != field.name:+ alias_suffix = f", aliased from {source_name}"++ return f"- {field.name} ({field.type}{alias_suffix})"+async def _read_dashboard(self, dashboard_id: str, execute: bool) -> tuple[str, ToolMessagesArtifact | None]:try:dashboard = (diff --git a/ee/hogai/tools/read_taxonomy/mcp_tool.py b/ee/hogai/tools/read_taxonomy/mcp_tool.pyindex c5040f1f9837..30f28b37d23a 100644--- a/ee/hogai/tools/read_taxonomy/mcp_tool.py+++ b/ee/hogai/tools/read_taxonomy/mcp_tool.py@@ -19,7 +19,7 @@ class ReadTaxonomyMCPTool(MCPTool[ReadTaxonomyToolArgs]):args_schema = ReadTaxonomyToolArgsasync def execute(self, args: ReadTaxonomyToolArgs) -> str:- toolkit = TaxonomyAgentToolkit(self._team)+ toolkit = TaxonomyAgentToolkit(self._team, self._user)try:diff --git a/ee/hogai/tools/read_taxonomy/tool.py b/ee/hogai/tools/read_taxonomy/tool.pyindex 5018c08be264..e0bce40750a3 100644--- a/ee/hogai/tools/read_taxonomy/tool.py+++ b/ee/hogai/tools/read_taxonomy/tool.py@@ -89,7 +89,7 @@ class ReadTaxonomyTool(MaxTool):except ValidationError as e:raise MaxToolRetryableError(str(e))- toolkit = TaxonomyAgentToolkit(self._team)+ toolkit = TaxonomyAgentToolkit(self._team, self._user)try:res = execute_taxonomy_query(validated_query, toolkit, self._team)diff --git a/posthog/taxonomy/property_access.py b/posthog/taxonomy/property_access.pynew file mode 100644index 000000000000..d12d8c0d242a--- /dev/null+++ b/posthog/taxonomy/property_access.py@@ -0,0 +1,20 @@+from posthog.models import PropertyDefinition, Team, User+++def restricted_property_names(team: Team, user: User | None, property_type: PropertyDefinition.Type) -> set[str]:+ """Property names the user may not read for this type, per field-level access control.++ Mirrors PropertyDefinitionViewSet._get_restricted_property_names so taxonomy listings and value+ lookups (including the agent's) honor the same access control as the product property picker —+ otherwise restricted property names and values would still be surfaced. Returns an empty set+ when property access control is not enabled for the team, so this is a cheap no-op for the+ common case.++ Lives in posthog/ (not ee/) so callers in ee can reach it without ee depending on+ products.access_control, which the import boundary forbids.+ """+ # Deferred to keep products.access_control off the module import graph, matching+ # PropertyDefinitionViewSet._get_restricted_property_names.+ from products.access_control.backend.property_access_control import get_restricted_property_names # noqa: PLC0415++ return get_restricted_property_names(team_id=team.id, user=user, property_type=property_type)