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::{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}
128
129/// The result of running a single [`BackPaginationRequest`] to completion.
130#[allow(dead_code)]
131#[derive(Clone, Copy, Debug)]
132pub(crate) struct BackPaginationRunResult {
133    /// Why the run ended.
134    pub reason: BackPaginationStopReason,
135}
136
137/// Identifies a coalescable run i.e. a room back-paginated at a given priority.
138type RequestCoalescingKey = (OwnedRoomId, Priority);
139
140/// A handle to an enqueued [`BackPaginationRequest`]. Dropping the last handle
141/// for a request cancels it.
142pub(crate) struct BackPaginationHandle {
143    /// Cancels the request once every handle sharing it is dropped, unless
144    /// disarmed by [`BackPaginationHandle::detach`].
145    guard: Arc<DropGuard>,
146    // Only read by `join`, which the consumers awaiting a result are landing with.
147    #[allow(dead_code)]
148    completion: Option<oneshot::Receiver<BackPaginationRunResult>>,
149}
150
151#[cfg(not(tarpaulin_include))]
152impl std::fmt::Debug for BackPaginationHandle {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.debug_struct("BackPaginationHandle").finish_non_exhaustive()
155    }
156}
157
158impl BackPaginationHandle {
159    /// Let the request run to completion instead of cancelling it, for callers
160    /// that don't care about its result.
161    ///
162    /// Only the last handle for a request can disarm its cancellation; while
163    /// other handles are alive they keep the request running anyway.
164    pub(crate) fn detach(self) {
165        if let Some(guard) = Arc::into_inner(self.guard) {
166            guard.disarm();
167        }
168    }
169
170    /// Await the request's completion, returning why it ended.
171    #[allow(dead_code)]
172    pub(crate) async fn join(mut self) -> BackPaginationRunResult {
173        let cancelled = BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
174        match self.completion.take() {
175            Some(completion) => completion.await.unwrap_or(cancelled),
176            None => cancelled,
177        }
178    }
179}
180
181/// A bounded queue of back-pagination requests, ordered by priority.
182#[derive(Clone)]
183pub struct BackPaginationQueue {
184    inner: Arc<BackPaginationQueueInner>,
185}
186
187struct BackPaginationQueueInner {
188    sender: mpsc::UnboundedSender<SchedulerEvent>,
189    /// The cancellation shared by all the handles of a coalescing key, so a run
190    /// is only cancelled once every caller waiting on it has dropped its
191    /// handle.
192    ///
193    /// This only tracks handle lifetimes; the scheduler stays authoritative for
194    /// whether a request actually coalesces onto an existing run.
195    cancellations: Mutex<HashMap<RequestCoalescingKey, SharedCancellation>>,
196    _task: matrix_sdk_base::task_monitor::BackgroundTaskHandle,
197}
198
199/// The cancellation of a single coalescable run.
200struct SharedCancellation {
201    /// Handed to the run, cancelled when the last `guard` below is dropped.
202    token: CancellationToken,
203    /// Weak, because the guard is owned by the handles: once they're all gone
204    /// the token fires and this entry is stale.
205    guard: Weak<DropGuard>,
206}
207
208#[cfg(not(tarpaulin_include))]
209impl std::fmt::Debug for BackPaginationQueue {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        f.debug_struct("BackPaginationQueue").finish_non_exhaustive()
212    }
213}
214
215impl BackPaginationQueue {
216    /// Create the queue and spawn its executor task.
217    pub(super) fn new(
218        event_cache: Weak<EventCacheInner>,
219        max_concurrent: NonZeroUsize,
220        task_monitor: &TaskMonitor,
221    ) -> Self {
222        let (sender, receiver) = mpsc::unbounded_channel();
223
224        // The scheduler holds a sender of its own, to be handed to the runs it
225        // spawns, so the channel never closes on its own: the task runs until
226        // the queue is dropped, which aborts it.
227        let task = task_monitor
228            .spawn_infinite_task(
229                "event_cache::back_pagination_queue",
230                scheduler(event_cache, receiver, sender.clone(), max_concurrent.get()),
231            )
232            .abort_on_drop();
233
234        Self {
235            inner: Arc::new(BackPaginationQueueInner {
236                sender,
237                cancellations: Mutex::new(HashMap::new()),
238                _task: task,
239            }),
240        }
241    }
242
243    /// Enqueue a new request returning a handle to await it. A request for a
244    /// room already queued or running at the same priority is coalesced onto
245    /// that run rather than starting a second one.
246    pub(crate) fn enqueue(
247        &self,
248        request: BackPaginationRequest,
249    ) -> Result<BackPaginationHandle, BackPaginationQueueError> {
250        let key = (request.room_id.clone(), request.priority);
251        let (token, guard) = cancellation_for(&self.inner.cancellations, key);
252
253        let (completion_tx, completion_rx) = oneshot::channel();
254        let submitted = SubmittedRequest { request, token, completion: completion_tx };
255
256        self.inner
257            .sender
258            .send(SchedulerEvent::Submitted(submitted))
259            .map_err(|_| BackPaginationQueueError::ShutDown)?;
260
261        Ok(BackPaginationHandle { guard, completion: Some(completion_rx) })
262    }
263}
264
265/// The cancellation shared by every handle for `key`, created if this is the
266/// first live one.
267///
268/// Requests that coalesce onto the same run must not be able to cancel each
269/// other, so they all hold a clone of one guard and the run is only cancelled
270/// once the last of them is dropped.
271fn cancellation_for(
272    cancellations: &Mutex<HashMap<RequestCoalescingKey, SharedCancellation>>,
273    key: RequestCoalescingKey,
274) -> (CancellationToken, Arc<DropGuard>) {
275    let mut cancellations = cancellations.lock();
276
277    if let Some(existing) = cancellations.get(&key)
278        && let Some(guard) = existing.guard.upgrade()
279    {
280        return (existing.token.clone(), guard);
281    }
282
283    // Forget the keys whose handles are all gone, while we're holding the lock.
284    cancellations.retain(|_, cancellation| cancellation.guard.strong_count() > 0);
285
286    let token = CancellationToken::new();
287    let guard = Arc::new(token.clone().drop_guard());
288    cancellations
289        .insert(key, SharedCancellation { token: token.clone(), guard: Arc::downgrade(&guard) });
290
291    (token, guard)
292}
293
294/// An error happening while interacting with the [`BackPaginationQueue`].
295#[derive(Debug, thiserror::Error)]
296pub(crate) enum BackPaginationQueueError {
297    /// The queue's executor isn't running anymore, so no new request can be
298    /// enqueued.
299    #[error("the back-pagination queue executor is not running")]
300    ShutDown,
301}
302
303/// Everything the scheduler reacts to, on a single channel so it can wait on
304/// one `recv_many` rather than selecting over two receivers.
305enum SchedulerEvent {
306    /// A caller enqueued a new request.
307    Submitted(SubmittedRequest),
308    /// A run finished: free its room and hand its result to every waiter.
309    Finished(RequestCoalescingKey, BackPaginationRunResult),
310}
311
312/// A request as it arrives on the queue's channel, before the scheduler has
313/// assigned it a sequence number or decided whether to coalesce it.
314struct SubmittedRequest {
315    request: BackPaginationRequest,
316    token: CancellationToken,
317    completion: oneshot::Sender<BackPaginationRunResult>,
318}
319
320/// A [`BackPaginationRequest`] admitted to the scheduler, holding the sequence
321/// number and request details.
322struct PendingRequest {
323    request: BackPaginationRequest,
324    /// Insertion order, assigned by the scheduler, for FIFO within a priority.
325    seq: u64,
326    token: CancellationToken,
327}
328
329impl PartialEq for PendingRequest {
330    fn eq(&self, other: &Self) -> bool {
331        self.request.priority == other.request.priority && self.seq == other.seq
332    }
333}
334
335impl Eq for PendingRequest {}
336
337impl PartialOrd for PendingRequest {
338    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
339        Some(self.cmp(other))
340    }
341}
342
343impl Ord for PendingRequest {
344    fn cmp(&self, other: &Self) -> Ordering {
345        // Higher priority first, then earlier `seq` first
346        self.request.priority.cmp(&other.request.priority).then_with(|| other.seq.cmp(&self.seq))
347    }
348}
349
350/// The executor schedules requests by priority, bounded concurrency at one run
351/// per room at a time.
352#[instrument(skip_all)]
353async fn scheduler(
354    event_cache: Weak<EventCacheInner>,
355    mut receiver: mpsc::UnboundedReceiver<SchedulerEvent>,
356    sender: mpsc::UnboundedSender<SchedulerEvent>,
357    max_concurrent: usize,
358) {
359    trace!("Spawning the back-pagination queue executor");
360
361    let mut pending_requests: BinaryHeap<PendingRequest> = BinaryHeap::new();
362    // The tasks of the currently running requests, keyed by room: also the set
363    // of rooms that can't take another run right now. Dropping the scheduler
364    // aborts all of them.
365    let mut active_requests: HashMap<OwnedRoomId, AbortOnDrop<()>> = HashMap::new();
366    let mut next_seq: u64 = 0;
367
368    // Completion senders for every request the scheduler knows about (queued or
369    // running), keyed by room and priority. A duplicate request coalesces onto
370    // the existing run by adding its completion sender here rather than
371    // starting a second run. When the run finishes every waiter for the key
372    // receives the same result.
373    let mut waiters: HashMap<RequestCoalescingKey, Vec<oneshot::Sender<BackPaginationRunResult>>> =
374        HashMap::new();
375
376    // At most `max_concurrent` runs are in flight, so there's never a reason to
377    // drain more than that in one go.
378    let mut events = Vec::with_capacity(max_concurrent);
379
380    loop {
381        // Schedule as many pending requests as the concurrency budget allows,
382        // never starting a second run for a room that's already running one.
383        schedule(
384            &event_cache,
385            &mut pending_requests,
386            &mut active_requests,
387            max_concurrent,
388            &sender,
389        );
390
391        // Unreachable while this task holds `sender`, but guards against a hot
392        // loop if that ever stops being true.
393        if receiver.recv_many(&mut events, max_concurrent).await == 0 {
394            info!("Back-pagination queue channel closed, exiting");
395            break;
396        }
397
398        for event in events.drain(..) {
399            match event {
400                SchedulerEvent::Submitted(submitted) => {
401                    let key = (submitted.request.room_id.clone(), submitted.request.priority);
402
403                    if try_coalesce(&mut waiters, &key, submitted.completion) {
404                        trace!(
405                            room_id = %key.0,
406                            priority = ?key.1,
407                            "coalesced back-pagination request onto an existing run"
408                        );
409                        continue;
410                    }
411
412                    pending_requests.push(PendingRequest {
413                        request: submitted.request,
414                        seq: next_seq,
415                        token: submitted.token,
416                    });
417                    next_seq += 1;
418                }
419
420                SchedulerEvent::Finished(key, result) => {
421                    active_requests.remove(&key.0);
422                    // Fan the single run's result out to every coalesced
423                    // waiter.
424                    if let Some(senders) = waiters.remove(&key) {
425                        for waiter in senders {
426                            let _ = waiter.send(result);
427                        }
428                    }
429                }
430            }
431        }
432    }
433}
434
435/// Coalesce a new caller's `completion` onto an existing run for `key`, or
436/// admit it as the first waiter of a new run.
437///
438/// Requests sharing a [`RequestCoalescingKey`] are functionally
439/// interchangeable, so only one run is needed; extra callers wait on the same
440/// result. Different priorities for the same room have different keys, so they
441/// never coalesce. A busy room must still let a higher-priority request wait
442/// its turn.
443fn try_coalesce(
444    waiters: &mut HashMap<RequestCoalescingKey, Vec<oneshot::Sender<BackPaginationRunResult>>>,
445    key: &RequestCoalescingKey,
446    completion: oneshot::Sender<BackPaginationRunResult>,
447) -> bool {
448    match waiters.get_mut(key) {
449        Some(existing) => {
450            existing.push(completion);
451            true
452        }
453        None => {
454            waiters.insert(key.to_owned(), vec![completion]);
455            false
456        }
457    }
458}
459
460/// Pop and spawn every currently-schedulable request.
461fn schedule(
462    event_cache: &Weak<EventCacheInner>,
463    pending_requests: &mut BinaryHeap<PendingRequest>,
464    active_requests: &mut HashMap<OwnedRoomId, AbortOnDrop<()>>,
465    max_concurrent: usize,
466    sender: &mpsc::UnboundedSender<SchedulerEvent>,
467) {
468    for request in next_runnable(pending_requests, active_requests, max_concurrent) {
469        let key = (request.request.room_id.clone(), request.request.priority);
470
471        trace!(
472            room_id = %key.0,
473            priority = ?key.1,
474            active = active_requests.len(),
475            queued = pending_requests.len(),
476            "back-pagination scheduled"
477        );
478
479        let room_id = key.0.clone();
480        let event_cache = event_cache.clone();
481        let sender = sender.clone();
482        let task = spawn(async move {
483            let result = run_request(&event_cache, request.request, &request.token).await;
484            // The scheduler owns the completion senders (for coalescing), so
485            // hand it the result to fan out to every waiter for this key.
486            let _ = sender.send(SchedulerEvent::Finished(key, result));
487        });
488
489        active_requests.insert(room_id, task.abort_on_drop());
490    }
491}
492
493/// Pick the requests that can start right now, highest priority first: bounded
494/// by `max_concurrent` total in flight, and never two runs for the same room.
495///
496/// Requests popped but not yet runnable (their room is busy) are pushed back
497/// onto the heap.
498// Generic over the map's value type so the scheduling tests don't need a
499// runtime to build a task handle; only the keys matter here.
500fn next_runnable<T>(
501    pending_requests: &mut BinaryHeap<PendingRequest>,
502    active_requests: &HashMap<OwnedRoomId, T>,
503    max_concurrent: usize,
504) -> Vec<PendingRequest> {
505    let mut picked: Vec<PendingRequest> = Vec::new();
506    let mut skipped = Vec::new();
507
508    while active_requests.len() + picked.len() < max_concurrent {
509        let Some(request) = pending_requests.pop() else {
510            break;
511        };
512
513        let room_id = &request.request.room_id;
514        if active_requests.contains_key(room_id)
515            || picked.iter().any(|other| other.request.room_id == *room_id)
516        {
517            // This room is busy, try it again next round.
518            skipped.push(request);
519            continue;
520        }
521
522        picked.push(request);
523    }
524
525    pending_requests.extend(skipped);
526
527    picked
528}
529
530/// Back-paginate one room until its [`StopCondition`], the start of the
531/// timeline, the batch budget, or cancellation.
532#[instrument(skip_all, fields(room_id = %request.room_id, priority = ?request.priority))]
533async fn run_request(
534    event_cache: &Weak<EventCacheInner>,
535    mut request: BackPaginationRequest,
536    token: &CancellationToken,
537) -> BackPaginationRunResult {
538    // Cancelled while still queued, nothing to do.
539    if token.is_cancelled() {
540        return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
541    }
542
543    // Grab an owned `RoomPagination`, dropping the caches guard immediately so
544    // we don't hold the room lock across network paginations.
545    let pagination = {
546        let Some(inner) = event_cache.upgrade() else {
547            return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
548        };
549        match inner.all_caches_for_room(&request.room_id).await {
550            Ok(caches) => caches.room().pagination(),
551            Err(err) => {
552                warn!("no caches for room while back-paginating: {err}");
553                return BackPaginationRunResult { reason: BackPaginationStopReason::Failed };
554            }
555        }
556    };
557
558    let mut batches = 0usize;
559
560    let reason = loop {
561        if token.is_cancelled() {
562            break BackPaginationStopReason::Cancelled;
563        }
564
565        let outcome = match pagination.run_backwards_once(request.batch_size).await {
566            Ok(outcome) => outcome,
567            Err(err) => {
568                warn!("back-pagination failed: {err}");
569                break BackPaginationStopReason::Failed;
570            }
571        };
572
573        // Reaching the start of the timeline can still come with a last batch
574        // of events, so let the stop condition see it before ending the run.
575        if (request.stop)(&outcome).is_break() {
576            break BackPaginationStopReason::StopConditionMet;
577        }
578
579        if outcome.reached_start {
580            break BackPaginationStopReason::ReachedTimelineStart;
581        }
582
583        if outcome.events.is_empty() {
584            break BackPaginationStopReason::NoDataAvailable;
585        }
586
587        batches += 1;
588        if let Some(max) = request.max_batches
589            && batches >= max
590        {
591            break BackPaginationStopReason::BatchLimitReached;
592        }
593    };
594
595    debug!(?reason, "back-pagination run finished");
596
597    BackPaginationRunResult { reason }
598}
599
600#[cfg(all(test, not(target_arch = "wasm32")))]
601mod tests {
602    use std::{collections::HashMap, ops::ControlFlow};
603
604    use matrix_sdk_base::locks::Mutex;
605    use ruma::room_id;
606
607    use super::{
608        BackPaginationRequest, PendingRequest, Priority, cancellation_for, next_runnable,
609        try_coalesce,
610    };
611
612    /// Build a queued request for a room, at a priority, with an insertion seq.
613    fn queued(room_id: ruma::OwnedRoomId, priority: Priority, seq: u64) -> PendingRequest {
614        PendingRequest {
615            request: BackPaginationRequest {
616                room_id,
617                priority,
618                // Scheduling tests never evaluate the stop condition.
619                stop: Box::new(|_| ControlFlow::Continue(())),
620                batch_size: 10,
621                max_batches: None,
622            },
623            seq,
624            token: tokio_util::sync::CancellationToken::new(),
625        }
626    }
627
628    /// `next_runnable` serves highest priority first, then FIFO within a
629    /// priority.
630    #[test]
631    fn test_scheduling_priority_and_fifo() {
632        use std::collections::BinaryHeap;
633
634        let (a, b, c, d) = (room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e"), room_id!("!d:e"));
635
636        let mut pending_requests = BinaryHeap::new();
637        // Push out of priority order, with monotonic seqs.
638        pending_requests.push(queued(a.to_owned(), Priority::Low, 0));
639        pending_requests.push(queued(b.to_owned(), Priority::High, 1));
640        pending_requests.push(queued(c.to_owned(), Priority::Normal, 2));
641        pending_requests.push(queued(d.to_owned(), Priority::High, 3));
642
643        let active_requests: HashMap<_, ()> = HashMap::new();
644        let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
645            .into_iter()
646            .map(|r| r.request.room_id)
647            .collect();
648
649        // High first (b before d by FIFO), then Normal, then Low.
650        assert_eq!(picked, vec![b.to_owned(), d.to_owned(), c.to_owned(), a.to_owned()]);
651    }
652
653    /// `next_runnable` never returns more than `max_concurrent`.
654    #[test]
655    fn test_scheduling_respects_concurrency_cap() {
656        use std::collections::BinaryHeap;
657
658        let mut pending_requests = BinaryHeap::new();
659        for (i, room) in [room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e")].iter().enumerate() {
660            pending_requests.push(queued((*room).to_owned(), Priority::Normal, i as u64));
661        }
662
663        let active_requests: HashMap<_, ()> = HashMap::new();
664        let picked = next_runnable(&mut pending_requests, &active_requests, 2);
665
666        assert_eq!(picked.len(), 2);
667        // The third request stays queued.
668        assert_eq!(pending_requests.len(), 1);
669    }
670
671    /// `next_runnable` won't start a room that's already active, nor two runs
672    /// for the same room in one pass.
673    #[test]
674    fn test_scheduling_per_room_single_flight() {
675        use std::collections::BinaryHeap;
676
677        let (a, b) = (room_id!("!a:e"), room_id!("!b:e"));
678
679        // `a` is already running.
680        let active_requests = HashMap::from([(a.to_owned(), ())]);
681
682        let mut pending_requests = BinaryHeap::new();
683        pending_requests.push(queued(a.to_owned(), Priority::High, 0)); // same room as active
684        pending_requests.push(queued(a.to_owned(), Priority::High, 1)); // and again
685        pending_requests.push(queued(b.to_owned(), Priority::Low, 2)); // a different room
686
687        let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
688            .into_iter()
689            .map(|r| r.request.room_id)
690            .collect();
691
692        // Only `b` runs; both `a` requests stay queued (a is busy).
693        assert_eq!(picked, vec![b.to_owned()]);
694        assert_eq!(pending_requests.len(), 2);
695    }
696
697    /// Every handle for a room + priority shares one cancellation, so a caller
698    /// dropping its handle can't cancel a run others are still waiting on.
699    #[test]
700    fn test_cancellation_is_shared_per_key() {
701        let cancellations = Mutex::new(HashMap::new());
702        let key = (room_id!("!a:e").to_owned(), Priority::Normal);
703
704        let (first_token, first_guard) = cancellation_for(&cancellations, key.clone());
705        let (second_token, second_guard) = cancellation_for(&cancellations, key.clone());
706
707        // One run, so one token for both callers.
708        assert!(!first_token.is_cancelled());
709        drop(first_guard);
710        assert!(!first_token.is_cancelled());
711        assert!(!second_token.is_cancelled());
712
713        // The last handle to go cancels the run.
714        drop(second_guard);
715        assert!(first_token.is_cancelled());
716        assert!(second_token.is_cancelled());
717
718        // Once they're all gone the key is stale, so the next caller gets a
719        // fresh token rather than an already-cancelled one.
720        let (third_token, _third_guard) = cancellation_for(&cancellations, key);
721        assert!(!third_token.is_cancelled());
722
723        // A different priority for the same room is a different run.
724        let other = (room_id!("!a:e").to_owned(), Priority::High);
725        let (other_token, other_guard) = cancellation_for(&cancellations, other);
726        drop(other_guard);
727        assert!(other_token.is_cancelled());
728        assert!(!third_token.is_cancelled());
729    }
730
731    /// The first request for a room + priority opens a new run; a later one at
732    /// the same key coalesces onto it (shares its waiter list); a different
733    /// priority for the same room opens its own run.
734    #[test]
735    fn test_coalescing() {
736        let a = room_id!("!a:e");
737        let mut waiters = HashMap::new();
738
739        let completion = || tokio::sync::oneshot::channel().0;
740        let normal = (a.to_owned(), Priority::Normal);
741        let high = (a.to_owned(), Priority::High);
742
743        // First request at (a, Normal): opens a new run.
744        assert!(!try_coalesce(&mut waiters, &normal, completion()));
745        assert_eq!(waiters[&normal].len(), 1);
746
747        // Second request at the same key: coalesces onto it.
748        assert!(try_coalesce(&mut waiters, &normal, completion()));
749        assert_eq!(waiters[&normal].len(), 2);
750
751        // Same room, different priority: a separate run, not a coalesce.
752        assert!(!try_coalesce(&mut waiters, &high, completion()));
753        assert_eq!(waiters.len(), 2);
754        assert_eq!(waiters[&high].len(), 1);
755    }
756}