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): stop locking teams for ticket numbers (#97157)

Alex Vee807a7365c2
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index 242291a9b4f9..c20a804cee5f 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -2,7 +2,7 @@ import json
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from decimal import Decimal
-from threading import Barrier
+from threading import Barrier, Event
from posthog.test.base import (
APIBaseTest,
@@ -68,8 +68,8 @@ class TestComposeTicketSerializer(SimpleTestCase):
def test_rejects_more_than_100_tags(self):
# The compose write applies each tag inside the ticket-creation transaction, which
- # holds a team-row lock. An unbounded list would fan out that work under the lock, so
- # the field is capped at 100 before any DB work starts.
+ # holds the ticket-number allocation lock. An unbounded list would fan out that work
+ # under the lock, so the field is capped at 100 before any DB work starts.
serializer = ComposeTicketSerializer(data=self._payload(tags=[f"t{i}" for i in range(101)]))
assert not serializer.is_valid()
assert set(serializer.errors) == {"tags"}
@@ -1718,6 +1718,54 @@ class TestTicketNumberAllocationConcurrency(NonAtomicBaseTest):
self.assertEqual(sorted(numbers), list(range(1, worker_count + 1)))
self.assertEqual(Ticket.objects.filter(team_id=team_id).count(), worker_count)
+ @patch("products.conversations.backend.signals.capture_ticket_created")
+ def test_create_does_not_lock_the_team_row(self, _mock_capture):
+ # Concurrent uniqueness still passes if allocation takes Team FOR UPDATE again.
+ # Pause before the insert so the advisory lock is held and the Team row is not.
+ paused = Event()
+ resume = Event()
+ real_create = type(Ticket.objects).create
+
+ def pausing_create(manager, *args, **kwargs):
+ paused.set()
+ if not resume.wait(timeout=5):
+ raise TimeoutError("test did not resume allocation")
+ return real_create(manager, *args, **kwargs)
+
+ def allocate() -> None:
+ close_old_connections()
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute("SET lock_timeout = '10s'")
+ cursor.execute("SET statement_timeout = '15s'")
+ Ticket.objects.create_with_number(
+ team=self.team,
+ channel_source=Channel.WIDGET,
+ widget_session_id="session-team-lock",
+ distinct_id="user-team-lock",
+ )
+ finally:
+ close_old_connections()
+
+ with patch.object(type(Ticket.objects), "create", pausing_create):
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(allocate)
+ if not paused.wait(timeout=5):
+ resume.set()
+ future.result(timeout=1)
+ self.fail("allocator did not pause before insert")
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute("SET lock_timeout = '250ms'")
+ with transaction.atomic():
+ Team.objects.select_for_update().get(id=self.team.id)
+ finally:
+ with connection.cursor() as cursor:
+ cursor.execute("RESET lock_timeout")
+ resume.set()
+ future.result(timeout=5)
+ self.assertTrue(Ticket.objects.filter(team=self.team, widget_session_id="session-team-lock").exists())
+
@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)
class TestTicketPersonData(APIBaseTest):
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.py
index d162516f3580..a0533c76c607 100644
--- a/products/conversations/backend/models/ticket.py
+++ b/products/conversations/backend/models/ticket.py
@@ -16,10 +16,11 @@ 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.
+ """Serialize ticket_number assignment for this team.
- Callers must be inside ``transaction.atomic()`` and acquire this before
- any other allocation lock.
+ Uses a transaction-scoped advisory lock instead of locking the Team row,
+ so unrelated writers of Team children are not blocked. Callers must be
+ inside ``transaction.atomic()``.
"""
db_connection = transaction.get_connection(self.db)
if not db_connection.in_atomic_block:
@@ -32,16 +33,12 @@ class TicketManager(models.Manager):
def create_with_number(self, **kwargs):
"""Create a ticket with the next ticket_number for its team."""
- from posthog.models import Team
-
team = kwargs.get("team")
if not team:
raise ValueError("team is required")
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 0
kwargs["ticket_number"] = max_num + 1
return self.create(**kwargs)
diff --git a/products/conversations/backend/temporal/zendesk_import/activities.py b/products/conversations/backend/temporal/zendesk_import/activities.py
index a6a65cbfc76f..3845322325d7 100644
--- a/products/conversations/backend/temporal/zendesk_import/activities.py
+++ b/products/conversations/backend/temporal/zendesk_import/activities.py
@@ -633,8 +633,6 @@ def _persist_ticket_batch(team: Team, built: list[_BuiltTicket], tags_by_name: d
# 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 allocators
- Team.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 0
tickets_to_create = [b.ticket for b in built]
for offset, ticket_to_number in enumerate(tickets_to_create):
diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py
index dfd9924d8eed..85d0466edca1 100644
--- a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py
+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py
@@ -623,49 +623,52 @@ class TestZendeskImportBatchActivity(BaseTest):
self.assertFalse(Ticket.objects.filter(team=self.team, zendesk_ticket_id=404).exists())
+def _zendesk_allocation_ticket(team: Team) -> _BuiltTicket:
+ return _BuiltTicket(
+ ticket=Ticket(
+ team=team,
+ widget_session_id="zendesk-allocation",
+ 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,
+ )
+
+
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:
+ def test_import_waits_for_the_allocation_lock(self) -> None:
lock_acquired = Event()
release_lock = Event()
def hold_allocation_lock() -> None:
close_old_connections()
try:
+ with connection.cursor() as cursor:
+ cursor.execute("SET lock_timeout = '10s'")
+ cursor.execute("SET statement_timeout = '15s'")
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)
+ Ticket.objects.lock_ticket_number_allocation(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,
- )
+ built = _zendesk_allocation_ticket(self.team)
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")
+ self.fail("allocator did not acquire the allocation lock")
try:
with connection.cursor() as cursor:
cursor.execute("SET lock_timeout = '250ms'")
@@ -673,10 +676,52 @@ class TestZendeskTicketNumberAllocationConcurrency(NonAtomicBaseTest):
_persist_ticket_batch(self.team, [built], {})
finally:
with connection.cursor() as cursor:
- cursor.execute("SET lock_timeout = 0")
+ cursor.execute("RESET lock_timeout")
release_lock.set()
lock_future.result(timeout=5)
+ def test_import_does_not_lock_the_team_row(self) -> None:
+ # A ticket insert takes KEY SHARE on the Team row for its FK. Pause before bulk_create
+ # so that lock does not make the Team FOR UPDATE probe fail.
+ paused = Event()
+ resume = Event()
+ real_bulk_create = type(Ticket.objects).bulk_create
+
+ def pausing_bulk_create(manager, *args, **kwargs):
+ paused.set()
+ if not resume.wait(timeout=5):
+ raise TimeoutError("test did not resume persist")
+ return real_bulk_create(manager, *args, **kwargs)
+
+ def persist() -> None:
+ close_old_connections()
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute("SET lock_timeout = '10s'")
+ cursor.execute("SET statement_timeout = '15s'")
+ _persist_ticket_batch(self.team, [_zendesk_allocation_ticket(self.team)], {})
+ finally:
+ close_old_connections()
+
+ with patch.object(type(Ticket.objects), "bulk_create", pausing_bulk_create):
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(persist)
+ if not paused.wait(timeout=5):
+ resume.set()
+ future.result(timeout=1)
+ self.fail("persist did not pause before insert")
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute("SET lock_timeout = '250ms'")
+ with transaction.atomic():
+ Team.objects.select_for_update().get(id=self.team.id)
+ finally:
+ with connection.cursor() as cursor:
+ cursor.execute("RESET lock_timeout")
+ resume.set()
+ future.result(timeout=5)
+ self.assertTrue(Ticket.objects.filter(team=self.team, widget_session_id="zendesk-allocation").exists())
+
class TestZendeskImportJobUpdates(BaseTest):
def _make_job(self, **kwargs: Any) -> ZendeskImportJob: