: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
fix(conversations): harden slack nudge open-ticket click handling (#72687)
Luke Belton7681837d908e
diff --git a/products/conversations/backend/api/slack_interactivity.py b/products/conversations/backend/api/slack_interactivity.pyindex 9791f8cab060..65e6dddfcf27 100644--- a/products/conversations/backend/api/slack_interactivity.py+++ b/products/conversations/backend/api/slack_interactivity.py@@ -56,7 +56,11 @@ def supporthog_interactivity_handler(request: HttpRequest) -> HttpResponse:if team_exists_for_slack_workspace(slack_team_id) and not (settings.DEBUG and is_primary_region(request)):cast(Any, process_supporthog_interactivity).delay(payload=payload, slack_team_id=slack_team_id)elif is_primary_region(request):- proxy_to_secondary_region(request, log_prefix="supporthog_interactivity")+ # Acking a failed proxy with 200 makes the click silently vanish — Slack shows the+ # clicker nothing and never resends. Surface the failure so Slack displays a+ # delivery error and the user knows to click again.+ if not proxy_to_secondary_region(request, log_prefix="supporthog_interactivity"):+ return HttpResponse("Failed to reach owning region", status=502)else:logger.warning("supporthog_interactivity_no_team_any_region", slack_team_id=slack_team_id)diff --git a/products/conversations/backend/api/tests/test_slack_endpoints.py b/products/conversations/backend/api/tests/test_slack_endpoints.pyindex d5d5ba0314cc..15f4b03d7ebe 100644--- a/products/conversations/backend/api/tests/test_slack_endpoints.py+++ b/products/conversations/backend/api/tests/test_slack_endpoints.py@@ -243,6 +243,7 @@ class TestSupportSlackInteractivityAPI(BaseTest):self, mock_validate: MagicMock, mock_process: MagicMock, mock_proxy: MagicMock):mock_validate.return_value = None+ mock_proxy.return_value = Truewith patch("products.conversations.backend.api.slack_interactivity.is_primary_region", return_value=True):response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})@@ -251,6 +252,23 @@ class TestSupportSlackInteractivityAPI(BaseTest):mock_process.delay.assert_not_called()mock_proxy.assert_called_once()+ @patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")+ @patch("products.conversations.backend.api.slack_interactivity.process_supporthog_interactivity")+ @patch("products.conversations.backend.api.slack_interactivity.validate_support_request")+ def test_returns_502_when_proxy_to_secondary_fails(+ self, mock_validate: MagicMock, mock_process: MagicMock, mock_proxy: MagicMock+ ):+ # Acking a failed proxy with 200 silently drops the click — Slack shows the+ # clicker nothing and never resends. A non-2xx surfaces the failure in Slack.+ mock_validate.return_value = None+ mock_proxy.return_value = False++ with patch("products.conversations.backend.api.slack_interactivity.is_primary_region", return_value=True):+ response = self._post({"type": "block_actions", "team": {"id": "T_UNKNOWN"}})++ assert response.status_code == 502+ mock_process.delay.assert_not_called()+@patch("products.conversations.backend.api.slack_interactivity.proxy_to_secondary_region")@patch("products.conversations.backend.api.slack_interactivity.process_supporthog_interactivity")@patch("products.conversations.backend.api.slack_interactivity.validate_support_request")diff --git a/products/conversations/backend/api/tests/test_slack_message_routing.py b/products/conversations/backend/api/tests/test_slack_message_routing.pyindex b7311ba01d61..53dd7b617ad0 100644--- a/products/conversations/backend/api/tests/test_slack_message_routing.py+++ b/products/conversations/backend/api/tests/test_slack_message_routing.py@@ -6,7 +6,7 @@ from unittest.mock import Mock, patchfrom django.core.cache import cachefrom django.test import override_settings-from celery.exceptions import MaxRetriesExceededError+from celery.exceptions import MaxRetriesExceededError, Retryfrom parameterized import parameterizedfrom posthog.models.team.extensions import get_or_create_team_extension@@ -1093,16 +1093,10 @@ class TestSupporthogInteractivity(BaseTest):True,"ticket #42",True,+ # Placeholder ("opening a ticket") posted first, confirmation second.+ 2,),- (- "genuine_failure",- {"channel": "C_CONFIG", "message_ts": "1700000000.000100"},- None,- True,- "couldn't",- False,- ),- ("malformed_value", {}, None, False, "couldn't", False),+ ("malformed_value", {}, None, False, "couldn't", False, 1),])@patch(f"{TASKS_MODULE}.get_slack_client")@@ -1115,6 +1109,7 @@ class TestSupporthogInteractivity(BaseTest):expect_create_called,expected_text,expected_ticket_created,+ expected_update_count,mock_create,mock_get_client,):@@ -1124,7 +1119,7 @@ class TestSupporthogInteractivity(BaseTest):assert mock_create.call_count == (1 if expect_create_called else 0)client = mock_get_client.return_value- client.chat_update.assert_called_once()+ assert client.chat_update.call_count == expected_update_countassert expected_text in client.chat_update.call_args.kwargs["text"].lower()# The click lands in the nudge funnel with the outcome; prompts posted before the# verdict was stamped into the button value report "unknown".@@ -1136,17 +1131,96 @@ class TestSupporthogInteractivity(BaseTest):@patch(f"{TASKS_MODULE}.get_slack_client")@patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")- def test_open_shows_error_when_retries_exhausted(self, mock_create, mock_get_client):- # A persistent failure retries and eventually exhausts — the prompt must still be- # replaced with the error state, not left with live buttons forever.- mock_create.side_effect = RuntimeError("boom")+ def test_open_retries_when_create_returns_none(self, mock_create, mock_get_client):+ # A duplicate delivery that loses the per-thread create lock gets None back while+ # the sibling's ticket is mid-create. The task must retry — resolving to the+ # committed ticket on the re-run — not report a false "couldn't open a ticket"+ # to the user and a false ticket_created=false to the funnel.+ mock_create.return_value = None++ with self.assertRaises(Retry):+ process_supporthog_interactivity(+ self._payload(TICKET_CONFIRM_ACTION_OPEN, {"channel": "C_CONFIG", "message_ts": "1700000000.000100"}),+ "T123",+ )- with patch.object(process_supporthog_interactivity, "retry", side_effect=MaxRetriesExceededError()):+ self.mock_capture_event.assert_not_called()+ # Only the progress placeholder may have been posted — no final state yet.+ client = mock_get_client.return_value+ for update_call in client.chat_update.call_args_list:+ assert "opening" in update_call.kwargs["text"].lower()++ @patch(f"{TASKS_MODULE}.get_slack_client")+ @patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")+ def test_open_retries_when_final_prompt_update_fails(self, mock_create, mock_get_client):+ # If the final confirmation update fails transiently after the progress placeholder+ # was posted, the task must retry rather than leave the prompt stuck on+ # "Opening a ticket…" forever — and the funnel event must not fire before the+ # retry resolves.+ mock_create.return_value = Mock(ticket_number=42)+ mock_get_client.return_value.chat_update.side_effect = RuntimeError("slack down")++ with self.assertRaises(Retry):process_supporthog_interactivity(self._payload(TICKET_CONFIRM_ACTION_OPEN, {"channel": "C_CONFIG", "message_ts": "1700000000.000100"}),"T123",)+ self.mock_capture_event.assert_not_called()++ @patch(f"{TASKS_MODULE}.get_slack_client")+ @patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")+ def test_open_skips_placeholder_when_ticket_already_open(self, mock_create, mock_get_client):+ # A duplicate delivery arriving after a sibling already created the ticket must not+ # post the "opening" placeholder over the sibling's confirmation — only the final+ # confirmation update may go out.+ Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.SLACK,+ widget_session_id="",+ distinct_id="",+ slack_channel_id="C_CONFIG",+ slack_thread_ts="1700000000.000100",+ )+ mock_create.return_value = Mock(ticket_number=7)++ process_supporthog_interactivity(+ self._payload(TICKET_CONFIRM_ACTION_OPEN, {"channel": "C_CONFIG", "message_ts": "1700000000.000100"}),+ "T123",+ )+client = mock_get_client.return_valueclient.chat_update.assert_called_once()+ assert "ticket #7" in client.chat_update.call_args.kwargs["text"].lower()++ @parameterized.expand(+ [+ ("create_raises", RuntimeError("boom")),+ ("create_returns_none", None),+ ]+ )+ @patch(f"{TASKS_MODULE}.get_slack_client")+ @patch(f"{TASKS_MODULE}.create_ticket_from_confirmation")+ def test_open_shows_error_when_retries_exhausted(self, _name, failure, mock_create, mock_get_client):+ # A persistent failure (create raising, or a None that never resolves into a+ # ticket) retries and eventually exhausts — the prompt must still be replaced+ # with the error state, not left with live buttons forever.+ if isinstance(failure, Exception):+ mock_create.side_effect = failure+ else:+ mock_create.return_value = failure++ with patch.object(process_supporthog_interactivity, "retry", side_effect=MaxRetriesExceededError()):+ process_supporthog_interactivity(+ self._payload(TICKET_CONFIRM_ACTION_OPEN, {"channel": "C_CONFIG", "message_ts": "1700000000.000100"}),+ "T123",+ )++ client = mock_get_client.return_value+ # Progress placeholder first, then the error state — never left on the placeholder.+ assert client.chat_update.call_count == 2assert "couldn't" in client.chat_update.call_args.kwargs["text"].lower()+ self.mock_capture_event.assert_called_once()+ _team, event_name, event_props = self.mock_capture_event.call_args.args+ assert event_name == "support nudge open ticket clicked"+ assert event_props["ticket_created"] is Falsediff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex 91d06a80f236..e8f2ac716d7c 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -1081,7 +1081,9 @@ def create_ticket_from_confirmation(Mirrors the emoji-reaction path: re-fetch the source message, create the ticket, thenbackfill any replies posted while the prompt was pending. Idempotent — a duplicateclick returns the already-open ticket so the caller can confirm rather than error.- Returns None only on genuine failure (source message gone, fetch error, empty content).+ Returns None on genuine failure (source message gone, fetch error, empty content), but+ also when a concurrent duplicate delivery holds the create lock mid-flight — callers+ should treat None as retryable, since a re-run resolves to the winner's committed ticket."""existing = Ticket.objects.filter(team=team, slack_channel_id=slack_channel_id, slack_thread_ts=message_ts).first()if existing:diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex 6919e367c991..517b03ff4da3 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -19,7 +19,7 @@ from django.utils import timezoneimport requestsimport structlogfrom celery import shared_task-from celery.exceptions import MaxRetriesExceededError+from celery.exceptions import MaxRetriesExceededError, Retryfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity@@ -185,13 +185,15 @@ def _delete_supporthog_prompt(team: Team, channel: str, message_ts: str) -> Nonelogger.warning("supporthog_interactivity_prompt_delete_failed", exc_info=True)-def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: str) -> None:- """Replace the "open a ticket?" prompt in place with a final status line (buttons removed).+def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: str) -> bool:+ """Replace the "open a ticket?" prompt in place with a new status line (buttons removed).- Best-effort: a failure here never blocks the ticket creation that already ran.+ Never raises — a failure here must not block the ticket creation that already ran —+ but reports success so callers can retry updates that must not be lost (the final+ confirmation/error state, as opposed to the best-effort progress placeholder)."""if not channel or not message_ts:- return+ return Falsetry:get_slack_client(team).chat_update(channel=channel,@@ -199,8 +201,10 @@ def _update_supporthog_prompt(team: Team, channel: str, message_ts: str, text: stext=text,blocks=[{"type": "section", "text": {"type": "mrkdwn", "text": text}}],)+ return Trueexcept Exception:logger.warning("supporthog_interactivity_prompt_update_failed", exc_info=True)+ return Falsedef _post_dismiss_acknowledgment(team: Team, channel: str, user: str, thread_ts: str) -> None:@@ -283,6 +287,19 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: strif action_id == TICKET_CONFIRM_ACTION_OPEN:ticket = Noneif source_channel and source_message_ts:+ # Ticket creation takes several seconds (Slack fetches + backfill) and the+ # click may have crossed a region on the way here — replace the buttons with+ # a progress line right away so the click visibly landed and repeat clicks+ # stop. First attempt only, and only while no sibling delivery has already+ # resolved the prompt (a stale placeholder must not overwrite a confirmation).+ is_retry = bool(getattr(cast(Any, process_supporthog_interactivity).request, "retries", 0))+ ticket_already_open = Ticket.objects.filter(+ team=team, slack_channel_id=source_channel, slack_thread_ts=source_message_ts+ ).exists()+ if not is_retry and not ticket_already_open:+ _update_supporthog_prompt(+ team, prompt_channel, prompt_ts, ":hourglass_flowing_sand: Opening a ticket…"+ )try:ticket = create_ticket_from_confirmation(team=team,@@ -290,6 +307,18 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: strslack_channel_id=source_channel,message_ts=source_message_ts,)+ if ticket is None:+ # A duplicate delivery (double click or webhook retry) can lose the+ # per-thread create lock to a concurrent sibling and see None while+ # the sibling's ticket is mid-create. Retry instead of reporting a+ # false failure — the re-run resolves to the committed ticket via+ # the existing-ticket check in create_ticket_from_confirmation.+ # Genuine failures exhaust retries into the error update below.+ raise cast(Any, process_supporthog_interactivity).retry()+ except Retry:+ raise+ except MaxRetriesExceededError:+ passexcept Exception as e:logger.exception("supporthog_interactivity_create_failed", error=str(e))# Retry transient failures — the retried run redoes the whole handler,@@ -300,7 +329,25 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: strraise cast(Any, process_supporthog_interactivity).retry(exc=e)except MaxRetriesExceededError:pass- # Captured after retries resolve (the retry re-raise above exits the task first),+ # Replace the prompt in place: a confirmation when we have a ticket (created or+ # already open), or an explicit error so a failed open never reads as success.+ # post_confirmation=False above means no separate confirmation was posted.+ if ticket:+ text = ticket_created_text(ticket)+ else:+ emoji = get_safe_ticket_emoji(support_settings)+ text = f":warning: Couldn't open a ticket — react with :{emoji}: or @mention us to try again."+ final_update_ok = _update_supporthog_prompt(team, prompt_channel, prompt_ts, text)+ if not final_update_ok and prompt_channel and prompt_ts:+ # The progress placeholder must never be the prompt's last word — if the+ # final update fails transiently, retry the task (creation is idempotent,+ # the re-run re-attempts just this update). Once retries are exhausted,+ # fall through so the funnel event still records the outcome.+ try:+ raise cast(Any, process_supporthog_interactivity).retry()+ except MaxRetriesExceededError:+ pass+ # Captured after all retry exits (each retry re-raise leaves the task first),# so the event fires once with the final outcome.capture_nudge_event(team,@@ -311,15 +358,6 @@ def process_supporthog_interactivity(payload: dict[str, Any], slack_team_id: str"ticket_id": str(ticket.id) if ticket else None,},)- # Replace the prompt in place: a confirmation when we have a ticket (created or- # already open), or an explicit error so a failed open never reads as success.- # post_confirmation=False above means no separate confirmation was posted.- if ticket:- text = ticket_created_text(ticket)- else:- emoji = get_safe_ticket_emoji(support_settings)- text = f":warning: Couldn't open a ticket — react with :{emoji}: or @mention us to try again."- _update_supporthog_prompt(team, prompt_channel, prompt_ts, text)return