: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(workflows): attribute unsubscribes to the run and version that sent the email (#127115)
Michael Reichenbach72c2e50becc7
diff --git a/products/messaging/backend/facade/preferences.py b/products/messaging/backend/facade/preferences.pyindex 147a707d7846..7d53fc89d4e0 100644--- a/products/messaging/backend/facade/preferences.py+++ b/products/messaging/backend/facade/preferences.py@@ -17,6 +17,7 @@ from products.messaging.backend.services import ()from products.messaging.backend.services.lazy_list import LazyListfrom products.messaging.backend.services.opt_out_service import BulkOptOutEntry, UnknownCategoryError+from products.messaging.backend.services.unsubscribe_metrics import EmailSendReferenceALL_MESSAGE_PREFERENCE_CATEGORY_ID: str = preference_model.ALL_MESSAGE_PREFERENCE_CATEGORY_IDEMAIL_TRACKING_PREFERENCE_ID: str = preference_model.EMAIL_TRACKING_PREFERENCE_ID@@ -237,3 +238,7 @@ def record_unsubscribe_metric(team_id: int, token_data: dict[str, Any], opted_ouunsubscribe_metrics.record_email_unsubscribed_metric(team_id, unsubscribe_metrics.parse_unsubscribe_source(token_data), opted_out_category_ids)+++def email_send_reference(token_data: dict[str, Any]) -> EmailSendReference | None:+ return unsubscribe_metrics.parse_email_send_reference(token_data)diff --git a/products/messaging/backend/presentation/views/recipient_preferences.py b/products/messaging/backend/presentation/views/recipient_preferences.pyindex 8f8838b5c0a3..d88387aff9ea 100644--- a/products/messaging/backend/presentation/views/recipient_preferences.py+++ b/products/messaging/backend/presentation/views/recipient_preferences.py@@ -15,9 +15,11 @@ from posthog.plugins.plugin_server_api import validate_messaging_preferences_tokfrom products.messaging.backend.facade.preferences import (ALL_MESSAGE_PREFERENCE_CATEGORY_ID,EMAIL_TRACKING_PREFERENCE_ID,+ EmailSendReference,PreferenceStatus,all_preference_statuses,category_ids as team_category_ids,+ email_send_reference,get_or_create_recipient,marketing_categories,preference_status,@@ -30,14 +32,16 @@ from products.workflows.backend.facade.enums import EmailTrackingConsentModelogger = structlog.get_logger(__name__)-def report_workflows_email_unsubscribed(team_id: int, identifier: str, category_ids: list[str], source: str) -> None:+def report_workflows_email_unsubscribed(+ team_id: int, identifier: str, category_ids: list[str], source: str, send: EmailSendReference | None+) -> None:"""Emit $workflows_email_unsubscribed engagement events into the customer's project.Mirrors the plugin-server's $workflows_email_* engagement events (email-tracking.service.ts),- gated on the same capture_workflows_engagement_events team flag. The unsubscribe token only- carries team_id + identifier, so this event is email-level: distinct_id is the recipient's- email, and no workflow/action id is available. Best-effort — never fails the unsubscribe flow.+ gated on the same capture_workflows_engagement_events team flag. distinct_id is the recipient's+ email. A link from a workflow email names the workflow, step, run and version that sent it;+ older links name none. Best-effort — never fails the unsubscribe flow."""try:team = Team.objects.get(id=team_id)@@ -61,6 +65,7 @@ def report_workflows_email_unsubscribed(team_id: int, identifier: str, category_"$email": identifier,"category": category_id,"source": source,+ **(send.event_properties() if send else {}),}try:result = capture_internal(@@ -167,7 +172,13 @@ def preferences_page(request: HttpRequest, token: str) -> HttpResponse:# Only a genuine transition emits, so token replays and scanner prefetches don't inflate eventsif not was_fully_opted_out:record_unsubscribe_metric(team_id, data, [ALL_MESSAGE_PREFERENCE_CATEGORY_ID])- report_workflows_email_unsubscribed(team_id, identifier, [ALL_MESSAGE_PREFERENCE_CATEGORY_ID], "one_click")+ report_workflows_email_unsubscribed(+ team_id,+ identifier,+ [ALL_MESSAGE_PREFERENCE_CATEGORY_ID],+ "one_click",+ email_send_reference(data),+ )# A mail client's unsubscribe button gets an empty 200. The confirm form gets the success page.if request.POST.get("List-Unsubscribe") == "One-Click":@@ -296,7 +307,9 @@ def update_preferences(request: HttpRequest) -> JsonResponse:]if newly_opted_out:record_unsubscribe_metric(team_id, data, newly_opted_out)- report_workflows_email_unsubscribed(team_id, identifier, newly_opted_out, "preferences_page")+ report_workflows_email_unsubscribed(+ team_id, identifier, newly_opted_out, "preferences_page", email_send_reference(data)+ )new_tracking_consent = preferences_dict.get(EMAIL_TRACKING_PREFERENCE_ID)if new_tracking_consent is not None and new_tracking_consent != prior_preferences.get(diff --git a/products/messaging/backend/services/unsubscribe_metrics.py b/products/messaging/backend/services/unsubscribe_metrics.pyindex 3aea6d34e2ba..6beb400124e2 100644--- a/products/messaging/backend/services/unsubscribe_metrics.py+++ b/products/messaging/backend/services/unsubscribe_metrics.py@@ -41,6 +41,40 @@ def parse_unsubscribe_source(token_data: dict[str, Any]) -> UnsubscribeSource |return UnsubscribeSource(app_source_id=app_source_id, instance_id=instance_id)+@frozen+class EmailSendReference:+ workflow_id: str+ action_id: str | None+ invocation_id: str+ workflow_version: int | None++ def event_properties(self) -> dict[str, Any]:+ properties = {+ "$workflow_id": self.workflow_id,+ "$workflow_action_id": self.action_id,+ "$workflow_invocation_id": self.invocation_id,+ "$workflow_version": self.workflow_version,+ }+ return {key: value for key, value in properties.items() if value is not None}+++def parse_email_send_reference(token_data: dict[str, Any]) -> EmailSendReference | None:+ workflow_id = token_data.get("workflow_id")+ invocation_id = token_data.get("invocation_id")+ if not isinstance(workflow_id, str) or not isinstance(invocation_id, str):+ return None+ action_id = token_data.get("instance_id")+ workflow_version = token_data.get("workflow_version")+ return EmailSendReference(+ workflow_id=workflow_id,+ action_id=action_id if isinstance(action_id, str) and _INSTANCE_ID_PATTERN.match(action_id) else None,+ invocation_id=invocation_id,+ workflow_version=workflow_version+ if isinstance(workflow_version, int) and not isinstance(workflow_version, bool)+ else None,+ )++def _includes_real_category(team_id: int, category_ids: list[str]) -> bool:# The preferences form accepts any category id string, so made-up ids must not add to the count.if ALL_MESSAGE_PREFERENCE_CATEGORY_ID in category_ids:diff --git a/products/messaging/backend/tests/api/test_message_preferences.py b/products/messaging/backend/tests/api/test_message_preferences.pyindex 140d00eb99bf..8a4cd03f3932 100644--- a/products/messaging/backend/tests/api/test_message_preferences.py+++ b/products/messaging/backend/tests/api/test_message_preferences.py@@ -22,6 +22,14 @@ from products.messaging.backend.models.message_preferences import (PreferenceStatus,)+SEND_CLAIMS = {+ "app_source_id": "flow-1",+ "instance_id": "action-1",+ "workflow_id": "flow-1",+ "invocation_id": "run-1",+ "workflow_version": 3,+}+STYLESHEET_LINK = '<link rel="stylesheet" href="/static/message-preferences.css" />'@@ -338,14 +346,46 @@ class TestMessagePreferencesViews(BaseTest):config.capture_workflows_engagement_events = Trueconfig.save()+ @parameterized.expand(+ [+ ("a link that names no email", {}, {}),+ ("a link that names the email but not its run", {"app_source_id": "flow-1", "instance_id": "action-1"}, {}),+ (+ "a link that names the step, run and version that sent it",+ SEND_CLAIMS,+ {+ "$workflow_id": "flow-1",+ "$workflow_action_id": "action-1",+ "$workflow_invocation_id": "run-1",+ "$workflow_version": 3,+ },+ ),+ (+ "a link that names its run but not its step or version",+ {"app_source_id": "batch-run-1", "workflow_id": "flow-1", "invocation_id": "run-1"},+ {"$workflow_id": "flow-1", "$workflow_invocation_id": "run-1"},+ ),+ ("a link whose run id is not a string", {**SEND_CLAIMS, "invocation_id": 42}, {}),+ (+ "a link whose step id the metric rejects",+ {**SEND_CLAIMS, "instance_id": "action 1"},+ {"$workflow_id": "flow-1", "$workflow_invocation_id": "run-1", "$workflow_version": 3},+ ),+ (+ "a link whose version is not an integer",+ {**SEND_CLAIMS, "workflow_version": True},+ {"$workflow_id": "flow-1", "$workflow_action_id": "action-1", "$workflow_invocation_id": "run-1"},+ ),+ ]+ )@patch("products.messaging.backend.presentation.views.recipient_preferences.capture_internal")@patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_one_click_unsubscribe_emits_unsubscribed_event(- self, mock_validate_messaging_preferences_token, mock_capture_internal+ self, _name, token_claims, send_properties, mock_validate_messaging_preferences_token, mock_capture_internal):self._enable_engagement_events()mock_validate_messaging_preferences_token.return_value = mock_response(- 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier, **token_claims})response = self._post_one_click()@@ -360,6 +400,7 @@ class TestMessagePreferencesViews(BaseTest):"$email": self.recipient.identifier,"category": ALL_MESSAGE_PREFERENCE_CATEGORY_ID,"source": "one_click",+ **send_properties,},)@@ -383,7 +424,7 @@ class TestMessagePreferencesViews(BaseTest):}self.recipient.save()mock_validate_messaging_preferences_token.return_value = mock_response(- 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier, **SEND_CLAIMS})data = {@@ -403,6 +444,7 @@ class TestMessagePreferencesViews(BaseTest):)for call in mock_capture_internal.call_args_list:self.assertEqual(call.kwargs["properties"]["source"], "preferences_page")+ self.assertEqual(call.kwargs["properties"]["$workflow_invocation_id"], "run-1")@parameterized.expand(["one_click", "preferences_form"])@patch("products.messaging.backend.presentation.views.recipient_preferences.capture_internal")