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(conversations): resolve ticket org groups from the person's profile (#72217)

Abigail7f1f6729c248
diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.py
index 0583d046e0a3..e7e4ada6f3ed 100644
--- a/products/conversations/backend/api/tests/test_events.py
+++ b/products/conversations/backend/api/tests/test_events.py
@@ -3,7 +3,7 @@ from datetime import datetime
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.core.cache import cache
@@ -584,6 +584,200 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is False
assert "$groups" not in call_kwargs["properties"]
+ @parameterized.expand(
+ [
+ ("group_exists", True),
+ ("group_missing", False),
+ ]
+ )
+ @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.get_groups_by_identifiers")
+ @patch("products.conversations.backend.events.get_group_types_for_project")
+ @patch("products.conversations.backend.events._resolve_groups_from_analytics", return_value=None)
+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")
+ def test_capture_ticket_created_person_property_org_fallback(
+ self, _name, group_exists, mock_get_persons, _mock_analytics, mock_group_types, mock_get_groups, mock_capture
+ ):
+ # No membership and events aged out of the analytics window: the org id on the person's
+ # own profile resolves $groups — but only when that org group exists in this project.
+ from posthog.models.person.person import Person
+
+ mock_get_persons.return_value = [
+ Person(team_id=self.team.id, is_identified=True, properties={"organization_id": "org-uuid-1"})
+ ]
+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 0}]
+ mock_get_groups.return_value = [Mock()] if group_exists else []
+
+ capture_ticket_created(self.ticket)
+
+ mock_get_groups.assert_called_once_with(self.team.id, 0, ["org-uuid-1"])
+ call_kwargs = mock_capture.call_args.kwargs
+ if group_exists:
+ assert call_kwargs["process_person_profile"] is True
+ groups = call_kwargs["properties"]["$groups"]
+ assert groups["organization"] == "org-uuid-1"
+ assert groups["project"] == str(self.team.uuid)
+ assert groups["instance"] == SITE_URL
+ self.ticket.refresh_from_db()
+ assert self.ticket.organization_id == "org-uuid-1"
+ else:
+ assert call_kwargs["process_person_profile"] is False
+ assert "$groups" not in call_kwargs["properties"]
+ self.ticket.refresh_from_db()
+ assert self.ticket.organization_id is None
+
+ @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.get_groups_by_identifiers")
+ @patch("products.conversations.backend.events._resolve_groups_from_analytics")
+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")
+ def test_capture_ticket_created_analytics_groups_win_over_person_property(
+ self, mock_get_persons, mock_analytics, mock_get_groups, mock_capture
+ ):
+ # The analytics fallback is strictly ahead of the person-property fallback.
+ from posthog.models.person.person import Person
+
+ mock_get_persons.return_value = [
+ Person(team_id=self.team.id, is_identified=True, properties={"organization_id": "profile-org"})
+ ]
+ mock_analytics.return_value = {
+ "instance": SITE_URL,
+ "project": str(self.team.uuid),
+ "organization": "analytics-org",
+ }
+
+ capture_ticket_created(self.ticket)
+
+ mock_get_groups.assert_not_called()
+ assert mock_capture.call_args.kwargs["properties"]["$groups"]["organization"] == "analytics-org"
+
+ @parameterized.expand(
+ [
+ ("integer", 123),
+ ("list", ["org-uuid-1"]),
+ ("empty_string", ""),
+ ]
+ )
+ @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.get_groups_by_identifiers")
+ @patch("products.conversations.backend.events._resolve_groups_from_analytics", return_value=None)
+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")
+ def test_capture_ticket_created_person_property_org_fallback_rejects_non_string(
+ self, _name, org_id_value, mock_get_persons, _mock_analytics, mock_get_groups, mock_capture
+ ):
+ from posthog.models.person.person import Person
+
+ mock_get_persons.return_value = [
+ Person(team_id=self.team.id, is_identified=True, properties={"organization_id": org_id_value})
+ ]
+
+ capture_ticket_created(self.ticket)
+
+ mock_get_groups.assert_not_called()
+ 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")
+ @patch("products.conversations.backend.events.get_groups_by_identifiers", side_effect=Exception("personhog down"))
+ @patch("products.conversations.backend.events.get_group_types_for_project")
+ @patch("products.conversations.backend.events._resolve_groups_from_analytics", return_value=None)
+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")
+ def test_capture_ticket_created_still_fires_on_group_lookup_failure(
+ self, mock_get_persons, _mock_analytics, mock_group_types, _mock_get_groups, mock_capture
+ ):
+ from posthog.models.person.person import Person
+
+ mock_get_persons.return_value = [
+ Person(team_id=self.team.id, is_identified=True, properties={"organization_id": "org-uuid-1"})
+ ]
+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 0}]
+
+ capture_ticket_created(self.ticket)
+
+ mock_capture.assert_called_once()
+ call_kwargs = mock_capture.call_args.kwargs
+ assert call_kwargs["process_person_profile"] is False
+ assert "$groups" not in call_kwargs["properties"]
+
+ @parameterized.expand(
+ [
+ # The person found by email resolves via their profile whether or not any
+ # distinct_ids came back for them (no-distinct_ids skips membership/analytics).
+ ("with_distinct_ids", True),
+ ("without_distinct_ids", False),
+ ]
+ )
+ @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.get_groups_by_identifiers")
+ @patch("products.conversations.backend.events.get_group_types_for_project")
+ @patch("products.conversations.backend.events._resolve_groups_from_analytics", return_value=None)
+ @patch("products.conversations.backend.person_lookup._get_persons_by_email")
+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")
+ def test_capture_ticket_created_email_fallback_person_property_org(
+ self,
+ _name,
+ has_distinct_ids,
+ mock_get_persons,
+ mock_get_by_email,
+ mock_analytics,
+ mock_group_types,
+ mock_get_groups,
+ mock_capture,
+ ):
+ # Email leg: the person found by email has no membership and no recent group-stamped
+ # events, but their profile's organization_id resolves the org.
+ from posthog.models.person.person import Person
+
+ customer_email = "[email protected]"
+ # distinct_id (the email) resolves no identified person...
+ mock_get_persons.return_value = []
+ # ...the ClickHouse email lookup finds the person, whose real distinct_id has no membership
+ person = Person(team_id=self.team.id, is_identified=True, properties={"organization_id": "org-uuid-2"})
+ person._distinct_ids = ["real-did-1"] if has_distinct_ids else []
+ mock_get_by_email.return_value = {customer_email: person}
+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 0}]
+ mock_get_groups.return_value = [Mock()]
+
+ 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)
+
+ if not has_distinct_ids:
+ mock_analytics.assert_not_called()
+ call_kwargs = mock_capture.call_args.kwargs
+ assert call_kwargs["process_person_profile"] is True
+ groups = call_kwargs["properties"]["$groups"]
+ assert groups["organization"] == "org-uuid-2"
+ assert groups["project"] == str(self.team.uuid)
+
+ @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events.get_groups_by_identifiers")
+ @patch("products.conversations.backend.events.get_group_types_for_project", return_value=[])
+ @patch("products.conversations.backend.events._resolve_groups_from_analytics", return_value=None)
+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")
+ def test_capture_ticket_created_person_property_org_fallback_requires_org_group_type(
+ self, mock_get_persons, _mock_analytics, _mock_group_types, mock_get_groups, mock_capture
+ ):
+ # Projects without an organization group type never attribute via person properties.
+ from posthog.models.person.person import Person
+
+ mock_get_persons.return_value = [
+ Person(team_id=self.team.id, is_identified=True, properties={"organization_id": "org-uuid-1"})
+ ]
+
+ capture_ticket_created(self.ticket)
+
+ mock_get_groups.assert_not_called()
+ call_kwargs = mock_capture.call_args.kwargs
+ assert call_kwargs["process_person_profile"] is False
+ assert "$groups" not in call_kwargs["properties"]
+
@parameterized.expand(
[
# Channels NOT in the email-fallback allowlist must never run the email lookup.
@@ -805,6 +999,46 @@ class TestConversationEvents(BaseTest):
assert groups["project"] == str(self.team.uuid)
assert groups["instance"] == SITE_URL
+ @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events._resolve_org_groups")
+ def test_capture_message_received_persists_resolved_organization_id(self, mock_resolve, mock_capture):
+ # A resolution that only succeeds after creation (e.g. the profile property was set
+ # later) is persisted so subsequent messages take the stored-org fast path.
+ mock_resolve.return_value = (
+ True,
+ {"instance": SITE_URL, "project": str(self.team.uuid), "organization": "late-org-1"},
+ )
+
+ assert self.ticket.organization_id is None
+ capture_message_received(self.ticket, "msg-789", "Hello again")
+
+ # Fetch a fresh instance: refresh_from_db() on self.ticket would leave mypy's
+ # None-narrowing from the precondition assert in place, making the equality
+ # assert "unreachable".
+ stored = Ticket.objects.get(id=self.ticket.id)
+ assert stored.organization_id == "late-org-1"
+ assert mock_capture.call_args.kwargs["properties"]["$groups"]["organization"] == "late-org-1"
+
+ @patch("products.conversations.backend.events.capture_internal")
+ @patch("products.conversations.backend.events._resolve_org_groups")
+ def test_capture_message_received_does_not_overwrite_concurrently_persisted_organization_id(
+ self, mock_resolve, mock_capture
+ ):
+ # A concurrent handler persisted an org between this handler's read and its write:
+ # first write wins, in DB and on the in-memory ticket.
+ mock_resolve.return_value = (
+ True,
+ {"instance": SITE_URL, "project": str(self.team.uuid), "organization": "late-org-2"},
+ )
+ Ticket.objects.filter(id=self.ticket.id).update(organization_id="first-org-1")
+
+ assert self.ticket.organization_id is None # in-memory instance predates the concurrent write
+ capture_message_received(self.ticket, "msg-790", "Hello once more")
+
+ stored = Ticket.objects.get(id=self.ticket.id)
+ assert stored.organization_id == "first-org-1"
+ assert self.ticket.organization_id is None
+
@patch("products.conversations.backend.events.capture_internal")
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."""
diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.py
index a628f60859ca..1bb0226588ab 100644
--- a/products/conversations/backend/events.py
+++ b/products/conversations/backend/events.py
@@ -16,8 +16,10 @@ import structlog
from posthog.api.capture import capture_internal
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.event_usage import groups as build_groups
+from posthog.models.group.util import get_groups_by_identifiers
from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.organization import OrganizationMembership
+from posthog.models.person.person import Person
from posthog.models.person.util import get_persons_by_distinct_ids
from posthog.models.team import Team
from posthog.models.user import User
@@ -150,6 +152,38 @@ def _resolve_groups_from_analytics(team: Team, distinct_ids: list[str]) -> dict
return groups
+def _resolve_groups_from_person_properties(team: Team, person: Person) -> dict | None:
+ """Resolve ``$groups`` from the person's own ``organization_id`` profile property.
+
+ Fallback for when both the membership lookup and the analytics fallback miss:
+ app instrumentation commonly stamps the org id onto the person profile via
+ ``$identify``, and the profile persists even when the person's last identified
+ session predates the analytics fallback's 30-day event window.
+
+ Person properties are client-supplied — the same trust level as the analytics
+ fallback (enrichment, never authorization). The value only counts when it names
+ an organization group that already exists in this project, so a team whose
+ ``organization_id`` person property follows a different convention than its
+ organization group keys can't stamp bogus group keys onto events. A value that
+ coincidentally matches an unrelated org group key (e.g. small-integer keys) can
+ still mis-enrich — same collision class as event-supplied ``$groups``.
+ """
+ org_id = (person.properties or {}).get("organization_id")
+ if not org_id or not isinstance(org_id, str):
+ return None
+
+ 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:
+ return None
+ if not get_groups_by_identifiers(team.id, org_index, [org_id]):
+ return None
+
+ return {"instance": SITE_URL, "project": str(team.uuid), "organization": org_id}
+
+
def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:
"""Resolve the customer organization's ``$groups`` for a ticket.
@@ -160,17 +194,20 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:
so the membership is found directly. Other channels (Slack, Email, MS
Teams) set ``distinct_id`` to the customer email (or empty), so we fall
back to looking the person up by ``properties.email`` in ClickHouse and
- resolving the membership through that person's real distinct_ids.
+ resolving the membership through that person's real distinct_ids. Either
+ way, the person's own ``organization_id`` profile property is the last
+ resort when the membership and analytics lookups both miss.
"""
# 1. Real distinct_id (web widget). An identified person is authoritative: if they
# have no org membership, don't guess via email (a shared email could resolve to a
# different person's org), so return early instead of falling through.
if ticket.distinct_id:
- # Only is_identified is read, and the membership lookup below keys off the ticket's own
- # distinct_id — so skip fetching the person's distinct_ids.
+ # Only is_identified and properties are read, and the membership lookup below keys off
+ # the ticket's own distinct_id — so skip fetching the person's distinct_ids.
with personhog_caller_tag("conversations/ticket-event-person"):
persons = get_persons_by_distinct_ids(team.id, [ticket.distinct_id], distinct_id_limit=0)
- if any(p.is_identified for p in persons):
+ identified_person = next((p for p in persons if p.is_identified), None)
+ if identified_person is not None:
membership = (
OrganizationMembership.objects.select_related("organization")
.filter(user__distinct_id=ticket.distinct_id)
@@ -183,6 +220,11 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:
# 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, groups
+ # Their events may have aged out of the analytics window; the profile they
+ # identified with is still the same person's own claim about their org.
+ groups = _resolve_groups_from_person_properties(team, identified_person)
if groups:
return True, groups
return False, None
@@ -199,16 +241,21 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:
from products.conversations.backend.person_lookup import _get_persons_by_email # noqa: PLC0415
person = _get_persons_by_email(team, [email]).get(email.lower())
- if person is not None and person.distinct_ids:
- membership = (
- OrganizationMembership.objects.select_related("organization")
- .filter(user__distinct_id__in=person.distinct_ids)
- .first()
- )
- 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 person is not None:
+ if person.distinct_ids:
+ membership = (
+ OrganizationMembership.objects.select_related("organization")
+ .filter(user__distinct_id__in=person.distinct_ids)
+ .first()
+ )
+ 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, groups
+ # Same last resort as above: the org id the person's own profile carries.
+ groups = _resolve_groups_from_person_properties(team, person)
if groups:
return True, groups
@@ -402,6 +449,17 @@ def capture_message_received(ticket: Ticket, message_id: str, message_content: s
process_person, groups = _resolve_org_groups(ticket, team)
if groups is not None:
properties["$groups"] = groups
+ org_id = groups.get("organization")
+ if org_id:
+ # Persist like capture_ticket_created does, so later messages take the
+ # stored-org fast path instead of re-running the resolver. First write
+ # wins: only mirror to the in-memory ticket when this update landed,
+ # so a concurrent handler's value isn't shadowed.
+ rows_updated = Ticket.objects.filter(id=ticket.id, organization_id__isnull=True).update(
+ organization_id=org_id
+ )
+ if rows_updated:
+ ticket.organization_id = org_id
except Exception:
logger.exception("message_received_person_lookup_failed", team_id=team.id, ticket_id=str(ticket.id))
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.py
index 929746777ba3..9a2adb6aa900 100644
--- a/products/conversations/backend/models/ticket.py
+++ b/products/conversations/backend/models/ticket.py
@@ -105,7 +105,8 @@ class Ticket(UUIDTModel):
# Snooze — when set, ticket is "on hold" until this time, then auto-reopened by wake task
snoozed_until = models.DateTimeField(null=True, blank=True)
- # Customer's PostHog org group key, resolved once at creation (local org pk or cross-region analytics key).
+ # Customer's PostHog org group key, resolved once at creation or on a later message
+ # (local org pk, cross-region analytics key, or the person's organization_id property).
organization_id = models.CharField(max_length=400, null=True, blank=True)
# Zendesk import dedup — set when a ticket is imported from Zendesk Support.