: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: resolve $groups from analytics when org membership is cross-region (#62938)
Alex V4c7f8e1bec0d
diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.pyindex 7508591e6242..90ee07ea84be 100644--- a/products/conversations/backend/api/tests/test_events.py+++ b/products/conversations/backend/api/tests/test_events.py@@ -1,15 +1,19 @@import uuid-from posthog.test.base import BaseTest+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import patch+from django.core.cache import cache+from parameterized import parameterizedfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.user import User+from posthog.settings import SITE_URLfrom products.conversations.backend.events import (EVENT_SOURCE,+ _resolve_groups_from_analytics,capture_message_received,capture_message_sent,capture_ticket_assigned,@@ -23,6 +27,8 @@ from products.conversations.backend.models import Ticketclass TestConversationEvents(BaseTest):def setUp(self):super().setUp()+ # The resolved-groups cache is keyed by (team_id, distinct_ids), both reused across tests here.+ cache.clear()self.widget_session_id = str(uuid.uuid4())self.ticket = Ticket.objects.create_with_number(team=self.team,@@ -543,6 +549,153 @@ class TestConversationEvents(BaseTest):assert call_kwargs["process_person_profile"] is Falseassert "$groups" not in call_kwargs["properties"]+ @parameterized.expand(+ [+ ("with_customer", "cus_456"),+ ("without_customer", ""),+ ]+ )+ @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("products.conversations.backend.events.get_group_types_for_project")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_analytics_fallback_groups(+ self, _name, customer_key, mock_get_persons, mock_group_types, mock_hogql, mock_capture+ ):+ """Cross-region account: no membership row in this region's Postgres, org resolved from event $groups."""+ from posthog.models.person.person import Person++ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]+ mock_group_types.return_value = [+ {"group_type": "project", "group_type_index": 0},+ {"group_type": "organization", "group_type_index": 1},+ {"group_type": "customer", "group_type_index": 2},+ ]+ mock_hogql.return_value.results = [["org-eu-123", customer_key]]++ capture_ticket_created(self.ticket)++ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is True+ groups = call_kwargs["properties"]["$groups"]+ assert groups["organization"] == "org-eu-123"+ # instance/project are rebuilt server-side, never taken from the event row+ assert groups["project"] == str(self.team.uuid)+ assert "instance" in groups+ if customer_key:+ assert groups["customer"] == customer_key+ else:+ assert "customer" not in groups++ @parameterized.expand(+ [+ ("no_events", []),+ ("empty_org_key", [["", ""]]),+ ]+ )+ @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("products.conversations.backend.events.get_group_types_for_project")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_analytics_fallback_no_groups(+ self, _name, results, mock_get_persons, mock_group_types, mock_hogql, mock_capture+ ):+ from posthog.models.person.person import Person++ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 1}]+ mock_hogql.return_value.results = results++ capture_ticket_created(self.ticket)++ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is False+ assert "$groups" not in call_kwargs["properties"]++ @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_membership_hit_skips_analytics_fallback(+ self, mock_get_persons, mock_hogql, mock_capture+ ):+ from posthog.models.person.person import Person++ person_org = Organization.objects.create(name="Person Org")+ person_user = User.objects.create(email="[email protected]", distinct_id="customer-123")+ OrganizationMembership.objects.create(user=person_user, organization=person_org)++ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]++ capture_ticket_created(self.ticket)++ mock_hogql.assert_not_called()+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["properties"]["$groups"]["organization"] == str(person_org.id)++ @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("products.conversations.backend.events.get_group_types_for_project")+ @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_email_channel_analytics_fallback_groups(+ self, mock_get_persons, mock_get_by_email, mock_group_types, mock_hogql, mock_capture+ ):+ """Email channel, person found by email, no membership in this region -> org from event $groups."""+ from posthog.models.person.person import Person++ customer_email = "[email protected]"+ mock_get_persons.return_value = []+ person = Person(team_id=self.team.id, is_identified=True)+ person._distinct_ids = ["real-did-1"]+ mock_get_by_email.return_value = {customer_email: person}++ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 0}]+ mock_hogql.return_value.results = [["org-eu-123", ""]]++ ticket = Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id="",+ distinct_id=customer_email,+ channel_source="email",+ anonymous_traits={"name": "Biz", "email": customer_email},+ )++ capture_ticket_created(ticket)++ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is True+ assert call_kwargs["properties"]["$groups"]["organization"] == "org-eu-123"++ @parameterized.expand(+ [+ ("positive", [["org-eu-123", ""]], True),+ ("negative", [], False),+ ]+ )+ @patch("products.conversations.backend.events.capture_internal_routed")+ @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("products.conversations.backend.events.get_group_types_for_project")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_analytics_fallback_result_is_cached(+ self, _name, results, expect_groups, mock_get_persons, mock_group_types, mock_hogql, mock_capture+ ):+ from posthog.models.person.person import Person++ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 0}]+ mock_hogql.return_value.results = results++ capture_ticket_created(self.ticket)+ capture_message_received(self.ticket, "msg-456", "Hello support")++ mock_hogql.assert_called_once()+ assert mock_capture.call_count == 2+ for call in mock_capture.call_args_list:+ if expect_groups:+ assert call.kwargs["properties"]["$groups"]["organization"] == "org-eu-123"+ else:+ assert "$groups" not in call.kwargs["properties"]+@patch("products.conversations.backend.events.capture_internal_routed")def test_capture_ticket_status_changed_system_actor_uses_customer_distinct_id(self, mock_capture):"""System actions (e.g. snooze wake) use the customer's distinct_id, not an actor's."""@@ -566,3 +719,102 @@ class TestConversationEvents(BaseTest):assert call_kwargs["properties"]["actor_type"] == "external"assert call_kwargs["properties"]["actor_id"] is Noneassert call_kwargs["properties"]["actor_email"] is None+++class TestResolveGroupsFromAnalyticsClickHouse(ClickhouseTestMixin, APIBaseTest):+ """End-to-end coverage of the cross-region fallback against real ClickHouse events.++ The fallback exists to recover an org from a customer's analytics events when the+ region-local OrganizationMembership lookup misses. These events carry $group_N but+ deliberately NO $groupidentify — the common case where an app calls+ posthog.group(type, key) without properties — to prove resolution doesn't depend on+ $groupidentify and reads the org/customer group columns by their per-project index.+ """++ def setUp(self):+ super().setUp()+ cache.clear()++ @patch(+ "products.conversations.backend.events.get_group_types_for_project",+ return_value=[+ {"group_type": "project", "group_type_index": 0},+ {"group_type": "organization", "group_type_index": 1},+ {"group_type": "customer", "group_type_index": 2},+ ],+ )+ def test_resolves_groups_from_event_columns_without_groupidentify(self, _mock_group_types):+ # Plain $pageview events (not $groupidentify) stamped with the customer's groups.+ # Org is at index 1, customer at index 2 — proving column selection follows the+ # project's group-type mapping rather than assuming $group_0.+ for _ in range(3):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="eu-user-did",+ properties={"$group_1": "org-eu-123", "$group_2": "cus_456"},+ )+ flush_persons_and_events()++ groups = _resolve_groups_from_analytics(self.team, ["eu-user-did"])++ assert groups == {+ "instance": SITE_URL,+ "project": str(self.team.uuid),+ "organization": "org-eu-123",+ "customer": "cus_456",+ }++ @patch(+ "products.conversations.backend.events.get_group_types_for_project",+ return_value=[+ {"group_type": "project", "group_type_index": 0},+ {"group_type": "organization", "group_type_index": 1},+ ],+ )+ def test_resolves_org_without_customer_group_type(self, _mock_group_types):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="eu-user-did",+ properties={"$group_1": "org-eu-123"},+ )+ flush_persons_and_events()++ groups = _resolve_groups_from_analytics(self.team, ["eu-user-did"])++ assert groups == {"instance": SITE_URL, "project": str(self.team.uuid), "organization": "org-eu-123"}++ @patch(+ "products.conversations.backend.events.get_group_types_for_project",+ return_value=[+ {"group_type": "project", "group_type_index": 0},+ {"group_type": "organization", "group_type_index": 1},+ ],+ )+ def test_no_org_group_on_events_returns_none(self, _mock_group_types):+ # Events exist but never carried an organization group → nothing to recover.+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="eu-user-did",+ properties={"$group_0": "project:1"},+ )+ flush_persons_and_events()++ assert _resolve_groups_from_analytics(self.team, ["eu-user-did"]) is None++ @patch(+ "products.conversations.backend.events.get_group_types_for_project",+ return_value=[{"group_type": "organization", "group_type_index": 1}],+ )+ def test_lookup_is_scoped_to_the_passed_distinct_ids(self, _mock_group_types):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="someone-else",+ properties={"$group_1": "org-other"},+ )+ flush_persons_and_events()++ assert _resolve_groups_from_analytics(self.team, ["eu-user-did"]) is Nonediff --git a/products/conversations/backend/cache.py b/products/conversations/backend/cache.pyindex bbd6c71532ca..426052bdfe17 100644--- a/products/conversations/backend/cache.py+++ b/products/conversations/backend/cache.py@@ -5,6 +5,9 @@ Caches responses to reduce database load from frequent polling.Short TTLs ensure stale data expires quickly without explicit invalidation."""+import json+import hashlib+from django.core.cache import cacheimport structlog@@ -278,3 +281,40 @@ def set_cached_teams_user(tenant_id: str, teams_user_id: str, user_info: dict) -cache.set(key, user_info, timeout=TEAMS_USER_CACHE_TTL)except Exception:logger.warning("conversations_cache_set_error", key=key)+++# Resolved Groups Cache+# Caches the ClickHouse-resolved $groups for a customer (see events._resolve_groups_from_analytics).+# Ticket conversations re-resolve groups on creation plus every customer message, so this bounds+# the ClickHouse fallback to one query per customer per TTL. Empty dict = negative cache+# (customer's events carry no organization group). Org membership churn is slow, hence long TTLs.++RESOLVED_GROUPS_CACHE_TTL = 12 * 60 * 60 # 12 hours+RESOLVED_GROUPS_NEGATIVE_CACHE_TTL = 60 * 60 # 1 hour+++def _resolved_groups_cache_key(team_id: int, distinct_ids: list[str]) -> str:+ # JSON-encode for an unambiguous preimage: joining with a separator collides+ # when distinct_ids themselves contain it (["a|b", "c"] vs ["a", "b|c"]).+ digest = hashlib.sha256(json.dumps(sorted(distinct_ids)).encode()).hexdigest()[:32]+ return _make_cache_key("resolved_groups", str(team_id), digest)+++def get_cached_resolved_groups(team_id: int, distinct_ids: list[str]) -> dict | None:+ """Get cached resolved groups. Returns None on cache miss, {} for negative cache."""+ key = _resolved_groups_cache_key(team_id, distinct_ids)+ try:+ return cache.get(key)+ except Exception:+ logger.warning("conversations_cache_get_error", key=key)+ return None+++def set_cached_resolved_groups(team_id: int, distinct_ids: list[str], groups: dict | None) -> None:+ """Cache resolved groups (or {} as negative cache when resolution found nothing)."""+ key = _resolved_groups_cache_key(team_id, distinct_ids)+ timeout = RESOLVED_GROUPS_CACHE_TTL if groups else RESOLVED_GROUPS_NEGATIVE_CACHE_TTL+ try:+ cache.set(key, groups or {}, timeout=timeout)+ except Exception:+ logger.warning("conversations_cache_set_error", key=key)diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.pyindex 1b2e82e20a43..9c410ce679c5 100644--- a/products/conversations/backend/events.py+++ b/products/conversations/backend/events.py@@ -10,13 +10,20 @@ from typing import Literalimport structlog+from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query+from posthog.api.capture_dispatch import capture_internal_routed+from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.event_usage import groups as build_groups+from posthog.models.group_type_mapping import get_group_types_for_projectfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.person.util import get_persons_by_distinct_idsfrom posthog.models.team import Teamfrom posthog.models.user import User+from posthog.settings import SITE_URL+from products.conversations.backend.cache import get_cached_resolved_groups, set_cached_resolved_groupsfrom products.conversations.backend.models import Ticketfrom products.conversations.backend.models.constants import Channelfrom products.conversations.backend.person_lookup import _get_persons_by_email@@ -56,6 +63,87 @@ def _get_actor_distinct_id(# to use for organization attribution._EMAIL_FALLBACK_CHANNELS = frozenset({Channel.EMAIL.value, Channel.SLACK.value, Channel.TEAMS.value})+# Latest organization/customer group keys from the customer's recent events. We read the+# dedicated $group_N columns (set on every event that carries $groups) rather than filtering on+# $groupidentify events: posthog.group(type, key) called without properties associates the group+# with all subsequent events but emits no $groupidentify (the documented SDK behavior), and even+# newer SDKs only re-emit it for newly-seen groups. A $groupidentify filter would therefore+# silently miss exactly the cross-region customers this fallback exists for — those whose apps+# don't pass group properties, or whose last group identify predates the 30-day window.+# {org_col}/{customer_select} are interpolated from this project's own group-type indexes (see+# _resolve_groups_from_analytics); column names can't be HogQL placeholders.+GROUPS_FROM_EVENTS_QUERY = """+SELECT+ argMax({org_col}, timestamp),+ {customer_select}+FROM events+WHERE distinct_id IN {{distinct_ids}}+ AND timestamp >= now() - INTERVAL 30 DAY+ AND {org_col} != ''+"""+++def _resolve_groups_from_analytics(team: Team, distinct_ids: list[str]) -> dict | None:+ """Resolve ``$groups`` from the customer's recent analytics events in ClickHouse.++ Fallback for when the ``OrganizationMembership`` lookup misses: that join runs+ against this region's Postgres only, so accounts registered in another region+ (e.g. an EU user filing a ticket against a US project) are invisible to it.+ Their identified app sessions, however, stamp ``$group_N`` onto every event+ captured into this project, which is cross-region by construction.++ Event-supplied groups are captured with the project's public token and are+ therefore spoofable — fine for analytics enrichment (same trust level as+ ``$identify``), never for authorization. ``instance``/``project`` are rebuilt+ server-side so fallback-path events match ``build_groups()`` output.+ """+ if not distinct_ids:+ return None++ cached = get_cached_resolved_groups(team.id, distinct_ids)+ if cached is not None:+ return cached or None # {} is the negative-cache sentinel++ # The $group_N column index is per-project, so resolve the org/customer indexes from this+ # project's group-type mapping. Doubles as a cheap guard: bail (and negative-cache) for+ # projects without an organization group type before touching ClickHouse.+ group_type_index = {+ gtm["group_type"]: gtm["group_type_index"] for gtm in get_group_types_for_project(team.project_id)+ }+ org_index = group_type_index.get("organization")+ if org_index is None:+ set_cached_resolved_groups(team.id, distinct_ids, None)+ return None+ customer_index = group_type_index.get("customer")++ # Indexes are trusted ints (0-4) from the project's own mapping; safe to interpolate.+ org_col = f"`$group_{org_index}`"+ customer_select = (+ f"argMaxIf(`$group_{customer_index}`, timestamp, `$group_{customer_index}` != '')"+ if customer_index is not None+ else "''"+ )+ query = GROUPS_FROM_EVENTS_QUERY.format(org_col=org_col, customer_select=customer_select)++ with tags_context(product=Product.CONVERSATIONS, feature=Feature.QUERY):+ response = execute_hogql_query(+ query,+ placeholders={"distinct_ids": ast.Constant(value=distinct_ids)},+ team=team,+ query_type="conversations_groups_lookup",+ )++ groups: dict | None = None+ if response.results:+ org_key, customer_key = response.results[0]+ if org_key:+ groups = {"instance": SITE_URL, "project": str(team.uuid), "organization": org_key}+ if customer_key:+ groups["customer"] = customer_key++ set_cached_resolved_groups(team.id, distinct_ids, groups)+ return groups+def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:"""Resolve the customer organization's ``$groups`` for a ticket.@@ -84,6 +172,13 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:)if membership:return True, build_groups(membership.organization, team)+ # Membership rows are region-local: accounts registered in another region+ # never appear in this Postgres. Fall back to the $groups their sessions+ # stamped onto this project's analytics events (same distinct_id, so the+ # shared-email caveat above still holds).+ groups = _resolve_groups_from_analytics(team, [ticket.distinct_id])+ if groups:+ return True, groupsreturn False, None# 2. Email fallback, restricted to channels with a provider-verified email identity.@@ -102,6 +197,10 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:)if membership:return True, build_groups(membership.organization, team)+ # Same cross-region fallback as above, keyed by the person's distinct_ids.+ groups = _resolve_groups_from_analytics(team, person.distinct_ids)+ if groups:+ return True, groupsreturn False, None