#20119·tikv

storage: unsound Send/Sync impl for StorageConfigManger permits a data race from safe code

Author: YZL0v3ZZCreated Sep 26, 2026Updated Sep 26, 2026
Labelstype/bugcontribution

Bug Report

What version of TiKV are you using?

TiKV 9.0.0-beta.2 at commit 115edc6e14a6a3bd88e0dfc603686d8bbb5848c8, the snapshot against which the defect was reproduced (2026-09-23). The affected file is src/storage/config_manager.rs in the root tikv package, where the struct is declared at line 24 and the two unsafe impl blocks sit at lines 32 and 33. While this report was being prepared, the same unbounded implementations were still present on the default branch, so the defect is not an artifact of the pinned snapshot, and neither implementation carries a SAFETY comment that would record the intended precondition.

What operating system and CPU are you using?

Linux x86_64 with 32 logical CPUs, rustc nightly-2026-03-21, targeting x86_64-unknown-linux-gnu. The verdict rests on ThreadSanitizer (-Zsanitizer=thread), which is the only one of the three applicable sanitizers that can decide a plain data race: AddressSanitizer does not observe the racing accesses, since neither access is invalid on its own, and Miri cannot execute the PoC, since the PoC constructs a storage engine and several thread pools through RocksDB and yatp.

Steps to reproduce

The reproduction is a single integration test that can be pasted without changes. No TiKV source file is modified.

  1. Save the source from the first collapsible block below as components/test_storage/tests/f3_storage_config_manager_unsound_send_sync.rs. The test_storage package declares no [[test]] entries, so autotests discovers the file automatically, and its existing dependencies already include tikv, tikv_util, and api_version.

  2. Run the control test, which must pass, and which compiles only because the unsafe impl blocks are unbounded:

bash
cargo +nightly-2026-03-21 test -p test_storage \
  --test f3_storage_config_manager_unsound_send_sync -- --nocapture --test-threads=1
  1. Run the two ignored tests under ThreadSanitizer, which reports the data race and exits with status 66:
bash
CARGO_TARGET_DIR=target/tsan \
RUSTFLAGS="-Zsanitizer=thread -Cunsafe-allow-abi-mismatch=sanitizer" \
  cargo +nightly-2026-03-21 test --target x86_64-unknown-linux-gnu \
  -p test_storage --test f3_storage_config_manager_unsound_send_sync \
  -- --ignored --nocapture --test-threads=1

Two details of the invocation deserve a note. First, the -Cunsafe-allow-abi-mismatch=sanitizer flag together with a fresh CARGO_TARGET_DIR keeps the instrumented build from failing when it links against uninstrumented dependency units. Second, the run emits a large number of warnings that belong to the harness rather than to the defect, because the process uses jemalloc as its global allocator and because the test starts and stops yatp pools; the decisive report is the only one whose 24-byte allocation is created by the PoC itself and whose two stacks both belong to the PoC, and it is quoted below.

Complete PoC source: paste as components/test_storage/tests/f3_storage_config_manager_unsound_send_sync.rs (safe Rust, no unsafe)
rust
//! F3 PoC: `StorageConfigManger` declares `Send + Sync` for every `K` while
//! `K` has no thread-safety bound (`src/storage/config_manager.rs:32-33`).
//!
//! `K: ConfigurableDb` is ordinary safe code, so a handle built on `Rc`
//! (`!Send + !Sync`) can be moved to another thread through safe APIs and used
//! there while the original thread still uses it -> data race (and, on the
//! shared `Rc` refcount, potential double-free / use-after-free).
//!
//! Integration location:
//!   `components/test_storage/tests/f3_storage_config_manager_unsound_send_sync.rs`
//!
//!   cargo +nightly-2026-03-21 test -p test_storage \
//!     --test f3_storage_config_manager_unsound_send_sync -- --nocapture --test-threads=1
//!
//! TSan (Linux; primary verdict):
//!   CARGO_TARGET_DIR=target/tsan \
//!   RUSTFLAGS="-Zsanitizer=thread -Cunsafe-allow-abi-mismatch=sanitizer" \
//!     cargo +nightly-2026-03-21 test --target x86_64-unknown-linux-gnu \
//!     -p test_storage --test f3_storage_config_manager_unsound_send_sync \
//!     -- --ignored --nocapture --test-threads=1

use std::{
    cell::Cell,
    rc::Rc,
    sync::{Arc, Barrier},
    thread,
    time::{Duration, Instant},
};

