: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
feat(customer-analytics): match accounts by email in account search (#92788)
Arthur Moreira de Deus02934bd55a3c
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex 94e448d9d3cf..e420ae086717 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -444,7 +444,7 @@ class EntitySearchContext:return f"{max(percentages)}%" if percentages else Noneasync def _search_accounts(self, query: str) -> tuple[list[dict[str, Any]], int]:- """Search accounts by name or external id."""+ """Search accounts by name, external id, known email, or email domain."""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]:diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 7bf8274e014f..095c70b0404a 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -103,7 +103,12 @@ from products.customer_analytics.backend.logic import (feature_requests as _feature_requests_logic,relationships as _relationships_logic,)-from products.customer_analytics.backend.logic.account_filters import InvalidAccountFilter, apply_account_filters+from products.customer_analytics.backend.logic.account_filters import (+ InvalidAccountFilter,+ account_search_q,+ apply_account_filters,+ parse_email_search,+)from products.customer_analytics.backend.logic.account_logo import resolve_logo_domainfrom products.customer_analytics.backend.logic.custom_property_definitions import (apply_option_side_effects,@@ -205,6 +210,32 @@ def _to_account_ref(row: dict) -> contracts.AccountRef:return contracts.AccountRef(id=str(row["id"]), name=row["name"], external_id=row["external_id"])+def _list_account_search_member_external_ids(+ team_id: int, query: str, user_access_control: "UserAccessControl"+) -> tuple[str, ...]:+ email = parse_email_search(query)+ user = user_access_control.user+ if email is None or not user.is_staff:+ return ()++ team = user_access_control.team+ if team is None or team.id != team_id:+ team = Team.objects.get(id=team_id)++ from products.customer_analytics.backend.logic.account_member_search import ( # noqa: PLC0415 # Keeps HogQL off non-email account search imports.+ list_account_external_ids_by_member_email,+ )++ return list_account_external_ids_by_member_email(team=team, user=user, email=email)+++def _get_account_search_q(team_id: int, query: str, user_access_control: "UserAccessControl") -> Q:+ return account_search_q(+ query,+ member_external_ids=_list_account_search_member_external_ids(team_id, query, user_access_control),+ )++def _account_tags(account: Account) -> list[str]:return sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True))@@ -266,14 +297,15 @@ def search_accounts(*,include_ignored: bool = False,) -> tuple[list[contracts.AccountRef], int]:- """Accounts matching `query` by name or external id, access-filtered for the caller.+ """Accounts matching `query` by name, external id, known email, or email domain,+ access-filtered for the caller.Returns `(rows, total_count)` where `total_count` is the pre-limit match count."""queryset = _accounts_queryset(team_id, user_access_control)if not include_ignored:queryset = queryset.filter(ignored_at__isnull=True)- queryset = queryset.filter(Q(name__icontains=query) | Q(external_id__icontains=query))+ queryset = queryset.filter(_get_account_search_q(team_id, query, user_access_control))total_count = queryset.count()rows = list(queryset.order_by("name")[:limit].values("id", "name", "external_id"))return [_to_account_ref(row) for row in rows], total_count@@ -2811,15 +2843,27 @@ def _apply_account_table_filters(queryset: QuerySet[Account],*,team_id: int,+ user_access_control: "UserAccessControl",filters: tuple[contracts.AccountTableFilter, ...],custom_property_display_types: dict[UUID, DisplayType],) -> QuerySet[Account]:+ member_external_ids_by_query: dict[str, tuple[str, ...]] = {}+ for filter_ in filters:+ if isinstance(filter_, contracts.AccountTableSearchFilter):+ query = filter_.query.strip()+ if parse_email_search(query) is not None:+ member_external_ids_by_query[query] = _list_account_search_member_external_ids(+ team_id, query, user_access_control+ )+ break+try:return apply_account_filters(queryset,team_id=team_id,filters=filters,custom_property_display_types=custom_property_display_types,+ member_external_ids_by_query=member_external_ids_by_query,)except InvalidAccountFilter as error:raise InvalidAccountTableColumn(str(error)) from error@@ -2962,6 +3006,7 @@ def query_accounts_metrics(accounts = _apply_account_table_filters(accounts,team_id=team_id,+ user_access_control=user_access_control,filters=filters,custom_property_display_types=custom_property_display_types,)@@ -3050,6 +3095,7 @@ def query_accounts_table(queryset = _apply_account_table_filters(queryset,team_id=team_id,+ user_access_control=user_access_control,filters=filters,custom_property_display_types=custom_property_display_types,)@@ -3191,7 +3237,7 @@ def list_accounts_for_view(queryset = queryset.filter(ignored_at__isnull=True)if search:- queryset = queryset.filter(Q(name__icontains=search) | Q(external_id__icontains=search))+ queryset = queryset.filter(_get_account_search_q(team_id, search, user_access_control))if tags:queryset = queryset.filter(tagged_items__tag__name__in=tags).distinct()diff --git a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.pyindex cded9b7f249b..cd78c8cc9954 100644--- a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py+++ b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py@@ -36,6 +36,7 @@ from posthog.models import Userfrom products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlErrorfrom products.customer_analytics.backend.facade import api, contracts+from products.customer_analytics.backend.logic.account_filters import parse_email_searchACCOUNTS_TABLE_MAX_COLUMNS = 100ACCOUNTS_TABLE_MAX_FILTERS = 50@@ -49,6 +50,25 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])query: AccountsTableQuerycached_response: CachedAccountsTableQueryResponse+ def _has_complete_email_search(self) -> bool:+ return any(+ isinstance(filter_, AccountsTableSearchFilter) and parse_email_search(filter_.query) is not None+ for filter_ in self.query.filters or []+ )++ def requires_fresh_calculation(self) -> bool:+ return self._has_complete_email_search()++ def get_cache_payload(self) -> dict:+ payload = super().get_cache_payload()+ if self._has_complete_email_search():+ user = self.user+ payload["account_member_search_principal"] = {+ "user_id": user.id if isinstance(user, User) else None,+ "is_staff": user.is_staff if isinstance(user, User) else False,+ }+ return payload+def validate_query_runner_access(self, user: User) -> bool:return UserAccessControl(user=user, team=self.team).assert_access_level_for_resource("account", "viewer")@@ -101,6 +121,8 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])query_filters = self.query.filters or []if len(query_filters) > ACCOUNTS_TABLE_MAX_FILTERS:raise ValidationError(f"Account table queries support up to {ACCOUNTS_TABLE_MAX_FILTERS} filters.")+ if sum(isinstance(filter_, AccountsTableSearchFilter) for filter_ in query_filters) > 1:+ raise ValidationError("Account table queries support one search filter.")filters: list[contracts.AccountTableFilter] = []try:diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.pyindex 245e05a6e606..5e5aa13b5252 100644--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py@@ -49,6 +49,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.access_control.backend.models.access_control import AccessControl+from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAGfrom products.customer_analytics.backend.facade import api, contractsfrom products.customer_analytics.backend.hogql_queries.accounts_table_query_runner import (ACCOUNTS_TABLE_MAX_COLUMNS,@@ -448,6 +449,91 @@ class TestAccountsTableQueryRunner(BaseTest):assert [row.id for row in response.results] == [str(active_account.id)]assert str(untagged_account.id) not in {row.id for row in response.results}+ @patch(+ "products.customer_analytics.backend.logic.account_member_search.posthog_feature_flag_enabled",+ return_value=True,+ )+ def test_searches_staff_account_members_by_exact_email(self, _mock_feature_enabled) -> None:+ self.user.is_staff = True+ self.user.save(update_fields=["is_staff"])+ account = create_account(+ team_id=self.team.id,+ name="Member account",+ external_id=str(self.organization.id),+ )+ definition = AccountRelationshipDefinition.objects.unscoped().create(team=self.team, name="CSM")+ AccountRelationship.objects.unscoped().create(+ team=self.team,+ account=account,+ definition=definition,+ user=self.user,+ )++ response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[+ AccountsTableSearchFilter(query=self.user.email.upper()),+ AccountsTableAssignedFilter(),+ ],+ )+ )++ assert [row.id for row in response.results] == [str(account.id)]+ _mock_feature_enabled.assert_called_once_with(+ CUSTOMER_ANALYTICS_CSP_FLAG,+ str(self.user.distinct_id),+ organization_id=self.team.organization_id,+ team_id=self.team.id,+ )++ @parameterized.expand(+ [+ ("name", "acme", False),+ ("domain", "acme.example", False),+ ("partial email", "member@acme", False),+ ("complete email", "[email protected]", True),+ ]+ )+ def test_only_complete_email_search_requires_fresh_calculation(+ self, _name: str, query: str, expected: bool+ ) -> None:+ runner = AccountsTableQueryRunner(+ query=AccountsTableQuery(columns=[], filters=[AccountsTableSearchFilter(query=query)]),+ team=self.team,+ user=self.user,+ )++ assert runner.requires_fresh_calculation() is expected++ def test_complete_email_search_cache_is_partitioned_by_principal(self) -> None:+ query = AccountsTableQuery(+ columns=[],+ filters=[AccountsTableSearchFilter(query="[email protected]")],+ )+ self.user.is_staff = False+ viewer_runner = AccountsTableQueryRunner(query=query, team=self.team, user=self.user)+ viewer_cache_key = viewer_runner.get_cache_key()++ self.user.is_staff = True+ staff_runner = AccountsTableQueryRunner(query=query, team=self.team, user=self.user)+ staff_cache_key = staff_runner.get_cache_key()++ assert viewer_cache_key != staff_cache_key+ assert staff_runner.get_cache_payload()["account_member_search_principal"] == {+ "user_id": self.user.id,+ "is_staff": True,+ }++ @patch("products.customer_analytics.backend.logic.account_member_search.list_account_external_ids_by_member_email")+ def test_non_email_search_skips_account_member_lookup(self, mock_member_lookup) -> None:+ account = create_account(team_id=self.team.id, name="Acme")++ response = self._run(AccountsTableQuery(columns=[], filters=[AccountsTableSearchFilter(query="acme")]))++ assert [row.id for row in response.results] == [str(account.id)]+ mock_member_lookup.assert_not_called()+def test_filters_by_relationship_definition_and_user(self) -> None:csm_account = create_account(team_id=self.team.id, name="CSM")ae_account = create_account(team_id=self.team.id, name="AE")@@ -816,6 +902,14 @@ class TestAccountsTableQueryRunner(BaseTest):))+ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ filters=[AccountsTableSearchFilter(query="first"), AccountsTableSearchFilter(query="second")],+ )+ )+def test_rejects_excessive_custom_property_filter_values(self) -> None:definition = create_custom_property_definition(team_id=self.team.id,diff --git a/products/customer_analytics/backend/logic/account_filters.py b/products/customer_analytics/backend/logic/account_filters.pyindex 980bfcb6d894..c1624f19b136 100644--- a/products/customer_analytics/backend/logic/account_filters.py+++ b/products/customer_analytics/backend/logic/account_filters.py@@ -1,9 +1,12 @@import re+from collections.abc import Collection, Mappingfrom datetime import UTC, datetime, time, timedeltafrom typing import castfrom uuid import UUIDfrom zoneinfo import ZoneInfo+from django.core.exceptions import ValidationError as DjangoValidationError+from django.core.validators import validate_emailfrom django.db.models import Exists, OuterRef, Q, QuerySetfrom django.db.models.fields.json import KeyTextTransformfrom django.utils import timezone@@ -53,6 +56,35 @@ ACCOUNT_DIRECT_FIELDS = {}+def parse_email_search(query: str) -> str | None:+ normalized = query.strip().lower()+ local_part, separator, domain = normalized.partition("@")+ if not separator or not local_part or "." not in domain:+ return None+ try:+ validate_email(normalized)+ except DjangoValidationError:+ return None+ return normalized+++def account_search_q(query: str, *, member_external_ids: Collection[str] = ()) -> Q:+ """Free-text account search over account identity and matching properties."""+ predicate = Q(name__icontains=query) | Q(external_id__icontains=query)+ normalized = query.strip().lower()+ email = parse_email_search(normalized)+ if email is not None:+ predicate |= Q(_properties__known_emails__contains=[email])+ if member_external_ids:+ predicate |= Q(external_id__in=member_external_ids)+ domain = email.rsplit("@", 1)[-1]+ else:+ domain = normalized if "@" not in normalized else ""+ if "." in domain:+ predicate |= Q(_properties__email_domains__contains=[domain])+ return predicate++def _coerce_datetime_filter_value(value: float | bool | str, *, timezone_info: ZoneInfo) -> datetime:if not isinstance(value, str):raise InvalidAccountFilter("Date filters require ISO-8601 or relative date values.")@@ -260,6 +292,7 @@ def apply_account_filters(filters: tuple[contracts.AccountTableFilter, ...],custom_property_display_types: dict[UUID, DisplayType],timezone_info: ZoneInfo | None = None,+ member_external_ids_by_query: Mapping[str, Collection[str]] | None = None,) -> QuerySet[Account]:effective_timezone_info = timezone_info or UTC_TIMEZONEactive_relationships = AccountRelationship.objects.for_team(team_id).filter(@@ -269,7 +302,10 @@ def apply_account_filters(if isinstance(filter_, contracts.AccountTableSearchFilter):query = filter_.query.strip()if query:- queryset = queryset.filter(Q(name__icontains=query) | Q(external_id__icontains=query))+ member_external_ids = (+ member_external_ids_by_query.get(query, ()) if member_external_ids_by_query is not None else ()+ )+ queryset = queryset.filter(account_search_q(query, member_external_ids=member_external_ids))elif isinstance(filter_, contracts.AccountTableTagsFilter):if filter_.tag_names:matching_tags = TaggedItem.objects.filter(diff --git a/products/customer_analytics/backend/logic/account_member_search.py b/products/customer_analytics/backend/logic/account_member_search.pynew file mode 100644index 000000000000..7426e4669f23--- /dev/null+++ b/products/customer_analytics/backend/logic/account_member_search.py@@ -0,0 +1,93 @@+from typing import cast++import structlog++from posthog.hogql import ast+from posthog.hogql.errors import QueryError, ResolutionError, TableAccessDeniedError+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.constants import INTERNAL_BOT_EMAIL_SUFFIX+from posthog.models import OrganizationMembership+from posthog.models.team import Team+from posthog.models.user import User+from posthog.permissions import posthog_feature_flag_enabled++from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAG++logger = structlog.get_logger(__name__)++ACCOUNT_MEMBER_SEARCH_MAX_ORGANIZATIONS = 100+EU_ORGANIZATION_MEMBERS_VIEW = "eu_org_members"+++def _is_account_member_search_enabled(team: Team, user: User) -> bool:+ return user.is_staff and posthog_feature_flag_enabled(+ CUSTOMER_ANALYTICS_CSP_FLAG,+ str(user.distinct_id),+ organization_id=team.organization_id,+ team_id=team.id,+ )+++def _list_us_organization_ids(email: str) -> tuple[str, ...]:+ if email.endswith(INTERNAL_BOT_EMAIL_SUFFIX):+ return ()+ organization_ids = (+ OrganizationMembership.objects.filter(user__email=email, user__is_active=True)+ .order_by("organization_id")+ .values_list("organization_id", flat=True)[:ACCOUNT_MEMBER_SEARCH_MAX_ORGANIZATIONS]+ )+ return tuple(str(organization_id) for organization_id in organization_ids)+++def _list_eu_organization_ids(team: Team, user: User, email: str) -> tuple[str, ...]:+ try:+ with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY):+ response = execute_hogql_query(+ query=f"""+ SELECT DISTINCT organization_id+ FROM {EU_ORGANIZATION_MEMBERS_VIEW}+ WHERE email = {{email}}+ ORDER BY organization_id+ LIMIT {ACCOUNT_MEMBER_SEARCH_MAX_ORGANIZATIONS}+ """,+ placeholders={"email": ast.Constant(value=email)},+ team=team,+ user=user,+ query_type="customer_analytics_account_member_email_lookup",+ )+ except (ResolutionError, TableAccessDeniedError) as error:+ logger.info(+ "account_member_email_lookup_unavailable",+ team_id=team.id,+ error_type=type(error).__name__,+ )+ return ()+ except QueryError as error:+ logger.warning(+ "account_member_email_lookup_failed",+ team_id=team.id,+ error_type=type(error).__name__,+ )+ return ()+ except Exception as error:+ logger.warning(+ "account_member_email_lookup_failed",+ team_id=team.id,+ error_type=type(error).__name__,+ )+ return ()++ rows = cast(list[list[object]], response.results or [])+ return tuple(str(row[0]) for row in rows if row and row[0] is not None)+++def list_account_external_ids_by_member_email(*, team: Team, user: User, email: str) -> tuple[str, ...]:+ if not _is_account_member_search_enabled(team, user):+ return ()++ organization_ids = _list_us_organization_ids(email)+ if organization_ids:+ return organization_ids+ return _list_eu_organization_ids(team, user, email)diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 7012a8b0d611..ddc465aadfdf 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -1531,7 +1531,11 @@ class AccountViewSet(type=OpenApiTypes.STR,location=OpenApiParameter.QUERY,required=False,- description="Case-insensitive substring search across account name and external ID.",+ description=(+ "Case-insensitive substring search across account name and external ID. "+ "A query holding an email address also matches accounts that list it as a known "+ "email, and a query holding a domain matches accounts that own that email domain."+ ),),OpenApiParameter(name="tags",diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex 420c79752db1..40b0fe164164 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -138,16 +138,58 @@ class TestCustomerAnalyticsFacade(BaseTest):facade.get_account_context_data(self.team.id, account_id=str(account.id), user_access_control=uac) is None)- def test_search_accounts_matches_name_and_external_id(self):- create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123")+ @parameterized.expand(+ [+ ("name", "acme", ["Acme Corp"]),+ ("external id", "globex-9", ["Globex"]),+ ("known email", "[email protected]", ["Acme Corp"]),+ ("email domain of an address", "[email protected]", ["Acme Corp"]),+ ("bare email domain", "acme.example", ["Acme Corp"]),+ ("address nobody owns", "[email protected]", []),+ ]+ )+ def test_search_accounts_matches(self, _name: str, query: str, expected_names: list[str]):+ create_account(+ team_id=self.team.id,+ name="Acme Corp",+ external_id="acme-123",+ properties={"email_domains": ["acme.example"], "known_emails": ["[email protected]"]},+ )create_account(team_id=self.team.id, name="Globex", external_id="globex-9")- rows, count = facade.search_accounts(self.team.id, "acme", self._uac(), limit=10)+ rows, count = facade.search_accounts(self.team.id, query, self._uac(), limit=10)++ assert count == len(expected_names)+ assert [r.name for r in rows] == expected_names+ assert all(isinstance(row, contracts.AccountRef) and isinstance(row.id, str) for row in rows)++ @patch(+ "products.customer_analytics.backend.logic.account_member_search.posthog_feature_flag_enabled",+ return_value=True,+ )+ @patch("products.customer_analytics.backend.logic.account_member_search.execute_hogql_query")+ def test_search_accounts_matches_eu_organization_member_email(+ self, mock_execute_hogql_query: MagicMock, _mock_feature_enabled: MagicMock+ ) -> None:+ self.user.is_staff = True+ self.user.save(update_fields=["is_staff"])+ eu_organization_id = str(uuid4())+ account = create_account(+ team_id=self.team.id,+ name="EU member account",+ external_id=eu_organization_id,+ )+ mock_execute_hogql_query.return_value = MagicMock(results=[[eu_organization_id]])++ rows, count = facade.search_accounts(+ self.team.id,+ "[email protected]",+ self._uac(),+ limit=10,+ )assert count == 1- assert [r.name for r in rows] == ["Acme Corp"]- assert isinstance(rows[0], contracts.AccountRef)- assert isinstance(rows[0].id, str)+ assert [row.id for row in rows] == [str(account.id)]def test_search_accounts_excludes_ignored_by_default(self):create_account(team_id=self.team.id, name="Acme Tracked")@@ -470,11 +512,12 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):required_level="viewer",)- def test_list_accounts_for_view_filters_by_search(self):- self._create(name="Acme Corp", external_id="acme-1")+ @parameterized.expand([("name", "acme"), ("email domain", "[email protected]")])+ def test_list_accounts_for_view_filters_by_search(self, _name: str, search: str):+ self._create(name="Acme Corp", external_id="acme-1", properties={"email_domains": ["acme.example"]})self._create(name="Globex", external_id="glx-9")page, count = facade.list_accounts_for_view(- team_id=self.team.id, user_access_control=self._uac(), offset=0, limit=10, search="acme"+ team_id=self.team.id, user_access_control=self._uac(), offset=0, limit=10, search=search)assert count == 1assert [a.name for a in page] == ["Acme Corp"]diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex e65c44c9e57c..7e7a9966cafd 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -64,6 +64,14 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc`accountsLogic.accountsTableQueryPlan` translates selected columns, filters, custom-property display windows, tile filters, and server-side sort into a typed `AccountsTableQuery`. Unsupported saved columns and filters are omitted instead of switching execution engines. `AccountsTable` reads each keyed `AccountsTableRow` directly through `accountsTableCell`; there is no positional-row compatibility transform. Every column can be resized from its header down to 80px. Widths save automatically in one team-scoped local storage dictionary keyed by stable column alias. A column keeps its width when a view hides it, then restores it when another view shows it.+Search matches the account name and external ID as substrings.+A complete email address also matches accounts that list it under `known_emails`.+For staff in organizations with `CUSTOMER_ANALYTICS_CSP`, exact email search resolves active US organization memberships by indexed Postgres email lookup, then falls back to the `eu_org_members` warehouse view when US has no match; organization IDs join to `Account.external_id`.+The member lookup is strictly gated on a valid complete email, so name, ID, partial-email, and bare-domain searches issue no member or warehouse queries.+A domain (bare, or the domain part of a complete address) matches accounts that own it under `email_domains`.+`account_search_q` in `backend/logic/account_filters.py` defines the Postgres predicate, while `backend/logic/account_member_search.py` owns the staff-only member lookup.+The list query, account search endpoint, and agent entity search share both paths.+Ignored accounts (`ignored_at IS NOT NULL`) are excluded from list rows and overview metrics by default. A direct account route sets `includeIgnored` as well as `includeChurned`, so an ignored account still opens by id. `ignored_at` is a selectable account field, but the Accounts UI does not write it.Overview tiles run as a separate metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`; `null` when there are no tiles or while definitions are loading). Count, sum, average, minimum, maximum, median, scaling, and threshold counts execute in Postgres. The "My accounts" checkbox resolves to the current user's explicit ID before either query is built, so shared URLs remain viewer-independent. Two cell shapes matter:diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsxindex 5d5fc1c6e47c..3fae26e150a2 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx@@ -58,7 +58,7 @@ export function AccountsTabFilters(): JSX.Element {<div className="flex flex-wrap gap-2 items-center"><LemonInputtype="search"- placeholder="Search by name or ID..."+ placeholder="Search by name, ID, or email..."value={searchInput}onChange={setSearchInput}size="small"diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 2376eae035e8..0186f5a01dc4 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -3706,7 +3706,7 @@ export type AccountsListParams = {*/ordering?: string/**- * Case-insensitive substring search across account name and external ID.+ * Case-insensitive substring search across account name and external ID. A query holding an email address also matches accounts that list it as a known email, and a query holding a domain matches accounts that own that email domain.*/search?: string/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e2b0c4f52757..4fa94a006ba9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -90755,7 +90755,7 @@ export namespace Schemas {*/ordering?: string;/**- * Case-insensitive substring search across account name and external ID.+ * Case-insensitive substring search across account name and external ID. A query holding an email address also matches accounts that list it as a known email, and a query holding a domain matches accounts that own that email domain.*/search?: string;/**diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex ac2b65cb30bc..82b32bd48aed 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -132,7 +132,12 @@ export const AccountsListQueryParams = () => zod.object({limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),ordering: zod.string().optional().describe("Sort order. Defaults to '-created_at'."),- search: zod.string().optional().describe('Case-insensitive substring search across account name and external ID.'),+ search: zod+ .string()+ .optional()+ .describe(+ 'Case-insensitive substring search across account name and external ID. A query holding an email address also matches accounts that list it as a known email, and a query holding a domain matches accounts that own that email domain.'+ ),tags: zod.string().optional()