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): stop attributing ticket events to the support project (#101674)

Alex Vc14c159bf0b7
diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.py
index a9ae01c68dcd..e12f630632f5 100644
--- a/products/conversations/backend/api/tests/test_events.py
+++ b/products/conversations/backend/api/tests/test_events.py
@@ -393,14 +393,35 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is expect_groups
assert "$groups" not in call_kwargs["properties"]
+ @parameterized.expand(
+ [
+ # A project outside the resolved organization would contradict the organization group.
+ ("no_current_project", None),
+ ("current_project_in_org", "same_org"),
+ ("current_project_in_another_org", "other_org"),
+ ]
+ )
@patch("products.conversations.backend.events.capture_internal")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
- def test_capture_ticket_created_groups_from_person_org(self, mock_get_persons, mock_capture):
+ def test_capture_ticket_created_groups_from_person_org(
+ self, _name, current_project, mock_get_persons, mock_capture
+ ):
+ from posthog.models import Team
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)
+ person_team = None
+ if current_project == "same_org":
+ person_team = Team.objects.create(organization=person_org, name="Customer project")
+ elif current_project == "other_org":
+ person_team = Team.objects.create(
+ organization=Organization.objects.create(name="Another Org"), name="Other project"
+ )
+ if person_team is not None:
+ person_user.current_team = person_team
+ person_user.save(update_fields=["current_team"])
mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]
@@ -410,8 +431,12 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is True
groups = call_kwargs["properties"]["$groups"]
assert groups["organization"] == str(person_org.id)
- assert groups["project"] == str(self.team.uuid)
assert "instance" in groups
+ if current_project == "same_org":
+ assert person_team is not None
+ assert groups["project"] == str(person_team.uuid)
+ else:
+ assert "project" not in groups
@patch("products.conversations.backend.events.capture_internal")
@patch("products.conversations.backend.events.get_persons_by_distinct_ids")
@@ -430,7 +455,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is True
groups = call_kwargs["properties"]["$groups"]
assert groups["organization"] == str(person_org.id)
- assert groups["project"] == str(self.team.uuid)
+ assert "project" not in groups
assert "instance" in groups
@parameterized.expand(
@@ -623,7 +648,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is True
groups = call_kwargs["properties"]["$groups"]
assert groups["organization"] == str(person_org.id)
- assert groups["project"] == str(self.team.uuid)
+ assert "project" not in groups
@parameterized.expand(
[
@@ -716,7 +741,7 @@ class TestConversationEvents(BaseTest):
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 "project" not in groups
assert groups["instance"] == SITE_URL
self.ticket.refresh_from_db()
assert self.ticket.organization_id == "org-uuid-1"
@@ -739,11 +764,7 @@ class TestConversationEvents(BaseTest):
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",
- }
+ mock_analytics.return_value = {"instance": SITE_URL, "organization": "analytics-org"}
capture_ticket_created(self.ticket)
@@ -854,7 +875,7 @@ class TestConversationEvents(BaseTest):
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)
+ assert "project" not in groups
@patch("products.conversations.backend.events.capture_internal")
@patch("products.conversations.backend.events.get_groups_by_identifiers")
@@ -941,7 +962,7 @@ class TestConversationEvents(BaseTest):
{"group_type": "organization", "group_type_index": 1},
{"group_type": "customer", "group_type_index": 2},
]
- mock_hogql.return_value.results = [["org-eu-123", customer_key]]
+ mock_hogql.return_value.results = [[("org-eu-123", "customer-project-uuid"), customer_key]]
capture_ticket_created(self.ticket)
@@ -949,8 +970,8 @@ class TestConversationEvents(BaseTest):
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)
+ # instance is rebuilt server-side; project is the customer's own, read from the event row
+ assert groups["project"] == "customer-project-uuid"
assert "instance" in groups
if customer_key:
assert groups["customer"] == customer_key
@@ -960,7 +981,7 @@ class TestConversationEvents(BaseTest):
@parameterized.expand(
[
("no_events", []),
- ("empty_org_key", [["", ""]]),
+ ("empty_org_key", [[("", ""), ""]]),
]
)
@patch("products.conversations.backend.events.capture_internal")
@@ -1020,7 +1041,7 @@ class TestConversationEvents(BaseTest):
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", ""]]
+ mock_hogql.return_value.results = [[("org-eu-123", ""), ""]]
ticket = Ticket.objects.create_with_number(
team=self.team,
@@ -1038,7 +1059,7 @@ class TestConversationEvents(BaseTest):
@parameterized.expand(
[
- ("positive", [["org-eu-123", ""]], True),
+ ("positive", [[("org-eu-123", ""), ""]], True),
("negative", [], False),
]
)
@@ -1091,7 +1112,7 @@ class TestConversationEvents(BaseTest):
mock_get_persons.return_value = []
mock_get_by_email.return_value = {}
mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 0}]
- mock_hogql.return_value.results = [["attacker-org", ""]]
+ mock_hogql.return_value.results = [[("attacker-org", ""), ""]]
ticket = Ticket.objects.create_with_number(
team=self.team,
@@ -1144,7 +1165,7 @@ class TestConversationEvents(BaseTest):
assert call_kwargs["process_person_profile"] is True
groups = call_kwargs["properties"]["$groups"]
assert groups["organization"] == "stored-org-123"
- assert groups["project"] == str(self.team.uuid)
+ assert "project" not in groups
assert groups["instance"] == SITE_URL
def _configure_account_group_type(self, index: int | None) -> None:
@@ -1183,11 +1204,7 @@ class TestConversationEvents(BaseTest):
mock_get_account.assert_called_once_with(self.team.id, "C123")
call_kwargs = mock_capture.call_args.kwargs
assert call_kwargs["process_person_profile"] is False
- assert call_kwargs["properties"]["$groups"] == {
- "instance": SITE_URL,
- "project": str(self.team.uuid),
- "organization": "acme-org-1",
- }
+ assert call_kwargs["properties"]["$groups"] == {"instance": SITE_URL, "organization": "acme-org-1"}
ticket.refresh_from_db()
assert ticket.organization_id == "acme-org-1"
assert ticket.organization_id_source == OrganizationIdSource.SLACK_CHANNEL_ACCOUNT
@@ -1320,7 +1337,7 @@ class TestConversationEvents(BaseTest):
# 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"},
+ {"instance": SITE_URL, "organization": "late-org-1"},
OrganizationIdSource.PERSON,
)
@@ -1343,7 +1360,7 @@ class TestConversationEvents(BaseTest):
# 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"},
+ {"instance": SITE_URL, "organization": "late-org-2"},
OrganizationIdSource.PERSON,
)
Ticket.objects.filter(id=self.ticket.id).update(organization_id="first-org-1")
@@ -1411,7 +1428,7 @@ class TestResolveGroupsFromAnalyticsClickHouse(ClickhouseTestMixin, APIBaseTest)
team=self.team,
event="$pageview",
distinct_id="eu-user-did",
- properties={"$group_1": "org-eu-123", "$group_2": "cus_456"},
+ properties={"$group_0": "customer-project-uuid", "$group_1": "org-eu-123", "$group_2": "cus_456"},
)
flush_persons_and_events()
@@ -1419,7 +1436,7 @@ class TestResolveGroupsFromAnalyticsClickHouse(ClickhouseTestMixin, APIBaseTest)
assert groups == {
"instance": SITE_URL,
- "project": str(self.team.uuid),
+ "project": "customer-project-uuid",
"organization": "org-eu-123",
"customer": "cus_456",
}
@@ -1442,7 +1459,8 @@ class TestResolveGroupsFromAnalyticsClickHouse(ClickhouseTestMixin, APIBaseTest)
groups = _resolve_groups_from_analytics(self.team, ["eu-user-did"])
- assert groups == {"instance": SITE_URL, "project": str(self.team.uuid), "organization": "org-eu-123"}
+ # No project group on the customer's events: unset beats the support team's own project.
+ assert groups == {"instance": SITE_URL, "organization": "org-eu-123"}
@patch(
"products.conversations.backend.events.get_group_types_for_project",
diff --git a/products/conversations/backend/cache.py b/products/conversations/backend/cache.py
index a6d171b9f8a4..f630320770b5 100644
--- a/products/conversations/backend/cache.py
+++ b/products/conversations/backend/cache.py
@@ -334,7 +334,8 @@ 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)
+ # Bump the version suffix when the cached $groups shape changes: the 12-hour TTL outlives a deploy.
+ return _make_cache_key("resolved_groups_v2", str(team_id), digest)
def get_cached_resolved_groups(team_id: int, distinct_ids: list[str]) -> dict | None:
diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.py
index 679050d3c1a8..f77270b46b9a 100644
--- a/products/conversations/backend/events.py
+++ b/products/conversations/backend/events.py
@@ -62,6 +62,9 @@ def _get_actor_distinct_id(
return ticket.distinct_id or ticket.channel_source or "unknown"
+# A resolved ``$groups`` describes the customer, never us: these events are captured into the
+# support team's own project, so its uuid as the `project` group mis-attributes every ticket.
+
# Channels whose customer email is tied to a provider-verified identity and is therefore safe
# to use for organization attribution.
_EMAIL_FALLBACK_CHANNELS = frozenset({Channel.EMAIL.value, Channel.SLACK.value, Channel.TEAMS.value})
@@ -73,11 +76,12 @@ _EMAIL_FALLBACK_CHANNELS = frozenset({Channel.EMAIL.value, Channel.SLACK.value,
# 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.
+# {org_col}/{project_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. One argMax over both
+# group columns pairs an organization with the project it was seen with, never with an older one.
GROUPS_FROM_EVENTS_QUERY = """
SELECT
- argMax({org_col}, timestamp),
+ argMax(tuple({org_col}, {project_col}), timestamp),
{customer_select}
FROM events
WHERE distinct_id IN {{distinct_ids}}
@@ -97,8 +101,9 @@ def _resolve_groups_from_analytics(team: Team, distinct_ids: list[str]) -> dict
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.
+ ``$identify``), never for authorization. ``instance`` is rebuilt server-side;
+ ``project`` is the customer's own project group, read from the same event as the
+ organization.
"""
if not distinct_ids:
return None
@@ -118,6 +123,7 @@ def _resolve_groups_from_analytics(team: Team, distinct_ids: list[str]) -> dict
set_cached_resolved_groups(team.id, distinct_ids, None)
return None
customer_index = group_type_index.get("customer")
+ project_index = group_type_index.get("project")
# Indexes are trusted ints (0-4) from the project's own mapping; safe to interpolate.
org_col = f"`$group_{org_index}`"
@@ -126,7 +132,8 @@ def _resolve_groups_from_analytics(team: Team, distinct_ids: list[str]) -> dict
if customer_index is not None
else "''"
)
- query = GROUPS_FROM_EVENTS_QUERY.format(org_col=org_col, customer_select=customer_select)
+ project_col = f"`$group_{project_index}`" if project_index is not None else "''"
+ query = GROUPS_FROM_EVENTS_QUERY.format(org_col=org_col, project_col=project_col, customer_select=customer_select)
# Deferred: hogql.query pulls the whole query-runner layer, and this module loads
# at django.setup() via the conversations signal wiring.
@@ -143,11 +150,13 @@ def _resolve_groups_from_analytics(team: Team, distinct_ids: list[str]) -> dict
groups: dict | None = None
if response.results:
- org_key, customer_key = response.results[0]
+ (org_key, project_key), customer_key = response.results[0]
if org_key:
- groups = {"instance": SITE_URL, "project": str(team.uuid), "organization": org_key}
+ groups = {"instance": SITE_URL, "organization": org_key}
if customer_key:
groups["customer"] = customer_key
+ if project_key:
+ groups["project"] = project_key
set_cached_resolved_groups(team.id, distinct_ids, groups)
return groups
@@ -182,7 +191,24 @@ def _resolve_groups_from_person_properties(team: Team, person: Person) -> dict |
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}
+ return {"instance": SITE_URL, "organization": org_id}
+
+
+def _requester_project(membership: OrganizationMembership) -> Team | None:
+ """The requester's own project for the ``project`` group, or ``None`` when it can't be named.
+
+ ``current_team`` follows the project switcher, so it names the project the requester worked
+ in last — usually the one they filed the ticket from. Read the field directly rather than
+ ``user.team``, which backfills and saves a project for users who have none.
+
+ A multi-org requester can have a current project outside the organization this membership
+ resolved, and an organization and a project from two different organizations would enrich
+ the event with a contradiction. Leave ``project`` unset in that case.
+ """
+ current_team = membership.user.current_team
+ if current_team is None or current_team.organization_id != membership.organization_id:
+ return None
+ return current_team
def _org_groups_for_person(ticket: Ticket, team: Team, person: Person, distinct_ids: list[str]) -> dict | None:
@@ -197,12 +223,12 @@ def _org_groups_for_person(ticket: Ticket, team: Team, person: Person, distinct_
if distinct_ids:
try:
membership = (
- OrganizationMembership.objects.select_related("organization")
+ OrganizationMembership.objects.select_related("organization", "user__current_team")
.filter(user__distinct_id__in=distinct_ids)
.first()
)
if membership:
- return build_groups(membership.organization, team)
+ return build_groups(membership.organization, _requester_project(membership))
except Exception:
logger.exception("ticket_org_membership_lookup_failed", team_id=team.id, ticket_id=str(ticket.id))
# Membership rows are region-local: accounts registered in another region
@@ -315,7 +341,7 @@ def _resolve_groups_from_slack_channel(team: Team, slack_channel_id: str) -> dic
if account is None or not account.external_id:
return None
- return {"instance": SITE_URL, "project": str(team.uuid), group_type_name: account.external_id}
+ return {"instance": SITE_URL, group_type_name: account.external_id}
def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None, str | None]:
@@ -345,9 +371,9 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None,
return process_person, None, None
-def _groups_from_org_id(team: Team, organization_id: str) -> dict:
+def _groups_from_org_id(organization_id: str) -> dict:
"""Rebuild minimal $groups from a stored org id, skipping the expensive resolver."""
- return {"instance": SITE_URL, "project": str(team.uuid), "organization": organization_id}
+ return {"instance": SITE_URL, "organization": organization_id}
def _get_ticket_base_properties(ticket: Ticket) -> dict:
@@ -589,7 +615,7 @@ def capture_message_received(ticket: Ticket, message_id: str, message_content: s
process_person = False
try:
if ticket.organization_id:
- properties["$groups"] = _groups_from_org_id(team, ticket.organization_id)
+ properties["$groups"] = _groups_from_org_id(ticket.organization_id)
# Only a person-resolved org attests the sender (legacy rows without a source
# were person-resolved); a channel-inferred org says nothing about them, so
# don't create a person profile for it. Allowlist rather than blocklist so a