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.

fix(conversations): make compose ticket creation idempotent (#90173)

posthog[bot]0d94853292a6
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index 028e19d9667e..66de0444e00b 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -38,6 +38,7 @@ from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.role import Role
+from products.conversations.backend import reply_dedupe
from products.conversations.backend.api.ticket_filters import query_params_to_view_filters
from products.conversations.backend.api.tickets import ComposeTicketSerializer, TicketReplyRequestSerializer
from products.conversations.backend.models import (
@@ -51,7 +52,12 @@ from products.conversations.backend.models import (
)
from products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Status
from products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_email
-from products.conversations.backend.reply_dedupe import REPLY_IN_PROGRESS_ERROR_TYPE, ReplyFingerprint, reserve
+from products.conversations.backend.reply_dedupe import (
+ REPLY_IN_PROGRESS_ERROR_TYPE,
+ ComposeFingerprint,
+ ReplyFingerprint,
+ reserve,
+)
from ee.clickhouse.materialized_columns.columns import get_bloom_filter_lower_index_name
@@ -2079,6 +2085,9 @@ class TestComposeTicketAPI(APIBaseTest):
domain_verified=True,
inbound_token="test-token-compose",
)
+ # fakeredis keeps one FakeServer per process, so dedupe reservations would otherwise leak
+ # between tests.
+ get_client().flushall()
def _compose(self, data):
return self.client.post(
@@ -2233,6 +2242,204 @@ class TestComposeTicketAPI(APIBaseTest):
assert search.status_code == status.HTTP_200_OK
assert [t["id"] for t in search.json()["results"]] == [str(ticket.id)]
+ def test_compose_identical_request_is_idempotent(self, mock_on_commit):
+ # A caller that retries a slow compose (e.g. a workflow webhook whose fetch timed out) must
+ # get the same ticket back, not a second one — and the customer must not be emailed twice.
+ payload = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ "email_subject": "Thanks for your pitch",
+ "message": "Great idea, we logged it.",
+ }
+
+ first = self._compose(payload)
+ second = self._compose(payload)
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_200_OK
+ assert first.json() == second.json()
+ assert Ticket.objects.filter(team=self.team).count() == 1
+ assert Comment.objects.filter(scope="conversations_ticket", item_id=first.json()["id"]).count() == 1
+
+ def test_compose_recovers_the_existing_ticket_when_the_reservation_is_lost(self, mock_on_commit):
+ # The Redis reservation can vanish (eviction, restart) after a ticket commits. A retry then
+ # reserves cleanly and must recover the existing ticket from the database — via
+ # find_persisted_match — instead of opening a second one and re-emailing the customer.
+ payload = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ "email_subject": "Thanks for your pitch",
+ "message": "Great idea, we logged it.",
+ }
+
+ first = self._compose(payload)
+ assert first.status_code == status.HTTP_201_CREATED
+ get_client().flushall()
+
+ second = self._compose(payload)
+
+ assert second.status_code == status.HTTP_200_OK
+ assert second.json() == first.json()
+ assert Ticket.objects.filter(team=self.team).count() == 1
+
+ def test_compose_distinct_messages_are_not_deduplicated(self, mock_on_commit):
+ base = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ }
+
+ first = self._compose({**base, "message": "First idea"})
+ second = self._compose({**base, "message": "Second, different idea"})
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_201_CREATED
+ assert first.json()["id"] != second.json()["id"]
+ assert Ticket.objects.filter(team=self.team).count() == 2
+
+ def test_compose_same_message_to_different_persons_is_not_deduplicated(self, mock_on_commit):
+ # Two people can share one email address (person merging leaves this common). A compose to
+ # each — same subject and body, different recipient_distinct_id — is two distinct tickets,
+ # each linked to its own person. The fingerprint must not collapse them onto one.
+ _create_person(
+ team=self.team,
+ distinct_ids=["person-a"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ _create_person(
+ team=self.team,
+ distinct_ids=["person-b"],
+ properties={"email": "[email protected]"},
+ immediate=True,
+ )
+ base = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ "message": "Same body",
+ }
+
+ first = self._compose({**base, "recipient_distinct_id": "person-a"})
+ second = self._compose({**base, "recipient_distinct_id": "person-b"})
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_201_CREATED
+ assert first.json()["id"] != second.json()["id"]
+ assert Ticket.objects.filter(team=self.team).count() == 2
+ assert Ticket.objects.get(pk=first.json()["id"]).distinct_id == "person-a"
+ assert Ticket.objects.get(pk=second.json()["id"]).distinct_id == "person-b"
+
+ def test_compose_same_content_from_different_agents_is_not_deduplicated(self, mock_on_commit):
+ # Two support agents can each reach out to the same recipient with the same subject and body
+ # within the dedupe window. Those are two distinct tickets, each authored by its own agent,
+ # so the fingerprint must not collapse them onto one.
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ payload = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ "message": "Same body",
+ }
+
+ first = self._compose(payload)
+ self.client.force_login(other_user)
+ second = self._compose(payload)
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_201_CREATED
+ assert first.json()["id"] != second.json()["id"]
+ assert Ticket.objects.filter(team=self.team).count() == 2
+
+ def test_compose_same_content_with_different_tags_is_not_deduplicated(self, mock_on_commit):
+ # A different tag set must open its own ticket, not silently drop the tags of a replay.
+ base = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ "message": "Great idea, we logged it.",
+ }
+
+ first = self._compose({**base, "tags": ["roadmap_pitch"]})
+ second = self._compose({**base, "tags": ["bug_report"]})
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_201_CREATED
+ assert first.json()["id"] != second.json()["id"]
+ assert Ticket.objects.filter(team=self.team).count() == 2
+
+ first_detail = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{first.json()['id']}/")
+ second_detail = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{second.json()['id']}/")
+ assert first_detail.json()["tags"] == ["roadmap_pitch"]
+ assert second_detail.json()["tags"] == ["bug_report"]
+
+ def test_compose_recovers_the_existing_ticket_past_newer_unrelated_tickets(self, mock_on_commit):
+ # A burst of newer, unrelated tickets to the same channel must not crowd out the real match.
+ payload = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ "email_subject": "Thanks for your pitch",
+ "message": "Great idea, we logged it.",
+ }
+
+ first = self._compose(payload)
+ assert first.status_code == status.HTTP_201_CREATED
+ get_client().flushall()
+
+ # Created straight through the model, not the throttled compose endpoint: the burst here
+ # is deliberately larger than the endpoint's per-minute rate limit.
+ for i in range(20):
+ noise_ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ channel_source=Channel.EMAIL,
+ distinct_id="[email protected]",
+ status=Status.OPEN,
+ widget_session_id=f"noise-session-{i}",
+ email_config=self.email_config,
+ email_from="[email protected]",
+ email_subject=f"Unrelated subject {i}",
+ anonymous_traits={"email": "[email protected]"},
+ identity_verified=None,
+ )
+ Comment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ scope="conversations_ticket",
+ item_id=str(noise_ticket.id),
+ content="Unrelated content",
+ item_context={"author_type": "human", "is_private": False},
+ )
+ get_client().flushall()
+
+ second = self._compose(payload)
+
+ assert second.status_code == status.HTTP_200_OK
+ assert second.json() == first.json()
+ assert Ticket.objects.filter(team=self.team).count() == 21
+
+ def test_compose_conflicts_while_an_identical_request_is_in_flight(self, mock_on_commit):
+ payload = {
+ "recipient_email": "[email protected]",
+ "email_config_id": str(self.email_config.id),
+ "message": "Great idea, we logged it.",
+ }
+ fingerprint = ComposeFingerprint.build(
+ team_id=self.team.id,
+ email_config_id=str(self.email_config.id),
+ recipient_email="[email protected]",
+ email_subject="",
+ message="Great idea, we logged it.",
+ rich_content=None,
+ distinct_id="[email protected]",
+ creator_id=self.user.id,
+ )
+ assert fingerprint is not None
+ # Another request holds the reservation and hasn't finished creating yet.
+ held = reply_dedupe.reserve(fingerprint)
+ assert held.state is reply_dedupe.ReservationState.ACQUIRED
+
+ response = self._compose(payload)
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["error_type"] == reply_dedupe.COMPOSE_IN_PROGRESS_ERROR_TYPE
+ assert not Ticket.objects.filter(team=self.team).exists()
+
def test_compose_applies_tags_to_the_new_ticket(self, mock_on_commit):
# Tags let support filter composed tickets by source (e.g. roadmap pitches). If compose
# drops the field, the ticket lands untagged and that filtering breaks.
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index 066f844ac4d2..257477af6efb 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -41,6 +41,7 @@ from posthog.api.tagged_item import (
BulkUpdateTagsUUIDResponseSerializer,
TaggedItemSerializerMixin,
TaggedItemViewSetMixin,
+ normalize_tag_names,
set_tags_on_object,
)
from posthog.dataclasses import frozen
@@ -1711,8 +1712,16 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro
@extend_schema(
request=ComposeTicketSerializer,
responses={
- 201: OpenApiResponse(response=ComposeTicketResponseSerializer),
+ 201: OpenApiResponse(response=ComposeTicketResponseSerializer, description="Ticket created."),
+ 200: OpenApiResponse(
+ response=ComposeTicketResponseSerializer,
+ description="An identical compose was already handled; the existing ticket is returned.",
+ ),
400: OpenApiResponse(response=TicketErrorSerializer),
+ 409: OpenApiResponse(
+ response=TicketErrorSerializer,
+ description="An identical compose is still being created by another request.",
+ ),
},
)
@action(
@@ -1722,7 +1731,12 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro
throttle_classes=[ComposeTicketBurstThrottle, ComposeTicketSustainedThrottle],
)
def compose(self, request, *args, **kwargs):
- """Create a new outbound ticket and send the first message to the customer."""
+ """Create a new outbound ticket and send the first message to the customer.
+
+ Idempotent within a short window: an identical compose retried while the first is still
+ in flight returns 409, and one retried after it committed returns the same ticket with a
+ 200. Only a genuinely new request creates a ticket and emails the customer.
+ """
serializer = ComposeTicketSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
@@ -1776,51 +1790,82 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro
status=drf_status.HTTP_400_BAD_REQUEST,
)
- with transaction.atomic():
- ticket = Ticket.objects.create_with_number(
- team=team,
- channel_source=Channel.EMAIL,
- distinct_id=distinct_id,
- status=Status.OPEN,
- widget_session_id=str(uuid.uuid4()),
- email_config=email_config,
- email_from=recipient_email,
- email_subject=data.get("email_subject", ""),
- # Ticket search, the person display and restore-by-email all read the
- # customer's address from traits, so outbound tickets must carry it too.
- anonymous_traits={"email": recipient_email},
- # The recipient hasn't proven control of this address — a team member just typed it —
- # so leave identity unknown. It's promoted to verified if/when they reply and authenticate.
- identity_verified=None,
- )
-
- Comment.objects.create(
- team=team,
- created_by=request.user,
- scope="conversations_ticket",
- item_id=str(ticket.id),
- content=data["message"],
- rich_content=data.get("rich_content"),
- item_context={"author_type": "human", "is_private": False},
- )
+ def create_ticket() -> Ticket:
+ with transaction.atomic():
+ ticket = Ticket.objects.create_with_number(
+ team=team,
+ channel_source=Channel.EMAIL,
+ distinct_id=distinct_id,
+ status=Status.OPEN,
+ widget_session_id=str(uuid.uuid4()),
+ email_config=email_config,
+ email_from=recipient_email,
+ email_subject=data.get("email_subject", ""),
+ # Ticket search, the person display and restore-by-email all read the
+ # customer's address from traits, so outbound tickets must carry it too.
+ anonymous_traits={"email": recipient_email},
+ # The recipient hasn't proven control of this address — a team member just typed it —
+ # so leave identity unknown. It's promoted to verified if/when they reply and authenticate.
+ identity_verified=None,
+ )
- if data.get("tags"):
- set_tags_on_object(data["tags"], ticket)
+ Comment.objects.create(
+ team=team,
+ created_by=request.user,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content=data["message"],
+ rich_content=data.get("rich_content"),
+ item_context={"author_type": "human", "is_private": False},
+ )
- try:
- report_user_action(
- request.user,
- "support ticket composed",
- {"channel_source": Channel.EMAIL},
- team=team,
- request=request,
+ if data.get("tags"):
+ set_tags_on_object(data["tags"], ticket)
+ return ticket
+
+ # message, recipient_email, and email_config are all validated above, so build never
+ # returns None here.
+ fingerprint = reply_dedupe.ComposeFingerprint.build(
+ team_id=team.id,
+ email_config_id=str(email_config.id),
+ recipient_email=recipient_email,
+ email_subject=data.get("email_subject", ""),
+ message=data["message"],
+ rich_content=data.get("rich_content"),
+ distinct_id=distinct_id,
+ creator_id=request.user.id if request.user and request.user.is_authenticated else None,
+ tags=normalize_tag_names(data.get("tags") or []),
+ )
+ assert fingerprint is not None
+ guarded = reply_dedupe.create_ticket_deduplicated(fingerprint, create_ticket)
+ if guarded.outcome is reply_dedupe.CreateOutcome.CONFLICT:
+ return Response(
+ {
+ "detail": reply_dedupe.COMPOSE_IN_PROGRESS_DETAIL,
+ "error_type": reply_dedupe.COMPOSE_IN_PROGRESS_ERROR_TYPE,
+ },
+ status=drf_status.HTTP_409_CONFLICT,
)
- except Exception as e:
- capture_exception(e, {"ticket_id": str(ticket.id)})
+ ticket = cast(Ticket, guarded.ticket)
+ created = guarded.outcome is reply_dedupe.CreateOutcome.CREATED
+
+ # A replay already reported this action and already emailed the customer, so only a genuine
+ # create repeats either.
+ if created:
+ try:
+ report_user_action(
+ request.user,
+ "support ticket composed",
+ {"channel_source": Channel.EMAIL},
+ team=team,
+ request=request,
+ )
+ except Exception as e:
+ capture_exception(e, {"ticket_id": str(ticket.id)})
return Response(
- {"id": str(ticket.id), "ticket_number": ticket.ticket_number},
- status=drf_status.HTTP_201_CREATED,
+ ComposeTicketResponseSerializer(ticket).data,
+ status=drf_status.HTTP_201_CREATED if created else drf_status.HTTP_200_OK,
)
diff --git a/products/conversations/backend/migrations/0069_ticket_compose_dedupe_index.py b/products/conversations/backend/migrations/0069_ticket_compose_dedupe_index.py
new file mode 100644
index 000000000000..cb2557489f9b
--- /dev/null
+++ b/products/conversations/backend/migrations/0069_ticket_compose_dedupe_index.py
@@ -0,0 +1,26 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds cannot run inside a transaction; keep them in their own migration.
+ atomic = False
+
+ dependencies = [
+ ("conversations", "0068_alter_emailchannelsetup_team_and_more"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="ticket",
+ index=models.Index(
+ models.F("team_id"),
+ models.F("email_config_id"),
+ models.F("email_from"),
+ models.F("created_at").desc(),
+ name="posthog_con_compose_dedupe_idx",
+ condition=models.Q(channel_source="email"),
+ ),
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index 05b24850e0b7..c864fb006215 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0068_alter_emailchannelsetup_team_and_more
+0069_ticket_compose_dedupe_index
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.py
index af29f63b8133..ab46ef1a0477 100644
--- a/products/conversations/backend/models/ticket.py
+++ b/products/conversations/backend/models/ticket.py
@@ -198,6 +198,17 @@ class Ticket(UUIDTModel):
name="posthog_org_slack_ch_idx",
condition=models.Q(channel_source="slack"),
),
+ # Compose dedupe fallback: find recent outbound email tickets by (team, email channel,
+ # sender) within a short window, newest first. Runs on every new compose, so without
+ # this it scans the channel's whole ticket history. Partial to email keeps it small.
+ models.Index(
+ models.F("team_id"),
+ models.F("email_config_id"),
+ models.F("email_from"),
+ models.F("created_at").desc(),
+ name="posthog_con_compose_dedupe_idx",
+ condition=models.Q(channel_source="email"),
+ ),
]
constraints = [
models.UniqueConstraint(fields=["team", "ticket_number"], name="unique_ticket_number_per_team"),
diff --git a/products/conversations/backend/reply_dedupe.py b/products/conversations/backend/reply_dedupe.py
index 6fd8a9ea6d84..1d479f0e6079 100644
--- a/products/conversations/backend/reply_dedupe.py
+++ b/products/conversations/backend/reply_dedupe.py
@@ -5,6 +5,10 @@ the request within a second, and an operator whose send looks like it failed sen
again. Dedupe on the validated request the server already has, so neither caller needs to supply
an idempotency key.
+The same reservation protocol also guards outbound ``compose``. A caller that retries a slow
+compose — a workflow webhook whose fetch times out just as the server finishes — would otherwise
+open the same ticket, and email the customer, once per retry.
+
Redis access goes through ``posthog.redis.get_client()`` rather than the Django cache. The default
cache alias is replica-aware, so the ``GET`` that follows a lost ``SET NX`` could read a lagging
replica and report a conflict for a reservation that already resolved. This client is bound to
@@ -15,21 +19,39 @@ replica and report a conflict for a reservation that already resolved. This clie
import json
import uuid
import hashlib
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
-from typing import Any
+from typing import Any, Protocol
+from django.db.models import Q
from django.utils import timezone
import structlog
+from posthog.api.tagged_item import current_tag_names
from posthog.models.comment import Comment
from posthog.redis import get_client
+from products.conversations.backend.models import Channel, Ticket
+
logger = structlog.get_logger(__name__)
+
+class _DedupeFingerprint(Protocol):
+ """What the reservation protocol needs from any fingerprint: a key, and a way to find or
+ re-verify the object an earlier attempt created. ``ReplyFingerprint`` and ``ComposeFingerprint``
+ both satisfy it, over comments and tickets respectively."""
+
+ @property
+ def key(self) -> str: ...
+
+ def find_persisted_match(self, *, created_after: datetime) -> Any: ...
+
+ def load_replay_target(self, object_id: str | None) -> Any: ...
+
+
# A reservation only has to outlive one request, and a worker killed mid-create self-heals this
# many seconds later instead of blocking that exact message for the full replay window.
IN_FLIGHT_TTL_SECONDS = 30
@@ -43,11 +65,16 @@ SUPPORT_AUTHOR_TYPE = "support"
REPLY_IN_PROGRESS_ERROR_TYPE = "reply_in_progress"
REPLY_IN_PROGRESS_DETAIL = "This message is already being sent. Check the thread before sending it again."
+COMPOSE_IN_PROGRESS_ERROR_TYPE = "compose_in_progress"
+COMPOSE_IN_PROGRESS_DETAIL = "This ticket is already being created. Check the inbox before composing it again."
+
# Both endpoints hash into one keyspace, so a retry that switches paths still replays. Bump the
# version when the fingerprint's contents change, so old entries can't be read under new rules.
_KEY_PREFIX = "conversations:reply_dedupe:v1:"
_IN_FLIGHT_VALUE_PREFIX = "inflight:"
-_COMMENT_VALUE_PREFIX = "comment:"
+# Marks a reservation value that holds the id of the created object — a comment for reply, a
+# ticket for compose. The key prefix keeps the two keyspaces apart, so the value prefix is shared.
+_STORED_VALUE_PREFIX = "comment:"
# Compare the owner token before writing, so a creator that stalled past its own TTL cannot
# overwrite or delete the reservation a later attempt has since taken.
@@ -82,7 +109,8 @@ class Reservation:
key: str
# Absent when we failed open, which makes publish and release no-ops.
owner_token: str | None = None
- comment_id: str | None = None
+ # Id of the created object (a comment for reply, a ticket for compose).
+ object_id: str | None = None
@dataclass(frozen=True, kw_only=True)
@@ -227,34 +255,34 @@ class GuardedCreate:
comment: Comment | None = None
-def create_deduplicated(fingerprint: ReplyFingerprint, create: Callable[[], Comment]) -> GuardedCreate:
- """Run ``create`` at most once per fingerprint, and report what happened.
+def _run_deduplicated(fingerprint: _DedupeFingerprint, create: Callable[[], Any]) -> tuple[CreateOutcome, Any]:
+ """Run ``create`` at most once per fingerprint, and report the outcome plus the object.
- Both support-message endpoints go through here so the protocol can't drift between them. The
- caller owns the response shape: a REPLAYED outcome is theirs to render as a 200 and a CONFLICT
- as a 409. Exceptions from ``create`` propagate unchanged after the reservation is settled.
+ The shared core for both create endpoints, so the reservation protocol can't drift between
+ them. The caller owns the response shape: a REPLAYED outcome is theirs to render as a 200 and a
+ CONFLICT as a 409. Exceptions from ``create`` propagate unchanged after the reservation is
+ settled. On CONFLICT the object is None.
"""
reservation = reserve(fingerprint)
if reservation.state is ReservationState.REPLAY:
- replayed = fingerprint.load_replay_target(reservation.comment_id)
+ replayed = fingerprint.load_replay_target(reservation.object_id)
if replayed is not None:
- return GuardedCreate(outcome=CreateOutcome.REPLAYED, comment=replayed)
+ return CreateOutcome.REPLAYED, replayed
# A mapping we can't verify is treated as no mapping, rather than serving an unrelated row.
elif reservation.state is ReservationState.IN_FLIGHT:
- return GuardedCreate(outcome=CreateOutcome.CONFLICT)
+ return CreateOutcome.CONFLICT, None
attempted_at = timezone.now()
already_created = fingerprint.find_persisted_match(created_after=_replay_window_start(attempted_at))
if already_created is not None:
publish(reservation, already_created.id)
- return GuardedCreate(outcome=CreateOutcome.REPLAYED, comment=already_created)
+ return CreateOutcome.REPLAYED, already_created
try:
- comment = create()
+ created_object = create()
except Exception:
- # Mention fan-out and post_save receivers run after the INSERT, so an exception does not
- # mean the row is absent. Releasing blindly would make an already-delivered message
- # immediately repeatable.
+ # Receivers and mention fan-out run after the INSERT, so an exception does not mean the row
+ # is absent. Releasing blindly would make an already-delivered object immediately repeatable.
recovered = fingerprint.find_persisted_match(created_after=attempted_at)
if recovered is not None:
publish(reservation, recovered.id)
@@ -262,15 +290,21 @@ def create_deduplicated(fingerprint: ReplyFingerprint, create: Callable[[], Comm
release(reservation)
raise
- publish(reservation, comment.id)
- return GuardedCreate(outcome=CreateOutcome.CREATED, comment=comment)
+ publish(reservation, created_object.id)
+ return CreateOutcome.CREATED, created_object
+
+
+def create_deduplicated(fingerprint: ReplyFingerprint, create: Callable[[], Comment]) -> GuardedCreate:
+ """Deduplicate a support-message create. See ``_run_deduplicated`` for the outcome contract."""
+ outcome, comment = _run_deduplicated(fingerprint, create)
+ return GuardedCreate(outcome=outcome, comment=comment)
def _replay_window_start(attempted_at: datetime) -> datetime:
return attempted_at - timedelta(seconds=REPLAY_WINDOW_SECONDS)
-def reserve(fingerprint: ReplyFingerprint) -> Reservation:
+def reserve(fingerprint: _DedupeFingerprint) -> Reservation:
"""Claim the right to create this message, or report who got there first.
Fails open (ACQUIRED without a token) once Redis has failed twice. That degrades to the caller's
@@ -299,11 +333,11 @@ def reserve(fingerprint: ReplyFingerprint) -> Reservation:
return Reservation(state=ReservationState.ACQUIRED, key=key)
-def publish(reservation: Reservation, comment_id: Any) -> None:
- """Point the reservation at the created message so later retries replay it."""
+def publish(reservation: Reservation, object_id: Any) -> None:
+ """Point the reservation at the created object so later retries replay it."""
if reservation.owner_token is None:
return
- value = f"{_COMMENT_VALUE_PREFIX}{comment_id}"
+ value = f"{_STORED_VALUE_PREFIX}{object_id}"
for attempt in range(2):
try:
get_client().eval(
@@ -333,13 +367,173 @@ def _classify_held_value(key: str, held: Any, token: str) -> Reservation:
if value == token:
# Our own SET landed even though its reply never reached us, so we still own the reservation.
return Reservation(state=ReservationState.ACQUIRED, key=key, owner_token=token)
- if value.startswith(_COMMENT_VALUE_PREFIX):
+ if value.startswith(_STORED_VALUE_PREFIX):
return Reservation(
state=ReservationState.REPLAY,
key=key,
- comment_id=value.removeprefix(_COMMENT_VALUE_PREFIX),
+ object_id=value.removeprefix(_STORED_VALUE_PREFIX),
)
if value.startswith(_IN_FLIGHT_VALUE_PREFIX):
return Reservation(state=ReservationState.IN_FLIGHT, key=key)
logger.warning("conversations_reply_dedupe_malformed_value", key=key)
return Reservation(state=ReservationState.ACQUIRED, key=key)
+
+
+# Compose opens a brand-new outbound ticket, so it hashes into its own keyspace — a compose retry
+# must never collapse onto a reply, or vice versa. Bump the version when the contents below change.
+_COMPOSE_KEY_PREFIX = "conversations:compose_dedupe:v4:"
+
+
+@dataclass(frozen=True, kw_only=True)
+class ComposeFingerprint:
+ """The immutable identity of an outbound compose request.
+
+ Two requests with the same fingerprint open the same outbound ticket: same team, sending
+ channel, recipient, subject, first message, and resolved person link. ``build`` returns None
+ for anything this guard must not collapse.
+ """
+
+ team_id: int
+ email_config_id: str
+ recipient_email: str
+ email_subject: str
+ message: str
+ rich_content: Any
+ # The resolved recipient person link the create writes onto the ticket. Two composes with the
+ # same body but a different recipient point at different people, so they must not collapse.
+ distinct_id: str
+ # The user that authored the compose, stored as the opening comment's creator. Two agents that
+ # send identical content to the same recipient are two distinct tickets, so they must not
+ # collapse — only a genuine retry from the same author does.
+ creator_id: int | None
+ # Two composes that differ only by tags are distinct requests, not a replay of one another.
+ tags: frozenset[str]
+
+ @classmethod
+ def build(
+ cls,
+ *,
+ team_id: int,
+ email_config_id: Any,
+ recipient_email: Any,
+ email_subject: Any,
+ message: Any,
+ rich_content: Any,
+ distinct_id: Any,
+ creator_id: int | None,
+ tags: Iterable[str] = (),
+ ) -> "ComposeFingerprint | None":
+ if not email_config_id or not recipient_email or not isinstance(message, str) or not message:
+ return None
+ return cls(
+ team_id=team_id,
+ email_config_id=str(email_config_id),
+ recipient_email=str(recipient_email),
+ email_subject=str(email_subject or ""),
+ message=message,
+ rich_content=rich_content,
+ distinct_id=str(distinct_id or ""),
+ creator_id=creator_id,
+ tags=frozenset(tags),
+ )
+
+ @property
+ def key(self) -> str:
+ canonical = json.dumps(
+ {
+ "team_id": self.team_id,
+ "email_config_id": self.email_config_id,
+ "recipient_email": self.recipient_email,
+ "email_subject": self.email_subject,
+ "message": self.message,
+ "rich_content": self.rich_content,
+ "distinct_id": self.distinct_id,
+ "creator_id": self.creator_id,
+ "tags": sorted(self.tags),
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+ # Only the digest reaches Redis, so no message content lands in a key.
+ return f"{_COMPOSE_KEY_PREFIX}{hashlib.sha256(canonical.encode()).hexdigest()}"
+
+ def matches(self, ticket: Ticket) -> bool:
+ """Whether this persisted outbound ticket is the one this request asked for."""
+ if (
+ ticket.team_id != self.team_id
+ or ticket.channel_source != Channel.EMAIL
+ or str(ticket.email_config_id or "") != self.email_config_id
+ or (ticket.email_from or "") != self.recipient_email
+ or (ticket.email_subject or "") != self.email_subject
+ or (ticket.distinct_id or "") != self.distinct_id
+ ):
+ return False
+ # The first message lives on the ticket's opening comment, so confirm the body too: a
+ # second, different pitch to the same recipient in the window is a distinct ticket.
+ first = (
+ Comment.objects.filter(team_id=self.team_id, scope=SUPPORT_TICKET_SCOPE, item_id=str(ticket.id))
+ .order_by("created_at")
+ .first()
+ )
+ if first is None or first.deleted or first.content != self.message or first.rich_content != self.rich_content:
+ return False
+ # The author is the opening comment's creator, so a different agent's identical compose is
+ # a distinct ticket even when everything else matches.
+ if first.created_by_id != self.creator_id:
+ return False
+ # A retry that adds or drops a tag must not replay a differently-tagged ticket.
+ if current_tag_names(ticket) != self.tags:
+ return False
+ return True
+
+ def find_persisted_match(self, *, created_after: datetime) -> Ticket | None:
+ """The outbound ticket this request would have opened, if an earlier attempt already did.
+
+ This closes the window where a create commits but its publication never lands: the
+ reservation is gone, so only the database can tell the retry that its ticket exists.
+ """
+ # Filter on every matches() column the DB can express directly, so the unbounded query
+ # below can't miss the real match under a burst of newer, non-matching tickets. subject
+ # is nullable and matches() treats NULL as "", so a blank subject must accept NULL too.
+ subject_filter = (
+ Q(email_subject__isnull=True) | Q(email_subject="")
+ if not self.email_subject
+ else Q(email_subject=self.email_subject)
+ )
+ candidates = Ticket.objects.filter(
+ subject_filter,
+ team_id=self.team_id,
+ channel_source=Channel.EMAIL,
+ email_config_id=self.email_config_id,
+ email_from=self.recipient_email,
+ distinct_id=self.distinct_id,
+ created_at__gte=created_after,
+ ).order_by("-created_at")
+ return next((ticket for ticket in candidates if self.matches(ticket)), None)
+
+ def load_replay_target(self, ticket_id: str | None) -> Ticket | None:
+ """Re-verify a published mapping before serving it as a replay."""
+ if not ticket_id:
+ return None
+ ticket = Ticket.objects.filter(team_id=self.team_id, pk=ticket_id).first()
+ if ticket is None or not self.matches(ticket):
+ logger.warning("conversations_compose_dedupe_stale_mapping", ticket_id=ticket_id)
+ return None
+ return ticket
+
+
+@dataclass(frozen=True, kw_only=True)
+class GuardedTicketCreate:
+ outcome: CreateOutcome
+ ticket: Ticket | None = None
+
+
+def create_ticket_deduplicated(fingerprint: ComposeFingerprint, create: Callable[[], Ticket]) -> GuardedTicketCreate:
+ """Deduplicate an outbound compose. See ``_run_deduplicated`` for the outcome contract.
+
+ This is what stops a caller that retries a slow compose from opening the same ticket — and
+ emailing the customer — more than once.
+ """
+ outcome, ticket = _run_deduplicated(fingerprint, create)
+ return GuardedTicketCreate(outcome=outcome, ticket=ticket)
diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.ts
index b3fe3109f422..887a9b80f0f4 100644
--- a/products/conversations/frontend/generated/api.ts
+++ b/products/conversations/frontend/generated/api.ts
@@ -380,6 +380,10 @@ export const getConversationsTicketsComposeCreateUrl = (projectId: string) => {
/**
* Create a new outbound ticket and send the first message to the customer.
+ *
+ * Idempotent within a short window: an identical compose retried while the first is still
+ * in flight returns 409, and one retried after it committed returns the same ticket with a
+ * 200. Only a genuinely new request creates a ticket and emails the customer.
*/
export const conversationsTicketsComposeCreate = async (
projectId: string,
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index 9de920e8daf6..85b5176dd6a6 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -263,6 +263,10 @@ export const ConversationsTicketsBulkUpdateTagsCreateBody = /* @__PURE__ */ zod
/**
* Create a new outbound ticket and send the first message to the customer.
+ *
+ * Idempotent within a short window: an identical compose retried while the first is still
+ * in flight returns 409, and one retried after it committed returns the same ticket with a
+ * 200. Only a genuinely new request creates a ticket and emails the customer.
*/
export const conversationsTicketsComposeCreateBodyRecipientDistinctIdMax = 400