From 070f028599d844a27da05af7d29a0a5391234b1f Mon Sep 17 00:00:00 2001 From: Hocuri <18012815+Hocuri@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:43:43 +0100 Subject: [PATCH 1/2] fix: Download post-messages only from one transport Before this PR, post-messages were downloaded from all transports concurrently, wasting network traffic. The problem was that all transports queried the `downloads` table at roughly the same time, then downloaded the message at the same time, then removed the row from the `downloads` table at roughly the same time. This PR fixes this by locking the mutex before querying the `downloads` table. Also, I added a `_fetch_msgs_lock_guard` param to functions that need this mutex guard to be held, because I was losing track of which functions require it to be held. --- A problem somewhat unrelated to this PR: If one or multiple messages take a very long time to download, then no small messages can be downloaded inbetween. A straightforward solution that would somewhat help is fetching once after downloading, then going idle when no more messages need to be downloaded: ```rust loop { fetch_delete(...).await; download_known_post_messages_without_pre_message(...); if !download_msgs(...) { break; } } idle() ``` A more complete but more complex solution would be to split `fetch_msgs_mutex` into two mutexes, and allow small messages to be fetched&processed while post-messages are fetched, but I'm not sure if we'll be able to implement this in a bug-free way. Do you think I should implement either of this? --- .../tests/test_multitransport.py | 47 +++++++++++++++++++ src/download.rs | 46 ++++++++++++++---- src/imap.rs | 11 ++++- 3 files changed, 95 insertions(+), 9 deletions(-) diff --git a/deltachat-rpc-client/tests/test_multitransport.py b/deltachat-rpc-client/tests/test_multitransport.py index 2c2497f441..b62904fd3f 100644 --- a/deltachat-rpc-client/tests/test_multitransport.py +++ b/deltachat-rpc-client/tests/test_multitransport.py @@ -1,4 +1,5 @@ import os +import re import time import urllib.parse @@ -382,6 +383,52 @@ def test_background_fetch_no_duplicates(acf, direct_imap, dc): assert len(messages_with_text(alice_chat, "hello")) == 1 +def test_post_msg_downloaded_once(acf, direct_imap, tmp_path): + """A post-message that is available on multiple relays + must be downloaded only once.""" + # Min. UI setting as of v2.35 + download_limit = 163840 + alice, _alice_chat, bob_chat = alice_with_two_transports_and_bob(acf) + alice.set_config("download_limit", str(download_limit)) + imaps = [direct_imap(alice, transport["addr"], transport["password"]) for transport in alice.list_transports()] + assert len(imaps) == 2 + + alice.stop_io() + path = tmp_path / "large" + path.write_bytes(os.urandom(download_limit + 1)) + bob_chat.send_file(str(path)) + + # Wait for the pre- and post-message on both relays + for imap in imaps: + while len(imap.get_all_messages()) < 2: + time.sleep(0.1) + + alice.start_io() + msg = alice.wait_for_incoming_msg() + assert msg.get_snapshot().download_state == DownloadState.AVAILABLE + alice._rpc.download_full_message(alice.id, msg.id) + + # Wait until both transports are idle, + # then check that the message was downloaded only from one transport: + + idle_transports = set() + downloaded = False + downloads = 0 + + while len(idle_transports) < 2: + event = alice.wait_for_event() + + if event.kind == EventType.MSGS_CHANGED and event.msg_id == msg.id: + downloaded = msg.get_snapshot().download_state == DownloadState.DONE + elif event.kind == EventType.INFO: + if re.search(r"Downloading message \S+ fully", event.msg): + downloads += 1 + elif downloaded and (m := re.search(r"Transport (\d+): IDLE entering wait-on-remote state", event.msg)): + idle_transports.add(m[1]) + + assert downloads == 1 + + def test_multitransport_mdn(acf): """Test sending an MDN right after configuring two transports.""" alice, bob = acf.get_online_accounts(2) diff --git a/src/download.rs b/src/download.rs index e154fbaaa9..b4caaad8a7 100644 --- a/src/download.rs +++ b/src/download.rs @@ -5,6 +5,7 @@ use std::collections::BTreeMap; use anyhow::{Result, anyhow, bail, ensure}; use deltachat_derive::{FromSql, ToSql}; use serde::{Deserialize, Serialize}; +use tokio::sync::MutexGuard; use crate::context::Context; use crate::imap::session::Session; @@ -136,6 +137,7 @@ pub(crate) async fn download_msg( context: &Context, rfc724_mid: String, session: &mut Session, + _fetch_msgs_lock_guard: &MutexGuard<'_, ()>, ) -> Result> { let transport_id = session.transport_id(); let row = context @@ -160,7 +162,13 @@ pub(crate) async fn download_msg( return Ok(None); }; session - .fetch_single_msg(context, &server_folder, server_uid, rfc724_mid) + .fetch_single_msg( + context, + &server_folder, + server_uid, + rfc724_mid, + _fetch_msgs_lock_guard, + ) .await?; if ephemeral::should_delete_all_downloaded_messages(context).await? { @@ -185,6 +193,7 @@ impl Session { folder: &str, uid: u32, rfc724_mid: String, + _fetch_msgs_lock_guard: &MutexGuard<'_, ()>, ) -> Result<()> { if uid == 0 { bail!("Attempt to fetch UID 0"); @@ -199,11 +208,15 @@ impl Session { let mut uid_message_ids: BTreeMap = BTreeMap::new(); uid_message_ids.insert(uid, rfc724_mid); let (sender, receiver) = async_channel::unbounded(); - { - let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; - Box::pin(self.fetch_many_msgs(context, folder, vec![uid], &uid_message_ids, sender)) - .await?; - } + Box::pin(self.fetch_many_msgs( + context, + folder, + vec![uid], + &uid_message_ids, + sender, + _fetch_msgs_lock_guard, + )) + .await?; if receiver.recv().await.is_err() { bail!("Failed to fetch UID {uid}"); } @@ -266,6 +279,9 @@ pub(crate) async fn msg_is_downloaded_for(context: &Context, rfc724_mid: &str) - } pub(crate) async fn download_msgs(context: &Context, session: &mut Session) -> Result<()> { + // Lock the mutex before querying the `download` table to prevent + // multiple transports from downloading the same message at the same time: + let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; let rfc724_mids = context .sql .query_map_vec("SELECT rfc724_mid FROM download", (), |row| { @@ -275,7 +291,14 @@ pub(crate) async fn download_msgs(context: &Context, session: &mut Session) -> R .await?; for rfc724_mid in &rfc724_mids { - match download_msg(context, rfc724_mid.clone(), session).await { + match download_msg( + context, + rfc724_mid.clone(), + session, + &_fetch_msgs_lock_guard, + ) + .await + { Ok(Some(())) => { delete_from_downloads(context, rfc724_mid).await?; delete_from_available_post_msgs(context, rfc724_mid).await?; @@ -321,6 +344,7 @@ pub(crate) async fn download_known_post_messages_without_pre_message( context: &Context, session: &mut Session, ) -> Result<()> { + let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; let rfc724_mids = context .sql .query_map_vec("SELECT rfc724_mid FROM available_post_msgs", (), |row| { @@ -338,7 +362,13 @@ pub(crate) async fn download_known_post_messages_without_pre_message( // because the Pre-Message got lost. // The message may be in the wrong order, // but at least we have it at all. - let res = download_msg(context, rfc724_mid.clone(), session).await; + let res = download_msg( + context, + rfc724_mid.clone(), + session, + &_fetch_msgs_lock_guard, + ) + .await; if let Ok(Some(())) = res { delete_from_available_post_msgs(context, rfc724_mid).await?; } diff --git a/src/imap.rs b/src/imap.rs index 6669ffbfbf..8f46dcd707 100644 --- a/src/imap.rs +++ b/src/imap.rs @@ -18,6 +18,7 @@ use async_channel::{self, Receiver, Sender}; use async_imap::types::{Fetch, Flag, UnsolicitedResponse}; use futures::TryStreamExt as _; use ratelimit::Ratelimit; +use tokio::sync::MutexGuard; use tokio_util::sync::CancellationToken; use url::Url; @@ -706,7 +707,14 @@ impl Imap { let actually_download_messages_future = async { session - .fetch_many_msgs(context, folder, uids_fetch, &uid_message_ids, sender) + .fetch_many_msgs( + context, + folder, + uids_fetch, + &uid_message_ids, + sender, + &_fetch_msgs_lock_guard, + ) .await .context("fetch_many_msgs") }; @@ -1016,6 +1024,7 @@ impl Session { request_uids: Vec, uid_message_ids: &BTreeMap, received_msgs_channel: Sender<(u32, Option)>, + _fetch_msgs_lock_guard: &MutexGuard<'_, ()>, ) -> Result<()> { if request_uids.is_empty() { return Ok(()); From 5c2ae2a886f202c8f82db674b1fe38289a9d585d Mon Sep 17 00:00:00 2001 From: Hocuri <18012815+Hocuri@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:09:17 +0100 Subject: [PATCH 2/2] Lock the mutex for each message individually --- src/download.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/download.rs b/src/download.rs index b4caaad8a7..5a07b9758c 100644 --- a/src/download.rs +++ b/src/download.rs @@ -279,9 +279,6 @@ pub(crate) async fn msg_is_downloaded_for(context: &Context, rfc724_mid: &str) - } pub(crate) async fn download_msgs(context: &Context, session: &mut Session) -> Result<()> { - // Lock the mutex before querying the `download` table to prevent - // multiple transports from downloading the same message at the same time: - let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; let rfc724_mids = context .sql .query_map_vec("SELECT rfc724_mid FROM download", (), |row| { @@ -291,6 +288,20 @@ pub(crate) async fn download_msgs(context: &Context, session: &mut Session) -> R .await?; for rfc724_mid in &rfc724_mids { + let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; + + if !context + .sql + .exists( + "SELECT COUNT(*) FROM download WHERE rfc724_mid=?", + (rfc724_mid,), + ) + .await? + { + // Another transport has downloaded the message in the meantime + continue; + } + match download_msg( context, rfc724_mid.clone(), @@ -344,7 +355,6 @@ pub(crate) async fn download_known_post_messages_without_pre_message( context: &Context, session: &mut Session, ) -> Result<()> { - let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; let rfc724_mids = context .sql .query_map_vec("SELECT rfc724_mid FROM available_post_msgs", (), |row| { @@ -353,6 +363,11 @@ pub(crate) async fn download_known_post_messages_without_pre_message( }) .await?; for rfc724_mid in &rfc724_mids { + let _fetch_msgs_lock_guard = context.fetch_msgs_mutex.lock().await; + if !available_post_msgs_contains_rfc724_mid(context, rfc724_mid).await? { + // Another transport has downloaded the message in the meantime + continue; + } if msg_is_downloaded_for(context, rfc724_mid).await? { delete_from_available_post_msgs(context, rfc724_mid).await?; continue;