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`].
141/// Dropping the last handle 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 the
226        // 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.
244    /// A request for a room already queued or running at the same priority is
245    /// coalesced onto 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 of
363    // rooms that can't take another run right now. Dropping the scheduler aborts
364    // 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 the
370    // existing run by adding its completion sender here rather than starting a
371    // second run. When the run finishes every waiter for the key receives the same
372    // 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, never
382        // 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 loop
392        // 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 waiter.
423                    if let Some(senders) = waiters.remove(&key) {
424                        for waiter in senders {
425                            let _ = waiter.send(result);
426                        }
427                    }
428                }
429            }
430        }
431    }
432}
433
434/// Coalesce a new caller's `completion` onto an existing run for `key`, or
435/// admit it as the first waiter of a new run.
436///
437/// Requests sharing a [`RequestCoalescingKey`] are functionally
438/// interchangeable, so only one run is needed; extra callers wait on the same
439/// result. Different priorities for the same room have different keys, so they
440/// never coalesce. A busy room must still let a higher-priority request wait
441/// its turn.
442fn try_coalesce(
443    waiters: &mut HashMap<RequestCoalescingKey, Vec<oneshot::Sender<BackPaginationRunResult>>>,
444    key: &RequestCoalescingKey,
445    completion: oneshot::Sender<BackPaginationRunResult>,
446) -> bool {
447    match waiters.get_mut(key) {
448        Some(existing) => {
449            existing.push(completion);
450            true
451        }
452        None => {
453            waiters.insert(key.to_owned(), vec![completion]);
454            false
455        }
456    }
457}
458
459/// Pop and spawn every currently-schedulable request.
460fn schedule(
461    event_cache: &Weak<EventCacheInner>,
462    pending_requests: &mut BinaryHeap<PendingRequest>,
463    active_requests: &mut HashMap<OwnedRoomId, AbortOnDrop<()>>,
464    max_concurrent: usize,
465    sender: &mpsc::UnboundedSender<SchedulerEvent>,
466) {
467    for request in next_runnable(pending_requests, active_requests, max_concurrent) {
468        let key = (request.request.room_id.clone(), request.request.priority);
469
470        trace!(
471            room_id = %key.0,
472            priority = ?key.1,
473            active = active_requests.len(),
474            queued = pending_requests.len(),
475            "back-pagination scheduled"
476        );
477
478        let room_id = key.0.clone();
479        let event_cache = event_cache.clone();
480        let sender = sender.clone();
481        let task = spawn(async move {
482            let result = run_request(&event_cache, request.request, &request.token).await;
483            // The scheduler owns the completion senders (for coalescing), so hand it the
484            // result to fan out to every waiter for this key.
485            let _ = sender.send(SchedulerEvent::Finished(key, result));
486        });
487
488        active_requests.insert(room_id, task.abort_on_drop());
489    }
490}
491
492/// Pick the requests that can start right now, highest priority first: bounded
493/// by `max_concurrent` total in flight, and never two runs for the same room.
494///
495/// Requests popped but not yet runnable (their room is busy) are pushed back
496/// onto the heap.
497// Generic over the map's value type so the scheduling tests don't need a
498// runtime to build a task handle; only the keys matter here.
499fn next_runnable<T>(
500    pending_requests: &mut BinaryHeap<PendingRequest>,
501    active_requests: &HashMap<OwnedRoomId, T>,
502    max_concurrent: usize,
503) -> Vec<PendingRequest> {
504    let mut picked: Vec<PendingRequest> = Vec::new();
505    let mut skipped = Vec::new();
506
507    while active_requests.len() + picked.len() < max_concurrent {
508        let Some(request) = pending_requests.pop() else {
509            break;
510        };
511
512        let room_id = &request.request.room_id;
513        if active_requests.contains_key(room_id)
514            || picked.iter().any(|other| other.request.room_id == *room_id)
515        {
516            // This room is busy, try it again next round.
517            skipped.push(request);
518            continue;
519        }
520
521        picked.push(request);
522    }
523
524    pending_requests.extend(skipped);
525
526    picked
527}
528
529/// Back-paginate one room until its [`StopCondition`], the start of the
530/// timeline, the batch budget, or cancellation.
531#[instrument(skip_all, fields(room_id = %request.room_id, priority = ?request.priority))]
532async fn run_request(
533    event_cache: &Weak<EventCacheInner>,
534    mut request: BackPaginationRequest,
535    token: &CancellationToken,
536) -> BackPaginationRunResult {
537    // Cancelled while still queued, nothing to do.
538    if token.is_cancelled() {
539        return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
540    }
541
542    // Grab an owned `RoomPagination`, dropping the caches guard immediately so
543    // we don't hold the room lock across network paginations.
544    let pagination = {
545        let Some(inner) = event_cache.upgrade() else {
546            return BackPaginationRunResult { reason: BackPaginationStopReason::Cancelled };
547        };
548        match inner.all_caches_for_room(&request.room_id).await {
549            Ok(caches) => caches.room().pagination(),
550            Err(err) => {
551                warn!("no caches for room while back-paginating: {err}");
552                return BackPaginationRunResult { reason: BackPaginationStopReason::Failed };
553            }
554        }
555    };
556
557    let mut batches = 0usize;
558
559    let reason = loop {
560        if token.is_cancelled() {
561            break BackPaginationStopReason::Cancelled;
562        }
563
564        let outcome = match pagination.run_backwards_once(request.batch_size).await {
565            Ok(outcome) => outcome,
566            Err(err) => {
567                warn!("back-pagination failed: {err}");
568                break BackPaginationStopReason::Failed;
569            }
570        };
571
572        // Reaching the start of the timeline can still come with a last batch of
573        // events, so let the stop condition see it before ending the run.
574        if (request.stop)(&outcome).is_break() {
575            break BackPaginationStopReason::StopConditionMet;
576        }
577
578        if outcome.reached_start {
579            break BackPaginationStopReason::ReachedTimelineStart;
580        }
581
582        if outcome.events.is_empty() {
583            break BackPaginationStopReason::NoDataAvailable;
584        }
585
586        batches += 1;
587        if let Some(max) = request.max_batches
588            && batches >= max
589        {
590            break BackPaginationStopReason::BatchLimitReached;
591        }
592    };
593
594    debug!(?reason, "back-pagination run finished");
595
596    BackPaginationRunResult { reason }
597}
598
599#[cfg(all(test, not(target_arch = "wasm32")))]
600mod tests {
601    use std::{collections::HashMap, ops::ControlFlow};
602
603    use matrix_sdk_base::locks::Mutex;
604    use ruma::room_id;
605
606    use super::{
607        BackPaginationRequest, PendingRequest, Priority, cancellation_for, next_runnable,
608        try_coalesce,
609    };
610
611    /// Build a queued request for a room, at a priority, with an insertion seq.
612    fn queued(room_id: ruma::OwnedRoomId, priority: Priority, seq: u64) -> PendingRequest {
613        PendingRequest {
614            request: BackPaginationRequest {
615                room_id,
616                priority,
617                // Scheduling tests never evaluate the stop condition.
618                stop: Box::new(|_| ControlFlow::Continue(())),
619                batch_size: 10,
620                max_batches: None,
621            },
622            seq,
623            token: tokio_util::sync::CancellationToken::new(),
624        }
625    }
626
627    /// `next_runnable` serves highest priority first, then FIFO within a
628    /// priority.
629    #[test]
630    fn test_scheduling_priority_and_fifo() {
631        use std::collections::BinaryHeap;
632
633        let (a, b, c, d) = (room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e"), room_id!("!d:e"));
634
635        let mut pending_requests = BinaryHeap::new();
636        // Push out of priority order, with monotonic seqs.
637        pending_requests.push(queued(a.to_owned(), Priority::Low, 0));
638        pending_requests.push(queued(b.to_owned(), Priority::High, 1));
639        pending_requests.push(queued(c.to_owned(), Priority::Normal, 2));
640        pending_requests.push(queued(d.to_owned(), Priority::High, 3));
641
642        let active_requests: HashMap<_, ()> = HashMap::new();
643        let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
644            .into_iter()
645            .map(|r| r.request.room_id)
646            .collect();
647
648        // High first (b before d by FIFO), then Normal, then Low.
649        assert_eq!(picked, vec![b.to_owned(), d.to_owned(), c.to_owned(), a.to_owned()]);
650    }
651
652    /// `next_runnable` never returns more than `max_concurrent`.
653    #[test]
654    fn test_scheduling_respects_concurrency_cap() {
655        use std::collections::BinaryHeap;
656
657        let mut pending_requests = BinaryHeap::new();
658        for (i, room) in [room_id!("!a:e"), room_id!("!b:e"), room_id!("!c:e")].iter().enumerate() {
659            pending_requests.push(queued((*room).to_owned(), Priority::Normal, i as u64));
660        }
661
662        let active_requests: HashMap<_, ()> = HashMap::new();
663        let picked = next_runnable(&mut pending_requests, &active_requests, 2);
664
665        assert_eq!(picked.len(), 2);
666        // The third request stays queued.
667        assert_eq!(pending_requests.len(), 1);
668    }
669
670    /// `next_runnable` won't start a room that's already active, nor two runs
671    /// for the same room in one pass.
672    #[test]
673    fn test_scheduling_per_room_single_flight() {
674        use std::collections::BinaryHeap;
675
676        let (a, b) = (room_id!("!a:e"), room_id!("!b:e"));
677
678        // `a` is already running.
679        let active_requests = HashMap::from([(a.to_owned(), ())]);
680
681        let mut pending_requests = BinaryHeap::new();
682        pending_requests.push(queued(a.to_owned(), Priority::High, 0)); // same room as active
683        pending_requests.push(queued(a.to_owned(), Priority::High, 1)); // and again
684        pending_requests.push(queued(b.to_owned(), Priority::Low, 2)); // a different room
685
686        let picked: Vec<_> = next_runnable(&mut pending_requests, &active_requests, 10)
687            .into_iter()
688            .map(|r| r.request.room_id)
689            .collect();
690
691        // Only `b` runs; both `a` requests stay queued (a is busy).
692        assert_eq!(picked, vec![b.to_owned()]);
693        assert_eq!(pending_requests.len(), 2);
694    }
695
696    /// Every handle for a room + priority shares one cancellation, so a caller
697    /// dropping its handle can't cancel a run others are still waiting on.
698    #[test]
699    fn test_cancellation_is_shared_per_key() {
700        let cancellations = Mutex::new(HashMap::new());
701        let key = (room_id!("!a:e").to_owned(), Priority::Normal);
702
703        let (first_token, first_guard) = cancellation_for(&cancellations, key.clone());
704        let (second_token, second_guard) = cancellation_for(&cancellations, key.clone());
705
706        // One run, so one token for both callers.
707        assert!(!first_token.is_cancelled());
708        drop(first_guard);
709        assert!(!first_token.is_cancelled());
710        assert!(!second_token.is_cancelled());
711
712        // The last handle to go cancels the run.
713        drop(second_guard);
714        assert!(first_token.is_cancelled());
715        assert!(second_token.is_cancelled());
716
717        // Once they're all gone the key is stale, so the next caller gets a fresh
718        // token rather than an already-cancelled one.
719        let (third_token, _third_guard) = cancellation_for(&cancellations, key);
720        assert!(!third_token.is_cancelled());
721
722        // A different priority for the same room is a different run.
723        let other = (room_id!("!a:e").to_owned(), Priority::High);
724        let (other_token, other_guard) = cancellation_for(&cancellations, other);
725        drop(other_guard);
726        assert!(other_token.is_cancelled());
727        assert!(!third_token.is_cancelled());
728    }
729
730    /// The first request for a room + priority opens a new run; a later one at
731    /// the same key coalesces onto it (shares its waiter list); a different
732    /// priority for the same room opens its own run.
733    #[test]
734    fn test_coalescing() {
735        let a = room_id!("!a:e");
736        let mut waiters = HashMap::new();
737
738        let completion = || tokio::sync::oneshot::channel().0;
739        let normal = (a.to_owned(), Priority::Normal);
740        let high = (a.to_owned(), Priority::High);
741
742        // First request at (a, Normal): opens a new run.
743        assert!(!try_coalesce(&mut waiters, &normal, completion()));
744        assert_eq!(waiters[&normal].len(), 1);
745
746        // Second request at the same key: coalesces onto it.
747        assert!(try_coalesce(&mut waiters, &normal, completion()));
748        assert_eq!(waiters[&normal].len(), 2);
749
750        // Same room, different priority: a separate run, not a coalesce.
751        assert!(!try_coalesce(&mut waiters, &high, completion()));
752        assert_eq!(waiters.len(), 2);
753        assert_eq!(waiters[&high].len(), 1);
754    }
755}