Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
narrow: Bound date-anchor lookups on the driving usermessage index.
Aman Agrawalcf0b97239731
diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.pyindex 2b289039549..5159dafd035 100644--- a/zerver/lib/narrow.py+++ b/zerver/lib/narrow.py@@ -1146,18 +1146,31 @@ def find_date_anchor(*,anchor_date: datetime,query: QuerySet[Message],+ realm_id: int,+ id_field: str,) -> int | None:- first_after = (- query.filter(date_sent__gte=anchor_date)+ """Finds the message to anchor on for a date, translating it into a+ message ID so that the narrow search runs on the ID indexes.+ """+ boundary_id = (+ Message.objects.filter(realm_id=realm_id, date_sent__gte=anchor_date).order_by("date_sent", "id").values_list("id", flat=True).first())- if first_after is not None:- return first_after++ if boundary_id is not None:+ first_after = (+ query.filter(**{f"{id_field}__gte": boundary_id})+ .order_by(id_field)+ .values_list("id", flat=True)+ .first()+ )+ if first_after is not None:+ return first_after# If nothing is on/after the anchor date, fall back to the newest message.- newest = query.order_by("-date_sent", "-id").values_list("id", flat=True).first()+ newest = query.order_by(f"-{id_field}").values_list("id", flat=True).first()return newest@@ -1474,11 +1487,25 @@ def fetch_messages(if client_requested_message_ids is not None:query = query.filter(id__in=client_requested_message_ids)else:+ if need_user_message:+ # Order/bound the anchor search and pagination on the driving+ # zerver_usermessage (user_profile_id, message_id) index. PostgreSQL+ # won't push a zerver_message.id bound across the outer join, so+ # using it would scan the user's whole history to reach an old+ # anchor. The alias reuses the existing join rather than adding a+ # second one.+ query = query.alias(_range_message_id=F("usermessage__message_id"))+ id_field = "_range_message_id"+ else:+ id_field = "id"+if anchor_type == "date":assert isinstance(anchor_value, datetime)anchor_value = find_date_anchor(anchor_date=anchor_value,query=query,+ realm_id=realm.id,+ id_field=id_field,)# We did not find any message before or after the given timestamp,# which means there are no messages in this narrow.@@ -1516,17 +1543,6 @@ def fetch_messages(if anchored_to_right:num_after = 0- if need_user_message:- # Order/bound pagination on the driving zerver_usermessage- # (user_profile_id, message_id) index. PostgreSQL won't push a- # zerver_message.id bound across the outer join, so using it would- # scan the user's whole history to reach an old anchor. The alias- # reuses the existing join rather than adding a second one.- query = query.alias(_range_message_id=F("usermessage__message_id"))- id_field = "_range_message_id"- else:- id_field = "id"-query = limit_query_to_range(query=query,num_before=num_before,diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex 0045713d492..bbfaeb5d568 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -4716,7 +4716,7 @@ class GetOldMessagesTest(ZulipTestCase):"narrow": "[]",}- with self.assert_database_query_count(12):+ with self.assert_database_query_count(13):result = self.get_and_check_messages(get_and_check_messages_options)self.assertEqual(result["anchor"], anchor_message_id)@@ -4728,7 +4728,7 @@ class GetOldMessagesTest(ZulipTestCase):# we should choose the message sent first.first_message_with_same_timestamp_id = anchor_message_idMessage.objects.filter(id=newer_message_id).update(date_sent=base_time)- with self.assert_database_query_count(12):+ with self.assert_database_query_count(13):result = self.get_and_check_messages(get_and_check_messages_options)self.assertEqual(result["anchor"], first_message_with_same_timestamp_id)self.assert_length(result["messages"], 1)@@ -4752,7 +4752,7 @@ class GetOldMessagesTest(ZulipTestCase):# Narrow conditions should be respected when passing `anchor_date`.scotland_channel_message_id = self.send_stream_message(sender, "Scotland")Message.objects.filter(id=scotland_channel_message_id).update(date_sent=base_time)- with self.assert_database_query_count(16):+ with self.assert_database_query_count(17):result = self.get_and_check_messages({**get_and_check_messages_options,@@ -4764,6 +4764,21 @@ class GetOldMessagesTest(ZulipTestCase):self.assertEqual(result["messages"][0]["id"], scotland_channel_message_id)self.assertTrue(result["found_anchor"])+ # The anchor search must be ordered and bounded on+ # zerver_usermessage.message_id; ordering it by date_sent scans a+ # large fraction of zerver_message. See find_date_anchor.+ with queries_captured() as queries:+ self.get_and_check_messages(get_and_check_messages_options)+ anchor_sqls = [+ query.sql+ for query in queries+ if query.sql.endswith("LIMIT 1") and "zerver_usermessage" in query.sql+ ]+ self.assert_length(anchor_sqls, 1)+ self.assertIn('ORDER BY "zerver_usermessage"."message_id" ASC', anchor_sqls[0])+ self.assertIn('AND "zerver_usermessage"."message_id" >= ', anchor_sqls[0])+ self.assertNotIn("date_sent", anchor_sqls[0])+# If the narrow has no matching messages, we should return an empty result.empty_stream = "Empty stream"self.subscribe(hamlet, empty_stream)