Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
direct_messages: Remove personal-recipient message code paths.
Alex Vandivercf7d0271c2fe
diff --git a/zerver/actions/message_delete.py b/zerver/actions/message_delete.pyindex 2ab20a0bc6f..d1d1940a207 100644--- a/zerver/actions/message_delete.py+++ b/zerver/actions/message_delete.py@@ -59,13 +59,6 @@ def check_update_first_message_id(def do_delete_messages(realm: Realm, messages: Iterable[Message], *, acting_user: UserProfile | None) -> None:- """1:1 Direct messages must be grouped to a single conversation by- the caller, since this logic does not know how to handle multiple- senders sharing a single Recipient object.-- When the Recipient.PERSONAL is no longer a case to consider, this- restriction can be deleted.- """message_ids = [message.id for message in messages]move_messages_to_archive(message_ids,diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.pyindex e31df9beb8e..dfb998f8056 100644--- a/zerver/actions/message_send.py+++ b/zerver/actions/message_send.py@@ -788,7 +788,7 @@ def create_user_messages(base_flags = 0if rendering_result.mentions_stream_wildcard:base_flags |= UserMessage.flags.stream_wildcard_mentioned- if message.recipient.type in [Recipient.DIRECT_MESSAGE_GROUP, Recipient.PERSONAL]:+ if message.recipient.type == Recipient.DIRECT_MESSAGE_GROUP:base_flags |= UserMessage.flags.is_private# For long_term_idle (aka soft-deactivated) users, we are alloweddiff --git a/zerver/lib/display_recipient.py b/zerver/lib/display_recipient.pyindex ad7808002a2..294c33ec1ec 100644--- a/zerver/lib/display_recipient.py+++ b/zerver/lib/display_recipient.py@@ -138,28 +138,21 @@ def bulk_fetch_user_display_recipients(Returns dict mapping recipient_id to corresponding display_recipient"""- from zerver.models import Recipientfrom zerver.models.recipients import bulk_get_direct_message_group_user_idsif len(recipient_tuples) == 0:return {}get_recipient_id = lambda tup: tup[0]- get_type = lambda tup: tup[1]-- direct_message_group_tuples = [- tup for tup in recipient_tuples if get_type(tup) == Recipient.DIRECT_MESSAGE_GROUP- ]- direct_message_group_recipient_ids = [- get_recipient_id(tup) for tup in direct_message_group_tuples- ]+ direct_message_group_recipient_ids = [get_recipient_id(tup) for tup in recipient_tuples]user_ids_in_direct_message_groups = bulk_get_direct_message_group_user_ids(direct_message_group_recipient_ids)# Find all user ids whose UserProfiles we will need to fetch:- user_ids_to_fetch = set()+ user_ids_to_fetch: set[int] = set()+for recipient_id in direct_message_group_recipient_ids:direct_message_group_user_ids = user_ids_in_direct_message_groups[recipient_id]user_ids_to_fetch |= direct_message_group_user_ids@@ -168,6 +161,7 @@ def bulk_fetch_user_display_recipients(user_display_recipients = bulk_fetch_single_user_display_recipients(list(user_ids_to_fetch))result = {}+for recipient_id in direct_message_group_recipient_ids:user_ids = sorted(user_ids_in_direct_message_groups[recipient_id])display_recipients = [user_display_recipients[user_id] for user_id in user_ids]diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.pyindex 51bb0a4d356..9f774e4b2e1 100644--- a/zerver/lib/email_notifications.py+++ b/zerver/lib/email_notifications.py@@ -409,19 +409,15 @@ def prepare_synthetic_root_message_id(recipient_type: int,recipient_id: int,*,- dm_sender_id: int | None = None,topic_name: str | None = None,) -> str:"""To help email clients thread messages from the same conversation together,we treat all messages as replies to a synthetic root message. This root- message's `Message-ID` header is derived from the recipient_id (and sender_id or topic),- ensuring consistency across all emails in the thread.+ message's `Message-ID` header is derived from the recipient_id (and topic+ for channel messages), ensuring consistency across all emails in the thread."""- if recipient_type == Recipient.PERSONAL:- assert dm_sender_id is not None- id_left = f"{recipient_id}.{dm_sender_id}"- elif recipient_type == Recipient.DIRECT_MESSAGE_GROUP:+ if recipient_type == Recipient.DIRECT_MESSAGE_GROUP:id_left = f"{recipient_id}"else:assert topic_name is not Nonediff --git a/zerver/lib/message.py b/zerver/lib/message.pyindex 1d936c2774a..f57dcddccbf 100644--- a/zerver/lib/message.py+++ b/zerver/lib/message.py@@ -11,7 +11,6 @@ from django.db.models import Exists, F, Max, OuterRef, QuerySet, Subquery, Sumfrom django.utils.timezone import now as timezone_nowfrom django.utils.translation import gettext as _from django_cte import CTE, with_cte-from psycopg2.sql import SQLfrom analytics.lib.counts import COUNT_STATSfrom analytics.models import RealmCount@@ -1421,81 +1420,12 @@ def get_last_message_id() -> int:return last_id-def _get_recent_conversations_via_legacy_personal_recipient(- user_profile_id: int, recipient_id: int-) -> list[tuple[int, int]]:- """This function uses some carefully optimized SQL queries, designed- to use the UserMessage index on private_messages. It is- somewhat complicated by the fact that for 1:1 direct- messages, we store the message against a recipient_id of whichever- user was the recipient, and thus for 1:1 direct messages sent- directly to us, we need to look up the other user from the- sender_id on those messages. You'll see that pattern repeated- both here and also in zerver/lib/events.py.-- It may be possible to write this query directly in Django, however- it is made much easier by using CTEs, which Django does not- natively support.- """- RECENT_CONVERSATIONS_LIMIT = 1000-- query = SQL(- """- WITH personals AS (- SELECT um.message_id AS message_id- FROM zerver_usermessage um- WHERE um.user_profile_id = %(user_profile_id)s- AND um.flags & 2048 <> 0- ORDER BY message_id DESC limit %(conversation_limit)s- ),- message AS (- SELECT message_id,- CASE- WHEN m.recipient_id = %(recipient_id)s- THEN m.sender_id- ELSE NULL- END AS sender_id,- CASE- WHEN m.recipient_id <> %(recipient_id)s- THEN m.recipient_id- ELSE NULL- END AS outgoing_recipient_id- FROM personals- JOIN zerver_message m- ON personals.message_id = m.id- ),- unified AS (- SELECT message_id,- COALESCE(zerver_userprofile.recipient_id, outgoing_recipient_id) AS other_recipient_id- FROM message- LEFT JOIN zerver_userprofile- ON zerver_userprofile.id = sender_id- )- SELECT other_recipient_id,- MAX(message_id)- FROM unified- GROUP BY other_recipient_id- """- )-- with connection.cursor() as cursor:- cursor.execute(- query,- {- "user_profile_id": user_profile_id,- "conversation_limit": RECENT_CONVERSATIONS_LIMIT,- "recipient_id": recipient_id,- },- )- return cursor.fetchall()--def _get_recent_conversations_via_direct_message_group(user_profile_id: int,) -> list[tuple[int, int]]:"""- This function fetches the most recent 1:1 conversations with this- user which were through direct message groups.+ This function fetches the most recent DM conversations for this+ user, returning (recipient_id, max_message_id) pairs."""RECENT_CONVERSATIONS_LIMIT = 1000@@ -1507,12 +1437,8 @@ def _get_recent_conversations_via_direct_message_group()return list(- # When all DMs are through direct message groups, and not- # personal recipients, the recipient__type limit can be- # removed.Message.objects.filter(id__in=recent_pm_message_ids,- recipient__type=Recipient.DIRECT_MESSAGE_GROUP,).values("recipient_id").annotate(max_message_id=Max("id"))@@ -1526,20 +1452,12 @@ def get_recent_private_conversations(user_profile: UserProfile) -> dict[frozensebelow; this structure is converted into its final form bypost_process."""- # Step 1: Collect recent message info- direct_recipient_conversations = []- if user_profile.recipient_id is not None:- direct_recipient_conversations = _get_recent_conversations_via_legacy_personal_recipient(- user_profile.id, user_profile.recipient_id- )-recent_conversations = _get_recent_conversations_via_direct_message_group(user_profile.id)- all_recipients = {recipient_id for recipient_id, _ in direct_recipient_conversations}- all_recipients.update(recipient_id for recipient_id, _ in recent_conversations)+ all_recipients = {recipient_id for recipient_id, _ in recent_conversations}# Now we need to map all the recipient_id objects to lists of user IDs- recipient_map = defaultdict(list)+ recipient_map: dict[int, list[int]] = defaultdict(list)subscriptions = (Subscription.objects.filter(recipient_id__in=all_recipients).exclude(user_profile_id=user_profile.id)@@ -1548,18 +1466,10 @@ def get_recent_private_conversations(user_profile: UserProfile) -> dict[frozensefor recipient_id, user_profile_id in subscriptions:recipient_map[recipient_id].append(user_profile_id)- # Merge the two sets of conversations- merged_conversations: dict[frozenset[int], int] = {}- for recipient_id, max_message_id in direct_recipient_conversations + recent_conversations:- user_id_set = frozenset(recipient_map[recipient_id])- if user_id_set in merged_conversations:- merged_conversations[user_id_set] = max(- max_message_id, merged_conversations[user_id_set]- )- else:- merged_conversations[user_id_set] = max_message_id-- return merged_conversations+ return {+ frozenset(recipient_map[recipient_id]): max_message_id+ for recipient_id, max_message_id in recent_conversations+ }def can_mention_many_users(sender: UserProfile) -> bool:diff --git a/zerver/lib/message_cache.py b/zerver/lib/message_cache.pyindex 4cb8751c790..112b5771f9e 100644--- a/zerver/lib/message_cache.py+++ b/zerver/lib/message_cache.py@@ -525,7 +525,7 @@ class MessageDict:if recipient_type == Recipient.STREAM:display_type = "stream"- elif recipient_type in (Recipient.DIRECT_MESSAGE_GROUP, Recipient.PERSONAL):+ elif recipient_type == Recipient.DIRECT_MESSAGE_GROUP:assert not isinstance(display_recipient, str)display_type = "private"if len(display_recipient) == 1:diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.pyindex 690f8dc4b0d..e1d9e52f58e 100644--- a/zerver/lib/narrow.py+++ b/zerver/lib/narrow.py@@ -560,8 +560,6 @@ class NarrowBuilder:if user_profiles == []:return query.where(maybe_negate(false()))- all_user_ids = {u.id for u in user_profiles} | {self.user_profile.id}-recipient = recipient_for_user_profiles(user_profiles=user_profiles,forwarded_mirror_message=False,@@ -573,80 +571,10 @@ class NarrowBuilder:except (JsonableError, ValidationError):raise BadNarrowOperatorError("unknown user in " + str(operand))except DirectMessageGroup.DoesNotExist:- # Group DM where direct message group doesn't exist.- # For 3+ person groups, no messages can exist.- if len(all_user_ids) > 2:- return query.where(maybe_negate(false()))- # For 1:1 DMs, fall through to query PERSONAL recipients only- recipient = None-- # Group direct message (3+ participants)- if (- recipient is not None- and recipient.type == Recipient.DIRECT_MESSAGE_GROUP- and len(all_user_ids) > 2- ):- cond = column("recipient_id", Integer) == recipient.id- return query.where(maybe_negate(cond))-- # 1:1 direct message- other_participant = None-- # Find if another person is in direct message- for user in user_profiles:- if user.id != self.user_profile.id:- other_participant = user-- # Direct message with another person- if other_participant:- # We need bidirectional direct messages with another person.- # But Recipient.PERSONAL objects only encode the person who- # received the message, and not the other participant in- # the thread (the sender), we need to do a somewhat- # complex query to get messages between these two users- # with either of them as the sender.- self_recipient_id = self.user_profile.recipient_id- other_recipient_id = other_participant.recipient_id-- # Include messages from both PERSONAL and DM group recipients.- # This handles the migration period where messages may exist- # with either recipient type.- group_recipient: Iterable[ClauseElement] = tuple()- if recipient and recipient.type == Recipient.DIRECT_MESSAGE_GROUP:- group_recipient = (column("recipient_id", Integer) == recipient.id,)- cond = and_(- column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0,- column("realm_id", Integer) == self.realm.id,- or_(- and_(- column("sender_id", Integer) == other_participant.id,- column("recipient_id", Integer) == self_recipient_id,- ),- and_(- column("sender_id", Integer) == self.user_profile.id,- column("recipient_id", Integer) == other_recipient_id,- ),- *group_recipient,- ),- )-- return query.where(maybe_negate(cond))+ # DM group doesn't exist, so no messages can exist.+ return query.where(maybe_negate(false()))- # Direct message with self- # Build condition for PERSONAL recipients (bidirectional)- # Include messages from both PERSONAL and DM group recipients- personal_cond = column("recipient_id", Integer) == self.user_profile.recipient_id- if recipient is not None and recipient.type == Recipient.DIRECT_MESSAGE_GROUP:- personal_cond = or_(- personal_cond,- column("recipient_id", Integer) == recipient.id,- )- cond = and_(- column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0,- column("realm_id", Integer) == self.realm.id,- column("sender_id", Integer) == self.user_profile.id,- personal_cond,- )+ cond = column("recipient_id", Integer) == recipient.idreturn query.where(maybe_negate(cond))def _get_direct_message_group_recipients(self, other_user: UserProfile) -> set[int]:@@ -701,26 +629,7 @@ class NarrowBuilder:direct_message_group_recipient_ids)- self_recipient_id = self.user_profile.recipient_id- if self_recipient_id is not None and narrow_user_profile.recipient_id is not None:- # See note above in `by_dm` about needing bidirectional messages- # for direct messages with another person.- dm_conditions = or_(- and_(- column("sender_id", Integer) == narrow_user_profile.id,- column("recipient_id", Integer) == self_recipient_id,- ),- and_(- column("sender_id", Integer) == self.user_profile.id,- column("recipient_id", Integer) == narrow_user_profile.recipient_id,- ),- direct_message_group_cond,- )- cond = and_(private_flag, realm_match, dm_conditions)- else:- # If the user does not have a recipient_id, then they only rely on- # direct group message for their conversations.- cond = and_(private_flag, realm_match, direct_message_group_cond)+ cond = and_(private_flag, realm_match, direct_message_group_cond)return query.where(maybe_negate(cond))def by_mention(diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.pyindex 8d96135e972..a600e0ea15e 100644--- a/zerver/lib/push_notifications.py+++ b/zerver/lib/push_notifications.py@@ -1039,16 +1039,15 @@ def get_message_payload(data["topic"] = get_topic_display_name(message.topic_name(), user_profile.default_language)else:- assert message.recipient.type in [Recipient.PERSONAL, Recipient.DIRECT_MESSAGE_GROUP]+ assert message.recipient.type == Recipient.DIRECT_MESSAGE_GROUPif for_legacy_clients:data["recipient_type"] = "private"- if message.recipient.type == Recipient.DIRECT_MESSAGE_GROUP:- # For group DMs, we need to fetch the users for the pm_users field.- # Note that this doesn't do a separate database query, because both- # functions use the get_display_recipient_by_id cache.- recipients = get_display_recipient(message.recipient)- if len(recipients) > 2:- data["pm_users"] = direct_message_group_users(message.recipient.id)+ # For 3+ person DMs, we need to fetch the users for the pm_users field.+ # Note that this doesn't do a separate database query, because both+ # functions use the get_display_recipient_by_id cache.+ recipients = get_display_recipient(message.recipient)+ if len(recipients) > 2:+ data["pm_users"] = direct_message_group_users(message.recipient.id)else:data["recipient_type"] = "direct"# For 1:1 and group DMs, we need to fetch the users for the `recipient_user_ids`@@ -1058,7 +1057,7 @@ def get_message_payload(recipient_user_ids = {display_recipient["id"] for display_recipient in display_recipients}- if len(recipient_user_ids) == 1: # Recipient.PERSONAL+ if len(recipient_user_ids) == 1: # Self-DMrecipient_user_ids.add(message.sender_id)data["recipient_user_ids"] = sorted(recipient_user_ids)@@ -1116,8 +1115,6 @@ def get_apns_alert_subtitle(NotificationTriggers.STREAM_WILDCARD_MENTION,):return _("{full_name} mentioned everyone:").format(full_name=sender_name)- elif message.recipient.type == Recipient.PERSONAL:- return ""elif message.recipient.type == Recipient.DIRECT_MESSAGE_GROUP:recipients = get_display_recipient(message.recipient)if len(recipients) <= 2:diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 6431976a906..0de6c9eea8a 100644--- a/zerver/lib/test_classes.py+++ b/zerver/lib/test_classes.py@@ -2866,7 +2866,7 @@ class PushNotificationTestCase(BouncerTestCase):self.user_profile = self.example_user("hamlet")self.sending_client = get_client("test")self.sender = self.example_user("hamlet")- self.personal_recipient_user = self.example_user("othello")+ self.dm_recipient_user = self.example_user("othello")def get_message(self, type: int, type_id: int, realm_id: int) -> Message:recipient, _ = Recipient.objects.get_or_create(diff --git a/zerver/lib/users.py b/zerver/lib/users.pyindex ec37616481a..1187827eede 100644--- a/zerver/lib/users.py+++ b/zerver/lib/users.py@@ -768,15 +768,12 @@ def check_can_access_user(recipient__type__in=[Recipient.STREAM, Recipient.DIRECT_MESSAGE_GROUP],).values_list("recipient_id", flat=True)- if Subscription.objects.filter(+ return Subscription.objects.filter(recipient_id__in=subscribed_recipient_ids,user_profile=target_user,active=True,is_user_active=True,- ).exists():- return True-- return False+ ).exists()def get_inaccessible_user_ids(diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.pyindex ec4eef4e0dc..ddd92342f5f 100644--- a/zerver/tests/test_event_system.py+++ b/zerver/tests/test_event_system.py@@ -1278,7 +1278,7 @@ class FetchQueriesTest(ZulipTestCase):self.login_user(user)with (- self.assert_database_query_count(49),+ self.assert_database_query_count(48),mock.patch("zerver.lib.events.always_want") as want_mock,):fetch_initial_state_data(user, realm=user.realm)@@ -1317,7 +1317,7 @@ class FetchQueriesTest(ZulipTestCase):realm_user=4,realm_user_groups=2,realm_user_settings_defaults=1,- recent_private_conversations=2,+ recent_private_conversations=1,reminders=1,saved_snippets=1,scheduled_messages=1,diff --git a/zerver/tests/test_handle_push_notification.py b/zerver/tests/test_handle_push_notification.pyindex 567f2bb023c..dc8846b221b 100644--- a/zerver/tests/test_handle_push_notification.py+++ b/zerver/tests/test_handle_push_notification.py@@ -62,8 +62,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=self.user_profile,@@ -163,8 +163,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=self.user_profile,@@ -230,8 +230,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=self.user_profile,@@ -333,8 +333,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=self.user_profile,@@ -361,8 +361,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):user_profile = self.example_user("hamlet")message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)usermessage = UserMessage.objects.create(@@ -408,8 +408,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):user_profile = self.example_user("hamlet")message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=user_profile,@@ -443,8 +443,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):user_profile = self.example_user("hamlet")message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=user_profile,@@ -529,8 +529,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):user_profile = self.user_profilemessage = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=user_profile,@@ -662,7 +662,7 @@ class HandlePushNotificationTest(PushNotificationTestCase):# * 3 : fetch PushDeviceToken, update RealmCount, fetch Devicemessage = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,+ type_id=self.dm_recipient_user.id,realm_id=realm.id,)UserMessage.objects.create(user_profile=self.user_profile, message=message)@@ -716,8 +716,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):user_profile = self.user_profilemessage = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=user_profile,@@ -775,8 +775,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):self.setup_fcm_tokens()message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=self.user_profile,@@ -1127,8 +1127,8 @@ class HandlePushNotificationTest(PushNotificationTestCase):user_profile = self.example_user("hamlet")message = self.get_message(Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ type_id=self.dm_recipient_user.id,+ realm_id=self.dm_recipient_user.realm_id,)UserMessage.objects.create(user_profile=user_profile,diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex 54b4641f59f..8f430eba573 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -305,7 +305,7 @@ class HomeTest(ZulipTestCase):# Verify succeeds once logged-inwith (- self.assert_database_query_count(59),+ self.assert_database_query_count(58),patch("zerver.lib.cache.cache_set") as cache_mock,):result = self._get_home_page(stream="Denmark")@@ -641,7 +641,7 @@ class HomeTest(ZulipTestCase):# Verify number of queries for Realm admin isn't much higher than for normal users.self.login("iago")with (- self.assert_database_query_count(59),+ self.assert_database_query_count(58),patch("zerver.lib.cache.cache_set") as cache_mock,):result = self._get_home_page()@@ -673,7 +673,7 @@ class HomeTest(ZulipTestCase):self._get_home_page()# Then for the second page load, measure the number of queries.- with self.assert_database_query_count(54):+ with self.assert_database_query_count(53):result = self._get_home_page()# Do a sanity check that our new streams were in the payload.diff --git a/zerver/tests/test_message_dict.py b/zerver/tests/test_message_dict.pyindex 57d285dc087..1c174ff11fb 100644--- a/zerver/tests/test_message_dict.py+++ b/zerver/tests/test_message_dict.py@@ -373,7 +373,7 @@ class MessageHydrationTest(ZulipTestCase):]obj = dict(- recipient_type=Recipient.PERSONAL,+ recipient_type=Recipient.DIRECT_MESSAGE_GROUP,recipient_type_id=None,sender_is_mirror_dummy=False,sender_email=cordelia.email,diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex 74aafcd9c05..15668016342 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -375,12 +375,11 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_dm_operator_and_not_the_same_user_as_operand_with_no_direct_message_group(self,) -> None:- # During migration (PREFER_DIRECT_MESSAGE_GROUP=True), even without a DM group,- # we query PERSONAL recipients since messages might exist with them+ # Without a DM group, no messages are possibleterm = NarrowParameter(operator="dm", operand=self.othello_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)",+ "WHERE false",)def test_add_term_using_dm_operator_and_not_the_same_user_as_operand(self) -> None:@@ -392,10 +391,10 @@ class NarrowBuilderTest(ZulipTestCase):])term = NarrowParameter(operator="dm", operand=self.othello_email)- # During migration, query includes both PERSONAL and DM group recipients+ # Query uses DM group recipientself._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s)",+ "WHERE recipient_id = %(recipient_id_1)s",)def test_negated_is_dm_with_dm_operator(self) -> None:@@ -444,11 +443,11 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_dm_operator_not_the_same_user_as_operand_no_direct_message_group_and_negated(self,) -> None: # NEGATED- # During migration, query PERSONAL recipients (negated)+ # Without a DM group, negated false() becomes trueterm = NarrowParameter(operator="dm", operand=self.othello_email, negated=True)self._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s))",+ "WHERE true",)def test_add_term_using_dm_operator_not_the_same_user_as_operand_and_negated(@@ -462,20 +461,20 @@ class NarrowBuilderTest(ZulipTestCase):])term = NarrowParameter(operator="dm", operand=self.othello_email, negated=True)- # During migration, query includes both PERSONAL and DM group recipients (negated)+ # Query uses DM group recipient (negated)self._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s))",+ "WHERE recipient_id != %(recipient_id_1)s",)def test_add_term_using_dm_operator_the_same_user_as_operand_no_direct_message_group(self,) -> None:- # During migration, query PERSONAL recipients for self-DM+ # Without a DM group, no messages are possibleterm = NarrowParameter(operator="dm", operand=self.hamlet_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s",+ "WHERE false",)def test_add_term_using_dm_operator_the_same_user_as_operand(self) -> None:@@ -486,20 +485,20 @@ class NarrowBuilderTest(ZulipTestCase):])term = NarrowParameter(operator="dm", operand=self.hamlet_email)- # During migration, query includes both PERSONAL and DM group recipients for self-DM+ # Query uses DM group recipient for self-DMself._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s)",+ "WHERE recipient_id = %(recipient_id_1)s",)def test_add_term_using_dm_operator_the_same_user_as_operand_no_direct_message_group_and_negated(self,) -> None: # NEGATED- # During migration, query PERSONAL recipients for self-DM (negated)+ # Without a DM group, negated false() becomes trueterm = NarrowParameter(operator="dm", operand=self.hamlet_email, negated=True)self._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s)",+ "WHERE true",)def test_add_term_using_dm_operator_the_same_user_as_operand_and_negated(@@ -512,10 +511,10 @@ class NarrowBuilderTest(ZulipTestCase):])term = NarrowParameter(operator="dm", operand=self.hamlet_email, negated=True)- # During migration, query includes both PERSONAL and DM group recipients (negated)+ # Query uses DM group recipient (negated)self._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s))",+ "WHERE recipient_id != %(recipient_id_1)s",)def test_add_term_using_dm_operator_and_self_and_user_as_operand_no_direct_message_group(@@ -525,10 +524,10 @@ class NarrowBuilderTest(ZulipTestCase):f"{self.example_user('hamlet').email},{self.example_user('othello').email}")term = NarrowParameter(operator="dm", operand=myself_and_other)- # Even with PREFER=True, if no DM group exists, query old personal messages+ # Without a DM group, no messages are possibleself._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)",+ "WHERE false",)def test_add_term_using_dm_operator_and_self_and_user_as_operand(self) -> None:@@ -543,10 +542,10 @@ class NarrowBuilderTest(ZulipTestCase):f"{self.example_user('hamlet').email},{self.example_user('othello').email}")term = NarrowParameter(operator="dm", operand=myself_and_other)- # During migration, query includes both PERSONAL and DM group recipients+ # Query uses DM group recipientself._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s)",+ "WHERE recipient_id = %(recipient_id_1)s",)def test_add_term_using_dm_operator_more_than_one_user_as_operand_no_direct_message_group(@@ -581,10 +580,10 @@ class NarrowBuilderTest(ZulipTestCase):f"{self.example_user('hamlet').email},{self.example_user('othello').email}")term = NarrowParameter(operator="dm", operand=myself_and_other, negated=True)- # Even with PREFER=True, if no DM group exists, query old personal messages (negated)+ # Without a DM group, negated false() becomes trueself._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s))",+ "WHERE true",)def test_add_term_using_dm_operator_self_and_user_as_operand_and_negated(@@ -601,10 +600,10 @@ class NarrowBuilderTest(ZulipTestCase):f"{self.example_user('hamlet').email},{self.example_user('othello').email}")term = NarrowParameter(operator="dm", operand=myself_and_other, negated=True)- # During migration, query includes both PERSONAL and DM group recipients (negated)+ # Query uses DM group recipient (negated)self._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id = %(recipient_id_3)s))",+ "WHERE recipient_id != %(recipient_id_1)s",)def test_add_term_using_dm_operator_more_than_one_user_as_operand_no_direct_message_group_and_negated(@@ -651,7 +650,7 @@ class NarrowBuilderTest(ZulipTestCase):self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s")def test_add_term_using_dm_including_operator_with_different_user_email(self) -> None:- # Dropping the personal recipient for Othello+ # Simulate a user with recipient=Noneothello = self.example_user("othello")othello.recipient = Noneothello.save()@@ -677,7 +676,7 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_dm_including_operator_with_different_user_email_and_negated(self,) -> None: # NEGATED- # Dropping the personal recipient for Othello+ # Simulate a user with recipient=Noneothello = self.example_user("othello")othello.recipient = Noneothello.save()@@ -833,11 +832,10 @@ class NarrowBuilderTest(ZulipTestCase):# Test that "pm-with" (legacy alias for "dm") works.def test_add_term_using_pm_with_operator_no_direct_message_group(self) -> None:- # During migration, query PERSONAL recipients for self-DM even without DM groupterm = NarrowParameter(operator="pm-with", operand=self.hamlet_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s",+ "WHERE false",)# Test that "pm-with" (legacy alias for "dm") works.@@ -845,10 +843,10 @@ class NarrowBuilderTest(ZulipTestCase):# Create a direct message group with the userget_or_create_direct_message_group([self.user_profile.id])term = NarrowParameter(operator="pm-with", operand=self.hamlet_email)- # During migration, query includes both PERSONAL and DM group recipients for self-DM+ # Query uses DM group recipient for self-DMself._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s)",+ "WHERE recipient_id = %(recipient_id_1)s",)# Test that the underscore version of "pm-with" works.@@ -856,10 +854,10 @@ class NarrowBuilderTest(ZulipTestCase):# Create a direct message group with the userget_or_create_direct_message_group([self.user_profile.id])term = NarrowParameter(operator="pm_with", operand=self.hamlet_email)- # During migration, query includes both PERSONAL and DM group recipients for self-DM+ # Query uses DM group recipient for self-DMself._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND sender_id = %(sender_id_1)s AND (recipient_id = %(recipient_id_1)s OR recipient_id = %(recipient_id_2)s)",+ "WHERE recipient_id = %(recipient_id_1)s",)# Test that deprecated "group-pm-with" (replaced by "dm-including" ) works.@@ -2195,10 +2193,6 @@ class GetOldMessagesTest(ZulipTestCase):query_ids["hamlet_and_othello_recipient"] = self.get_dm_group_recipient(hamlet_user, othello_user).id- assert hamlet_user.recipient is not None- query_ids["hamlet_personal_recipient"] = hamlet_user.recipient.id- assert othello_user.recipient is not None- query_ids["othello_personal_recipient"] = othello_user.recipient.idrecipients = (get_public_streams_queryset(hamlet_user.realm).values_list("recipient_id", flat=True)@@ -5271,7 +5265,7 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)def test_get_messages_with_narrow_queries(self) -> None:- # During migration, the query includes both PERSONAL and DM group recipients+ # The query includes both PERSONAL and DM group recipientsquery_ids = self.get_query_ids()hamlet_email = self.example_user("hamlet").emailothello_email = self.example_user("othello").email@@ -5284,7 +5278,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_and_othello_recipient} AND message_id = 0) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5305,7 +5299,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_and_othello_recipient} AND message_id = 0) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5326,7 +5320,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND (sender_id = {othello_id} AND recipient_id = {hamlet_personal_recipient} OR sender_id = {hamlet_id} AND recipient_id = {othello_personal_recipient} OR recipient_id = {hamlet_and_othello_recipient}) ORDER BY message_id ASC \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_and_othello_recipient} ORDER BY message_id ASC \n\LIMIT 10) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)@@ -5469,7 +5463,7 @@ WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (FROM zerver_stream \n\WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2048) != 0 AND realm_id = {realm_id} AND sender_id = {hamlet_id} AND (recipient_id = {hamlet_personal_recipient} OR recipient_id = {hamlet_recipient}) ORDER BY message_id ASC \n\+WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_recipient} ORDER BY message_id ASC \n\LIMIT 10) AS anon_1 ORDER BY message_id ASC\"""sql = sql_template.format(**query_ids)diff --git a/zerver/tests/test_message_notification_emails.py b/zerver/tests/test_message_notification_emails.pyindex ecaab5172bf..7bf34c3cc22 100644--- a/zerver/tests/test_message_notification_emails.py+++ b/zerver/tests/test_message_notification_emails.py@@ -1980,16 +1980,16 @@ class TestMessageNotificationEmails(ZulipTestCase):message_id = self.send_personal_message(aaron, hamlet)recipient_id = Message.objects.get(id=message_id).recipient_idsynthetic_root_message_id = prepare_synthetic_root_message_id(- Recipient.PERSONAL, recipient_id, dm_sender_id=aaron.id+ Recipient.DIRECT_MESSAGE_GROUP, recipient_id)- self.assertEqual(synthetic_root_message_id, f"<{recipient_id}.{aaron.id}@testserver>")+ self.assertEqual(synthetic_root_message_id, f"<{recipient_id}@testserver>")message_id = self.send_personal_message(cordelia, hamlet)recipient_id = Message.objects.get(id=message_id).recipient_idsynthetic_root_message_id = prepare_synthetic_root_message_id(- Recipient.PERSONAL, recipient_id, dm_sender_id=cordelia.id+ Recipient.DIRECT_MESSAGE_GROUP, recipient_id)- self.assertEqual(synthetic_root_message_id, f"<{recipient_id}.{cordelia.id}@testserver>")+ self.assertEqual(synthetic_root_message_id, f"<{recipient_id}@testserver>")# Verify different `synthetic_root_message_id` for different group-DM to hamlet.message_id = self.send_group_direct_message(aaron, [hamlet, cordelia], "Group DM!")diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.pyindex 1854207863a..2ea47b57480 100644--- a/zerver/tests/test_message_send.py+++ b/zerver/tests/test_message_send.py@@ -2798,14 +2798,14 @@ class PersonalMessageSendTest(ZulipTestCase):self.assertEqual(message.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)self.assertEqual(message.recipient_id, direct_message_group.recipient_id)- def test_personal_when_personal_recipient_is_none(self) -> None:+ def test_1_to_1_dm_without_existing_dm_group(self) -> None:"""- If you send a personal using direct_message_group, only you and the recipient see it.+ Sending a 1:1 DM creates a DirectMessageGroup if one doesn't exist."""sender = self.example_user("hamlet")receiver = self.example_user("othello")- # Removing the personal recipient to ensure a new direct message group is created.+ # Remove the existing DM group to test the creation path.receiver.recipient = Nonereceiver.save()diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.pyindex c0101d9cf89..5163d03a6fa 100644--- a/zerver/tests/test_push_notifications.py+++ b/zerver/tests/test_push_notifications.py@@ -1887,12 +1887,13 @@ class TestGetGCMPayload(PushNotificationTestCase):self._test_get_message_payload_gcm_stream_message(empty_string_topic=True)def test_get_message_payload_gcm_direct_message(self) -> None:+ hamlet = self.example_user("hamlet")+ dm_group = get_or_create_direct_message_group([hamlet.id, self.dm_recipient_user.id])message = self.get_message(- Recipient.PERSONAL,- type_id=self.personal_recipient_user.id,- realm_id=self.personal_recipient_user.realm_id,+ Recipient.DIRECT_MESSAGE_GROUP,+ type_id=dm_group.id,+ realm_id=self.dm_recipient_user.realm_id,)- hamlet = self.example_user("hamlet")payload, gcm_options = self._get_message_payload_gcm(hamlet, message)self.assertDictEqual(payload,