`quickwit-search` and `quickwit-indexing`: cancellation of a polled `oneshot` receiver can free the channel while a producer still sends
Describe the bug
Quickwit retrieves hit documents and executes index merges through asynchronous futures supplied by Tantivy, which builds them on the oneshot channel crate. Whenever such a future is cancelled after having been polled at least once, the receiver is dropped while the producer thread may still be completing its send. Inside oneshot 0.1.13 and 0.2.1, both of which are resolved by the pinned dependency graph, that interleaving reaches a race in which the receiver frees the channel before the sender has finished its final state transition. The sender then performs an atomic write on the released allocation and, on a different interleaving, reads a Waker from it. AddressSanitizer reports the first case as heap-use-after-free, with a one-byte write inside oneshot::sender::Sender::send.
The cancellation is ordinary control flow rather than an exceptional or unsafe operation. A REST or gRPC search request that is dropped when the client disconnects or times out cancels the document fetch stage; a single split that fails causes try_collect to return early and to cancel the sibling fetches of the same batch; an indexer that is killed during shutdown or pipeline replacement cancels an in-flight merge. None of these events requires a malformed request or a violated contract, and no input value participates in the trigger.
Two production chains are affected:
- Document retrieval.
fetch_docsinstalls a rayon thread pool as the Tantivy search executor, and every hit is fetched throughSearcher::doc_async, which reachesStoreReader::read_block_async. Decompression is dispatched withExecutor::spawn_blocking, whose future wraps aoneshot::Receiver, and the blocking task sends its result from a rayon thread. - Index merge.
MergeExecutorawaitsIndexWriter::merge, which returns aFutureResultthat is likewise backed by aoneshot::Receiver; the segment updater sends the outcome from its own thread.
The race is present in oneshot 0.2.1, the version resolved by quickwit-indexing, and the same destructor protocol is shared by the 0.1.x line, which Tantivy resolves to 0.1.13. The confirmed consequence is a heap use-after-free that can corrupt the allocator or terminate the process, and the sender's subsequent read of the waker makes control flow dependent on freed bytes.
Root Cause
The oneshot channel is a single-producer, single-consumer object that keeps its state, its message, and at most one waker inside a single heap allocation. The endpoint that frees that allocation is determined by the state value observed through atomic read-modify-write operations, and the handover between a waiting receiver and a sending producer is split across two steps. The receiver installs a waker and moves the state to RECEIVING when it is polled. The sender, upon observing RECEIVING, moves the state to UNPARKING, takes the waker, and then publishes the final state, which is MESSAGE for send and DISCONNECTED for Sender::drop.
The receiver's destructor is expected to wait while that handover is in progress. It performs that wait in the UNPARKING arm, as shown below (oneshot 0.2.1, src/receiver.rs:825-903; the 0.1.x Receiver::drop implements the same protocol):
#[cfg(feature = "async")]
impl<T> Drop for AsyncReceiver<T> {
fn drop(&mut self) {
let channel = unsafe { self.channel_ptr.as_ref() };
// If this receiver was previously polled, but was not polled to completion, then the
// channel is in the RECEIVING state and with a waker written. ...
if channel.state().load(Relaxed) == RECEIVING
&& channel
.state()
.compare_exchange(RECEIVING, EMPTY, Relaxed, Relaxed)
.is_ok()
{
// SAFETY: The RECEIVING state guarantees we have written a waker.
unsafe { channel.drop_waker() };
}
// Set the channel state to disconnected and read what state the channel was in
// ORDERING: Release is required so that in the states where the sender becomes responsible
// for deallocating the channel, they can synchronize with this final state swap store from
// us. ...
match channel.state().swap(DISCONNECTED, AcqRel) {
// The sender has not sent anything, nor is it dropped. The sender is responsible for
// deallocating the channel.
EMPTY => (),
// The sender already sent something. We must drop the message, and free the channel.
MESSAGE => {
unsafe { channel.drop_message() };
unsafe { dealloc(self.channel_ptr) };
}
// The sender was already dropped. We are responsible for freeing the channel.
DISCONNECTED => {
unsafe { dealloc(self.channel_ptr) };
}
// This receiver was previously polled. The channel must have been in the RECEIVING
// state. But the sender has observed the RECEIVING state and is currently reading the
// waker to wake us up. We need to loop here until we observe the MESSAGE or
// DISCONNECTED state. ...
UNPARKING => {
loop {
hint::spin_loop();
// ORDERING: The state swap above has already synchronized with the write of
// the message. Here we only need to observe the actual state change.
match channel.state().load(Relaxed) {
MESSAGE => {
unsafe { channel.drop_message() };
break;
}
DISCONNECTED => break,
UNPARKING => (),
_ => unreachable!(),
}
}
// ORDERING: We need to synchronize with the sender's final write of the state. ...
fence(Acquire);
// SAFETY: Happens-before relationship with the sender's final write of the state
// is established with the acquire fence above.
unsafe { dealloc(self.channel_ptr) };
}
_ => unreachable!(),
}
}
}The defect lies in the UNPARKING arm. The swap(DISCONNECTED, AcqRel) that selects this arm has already stored DISCONNECTED; the wait loop therefore cannot distinguish that value, which the receiver itself just published, from a value written by the sender. The sender, however, never writes DISCONNECTED on this path; both Sender::send and Sender::drop leave UNPARKING by publishing their own final state, as the sending side of the handover shows (oneshot 0.2.1, src/sender.rs:104-154):
// Set the state to signal there is a message on the channel.
// ORDERING: we need release ordering to allow the receiver to synchronize with our write
// of the message (and with our final write of the state, in the case where the receiver
// becomes responsible for freeing the channel.) ...
//
// EMPTY + 1 = MESSAGE
// RECEIVING + 1 = UNPARKING
// DISCONNECTED + 1 = invalid, however this state is never observed
match channel.state().fetch_add(1, AcqRel) {
// The receiver is alive and has not started waiting. Send done.
EMPTY => Ok(()),
// The receiver is waiting. Wake it up so it can return the message.
// We transitioned into the UNPARKING state. ...
RECEIVING => {
// Take the waker, but critically do not unpark it. ...
// SAFETY: at this point we are in the UNPARKING state, and the receiving thread
// does not access the waker while in this state, nor does it free the channel
// allocation in this state. ...
let waker = unsafe { channel.take_waker() };
// ORDERING: this ordering serves two-fold: ...
// We do not need to observe and act on the state that was replaced here.
// in the UNPARKING state, the receiver must just wait for us to set a final state
channel.state().swap(MESSAGE, AcqRel);
// Note: it is possible that between the store above and this statement
// the receiving thread is spuriously unparked, takes the message, and frees
// the channel. ...
waker.unpark();
Ok(())
}
// The receiver was already dropped. The `SendError` is responsible for freeing the
// channel.
DISCONNECTED => Err(unsafe { SendError::new(channel_ptr) }),
_ => unreachable!(),
}The allocation is released through a plain Box::from_raw, so the premature free is immediately visible to the allocator (oneshot 0.2.1, src/lib.rs:209-212):
#[inline]
pub(crate) unsafe fn dealloc<T>(channel: NonNull<Channel<T>>) {
// SAFETY: Method guarantee that the pointer is valid and points to a Channel<T>.
drop(unsafe { Box::from_raw(channel.as_ptr()) });
}The failing interleaving is short and does not depend on any input:
- The receiver is polled once, so a waker is installed and the state is
RECEIVING. - The producer starts
send, moves the state fromRECEIVINGtoUNPARKING, and removes the waker. - The receiver is cancelled, and its destructor swaps the state to
DISCONNECTED, observingUNPARKING. The wait loop then readsDISCONNECTED, that is, the value written by the destructor itself, concludes that the producer has finished, and frees the allocation. - The producer publishes
MESSAGEwithchannel.state().swap(MESSAGE, AcqRel), writing to the freed allocation.
The Sender::drop path is symmetric: it moves RECEIVING to UNPARKING, takes the waker, and publishes DISCONNECTED, so the same premature free occurs before that final write.
How Quickwit reaches the window: document retrieval
quickwit/quickwit-search/src/fetch_docs.rs:177-180 replaces the default Tantivy search executor with a rayon thread pool for the split that is being queried:
// we add an executor here, we could add it in open_index_with_caches, though we should verify
// the side-effect before
let tantivy_executor = quickwit_common::thread_pool::get_underlying_rayon_thread_pool().into();
index.set_executor(tantivy_executor);Every hit is then fetched asynchronously (quickwit/quickwit-search/src/fetch_docs.rs:197-204):
async move {
let doc: TantivyDocument = moved_searcher
.doc_async(global_doc_addr.doc_addr)
.await
.context("searcher-doc-async")?;
...
}and the per-split futures are driven with a concurrency limit, so an early error or an external cancellation drops the futures that are still in flight (quickwit/quickwit-search/src/fetch_docs.rs:246-251):
futures::stream::iter(doc_futures)
.buffer_unordered(NUM_CONCURRENT_REQUESTS)
.try_collect::<Vec<_>>()
.awaitNUM_CONCURRENT_REQUESTS is 30. Tantivy resolves the executor and the store reader as follows (quickwit-oss/tantivy at e229de6db748c6b21747a99a18220446e76104e1, src/core/searcher.rs:106-115):
/// Fetches a document in an asynchronous manner.
#[cfg(feature = "quickwit")]
pub async fn doc_async<D: DocumentDeserialize>(
&self,
doc_address: DocAddress,
) -> crate::Result<D> {
let executor = self.inner.index.search_executor();
let store_reader = &self.inner.store_readers[doc_address.segment_ord as usize];
store_reader.get_async(doc_address.doc_id, executor).await
}Decompression is the point at which the oneshot channel is created (quickwit-oss/tantivy, src/store/reader.rs:388-415):
async fn read_block_async(
&self,
checkpoint: &Checkpoint,
executor: &Executor,
) -> io::Result<Block> {
let cache_key = checkpoint.byte_range.start;
if let Some(block) = self.cache.get_from_cache(checkpoint.byte_range.start) {
return Ok(block);
}
let compressed_block = self
.data
.slice(checkpoint.byte_range.clone())
.read_bytes_async()
.await?;
let decompressor = self.decompressor;
let maybe_decompressed_block = executor
.spawn_blocking(move || decompressor.decompress(compressed_block.as_ref()))
.await
.expect("decompression panicked");
let decompressed_block = OwnedBytes::new(maybe_decompressed_block?);
self.cache
.put_into_cache(cache_key, decompressed_block.clone());
Ok(decompressed_block)
}Executor::spawn_blocking is the async primitive under examination (quickwit-oss/tantivy, src/core/executor.rs:107-129):
/// Spawn a task on the pool, returning a future completing on task success.
///
/// If the task panics, returns `Err(())`.
#[cfg(feature = "quickwit")]
#[allow(clippy::result_unit_err)] // `Err(())` only signals a panic; no error info to convey.
pub fn spawn_blocking<T: Send + 'static>(
&self,
cpu_intensive_task: impl FnOnce() -> T + Send + 'static,
) -> impl std::future::Future<Output = Result<T, ()>> {
match self {
Executor::SingleThread => Either::Left(std::future::ready(Ok(cpu_intensive_task()))),
Executor::ThreadPool(pool) => {
let (sender, receiver) = oneshot::channel();
pool.spawn(|| {
if sender.is_closed() {
return;
}
let task_result = cpu_intensive_task();
let _ = sender.send(task_result);
});
let res = receiver.map(|res| res.map_err(|_| ()));
Either::Right(res)
}
}
}Two details are worth emphasizing. First, the future returned to the caller is a oneshot::Receiver combinator, so polling it polls the receiver and dropping it drops the receiver. Second, the sender.is_closed() guard narrows the window but does not remove it: the guard is evaluated before the CPU-bound task starts, whereas the send occurs after the task returns, which leaves the entire task duration as the interval during which a cancellation can race the final send.
How Quickwit reaches the window: index merge
quickwit/quickwit-indexing/src/actors/merge_executor.rs:543 opens an IndexWriter on the union directory, and line 588 awaits the merge:
let mut index_writer: IndexWriter = union_index.writer_with_num_threads(1, 15_000_000)?;
...
debug!(segment_ids=?segment_ids,"merging-segments");
// TODO it would be nice if tantivy could let us run the merge in the current thread.
index_writer.merge(&segment_ids).await?;Tantivy returns a FutureResult from that call (quickwit-oss/tantivy, src/indexer/index_writer.rs:531-540):
/// Merges a given list of segments.
///
/// If all segments are empty no new segment will be created.
///
/// `segment_ids` is required to be non-empty.
pub fn merge(&mut self, segment_ids: &[SegmentId]) -> FutureResult<Option<SegmentMeta>> {
let merge_operation = self.segment_updater.make_merge_operation(segment_ids);
let segment_updater = self.segment_updater.clone();
segment_updater.start_merge(merge_operation)
}FutureResult is a thin handle over a oneshot::Receiver whose completion arrives from the segment updater thread (quickwit-oss/tantivy, src/future_result.rs:17-27 and 67-91):
pub struct FutureResult<T> {
inner: Inner<T>,
}
enum Inner<T> {
FailedBeforeStart(Option<TantivyError>),
InProgress {
receiver: oneshot::Receiver<crate::Result<T>>,
error_msg_if_failure: &'static str,
},
}impl<T> Future for FutureResult<T> {
type Output = crate::Result<T>;
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
unsafe {
match &mut Pin::get_unchecked_mut(self).inner {
Inner::FailedBeforeStart(err) => Poll::Ready(Err(err.take().unwrap())),
Inner::InProgress {
receiver,
error_msg_if_failure,
} => match Future::poll(Pin::new_unchecked(receiver), cx) {
Poll::Ready(oneshot_res) => {
let res = oneshot_res.unwrap_or_else(|_| {
Err(crate::TantivyError::SystemError(
error_msg_if_failure.to_string(),
))
});
Poll::Ready(res)
}
Poll::Pending => Poll::Pending,
},
}
}
}
}Its documentation states the intended contract, namely that dropping the handle does not cancel the task being executed. The handle is nevertheless a future that may be polled and then dropped, which is exactly the sequence that the destructor mishandles. A merge can remain in flight for seconds or minutes, so an actor kill is likely to arrive while the FutureResult is suspended.
Dependency resolution
The affected versions enter through two independent edges. The workspace declares the direct dependency as oneshot = { version = "0.2", features = ["async", "std"] }, which resolves to 0.2.1, and quickwit-indexing consumes it in the Kafka source. Tantivy 0.27.0, pinned at revision e229de6db748c6b21747a99a18220446e76104e1, depends on oneshot 0.1.13, which reaches the search and merge paths shown above.
# quickwit/Cargo.toml
oneshot = { version = "0.2", features = ["async", "std"] }
# quickwit/quickwit-indexing/Cargo.toml
oneshot = { workspace = true }Suggested fix
Within Quickwit, the most direct mitigation is to move to a fixed oneshot release as soon as one is published, and to align Tantivy's requirement at the same time. Should a fixed release not be available, the two call sites can be decoupled from the vulnerable primitive without changing their observable behaviour: the decompression step can run on spawn_blocking through a handle that is joined rather than through a future that owns a receiver, and the merge can be driven by a completion handle whose receiver is retained until completion. A third option is to vendor a patched oneshot through [patch.crates-io] while a corrected release is being prepared.
At the dependency level, the wait condition in the destructor should keep waiting while either UNPARKING or the receiver's own DISCONNECTED value is observed, or the final state should not be published until the producer has finished. Publishing corrected 0.1.x and 0.2.x releases, and updating the Tantivy requirement, would remove the exposure for every consumer of the library.
Regression coverage is currently absent in both repositories. A test that polls the receiver once and then drops it concurrently with a send, executed under AddressSanitizer or ThreadSanitizer, reproduces the failure in under a second; the reproducer below is such a test and can be adapted directly. Adding the trigger to the existing cancellation tests for fetch_docs and for the merge executor would guard the Quickwit level as well.
Steps to reproduce (if applicable)
- Save the reproducer below as
quickwit/quickwit-indexing/tests/f1_oneshot_cancel_uaf.rs. Thetests/directory does not exist and is discovered automatically, so no manifest change and no source change are required. - Run the sanitiz
Source: quickwit-oss/quickwit