tikv_util: use-after-free in `mpsc::future` when a sender and the receiver are dropped concurrently
Bug Report
What version of TiKV are you using?
TiKV 9.0.0-beta.2 at commit 115edc6e14a6a3bd88e0dfc603686d8bbb5848c8 (2026-09-23), with the workspace pinning nightly-2026-01-30. The affected crate is tikv_util (components/tikv_util, publish = false), module mpsc::future, and the two Drop implementations discussed below are still unchanged on the current default branch.
What operating system and CPU are you using?
Linux x86_64 with 32 logical CPUs, rustc nightly-2026-03-21, and AddressSanitizer enabled through -Zsanitizer=address for the x86_64-unknown-linux-gnu target. Because the defect is a race, the reproduction oversubscribes the machine on purpose, running four threads per logical CPU; on a machine with fewer CPUs the same failure is expected, although it may take more attempts, and the F1_PAIRS and F1_SECONDS environment variables of the test control that effort.
Steps to reproduce
The reproduction is a single integration test that can be pasted without changes. No TiKV source file is modified.
- Save the source from the first collapsible block below as
components/tikv_util/tests/f1_future_channel_drop_uaf.rs. Cargo discoverstests/*.rsautomatically, so neitherCargo.tomlnor any module declaration has to change. - Run the test under AddressSanitizer, with a fresh target directory and the
-Cunsafe-allow-abi-mismatch=sanitizerescape hatch that keepssanitizer_mixerrors from blocking the build when instrumented Rust code is linked against uninstrumented dependency units:
CARGO_TARGET_DIR=target/asan \
RUSTFLAGS="-Zsanitizer=address -Cunsafe-allow-abi-mismatch=sanitizer" \
cargo +nightly-2026-03-21 test --target x86_64-unknown-linux-gnu \
-p tikv_util --test f1_future_channel_drop_uaf -- --include-ignored --nocapture --test-threads=1- AddressSanitizer aborts at the first invalid access and prints the report reproduced in the next section.
Two details of the invocation deserve a note. First, --include-ignored is required, because the failing test registers a waker in the channel before dropping the receiver, which is the state the production path reaches most of the time (see Root cause), and that test loop is ignored by default so that an ordinary cargo test stays fast. Second, the same file contains a control test that exercises both sequential drop orders and is expected to pass; in our run the sanitizer aborted the process during the first racing test, so only the racing test was exercised, and running the control separately is worthwhile if a green baseline is wanted.
components/tikv_util/tests/f1_future_channel_drop_uaf.rs (safe Rust, no unsafe)//! PoC: `tikv_util::mpsc::future` endpoint teardown use-after-free.
//!
//! Integration location: `components/tikv_util/tests/f1_future_channel_drop_uaf.rs`
//! (paste as-is; Cargo auto-discovers `tests/*.rs`, no `Cargo.toml` / source change).
//!
//! Defect:
//! `Sender::drop` (components/tikv_util/src/mpsc/future.rs:126-141) decrements `liveness`
//! with `fetch_sub(SENDER_COUNT_BASE)`; when the decrement observed
//! `SENDER_COUNT_BASE | RECEIVER_COUNT_BASE` (last sender + receiver still
//! counted) it still calls `queue.waker.wake()`, that is, it dereferences the
//! `Queue` allocation.
//! `Receiver::drop` (components/tikv_util/src/mpsc/future.rs:194-207) decrements `liveness`
//! with `fetch_sub(RECEIVER_COUNT_BASE)` and frees the very same allocation
//! via `Box::from_raw` as soon as its decrement observed
//! `RECEIVER_COUNT_BASE` (no sender left).
//! Both endpoints are `Send`/`Sync` (future.rs:143-144, 209), so two threads may drop the last
//! sender and the receiver at the same time: the sender's `wake()` then touches memory that the
//! receiver has already handed back to the allocator.
//!
//! This is the `oneshot`/RUSTSEC-2026-0005 cancellation shape (consumer task cancelled while the
//! producer side goes away) on TiKV's own future channel.
//!
//! The PoC is *detection* oriented: a hit is reported by the sanitizer (ASan: `heap-use-after-free`,
//! TSan: race with the deallocation, Miri: access to a freed allocation), which aborts the process.
//! Without a sanitizer the loop is expected to finish silently; an unobserved race is not a
//! state where no bug exists. The invocation used for the result below appears in the issue body.
//!
//! Knobs: `F1_PAIRS` (racing channel pairs, default 2*cores), `F1_ITERS` (per-pair sender drops,
//! 0 = unbounded), `F1_SECONDS` (wall-clock cap, 0 = unbounded).
use std::{
hint::spin_loop,
pin::Pin,
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering},
},
task::Context,
thread,
time::{Duration, Instant},
};
use futures::{stream::Stream, task::noop_waker};
use tikv_util::mpsc::future::{Receiver, WakePolicy, unbounded};
/// One racing channel pair. The sender thread creates a fresh channel per iteration and hands the
/// receiver to the receiver thread, so both endpoints are dropped "at the same moment".
struct Pair {
rx_slot: Mutex<Option<Receiver<u64>>>,
/// receiver -> sender: "I own the receiver and I am one step away from dropping it".
ready: AtomicU64,
/// sender -> receiver: "I am dropping the sender right now".
go: AtomicU64,
iters: AtomicU64,
stop: AtomicBool,
/// Poll the receiver once before dropping it (registers a waker in the channel).
warm: bool,
}
impl Pair {
fn new(warm: bool) -> Arc<Self> {
Arc::new(Self {
rx_slot: Mutex::new(None),
ready: AtomicU64::new(0),
go: AtomicU64::new(0),
iters: AtomicU64::new(0),
stop: AtomicBool::new(false),
warm,
})
}
}
/// Creates the channel, hands `Receiver` over, waits until the other side is ready, then drops the
/// `Sender` (this is the access that races with `Receiver::drop`).
fn sender_loop(pair: Arc<Pair>) {
let mut ready_seen = 0u64;
loop {
if pair.stop.load(Ordering::Relaxed) {
return;
}
let (tx, rx) = unbounded::<u64>(WakePolicy::Immediately);
*pair.rx_slot.lock().unwrap() = Some(rx);
while pair.ready.load(Ordering::Acquire) == ready_seen {
if pair.stop.load(Ordering::Relaxed) {
return;
}
spin_loop();
}
ready_seen = pair.ready.load(Ordering::Acquire);
// Publish "go" and drop the sender. `ready`/`go` give the sender the earlier
// modification order on `liveness`, which is the interleaving that reaches
// `prev == SENDER_COUNT_BASE | RECEIVER_COUNT_BASE` and therefore the `wake()`.
pair.go.fetch_add(1, Ordering::Release);
drop(tx);
pair.iters.fetch_add(1, Ordering::Relaxed);
}
}
/// Owns the `Receiver` and drops it concurrently with the sender's drop.
fn receiver_loop(pair: Arc<Pair>) {
let mut go_seen = 0u64;
loop {
let mut rx = loop {
if let Some(rx) = pair.rx_slot.lock().unwrap().take() {
break rx;
}
if pair.stop.load(Ordering::Relaxed) {
return;
}
spin_loop();
};
if pair.warm {
// Secondary variant: register a waker and make this core own the channel's
// `AtomicWaker` cache line, so the sender's post-free touch must snoop it.
let waker = noop_waker();
let mut cx = Context::from_waker(&waker);
let _ = Pin::new(&mut rx).poll_next(&mut cx);
}
pair.ready.fetch_add(1, Ordering::Release);
while pair.go.load(Ordering::Acquire) == go_seen {
if pair.stop.load(Ordering::Relaxed) {
return;
}
spin_loop();
}
go_seen = pair.go.load(Ordering::Acquire);
drop(rx);
}
}
fn cpus() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4)
}
/// Default number of racing pairs: 4 threads per core (over-subscription is what produces the
/// scheduler preemption points the race needs).
fn default_pairs() -> usize {
(2 * cpus()).min(64)
}
fn env_usize(key: &str, default: usize) -> usize {
std::env::var(key)
.ok()
.and_then(|v| v.trim().parse().ok())
.unwrap_or(default)
}
fn env_u64(key: &str, default: u64) -> u64 {
std::env::var(key)
.ok()
.and_then(|v| v.trim().parse().ok())
.unwrap_or(default)
}
/// `F1_PAIRS=0` (or unset) means "pick a default based on the core count".
fn pairs_from_env() -> usize {
let n = env_usize("F1_PAIRS", 0);
if n == 0 { default_pairs() } else { n }
}
fn human(v: u64) -> String {
if v == 0 {
"unbounded".to_owned()
} else {
v.to_string()
}
}
/// Runs the racing loops until the iteration / wall-clock budget is exhausted.
fn run_race(name: &str, pairs: usize, warm: bool, iters_per_pair: u64, seconds: u64) -> u64 {
eprintln!(
"[F1] {name}: pairs={pairs} ({} threads), iters/pair={}, seconds={}",
pairs * 2,
human(iters_per_pair),
human(seconds),
);
let all: Vec<Arc<Pair>> = (0..pairs).map(|_| Pair::new(warm)).collect();
let mut handles = Vec::with_capacity(pairs * 2);
for p in &all {
let p = Arc::clone(p);
handles.push(thread::spawn(move || sender_loop(p)));
}
for p in &all {
let p = Arc::clone(p);
handles.push(thread::spawn(move || receiver_loop(p)));
}
let start = Instant::now();
let deadline = if seconds == 0 {
None
} else {
Some(start + Duration::from_secs(seconds))
};
let mut last_report = 0u64;
loop {
if seconds == 0 {
thread::yield_now();
} else {
thread::sleep(Duration::from_millis(250));
}
let total: u64 = all.iter().map(|p| p.iters.load(Ordering::Relaxed)).sum();
let elapsed = start.elapsed().as_secs_f64();
if elapsed >= 1.0 && total != last_report {
eprintln!("[F1] {name}: {total} racing drops in {elapsed:.1}s");
last_report = total;
}
let time_up = deadline.is_some_and(|d| Instant::now() >= d);
let iters_up = iters_per_pair != 0
&& all
.iter()
.all(|p| p.iters.load(Ordering::Relaxed) >= iters_per_pair);
if time_up || iters_up {
for p in &all {
p.stop.store(true, Ordering::Release);
}
for h in handles {
let _ = h.join();
}
return total;
}
}
}
fn report(name: &str, total: u64) {
eprintln!("[F1] {name}: {total} racing drops finished with no sanitizer report.");
eprintln!(
"[F1] {name}: a silent run only means this interleaving was not observed; run under \
ASan/TSan/Miri (see PoC/README-F1-PoC.md)."
);
}
/// Control: the sequential drop orders are the intended usage and never race.
#[test]
fn f1_control_sequential_endpoint_drop_stays_inside_queue_lifetime() {
for _ in 0..1_000 {
let (tx, rx) = unbounded::<u64>(WakePolicy::Immediately);
assert!(tx.send(7).is_ok());
drop(tx); // last sender: wakes the queue but does not free it
let mut rx = rx;
assert_eq!(rx.try_recv().ok(), Some(7));
drop(rx); // frees the queue, sender is already gone
}
for _ in 0..1_000 {
let (tx, rx) = unbounded::<u64>(WakePolicy::Immediately);
drop(rx); // receiver first: does not free the queue
assert!(tx.send(8).is_err());
drop(tx); // last sender: frees the queue, no wake path
}
eprintln!("[F1] control: sequential teardown never touched the queue after it was freed");
}
/// Main PoC: concurrent teardown of the last sender and the receiver.
#[test]
fn f1_concurrent_endpoint_drop_wakes_the_freed_queue() {
const NAME: &str = "concurrent-drop";
let pairs = pairs_from_env();
let iters = env_u64("F1_ITERS", 0);
let seconds = env_u64("F1_SECONDS", 20);
let total = run_race(NAME, pairs, false, iters, seconds);
report(NAME, total);
}
/// Secondary variant: the receiver registers a waker before dropping, biasing the sender's
/// now-dangling `AtomicWaker` touch towards a cache snoop.
#[test]
#[ignore = "secondary teardown variant; run explicitly"]
fn f1_concurrent_drop_with_registered_waker() {
const NAME: &str = "concurrent-drop-warm";
let pairs = pairs_from_env();
let iters = env_u64("F1_ITERS", 0);
let seconds = env_u64("F1_SECONDS", 20);
let total = run_race(NAME, pairs, true, iters, seconds);
report(NAME, total);
}
/// Small variant for `cargo miri test -- --ignored ...` (Miri is orders of magnitude slower).
#[test]
#[ignore = "run under `cargo miri test` (small iteration budget)"]
fn f1_miri_small_concurrent_drop() {
const NAME: &str = "miri-small";
let n = env_usize("F1_PAIRS", 0);
let pairs = if n == 0 { 2 } else { n };
let iters = env_u64("F1_ITERS", 512);
let seconds = env_u64("F1_SECONDS", 0);
let total = run_race(NAME, pairs, true, iters, seconds);
report(NAME, total);
}What did you expect?
Dropping the two endpoints of a channel from two different threads should be safe, and that is what the public API advertises: Sender is Send, Sync, and Clone, while Receiver is Send, and neither the module documentation nor the type documentation imposes any ordering between the two drops. Concretely, the last Sender to be dropped is expected either to wake a receiver that is still alive or to release the channel, and never to touch memory that has already been returned to the allocator.
What did happened?
AddressSanitizer reports a heap use-after-free whose writer is the channel's own wake path and whose released allocation is the channel itself; the excerpt below preserves the frame names and omits the numeric addresses, which the complete log keeps:
==...==ERROR: AddressSanitizer: heap-use-after-free on address 0x...
WRITE of size 8 at 0x... thread T2
#0 <core::sync::atomic::Atomic<usize>>::fetch_or
#1 <futures_core::task::__internal::atomic_waker::AtomicWaker>::take
#2 <futures_core::task::__internal::atomic_waker::AtomicWaker>::wake
#3 <tikv_util::mpsc::future::Sender<u64> as core::ops::drop::Drop>::drop
freed by thread T66 here:
#0 free
#1 <std::alloc::System as core::alloc::global::GlobalAlloc>::dealloc
#2 <tikv_util::mpsc::future::Receiver<u64> as core::ops::drop::Drop>::drop
previously allocated by thread T2 here:
#3 tikv_util::mpsc::future::unbounded::<u64>
SUMMARY: AddressSanitizer: heap-use-after-free in <core::sync::atomic::Atomic<usize>>::fetch_orAll three stacks agree with the sequence derived below: Sender::drop reaches AtomicWaker::wake on a Queue that Receiver::drop has already released. The failing test is the first test that the harness executes, and the log contains no progress heartbeat, which the test prints once per second, so the race was reached within roughly the first second of the loop rather than after many attempts; the pairs=64 (128 threads) line records the deliberate oversubscription that produces the preemption points.
Two properties of the report are worth spelling out. First, AddressSanitizer stops at the first invalid access, which is the update of the atomic state inside AtomicWaker::take(); had execution continued, the same call would read the Option<Waker> cell from the released allocation and invoke the function pointer stored there, because a waker had been registered. Second, the released 512-byte block is the Queue that with_queue allocates and hands to both endpoints, which identifies the allocation beyond doubt.
The complete and unmodified AddressSanitizer log follows. Only local paths and the shell prompt were normalized to /path/to/tikv and $.
$ CARGO_TARGET_DIR=target/asan \
RUSTFLAGS="-Zsanitizer=address -Cunsafe-allow-abi-mismatch=sanitizer" \
cargo +nightly-2026-03-21 test --target x86_64-unknown-linux-gnu \
-p tikv_util --test f1_future_channel_drop_uaf -- --include-ignored --nocapture --test-threads=1
warning: feature `core_intrinsics` is declared but not used
--> components/tikv_alloc/src/lib.rs:88:12
|
88 | #![feature(core_intrinsics)]
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_features)]` (part of `#[warn(unused)]`) on by default
warning: `tikv_alloc` (lib) generated 1 warning
warning: feature `box_patterns` is declared but not used
--> components/tikv_util/src/lib.rs:5:12
|
5 | #![feature(box_patterns)]
| ^^^^^^^^^^^^
|
= note: `#[warn(unused_features)]` (part of `#[warn(unused)]`) on by default
warning: `tikv_util` (lib) generated 1 warning
Finished `test` profile [unoptimized] target(s) in 0.31s
warning: the following packages contain code that will be rejected by a future version of Rust: nom v2.2.1
note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1`
Running tests/f1_future_channel_drop_uaf.rs (target/asan/x86_64-unknown-linux-gnu/debug/deps/f1_future_channel_drop_uaf-a86801499f6ad79a)
running 4 tests
test f1_concurrent_drop_with_registered_waker ... [F1] concurrent-drop-warm: pairs=64 (128 threads), iters/pair=unbounded, seconds=20
=================================================================
==3209238==ERROR: AddressSanitizer: heap-use-after-free on address 0x74c7fac47e10 at pc 0x5652a3d465f3 bp 0x7367f76e4450 sp 0x7367f76e4448
WRITE of size 8 at 0x74c7fac47e10 thread T2
#0 0x5652a3d465f2 in <core::sync::atomic::Atomic<usize>>::fetch_or futures_core.2288ae7f68f01bc8-cgu.01
#1 0x5652a3d452e8 in <futures_core::task::__internal::atomic_waker::AtomicWaker>::take (/path/to/tikv/target/asan/x86_64-unknown-linux-gnu/debug/deps/f1_future_channel_drop_uaf-a86801499f6ad79a+0x3af2e8) (BuildId: fb68254c38c526ec41695de9aeec429557fb6b2d)
#2 0x5652a3d454e9 in <futures_core::task::__internal::atomic_waker::AtomicWaker>::wake (/path/to/tikv/target/asan/x86_64-unknown-linux-gnu/debug/deps/f1_future_channel_drop_uaf-a86801499f6ad79a+0x3af4e9) (BuildId: fb68254c38c526ec41695de9aeec429557fb6b2d)
#3 0x5652a3cd56d1 in <tikv_util::mpsc::future::Sender<u64> as core::ops::drop::Drop>::drop 518foe8fho6pvdz9i5myvl5i8
#4 0x5652a3cd4bf5 in core::ptr::drop_in_place::<tikv_util::mpsc::future::Sender<u64>> 518foe8fho6pvdz9i5myvl5i8
#5 0x5652a3cda30a in core::mem::drop::<tikv_util::mpsc::future::Sender<u64>> a1oqebjua34dp7sdfj5sd0qd2
#6 0x5652a3cd1340 in f1_future_channel_drop_uaf::sender_loop 11z2j8xhchaxs5kstg3sqyl18
#7 0x5652a3cdca35 in f1_future_channel_drop_uaf::run_race::{closure#1} a85q8bsnk5qz1y1x5yv2s0g4u
#8 0x5652a3cd83f5 in std::sys::backtrace::__rust_begin_short_backtrace::<f1_future_channel_drop_uaf::run_race::{closure#1}, ()> 7rxim5n7h5ss3e2jzf15logqj
#9 0x5652a3ce1c21 in std::thread::lifecycle::spawn_unchecked::<f1_future_channel_drop_uaf::run_race::{closure#1}, ()>::{closure#1}::{closure#0} bzonj600erb11b20u885cgw8i
#10 0x5652a3cd0bfd in <core::panic::unwind_safe::AssertUnwindSafe<std::thread::lifecycle::spawn_unchecked<f1_future_channel_drop_uaf::run_race::{closure#1}, ()>::{closure#1}::{closure#0}> as core::ops::function::FnOnce<()>>::call_once 0x20oawyslymgwsscw4w27p0p
#11 0x5652a3cd8618 in std::panicking::catch_unwind::do_call::<core::panic::unwind_safe::Source: tikv/tikv