Cancelled search requests remain in SearchQueue and can cause spurious TooManySearchRequests

Author: YZL0v3ZZCreated Jul 13, 2026Updated Sep 27, 2026
Labelsrustbug

Describe the bug

SearchQueue::try_get_search_permit transfers a oneshot::Sender<Permit> to the search scheduler and then awaits the corresponding receiver. If the request future is cancelled after the scheduler has accepted that sender but before a permit is delivered, cancellation drops the receiver while the scheduler continues to retain the sender in its bounded Vec queue.

The scheduler does not prune closed oneshot senders before using queue.len() for capacity enforcement, random eviction, waiter selection, or the searches_waiting metric. A request that no longer exists can therefore continue to consume a queue slot and participate in admission decisions.

The vulnerable transition is:

request creates (Sender<Permit>, Receiver<Permit>)
    -> Sender is transferred to SearchQueue::run
    -> scheduler stores Sender in queue
    -> request is cancelled while awaiting Receiver<Permit>
    -> Receiver is dropped
    -> scheduler retains the now-closed Sender
    -> stale entry remains counted in queue.len()

This can produce user-visible effects when the queue is under load:

  • a live request can be randomly evicted and receive TooManySearchRequests while a cancelled waiter remains in the queue;
  • a released permit can first be delivered to a closed receiver, adding an unnecessary scheduling turn before live work proceeds;
  • searches_waiting can report cancelled requests as live pending work.

For example, with parallelism = 1 and capacity = 2, request A can hold the running permit, cancelled request B can remain as a stale waiter, and live request C can occupy the second apparent slot. When request D arrives, the scheduler sees a full queue and randomly removes either B or C. If it removes C, a live request is rejected while the cancelled B remains admitted.

All source links below are pinned to commit fff2ef5a42658b16a937d922aabc3fb7f89f2018.

  1. try_get_search_permit sends the waiter ticket to the scheduler before awaiting the receiver: crates/meilisearch/src/search_queue.rs#L177-L183
rust
let (sender, receiver) = oneshot::channel();
self.sender.send(sender).await.map_err(|_| MeilisearchHttpError::SearchLimiterIsDown)?;
let permit = receiver
    .await
    .map_err(|_| MeilisearchHttpError::TooManySearchRequests(self.capacity))?;

Once self.sender.send(sender).await completes, the scheduler independently owns the sender. Cancelling the caller at or before receiver.await drops only the receiver; there is no cancellation guard that removes the transferred sender.

  1. The scheduler retains these senders in a plain Vec and uses its raw length for capacity and metrics: crates/meilisearch/src/search_queue.rs#L121-L171
rust
let mut queue: Vec<oneshot::Sender<Permit>> = Default::default();

// ...

} else if queue.len() >= capacity {
    let remove = rng.gen_range(0..queue.len());
    let thing = queue.swap_remove(remove);
    drop(thing);
}
queue.push(search_request);

// ...

metric_searches_waiting.store(queue.len(), Ordering::Relaxed);

There is no Sender::is_closed() check or other cancellation-aware removal before queue.len() controls admission.

  1. Permit delivery also selects directly from the same population without skipping closed receivers in the same scheduler turn: crates/meilisearch/src/search_queue.rs#L131-L138
rust
_ = search_finished.recv() => {
    searches_running = searches_running.saturating_sub(1);
    if !queue.is_empty() {
        let remove = rng.gen_range(0..queue.len());
        let channel = queue.swap_remove(remove);
        let _ = channel.send(Permit { sender: sender.clone() });
    }
},

If the selected receiver was cancelled, send fails. The stale entry has already affected queue length, eviction, selection, and metrics before that failure reveals it.

  1. This wait occurs directly in HTTP request paths, including normal search, multi-search, and facet search:

A disconnected client, upstream timeout, or cancelled request handler can therefore reach this window while waiting for search admission.

To Reproduce

The following focused whitebox test intentionally asserts the current bad state. Therefore, the test passing means the stale-waiter state is reachable. It does not use sleeps or depend on the scheduler's random eviction choice.

Steps:

  1. Append the test-only module below to crates/meilisearch/src/search_queue.rs.
  2. Run the targeted unit-test command.
  3. Observe that the task waiting for a permit is successfully cancelled, but searches_waiting() remains 1 afterward.
Full whitebox test code
rust
#[cfg(test)]
mod cancellation_tests {
    use super::*;

