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.

feat(workflows): show unlinked sends on the person's emails tab (#118624)

Harley Alexandercef966a1dcb8
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 31742cf51fc6..687fe08ee4ce 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -539,6 +539,10 @@ _PERSON_ID_PARAMETER = OpenApiParameter(
_id_schema = extend_schema(parameters=[_PERSON_ID_PARAMETER])
+# A send with no person attached is matched to a person by its distinct ID. The cap keeps the query small
+# for a person with thousands of distinct IDs.
+_MESSAGE_ASSET_DISTINCT_ID_LIMIT = 100
+
# Per-action distinct-id fetch caps for the person loaded by ``safely_get_object``. Listed actions
# read only one distinct_id (property updates) or none (``destroy``/``activity`` use the uuid/pk;
# ``properties_timeline``/``delete_events`` don't read distinct_ids), so the fetch is capped here.
@@ -1660,6 +1664,25 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def push_notifications(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
return self._message_assets_response(request, kind="push")
+ def _person_email(self, person: Person) -> Optional[str]:
+ # Person properties come from ClickHouse, not from the personhog lookup that loaded the person.
+ from posthog.hogql import ast # noqa: PLC0415 — deferred to avoid a circular import at module load
+ from posthog.hogql.parser import parse_select # noqa: PLC0415
+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415
+
+ results = execute_hogql_query(
+ parse_select(
+ "SELECT properties.email FROM persons WHERE id = {person_id} LIMIT 1",
+ placeholders={"person_id": ast.Constant(value=str(person.uuid))},
+ ),
+ team=self.team,
+ # A property rule can hide the email from this user. Without the user, only the team-wide rules apply.
+ user=self.request.user,
+ query_type="person_message_assets_email",
+ ).results
+ email = results[0][0] if results else None
+ return email if isinstance(email, str) and email.strip() else None
+
def _message_assets_response(self, request: request.Request, kind: str) -> response.Response:
person = self.get_object()
param_serializer = PersonMessageAssetsRequestSerializer(data=request.query_params)
@@ -1681,6 +1704,8 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
after=after_date,
before=before_date,
kind=kind,
+ distinct_ids=person.distinct_ids[:_MESSAGE_ASSET_DISTINCT_ID_LIMIT],
+ email=self._person_email(person) if kind == "email" else None,
)
# Single lookup for every workflow referenced by this page of rows so the tab shows
# human-readable names instead of raw UUIDs. Deleted workflows drop out of the map
diff --git a/products/workflows/backend/services/message_assets.py b/products/workflows/backend/services/message_assets.py
index bd3e6727bc8c..944a5166b259 100644
--- a/products/workflows/backend/services/message_assets.py
+++ b/products/workflows/backend/services/message_assets.py
@@ -1,3 +1,4 @@
+from collections.abc import Sequence
from datetime import UTC, datetime
from typing import Any, Optional, cast
@@ -136,10 +137,21 @@ def fetch_message_assets_for_person(
after: Optional[datetime] = None,
before: Optional[datetime] = None,
kind: str = "email",
+ distinct_ids: Sequence[str] = (),
+ email: Optional[str] = None,
) -> list[MessageAsset]:
+ """The person's messages. A send with no person attached, such as a transactional email to someone
+ who had no person yet, also belongs to the person whose distinct ID it used or whose email it went to."""
+ owners = ["person_id = %(person_id)s"]
+ if distinct_ids:
+ owners.append("(person_id = '' AND distinct_id IN %(distinct_ids)s)")
+ if email:
+ # A plain IN keeps the bloom index on recipient usable. Inside the OR, a function of recipient would stop every
+ # branch from skipping granules.
+ owners.append("(person_id = '' AND recipient IN %(emails)s)")
where = [
"team_id = %(team_id)s",
- "person_id = %(person_id)s",
+ f"({' OR '.join(owners)})",
# Standalone hog_function email destinations aren't surfaced anywhere yet,
# so this endpoint only returns workflow-step rows.
"function_kind = 'hog_flow'",
@@ -151,6 +163,8 @@ def fetch_message_assets_for_person(
kwargs: dict[str, Any] = {
"team_id": team_id,
"person_id": person_id,
+ "distinct_ids": list(distinct_ids),
+ "emails": sorted({(email or "").strip(), (email or "").strip().lower()}),
"kind": kind,
"limit": limit,
"offset": offset,
diff --git a/products/workflows/backend/tests/api/test_message_assets.py b/products/workflows/backend/tests/api/test_message_assets.py
index c2990cc7e5c8..57aff93f1c60 100644
--- a/products/workflows/backend/tests/api/test_message_assets.py
+++ b/products/workflows/backend/tests/api/test_message_assets.py
@@ -7,10 +7,14 @@ from parameterized import parameterized
from rest_framework import status
from posthog.clickhouse.client.execute import sync_execute
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, PropertyDefinition
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.persons import create_person
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.message_assets_sql import INSERT_MESSAGE_ASSET_SQL
@@ -226,7 +230,7 @@ class TestMessageAssets(ClickhouseTestMixin, APIBaseTest):
class TestPersonEmails(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- self.person = create_person(team=self.team, distinct_ids=["distinct-1"], properties={"email": "[email protected]"})
+ self.person = create_person(team=self.team, distinct_ids=["distinct-1"], properties={"email": "[email protected]"})
self.hog_flow = HogFlow.objects.create(team=self.team, name="Welcome flow")
def _emails(self, params=None):
@@ -272,6 +276,71 @@ class TestPersonEmails(ClickhouseTestMixin, APIBaseTest):
# rather than a stale name or a database lookup error.
assert row["function_name"] == ""
+ @parameterized.expand(
+ [
+ (
+ "unlinked_send_to_their_distinct_id",
+ {"person_id": "", "distinct_id": "distinct-1", "recipient": "[email protected]"},
+ True,
+ ),
+ (
+ "unlinked_send_to_their_email",
+ {"person_id": "", "distinct_id": "[email protected]", "recipient": "[email protected]"},
+ True,
+ ),
+ (
+ "unlinked_send_to_their_email_lowercased",
+ {"person_id": "", "distinct_id": "[email protected]", "recipient": "[email protected]"},
+ True,
+ ),
+ (
+ "unlinked_send_to_someone_else",
+ {"person_id": "", "distinct_id": "other", "recipient": "[email protected]"},
+ False,
+ ),
+ (
+ "send_linked_to_another_person",
+ {
+ "person_id": "00000000-0000-0000-0000-000000000999",
+ "distinct_id": "distinct-1",
+ "recipient": "[email protected]",
+ },
+ False,
+ ),
+ ]
+ )
+ def test_includes_sends_with_no_person_that_match_the_person(self, _name, asset, expected):
+ create_message_asset(team_id=self.team.pk, function_id=str(self.hog_flow.pk), invocation_id="inv", **asset)
+
+ rows = self._emails().json()
+
+ assert [r["invocation_id"] for r in rows] == (["inv"] if expected else [])
+
+ def test_an_email_hidden_from_the_user_does_not_match_unlinked_sends(self):
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ email = PropertyDefinition.objects.create(
+ team=self.team, name="email", property_type="String", type=PropertyDefinition.Type.PERSON
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=email,
+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=self.user),
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ create_message_asset(
+ team_id=self.team.pk,
+ function_id=str(self.hog_flow.pk),
+ invocation_id="inv",
+ person_id="",
+ distinct_id="someone-else",
+ recipient="[email protected]",
+ )
+
+ assert self._emails().json() == []
+
def test_isolated_from_other_persons(self):
self._seed("mine")
self._seed("theirs", person_id="00000000-0000-0000-0000-000000000999")