Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

message_edit: Invalidate cache for propagated messages on topic edit.

Sairam Bisoyib45341991d57
diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.py
index d0c988c47ea..ff3575caf33 100644
--- a/zerver/actions/message_edit.py
+++ b/zerver/actions/message_edit.py
@@ -1,6 +1,6 @@
import itertools
from collections import defaultdict
-from collections.abc import Iterable
+from collections.abc import Callable, Iterable
from collections.abc import Set as AbstractSet
from dataclasses import dataclass
from datetime import timedelta
@@ -26,6 +26,7 @@ from zerver.actions.message_send import (
from zerver.actions.uploads import AttachmentChangeResult, check_attachment_reference_change
from zerver.actions.user_topics import bulk_do_set_user_topic_visibility_policy
from zerver.lib import utils
+from zerver.lib.cache import cache_delete_many, to_dict_cache_key_id
from zerver.lib.exceptions import (
JsonableError,
MessageMoveError,
@@ -859,9 +860,7 @@ def do_update_message(
changed_messages = Message.objects.filter(id=target_message.id)
changed_message_ids = [target_message.id]
changed_messages_count = 1
- save_changes_for_propagation_mode = lambda: Message.objects.filter(
- id=target_message.id
- ).select_related(*Message.DEFAULT_SELECT_RELATED)
+ save_changes_for_propagation_mode: Callable[[], None] = lambda: None
if message_edit_request.propagate_mode in ["change_later", "change_all"]:
# Other messages should only get topic/stream fields in their edit history.
topic_only_edit_history_event: EditHistoryEvent = {
@@ -947,12 +946,17 @@ def do_update_message(
# This does message.save(update_fields=[...])
save_message_for_edit_use_case(message=target_message)
- # This updates any later messages, if any. It returns the
- # freshly-fetched-from-the-database changed messages.
- changed_messages = save_changes_for_propagation_mode()
-
- realm_id = target_message.realm_id
- event["message_ids"] = sorted(update_message_cache(changed_messages, realm_id))
+ # Execute the bulk UPDATE of topic/stream/edit_history fields
+ # for any propagated messages.
+ save_changes_for_propagation_mode()
+
+ # Invalidate the message cache for all changed messages. They'll
+ # be lazily rebuilt from the database on next access. The DB has
+ # up-to-date content for all of them: the target message was saved
+ # above, and propagated messages were updated by
+ # save_changes_for_propagation_mode().
+ cache_delete_many(to_dict_cache_key_id(msg_id) for msg_id in changed_message_ids)
+ event["message_ids"] = sorted(changed_message_ids)
# The following blocks arranges that users who are subscribed to a
# stream and can see history from before they subscribed get
diff --git a/zerver/lib/topic.py b/zerver/lib/topic.py
index 84c28c2fe65..182bbff83f0 100644
--- a/zerver/lib/topic.py
+++ b/zerver/lib/topic.py
@@ -159,7 +159,7 @@ def update_messages_for_topic_edit(
message_edit_request: StreamMessageEditRequest,
edit_history_event: EditHistoryEvent,
last_edit_time: datetime,
-) -> tuple[QuerySet[Message], Callable[[], QuerySet[Message]]]:
+) -> tuple[QuerySet[Message], Callable[[], None]]:
# Uses index: zerver_message_realm_recipient_upper_subject
old_stream = message_edit_request.orig_stream
messages = Message.objects.filter(
@@ -224,18 +224,8 @@ def update_messages_for_topic_edit(
if message_edit_request.is_topic_edited:
update_fields["subject"] = message_edit_request.target_topic_name
- # The update will cause the 'messages' query to no longer match
- # any rows; we capture the set of matching ids first, do the
- # update, and then return a fresh collection -- so we know their
- # metadata has been updated for the UPDATE command, and the caller
- # can update the remote cache with that.
- message_ids = [edited_message.id, *messages.values_list("id", flat=True)]
-
- def propagate() -> QuerySet[Message]:
+ def propagate() -> None:
messages.update(**update_fields)
- return Message.objects.filter(id__in=message_ids).select_related(
- *Message.DEFAULT_SELECT_RELATED
- )
return messages, propagate
diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.py
index a53ef852ff4..4cf2b8d100d 100644
--- a/zerver/tests/test_message_edit.py
+++ b/zerver/tests/test_message_edit.py
@@ -51,9 +51,11 @@ class EditMessageTest(ZulipTestCase):
"""
We assume our caller just edited a message.
- Next, we will make sure we properly cached the messages. We still have
- to do a query to hydrate recipient info, but we won't need to hit the
- zerver_message table.
+ Next, we will make sure we can fetch the message correctly.
+ Stream message edits invalidate the cache (rather than eagerly
+ rebuilding it), so the first access triggers a lazy rebuild
+ from the database. We verify the rebuild populates the cache
+ by checking that a second fetch needs no message-table query.
"""
with queries_captured(keep_cache_warm=True) as queries:
@@ -69,9 +71,24 @@ class EditMessageTest(ZulipTestCase):
realm=msg.realm,
)
+ # The lazy rebuild should have populated the cache, so a
+ # second fetch only needs a sender-info query, not a
+ # message-table query.
+ with queries_captured(keep_cache_warm=True) as queries:
+ messages_for_ids(
+ message_ids=[msg.id],
+ user_message_flags={msg_id: []},
+ search_fields={},
+ apply_markdown=False,
+ client_gravatar=False,
+ allow_empty_topic_name=True,
+ message_edit_history_visibility_policy=MessageEditHistoryVisibilityPolicyEnum.all.value,
+ user_profile=None,
+ realm=msg.realm,
+ )
+
self.assert_length(queries, 1)
- for query in queries:
- self.assertNotIn("message", query.sql)
+ self.assertNotIn("message", queries[0].sql)
self.assertEqual(
fetch_message_dict[TOPIC_NAME],