    #[tokio::test(flavor = "current_thread")]
    async fn cancelled_permit_waiter_remains_counted_in_search_queue() {
        let queue = Arc::new(SearchQueue::new(1, NonZeroUsize::new(1).unwrap()));

        // Saturate the only running-search slot so the next request must wait.
        let active_permit = queue
            .try_get_search_permit()
            .await
            .expect("the first request should receive a permit");
        assert_eq!(queue.searches_waiting(), 0);

        let waiting_queue = Arc::clone(&queue);
        let waiting_task = tokio::spawn(async move {
            waiting_queue.try_get_search_permit().await
        });

        // This is the acceptance point: the scheduler has stored the sender in
        // its private queue and published the corresponding queue length.
        tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                if queue.searches_waiting() == 1 {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("the waiter should be accepted by the scheduler");
        assert!(
            !waiting_task.is_finished(),
            "the accepted waiter should still be awaiting its permit"
        );

        // The request future is cancelled while it awaits the permit. This
        // drops its receiver, but the scheduler already owns the sender.
        waiting_task.abort();
        let cancellation = waiting_task
            .await
            .expect_err("aborting the waiter should cancel its task");
        assert!(cancellation.is_cancelled());

        // Bug-existence assertion: dropping the receiver does not remove the
        // sender from the scheduler queue, so the cancelled waiter remains a
        // counted capacity slot after cancellation.
        assert_eq!(queue.searches_waiting(), 1);

        drop(active_permit);
    }
}

Targeted command, run from the repository root:

bash
cargo +1.91.1 test -p meilisearch --lib cancelled_permit_waiter_remains_counted_in_search_queue -- --nocapture

Observed result:

Finished `test` profile [unoptimized + debuginfo] target(s) in 4m 04s
     Running unittests src/lib.rs (target/debug/deps/meilisearch-1dba1b807c17282b)

running 1 test
test search_queue::cancellation_tests::cancelled_permit_waiter_remains_counted_in_search_queue ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 14 filtered out; finished in 0.00s

Why a passing test reproduces the bug:

  1. The first permit saturates the only running-search slot, establishing that the queue is initially healthy and empty.
  2. The test waits until searches_waiting() == 1. In the current implementation this metric is published from queue.len(), so this confirms that the scheduler has received and stored the second request's sender.
  3. !waiting_task.is_finished() confirms that the corresponding caller is still pending on permit delivery rather than having completed normally.
  4. waiting_task.abort() cancels that real request future, and JoinError::is_cancelled() confirms the cancellation edge fired. Dropping the task also drops its oneshot receiver.
  5. The final searches_waiting() == 1 is the violated property: the request future no longer exists, but its transferred sender remains represented as a pending queue slot.

The timeout only guards against a deadlocked test. The transition itself is coordinated by the scheduler's published queue length, not by wall-clock sleeping or probabilistic scheduling.

Expected behavior

Once a caller waiting for a permit is cancelled, its queue entry should no longer participate in live admission state. In particular:

  • closed/cancelled waiters should be removed or ignored before queue.len() is used for capacity enforcement or eviction;
  • searches_waiting should count only live waiters;
  • permit delivery should skip closed receivers and continue selecting live waiters without making stale tickets compete with them;
  • a live request should not receive TooManySearchRequests merely because a queue slot is occupied by a cancelled request.

A useful invariant is:

queue capacity, eviction, metrics, and permit selection operate only on live waiters

Meilisearch version

  • Workspace version: 1.50.0
  • Audited and reproduced commit: fff2ef5a42658b16a937d922aabc3fb7f89f2018
  • Branch: main

Additional context

This is a cancellation-correctness issue in the admission protocol, not an issue with search execution after a permit has already been obtained. The normal later permit.drop().await path cannot clean up a request cancelled before permit delivery because that request never receives a Permit.

It is also separate from any potential double-notification concern involving Permit::drop(self) and Drop for Permit. This report requires neither obtaining a permit nor explicitly releasing one for the cancelled waiter. The defect is specifically:

cancel before permit delivery
    -> receiver disappears
    -> scheduler retains the transferred wait ticket

A possible repair direction is to prune oneshot::Senders whose receivers are closed before capacity and eviction decisions, and to skip closed senders while dispatching permits. The exact fix should preserve a stronger invariant across every scheduler turn: stale entries must not affect capacity, fairness, metrics, or liveness, even if they are retained briefly as implementation details.

The whitebox reproduction was run as a Rust unit test on Linux and requires no running Meilisearch server, index, client, or external service.