From aff6b2ad14195074e7ad7c95804f6c3f12f0d1a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lucas?= Date: Mon, 15 Jun 2026 09:44:11 -0300 Subject: [PATCH] fix(retry): bound outbound resend rate per group to prevent AccountLocked A bot running this lib hit a 403 AccountLocked. Root cause from production logs: a sustained high rate of outbound retry resends to a single group. During a mass PN->LID migration, hundreds of distinct devices each fail to decrypt the same messages and each send a retry, and we pairwise-resend to every one. The penalized signal is the aggregate per-chat resend rate, not any single device's depth, so MAX_RETRY_COUNT (which trusts the peer-echoed count, stuck at 1) never fires and a per-(chat,msg,requester) cap cuts under 0.5% of the storm. Add a per-group token-bucket rate limiter on the resends we perform, keyed by chat so it bounds the aggregate rate regardless of how many devices drive it. It drops rather than queues when over budget: the requester was already marked for fresh SKDM, so it recovers on the next send and re-requests on its own timer. Refill is lazy off the monotonic clock (no timers, correct over long sessions), the bucket cache is capacity-only (bounded memory), and the same-chat read-modify-write is race-free via single-flight get_with plus a per-bucket mutex. Group-only because DMs have no SKDM fallback. Defaults are conservative (burst 20, refill 10/min) and tunable live via Client::set_resend_rate_limit and BotBuilder::with_resend_rate_limit; resends_throttled_total surfaces storm chats. Builds on the investigation in #870. --- src/bot.rs | 23 +++ src/cache_config.rs | 11 ++ src/client.rs | 18 +++ src/client/accessors.rs | 22 +++ src/client/lifecycle.rs | 6 + src/lib.rs | 1 + src/resend_rate_limiter.rs | 277 +++++++++++++++++++++++++++++++++++++ src/retry.rs | 134 ++++++++++++++++++ 8 files changed, 492 insertions(+) create mode 100644 src/resend_rate_limiter.rs diff --git a/src/bot.rs b/src/bot.rs index 09363c65c..c03fada6e 100644 --- a/src/bot.rs +++ b/src/bot.rs @@ -492,6 +492,7 @@ pub struct BotBuilder< initial_push_name: Option, cache_config: CacheConfig, wanted_pre_key_count: Option, + resend_rate_limit: Option<(u32, u32)>, _marker: PhantomData<(B, T, H, R)>, } @@ -512,6 +513,7 @@ impl BotBuilder BotBuilder { initial_push_name: self.initial_push_name, cache_config: self.cache_config, wanted_pre_key_count: self.wanted_pre_key_count, + resend_rate_limit: self.resend_rate_limit, _marker: PhantomData, } } @@ -834,6 +837,22 @@ impl BotBuilder { self } + /// Tune the per-chat outbound resend rate limiter. + /// + /// Outbound retry resends to a chat are bounded by a token bucket: `burst` + /// is the instantaneous allowance, `refill_per_min` the sustained ceiling + /// per chat. This caps the aggregate resend rate WhatsApp's anti-abuse + /// penalizes during a PN to LID migration fan-out, while throttled devices + /// still recover via the fresh-SKDM mark. A `burst` of 0 disables it. + /// + /// Defaults are conservative (burst 20, refill 10/min) and apply without + /// calling this. Can also be retuned live via + /// [`Client::set_resend_rate_limit`](crate::Client::set_resend_rate_limit). + pub fn with_resend_rate_limit(mut self, burst: u32, refill_per_min: u32) -> Self { + self.resend_rate_limit = Some((burst, refill_per_min)); + self + } + /// Set an initial push name on the device before connecting. /// /// This is included in the `ClientPayload` during registration, allowing the @@ -955,6 +974,10 @@ impl BotBuilder { client.set_wanted_pre_key_count(count); } + if let Some((burst, refill_per_min)) = self.resend_rate_limit { + client.set_resend_rate_limit(burst, refill_per_min); + } + Ok(Bot { client, sync_task_receiver: Some(sync_task_receiver), diff --git a/src/cache_config.rs b/src/cache_config.rs index ccd8034bc..6a73f94a6 100644 --- a/src/cache_config.rs +++ b/src/cache_config.rs @@ -201,6 +201,12 @@ pub struct CacheConfig { pub session_locks_capacity: u64, /// Per-chat lane capacity (combined lock + queue). Default: 5000. pub chat_lanes_capacity: u64, + /// Per-chat resend rate-limiter capacity: one token-bucket entry per group + /// recently driving retry resends. Keep above the count of concurrently + /// storming groups: eviction is FIFO and fail-open (an evicted bucket is + /// recreated full), so undersizing only forgives rate, never over-throttles. + /// Default: 4096. + pub resend_rate_limiter_capacity: u64, // --- Sent message DB cleanup --- /// TTL in seconds for sent messages in DB before periodic cleanup. Must @@ -273,6 +279,10 @@ impl std::fmt::Debug for CacheConfig { .field("session_recreate_history", &self.session_recreate_history) .field("session_locks_capacity", &self.session_locks_capacity) .field("chat_lanes_capacity", &self.chat_lanes_capacity) + .field( + "resend_rate_limiter_capacity", + &self.resend_rate_limiter_capacity, + ) .field("sent_message_ttl_secs", &self.sent_message_ttl_secs) .field("msg_secret_policy", &self.msg_secret_policy) .field("msg_secret_retention", &self.msg_secret_retention) @@ -329,6 +339,7 @@ impl Default for CacheConfig { // breaking serialization. Size generously to avoid eviction pressure. session_locks_capacity: 10_000, chat_lanes_capacity: 5_000, + resend_rate_limiter_capacity: 4_096, sent_message_ttl_secs: 7200, // Bounded by default: seed only the still-relevant slice of history // and prune by per-add-on-kind event-time horizons, so the store no diff --git a/src/client.rs b/src/client.rs index 21d06ac38..74b1d0559 100644 --- a/src/client.rs +++ b/src/client.rs @@ -194,6 +194,9 @@ pub struct MemoryDiagnostics { // -- Capacity-only caches (no TTL) -- pub session_locks: u64, pub chat_lanes: u64, + pub resend_rate_limiter_chats: u64, + /// Total outbound resends dropped by the per-chat rate limiter since start. + pub resends_throttled_total: u64, // -- Unbounded collections -- pub response_waiters: usize, pub node_waiters: usize, @@ -239,6 +242,16 @@ impl std::fmt::Display for MemoryDiagnostics { writeln!(f, "--- Capacity-only caches ---")?; writeln!(f, " session_locks: {}", self.session_locks)?; writeln!(f, " chat_lanes: {}", self.chat_lanes)?; + writeln!( + f, + " resend_rl_chats: {}", + self.resend_rate_limiter_chats + )?; + writeln!( + f, + " resends_throttled: {}", + self.resends_throttled_total + )?; writeln!(f, "--- Unbounded collections ---")?; writeln!(f, " response_waiters: {}", self.response_waiters)?; writeln!(f, " node_waiters: {}", self.node_waiters)?; @@ -455,6 +468,11 @@ pub struct Client { /// loop us through prekey fetches. pub(crate) session_recreate_history: Cache, + /// Per-chat outbound resend rate limiter: bounds the aggregate resend rate + /// to a chat (the anti-abuse signal) so a PN to LID fan-out cannot storm into + /// AccountLocked. Throttled devices still recover via the fresh-SKDM mark. + pub(crate) resend_rate_limiter: crate::resend_rate_limiter::ResendRateLimiter, + /// Dispatch-once gate for `UndecryptableMessage`: a server resend of a /// failed id re-enters the failure path and would otherwise fire a /// duplicate event. Mirrors WA Web's DB-level placeholder uniqueness diff --git a/src/client/accessors.rs b/src/client/accessors.rs index 10fcca1b6..3a979498f 100644 --- a/src/client/accessors.rs +++ b/src/client/accessors.rs @@ -60,6 +60,26 @@ impl Client { self.wanted_pre_key_count.load(Ordering::Relaxed) } + /// Retune the per-chat outbound resend rate limiter live (no reconnect). + /// + /// Outbound resends to a chat are bounded by a token bucket: `burst` is the + /// instantaneous allowance and `refill_per_min` the sustained ceiling per + /// chat. This caps the aggregate resend rate that WhatsApp's anti-abuse + /// penalizes during a PN to LID migration fan-out, while throttled devices + /// still recover via the fresh-SKDM mark. A `burst` of 0 disables the limiter. + /// + /// Takes effect on each chat's next retry; a lowered `burst` clamps a live + /// bucket on its next access. + pub fn set_resend_rate_limit(&self, burst: u32, refill_per_min: u32) { + self.resend_rate_limiter.set_rate(burst, refill_per_min); + } + + /// Total outbound resends dropped by the per-chat rate limiter since start. + /// Surfaces storm chats without the `debug-diagnostics` feature. + pub fn resends_throttled_total(&self) -> u64 { + self.resend_rate_limiter.throttled_total() + } + /// Returns a snapshot of all internal collection sizes for memory leak detection. /// /// Moka caches report approximate counts (pending evictions may not be reflected). @@ -95,6 +115,8 @@ impl Client { pdo_requested: self.pdo_requested.entry_count(), session_locks: self.session_locks.entry_count(), chat_lanes: self.chat_lanes.entry_count(), + resend_rate_limiter_chats: self.resend_rate_limiter.entry_count(), + resends_throttled_total: self.resend_rate_limiter.throttled_total(), response_waiters: self.response_waiters.lock().await.len(), node_waiters: self.node_waiter_count.load(Ordering::Relaxed), pending_retries: pending_retries_count, diff --git a/src/client/lifecycle.rs b/src/client/lifecycle.rs index 62d973880..d713560cf 100644 --- a/src/client/lifecycle.rs +++ b/src/client/lifecycle.rs @@ -185,6 +185,12 @@ impl Client { session_recreate_history: cache_config.session_recreate_history.build_with_ttl(), + resend_rate_limiter: crate::resend_rate_limiter::ResendRateLimiter::new( + cache_config.resend_rate_limiter_capacity, + crate::resend_rate_limiter::DEFAULT_RESEND_BURST, + crate::resend_rate_limiter::DEFAULT_RESEND_REFILL_PER_MIN, + ), + undecryptable_dispatched: cache_config.undecryptable_dispatched.build_with_ttl(), offline_sync_metrics: Arc::new(OfflineSyncMetrics { diff --git a/src/lib.rs b/src/lib.rs index cc927defd..de34093f1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,6 +27,7 @@ pub use waproto; pub mod cache; pub mod portable_cache; +pub(crate) mod resend_rate_limiter; pub mod cache_config; pub use cache_config::{ diff --git a/src/resend_rate_limiter.rs b/src/resend_rate_limiter.rs new file mode 100644 index 000000000..957afb9ec --- /dev/null +++ b/src/resend_rate_limiter.rs @@ -0,0 +1,277 @@ +//! Per-chat outbound resend rate limiter. +//! +//! WhatsApp's anti-abuse penalizes the aggregate rate of outbound resends to a +//! chat, not any single device's depth. During a mass PN to LID migration, +//! hundreds of distinct devices retry the same messages, so per-device and +//! per-message caps never engage while the aggregate rate climbs into +//! AccountLocked. This bounds it with one token bucket per chat. +//! +//! A throttled resend is dropped, not queued: the requester was already marked +//! for fresh sender-key distribution earlier in the retry path, so it recovers +//! on the next send. Dropping keeps the hot path allocation-free with no timers. +//! Buckets refill lazily off the monotonic [`Instant`] (correct over long +//! sessions, immune to clock jumps); the rate is atomic so it retunes live. + +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +use async_lock::Mutex; +use wacore::time::Instant; +use wacore_binary::jid::Jid; + +use crate::cache::Cache; + +/// Bucket capacity: the burst of resends allowed to one chat before the refill +/// rate gates it. Buckets start full so a chat's first activity is never +/// throttled. +pub(crate) const DEFAULT_RESEND_BURST: u32 = 20; + +/// Tokens replenished per minute per chat, i.e. the sustained resend ceiling. +/// Conservative on purpose: well under the rate observed to trip AccountLocked, +/// yet above any healthy chat's steady resend need. +pub(crate) const DEFAULT_RESEND_REFILL_PER_MIN: u32 = 10; + +struct TokenBucket { + tokens: f64, + last_refill: Instant, +} + +impl TokenBucket { + #[inline] + fn new(initial: f64, now: Instant) -> Self { + Self { + tokens: initial, + last_refill: now, + } + } + + /// Refill for the time since the last access, then try to take one token. + /// Pure given `now`/`burst`/`refill_per_sec` so the rate logic is unit + /// tested without sleeping. `tokens` is clamped to `burst`, so an idle chat + /// cannot accumulate an unbounded reserve and a lowered `burst` takes effect + /// on the next access. + #[inline] + fn try_take(&mut self, now: Instant, burst: f64, refill_per_sec: f64) -> bool { + let elapsed = now + .saturating_duration_since(self.last_refill) + .as_secs_f64(); + self.tokens = (self.tokens + elapsed * refill_per_sec).min(burst); + self.last_refill = now; + if self.tokens >= 1.0 { + self.tokens -= 1.0; + true + } else { + false + } + } +} + +/// Per-chat token-bucket limiter for outbound retry resends. +pub(crate) struct ResendRateLimiter { + /// One bucket per chat. Capacity-only: evicting an idle chat's bucket only + /// forgives rate (it recreates full), never over-restricts. + buckets: Cache>>, + burst: AtomicU32, + refill_per_min: AtomicU32, + throttled_total: AtomicU64, +} + +impl ResendRateLimiter { + pub(crate) fn new(capacity: u64, burst: u32, refill_per_min: u32) -> Self { + Self { + buckets: Cache::builder().max_capacity(capacity.max(1)).build(), + burst: AtomicU32::new(burst), + refill_per_min: AtomicU32::new(refill_per_min), + throttled_total: AtomicU64::new(0), + } + } + + /// Retune the rate live. Takes effect on each chat's next acquire; a lowered + /// `burst` is clamped in on that bucket's next refill. + pub(crate) fn set_rate(&self, burst: u32, refill_per_min: u32) { + self.burst.store(burst, Ordering::Relaxed); + self.refill_per_min.store(refill_per_min, Ordering::Relaxed); + } + + /// Try to consume one resend token for `chat`. `true` allows the resend, + /// `false` drops it. A `burst` of 0 disables the limiter (always allows) and + /// skips all bucket work. + pub(crate) async fn try_acquire(&self, chat: &Jid) -> bool { + let burst = self.burst.load(Ordering::Relaxed); + if burst == 0 { + return true; + } + let burst = burst as f64; + let refill_per_sec = self.refill_per_min.load(Ordering::Relaxed) as f64 / 60.0; + + // Single-flight get-or-create so concurrent receipts for the same chat + // (each dispatched as a detached task) share one bucket; the per-bucket + // mutex then serializes the read-modify-write so the rate cannot be + // bypassed by interleaving. + let bucket = self + .buckets + .get_with_by_ref(chat, async move { + Arc::new(Mutex::new(TokenBucket::new(burst, Instant::now()))) + }) + .await; + + let allowed = bucket + .lock() + .await + .try_take(Instant::now(), burst, refill_per_sec); + if !allowed { + self.throttled_total.fetch_add(1, Ordering::Relaxed); + } + allowed + } + + /// Total resends dropped by the limiter since start (observability). + pub(crate) fn throttled_total(&self) -> u64 { + self.throttled_total.load(Ordering::Relaxed) + } + + /// Number of chats holding a live bucket (diagnostics). + #[cfg_attr(not(feature = "debug-diagnostics"), allow(dead_code))] + pub(crate) fn entry_count(&self) -> u64 { + self.buckets.entry_count() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + fn chat(s: &str) -> Jid { + s.parse().unwrap() + } + + // --- Pure bucket arithmetic (deterministic, no sleeps) --- + + #[test] + fn empty_bucket_refuses_then_refills_over_time() { + let t0 = Instant::now(); + let mut b = TokenBucket::new(0.0, t0); + assert!(!b.try_take(t0, 10.0, 1.0), "empty bucket must refuse"); + + // 1 token/sec for 3s accrues 3 tokens: three takes pass, the fourth fails. + let t3 = t0 + Duration::from_secs(3); + assert!(b.try_take(t3, 10.0, 1.0)); + assert!(b.try_take(t3, 10.0, 1.0)); + assert!(b.try_take(t3, 10.0, 1.0)); + assert!( + !b.try_take(t3, 10.0, 1.0), + "only the accrued tokens are spendable" + ); + } + + #[test] + fn idle_does_not_accumulate_beyond_burst() { + let t0 = Instant::now(); + let mut b = TokenBucket::new(5.0, t0); + for _ in 0..5 { + assert!(b.try_take(t0, 5.0, 1.0)); + } + assert!(!b.try_take(t0, 5.0, 1.0), "bucket drained"); + + // Idle an hour at 1 token/sec would accrue thousands, but the cap is burst. + let t1 = t0 + Duration::from_secs(3600); + let mut allowed = 0; + for _ in 0..100 { + if b.try_take(t1, 5.0, 1.0) { + allowed += 1; + } + } + assert_eq!(allowed, 5, "refill is clamped to burst, not unbounded"); + } + + // --- Async limiter, happy + bad paths (refill 0 makes token count exact) --- + + #[tokio::test] + async fn under_burst_allows_then_over_burst_refuses() { + let limiter = ResendRateLimiter::new(100, 5, 0); + let c = chat("123456789@g.us"); + for _ in 0..5 { + assert!(limiter.try_acquire(&c).await, "within burst must pass"); + } + assert!(!limiter.try_acquire(&c).await, "past burst must drop"); + assert!(!limiter.try_acquire(&c).await); + assert_eq!(limiter.throttled_total(), 2); + } + + #[tokio::test] + async fn disabled_limiter_allows_everything() { + let limiter = ResendRateLimiter::new(100, 0, 10); + let c = chat("123456789@g.us"); + for _ in 0..100 { + assert!(limiter.try_acquire(&c).await); + } + assert_eq!( + limiter.entry_count(), + 0, + "disabled limiter creates no buckets" + ); + assert_eq!(limiter.throttled_total(), 0); + } + + #[tokio::test] + async fn buckets_are_per_chat() { + let limiter = ResendRateLimiter::new(100, 2, 0); + let a = chat("111@g.us"); + let b = chat("222@g.us"); + assert!(limiter.try_acquire(&a).await); + assert!(limiter.try_acquire(&a).await); + assert!(!limiter.try_acquire(&a).await, "a exhausted its own budget"); + assert!(limiter.try_acquire(&b).await, "b has an independent budget"); + assert!(limiter.try_acquire(&b).await); + assert!(!limiter.try_acquire(&b).await); + } + + #[tokio::test] + async fn set_rate_lowers_an_existing_bucket_ceiling() { + let limiter = ResendRateLimiter::new(100, 10, 0); + let c = chat("123@g.us"); + // Create the bucket at burst 10 (one token spent, nine remain). + assert!(limiter.try_acquire(&c).await); + // Lower the ceiling: the nine remaining tokens clamp down to three. + limiter.set_rate(3, 0); + let mut allowed = 0; + for _ in 0..10 { + if limiter.try_acquire(&c).await { + allowed += 1; + } + } + assert_eq!(allowed, 3, "lowered burst clamps the live bucket"); + } + + // --- Concurrency: the rate cannot be bypassed by interleaved receipts --- + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_acquires_for_one_chat_do_not_exceed_burst() { + let limiter = Arc::new(ResendRateLimiter::new(100, 10, 0)); + let c = chat("123456789@g.us"); + let allowed = Arc::new(AtomicU64::new(0)); + + let mut handles = Vec::new(); + for _ in 0..40 { + let limiter = limiter.clone(); + let c = c.clone(); + let allowed = allowed.clone(); + handles.push(tokio::spawn(async move { + if limiter.try_acquire(&c).await { + allowed.fetch_add(1, Ordering::Relaxed); + } + })); + } + for h in handles { + h.await.unwrap(); + } + + assert_eq!( + allowed.load(Ordering::Relaxed), + 10, + "exactly burst resends pass under contention, no bypass" + ); + assert_eq!(limiter.throttled_total(), 30); + } +} diff --git a/src/retry.rs b/src/retry.rs index 7af5a082b..eb727febf 100644 --- a/src/retry.rs +++ b/src/retry.rs @@ -488,6 +488,22 @@ impl Client { return Ok(()); } + // Bound the aggregate resend rate per group (the anti-abuse signal): a + // PN to LID fan-out has many distinct devices retry the same messages, + // which per-device/per-message caps miss. Group-only: the requester was + // marked for fresh SKDM above so future messages recover, and it + // re-requests this one on its own timer once the bucket refills. DMs have + // no SKDM fallback, so they keep the unconditional resend (bounded by + // MAX_RETRY_COUNT) rather than risk dropping a delivery. + if info.chat.is_group() && !self.resend_rate_limiter.try_acquire(&info.chat).await { + debug!( + "Throttling resend of {} to {}: per-chat resend rate cap reached", + message_id, + info.chat.observe() + ); + return Ok(()); + } + info!( "Resending message {} to {} (retry #{})", message_id, @@ -2211,6 +2227,124 @@ mod tests { ); } + /// The resend rate limiter is reachable and tunable through the public + /// `Client` API, and its drops surface on `resends_throttled_total`. Covers + /// the wiring the `handle_retry_receipt` hook relies on; the bucket logic + /// itself is unit-tested in `resend_rate_limiter`. + #[tokio::test] + async fn client_resend_rate_limiter_is_wired_and_tunable() { + let client = + crate::test_utils::create_test_client_with_failing_http("resend_rl_wired").await; + let chat: Jid = "120363021033254949@g.us".parse().unwrap(); + + // Tight ceiling, no refill: the bucket holds exactly `burst` tokens. + client.set_resend_rate_limit(3, 0); + let mut allowed = 0; + for _ in 0..10 { + if client.resend_rate_limiter.try_acquire(&chat).await { + allowed += 1; + } + } + assert_eq!(allowed, 3, "client honors the configured per-chat burst"); + assert_eq!( + client.resends_throttled_total(), + 7, + "public counter tracks dropped resends" + ); + + // Disabling restores unthrottled behavior. + client.set_resend_rate_limit(0, 0); + let other: Jid = "120363000000000001@g.us".parse().unwrap(); + for _ in 0..50 { + assert!(client.resend_rate_limiter.try_acquire(&other).await); + } + } + + /// End-to-end: a throttled group retry drops the resend (returns Ok, sends + /// nothing) while the path up to the limiter still runs, and the cached + /// message is retained for the device's later re-request. Exercises the hook + /// placement and the no-resend-on-refusal semantics the unit tests cannot. + #[tokio::test] + async fn handle_retry_receipt_drops_throttled_group_resend() { + use wacore_binary::builder::NodeBuilder; + + let backend = crate::test_utils::create_test_backend().await; + let pm = Arc::new(PersistenceManager::new(backend).await.unwrap()); + let mut config = crate::cache_config::CacheConfig::default(); + config.recent_messages.capacity = 1_000; + let (client, _rx) = Client::new_with_cache_config( + Arc::new(crate::runtime_impl::TokioRuntime), + pm, + Arc::new(crate::transport::mock::MockTransportFactory::new()), + Arc::new(MockHttpClient), + None, + config, + ) + .await; + + let group: Jid = "120363021033254949@g.us".parse().unwrap(); + let msg_id = "RLMSG001"; + client + .add_recent_message( + &group, + msg_id, + &wa::Message { + conversation: Some("hi".into()), + ..Default::default() + }, + ) + .await; + + // Drain the single token so the incoming retry must be throttled; the + // throttle returns before any network resend, keeping the test offline. + client.set_resend_rate_limit(1, 0); + assert!(client.resend_rate_limiter.try_acquire(&group).await); + + // Inbound group retry from a device-0 LID participant: has_device's + // device-0 fast path makes it known, LID skips rotateKey, and no + // leaves update_local_signal_session a noop on a missing session. + let node = NodeBuilder::new("receipt") + .attr("participant", "555000111@lid") + .children([NodeBuilder::new("retry") + .attr("id", msg_id) + .attr("count", "1") + .build()]) + .build(); + let node_ref = crate::test_utils::node_to_owned_ref(&node); + let receipt = Receipt { + source: crate::types::message::MessageSource { + chat: group.clone(), + sender: "555000111@lid".parse().unwrap(), + is_group: true, + ..Default::default() + }, + message_ids: vec![msg_id.to_string()], + timestamp: wacore::time::now_utc(), + r#type: crate::types::presence::ReceiptType::Retry, + offline: false, + }; + + let result = client.handle_retry_receipt(&receipt, &node_ref).await; + assert!( + result.is_ok(), + "a throttled retry returns Ok(()), not an error" + ); + assert_eq!( + client.resends_throttled_total(), + 1, + "the resend was dropped by the limiter" + ); + assert!( + client.peek_recent_message(&group, msg_id).await.is_some(), + "throttling keeps the message cached for the device's re-request" + ); + assert_eq!( + client.pending_retries.lock().unwrap().len(), + 0, + "the in-progress marker is cleared after the throttled return" + ); + } + /// Atomicity guard for the per-peer session lock the retry caller wraps /// around the recreate check+stamp. The cache's get+insert is not atomic, and /// same-peer retries for different message_ids dispatch concurrently, so