: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(error-tracking): name the assignee in issue alert events (#106579)
Aleksander Błaszkiewicz95301101328f
diff --git a/products/error_tracking/backend/logic/assignees.py b/products/error_tracking/backend/logic/assignees.pynew file mode 100644index 000000000000..2f0803bc3cbd--- /dev/null+++ b/products/error_tracking/backend/logic/assignees.py@@ -0,0 +1,77 @@+"""Issue assignee values for lifecycle events and alert notifications.++The Temporal lifecycle activities import this module, so it must not import the+Temporal package: that package loads every workflow module, which would make an+import cycle with logic/lifecycle_events.py.+"""++import json+from typing import Any+from uuid import UUID++from django.db.models import Exists, OuterRef++from posthog.dataclasses import frozen+from posthog.models.organization import OrganizationMembership++from products.error_tracking.backend.models import ErrorTrackingIssueAssignment+++def assignee_property(assignee: dict[str, Any]) -> str:+ # Wire-compatible with cymbal's `Assignee` serialization on created/reopened events+ # (compact serde JSON, adjacently tagged, numeric user ids and string role ids), so+ # exact-match filters on the assignee property behave the same across all events.+ assignee_id = int(assignee["id"]) if assignee["type"] == "user" else str(assignee["id"])+ return json.dumps({"type": assignee["type"], "id": assignee_id}, separators=(",", ":"))+++@frozen+class ResolvedAssignee:+ property_value: str+ name: str | None+ email: str | None++ def display_properties(self) -> dict[str, str]:+ properties: dict[str, str] = {}+ if self.name:+ properties["assignee_name"] = self.name+ if self.email:+ properties["assignee_email"] = self.email+ return properties+++def resolve_current_assignee(issue_id: UUID | str) -> ResolvedAssignee | None:+ assignment = (+ ErrorTrackingIssueAssignment.objects.filter(issue_id=issue_id)+ .select_related("user", "role")+ .only("user__first_name", "user__last_name", "user__email", "role__name")+ .annotate(+ user_is_member=Exists(+ OrganizationMembership.objects.filter(+ user_id=OuterRef("user_id"), organization_id=OuterRef("issue__team__organization_id")+ )+ )+ )+ .first()+ )+ if assignment is None:+ return None+ if assignment.user is not None:+ user = assignment.user+ property_value = assignee_property({"type": "user", "id": user.id})+ # Removing a member from the organization does not clear their assignments. Keep a+ # former member's name and email out of events that go to the organization's destinations.+ if not assignment.user_is_member:+ return ResolvedAssignee(property_value=property_value, name=None, email=None)+ return ResolvedAssignee(+ property_value=property_value,+ name=user.get_full_name() or user.email,+ email=user.email,+ )+ if assignment.role is not None:+ return ResolvedAssignee(+ property_value=assignee_property({"type": "role", "id": assignment.role_id}),+ name=assignment.role.name,+ email=None,+ )+ return Nonediff --git a/products/error_tracking/backend/logic/issue_mutations.py b/products/error_tracking/backend/logic/issue_mutations.pyindex 2446a3230f82..dc802a0a6483 100644--- a/products/error_tracking/backend/logic/issue_mutations.py+++ b/products/error_tracking/backend/logic/issue_mutations.py@@ -19,6 +19,7 @@ from posthog.tasks.email import send_error_tracking_issue_assignedfrom products.access_control.backend.facade.api import role_belongs_to_organizationfrom products.cohorts.backend.facade.api import cohort_exists_for_teamfrom products.error_tracking.backend.logic import ErrorTrackingIssueNotFoundError, get_issue+from products.error_tracking.backend.logic.assignees import assignee_propertyfrom products.error_tracking.backend.logic.lifecycle_events import (ISSUE_ASSIGNED_EVENT,ISSUE_MERGED_EVENT,@@ -26,7 +27,6 @@ from products.error_tracking.backend.logic.lifecycle_events import (ISSUE_UNASSIGNED_EVENT,STATUS_CHANGE_EVENTS,PendingLifecycleEvent,- assignee_property,prepare_issue_lifecycle_event,produce_issue_lifecycle_event_on_commit,produce_issue_lifecycle_events_on_commit,diff --git a/products/error_tracking/backend/logic/lifecycle_events.py b/products/error_tracking/backend/logic/lifecycle_events.pyindex 207f99094ab6..9fb5e1979d82 100644--- a/products/error_tracking/backend/logic/lifecycle_events.py+++ b/products/error_tracking/backend/logic/lifecycle_events.py@@ -6,7 +6,6 @@ transitions that happen in Django so destinations subscribed to issue lifecycleevents see the full picture."""-import jsonimport uuidimport dataclassesfrom typing import Any, Optional@@ -18,11 +17,11 @@ import structlogfrom posthog.cdp.internal_events import InternalEventEvent, InternalEventPerson, produce_internal_eventfrom posthog.models.user import User+from products.error_tracking.backend.logic.assignees import resolve_current_assigneefrom products.error_tracking.backend.models import (ErrorTrackingAlert,ErrorTrackingAlertThread,ErrorTrackingIssue,- ErrorTrackingIssueAssignment,ErrorTrackingIssueFingerprintV2,)from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs@@ -55,25 +54,6 @@ def status_label(status: str) -> str:return status-def assignee_property(assignee: dict[str, Any]) -> str:- # Wire-compatible with cymbal's `Assignee` serialization on created/reopened events- # (compact serde JSON, adjacently tagged, numeric user ids and string role ids), so- # exact-match filters on the assignee property behave the same across all events.- assignee_id = int(assignee["id"]) if assignee["type"] == "user" else str(assignee["id"])- return json.dumps({"type": assignee["type"], "id": assignee_id}, separators=(",", ":"))---def _current_assignee_property(issue: ErrorTrackingIssue) -> Optional[str]:- assignment = ErrorTrackingIssueAssignment.objects.filter(issue_id=issue.id).only("user_id", "role_id").first()- if assignment is None:- return None- if assignment.user_id:- return assignee_property({"type": "user", "id": assignment.user_id})- if assignment.role_id:- return assignee_property({"type": "role", "id": assignment.role_id})- return None--def _issue_fingerprint_for_links(issue: ErrorTrackingIssue) -> Optional[str]:# Existing Error Tracking destination templates expect `fingerprint`. Manual# transitions have no triggering exception, so include one currently attached@@ -119,7 +99,12 @@ def prepare_issue_lifecycle_event(# falls back to the issue's latest exception instead of an empty window around# the mutation.fingerprint = _issue_fingerprint_for_links(issue)- current_assignee = _current_assignee_property(issue)+ current_assignee = resolve_current_assignee(issue.id)+ assignee_properties: dict[str, str] = (+ {"assignee": current_assignee.property_value, **current_assignee.display_properties()}+ if current_assignee is not None+ else {}+ )issue_id = str(issue.id)# The notification id names both the internal event and the alert delivery# workflow, so redelivered starts and retries stay idempotent per transition.@@ -135,7 +120,7 @@ def prepare_issue_lifecycle_event("severity": issue.severity,"status": status_label(status if status is not None else issue.status),**({"fingerprint": fingerprint} if fingerprint is not None else {}),- **({"assignee": current_assignee} if current_assignee is not None else {}),+ **assignee_properties,**(extra_properties or {}),}internal_event = InternalEventEvent(event=event, distinct_id=issue_id, properties=properties, uuid=notification_id)diff --git a/products/error_tracking/backend/temporal/lifecycle/side_effects.py b/products/error_tracking/backend/temporal/lifecycle/side_effects.pyindex 3dd43c24fe19..d5d945efe676 100644--- a/products/error_tracking/backend/temporal/lifecycle/side_effects.py+++ b/products/error_tracking/backend/temporal/lifecycle/side_effects.py@@ -14,6 +14,7 @@ from posthog.helpers.tiktoken_encoding import ()from posthog.models import Team+from products.error_tracking.backend.logic.assignees import resolve_current_assigneefrom products.error_tracking.backend.temporal.alerts.dispatch import start_alert_delivery_workflowfrom products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputsfrom products.error_tracking.backend.temporal.lifecycle.event_properties import (@@ -88,6 +89,18 @@ def _status_property(return _STATUS_LABELS.get(status, status) if humanize_status else status+def _assignee_display_properties(inputs: IssueLifecycleWorkflowInputs) -> dict[str, str]:+ if inputs.assignee is None:+ return {}+ resolved = resolve_current_assignee(inputs.issue_id)+ # Cymbal snapshots the assignee at ingestion, and the issue can be reassigned before+ # this activity runs. Names for a different assignee would contradict `assignee`,+ # so leave them out in that case.+ if resolved is None or resolved.property_value != inputs.assignee:+ return {}+ return resolved.display_properties()++def _normalize_timestamp(value: str) -> datetime:timestamp = parse_datetime(value)if timestamp is None:@@ -189,6 +202,7 @@ def produce_issue_lifecycle_internal_event(properties["status"] = status_propertyif inputs.assignee is not None:properties["assignee"] = inputs.assignee+ properties.update(_assignee_display_properties(inputs))if extra_properties is not None:properties.update(extra_properties)diff --git a/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.pyindex a78a22d8749d..fb9da964a9b5 100644--- a/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py+++ b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py@@ -1,4 +1,5 @@import copy+from collections.abc import Iteratorimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -8,6 +9,7 @@ from confluent_kafka import KafkaError, KafkaExceptionfrom posthog.cdp.internal_events import InternalEventEventfrom posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model+from products.error_tracking.backend.logic.assignees import ResolvedAssigneefrom products.error_tracking.backend.temporal.lifecycle.issue_created.types import (IssueCreatedSnapshot,IssueCreatedWorkflowInputs,@@ -28,6 +30,17 @@ from products.error_tracking.backend.temporal.lifecycle.side_effects import (produce_issue_lifecycle_internal_event,)+ASSIGNEE = '{"type":"user","id":1}'++[email protected](autouse=True)+def resolve_assignee() -> Iterator[MagicMock]:+ with patch(+ "products.error_tracking.backend.temporal.lifecycle.side_effects.resolve_current_assignee",+ return_value=None,+ ) as resolve:+ yield resolve+def _inputs() -> IssueReopenedWorkflowInputs:return IssueReopenedWorkflowInputs(@@ -44,7 +57,7 @@ def _inputs() -> IssueReopenedWorkflowInputs:fingerprint="fingerprint",event_uuid="01982721-5e00-7000-8000-000000000003",event_timestamp="2026-07-21T12:05:00Z",- assignee='{"type":"user","id":1}',+ assignee=ASSIGNEE,)@@ -98,8 +111,9 @@ def test_created_internal_event_preserves_raw_status() -> None:assert sent_events[0].properties["severity"] == "critical"-def test_oversized_internal_event_retries_without_exception_properties() -> None:+def test_oversized_internal_event_retries_without_exception_properties(resolve_assignee: MagicMock) -> None:inputs = _inputs()+ resolve_assignee.return_value = ResolvedAssignee(property_value=ASSIGNEE, name="Jane Doe", email="[email protected]")event_properties = {"$exception_list": [{"type": "TypeError", "value": "boom"}]}oversized_result = MagicMock()oversized_result.get.side_effect = KafkaException(KafkaError(KafkaError.MSG_SIZE_TOO_LARGE)) # type: ignore[attr-defined]@@ -151,6 +165,8 @@ def test_oversized_internal_event_retries_without_exception_properties() -> None"exception_props": event_properties,"status": "Pending Release","assignee": inputs.assignee,+ "assignee_name": "Jane Doe",+ "assignee_email": "[email protected]","attempt": 2,}assert sent_events[1].properties == {@@ -245,7 +261,55 @@ def test_alert_inputs_mirror_the_internal_event_and_key_the_exception_by_its_own_inputs(), event="$error_tracking_issue_reopened", exception_timestamp=_inputs().event_timestamp)assert reopened.status == "Pending Release"- assert reopened.assignee == '{"type":"user","id":1}'+ assert reopened.assignee == ASSIGNEE+++ "resolved, expected_names",+ [+ (+ ResolvedAssignee(property_value=ASSIGNEE, name="Jane Doe", email="[email protected]"),+ {"assignee_name": "Jane Doe", "assignee_email": "[email protected]"},+ ),+ (ResolvedAssignee(property_value='{"type":"role","id":"r1"}', name="Backend", email=None), {}),+ (None, {}),+ ],+ ids=["same_assignee", "reassigned_since_ingestion", "unassigned_since_ingestion"],+)+def test_internal_event_names_the_assignee_only_while_it_matches_the_snapshot(+ resolve_assignee: MagicMock, resolved: ResolvedAssignee | None, expected_names: dict[str, str]+) -> None:+ resolve_assignee.return_value = resolved+ sent_events: list[InternalEventEvent] = []++ def capture_event(_team_id: int, event: InternalEventEvent) -> MagicMock:+ sent_events.append(copy.deepcopy(event))+ return MagicMock()++ with (+ patch(+ "products.error_tracking.backend.temporal.lifecycle.side_effects.Team.objects.get",+ return_value=MagicMock(),+ ),+ patch(+ "products.error_tracking.backend.temporal.lifecycle.side_effects.fetch_event_properties",+ return_value={},+ ),+ patch(+ "products.error_tracking.backend.temporal.lifecycle.side_effects.produce_internal_event",+ side_effect=capture_event,+ ),+ patch("products.error_tracking.backend.temporal.lifecycle.side_effects.flush_internal_events_producer"),+ ):+ produce_issue_lifecycle_internal_event(+ _inputs(), event="$error_tracking_issue_reopened", exception_timestamp=_inputs().event_timestamp+ )++ properties = sent_events[0].properties+ assert properties["assignee"] == ASSIGNEE+ assert {key: value for key, value in properties.items() if key in ("assignee_name", "assignee_email")} == (+ expected_names+ )def test_dispatch_raises_so_the_activity_retries() -> None:diff --git a/products/error_tracking/backend/tests/api/test_error_tracking_api.py b/products/error_tracking/backend/tests/api/test_error_tracking_api.pyindex b48257632c5d..655081969843 100644--- a/products/error_tracking/backend/tests/api/test_error_tracking_api.py+++ b/products/error_tracking/backend/tests/api/test_error_tracking_api.py@@ -19,6 +19,7 @@ from rest_framework import statusfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.integration import Integration+from posthog.models.organization import OrganizationMembershipfrom posthog.models.scoping import team_scopefrom posthog.models.utils import uuid7from posthog.settings import (@@ -773,8 +774,15 @@ class TestErrorTracking(APIBaseTest):assert event.properties["status"] == "Resolved"assert event.properties["previous_status"] == "Active"- def test_issue_assign_produces_lifecycle_internal_event(self):+ @parameterized.expand([("user", "Jane"), ("user_without_name", ""), ("role", "Jane")])+ def test_issue_assign_produces_lifecycle_internal_event(self, case, first_name):+ assignee_type = "role" if case == "role" else "user"issue = self.create_issue()+ self.user.first_name = first_name+ self.user.last_name = "Doe" if first_name else ""+ self.user.save()+ role = Role.objects.create(name="Backend", organization=self.organization)+ assignee_id = self.user.id if assignee_type == "user" else str(role.id)with (patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,@@ -782,7 +790,7 @@ class TestErrorTracking(APIBaseTest):):response = self.client.patch(f"/api/environments/{self.team.id}/error_tracking/issues/{issue.id}/assign",- data={"assignee": {"id": self.user.id, "type": "user"}},+ data={"assignee": {"id": assignee_id, "type": assignee_type}},)assert response.status_code == 200, response.json()@@ -791,8 +799,44 @@ class TestErrorTracking(APIBaseTest):assert event.event == "$error_tracking_issue_assigned"assert event.distinct_id == str(issue.id)# Byte-identical to cymbal's compact serde output so exact-match filters work.- assert event.properties["assignee"] == f'{{"type":"user","id":{self.user.id}}}'- assert json.loads(event.properties["assignee"]) == {"type": "user", "id": self.user.id}+ user_assignee = f'{{"type":"user","id":{self.user.id}}}'+ expected_properties = {+ "user": {"assignee": user_assignee, "assignee_name": "Jane Doe", "assignee_email": self.user.email},+ "user_without_name": {+ "assignee": user_assignee,+ "assignee_name": self.user.email,+ "assignee_email": self.user.email,+ },+ "role": {"assignee": f'{{"type":"role","id":"{role.id}"}}', "assignee_name": "Backend"},+ }[case]+ assert {key: value for key, value in event.properties.items() if key.startswith("assignee")} == (+ expected_properties+ )+ assert json.loads(event.properties["assignee"]) == {"type": assignee_type, "id": assignee_id}++ def test_issue_lifecycle_event_omits_former_member_assignee_details(self):+ issue = self.create_issue()+ former_member = User.objects.create_and_join(self.organization, "[email protected]", "password", "Former")+ self.client.patch(+ f"/api/environments/{self.team.id}/error_tracking/issues/{issue.id}/assign",+ data={"assignee": {"id": former_member.id, "type": "user"}},+ )+ OrganizationMembership.objects.filter(user=former_member, organization=self.organization).delete()++ with (+ patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/error_tracking/issues/{issue.id}",+ data={"status": "resolved"},+ )++ assert response.status_code == 200, response.json()+ properties = mock_produce.call_args.kwargs["event"].properties+ assert properties["assignee"] == f'{{"type":"user","id":{former_member.id}}}'+ assert "assignee_name" not in properties+ assert "assignee_email" not in propertiesdef test_issue_unassign_produces_lifecycle_internal_event(self):issue = self.create_issue()diff --git a/products/error_tracking/skills/authoring-error-tracking-alerts/references/event-triggers.md b/products/error_tracking/skills/authoring-error-tracking-alerts/references/event-triggers.mdindex 5e6b2fc988b7..6d8aac789d9e 100644--- a/products/error_tracking/skills/authoring-error-tracking-alerts/references/event-triggers.md+++ b/products/error_tracking/skills/authoring-error-tracking-alerts/references/event-triggers.md@@ -92,6 +92,20 @@ detector is running.and `{project.name}`. The alert's own metadata is exposed as `{source.url}` and `{source.name}` —useful for "manage this alert" links inside the message body.+**Assignee** properties are present only when the issue has an assignee.+On an unassigned issue the keys are missing, so a test run against an unassigned issue does not show them.++- `event.properties.assignee` — a JSON string such as `{"type":"user","id":1234}`, not an object, so `event.properties.assignee.id` does not work.+ Use it for "is set" / "is not set" filters.+- `event.properties.assignee_name` — the user's full name (their email when they have no name), or the role name.+- `event.properties.assignee_email` — user assignees only.++The event keeps `assignee` but leaves out `assignee_name` and `assignee_email` in two cases: the assigned user has left the organization, or the issue was reassigned before the alert went out.+So a missing name does not mean the issue is unassigned.++To show the assignee in a message, use `{event.properties.assignee_name ?? (event.properties.assignee ? 'Assigned' : 'Unassigned')}`.+To alert only on unassigned issues, add the property filter `assignee` **is not set**.+**Deep-link shape** for the issue page (used by the canonical block templates):```text