use api_version::ApiV1;
use tikv::{
    config::{ConfigController, ConfigRes, ConfigurableDb, Module, TikvConfig},
    server::ttl::TtlCheckerTask,
    storage::{
        Storage, TestStorageBuilder,
        config_manager::StorageConfigManger,
        kv::RocksEngine,
        lock_manager::MockLockManager,
        txn::flow_controller::{EngineFlowController, FlowController},
    },
};
use tikv_util::worker::dummy_scheduler;

/// A `ConfigurableDb` handle built on `Rc`: `!Send + !Sync`. The public trait
/// has no thread-safety bounds, so this implementation is safe code.
struct RcDb(Rc<Cell<usize>>);

impl ConfigurableDb for RcDb {
    fn set_db_config(&self, _: &[(&str, &str)]) -> ConfigRes {
        Ok(())
    }
    fn set_cf_config(&self, _: &str, _: &[(&str, &str)]) -> ConfigRes {
        Ok(())
    }
    fn set_rate_bytes_per_sec(&self, _: i64) -> ConfigRes {
        Ok(())
    }
    fn set_rate_limiter_auto_tuned(&self, _: bool) -> ConfigRes {
        Ok(())
    }
    fn set_flush_size(&self, _: usize) -> ConfigRes {
        Ok(())
    }
    fn set_cf_flush_size(&self, _: &str, _: usize) -> ConfigRes {
        Ok(())
    }
    fn set_flush_oldest_first(&self, _: bool) -> ConfigRes {
        Ok(())
    }
    fn set_shared_block_cache_capacity(&self, capacity: usize) -> ConfigRes {
        // Non-atomic write into the shared handle; this is what the config
        // dispatch path does for `storage.block-cache.capacity`.
        self.0.set(capacity);
        Ok(())
    }
    fn set_high_priority_background_threads(&self, _: i32, _: bool) -> ConfigRes {
        Ok(())
    }
}

type TestStorage = Storage<RocksEngine, MockLockManager, ApiV1>;

fn build_storage() -> TestStorage {
    TestStorageBuilder::<RocksEngine, MockLockManager, ApiV1>::new(MockLockManager::new())
        .build()
        .unwrap()
}

fn new_manager<K>(
    storage: &TestStorage,
    db: K,
) -> StorageConfigManger<RocksEngine, K, MockLockManager> {
    let flow_controller = Arc::new(FlowController::Singleton(EngineFlowController::empty()));
    let (ttl_scheduler, _ttl_rx) = dummy_scheduler::<TtlCheckerTask>();
    StorageConfigManger::new(
        db,
        ttl_scheduler,
        flow_controller,
        storage.get_scheduler(),
        storage.get_concurrency_manager(),
    )
}

fn assert_send_sync<T: Send + Sync>() {}

/// Control test: this compiles only because of the two unbounded `unsafe impl`s.
/// If `K: Send + Sync` were required (or the impls removed), it must fail to
/// compile.
#[test]
fn manager_is_claimed_send_sync_for_a_non_send_db_handle() {
    assert_send_sync::<StorageConfigManger<RocksEngine, RcDb, MockLockManager>>();
}

/// The real config dispatch path calls the `!Sync` handle from a second thread
/// while the creating thread still uses it. TSan must report a `data race`.
#[test]
#[ignore = "triggers UB on purpose; run under TSan (ASan cannot see a plain data race)"]
fn configurable_db_is_accessed_from_another_thread() {
    let storage = build_storage();
    let shared = Rc::new(Cell::new(0usize));
    let manager = new_manager(&storage, RcDb(Rc::clone(&shared)));

    let (cfg, _tmp) = TikvConfig::with_tmp().unwrap();
    let cfg_controller = ConfigController::new(cfg);
    cfg_controller.register(Module::Storage, Box::new(manager));

    let barrier = Arc::new(Barrier::new(2));
    let writer = {
        let barrier = Arc::clone(&barrier);
        let controller = cfg_controller.clone();
        thread::spawn(move || {
            barrier.wait();
            // Runs on this thread, reaches RcDb::set_shared_block_cache_capacity.
            let _ = controller.update_config("storage.block-cache.capacity", "16MB");
        })
    };

    barrier.wait();
    // No synchronization with the writer: these reads race with the Cell::set
    // performed by the dispatch on the other thread.
    let deadline = Instant::now() + Duration::from_secs(10);
    let mut observed = 0;
    while observed == 0 && Instant::now() < deadline {
        observed = std::hint::black_box(shared.get());
    }
    writer.join().unwrap();
    assert_eq!(
        observed,
        16 * 1024 * 1024,
        "dispatch did not reach RcDb::set_shared_block_cache_capacity"
    );
}

/// Moving the manager to another thread is accepted by safe code; manager and
/// original thread then touch the same `Rc` refcount without synchronization.
#[test]
#[ignore = "triggers UB on purpose; TSan/ASan judge the concurrent Rc refcount"]
fn non_send_db_handle_migrates_across_threads() {
    let storage = build_storage();
    let shared = Rc::new(Cell::new(0usize));
    let manager = new_manager(&storage, RcDb(Rc::clone(&shared)));
    let kept = Rc::clone(&shared);

    let barrier = Arc::new(Barrier::new(2));
    let mover = {
        let barrier = Arc::clone(&barrier);
        thread::spawn(move || {
            barrier.wait();
            // Only the unbounded `unsafe impl Send` allows the `!Send` K to be
            // dropped on this thread.
            drop(manager);
        })
    };

    barrier.wait();
    for _ in 0..10_000 {
        let clone = Rc::clone(&kept);
        std::hint::black_box(&clone);
    }
    mover.join().unwrap();
    drop(kept);
}

What did you expect?

ConfigurableDb is a public trait whose methods take &self, and neither its documentation nor its signature states any thread-safety requirement (src/config/configurable.rs:12-22); an implementation over a non-thread-safe handle, Rc<Cell<usize>> being a minimal example, is therefore ordinary safe code. StorageConfigManger::new is public and accepts any K (src/storage/config_manager.rs:36-50), and ConfigManager: Send + Sync (components/online_config/src/lib.rs:148) then forces the whole manager to satisfy both auto traits, because ConfigController boxes it as Box<dyn ConfigManager> (src/config/mod.rs:5165), the dispatch call itself sits in update_impl at :5221, and the entry points update_config at :5261 and register at :5267 may run on any configuration thread, with callers in src/server/debug.rs:985 and src/server/status_server/mod.rs:324 and :847. Since the manager owns the handle, the two impls amount to an assertion that every K may cross a thread boundary, which directly contradicts the fact that K is not constrained to be Send or Sync. With proper bounds in place, the control test fails to compile, and the racing test cannot be written at all. Every in-tree instantiation currently passes a thread-safe handle, so a running server is not affected today; what remains is a soundness gap whose consequence is reached as soon as a caller supplies a handle that is not thread safe.

What did happened?

ThreadSanitizer reports a data race on the strong reference count of the Rc that the PoC's ConfigurableDb implementation holds. The read is the main thread's Rc::clone in non_send_db_handle_migrates_across_threads, and the write is the second thread dropping the manager, a sequence that in turn drops RcDb and the Rc it owns; only the unbounded unsafe impl Send allows that move and that drop to type-check. The racing accesses fall on a 24-byte heap block allocated by Rc::new inside the test, so both the allocation provenance and the two stacks place the access pair in the PoC rather than in the harness. The other ignored test also passes, and its assertion confirms that the second thread's ConfigController::update_config("storage.block-cache.capacity", ...) call reaches RcDb::set_shared_block_cache_capacity, which is direct evidence that the non-Sync handle is used from another thread.

The two runs follow; each is also attached separately as f3-control.log and f3-tsan.log.

Control run (plain cargo test), ThreadSanitizer decisive report, and run summary; 77 unrelated warnings are omitted
$ cargo +nightly-2026-03-21 test -p test_storage --test f3_storage_config_manager_unsound_send_sync -- --nocapture --test-threads=1
    Finished `test` profile [unoptimized] target(s) in 0.92s
