: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): bridge zendesk ticket allocation locks (#96721)
Alex V599ad15092b7
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.pyindex 1e82d3925bfd..d162516f3580 100644--- a/products/conversations/backend/models/ticket.py+++ b/products/conversations/backend/models/ticket.py@@ -1,13 +1,13 @@from typing import TYPE_CHECKING-from django.db import connection, models, transaction+from django.db import 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.+# every allocator (create_with_number and bulk import) must use the same pair._TICKET_NUMBER_LOCK_NAMESPACE = 0x0C0F_5E71if TYPE_CHECKING:@@ -15,6 +15,21 @@ if TYPE_CHECKING:class TicketManager(models.Manager):+ def lock_ticket_number_allocation(self, team_id: int) -> None:+ """Acquire the team-scoped transaction lock for ticket number assignment.++ Callers must be inside ``transaction.atomic()`` and acquire this before+ any other allocation lock.+ """+ db_connection = transaction.get_connection(self.db)+ if not db_connection.in_atomic_block:+ raise RuntimeError("lock_ticket_number_allocation requires an open transaction")+ with db_connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(%s, %s)",+ [_TICKET_NUMBER_LOCK_NAMESPACE, team_id],+ )+def create_with_number(self, **kwargs):"""Create a ticket with the next ticket_number for its team."""from posthog.models import Team@@ -23,17 +38,10 @@ class TicketManager(models.Manager):if not team:raise ValueError("team is required")- with transaction.atomic():- # 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 first- Team.objects.select_for_update().get(id=team.id)-+ with transaction.atomic(using=self.db):+ self.lock_ticket_number_allocation(team.id)+ # nosemgrep: hot-parent-row-select-for-update -- preserves compatibility with Team-lock-only allocators+ Team.objects.using(self.db).select_for_update().get(id=team.id)max_num = self.filter(team=team).aggregate(models.Max("ticket_number"))["ticket_number__max"] or 0kwargs["ticket_number"] = max_num + 1return self.create(**kwargs)diff --git a/products/conversations/backend/temporal/zendesk_import/activities.py b/products/conversations/backend/temporal/zendesk_import/activities.pyindex 7690b4728a6c..a6a65cbfc76f 100644--- a/products/conversations/backend/temporal/zendesk_import/activities.py+++ b/products/conversations/backend/temporal/zendesk_import/activities.py@@ -621,8 +621,8 @@ def _apply_denormalized_counters(team: Team, built: list[_BuiltTicket]) -> None:def _persist_ticket_batch(team: Team, built: list[_BuiltTicket], tags_by_name: dict[str, Tag]) -> int:# Phase 3: Persist tickets + comments in a single transaction (no network I/O). Ticket numbers- # are assigned under the same lock that guards bulk_create, so concurrent batch activities can't- # collide on unique_ticket_number_per_team.+ # are assigned under the same advisory lock as create_with_number, so live creates and+ # concurrent batch activities can't collide on unique_ticket_number_per_team.## IMPORTANT: persist historical rows with bulk_create/bulk_update ONLY. These bypass the# post_save/pre_save receivers in products/conversations/backend/signals.py, which is what@@ -632,6 +632,8 @@ def _persist_ticket_batch(team: Team, built: list[_BuiltTicket], tags_by_name: d# Comment.objects.create(), or .save() would fire those signals for every imported row —# triggering workflows and re-sending replies to real customers for years-old tickets. Don't.with transaction.atomic():+ Ticket.objects.lock_ticket_number_allocation(team.id)+ # nosemgrep: hot-parent-row-select-for-update -- preserves compatibility with Team-lock-only import allocatorsTeam.objects.select_for_update().get(id=team.id)max_num = Ticket.objects.filter(team_id=team.id).aggregate(Max("ticket_number"))["ticket_number__max"] or 0tickets_to_create = [b.ticket for b in built]diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.pyindex b082746362ae..dfd9924d8eed 100644--- a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py@@ -1,13 +1,18 @@from __future__ import annotations+from concurrent.futures import ThreadPoolExecutor+from threading import Eventfrom typing import Any-from posthog.test.base import BaseTest+from posthog.test.base import BaseTest, NonAtomicBaseTestfrom unittest.mock import MagicMock, patch+from django.db import close_old_connections, connection, transaction+from django.db.utils import OperationalError+from parameterized import parameterized-from posthog.models import Tag+from posthog.models import Tag, Teamfrom posthog.models.comment import Commentfrom products.conversations.backend.models import EmailChannel, EmailChannelKind, Ticket, ZendeskImportJob@@ -16,8 +21,10 @@ from products.conversations.backend.temporal.zendesk_import.activities import (ImportBatchInput,UpdateJobProgressInput,UpdateJobStatusInput,+ _BuiltTicket,_import_ticket_batch_sync,_parse_zendesk_datetime,+ _persist_ticket_batch,_update_job_progress_sync,_update_job_status_sync,)@@ -616,6 +623,61 @@ class TestZendeskImportBatchActivity(BaseTest):self.assertFalse(Ticket.objects.filter(team=self.team, zendesk_ticket_id=404).exists())+class TestZendeskTicketNumberAllocationConcurrency(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ @parameterized.expand([("advisory",), ("team_row",)])+ def test_import_waits_for_each_bridge_lock(self, held_lock: str) -> None:+ lock_acquired = Event()+ release_lock = Event()++ def hold_allocation_lock() -> None:+ close_old_connections()+ try:+ with transaction.atomic():+ if held_lock == "advisory":+ Ticket.objects.lock_ticket_number_allocation(self.team.id)+ else:+ Team.objects.select_for_update().get(id=self.team.id)+ lock_acquired.set()+ if not release_lock.wait(timeout=5):+ raise TimeoutError("test did not release the allocation lock")+ finally:+ close_old_connections()++ built = _BuiltTicket(+ ticket=Ticket(+ team=self.team,+ widget_session_id="zendesk-lock-bridge",+ distinct_id="[email protected]",+ channel_source=Channel.EMAIL,+ ),+ comments=[],+ tag_names=[],+ customer_message_count=0,+ agent_reply_count=0,+ created_at=None,+ updated_at=None,+ )++ with ThreadPoolExecutor(max_workers=1) as executor:+ lock_future = executor.submit(hold_allocation_lock)+ if not lock_acquired.wait(timeout=5):+ release_lock.set()+ lock_future.result(timeout=1)+ self.fail(f"allocator did not acquire the {held_lock} lock")+ try:+ with connection.cursor() as cursor:+ cursor.execute("SET lock_timeout = '250ms'")+ with self.assertRaisesRegex(OperationalError, "canceling statement due to lock timeout"):+ _persist_ticket_batch(self.team, [built], {})+ finally:+ with connection.cursor() as cursor:+ cursor.execute("SET lock_timeout = 0")+ release_lock.set()+ lock_future.result(timeout=5)++class TestZendeskImportJobUpdates(BaseTest):def _make_job(self, **kwargs: Any) -> ZendeskImportJob:return ZendeskImportJob.objects.unscoped().create(