#20131·tikv

bug: in-memory engine deadlocks on concurrent region cache snapshot drops

Author: YZL0v3ZZCreated Oct 1, 2026Updated Oct 1, 2026
Labelstype/bugcontribution

Summary

RegionManager::remove_region_snapshot acquires historical_regions and a region's region_snapshot_list in opposite orders on its fast and slow paths. Two concurrent snapshot drops that take different paths can deadlock on the same pair of mutexes. Both threads then hold regions_map.read() forever, which stops every region load, eviction, split, and delete in the in-memory engine.

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 region manager code is affected.

What operating system and CPU are you using?

Linux x86_64 with cargo +nightly-2026-03-21. The defect is a lock-order inversion, so it does not depend on the OS or the CPU.

Steps to reproduce

The deadlock requires an in-memory engine region that holds a live snapshot while it is split, plus a split child that holds a live snapshot while it is evicted.

  1. Enable the in-memory engine and cache a region B.
  2. Serve a read on B so that its snapshot list is non-empty, then split B. The split keeps B in historical_regions and inserts the split children into regions_map.
  3. Serve a read on a split child M that overlaps B, then evict M. M stays in PendingEvict because it still holds a live snapshot and overlaps the historical B.
  4. Drop the last snapshot of B (slow path) and the snapshot of M (fast path) concurrently.

The unit test below forces this interleaving deterministically. It holds B's snapshot list so that the slow path parks right after it takes historical_regions, starts the fast path on M, and then releases B's list.

bash
cargo +nightly-2026-03-21 test -p in_memory_engine --lib \
  test_remove_region_snapshot_lock_order_deadlock -- --nocapture