warning: the following packages contain code that will be rejected by a future version of Rust: nom v2.2.1, nom v5.1.0, quick-xml v0.22.0
note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 2`
     Running tests/f3_storage_config_manager_unsound_send_sync.rs (target/debug/deps/f3_storage_config_manager_unsound_send_sync-1a27c06f1ead7771)

running 3 tests
test configurable_db_is_accessed_from_another_thread ... ignored, triggers UB on purpose; run under TSan (ASan cannot see a plain data race)
test manager_is_claimed_send_sync_for_a_non_send_db_handle ... ok
test non_send_db_handle_migrates_across_threads ... ignored, triggers UB on purpose; TSan/ASan judge the concurrent Rc refcount

test result: ok. 1 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.00s
$

$ CARGO_TARGET_DIR=target/tsan \
  RUSTFLAGS="-Zsanitizer=thread -Cunsafe-allow-abi-mismatch=sanitizer" \
  cargo +nightly-2026-03-21 test --target x86_64-unknown-linux-gnu \
  -p test_storage --test f3_storage_config_manager_unsound_send_sync \
  -- --ignored --nocapture --test-threads=1
    Finished `test` profile [unoptimized] target(s) in 0.54s
warning: the following packages contain code that will be rejected by a future version of Rust: nom v2.2.1, nom v5.1.0, quick-xml v0.22.0
note: to see what the problems were, use the option `--future-incompat-report`, or run `cargo report future-incompatibilities --id 1`
     Running tests/f3_storage_config_manager_unsound_send_sync.rs (target/tsan/x86_64-unknown-linux-gnu/debug/deps/f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0)

running 2 tests
[77 further reports were emitted while the storage harness started and stopped; they are
 omitted here. They involve the global allocator under ThreadSanitizer, yatp pool startup
 and teardown, the thread-name map, and lazily initialized metrics. The report below is
 the only one whose 24-byte allocation is created by the PoC and whose two stacks both
 belong to the PoC. The complete raw log was preserved by the reporter.]
WARNING: ThreadSanitizer: data race (pid=3396085)
  Read of size 8 at 0x7208001264e0 by thread T606:
    #0 <alloc::rc::RcInner<core::cell::Cell<usize>> as alloc::rc::RcInnerPtr>::strong alopy0j39m43amlg9ym8dyjej (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x110246c) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #1 <alloc::rc::RcInner<core::cell::Cell<usize>> as alloc::rc::RcInnerPtr>::inc_strong alopy0j39m43amlg9ym8dyjej (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x11023cc) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #2 <alloc::rc::Rc<core::cell::Cell<usize>> as core::clone::Clone>::clone alopy0j39m43amlg9ym8dyjej (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x1102369) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #3 f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads 6rkxguej7aqued0ncjgu9db2b (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10f5289) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #4 f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0} 9moy7sgam2sp7ntg9zqyizca9 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10fc6ac) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #5 <f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0} as core::ops::function::FnOnce<()>>::call_once 5u1sdfwpxs2t2h8ow4gadx4k6 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10f26e6) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #6 test::__rust_begin_short_backtrace::<core::result::Result<(), alloc::string::String>, fn() -> core::result::Result<(), alloc::string::String>> test.8f2a59ce0e164567-cgu.0 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x129e1fa) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)

  Previous write of size 8 at 0x7208001264e0 by thread T1208:
    #0 <alloc::rc::Rc<core::cell::Cell<usize>> as core::ops::drop::Drop>::drop 5u1sdfwpxs2t2h8ow4gadx4k6 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10f1f9a) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #1 core::ptr::drop_in_place::<alloc::rc::Rc<core::cell::Cell<usize>>> 5u1sdfwpxs2t2h8ow4gadx4k6 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10e9ffc) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #2 core::ptr::drop_in_place::<f3_storage_config_manager_unsound_send_sync::RcDb> 5u1sdfwpxs2t2h8ow4gadx4k6 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10ed89c) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #3 core::ptr::drop_in_place::<tikv::storage::config_manager::StorageConfigManger<tikv_kv::rocksdb_engine::RocksEngine, f3_storage_config_manager_unsound_send_sync::RcDb, tikv::storage::lock_manager::MockLockManager>> 5u1sdfwpxs2t2h8ow4gadx4k6 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10ec0b0) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #4 core::mem::drop::<tikv::storage::config_manager::StorageConfigManger<tikv_kv::rocksdb_engine::RocksEngine, f3_storage_config_manager_unsound_send_sync::RcDb, tikv::storage::lock_manager::MockLockManager>> 6rkxguej7aqued0ncjgu9db2b (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10f498c) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #5 f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0} 9moy7sgam2sp7ntg9zqyizca9 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10fc81a) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #6 std::sys::backtrace::__rust_begin_short_backtrace::<f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0}, ()> 2ixn1hzavx2d8bv9tsgc2y582 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10d918c) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #7 std::thread::lifecycle::spawn_unchecked::<f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0}, ()>::{closure#1}::{closure#0} 3wlrlj6bhtbz0mseisvdidjpg (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10e1336) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #8 <core::panic::unwind_safe::AssertUnwindSafe<std::thread::lifecycle::spawn_unchecked<f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0}, ()>::{closure#1}::{closure#0}> as core::ops::function::FnOnce<()>>::call_once 168jdnbuxx9g593lvvwnjizp9 (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10d453b) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #9 std::panicking::catch_unwind::do_call::<core::panic::unwind_safe::AssertUnwindSafe<std::thread::lifecycle::spawn_unchecked<f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0}, ()>::{closure#1}::{closure#0}>, ()> eylpun68eebc3f1imxvzl84en (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x110b94b) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #10 __rust_try 3wlrlj6bhtbz0mseisvdidjpg (f3_storage_config_manager_unsound_send_sync-b375678cb85a20d0+0x10e1868) (BuildId: 55e9a73d92c3d853513cafd5c79cac765afe7bd5)
    #11 std::thread::lifecycle::spawn_unchecked::<f3_storage_config_manager_unsound_send_sync::non_send_db_handle_migrates_across_threads::{closure#0}, ()>