Skip to main content

matrix_sdk/event_cache/
back_pagination_queue.rs

1// Copyright 2026 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! A single component that owns one background task and executes
16//! back-pagination requests coming from various components (search,
17//! latest event, read receipt).
18//!
19//! Callers enqueue a [`BackPaginationRequest`] describing which room to
20//! back-paginate, at which priority, and until when and they get a
21//! [`BackPaginationHandle`] to await. Each consumer builds its own requests, in
22//! its own module; this one only schedules and runs them.
23//!
24//! The executor:
25//! - runs at most [`EventCacheConfig::max_concurrent_back_paginations`]
26//!   requests concurrently
27//! - schedules by [`Priority`], higher first, FIFO within a priority
28//! - never runs two requests for the same room concurrently
29//! - deduplicates by room *and* priority: a request for a room already queued
30//!   or running at the same priority is coalesced onto that run, so both
31//!   callers await and share its result rather than paginating the same history
32//!   twice.
33//!
34//! A running request is never preempted, so a queued request only starts once
35//! the current run for its room ends. Consumers bound their own runs with a
36//! [`BackPaginationRequest::max_batches`] cap or a stop predicate that fires
37//! once they have what they want.
38
39use std::{
40    cmp::Ordering,
41    collections::{BinaryHeap, HashMap},
42    num::NonZeroUsize,
43    ops::ControlFlow,
44    sync::{Arc, Weak},
45};
46
47use matrix_sdk_base::{RoomState, locks::Mutex, task_monitor::TaskMonitor};
48use matrix_sdk_common::executor::{AbortOnDrop, JoinHandleExt as _, spawn};
49use ruma::OwnedRoomId;
50use tokio::sync::{mpsc, oneshot};
51use tokio_util::sync::{CancellationToken, DropGuard};
52use tracing::{debug, info, instrument, trace, warn};
53
54use super::{EventCacheInner, caches::pagination::BackPaginationOutcome};
55
56/// Number of events requested per background pagination batch.
57pub(crate) const BATCH_SIZE: u16 = 30;
58
59/// Priority of a [`BackPaginationRequest`], relative to the others in the
60/// queue.
61#[allow(dead_code)]
62#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
63pub(crate) enum Priority {
64    /// Lowest priority: will run slowly when no higher priority requests are
65    /// pending.
66    Low,
67    /// Default priority. Higher than [`Self::Low`] and lower than
68    /// [`Self::High`].
69    Normal,
70    /// Highest priority: will run before any other pending request.
71    High,
72}
73
74/// When a single room's back-pagination run should stop: a predicate over each
75/// freshly loaded batch.
76///
77/// Each consumer supplies its own (a suitable latest-event candidate is loaded,
78/// a read receipt's target event id shows up, the batch is old enough for the
79/// search backfill). A predicate that never fires leaves the run bounded only
80/// by `max_batches`, the start of the timeline, or cancellation.
81pub(crate) type StopCondition = Box<dyn FnMut(&BackPaginationOutcome) -> ControlFlow<()> + Send>;
82
83/// A request to back-paginate one room, enqueued on the
84/// [`BackPaginationQueue`].
85pub(crate) struct BackPaginationRequest {
86    /// The room to back-paginate.
87    pub room_id: OwnedRoomId,
88    /// Scheduling priority.
89    pub priority: Priority,
90    /// When to stop.
91    pub stop: StopCondition,
92    /// Number of events to request per pagination.
93    pub batch_size: u16,
94    /// Maximum number of paginations for this request (`None` = unbounded).
95    pub max_batches: Option<usize>,
96}
97
98#[cfg(not(tarpaulin_include))]
99impl std::fmt::Debug for BackPaginationRequest {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.debug_struct("BackPaginationRequest")
102            .field("room_id", &self.room_id)
103            .field("priority", &self.priority)
104            .field("batch_size", &self.batch_size)
105            .field("max_batches", &self.max_batches)
106            .finish_non_exhaustive()
107    }
108}
109
110/// Why a single room's back-pagination run ended.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub(crate) enum BackPaginationStopReason {
113    /// Reached the start of the room's timeline; nothing more to load.
114    ReachedTimelineStart,
115    /// The request's [`StopCondition`] was met.
116    StopConditionMet,
117    /// Hit `max_batches` without satisfying the stop condition or reaching the
118    /// start of the timeline. More work likely remains; safe to retry later.
119    BatchLimitReached,
120    /// A pagination returned no events (e.g. a gap with no token to resolve it
121    /// yet). Not an error; there's simply nothing to load right now.
122    NoDataAvailable,
123    /// Setting up or running the pagination failed.
124    Failed,
125    /// The request was cancelled.
126    Cancelled,
127    /// The room isn't worth back-paginating: it's a space, which has no
128    /// messages to load, or the user isn't joined to it.
129    Skipped,
130}
131
132/// The result of running a single [`BackPaginationRequest`] to completion.
133#[allow(dead_code)]
134#[derive(Clone, Copy, Debug)]
135pub(crate) struct BackPaginationRunResult {
136    /// Why the run ended.
137    pub reason: BackPaginationStopReason,
138}
139
140/// Identifies a coalescable run i.e. a room back-paginated at a given priority.
141type RequestCoalescingKey = (OwnedRoomId, Priority);
142
143/// A handle to an enqueued [`BackPaginationRequest`]. Dropping the last handle
144/// for a request cancels it.
145pub(crate) struct BackPaginationHandle {
146    /// Cancels the request once every handle sharing it is dropped, unless
147    /// disarmed by [`BackPaginationHandle::detach`].
148    guard: Arc<DropGuard>,
149    // Only read by `join`, which the consumers awaiting a result are landing with.
150    #[allow(dead_code)]
151    completion: Option<oneshot::Receiver<BackPaginationRunResult>>,
152}
153
154#[cfg(not(tarpaulin_include))]
155impl std::fmt::Debug for BackPaginationHandle {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.debug_struct("BackPaginationHandle").finish_non_exhaustive()
158    }
159}
160
161impl BackPaginationHandle {
162    /// Let the request run to completion instead of cancelling it, for callers
163    /// that don't care about its result.
164    ///
165    /// Only the last handle for a request can disarm its cancellation; while
166    /// other handles are alive they keep the request running anyway.
167    pub(crate) fn detach(self) {
168        if let Some(guard) = Arc::into_inner(self.guard) {
169            guard.disarm();
170        }
171    }
172
173    /// Await the request's completion, returning why it ended.
174    #[allow(dead_code)]
175    pub(crate) async fn join(mut self) -> BackPaginationRunResult {
176        let cancelled = BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
177        match self.completion.take() {
178            Some(completion) => completion.await.unwrap_or(cancelled),
179            None => cancelled,
180        }
181    }
182}
183
184/// A bounded queue of back-pagination requests, ordered by priority.
185#[derive(Clone)]
186pub struct BackPaginationQueue {
187    inner: Arc<BackPaginationQueueInner>,
188}
189
190struct BackPaginationQueueInner {
191    sender: mpsc::UnboundedSender<SchedulerEvent>,
192    /// The cancellation shared by all the handles of a coalescing key, so a run
193    /// is only cancelled once every caller waiting on it has dropped its
194    /// handle.
195    ///
196    /// This only tracks handle lifetimes; the scheduler stays authoritative for
197    /// whether a request actually coalesces onto an existing run.
198    cancellations: Mutex<HashMap<RequestCoalescingKey, SharedCancellation>>,
199    task: matrix_sdk_base::task_monitor::BackgroundTaskHandle,
200}
201
202/// The cancellation of a single coalescable run.
203struct SharedCancellation {
204    /// Handed to the run, cancelled when the last `guard` below is dropped.
205    token: CancellationToken,
206    /// Weak, because the guard is owned by the handles: once they're all gone
207    /// the token fires and this entry is stale.
208    guard: Weak<DropGuard>,
209}
210
211#[cfg(not(tarpaulin_include))]
212impl std::fmt::Debug for BackPaginationQueue {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        f.debug_struct("BackPaginationQueue").finish_non_exhaustive()
215    }
216}
217
218impl BackPaginationQueue {
219    /// Create the queue and spawn its executor task.
220    pub(super) fn new(
221        event_cache: Weak<EventCacheInner>,
222        max_concurrent: NonZeroUsize,
223        task_monitor: &TaskMonitor,
224    ) -> Self {
225        let (sender, receiver) = mpsc::unbounded_channel();
226
227        // The scheduler holds a sender of its own, to be handed to the runs it
228        // spawns, so the channel never closes on its own: the task runs until
229        // the queue is dropped, which aborts it.
230        let task = task_monitor
231            .spawn_infinite_task(
232                "event_cache::back_pagination_queue",
233                scheduler(event_cache, receiver, sender.clone(), max_concurrent.get()),
234            )
235            .abort_on_drop();
236
237        Self {
238            inner: Arc::new(BackPaginationQueueInner {
239                sender,
240                cancellations: Mutex::new(HashMap::new()),
241                task,
242            }),
243        }
244    }
245
246    /// Enqueue a new request returning a handle to await it. A request for a
247    /// room already queued or running at the same priority is coalesced onto
248    /// that run rather than starting a second one.
249    pub(crate) fn enqueue(
250        &self,
251        request: BackPaginationRequest,
252    ) -> Result<BackPaginationHandle, BackPaginationQueueError> {
253        let key = (request.room_id.clone(), request.priority);
254        let (token, guard) = cancellation_for(&self.inner.cancellations, key);
255
256        let (completion_tx, completion_rx) = oneshot::channel();
257        let submitted = SubmittedRequest { request, token, completion: completion_tx };
258
259        self.inner
260            .sender
261            .send(SchedulerEvent::Submitted(submitted))
262            .map_err(|_| BackPaginationQueueError::ShutDown)?;
263
264        Ok(BackPaginationHandle { guard, completion: Some(completion_rx) })
265    }
266
267    /// Stop the queue for good.
268    ///
269    /// This aborts its executor, which cancels the running requests and drops
270    /// the queued ones. New requests are rejected with
271    /// [`BackPaginationQueueError::ShutDown`].
272    pub(super) fn shut_down(&self) {
273        self.inner.task.abort();
274    }
275}
276
277/// The cancellation shared by every handle for `key`, created if this is the
278/// first live one.
279///
280/// Requests that coalesce onto the same run must not be able to cancel each
281/// other, so they all hold a clone of one guard and the run is only cancelled
282/// once the last of them is dropped.
283fn cancellation_for(
284    cancellations: &Mutex<HashMap<RequestCoalescingKey, SharedCancellation>>,
285    key: RequestCoalescingKey,
286) -> (CancellationToken, Arc<DropGuard>) {
287    let mut cancellations = cancellations.lock();
288
289    if let Some(existing) = cancellations.get(&key)
290        && let Some(guard) = existing.guard.upgrade()
291    {
292        return (existing.token.clone(), guard);
293    }
294
295    // Forget the keys whose handles are all gone, while we're holding the lock.
296    cancellations.retain(|_, cancellation| cancellation.guard.strong_count() > 0);
297
298    let token = CancellationToken::new();
299    let guard = Arc::new(token.clone().drop_guard());
300    cancellations
301        .insert(key, SharedCancellation { token: token.clone(), guard: Arc::downgrade(&guard) });
302
303    (token, guard)
304}
305
306/// An error happening while interacting with the [`BackPaginationQueue`].
307#[derive(Debug, thiserror::Error)]
308pub(crate) enum BackPaginationQueueError {
309    /// The queue's executor isn't running anymore, so no new request can be
310    /// enqueued.
311    #[error("the back-pagination queue executor is not running")]
312    ShutDown,
313}
314
315/// Everything the scheduler reacts to, on a single channel so it can wait on
316/// one `recv_many` rather than selecting over two receivers.
317enum SchedulerEvent {
318    /// A caller enqueued a new request.
319    Submitted(SubmittedRequest),
320    /// A run finished: free its room and hand its result to every waiter.
321    Finished(RequestCoalescingKey, BackPaginationRunResult),
322}
323
324/// A request as it arrives on the queue's channel, before the scheduler has
325/// assigned it a sequence number or decided whether to coalesce it.
326struct SubmittedRequest {
327    request: BackPaginationRequest,
328    token: CancellationToken,
329    completion: oneshot::Sender<BackPaginationRunResult>,
330}
331
332/// A [`BackPaginationRequest`] admitted to the scheduler, holding the sequence
333/// number and request details.
334struct PendingRequest {
335    request: BackPaginationRequest,
336    /// Insertion order, assigned by the scheduler, for FIFO within a priority.
337    seq: u64,
338    token: CancellationToken,
339}
340
341impl PartialEq for PendingRequest {
342    fn eq(&self, other: &Self) -> bool {
343        self.request.priority == other.request.priority && self.seq == other.seq
344    }
345}
346
347impl Eq for PendingRequest {}
348
349impl PartialOrd for PendingRequest {
350    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
351        Some(self.cmp(other))
352    }
353}
354
355impl Ord for PendingRequest {
356    fn cmp(&self, other: &Self) -> Ordering {
357        // Higher priority first, then earlier `seq` first
358        self.request.priority.cmp(&other.request.priority).then_with(|| other.seq.cmp(&self.seq))
359    }
360}
361
362/// The executor schedules requests by priority, bounded concurrency at one run
363/// per room at a time.
364#[instrument(skip_all)]
365async fn scheduler(
366    event_cache: Weak<EventCacheInner>,
367    mut receiver: mpsc::UnboundedReceiver<SchedulerEvent>,
368    sender: mpsc::UnboundedSender<SchedulerEvent>,
369    max_concurrent: usize,
370) {
371    trace!("Spawning the back-pagination queue executor");
372
373    let mut pending_requests: BinaryHeap<PendingRequest> = BinaryHeap::new();
374    // The tasks of the currently running requests, keyed by room: also the set
375    // of rooms that can't take another run right now. Dropping the scheduler
376    // aborts all of them.
377    let mut active_requests: HashMap<OwnedRoomId, AbortOnDrop<()>> = HashMap::new();
378    let mut next_seq: u64 = 0;
379
380    // Completion senders for every request the scheduler knows about (queued or
381    // running), keyed by room and priority. A duplicate request coalesces onto
382    // the existing run by adding its completion sender here rather than
383    // starting a second run. When the run finishes every waiter for the key
384    // receives the same result.
385    let mut waiters: HashMap<RequestCoalescingKey, Vec<oneshot::Sender<BackPaginationRunResult>>> =
386        HashMap::new();
387
388    // At most `max_concurrent` runs are in flight, so there's never a reason to
389    // drain more than that in one go.
390    let mut events = Vec::with_capacity(max_concurrent);
391
392    loop {
393        // Schedule as many pending requests as the concurrency budget allows,
394        // never starting a second run for a room that's already running one.
395        schedule(
396            &event_cache,
397            &mut pending_requests,
398            &mut active_requests,
399            max_concurrent,
400            &sender,
401        );
402
403        // Unreachable while this task holds `sender`, but guards against a hot
404        // loop if that ever stops being true.
405        if receiver.recv_many(&mut events, max_concurrent).await == 0 {
406            info!("Back-pagination queue channel closed, exiting");
407            break;
408        }
409
410        for event in events.drain(..) {
411            match event {
412                SchedulerEvent::Submitted(submitted) => {
413                    let key = (submitted.request.room_id.clone(), submitted.request.priority);
414
415                    if try_coalesce(&mut waiters, &key, submitted.completion) {
416                        trace!(
417                            room_id = %key.0,
418                            priority = ?key.1,
419                            "coalesced back-pagination request onto an existing run"
420                        );
421                        continue;
422                    }
423
424                    pending_requests.push(PendingRequest {
425                        request: submitted.request,
426                        seq: next_seq,
427                        token: submitted.token,
428                    });
429                    next_seq += 1;
430                }
431
432                SchedulerEvent::Finished(key, result) => {
433                    active_requests.remove(&key.0);
434                    // Fan the single run's result out to every coalesced
435                    // waiter.
436                    if let Some(senders) = waiters.remove(&key) {
437                        for waiter in senders {
438                            let _ = waiter.send(result);
439                        }
440                    }
441                }
442            }
443        }
444    }
445}
446
447/// Coalesce a new caller's `completion` onto an existing run for `key`, or
448/// admit it as the first waiter of a new run.
449///
450/// Requests sharing a [`RequestCoalescingKey`] are functionally
451/// interchangeable, so only one run is needed; extra callers wait on the same
452/// result. Different priorities for the same room have different keys, so they
453/// never coalesce. A busy room must still let a higher-priority request wait
454/// its turn.
455fn try_coalesce(
456    waiters: &mut HashMap<RequestCoalescingKey, Vec<oneshot::Sender<BackPaginationRunResult>>>,
457    key: &RequestCoalescingKey,
458    completion: oneshot::Sender<BackPaginationRunResult>,
459) -> bool {
460    match waiters.get_mut(key) {
461        Some(existing) => {
462            existing.push(completion);
463            true
464        }
465        None => {
466            waiters.insert(key.to_owned(), vec![completion]);
467            false
468        }
469    }
470}
471
472/// Pop and spawn every currently-schedulable request.
473fn schedule(
474    event_cache: &Weak<EventCacheInner>,
475    pending_requests: &mut BinaryHeap<PendingRequest>,
476    active_requests: &mut HashMap<OwnedRoomId, AbortOnDrop<()>>,
477    max_concurrent: usize,
478    sender: &mpsc::UnboundedSender<SchedulerEvent>,
479) {
480    for request in next_runnable(pending_requests, active_requests, max_concurrent) {
481        let key = (request.request.room_id.clone(), request.request.priority);
482
483        trace!(
484            room_id = %key.0,
485            priority = ?key.1,
486            active = active_requests.len(),
487            queued = pending_requests.len(),
488            "back-pagination scheduled"
489        );
490
491        let room_id = key.0.clone();
492        let event_cache = event_cache.clone();
493        let sender = sender.clone();
494        let task = spawn(async move {
495            let result = run_request(&event_cache, request.request, &request.token).await;
496            // The scheduler owns the completion senders (for coalescing), so
497            // hand it the result to fan out to every waiter for this key.
498            let _ = sender.send(SchedulerEvent::Finished(key, result));
499        });
500
501        active_requests.insert(room_id, task.abort_on_drop());
502    }
503}
504
505/// Pick the requests that can start right now, highest priority first: bounded
506/// by `max_concurrent` total in flight, and never two runs for the same room.
507///
508/// Requests popped but not yet runnable (their room is busy) are pushed back
509/// onto the heap.
510// Generic over the map's value type so the scheduling tests don't need a
511// runtime to build a task handle; only the keys matter here.
512fn next_runnable<T>(
513    pending_requests: &mut BinaryHeap<PendingRequest>,
514    active_requests: &HashMap<OwnedRoomId, T>,
515    max_concurrent: usize,
516) -> Vec<PendingRequest> {
517    let mut picked: Vec<PendingRequest> = Vec::new();
518    let mut skipped = Vec::new();
519
520    while active_requests.len() + picked.len() < max_concurrent {
521        let Some(request) = pending_requests.pop() else {
522            break;
523        };
524
525        let room_id = &request.request.room_id;
526        if active_requests.contains_key(room_id)
527            || picked.iter().any(|other| other.request.room_id == *room_id)
528        {
529            // This room is busy, try it again next round.
530            skipped.push(request);
531            continue;
532        }
533
534        picked.push(request);
535    }
536
537    pending_requests.extend(skipped);
538
539    picked
540}
541
542/// Back-paginate one room until its [`StopCondition`], the start of the
543/// timeline, the batch budget, or cancellation.
544#[instrument(skip_all, fields(room_id = %request.room_id, priority = ?request.priority))]
545async fn run_request(
546    event_cache: &Weak<EventCacheInner>,
547    mut request: BackPaginationRequest,
548    token: &CancellationToken,
549) -> BackPaginationRunResult {
550    // Cancelled while still queued, nothing to do.
551    if token.is_cancelled() {
552        return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
553    }
554
555    // Grab an owned `RoomPagination`, dropping the caches guard immediately so
556    // we don't hold the room lock across network paginations.
557    //
558    // Also keep a subscription to the room for the whole run: dropping it when
559    // this function returns triggers an auto-shrink of the room's linked chunk
560    // if nobody else is subscribed, so backfilled events don't linger in
561    // memory.
562    let (pagination, _subscriber) = {
563        let Some(inner) = event_cache.upgrade() else {
564            return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
565        };
566        if let Ok(client) = inner.client()
567            && let Some(room) = client.get_room(&request.room_id)
568            && (room.is_space() || room.state() != RoomState::Joined)
569        {
570            debug!("skipping back-pagination for a space or a non-joined room");
571            return BackPaginationRunResult { reason: BackPaginationStopReason::Skipped };
572        }
573        let room = match inner.all_caches_for_room(&request.room_id).await {
574            Ok(caches) => caches.room().clone(),
575            Err(err) => {
576                warn!("no caches for room while back-paginating: {err}");
577                return BackPaginationRunResult { reason: BackPaginationStopReason::Failed };
578            }
579        };
580        let subscriber = match room.subscribe().await {
581            Ok((_events, subscriber)) => subscriber,
582            Err(err) => {
583                warn!("couldn't subscribe to the room while back-paginating: {err}");
584                return BackPaginationRunResult { reason: BackPaginationStopReason::Failed };
585            }
586        };
587        (room.pagination(), subscriber)
588    };
589
590    let mut batches = 0usize;
591
592    let reason = loop {
593        if token.is_cancelled() {
594            break BackPaginationStopReason::Cancelled;
595        }
596
597        let outcome = match pagination.run_backwards_once(request.batch_size).await {
598            Ok(outcome) => outcome,
599            Err(err) => {
600                warn!("back-pagination failed: {err}");
601                break BackPaginationStopReason::Failed;
602            }
603        };
604
605        // Reaching the start of the timeline can still come with a last batch
606        // of events, so let the stop condition see it before ending the run.
607        if (request.stop)(&outcome).is_break() {
608            break BackPaginationStopReason::StopConditionMet;
609        }
610
611        if outcome.reached_start {
612            break BackPaginationStopReason::ReachedTimelineStart;
613        }
614
615        if outcome.events.is_empty() {
616            break BackPaginationStopReason::NoDataAvailable;
617        }
618
619        batches += 1;
620        if let Some(max) = request.max_batches
621            && batches >= max
622        {
623            break BackPaginationStopReason::BatchLimitReached;
624        }
625    };
626
627    debug!(?reason, "back-pagination run finished");
628
629    BackPaginationRunResult { reason }
630}
631
632#[cfg(all(test, not(target_arch = "wasm32")))]
633mod tests {
634    use std::{collections::HashMap, ops::ControlFlow};
635
636    use matrix_sdk_base::locks::Mutex;
637    use ruma::room_id;
638
639    use super::{
640        BackPaginationRequest, PendingRequest, Priority, cancellation_for, next_runnable,
641        try_coalesce,
642    };
643
644    /// Build a queued request for a room, at a priority, with an insertion seq.
645    fn queued(room_id: ruma::OwnedRoomId, priority: Priority, seq: u64) -> PendingRequest {
646        PendingRequest {
647            request: BackPaginationRequest {
648                room_id,
649                priority,
650                // Scheduling tests never evaluate the stop condition.
651                stop: Box::new(|_| ControlFlow::Continue(())),
652                batch_size: 10,
653                max_batches: None,
654            },
655            seq,
656            token: tokio_util::sync::CancellationToken::new(),
657        }
658    }
659
660    /// `next_runnable` serves highest priority first, then FIFO within a
661    /// priority.
662    #[test]
663    fn test_scheduling_priority_and_fifo() {
664        use std::collections::BinaryHeap;
665
666        let (a, b, c, d) = (room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e"), room_id!("!d:e"));
667
668        let mut pending_requests = BinaryHeap::new();
669        // Push out of priority order, with monotonic seqs.
670        pending_requests.push(queued(a.to_owned(), Priority::Low, 0));
671        pending_requests.push(queued(b.to_owned(), Priority::High, 1));
672        pending_requests.push(queued(c.to_owned(), Priority::Normal, 2));
673        pending_requests.push(queued(d.to_owned(), Priority::High, 3));
674
675        let active_requests: HashMap<_, ()> = HashMap::new();
676        let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
677            .into_iter()
678            .map(|r| r.request.room_id)
679            .collect();
680
681        // High first (b before d by FIFO), then Normal, then Low.
682        assert_eq!(picked, vec![b.to_owned(), d.to_owned(), c.to_owned(), a.to_owned()]);
683    }
684
685    /// `next_runnable` never returns more than `max_concurrent`.
686    #[test]
687    fn test_scheduling_respects_concurrency_cap() {
688        use std::collections::BinaryHeap;
689
690        let mut pending_requests = BinaryHeap::new();
691        for (i, room) in [room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e")].iter().enumerate() {
692            pending_requests.push(queued((*room).to_owned(), Priority::Normal, i as u64));
693        }
694
695        let active_requests: HashMap<_, ()> = HashMap::new();
696        let picked = next_runnable(&mut pending_requests, &active_requests, 2);
697
698        assert_eq!(picked.len(), 2);
699        // The third request stays queued.
700        assert_eq!(pending_requests.len(), 1);
701    }
702
703    /// `next_runnable` won't start a room that's already active, nor two runs
704    /// for the same room in one pass.
705    #[test]
706    fn test_scheduling_per_room_single_flight() {
707        use std::collections::BinaryHeap;
708
709        let (a, b) = (room_id!("!a:e"), room_id!("!b:e"));
710
711        // `a` is already running.
712        let active_requests = HashMap::from([(a.to_owned(), ())]);
713
714        let mut pending_requests = BinaryHeap::new();
715        pending_requests.push(queued(a.to_owned(), Priority::High, 0)); // same room as active
716        pending_requests.push(queued(a.to_owned(), Priority::High, 1)); // and again
717        pending_requests.push(queued(b.to_owned(), Priority::Low, 2)); // a different room
718
719        let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
720            .into_iter()
721            .map(|r| r.request.room_id)
722            .collect();
723
724        // Only `b` runs; both `a` requests stay queued (a is busy).
725        assert_eq!(picked, vec![b.to_owned()]);
726        assert_eq!(pending_requests.len(), 2);
727    }
728
729    /// Every handle for a room + priority shares one cancellation, so a caller
730    /// dropping its handle can't cancel a run others are still waiting on.
731    #[test]
732    fn test_cancellation_is_shared_per_key() {
733        let cancellations = Mutex::new(HashMap::new());
734        let key = (room_id!("!a:e").to_owned(), Priority::Normal);
735
736        let (first_token, first_guard) = cancellation_for(&cancellations, key.clone());
737        let (second_token, second_guard) = cancellation_for(&cancellations, key.clone());
738
739        // One run, so one token for both callers.
740        assert!(!first_token.is_cancelled());
741        drop(first_guard);
742        assert!(!first_token.is_cancelled());
743        assert!(!second_token.is_cancelled());
744
745        // The last handle to go cancels the run.
746        drop(second_guard);
747        assert!(first_token.is_cancelled());
748        assert!(second_token.is_cancelled());
749
750        // Once they're all gone the key is stale, so the next caller gets a
751        // fresh token rather than an already-cancelled one.
752        let (third_token, _third_guard) = cancellation_for(&cancellations, key);
753        assert!(!third_token.is_cancelled());
754
755        // A different priority for the same room is a different run.
756        let other = (room_id!("!a:e").to_owned(), Priority::High);
757        let (other_token, other_guard) = cancellation_for(&cancellations, other);
758        drop(other_guard);
759        assert!(other_token.is_cancelled());
760        assert!(!third_token.is_cancelled());
761    }
762
763    /// The first request for a room + priority opens a new run; a later one at
764    /// the same key coalesces onto it (shares its waiter list); a different
765    /// priority for the same room opens its own run.
766    #[test]
767    fn test_coalescing() {
768        let a = room_id!("!a:e");
769        let mut waiters = HashMap::new();
770
771        let completion = || tokio::sync::oneshot::channel().0;
772        let normal = (a.to_owned(), Priority::Normal);
773        let high = (a.to_owned(), Priority::High);
774
775        // First request at (a, Normal): opens a new run.
776        assert!(!try_coalesce(&mut waiters, &normal, completion()));
777        assert_eq!(waiters[&normal].len(), 1);
778
779        // Second request at the same key: coalesces onto it.
780        assert!(try_coalesce(&mut waiters, &normal, completion()));
781        assert_eq!(waiters[&normal].len(), 2);
782
783        // Same room, different priority: a separate run, not a coalesce.
784        assert!(!try_coalesce(&mut waiters, &high, completion()));
785        assert_eq!(waiters.len(), 2);
786        assert_eq!(waiters[&high].len(), 1);
787    }
788}