Deterministic PoC test (paste into components/in_memory_engine/src/region_manager.rs, inside the #[cfg(test)] mod tests module)
rust
#[cfg(test)]
mod ime_snapshot_lock_order_poc {
    use std::{
        sync::{
            mpsc::{channel, RecvTimeoutError},
            Arc,
        },
        thread,
        time::{Duration, Instant},
    };

    use engine_traits::{CacheRegion, EvictReason};

    use super::*;
    use crate::read::RegionCacheSnapshotMeta;

    fn wait_until(mut cond: impl FnMut() -> bool, timeout: Duration) -> bool {
        let start = Instant::now();
        while start.elapsed() < timeout {
            if cond() {
                return true;
            }
            thread::yield_now();
        }
        false
    }

    fn snapshot_list_held(mgr: &RegionManager, region_id: u64) -> bool {
        let regions = mgr.regions_map.read();
        let meta = regions.region_meta(region_id).expect("region exists");
        meta.region_snapshot_list().try_lock().is_err()
    }

    #[test]
    fn test_remove_region_snapshot_lock_order_deadlock() {
        let mgr = Arc::new(RegionManager::default());

        // Cache B with one live snapshot, then split B. B moves to historical_regions.
        let b = CacheRegion::new(1, 0, b"k00".to_vec(), b"k10".to_vec());
        mgr.new_region(b.clone());
        mgr.region_snapshot(1, 0, 8).unwrap();
        let m = CacheRegion::new(2, 1, b"k03".to_vec(), b"k06".to_vec());
        mgr.split_region(
            &b,
            vec![
                CacheRegion::new(3, 1, b"k00".to_vec(), b"k03".to_vec()),
                m.clone(),
                CacheRegion::new(4, 1, b"k06".to_vec(), b"k10".to_vec()),
            ],
        );

        // Read M, then evict it. It stays PendingEvict while the snapshot is live.
        mgr.region_snapshot(2, 1, 10).unwrap();
        mgr.evict_region(&m, EvictReason::AutoEvict, None);
        {
            let regions = mgr.regions_map.read();
            assert_eq!(
                regions.region_meta(2).unwrap().get_state(),
                RegionState::PendingEvict
            );
        }

        let snap_b = RegionCacheSnapshotMeta::new(b.clone(), 8, 1);
        let snap_m = RegionCacheSnapshotMeta::new(m.clone(), 10, 2);

        // Hold B's snapshot list so the slow path parks after taking historical_regions.
        let hist_key = KeyAndVersion(b.end.clone(), b.epoch_version);
        let hist_snap: &std::sync::Mutex<SnapshotList> = {
            let historical = mgr.historical_regions.lock().unwrap();
            let meta = historical
                .get(&hist_key)
                .expect("B must be in historical_regions");
            // SAFETY: mgr outlives the guard. The slow path must acquire this
            // mutex before it can remove the entry.
            unsafe { &*(meta.region_snapshot_list() as *const _) }
        };
        let hist_guard = hist_snap.lock().unwrap();

        let (done_tx, done_rx) = channel::<()>();

        // Slow path: takes historical_regions, parks on B's snapshot list.
        let mgr2 = Arc::clone(&mgr);
        let done2 = done_tx.clone();
        let t2 = thread::spawn(move || {
            mgr2.remove_region_snapshot(&snap_b);
            let _ = done2.send(());
        });
        assert!(wait_until(
            || mgr.historical_regions.try_lock().is_err(),
            Duration::from_secs(1)
        ));

        // Fast path: takes M's snapshot list, parks on historical_regions.
        let mgr3 = Arc::clone(&mgr);
        let done3 = done_tx.clone();
        let t1 = thread::spawn(move || {
            mgr3.remove_region_snapshot(&snap_m);
            let _ = done3.send(());
        });
        assert!(wait_until(
            || snapshot_list_held(&mgr, 2),
            Duration::from_secs(1)
        ));

        // Release B's list: the slow path needs M's list, which the fast path holds.
        drop(hist_guard);

        let deadlocked = matches!(
            done_rx.recv_timeout(Duration::from_secs(3)),
            Err(RecvTimeoutError::Timeout)
        );
        assert!(deadlocked, "expected the lock-order inversion to deadlock");
        assert!(mgr.historical_regions.try_lock().is_err());
        assert!(snapshot_list_held(&mgr, 2));
        drop((t1, t2));
    }
}

What did you expect?

Both snapshot drops return, and the in-memory engine keeps loading and evicting regions.

What did happened?

Both calls block forever. historical_regions and M's snapshot list stay locked, so later snapshot drops and every writer that needs regions_map.write() block as well. The in-memory engine stops making progress until the process restarts.

Test output (the test passes because it detects the deadlock)
<user>@<host>:~/work/<project>$ cargo +nightly-2026-03-21 test -p in_memory_engine --lib test_remove_region_snapshot_lock_order_deadlock -- --nocapture
     Running unittests src/lib.rs (target/debug/deps/in_memory_engine-dfae04e9f70ae98a)

running 1 test
test region_manager::tests::ime_snapshot_lock_order_poc::test_remove_region_snapshot_lock_order_deadlock ... ok

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

The test waits 3 seconds for either drop to return, neither does, and both mutexes remain locked. On a build with a corrected lock order, the same assertion fails.

Root cause

historical_regions, regions_map, and each region_snapshot_list are std::sync::Mutex or parking_lot::RwLock, so an inverted acquisition order is fatal. The chain has four links: a region can hold a snapshot while it is pending eviction, a split moves a source region with live snapshots into historical_regions, the two snapshot-drop paths take the two mutexes in opposite orders, and both deadlocked threads hold regions_map.read().

(1) A region can hold a live snapshot while it stays in PendingEvict.

rust
// components/in_memory_engine/src/region_manager.rs:210–221
fn validate_update_region_state(&self, new_state: RegionState) -> bool {
    use RegionState::*;
    let valid_new_states: &[RegionState] = match self.state {
        Pending => &[Loading],
        Loading => &[Active, LoadingCanceled, Evicting],
        Active => &[PendingEvict],
        LoadingCanceled => &[PendingEvict, Evicting],
        PendingEvict => &[Evicting],
        Evicting => &[],
    };
    valid_new_states.contains(&new_state)
}
rust
// components/in_memory_engine/src/region_manager.rs:698–718 (abridged)
let regions_map = self.regions_map.read();
let Some(meta) = regions_map.region_meta(region_id) else {
    return Err(FailedReason::NotCached);
};
if meta.state != RegionState::Active {
    return Err(FailedReason::NotCached);
}
if meta.region.epoch_version != region_epoch {
    return Err(FailedReason::EpochNotMatch);
}
if read_ts <= meta.safe_point {
    return Err(FailedReason::TooOldRead);
}
meta.region_snapshot_list
    .lock()
    .unwrap()
    .new_snapshot(read_ts);
rust
// components/in_memory_engine/src/region_manager.rs:802–812
fn region_ready_to_evict(
    meta: &CacheRegionMeta,
    snapshot_list: &SnapshotList,
    historical_regions: &BTreeMap<KeyAndVersion, CacheRegionMeta>,
) -> bool {
    if meta.state != RegionState::PendingEvict {
        return false;
    }
    snapshot_list.is_empty()
        && !Self::overlaps_with_historical_regions(&meta.region, historical_regions)
}

Eviction moves an Active region to PendingEvict, and a non-empty snapshot list keeps it there. A historical region that overlaps it keeps it there as well.

(2) A split keeps a source region with live snapshots in historical_regions.

rust
// components/in_memory_engine/src/region_manager.rs:1064–1073
let snapshot_empty = region_meta.region_snapshot_list.lock().unwrap().is_empty();
if !snapshot_empty {
    self.historical_regions.lock().unwrap().insert(
        KeyAndVersion(
            region_meta.region.end.clone(),
            region_meta.region.epoch_version,
        ),
        region_meta,
    );
}

(3) Snapshot drops run concurrently from the read path.

Every read that uses the in-memory engine takes a RegionCacheSnapshot, and the snapshot releases the region entry when the request finishes.

rust
// components/hybrid_engine/src/observer/snapshot.rs:89–100 (abridged)
fn on_snapshot(&self, region: &Region, read_ts: u64, sequence_number: u64) -> Box<dyn ObservedSnapshot> {
    let region = CacheRegion::from_region(region);
    let snap = Some(self.cache_engine.snapshot(region, read_ts, sequence_number));
    Box::new(RegionCacheSnapshotPin { snap })
}
rust
// components/in_memory_engine/src/read.rs:92–98
impl Drop for RegionCacheSnapshot {
    fn drop(&mut self) {
        let regions_removable = self
            .engine
            .core
            .region_manager
            .remove_region_snapshot(&self.snapshot_meta);
        // ...
    }
}

(4) The fast path takes a region's snapshot list before historical_regions, while the slow path takes them in the opposite order.

rust
// components/in_memory_engine/src/region_manager.rs:731–753 (abridged)
let regions_map = self.regions_map.read();
if let Some(region_meta) = regions_map.region_meta(snapshot_meta.region.id)
    && region_meta.region.epoch_version == snapshot_meta.region.epoch_version
{
    let mut snapshot_list = region_meta.region_snapshot_list.lock().unwrap();
    snapshot_list.remove_snapshot(snapshot_meta.snapshot_ts);
    if Self::region_ready_to_evict(
        region_meta,
        &snapshot_list,
        &self.historical_regions.lock().unwrap(),
    ) {
        // ...
    }
    return vec![];
}
rust
// components/in_memory_engine/src/region_manager.rs:756–784 (abridged)
let mut historical_regions = self.historical_regions.lock().unwrap();
let meta = historical_regions.get_mut(&hist_key).unwrap();
let mut snapshot_list = meta.region_snapshot_list.lock().unwrap();
snapshot_list.remove_snapshot(snapshot_meta.snapshot_ts);
if snapshot_list.is_empty() {
    drop(snapshot_list);
    historical_regions.remove(&hist_key).unwrap();
    regions_map.iter_overlapped_regions(&snapshot_meta.region, |meta| {
        if matches!(
            meta.get_state(),
            RegionState::PendingEvict | RegionState::Evicting
        ) {
            assert_eq!(meta.get_state(), RegionState::PendingEvict);
            let snap_list = meta.region_snapshot_list.lock().unwrap();
            if Self::region_ready_to_evict(meta, &snap_list, &historical_regions) {
                // ...
            }
        }
        true
    });
    // ...
}

The slow path holds historical_regions across iter_overlapped_regions and locks the snapshot list of every overlapped region that is pending eviction. The lock orders at the four call sites are:

Call site Lock order
remove_region_snapshot, fast path (region_manager.rs:731–753) region_snapshot_list → historical_regions
remove_region_snapshot, slow path (region_manager.rs:756–784) historical_regions → other region's region_snapshot_list
do_evict_region (region_manager.rs:952–959) region_snapshot_list → historical_regions
split_region (region_manager.rs:1066–1068) region_snapshot_list → historical_regions

With the state from steps 1 to 4 above, the two drops interleave as follows.

T1 (fast path, drops M's snapshot):  holds M.region_snapshot_list → waits for historical_regions
T2 (slow path, drops B's snapshot):  holds historical_regions      → waits for M.region_snapshot_list

T1 blocks at region_manager.rs:742 and T2 blocks at region_manager.rs:778. Neither thread can release its first mutex, so the cycle is permanent.

(5) The deadlock freezes the rest of the engine.

Both threads acquire regions_map.read() at region_manager.rs:731 and never release it. Any writer (evict_region, load_region, split_region, and on_delete_regions) then blocks on regions_map.write().

rust
// components/in_memory_engine/src/region_manager.rs:861–872 (abridged)
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);
    });
    // ...
}

parking_lot::RwLock blocks new readers while a writer waits, so new region_snapshot calls queue behind the blocked writers as well.