: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): make replies transactional and bridge ticket locks (#96340)
Alex Vc70918d04d13
diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 0f1836d8c115..654e908548cb 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -1,3 +1,4 @@+from contextlib import nullcontextfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, cast@@ -485,7 +486,10 @@ class CommentSerializer(serializers.ModelSerializer):):mentions = []- comment = super().create(validated_data)+ # ATOMIC_REQUESTS is off, so wrap the comment insert with the email-outbox write.+ persist_ctx = transaction.atomic() if validated_data["scope"] == "conversations_ticket" else nullcontext()+ with persist_ctx:+ comment = super().create(validated_data)if mentions:if comment.scope not in DESKTOP_COMMENT_SCOPES:diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex c3eb17d2dd3c..a1bfc3c7d164 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -20,7 +20,7 @@ from posthog.redis import get_clientfrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEVfrom products.access_control.backend.models.access_control import AccessControl-from products.conversations.backend.models import Ticket+from products.conversations.backend.models import EmailOutboxMessage, Ticketfrom products.conversations.backend.models.constants import Channel, Statusfrom products.conversations.backend.reply_dedupe import REPLY_IN_PROGRESS_ERROR_TYPE, ReplyFingerprint, reserve@@ -1674,6 +1674,24 @@ class TestCommentsSupportReplyDedupe(APIBaseTest):assert response.json()["error_type"] == REPLY_IN_PROGRESS_ERROR_TYPEassert not Comment.objects.filter(scope="conversations_ticket").exists()+ def test_outbox_failure_rolls_back_comment_and_allows_retry(self) -> None:+ self.ticket.channel_source = Channel.EMAIL+ self.ticket.save(update_fields=["channel_source"])++ with mock.patch(+ "products.conversations.backend.signals.EmailOutboxMessage.objects.get_or_create",+ side_effect=RuntimeError("outbox write failed"),+ ):+ response = self._post()++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ assert not Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).exists()+ assert not EmailOutboxMessage.objects.filter(ticket=self.ticket).exists()++ retry = self._post()+ assert retry.status_code == status.HTTP_201_CREATED+ assert EmailOutboxMessage.objects.filter(ticket=self.ticket).count() == 1+@parameterized.expand([("internal_ticket_discussion", {"scope": "Ticket"}),diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 11078f40bd81..242291a9b4f9 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -1,11 +1,14 @@import json+from concurrent.futures import ThreadPoolExecutorfrom datetime import timedeltafrom decimal import Decimal+from threading import Barrierfrom posthog.test.base import (APIBaseTest,BaseTest,ClickhouseTestMixin,+ NonAtomicBaseTest,_create_person,get_index_from_explain,get_inner_person_subquery_clickhouse_sql,@@ -14,7 +17,8 @@ from posthog.test.base import ()from unittest.mock import patch-from django.db import transaction+from django.db import close_old_connections, connection, transaction+from django.db.utils import IntegrityErrorfrom django.test import SimpleTestCasefrom django.utils import timezone@@ -40,6 +44,7 @@ from products.conversations.backend.models import (EmailChannel,EmailChannelKind,EmailMessageMapping,+ EmailOutboxMessage,Ticket,TicketAssignment,TicketView,@@ -1656,6 +1661,63 @@ class TestTicketManager(BaseTest):self.assertEqual(ticket1.ticket_number, 1)self.assertEqual(ticket2.ticket_number, 2)+ def test_unrelated_integrity_error_propagates(self):+ Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.GITHUB,+ widget_session_id="",+ distinct_id="github:octocat",+ github_repo="org/repo",+ github_issue_number=42,+ )+ with self.assertRaises(IntegrityError):+ Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.GITHUB,+ widget_session_id="",+ distinct_id="github:octocat",+ github_repo="org/repo",+ github_issue_number=42,+ )+ remaining = Ticket.objects.get(team=self.team)+ self.assertEqual(remaining.ticket_number, 1)+ self.assertEqual(remaining.github_issue_number, 42)+++class TestTicketNumberAllocationConcurrency(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ @patch("products.conversations.backend.signals.capture_ticket_created")+ def test_concurrent_creates_get_unique_sequential_numbers(self, _mock_capture):+ worker_count = 4+ team_id = self.team.id+ start_barrier = Barrier(worker_count)++ def create_one(index: int) -> int:+ close_old_connections()+ try:+ with connection.cursor() as cursor:+ cursor.execute("SET lock_timeout = '10s'")+ cursor.execute("SET statement_timeout = '15s'")+ team = Team.objects.get(id=team_id)+ start_barrier.wait(timeout=5)+ ticket = Ticket.objects.create_with_number(+ team=team,+ channel_source=Channel.WIDGET,+ widget_session_id=f"session-{index}",+ distinct_id=f"user-{index}",+ )+ return ticket.ticket_number+ finally:+ close_old_connections()++ with ThreadPoolExecutor(max_workers=worker_count) as executor:+ futures = [executor.submit(create_one, i) for i in range(worker_count)]+ numbers = [future.result(timeout=20) for future in futures]++ self.assertEqual(sorted(numbers), list(range(1, worker_count + 1)))+ self.assertEqual(Ticket.objects.filter(team_id=team_id).count(), worker_count)+@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)class TestTicketPersonData(APIBaseTest):@@ -2744,6 +2806,24 @@ class TestTicketReplyAPI(APIBaseTest):assert Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).count() == 1mock_send_email_reply.delay.assert_called_once()+ @patch("products.conversations.backend.signals.send_email_reply")+ def test_outbox_failure_rolls_back_comment_and_allows_retry(self, mock_send_email_reply, mock_on_commit):+ with patch(+ "products.conversations.backend.signals.EmailOutboxMessage.objects.get_or_create",+ side_effect=RuntimeError("outbox write failed"),+ ):+ response = self.client.post(self.url, {"message": "On it now"}, format="json")++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ assert not Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).exists()+ assert not EmailOutboxMessage.objects.filter(ticket=self.ticket).exists()+ mock_send_email_reply.delay.assert_not_called()++ retry = self.client.post(self.url, {"message": "On it now"}, format="json")+ assert retry.status_code == status.HTTP_201_CREATED+ assert EmailOutboxMessage.objects.filter(ticket=self.ticket).count() == 1+ mock_send_email_reply.delay.assert_called_once()+def test_reply_still_being_created_returns_a_conflict(self, mock_on_commit):fingerprint = ReplyFingerprint.build(team_id=self.team.id,diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 5f8da9b00604..c5d987fbecb8 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -1519,15 +1519,17 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControitem_context = {"author_type": "support", "is_private": data["is_private"]}def create_comment() -> Comment:- return Comment.objects.create(- team=self.team,- created_by=request.user,- scope="conversations_ticket",- item_id=str(ticket.id),- content=data["message"],- rich_content=data.get("rich_content"),- item_context=item_context,- )+ # ATOMIC_REQUESTS is off, so wrap the comment insert with the email-outbox write.+ with transaction.atomic():+ return Comment.objects.create(+ team=self.team,+ created_by=request.user,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content=data["message"],+ rich_content=data.get("rich_content"),+ item_context=item_context,+ )fingerprint = reply_dedupe.ReplyFingerprint.build(team_id=self.team_id,diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.pyindex cdb354c9ce03..1e82d3925bfd 100644--- a/products/conversations/backend/models/ticket.py+++ b/products/conversations/backend/models/ticket.py@@ -1,21 +1,22 @@from typing import TYPE_CHECKING-from django.db import models, transaction+from django.db import connection, models, transactionfrom posthog.models.utils import UUIDTModelfrom .constants import Channel, ChannelDetail, Priority, Status+# Two-arg lock namespace for ticket_number allocation. Keep this value stable:+# mixed-version allocators only serialize if they use the same pair.+_TICKET_NUMBER_LOCK_NAMESPACE = 0x0C0F_5E71+if TYPE_CHECKING:from posthog.models import Personclass TicketManager(models.Manager):def create_with_number(self, **kwargs):- """- Create a ticket with an auto-incrementing ticket_number.- Uses SELECT FOR UPDATE on Team row to serialize ticket creation per team.- """+ """Create a ticket with the next ticket_number for its team."""from posthog.models import Teamteam = kwargs.get("team")@@ -23,7 +24,14 @@ class TicketManager(models.Manager):raise ValueError("team is required")with transaction.atomic():- # Lock team row to serialize ticket creation for this team+ # Advisory lock first so every allocator shares one mutex. The Team+ # row lock stays so processes that only lock Team still serialize.+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(%s, %s)",+ [_TICKET_NUMBER_LOCK_NAMESPACE, team.id],+ )+ # nosemgrep: hot-parent-row-select-for-update -- keep Team lock until every allocator takes the advisory lock firstTeam.objects.select_for_update().get(id=team.id)max_num = self.filter(team=team).aggregate(models.Max("ticket_number"))["ticket_number__max"] or 0diff --git a/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py b/products/conversations/backend/temporal/ai_reply/activities/persist_reply.pyindex c5f2a91efcc4..05102205ba89 100644--- a/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py+++ b/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py@@ -1,5 +1,7 @@from __future__ import annotations+from django.db import transaction+from temporalio import activityfrom posthog.models.comment import Comment@@ -35,15 +37,17 @@ def _persist_reply_sync(input: PersistReplyInput) -> None:if mode == "bot_reply":is_private = False- Comment.objects.create(- team_id=input.team_id,- scope="conversations_ticket",- item_id=input.ticket_id,- content=input.reply,- item_context={- "author_type": "AI",- "is_private": is_private,- "citations": input.citations,- "confidence": input.confidence,- },- )+ # ATOMIC_REQUESTS is off, so wrap the comment insert with the email-outbox write.+ with transaction.atomic():+ Comment.objects.create(+ team_id=input.team_id,+ scope="conversations_ticket",+ item_id=input.ticket_id,+ content=input.reply,+ item_context={+ "author_type": "AI",+ "is_private": is_private,+ "citations": input.citations,+ "confidence": input.confidence,+ },+ )diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.pyindex 1e1f2474b499..5fc690404064 100644--- a/products/conversations/backend/temporal/tests/test_pipeline.py+++ b/products/conversations/backend/temporal/tests/test_pipeline.py@@ -412,6 +412,45 @@ class TestPersistReplyActivity:assert comment.item_context["citations"] == ["chunk-1", "chunk-2"]assert comment.item_context["confidence"] == 0.85+ def test_public_email_reply_rolls_back_when_outbox_create_fails(self):+ from posthog.models.comment import Comment++ from products.conversations.backend.models import EmailOutboxMessage++ org = Organization.objects.create(name="Test Org")+ team = Team.objects.create(+ organization=org,+ name="Test Team",+ conversations_settings={"ai_reply_modes": {"email": {"how_to": "bot_reply"}}},+ )+ ticket = Ticket.objects.create_with_number(+ team=team,+ channel_source="email",+ widget_session_id="",+ distinct_id="[email protected]",+ email_from="[email protected]",+ )++ with patch(+ "products.conversations.backend.signals.EmailOutboxMessage.objects.get_or_create",+ side_effect=RuntimeError("outbox write failed"),+ ):+ with pytest.raises(RuntimeError, match="outbox write failed"):+ _persist_reply_sync(+ PersistReplyInput(+ team_id=team.id,+ ticket_id=str(ticket.id),+ reply="Here is the fix.",+ citations=["c1"],+ confidence=0.9,+ ticket_type="how_to",+ allow_bot_reply=True,+ )+ )++ assert not Comment.objects.filter(team_id=team.id, item_id=str(ticket.id)).exists()+ assert not EmailOutboxMessage.objects.filter(ticket=ticket).exists()+@parameterized.expand([(