Skip to content

: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.

fix(taxonomy): look up definitions by name through the project key (#107175)

Eli Reismanc6acb9b5ec72
diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
index b7772611dac2..c6c12cbce708 100644
--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
@@ -3,11 +3,16 @@ from textwrap import dedent
import time_machine
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, _create_person
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
-from posthog.schema import CachedActorsPropertyTaxonomyQueryResponse, CachedEventTaxonomyQueryResponse
+from posthog.schema import (
+ ActorsPropertyTaxonomyResponse,
+ CachedActorsPropertyTaxonomyQueryResponse,
+ CachedEventTaxonomyQueryResponse,
+ EventTaxonomyItem,
+)
from posthog.models import Team
from posthog.models.group.util import create_group
@@ -543,6 +548,61 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
assert toolkit.retrieve_event_or_action_property_values("event1", "$virt_is_bot") == "true, false"
+ @patch.object(DummyToolkit, "_retrieve_event_or_action_taxonomy")
+ def test_retrieve_event_or_action_property_values_resolves_sibling_environment_definitions(
+ self, mock_retrieve: MagicMock
+ ) -> None:
+ # The stored definition decides the formatting: found as a String the value is quoted, not found
+ # the toolkit reports the property as missing from the taxonomy.
+ sibling = Team.objects.create(organization=self.organization, project=self.team.project)
+ PropertyDefinition.objects.create(
+ team=sibling,
+ project=self.team.project,
+ type=PropertyDefinition.Type.EVENT,
+ name="sibling_tier",
+ property_type=PropertyType.String,
+ )
+ now = datetime(2024, 1, 1, tzinfo=UTC)
+ mock_retrieve.return_value = (
+ CachedEventTaxonomyQueryResponse(
+ cache_key="test",
+ is_cached=True,
+ last_refresh=now,
+ next_allowed_client_refresh=now,
+ results=[EventTaxonomyItem(property="sibling_tier", sample_count=1, sample_values=["gold"])],
+ timezone="UTC",
+ ),
+ "event event1",
+ )
+ toolkit = DummyToolkit(self.team, self.user)
+
+ self.assertEqual(toolkit.retrieve_event_or_action_property_values("event1", "sibling_tier"), '"gold"')
+
+ @patch("ee.hogai.chat_agent.query_planner.toolkit.ActorsPropertyTaxonomyQueryRunner")
+ def test_retrieve_entity_property_values_resolves_sibling_environment_definitions(
+ self, mock_runner_class: MagicMock
+ ) -> None:
+ sibling = Team.objects.create(organization=self.organization, project=self.team.project)
+ PropertyDefinition.objects.create(
+ team=sibling,
+ project=self.team.project,
+ type=PropertyDefinition.Type.PERSON,
+ name="sibling_tier",
+ property_type=PropertyType.String,
+ )
+ 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=[ActorsPropertyTaxonomyResponse(sample_count=1, sample_values=["gold"])],
+ timezone="UTC",
+ )
+ toolkit = DummyToolkit(self.team, self.user)
+
+ self.assertEqual(toolkit.retrieve_entity_property_values("person", "sibling_tier"), '"gold"')
+
def test_retrieve_event_or_action_properties_when_actions_exist_but_action_id_incorrect(self):
toolkit = DummyToolkit(self.team, self.user)
incorrect_action_id = self.action.id + 999 # Ensure it doesn't exist
diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.py
index d4f561bcfbc8..7731c3659afc 100644
--- a/ee/hogai/chat_agent/query_planner/toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/toolkit.py
@@ -428,9 +428,9 @@ class TaxonomyAgentToolkit:
virtual_definition = get_virtual_property_definition("event_properties", property_name)
property_definition: PropertyDefinitionOrVirtual
try:
- property_definition = PropertyDefinition.objects.get(
- team=self._team, name=property_name, type=PropertyDefinition.Type.EVENT
- )
+ property_definition = PropertyDefinition.objects.alias(
+ effective_project_id=effective_project_id_expr()
+ ).get(effective_project_id=self._team.project_id, name=property_name, type=PropertyDefinition.Type.EVENT)
except PropertyDefinition.DoesNotExist:
if virtual_definition is None:
return f"The property {property_name} does not exist in the taxonomy."
@@ -514,8 +514,10 @@ class TaxonomyAgentToolkit:
else:
prop_type = PropertyDefinition.Type.PERSON
group_type_index = None
- property_definition = PropertyDefinition.objects.get(
- team=self._team,
+ property_definition = PropertyDefinition.objects.alias(
+ effective_project_id=effective_project_id_expr()
+ ).get(
+ effective_project_id=self._team.project_id,
name=property_name,
type=prop_type,
group_type_index=group_type_index,
diff --git a/ee/hogai/chat_agent/taxonomy/test/test_toolkit.py b/ee/hogai/chat_agent/taxonomy/test/test_toolkit.py
index f2c6e9216679..c2f1d533094d 100644
--- a/ee/hogai/chat_agent/taxonomy/test/test_toolkit.py
+++ b/ee/hogai/chat_agent/taxonomy/test/test_toolkit.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -5,12 +7,15 @@ from langchain_core.agents import AgentAction
from parameterized import parameterized
from pydantic import BaseModel
-from posthog.schema import AssistantToolCall
+from posthog.schema import ActorsPropertyTaxonomyQuery, AssistantToolCall
+
+from posthog.models import Team
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from ee.hogai.chat_agent.taxonomy.toolkit import TaxonomyAgentToolkit, TaxonomyToolNotFoundError
from ee.hogai.chat_agent.taxonomy.tools import TaxonomyTool
+from ee.hogai.chat_agent.taxonomy.virtual_properties import PropertyDefinitionOrVirtual
class DummyToolkit(TaxonomyAgentToolkit):
@@ -323,6 +328,46 @@ class TestTaxonomyAgentToolkit(BaseTest):
# Sanitization collapses the newline so a description can't break out of its line.
self.assertIn("<description>Subscription tier of the account</description>", result.result)
+ @parameterized.expand(
+ [
+ (
+ "entity_lookup",
+ PropertyDefinition.Type.PERSON,
+ lambda toolkit: vars(TaxonomyAgentToolkit)["_get_definitions_for_entity"].func(
+ toolkit, "person", ["sibling_tier"], ActorsPropertyTaxonomyQuery(properties=["sibling_tier"])
+ ),
+ ),
+ (
+ "event_or_action_lookup",
+ PropertyDefinition.Type.EVENT,
+ lambda toolkit: vars(TaxonomyAgentToolkit)["_get_definitions_for_event_or_action"].func(
+ toolkit, ["sibling_tier"]
+ ),
+ ),
+ ]
+ )
+ def test_property_definitions_resolve_across_sibling_environments(
+ self,
+ _name: str,
+ definition_type: PropertyDefinition.Type,
+ lookup: Callable[[TaxonomyAgentToolkit], dict[str, PropertyDefinitionOrVirtual]],
+ ) -> None:
+ # Both lookups are `database_sync_to_async(thread_sensitive=False)`, which runs them on another thread and
+ # connection. The wrapper's `.func` runs them on the test's connection, the only one that sees its rows.
+ sibling = Team.objects.create(organization=self.organization, project=self.team.project)
+ PropertyDefinition.objects.create(
+ team=sibling,
+ project=self.team.project,
+ type=definition_type,
+ name="sibling_tier",
+ property_type="String",
+ )
+
+ definition = lookup(self.toolkit)["sibling_tier"]
+
+ assert isinstance(definition, PropertyDefinition)
+ self.assertEqual(definition.property_type, "String")
+
@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"}
diff --git a/ee/hogai/chat_agent/taxonomy/toolkit.py b/ee/hogai/chat_agent/taxonomy/toolkit.py
index defb61b9a7db..5c9c0849240d 100644
--- a/ee/hogai/chat_agent/taxonomy/toolkit.py
+++ b/ee/hogai/chat_agent/taxonomy/toolkit.py
@@ -544,8 +544,10 @@ class TaxonomyAgentToolkit:
)
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]
+ qs = PropertyDefinition.objects.alias(effective_project_id=effective_project_id_expr()).filter(
+ effective_project_id=self._team.project_id,
+ type=PropertyDefinition.Type.EVENT,
+ name__in=[item.property for item in response.results],
)
property_definitions = [prop async for prop in qs]
property_to_type = {
@@ -724,8 +726,10 @@ class TaxonomyAgentToolkit:
prop_type = PropertyDefinition.Type.PERSON
group_type_index = None
- property_definitions = PropertyDefinition.objects.filter(
- team=self._team,
+ property_definitions = PropertyDefinition.objects.alias(
+ effective_project_id=effective_project_id_expr()
+ ).filter(
+ effective_project_id=self._team.project_id,
name__in=property_names,
type=prop_type,
group_type_index=group_type_index,
@@ -803,10 +807,10 @@ class TaxonomyAgentToolkit:
@database_sync_to_async(thread_sensitive=False)
def _get_definitions_for_event_or_action(self, property_names: list[str]) -> dict[str, PropertyDefinitionOrVirtual]:
- definitions = {
+ definitions: dict[str, PropertyDefinition] = {
prop.name: prop
- for prop in PropertyDefinition.objects.filter(
- team=self._team,
+ for prop in PropertyDefinition.objects.alias(effective_project_id=effective_project_id_expr()).filter(
+ effective_project_id=self._team.project_id,
name__in=property_names,
type=PropertyDefinition.Type.EVENT,
)
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
index de00b4293dd5..0d0e9970caed 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
@@ -4,7 +4,8 @@ from dataclasses import dataclass
from datetime import UTC, datetime, timedelta, tzinfo
from typing import Optional, Union
-from django.db.models import F, Q
+from django.db.models import BigIntegerField, F, Q
+from django.db.models.functions import Coalesce
import structlog
from pydantic import ValidationError
@@ -494,13 +495,16 @@ def _select_relevant_events(
def _event_property_names(team: Team, events: list[str], per_event_limit: int) -> dict[str, list[str]]:
- # One indexed (team, event) query. Without it the planner gets no event-property schema and guesses
+ # One indexed (project, event) query. Without it the planner gets no event-property schema and guesses
# property names — the top cause of InternalHogQLError.
if not events:
return {}
by_event: dict[str, list[str]] = {}
rows = (
- EventProperty.objects.filter(team_id=team.pk, event__in=events)
+ EventProperty.objects.alias(
+ effective_project_id=Coalesce("project_id", "team_id", output_field=BigIntegerField())
+ )
+ .filter(effective_project_id=team.project_id, event__in=events)
.order_by("event", "property")
# DB-tier backstop: a property-heavy event can otherwise pull its entire row set into Python
# before the per-event cap below applies. Caps total rows read; rows are ordered by event name,
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py
index 287f874b43eb..61023b2d43af 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py
@@ -375,12 +375,25 @@ class TestEventPropertyNames(APIBaseTest):
def test_empty_for_no_events(self) -> None:
assert _event_property_names(self.team, [], per_event_limit=15) == {}
- def test_excludes_other_teams_properties(self) -> None:
- other_team = Team.objects.create(organization=self.organization, name="other")
- EventProperty.objects.create(team=other_team, event="export created", property="leaked")
+ @parameterized.expand(
+ [
+ ("other_project", False, ["mine"]),
+ ("sibling_environment", True, ["from_other", "mine"]),
+ ]
+ )
+ def test_reads_properties_across_the_project_only(
+ self, _name: str, same_project: bool, expected: list[str]
+ ) -> None:
+ if same_project:
+ other_team = Team.objects.create(organization=self.organization, project=self.team.project, name="other")
+ else:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ EventProperty.objects.create(
+ team=other_team, project=other_team.project, event="export created", property="from_other"
+ )
EventProperty.objects.create(team=self.team, event="export created", property="mine")
- assert _event_property_names(self.team, ["export created"], per_event_limit=15) == {"export created": ["mine"]}
+ assert _event_property_names(self.team, ["export created"], per_event_limit=15) == {"export created": expected}
class TestAIWindowConfigProperties:
diff --git a/products/warehouse_sources/backend/facade/person_property_provenance.py b/products/warehouse_sources/backend/facade/person_property_provenance.py
index 936b51c4e4da..23773c7d7917 100644
--- a/products/warehouse_sources/backend/facade/person_property_provenance.py
+++ b/products/warehouse_sources/backend/facade/person_property_provenance.py
@@ -6,7 +6,8 @@ and a mapping/description update from the API stamps it without waiting for the
from collections.abc import Iterable
-from django.db.models import Q
+from django.db.models import BigIntegerField
+from django.db.models.functions import Coalesce
from posthog.models import PropertyDefinition
@@ -62,9 +63,12 @@ def stamp_person_property_provenance(
definition_type = PropertyDefinition.Type.GROUP
definition_group_type_index = group_type_index
- # Property definitions are unique and read by effective project. Include legacy rows whose
- # project_id is null so the conflict-safe insert and the final stamp address the same identity.
- query = PropertyDefinition.objects.filter(Q(project_id=project_id) | Q(project_id__isnull=True, team_id=project_id))
+ # Property definitions are unique and read by effective project, so the conflict-safe insert and the final
+ # stamp address the same identity. The COALESCE also covers legacy rows whose project_id is null, and it matches
+ # the unique index, which an OR of the two columns does not.
+ query = PropertyDefinition.objects.alias(
+ effective_project_id=Coalesce("project_id", "team_id", output_field=BigIntegerField())
+ ).filter(effective_project_id=project_id)
if target == _GROUP_TARGET:
# Group propdefs are keyed per group type, so the index predicate is mandatory.
query = query.filter(type=PropertyDefinition.Type.GROUP, group_type_index=group_type_index)