Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
queries: Always pass no_key kwarg explicitly to select_for_update.
Mateusz Manderae474c61d120a
diff --git a/docs/subsystems/database-concurrency.md b/docs/subsystems/database-concurrency.mdnew file mode 100644index 00000000000..858262487cb--- /dev/null+++ b/docs/subsystems/database-concurrency.md@@ -0,0 +1,129 @@+# Database concurrency++## select_for_update()++When a transaction does a read-then-write sequence where correctness depends on the+state it read, it needs a row lock to serialize that operation with other+writers. Without a lock, another transaction can commit between the read and+write, making the transaction have stale information. Two requests/workers can+then apply conflicting updates.++Django exposes a way to control the appropriate row locks via+[`QuerySet.select_for_update()`][django-select-for-update-doc]. This produces+either `SELECT ... FOR NO KEY UPDATE` or `SELECT ... FOR UPDATE` queries,+depending on the `no_key` boolean argument passed to `select_for_update()`. The+key decision at each call site is choosing the appropriate lock strength.++[django-select-for-update-doc]: https://docs.djangoproject.com/en/5.0/ref/models/querysets/#select-for-update++### What select_for_update() does++`select_for_update()` issues a `SELECT ... FOR ...` query that locks the+selected rows until the surrounding transaction commits or rolls back. A+transaction trying to take a conflicting lock on those rows will block.+The behavior can be modified to either fail immediately if the lock can't be taken+or skip the rows we cannot lock, via the `nowait=True` and `skip_locked=True` arguments,+respectively.++This is the right tool for code paths where correctness depends on reading a+stable value and then writing based on that value in the same transaction.+This protection only works if other code paths that mutate the same data also+use appropriate row locks.++Additionally, `select_for_update()` should be used to ensure a consistent+order of lock acquisition to prevent deadlocks. In particular, for these two+example classes of situations:++- If two concurrent transactions attempt to update overlapping sets of rows,+ inconsistent ordering can lead to a deadlock. For example, if the first+ transaction locks rows in the order `id=1`, `id=2` and the second transaction+ locks them in the order `id=2`, `id=1`, they deadlock with the first+ transaction waiting for the lock on `id=2` to be released, while the second+ transaction waits for the lock on `id=1`. By using `select_for_update()` with+ a consistent `order_by()`, we can ensure both transactions acquire locks in+ the same order, preventing such deadlocks.+- If two concurrent transactions update rows in two tables in an inconsistent+ order, they can deadlock in a similar way. For example, if the first+ transaction updates a `Message` row, followed by some related `UserMessage`+ rows, while the second transaction updates the `UserMessage` rows, followed+ by the `Message` row, they can deadlock. The first transaction can end up+ stuck waiting for the lock on `UserMessage` rows, while the second+ transaction waits for the `Message` row lock. To prevent this, both+ transactions should use `select_for_update()` on the intended `Message` at+ the beginning - ensuring they execute serially and preventing the deadlock+ risk.++Because the lock lives for the duration of the transaction, we should keep the+`transaction.atomic()` block small once the lock is acquired.++As a project policy, Zulip requires an explicit `no_key=` kwarg on every+`select_for_update()` call, enforced by semgrep.++### Lock strengths (`no_key`)++Django's `select_for_update(no_key=...)` maps to PostgreSQL row-level locks:++- `no_key=True` takes a `FOR NO KEY UPDATE` lock.+- `no_key=False` takes a `FOR UPDATE` lock.++`FOR UPDATE` is stronger. In particular, it conflicts with the `FOR KEY SHARE` lock,+which PostgreSQL acquires for foreign-key checks when inserting/updating+referencing rows. Therefore, `FOR UPDATE` on a parent row will block inserts in other+tables that reference that row.++`FOR NO KEY UPDATE` still protects against concurrent writes to the locked row,+but does not block `FOR KEY SHARE`. This avoids unnecessary cross-table+contention and is usually the right default, unless the transaction has the possibility+of deleting some of the selected rows.++See [PostgreSQL's row-level lock documentation][postgres-row-level-lock-doc] for+further detail.++### Choosing `no_key=True` vs `no_key=False`++Use `no_key=True` when:++- You are updating fields other than FK-referenced key columns (in Zulip+ today, this is effectively just the row's primary key column).+- You are serializing access to prevent lost updates/races.+- The row itself will not be deleted and those key columns are not changing.++Use `no_key=False` when:++- You will delete the locked row (or call helper code that may delete it).+- You will change key columns that are referenced by foreign keys (as noted+ above, in Zulip today, this is just the row's primary key column).+- You intentionally need to block FK-reference creation to that row while the+ transaction is in progress.++If using `no_key=False`, add a short comment explaining why the stronger lock is+required.++### Example patterns++Typical update path (`no_key=True`):++```python+with transaction.atomic():+ row = Model.objects.select_for_update(no_key=True).get(id=row_id)+ row.some_number = row.some_number + 1+ row.save(update_fields=["some_number"])+```++Delete path (`no_key=False`):++```python+with transaction.atomic():+ row = Model.objects.select_for_update(no_key=False).get(id=row_id)+ maybe_delete_row(row)+```++When locking rows from a queryset with joins, use `of=("self",)` unless you+intentionally need to lock related tables too.++```python+rows = Message.objects.select_related(*Message.DEFAULT_SELECT_RELATED) \+ .select_for_update(of=("self",), no_key=True)+```++[postgres-row-level-lock-doc]: https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWSdiff --git a/docs/subsystems/index.md b/docs/subsystems/index.mdindex 4c6fab50bb8..a9e87d7d596 100644--- a/docs/subsystems/index.md+++ b/docs/subsystems/index.md@@ -21,6 +21,7 @@ performancerealmsmanagement-commandsschema-migrations+database-concurrencyhashchange-systememojionboarding-stepsdiff --git a/tools/semgrep-py.yml b/tools/semgrep-py.ymlindex 198ed302581..aaa1a90139c 100644--- a/tools/semgrep-py.yml+++ b/tools/semgrep-py.yml@@ -402,3 +402,13 @@ rules:$BODYlanguages: [python]severity: ERROR++ - id: select-for-update-require-no-key+ message: |+ Call select_for_update() with an explicit no_key= (True/False) kwarg. We should be purposeful about which lock we need.+ See https://zulip.readthedocs.io/en/latest/subsystems/database-concurrency.html#select-for-update for guidance.+ patterns:+ - pattern: $Q.select_for_update(...)+ - pattern-not: $Q.select_for_update(..., no_key=..., ...)+ languages: [python]+ severity: ERRORdiff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.pyindex 219df0c9029..d0c988c47ea 100644--- a/zerver/actions/message_edit.py+++ b/zerver/actions/message_edit.py@@ -1767,7 +1767,7 @@ def check_update_message(def re_thumbnail(message_class: type[Message] | type[ArchivedMessage], message_id: int, enqueue: bool) -> None:- message = message_class.objects.select_for_update().get(id=message_id)+ message = message_class.objects.select_for_update(no_key=True).get(id=message_id)assert message.rendered_content is not Noneimage_metadata = manifest_and_get_user_upload_previews(message.realm_id,diff --git a/zerver/actions/presence.py b/zerver/actions/presence.pyindex f6978bfad4d..51514e6e40d 100644--- a/zerver/actions/presence.py+++ b/zerver/actions/presence.py@@ -123,7 +123,9 @@ def do_update_user_presence(defaults["last_active_time"] = log_timetry:- presence = UserPresence.objects.select_for_update().get(user_profile=user_profile)+ presence = UserPresence.objects.select_for_update(no_key=True).get(+ user_profile=user_profile+ )creating = Falseexcept UserPresence.DoesNotExist:# We're not ready to write until we know the next last_update_id value.@@ -196,7 +198,7 @@ def do_update_user_presence(# Equivalent Python code:# if creating or len(update_fields) > 0:- # presence_sequence = PresenceSequence.objects.select_for_update().get(realm_id=user_profile.realm_id)+ # presence_sequence = PresenceSequence.objects.select_for_update(no_key=True).get(realm_id=user_profile.realm_id)# new_last_update_id = presence_sequence.last_update_id + 1# presence_sequence.last_update_id = new_last_update_id# if creating:diff --git a/zerver/actions/realm_settings.py b/zerver/actions/realm_settings.pyindex ade69554f0b..4fcd83db382 100644--- a/zerver/actions/realm_settings.py+++ b/zerver/actions/realm_settings.py@@ -719,7 +719,7 @@ def do_delete_all_realm_attachments(realm: Realm) -> None:to_delete = (obj_class._default_manager.filter(realm_id=realm.id).order_by("pk")- .select_for_update()+ .select_for_update(no_key=False).values_list("path_id", flat=True))for path_id in to_delete.iterator():diff --git a/zerver/actions/scheduled_messages.py b/zerver/actions/scheduled_messages.pyindex d3a48cfc50e..b5d7b59f264 100644--- a/zerver/actions/scheduled_messages.py+++ b/zerver/actions/scheduled_messages.py@@ -430,7 +430,7 @@ def try_deliver_one_scheduled_message() -> bool:delivered=False,failed=False,)- .select_for_update()+ .select_for_update(no_key=True).first())diff --git a/zerver/actions/uploads.py b/zerver/actions/uploads.pyindex 4907fb3a240..f95a5d0ee67 100644--- a/zerver/actions/uploads.py+++ b/zerver/actions/uploads.py@@ -94,7 +94,7 @@ def do_delete_old_unclaimed_attachments(weeks_ago: int) -> None:with delete_message_attachments(delete_from=(ImageAttachment, Attachment)) as delete_one:for path_id in (old_unclaimed_attachments.values_list("path_id", flat=True)- .select_for_update(of=("self",))+ .select_for_update(of=("self",), no_key=False).iterator()):delete_one(path_id)@@ -103,7 +103,7 @@ def do_delete_old_unclaimed_attachments(weeks_ago: int) -> None:) as delete_one:for path_id in (old_unclaimed_archived_attachments.values_list("path_id", flat=True)- .select_for_update(of=("self",))+ .select_for_update(of=("self",), no_key=False).iterator()):delete_one(path_id)@@ -123,7 +123,9 @@ def check_attachment_reference_change(to_remove = list(prev_attachments - new_attachments)if len(to_remove) > 0:- attachments_to_update = Attachment.objects.filter(path_id__in=to_remove).select_for_update()+ attachments_to_update = Attachment.objects.filter(path_id__in=to_remove).select_for_update(+ no_key=True+ )message.attachment_set.remove(*attachments_to_update)sender = message.senderdiff --git a/zerver/lib/message.py b/zerver/lib/message.pyindex 089c5098a9c..c43a3d466e6 100644--- a/zerver/lib/message.py+++ b/zerver/lib/message.py@@ -399,7 +399,11 @@ def access_message(if lock_message:# We want to lock only the `Message` row, and not the related fields# because the `Message` row only has a possibility of races.- base_query = base_query.select_for_update(of=("self",))+ # This is used in the message deletion codepath, so we need no_key=False+ # to acquire a FOR UPDATE lock.+ # TODO: We can easily change the lock_message argument to instead take an enum+ # for caller to specify whether no_key=False or True should be used.+ base_query = base_query.select_for_update(of=("self",), no_key=False)message = base_query.get(id=message_id)except Message.DoesNotExist:raise JsonableError(_("Invalid message(s)"))@@ -441,7 +445,9 @@ def access_message_and_usermessage(if lock_message:# We want to lock only the `Message` row, and not the related fields# because the `Message` row only has a possibility of races.- base_query = base_query.select_for_update(of=("self",))+ # This isn't used in any message deletion codepaths, so we can use+ # no_key=True.+ base_query = base_query.select_for_update(of=("self",), no_key=True)message = base_query.get(id=message_id)except Message.DoesNotExist:raise JsonableError(_("Invalid message(s)"))diff --git a/zerver/lib/onboarding.py b/zerver/lib/onboarding.pyindex 52f56e7ca65..3a41c92011b 100644--- a/zerver/lib/onboarding.py+++ b/zerver/lib/onboarding.py@@ -580,7 +580,7 @@ This **greetings** topic is a great place to say “hi” :wave: to your teammat# We find the one of our just-sent greetings messages, and react to it.# This is a bit hacky, but works and is kinda a 1-off thing.greetings_message = (- Message.objects.select_for_update()+ Message.objects.select_for_update(no_key=True).filter(id__in=message_ids, content=remove_single_newlines(content1_of_greetings_topic_name))diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.pyindex 9e81967e9f1..dac5b439435 100644--- a/zerver/lib/push_notifications.py+++ b/zerver/lib/push_notifications.py@@ -1597,7 +1597,7 @@ def send_push_notifications()# Uses 'zerver_device_user_push_token_id_idx' index.with transaction.atomic(durable=True):- push_devices = Device.objects.select_for_update().filter(+ push_devices = Device.objects.select_for_update(no_key=True).filter(user=user_profile, push_token_id__in=delete_token_ids_int)for push_device in push_devices:diff --git a/zerver/lib/scim.py b/zerver/lib/scim.pyindex a15b21147ae..9625e5475e3 100644--- a/zerver/lib/scim.py+++ b/zerver/lib/scim.py@@ -30,6 +30,7 @@ from zerver.lib.subdomains import get_subdomainfrom zerver.lib.user_groups import (check_user_group_name,get_role_based_system_groups_dict,+ get_user_group_by_id_in_realm,get_user_group_direct_member_ids,)from zerver.models import Realm, UserProfile@@ -579,8 +580,7 @@ class ZulipSCIMGroup(SCIMGroup):returnwith transaction.atomic(savepoint=False):- # We need to lock the group now to conduct update operations without race conditions.- user_group = NamedUserGroup.objects.select_for_update().get(id=self.obj.id)+ user_group = get_user_group_by_id_in_realm(self.obj.id, realm, for_read=False)current_member_ids = set(get_user_group_direct_member_ids(user_group))if name_new_value is not None:do_update_user_group_name(self.obj, name_new_value, acting_user=None)diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.pyindex 752e29e7143..83d1bc6fe9d 100644--- a/zerver/lib/send_email.py+++ b/zerver/lib/send_email.py@@ -554,7 +554,10 @@ def clear_scheduled_emails(user_ids: list[int], email_type: int | None = None) -# We need to obtain a FOR UPDATE lock on the selected rows to keep a concurrent# execution of this function (or something else) from deleting them before we access# the .users attribute.- items = ScheduledEmail.objects.filter(users__in=user_ids).select_for_update()+ items = ScheduledEmail.objects.filter(users__in=user_ids).select_for_update(+ # We might end up deleting rows.+ no_key=False+ )if email_type is not None:items = items.filter(type=email_type)item_ids = list(items.values_list("id", flat=True))diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.pyindex 3861de8344a..784717e86e9 100644--- a/zerver/lib/thumbnail.py+++ b/zerver/lib/thumbnail.py@@ -441,7 +441,7 @@ def manifest_and_get_user_upload_previews(realm_id=realm_id, path_id__in=path_ids).order_by("id")if lock:- image_attachments = image_attachments.select_for_update(of=("self",))+ image_attachments = image_attachments.select_for_update(of=("self",), no_key=True)for image_attachment in image_attachments:if image_attachment.thumbnail_metadata == []:# Image exists, and header of it parsed as a valid image,diff --git a/zerver/lib/user_groups.py b/zerver/lib/user_groups.pyindex 3476635188d..b5f1bffccf8 100644--- a/zerver/lib/user_groups.py+++ b/zerver/lib/user_groups.py@@ -121,9 +121,17 @@ def get_user_group_by_id_in_realm(if for_read:user_group = NamedUserGroup.objects.get(id=user_group_id, realm_for_sharding=realm)else:- user_group = NamedUserGroup.objects.select_for_update().get(- id=user_group_id, realm_for_sharding=realm- )+ user_group = NamedUserGroup.objects.select_for_update(+ # We never fully DELETE NamedUserGroup rows; however, we do want this getter+ # to prevent the addition of new users to the group while we hold the lock,+ # to block with hypothetical other codepath that might try to modify memberships+ # without taking an appropriate explicit lock.+ # Ideally, we would wish to also prevent the deletion of group memberships for the+ # duration of the lock even if the transaction doing the deletion forgets to take+ # its own FOR UPDATE lock on this group, but SELECT FOR UPDATE does not offer+ # that possibility. We accept this as a limitation for now.+ no_key=False,+ ).get(id=user_group_id, realm_for_sharding=realm)if not allow_deactivated and user_group.deactivated:raise JsonableError(_("User group is deactivated."))@@ -333,7 +341,12 @@ def lock_subgroups_with_respect_to_supergroup(recursive_subgroups = list(get_recursive_subgroups_for_groups(potential_subgroup_ids, acting_user.realm- ).select_for_update(nowait=True)+ ).select_for_update(+ nowait=True,+ # We want to prevent insertion of new memberships to these rows while+ # the lock is held.+ no_key=False,+ ))# TODO: This select_for_update query is subject to deadlocking, and# better error handling is needed. We may use@@ -460,7 +473,7 @@ def update_or_create_user_group_for_setting()user_group.direct_members.set(member_users)- potential_subgroups = NamedUserGroup.objects.select_for_update().filter(+ potential_subgroups = NamedUserGroup.objects.select_for_update(no_key=True).filter(realm_for_sharding=realm, id__in=direct_subgroups)group_ids_found = [group.id for group in potential_subgroups]diff --git a/zerver/management/commands/deliver_scheduled_emails.py b/zerver/management/commands/deliver_scheduled_emails.pyindex 35744c00fed..d54f57ce4cc 100644--- a/zerver/management/commands/deliver_scheduled_emails.py+++ b/zerver/management/commands/deliver_scheduled_emails.py@@ -41,7 +41,12 @@ Usage: ./manage.py deliver_scheduled_emailsjob = (ScheduledEmail.objects.filter(scheduled_timestamp__lte=timezone_now()).prefetch_related("users")- .select_for_update(skip_locked=True)+ .select_for_update(+ skip_locked=True,+ # These rows will later be deleted, so take a FOR UPDATE+ # lock.+ no_key=False,+ ).order_by("scheduled_timestamp").first())diff --git a/zerver/management/commands/update_subscriber_counts.py b/zerver/management/commands/update_subscriber_counts.pyindex 03968ab1dc0..6df8e5b05c8 100644--- a/zerver/management/commands/update_subscriber_counts.py+++ b/zerver/management/commands/update_subscriber_counts.py@@ -98,7 +98,7 @@ accurate; this command is run as a daily cron job to ensure the number is accurafor stream_id in stream_ids.iterator():with transaction.atomic(durable=True):- stream = Stream.objects.select_for_update().get(id=stream_id)+ stream = Stream.objects.select_for_update(no_key=True).get(id=stream_id)actual_subscriber_count = Subscription.objects.filter(active=True,recipient__type=2,diff --git a/zerver/migrations/0377_message_edit_history_format.py b/zerver/migrations/0377_message_edit_history_format.pyindex 703cf4d83a3..558f8a05115 100644--- a/zerver/migrations/0377_message_edit_history_format.py+++ b/zerver/migrations/0377_message_edit_history_format.py@@ -49,7 +49,7 @@ def backfill_message_edit_history_chunk(The range of message IDs to be processed is inclusive on both ends."""messages = (- message_model.objects.select_for_update()+ message_model.objects.select_for_update(no_key=True).only("recipient","recipient__type",diff --git a/zerver/models/messages.py b/zerver/models/messages.pyindex f03e110ffcd..515f4949934 100644--- a/zerver/models/messages.py+++ b/zerver/models/messages.py@@ -668,8 +668,14 @@ class UserMessage(AbstractUserMessage):simultaneous duplicate API requests to mark a certain set ofmessages as read).+ Note: Since we don't expect these UserMessage rows to be deleted by the+ caller, a FOR NO KEY UPDATE lock might be sufficient here. However, we+ don't expect the stronger FOR UPDATE lock to cause any issues,+ so for now, we still pass no_key=False, acquiring the stronger lock."""- return UserMessage.objects.select_for_update(of=("self",)).order_by("message_id")+ return UserMessage.objects.select_for_update(of=("self",), no_key=False).order_by(+ "message_id"+ )@staticmethoddef has_any_mentions(user_profile_id: int, message_id: int) -> bool:diff --git a/zerver/views/streams.py b/zerver/views/streams.pyindex a506272b0fb..afb387e5573 100644--- a/zerver/views/streams.py+++ b/zerver/views/streams.py@@ -1254,7 +1254,9 @@ def delete_in_topic(return json_success(request, data={"complete": False})with transaction.atomic(durable=True):messages_to_delete = messages.order_by("-id")[0:batch_size].select_for_update(- of=("self",)+ # We're deleting, so a FOR UPDATE lock is needed.+ no_key=False,+ of=("self",),)if not messages_to_delete:breakdiff --git a/zerver/views/upload.py b/zerver/views/upload.pyindex c9609da64e1..95caddd06e1 100644--- a/zerver/views/upload.py+++ b/zerver/views/upload.py@@ -343,7 +343,11 @@ def serve_file(# currently processing the row.with transaction.atomic(savepoint=False):ensure_thumbnails(- ImageAttachment.objects.select_for_update().get(id=image_attachment.id),+ # ensure_thumbnails can in rare cases end up deleting the ImageAttachment row, if thumbnailing+ # fails. Since a DELETE can happen, we want a full FOR UPDATE lock.+ ImageAttachment.objects.select_for_update(no_key=False).get(+ id=image_attachment.id+ ),)# Update the path that we are fetching to be the thumbnaildiff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.pyindex 58843eafd61..3e66dc91d55 100644--- a/zerver/views/user_settings.py+++ b/zerver/views/user_settings.py@@ -138,7 +138,7 @@ def confirm_email_change(request: HttpRequest, *, key: str) -> HttpResponse:new_email = email_change_object.new_emailold_email = email_change_object.old_email- user_profile = UserProfile.objects.select_for_update().get(+ user_profile = UserProfile.objects.select_for_update(no_key=True).get(id=email_change_object.user_profile_id)diff --git a/zerver/worker/embed_links.py b/zerver/worker/embed_links.pyindex 37b3f6c8e8a..e4609be4696 100644--- a/zerver/worker/embed_links.py+++ b/zerver/worker/embed_links.py@@ -44,7 +44,7 @@ class FetchLinksEmbedData(QueueProcessingWorker):# https://zulip.readthedocs.io/en/latest/subsystems/queuing.html#publishing-events-into-a-queuewith transaction.atomic(savepoint=False):try:- message = Message.objects.select_for_update().get(id=event["message_id"])+ message = Message.objects.select_for_update(no_key=True).get(id=event["message_id"])except Message.DoesNotExist:# Message may have been deletedreturndiff --git a/zerver/worker/thumbnail.py b/zerver/worker/thumbnail.pyindex a9f422c6453..d335ede0251 100644--- a/zerver/worker/thumbnail.py+++ b/zerver/worker/thumbnail.py@@ -39,7 +39,12 @@ class ThumbnailWorker(QueueProcessingWorker):# directly to a thumbnail URL we have not made yet.# This may mean that we may generate 0 thumbnail# images once we get the lock.- row = ImageAttachment.objects.select_for_update(of=("self",)).get(id=event["id"])+ # If the image data is bad and thumbnailing fails, the+ # ImageAttachment row might be deleted; so we need a FOR UPDATE+ # lock.+ row = ImageAttachment.objects.select_for_update(of=("self",), no_key=False).get(+ id=event["id"]+ )except ImageAttachment.DoesNotExist: # nocoveragelogger.info("ImageAttachment row %d missing [%dms]",@@ -226,7 +231,7 @@ def update_message_rendered_content(for message_class in (Message, ArchivedMessage):messages_with_image = (message_class.objects.filter(realm_id=realm_id, attachment__path_id=path_id)- .select_for_update(of=("self",))+ .select_for_update(of=("self",), no_key=True).order_by("id"))for message in messages_with_image:diff --git a/zilencer/views.py b/zilencer/views.pyindex c941defa51d..350a194863e 100644--- a/zilencer/views.py+++ b/zilencer/views.py@@ -1589,7 +1589,7 @@ def remote_server_post_analytics(# Lock the server, preventing this from racing with other# duplicate submissions of the data- server = RemoteZulipServer.objects.select_for_update().get(id=server.id)+ server = RemoteZulipServer.objects.select_for_update(no_key=True).get(id=server.id)remote_server_version_updated = Falseif version is not None: