bug: in-memory engine eviction controllers stall forever on dropped completion callbacks
Bug Report
Summary
RegionManager::evict_region accepts an on_evict_finished completion callback but silently drops it when the target region is not cached, is still loading, or is already being evicted. The two in-memory engine controllers that evict regions wait for exactly one callback per candidate over a bounded channel and never time out. When another eviction caller, such as the apply-side LoadEvictionObserver, evicts a candidate after the controller has collected its candidate list but before the controller calls evict_region on it, the callback never arrives, so rx.recv().await parks the controller forever. The parked controller never reaches complete_auto_load_and_evict or set_memory_checking(false), which leaves the checking_top_regions and memory_checking latches set and permanently disables automatic load/evict and memory-pressure eviction. The store recovers only after a restart.
What version of TiKV are you using?
I reproduced this on master at commit 7709ab9d738d16f856df990ad9ffb5c1908f84f8 (2026-09-29). Any build with the in-memory engine enabled that contains the same eviction and controller code is affected.
What operating system and CPU are you using?
Linux x86_64 with cargo +nightly-2026-03-21. The defect is a synchronization issue between the in-memory engine background checks and other eviction callers, so it does not depend on the OS or the CPU. It requires concurrency between those paths.
Steps to reproduce
- Enable the in-memory engine and cache several regions, so they are
Activeand appear incached_regions(). - Let a background controller collect its candidate list. Writes that reach the evict threshold schedule
MemoryCheckAndEvict, and the load/evict ticker schedulesTopRegionsLoadEvicteveryload-evict-interval. - Before the controller calls
evict_regionfor a candidate, let a competing eviction caller take that candidate. An ingest SST, a snapshot apply, a region merge, a follower change, a peer destroy, a manual removal of acache=alwaysrange, or a split is enough. The region moves toPendingEvictorEvicting, or it is removed from the cache. - The controller calls
evict_region(candidate, reason, Some(cb)). Since the candidate is no longerActive,do_evict_regionreturns beforemark_evictandcbis dropped. - The wait loop
for _ in 0..N { rx.recv().await }never receives the missing message, so the controller parks. Thechecking_top_regionsormemory_checkinglatch is never reset.
The unit test below forces the racing state deterministically. It first shows that a second eviction of an already Evicting region drops the callback, then pre-evicts every candidate and runs the real evict_on_evict_threshold_reached controller through the real RegionManager, and asserts that the controller does not return within 3 seconds.
cargo +nightly-2026-03-21 test -p in_memory_engine --lib \
ime_evict_callback_stall_poc -- --nocapturecomponents/in_memory_engine/src/region_stats.rs, inside the #[cfg(test)] pub mod tests module)#[cfg(test)]
mod ime_evict_callback_stall_poc {
use std::{
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
time::Duration,
};
use collections::HashMap;
use engine_traits::{CacheRegion, EvictReason, OnEvictFinishedCallback};
use parking_lot::Mutex;
use tikv_util::{
config::{ReadableSize, VersionTrack},
future::block_on_timeout,
worker::dummy_scheduler,
};
use super::{RegionInfoSimulator, new_cached_regions, new_region_stat};
use crate::{
InMemoryEngineConfig,
engine::SkiplistEngine,
memory_controller::MemoryController,
region_manager::{RegionManager, RegionState},
region_stats::RegionStatsManager,
test_util::new_region,
};
#[test]
fn test_second_evict_drops_completion_callback() {
let mgr = RegionManager::default();
let cache_region = CacheRegion::from_region(&new_region(1, b"k01", b"k02"));
mgr.new_region(cache_region.clone());
// First eviction turns the region `Evicting` and returns it as deletable.
assert_eq!(
mgr.evict_region(&cache_region, EvictReason::AutoEvict, None)
.len(),
1
);
// A competing evictor evicts the same region while it is still `Evicting`.
let invoked = Arc::new(AtomicBool::new(false));
let invoked2 = invoked.clone();
let cb: OnEvictFinishedCallback = Box::new(move || {
invoked2.store(true, Ordering::SeqCst);
Box::pin(async {})
});
assert!(
mgr.evict_region(&cache_region, EvictReason::AutoEvict, Some(cb))
.is_empty()
);
assert!(!invoked.load(Ordering::SeqCst));
assert_eq!(
mgr.regions_map()
.read()
.region_meta(cache_region.id)
.unwrap()
.get_state(),
RegionState::Evicting
);
}
#[test]
fn test_memory_eviction_check_parks_on_dropped_callback() {
let skiplist_engine = SkiplistEngine::new();
let mut config = InMemoryEngineConfig::config_for_test();
config.stop_load_threshold = Some(ReadableSize::kb(1));
let config = Arc::new(VersionTrack::new(config));
let mc = MemoryController::new(config.clone(), skiplist_engine);
let (scheduler, _rx) = dummy_scheduler();
let regions = vec![
new_region(1, b"k01", b"k02"),
new_region(2, b"k03", b"k04"),
new_region(3, b"k05", b"k06"),
new_region(4, b"k07", b"k08"),
new_region(5, b"k09", b"k10"),
new_region(6, b"k11", b"k12"),
];
let stats = vec![
new_region_stat(1, 100, 6),
new_region_stat(1, 10000, 1000),
new_region_stat(1, 100000, 100000),
new_region_stat(1, 100, 50),
new_region_stat(1, 1000, 120),
new_region_stat(1, 20, 2),
];
let top_regions = regions
.iter()
.cloned()
.zip(stats.iter().cloned())
.collect::<Vec<_>>();
let sim = Arc::new(RegionInfoSimulator {
regions: Mutex::new(Vec::new()),
region_stats: Mutex::new(HashMap::default()),
});
sim.set_top_regions(&top_regions);
sim.set_region_stats(&top_regions);
let rsm = RegionStatsManager::new(config.clone(), Duration::from_millis(10), sim);
let mgr = Arc::new(RegionManager::default());
for region in ®ions {
mgr.new_region(CacheRegion::from_region(region));
}
// Pre-evict every candidate, which is what a competing evictor does.
for region in ®ions {
let cache_region = CacheRegion::from_region(region);
assert_eq!(
mgr.evict_region(&cache_region, EvictReason::AutoEvict, None)
.len(),
1
);
}
let selected = Arc::new(AtomicUsize::new(0));
let selected2 = selected.clone();
let mgr2 = Arc::clone(&mgr);
let evict_fn = move |region: &CacheRegion,
reason: EvictReason,
cb: Option<OnEvictFinishedCallback>|
-> Vec<CacheRegion> {
selected2.fetch_add(1, Ordering::SeqCst);
mgr2.evict_region(region, reason, cb)
};
let fut = rsm.evict_on_evict_threshold_reached(
evict_fn,
&scheduler,
new_cached_regions(vec![1, 2, 3, 4, 5, 6]),
&mc,
);
assert!(block_on_timeout(fut, Duration::from_secs(3)).is_err());
assert!(selected.load(Ordering::SeqCst) >= 2);
}
}What did you expect?
The controllers should complete after the candidates are evicted, and the latches should be reset. A competing eviction of a candidate should not be able to park the background load/evict or memory-pressure check.
What did happened?
Both controllers park forever as soon as one candidate callback is dropped. checking_top_regions stays true, so every later TopRegionsLoadEvict tick returns early, and memory_checking stays true, so schedule_memory_check never schedules another check. Automatic load/evict stops, memory-pressure eviction stops, and the in-memory cache drains as writes evict one region at a time.
<user>@<host>:~/work/<project>$ cargo +nightly-2026-03-21 test -p in_memory_engine --lib ime_evict_callback_stall_poc -- --nocapture
Running unittests src/lib.rs (target/debug/deps/in_memory_engine-dfae04e9f70ae98a)
running 2 tests
test region_stats::tests::ime_evict_callback_stall_poc::test_second_evict_drops_completion_callback ... ok
test region_stats::tests::ime_evict_callback_stall_poc::test_memory_eviction_check_parks_on_dropped_callback ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 81 filtered out; finished in 3.01sThe first test shows that the callback is never invoked when the target is already Evicting. The second test finishes in 3.01 seconds, which is the block_on_timeout(3s) window, and it also asserts that the controller selected and evicted candidates before parking. On a build that guarantees the callback or bounds the wait, both assertions fail.
Root cause
The completion callback is a one-shot notification that evict_region may discard, while both controllers treat the number of received notifications as the number of completed evictions. The chain has five links. First, the callback is stored only when the target is Active. Second, a stored callback fires only when the eviction is later deleted. Third, the two background controllers wait for exactly one message per candidate and rely on that message to continue. Fourth, only the end of the parked task resets the latch that gates the next run. Fifth, other eviction callers run concurrently with the controllers and can move a candidate out of Active after the controller has already snapshotted its candidate list.
(1) evict_region documents a completion callback but drops it for non-active targets.
// components/in_memory_engine/src/region_manager.rs:858–902 (abridged)
// `cb` is called when the eviction of the region with id equaling to the id of
// `evict_region` has done.
// Note: `cb` should not do anything heavy.
pub(crate) fn evict_region(
&self,
evict_region: &CacheRegion,
evict_reason: EvictReason,
mut on_evict_finished: Option<OnEvictFinishedCallback>,
) -> Vec<CacheRegion> {
let mut regions_map = self.regions_map.write();
let mut evict_ids = vec![];
regions_map.on_all_overlapped_regions(evict_region, |meta| {
evict_ids.push(meta.region.id);
});
if evict_ids.is_empty() {
debug!("ime evict a region that is not cached";
"reason" => ?evict_reason,
"region" => ?evict_region);
return vec![];
}
// ...
for rid in evict_ids {
if let Some(region) = self.do_evict_region(
rid,
evict_region,
evict_reason,
&mut regions_map,
if rid == evict_region.id {
on_evict_finished.take()
} else {
None
},
) {
deletable_regions.push(region);
}
}
deletable_regions
}When the target id is absent from evict_ids, the loop never matches it and the callback is dropped when the function returns. When the id is present, the callback is handed to do_evict_region, which discards it on every path where the region is not Active:
// components/in_memory_engine/src/region_manager.rs:905–962 (abridged)
fn do_evict_region(
&self,
id: u64,
evict_region: &CacheRegion,
evict_reason: EvictReason,
regions_map: &mut RegionMetaMap,
on_evict_finished: Option<OnEvictFinishedCallback>,
) -> Option<CacheRegion> {
let meta = regions_map.mut_region_meta(id).unwrap();
let prev_state = meta.state;
// ...
if prev_state == RegionState::Pending {
let meta = regions_map.remove_region(id);
// ...
return None;
} else if prev_state.is_evict() {
info!("ime region already evicted";
"region" => ?meta.region, "state" => ?prev_state);
return None;
}
if prev_state == RegionState::Active {
meta.mark_evict(RegionState::PendingEvict, evict_reason, on_evict_finished);
} else {
meta.set_state(RegionState::LoadingCanceled)
};
// ...
}The is_evict predicate covers every intermediate state, including the PendingEvict and Evicting states that a competing eviction produces:
// components/in_memory_engine/src/region_manager.rs:71–74
pub fn is_evict(&self) -> bool {
use RegionState::*;
matches!(*self, LoadingCanceled | PendingEvict | Evicting)
}In production, a controller candidate that was Active when the candidate list was built can be PendingEvict, Evicting, or already removed by the time the controller reaches it. The callback is then dropped without any log or error.
(2) A callback fires only when it is stored on an Active region and the region is later deleted.
mark_evict stores the callback that the controllers rely on:
// components/in_memory_engine/src/region_manager.rs:234–249 (abridged)
pub(crate) fn mark_evict(
&mut self,
state: RegionState,
reason: EvictReason,
on_evict_finished: Option<OnEvictFinishedCallback>,
) {
// ...
self.set_state(state);
self.evict_info = Some(EvictInfo {
start: Instant::now_coarse(),
reason,
on_evict_finished,
});
}The stored callback runs only when the delete-range worker removes the region and calls on_delete_regions:
// components/in_memory_engine/src/region_manager.rs:964–995 (abridged)
pub fn on_delete_regions(&self, regions: &[CacheRegion]) {
let mut cbs = vec![];
{
let mut regions_map = self.regions_map.write();
for r in regions {
let meta = regions_map.remove_region(r.id);
// ...
let evict_info = meta.evict_info.unwrap();
// ...
if let Some(cb) = evict_info.on_evict_finished {
cbs.push(cb);
}
// ...
}
}
block_on(async {
for cb in cbs {
cb().await;
}
});
}The engine-level wrapper schedules that delete only for regions that evict_region returned as directly deletable:
// components/in_memory_engine/src/engine.rs:413–435 (abridged)
pub fn evict_region(
&self,
region: &CacheRegion,
evict_reason: EvictReason,
on_evict_finished: Option<OnEvictFinishedCallback>,
) {
let deletable_regions =
self.core
.region_manager
.evict_region(region, evict_reason, on_evict_finished);
if !deletable_regions.is_empty() {
if let Err(e) = self
.bg_worker_manager()
.schedule_task(BackgroundTask::DeleteRegions(deletable_regions))
{
// ...
}
}
}When a competing evictor already set the target to PendingEvict or Evicting, that target contributes no deletable region to this call, no delete task is scheduled for it, and the newly passed callback is gone. The earlier eviction eventually deletes the region and fires its own stored callback, but the controller is waiting on the callback from the later call.
(3) Both controllers wait for exactly one callback per candidate and never time out.
The auto load/evict controller builds its candidate list, evicts every candidate with a callback, and then waits for evict_count messages before it does any other work:
// components/in_memory_engine/src/background.rs:720–786 (abridged)
let (current_region_count, cached_regions) = {
let region_map = self.engine.region_manager().regions_map().read();
(region_map.regions().len(), region_map.cached_regions())
};
let (regions_to_load, regions_to_evict) = region_stats_manager
.collect_regions_to_load_and_evict(
current_region_count,
cached_regions,
&self.memory_controller,
);
let evict_count = regions_to_evict.len();
let mut regions_to_delete = Vec::with_capacity(evict_count);
// ...
let (tx, mut rx) = mpsc::channel(evict_count + 1);
for evict_region in regions_to_evict {
let cache_region = CacheRegion::from_region(&evict_region);
let tx_clone = tx.clone();
// Bound is set to 1 so that the sender side will not be blocked
let deletable_regions = self.engine.region_manager().evict_region(
&cache_region,
EvictReason::AutoEvict,
Some(Box::new(move || {
Box::pin(async move {
let _ = tx_clone.send(()).await;
})
})),
);
regions_to_delete.extend(deletable_regions);
}
// ...
for _ in 0..evict_count {
if rx.recv().await.is_none() {
break;
}
}
// ...
region_stats_manager.complete_auto_load_and_evict();The memory-pressure controller follows the same pattern per chunk of two candidates:
// components/in_memory_engine/src/region_stats.rs:324–417 (abridged)
pub(crate) async fn evict_on_evict_threshold_reached<F>(
&self,
mut evict_region: F,
delete_range_scheduler: &Scheduler<BackgroundTask>,
cached_regions: HashMap<u64, Arc<StdMutex<CopRequestsSma>>>,
memory_controller: &MemoryController,
) where
F: FnMut(&CacheRegion, EvictReason, Option<OnEvictFinishedCallback>) -> Vec<CacheRegion>,
{
let regions_activity = self.get_cached_region_stats(&cached_regions);
// ...
for regions in evict_candidates.chunks(2) {
let mut deletable_regions = vec![];
let (tx, mut rx) = mpsc::channel(3);
for r in regions {
// ...
let tx_clone = tx.clone();
deletable_regions.extend(evict_region(
&CacheRegion::from_region(r),
EvictReason::MemoryLimitReached,
Some(Box::new(move || {
Box::pin(async move {
let _ = tx_clone.send(()).await;
})
})),
));
self.handle_region_evicted(r);
}
// ...
for _ in 0..regions.len() {
// It's better to use `timeout(Duration, rx.recv())` but which needs to use
// tokio runtime with timer enabled while yatp does not.
if rx.recv().await.is_none() {
break;
}
}
if !memory_controller.reached_stop_load_threshold() {
return;
}
}
}Both channels are tokio::sync::mpsc channels. The original sender tx stays alive for the whole wait loop, so recv() can never return None; it returns only after a message arrives. There is no timeout and no completion tracking by region id. One missing message is therefore enough to park the task permanently.
The memory-pressure controller is scheduled by ordinary writes that reach the evict threshold or the capacity limit, and its caller resets the latch only after the await completes:
// components/in_memory_engine/src/background.rs:1157–1194 (abridged)
let task = async move {
if let Some(region_stats_manager) = &core.region_stats_manager {
let cached_region_ids = core
.engine
.region_manager
.regions_mSource: tikv/tikv