Cancelled search requests remain in SearchQueue and can cause spurious TooManySearchRequests
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
TooManySearchRequestswhile 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_waitingcan 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.
try_get_search_permitsends the waiter ticket to the scheduler before awaiting the receiver:crates/meilisearch/src/search_queue.rs#L177-L183
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.
- The scheduler retains these senders in a plain
Vecand uses its raw length for capacity and metrics:crates/meilisearch/src/search_queue.rs#L121-L171
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.
- 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
_ = 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.
- This wait occurs directly in HTTP request paths, including normal search, multi-search, and facet search:
crates/meilisearch/src/routes/indexes/search.rs#L543-L559crates/meilisearch/src/routes/multi_search.rs#L157-L196crates/meilisearch/src/routes/indexes/facet_search.rs#L292-L336
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:
- Append the test-only module below to
crates/meilisearch/src/search_queue.rs. - Run the targeted unit-test command.
- Observe that the task waiting for a permit is successfully cancelled, but
searches_waiting()remains1afterward.
#[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:
cargo +1.91.1 test -p meilisearch --lib cancelled_permit_waiter_remains_counted_in_search_queue -- --nocaptureObserved 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.00sWhy a passing test reproduces the bug:
- The first permit saturates the only running-search slot, establishing that the queue is initially healthy and empty.
- The test waits until
searches_waiting() == 1. In the current implementation this metric is published fromqueue.len(), so this confirms that the scheduler has received and stored the second request's sender. !waiting_task.is_finished()confirms that the corresponding caller is still pending on permit delivery rather than having completed normally.waiting_task.abort()cancels that real request future, andJoinError::is_cancelled()confirms the cancellation edge fired. Dropping the task also drops its oneshot receiver.- The final
searches_waiting() == 1is 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_waitingshould 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
TooManySearchRequestsmerely 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 waitersMeilisearch 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 ticketA 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.
Source: meilisearch/meilisearch