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(posthog-ai): Fix search tool crash for accounts kind (#62755)

Arthur Moreira de Deusd6db20b8202d
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.py
index 957ea5d76e95..ad48524a55f7 100644
--- a/ee/hogai/context/entity_search/context.py
+++ b/ee/hogai/context/entity_search/context.py
@@ -1,9 +1,10 @@
+from collections.abc import Iterable, Mapping
from datetime import timedelta
from enum import StrEnum
from typing import Any, Literal
from django.conf import settings
-from django.db.models import Max
+from django.db.models import Max, Q, QuerySet
from django.utils import timezone
from pydantic import ValidationError
@@ -11,6 +12,7 @@ from pydantic import ValidationError
from posthog.schema import ArtifactContentType, InsightVizNode
from posthog.api.search import (
+ LIMIT as SEARCH_LIMIT,
EntityConfig,
search_entities as search_entities_fts,
)
@@ -166,14 +168,28 @@ class EntitySearchContext:
if entity_types == "all":
entity_types = set(ENTITY_MAP.keys())
- results, counts, _ = await database_sync_to_async(search_entities_fts, thread_sensitive=False)(
- entity_types,
- query,
- self._team.project_id,
- self, # type: ignore
- ENTITY_MAP,
- )
- assert counts is not None
+ results: list[dict] = []
+ counts: dict[str, int | None] = {}
+
+ if "account" in entity_types:
+ # Account uses a fail-closed manager and is not in ENTITY_MAP, so it can't go through the shared FTS path
+ entity_types = entity_types - {"account"}
+ account_results, account_count = await self._search_accounts(query)
+ results.extend(account_results)
+ counts["account"] = account_count
+
+ if entity_types:
+ fts_results, fts_counts, _ = await database_sync_to_async(search_entities_fts, thread_sensitive=False)(
+ entity_types,
+ query,
+ self._team.project_id,
+ self, # type: ignore
+ ENTITY_MAP,
+ )
+ assert fts_counts is not None
+ results.extend(fts_results)
+ counts.update(fts_counts)
+
return results, counts
async def list_entities(
@@ -343,18 +359,17 @@ class EntitySearchContext:
return all_entities, total_count
- async def _list_accounts(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
- """List customer accounts, newest first. Uses the unscoped manager since Account is fail-closed."""
- return await database_sync_to_async(self._list_accounts_sync, thread_sensitive=False)(limit, offset)
-
- def _list_accounts_sync(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
- queryset = self.user_access_control.filter_queryset_by_access_level(
- Account.objects.unscoped().filter(team=self._team).order_by("-created_at")
+ def _accounts_queryset(self) -> QuerySet[Account]:
+ """Base accounts queryset. Uses the unscoped manager since Account is fail-closed."""
+ if not self.user_access_control.check_access_level_for_resource("account", "viewer"):
+ return Account.objects.unscoped().none()
+ return self.user_access_control.filter_queryset_by_access_level(
+ Account.objects.unscoped().filter(team=self._team)
)
- total_count = queryset.count()
- accounts = list(queryset[offset : offset + limit].values("id", "name", "external_id"))
- all_entities: list[dict[str, Any]] = [
+ @staticmethod
+ def _account_entities(accounts: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ return [
{
"type": "account",
"result_id": str(account["id"]),
@@ -362,7 +377,26 @@ class EntitySearchContext:
}
for account in accounts
]
- return all_entities, total_count
+
+ async def _search_accounts(self, query: str) -> tuple[list[dict[str, Any]], int]:
+ """Search accounts by name or external id."""
+ return await database_sync_to_async(self._search_accounts_sync, thread_sensitive=False)(query)
+
+ def _search_accounts_sync(self, query: str) -> tuple[list[dict[str, Any]], int]:
+ queryset = self._accounts_queryset().filter(Q(name__icontains=query) | Q(external_id__icontains=query))
+ total_count = queryset.count()
+ accounts = list(queryset.order_by("name")[:SEARCH_LIMIT].values("id", "name", "external_id"))
+ return self._account_entities(accounts), total_count
+
+ async def _list_accounts(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
+ """List customer accounts, newest first."""
+ return await database_sync_to_async(self._list_accounts_sync, thread_sensitive=False)(limit, offset)
+
+ def _list_accounts_sync(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
+ queryset = self._accounts_queryset().order_by("-created_at")
+ total_count = queryset.count()
+ accounts = list(queryset[offset : offset + limit].values("id", "name", "external_id"))
+ return self._account_entities(accounts), total_count
def _get_entity_row_values(self, result: dict, extra_columns: list[str], include_type: bool) -> list[str]:
"""
diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.py
index 3ddf480177ec..229362f8066e 100644
--- a/ee/hogai/context/entity_search/test/test_context.py
+++ b/ee/hogai/context/entity_search/test/test_context.py
@@ -5,8 +5,12 @@ from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
from django.conf import settings
from django.utils import timezone
+from asgiref.sync import sync_to_async
from parameterized import parameterized
+from posthog.constants import AvailableFeature
+from posthog.models import Team
+
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
from products.customer_analytics.backend.models import Account
@@ -18,6 +22,7 @@ from products.surveys.backend.models import Survey
from ee.hogai.context import AssistantContextManager
from ee.hogai.context.entity_search import EntitySearchContext
+from ee.models.rbac.access_control import AccessControl
class TestEntitySearchContext(NonAtomicBaseTest):
@@ -400,6 +405,80 @@ class TestEntitySearchContext(NonAtomicBaseTest):
assert entities == []
assert total == 0
+ async def test_search_entities_account_by_partial_name(self):
+ account = await Account.objects.unscoped().acreate(team=self.team, name="Globex", external_id="globex-1")
+ await Account.objects.unscoped().acreate(team=self.team, name="Acme Corp", external_id="acme-1")
+
+ results, counts = await self.context.search_entities({"account"}, "glob")
+
+ assert len(results) == 1
+ assert results[0]["type"] == "account"
+ assert results[0]["result_id"] == str(account.id)
+ assert results[0]["extra_fields"]["name"] == "Globex"
+ assert results[0]["extra_fields"]["external_id"] == "globex-1"
+ assert counts["account"] == 1
+
+ async def test_search_entities_account_by_external_id(self):
+ account = await Account.objects.unscoped().acreate(team=self.team, name="Globex", external_id="0190da51-0b0e")
+ await Account.objects.unscoped().acreate(team=self.team, name="Acme Corp", external_id="acme-1")
+
+ results, counts = await self.context.search_entities({"account"}, "0190da51")
+
+ assert len(results) == 1
+ assert results[0]["result_id"] == str(account.id)
+ assert counts["account"] == 1
+
+ async def test_search_entities_account_excludes_other_teams(self):
+ other_team = await sync_to_async(lambda: Team.objects.create(organization=self.organization))()
+ await Account.objects.unscoped().acreate(team=other_team, name="Globex", external_id="globex-1")
+
+ results, counts = await self.context.search_entities({"account"}, "globex")
+
+ assert results == []
+ assert counts["account"] == 0
+
+ async def test_search_entities_account_no_match(self):
+ await Account.objects.unscoped().acreate(team=self.team, name="Acme Corp", external_id="acme-1")
+
+ results, counts = await self.context.search_entities({"account"}, "globex")
+
+ assert results == []
+ assert counts["account"] == 0
+
+ def _deny_customer_analytics_access(self):
+ AccessControl.objects.create(team=self.team, resource="customer_analytics", access_level="none")
+ self.organization.available_product_features.append({"key": AvailableFeature.ACCESS_CONTROL}) # type: ignore[union-attr]
+ self.organization.save()
+
+ async def test_search_entities_account_denied_resource_access(self):
+ await Account.objects.unscoped().acreate(team=self.team, name="Globex", external_id="globex-1")
+ await sync_to_async(self._deny_customer_analytics_access)()
+
+ results, counts = await self.context.search_entities({"account"}, "globex")
+
+ assert results == []
+ assert counts["account"] == 0
+
+ async def test_list_entities_account_denied_resource_access(self):
+ await Account.objects.unscoped().acreate(team=self.team, name="Globex", external_id="globex-1")
+ await sync_to_async(self._deny_customer_analytics_access)()
+
+ entities, total = await self.context.list_entities("account", limit=10, offset=0)
+
+ assert entities == []
+ assert total == 0
+
+ async def test_search_entities_account_combined_with_fts_kinds(self):
+ await Account.objects.unscoped().acreate(team=self.team, name="Globex", external_id="globex-1")
+ await Dashboard.objects.acreate(team=self.team, name="Globex dashboard", deleted=False, created_by=self.user)
+
+ results, counts = await self.context.search_entities({"account", "dashboard"}, "globex")
+
+ result_types = {r["type"] for r in results}
+ assert result_types == {"account", "dashboard"}
+ assert counts["account"] == 1
+ assert counts["dashboard"] == 1
+
async def test_list_entities_pagination(self):
for i in range(5):
insight = await Insight.objects.acreate(
diff --git a/ee/hogai/tools/full_text_search/test/test_tool.py b/ee/hogai/tools/full_text_search/test/test_tool.py
index e29ad22c1c4e..f920d244cf16 100644
--- a/ee/hogai/tools/full_text_search/test/test_tool.py
+++ b/ee/hogai/tools/full_text_search/test/test_tool.py
@@ -3,6 +3,8 @@ from unittest.mock import ANY, patch
from langchain_core.runnables import RunnableConfig
+from products.customer_analytics.backend.models import Account
+
from ee.hogai.context import AssistantContextManager
from ee.hogai.context.entity_search.context import ENTITY_MAP
from ee.hogai.core.shared_prompts import HYPERLINK_USAGE_INSTRUCTIONS
@@ -102,3 +104,11 @@ class TestEntitySearchToolkit(NonAtomicBaseTest):
result = await self.toolkit.execute(query="test query", search_kind="invalid_type") # type: ignore
assert "Invalid entity kind: invalid_type. Please provide a valid entity kind for the tool." in result
+
+ async def test_search_accounts_end_to_end(self):
+ await Account.objects.unscoped().acreate(team=self.team, name="Globex", external_id="globex-1")
+
+ result = await self.toolkit.execute(query="globex", search_kind=EntityKind.ACCOUNTS)
+
+ assert "Globex" in result
+ assert "globex-1" in result