: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: prevent duplicate tickets from concurrent Slack reactions (#65508)
Alex V757e66dedafd
diff --git a/products/conversations/backend/api/tests/test_reaction_backfill.py b/products/conversations/backend/api/tests/test_reaction_backfill.pyindex 067bf2cf2fcf..0244a13bc2b2 100644--- a/products/conversations/backend/api/tests/test_reaction_backfill.py+++ b/products/conversations/backend/api/tests/test_reaction_backfill.py@@ -1,3 +1,5 @@+from typing import Any+from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, call, patch@@ -5,9 +7,14 @@ from parameterized import parameterizedfrom posthog.models.comment import Comment+from products.conversations.backend.cache import slack_ticket_create_lockfrom products.conversations.backend.models import Ticket-from products.conversations.backend.models.constants import Channel-from products.conversations.backend.slack import _backfill_thread_replies, handle_support_reaction+from products.conversations.backend.models.constants import Channel, ChannelDetail+from products.conversations.backend.slack import (+ _backfill_thread_replies,+ create_or_update_slack_ticket,+ handle_support_reaction,+)def _make_slack_reply(ts: str, user: str = "U_REPLY", text: str = "reply text", **extra) -> dict:@@ -445,3 +452,116 @@ class TestHandleSupportReactionBackfill(BaseTest):mock_client.assert_not_called()mock_create.assert_not_called()mock_backfill.assert_not_called()+++class TestSlackTicketCreateLockDedup(BaseTest):+ """Verify that the Redis lock in create_or_update_slack_ticket prevents duplicate tickets."""++ def setUp(self):+ super().setUp()+ self.team.conversations_settings = {"slack_enabled": True}+ self.team.save()++ @patch(f"{MODULE}.get_slack_client")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_second_call_returns_none_when_first_already_created(self, _files, _user, mock_client):+ mock_client.return_value = MagicMock()+ mock_client.return_value.chat_postMessage = MagicMock()++ kwargs: dict[str, Any] = {+ "team": self.team,+ "slack_channel_id": CHANNEL,+ "thread_ts": PARENT_TS,+ "slack_user_id": "U_SOMEONE",+ "text": "Help me please",+ "is_thread_reply": False,+ "slack_team_id": SLACK_TEAM,+ "channel_detail": ChannelDetail.SLACK_EMOJI_REACTION,+ }++ # First call creates the ticket+ ticket1 = create_or_update_slack_ticket(**kwargs)+ # Second call hits the re-check inside the lock and returns None (not the existing+ # ticket) so callers don't re-run backfill side effects.+ ticket2 = create_or_update_slack_ticket(**kwargs)++ tickets = Ticket.objects.filter(team=self.team, slack_channel_id=CHANNEL, slack_thread_ts=PARENT_TS)+ assert tickets.count() == 1+ assert ticket1 is not None+ assert ticket2 is None+ # Only one confirmation message posted (second call short-circuits)+ assert mock_client.return_value.chat_postMessage.call_count == 1++ @patch(f"{MODULE}.get_slack_client")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Bob", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_lock_held_returns_without_creating_duplicate(self, _files, _user, mock_client):+ mock_client.return_value = MagicMock()++ # Pre-acquire the lock via production code to simulate a concurrent worker holding it+ with slack_ticket_create_lock(self.team.id, CHANNEL, PARENT_TS) as acquired:+ assert acquired++ result = create_or_update_slack_ticket(+ team=self.team,+ slack_channel_id=CHANNEL,+ thread_ts=PARENT_TS,+ slack_user_id="U_SOMEONE",+ text="Help!",+ is_thread_reply=False,+ slack_team_id=SLACK_TEAM,+ channel_detail=ChannelDetail.SLACK_EMOJI_REACTION,+ )++ # No ticket created — lock was held+ assert (+ Ticket.objects.filter(team=self.team, slack_channel_id=CHANNEL, slack_thread_ts=PARENT_TS).count() == 0+ )+ assert result is None+ # No confirmation posted+ mock_client.return_value.chat_postMessage.assert_not_called()++ @patch(f"{MODULE}.get_bot_user_id", return_value="U_BOT")+ @patch(f"{MODULE}.get_slack_client")+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Cara", "email": "[email protected]", "avatar": None})+ @patch(f"{MODULE}.extract_slack_files", return_value=[])+ def test_dedup_create_returns_none_so_caller_skips_backfill(self, _files, _user, mock_client, _bot):+ # Reproduces the race where two reaction events both pass handle_support_reaction's+ # .exists() fast-path, then both reach create. The caller backfills only when create+ # returns a ticket — so the loser must get None or the backfill duplicates comments.+ reply_ts = "1700000000.000500"+ client = MagicMock()+ client.conversations_replies.return_value = {+ "messages": [+ {"user": "U_ROOT", "text": "Help me please", "ts": PARENT_TS},+ {"user": "U_CUSTOMER", "text": "more context", "ts": reply_ts, "thread_ts": PARENT_TS},+ ]+ }+ mock_client.return_value = client++ kwargs: dict[str, Any] = {+ "team": self.team,+ "slack_channel_id": CHANNEL,+ "thread_ts": PARENT_TS,+ "slack_user_id": "U_ROOT",+ "text": "Help me please",+ "is_thread_reply": False,+ "slack_team_id": SLACK_TEAM,+ "channel_detail": ChannelDetail.SLACK_EMOJI_REACTION,+ }++ # Mirror handle_support_reaction: create, then backfill iff a ticket came back.+ for _ in range(2):+ ticket = create_or_update_slack_ticket(**kwargs)+ if ticket:+ _backfill_thread_replies(client, self.team, ticket, CHANNEL, PARENT_TS, after_ts=PARENT_TS)++ tickets = Ticket.objects.filter(team=self.team, slack_channel_id=CHANNEL, slack_thread_ts=PARENT_TS)+ assert tickets.count() == 1+ created_ticket = tickets.first()+ assert created_ticket is not None+ # One seed comment + one backfilled reply. The duplicate call returns None, so backfill+ # runs only once and comments aren't doubled.+ comments = Comment.objects.filter(scope="conversations_ticket", item_id=str(created_ticket.id))+ assert comments.count() == 2diff --git a/products/conversations/backend/cache.py b/products/conversations/backend/cache.pyindex 426052bdfe17..757ed4cd6925 100644--- a/products/conversations/backend/cache.py+++ b/products/conversations/backend/cache.py@@ -7,6 +7,8 @@ Short TTLs ensure stale data expires quickly without explicit invalidation.import jsonimport hashlib+from collections.abc import Generator+from contextlib import contextmanagerfrom django.core.cache import cache@@ -293,6 +295,31 @@ RESOLVED_GROUPS_CACHE_TTL = 12 * 60 * 60 # 12 hoursRESOLVED_GROUPS_NEGATIVE_CACHE_TTL = 60 * 60 # 1 hour+# Slack Ticket Creation Lock+# Serializes concurrent ticket creation for the same Slack thread so two reaction_added+# events from different users can't both pass the existence checks and create duplicate+# tickets. cache.add is atomic (Redis SETNX): only one worker acquires. Short TTL is a+# safety net so a crashed worker can't wedge a thread permanently.++SLACK_TICKET_CREATE_LOCK_TTL = 30 # seconds+++@contextmanager+def slack_ticket_create_lock(team_id: int, channel: str, thread_ts: str) -> Generator[bool]:+ """Atomic Redis lock to serialize ticket creation for a Slack thread.++ Yields True if the lock was acquired, False if another worker holds it.+ Releases the lock on exit when acquired.+ """+ key = _make_cache_key("slack_ticket_create_lock", str(team_id), channel, thread_ts)+ acquired = cache.add(key, True, timeout=SLACK_TICKET_CREATE_LOCK_TTL)+ try:+ yield acquired+ finally:+ if acquired:+ cache.delete(key)++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"]).diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex 1579093f6edb..8ce9f860d7aa 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -32,6 +32,7 @@ from .cache import (set_cached_bot_user_id,set_cached_slack_avatar,set_cached_slack_user,+ slack_ticket_create_lock,)from .formatting import extract_slack_user_ids, slack_to_content_and_rich_contentfrom .models import Ticket@@ -469,22 +470,44 @@ def create_or_update_slack_ticket(content, rich_content = _build_content_with_images(cleaned_text, rich_content, images)- ticket = Ticket.objects.create_with_number(- team=team,- channel_source=Channel.SLACK,- channel_detail=channel_detail,- widget_session_id="", # Not used for Slack tickets- distinct_id=user_info.get("email") or "",- status=Status.NEW,- anonymous_traits={- "name": user_info["name"],- **({"email": user_info["email"]} if user_info["email"] else {}),- },- slack_channel_id=slack_channel_id,- slack_thread_ts=thread_ts,- slack_team_id=slack_team_id,- unread_team_count=0 if is_team_member else 1,- )+ # Serialize concurrent ticket creation for the same Slack thread via Redis lock.+ # Without this, two reaction_added events from different users race through the+ # .exists() checks above and both create a ticket.+ with slack_ticket_create_lock(team_id, slack_channel_id, thread_ts) as acquired:+ # Return None (not the existing ticket) on every dedup path: the winning worker+ # owns the create-side effects (first comment, confirmation message, and the+ # caller's _backfill_thread_replies). Handing a non-None ticket back to a losing+ # reaction/mention would re-trigger backfill and duplicate every thread comment.+ if not acquired:+ logger.info(+ "slack_ticket_create_lock_not_acquired",+ team_id=team_id,+ slack_channel_id=slack_channel_id,+ thread_ts=thread_ts,+ )+ return None++ # Re-check after acquiring — the winner may have committed between our earlier+ # .exists() call and now.+ if Ticket.objects.filter(team=team, slack_channel_id=slack_channel_id, slack_thread_ts=thread_ts).exists():+ return None++ ticket = Ticket.objects.create_with_number(+ team=team,+ channel_source=Channel.SLACK,+ channel_detail=channel_detail,+ widget_session_id="", # Not used for Slack tickets+ distinct_id=user_info.get("email") or "",+ status=Status.NEW,+ anonymous_traits={+ "name": user_info["name"],+ **({"email": user_info["email"]} if user_info["email"] else {}),+ },+ slack_channel_id=slack_channel_id,+ slack_thread_ts=thread_ts,+ slack_team_id=slack_team_id,+ unread_team_count=0 if is_team_member else 1,+ )Comment.objects.create(team=team,