1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
|
//! This test reproduces a race condition where returning `None` from `Expiry`
//! methods (to unset expiration) can cause a use-after-free panic in the timer wheel.
//!
//! The bug occurs because:
//! 1. `expiration_time` is set atomically (immediately) when `Expiry` returns `None`
//! 2. `timer_node` is only updated during housekeeping (later)
//! 3. This creates a window where `expiration_time` is `None` but `timer_node` still
//! points to a freed/invalid timer node
//!
//! Pattern that triggers the bug:
//! - Insert with `Err` value → gets TTL (timer node created)
//! - Update to `Ok` value → `Expiry` returns `None` (should remove timer node)
//! - Concurrent `get` or housekeeping reads stale `timer_node` pointer
#![cfg(feature = "sync")]
use moka::sync::Cache;
use moka::Expiry;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
type HandleResult<T> = Result<T, String>;
struct CustomExpiry {
error_ttl: Duration,
}
impl Default for CustomExpiry {
fn default() -> Self {
Self {
error_ttl: Duration::from_millis(100),
}
}
}
impl<K, V> Expiry<K, HandleResult<V>> for CustomExpiry {
fn expire_after_create(&self, _: &K, value: &HandleResult<V>, _: Instant) -> Option<Duration> {
match value {
Ok(_) => None,
Err(_) => Some(self.error_ttl),
}
}
fn expire_after_update(
&self,
_: &K,
value: &HandleResult<V>,
_: Instant,
_: Option<Duration>,
) -> Option<Duration> {
match value {
Ok(_) => None,
Err(_) => Some(self.error_ttl),
}
}
}
/// This test runs for a short duration (5 seconds by default) to catch the race condition.
/// In production, the bug was observed within 2 months of operation, but with aggressive
/// concurrent operations, it can be triggered much faster.
///
/// The test pattern:
/// 1. Insert threads: repeatedly insert `Err` then `Ok` values (triggers timer node create/remove)
/// 2. Get threads: continuously read entries (triggers `expire_after_read` and housekeeping)
/// 3. Housekeeping thread: explicitly runs `run_pending_tasks()` to process timer wheel operations
#[test]
fn test_timer_wheel_panic() {
// Use shorter duration for CI, increase for more thorough testing
let test_duration = Duration::from_secs(5);
const NUM_KEYS: u64 = if cfg!(miri) { 25 } else { 100 };
let panics = Arc::new(AtomicUsize::new(0));
let cache: Cache<u64, HandleResult<u64>> = Cache::builder()
.name("test_cache")
.expire_after(CustomExpiry::default())
.time_to_idle(Duration::from_secs(240))
.max_capacity(10000)
.build();
let cache = Arc::new(cache);
let start = Instant::now();
// Insert threads: Err -> Ok pattern
let insert_handles: Vec<_> = (0..4)
.map(|tid| {
let cache = Arc::clone(&cache);
let panics = Arc::clone(&panics);
let duration = test_duration;
thread::spawn(move || {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut ops = 0u64;
while start.elapsed() < duration {
for key in 0..NUM_KEYS {
let key = key + (tid as u64 * 10000);
// Insert error first (creates timer node with TTL)
cache.insert(key, Err("error".into()));
// Update to success (Expiry returns None - removes TTL)
cache.insert(key, Ok(ops));
// Sometimes go back to error
if ops % 3 == 0 {
cache.insert(key, Err("retry".into()));
}
ops += 1;
}
}
println!("[Insert {}] done: {} ops", tid, ops);
}))
.unwrap_or_else(|_| {
panics.fetch_add(1, Ordering::Relaxed);
eprintln!("[Insert {}] PANICKED!", tid);
});
})
})
.collect();
// Get threads - trigger expire_after_read and housekeeping
let get_handles: Vec<_> = (0..4)
.map(|tid| {
let cache = Arc::clone(&cache);
let panics = Arc::clone(&panics);
let duration = test_duration;
thread::spawn(move || {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut ops = 0u64;
while start.elapsed() < duration {
for key in 0..NUM_KEYS {
// Read from different thread's key space to increase contention
let key = key + ((ops % 4) * 10000);
let _ = cache.get(&key);
ops += 1;
}
}
println!("[Get {}] done: {} ops", tid, ops);
}))
.unwrap_or_else(|_| {
panics.fetch_add(1, Ordering::Relaxed);
eprintln!("[Get {}] PANICKED!", tid);
});
})
})
.collect();
let cache_hk = Arc::clone(&cache);
let panics_hk = Arc::clone(&panics);
let hk = thread::spawn(move || {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
while start.elapsed() < test_duration {
cache_hk.run_pending_tasks();
thread::sleep(Duration::from_millis(50));
}
}))
.unwrap_or_else(|_| {
panics_hk.fetch_add(1, Ordering::Relaxed);
eprintln!("[HK] PANICKED!");
});
});
for h in insert_handles {
let _ = h.join();
}
for h in get_handles {
let _ = h.join();
}
let _ = hk.join();
let total_panics = panics.load(Ordering::Relaxed);
assert_eq!(
total_panics, 0,
"Timer wheel panic detected! {} threads panicked",
total_panics
);
}
/// Extended stress test - runs longer for more thorough testing.
///
/// To run this test, do one of the following:
///
/// ```console
/// ## Normal cargo test command for release build
/// $ cargo test --release -p moka -F sync --test timer_wheel_panic_test stress -- \
/// --ignored --no-capture
///
/// ## Miri command with appropriate flags
/// ##
/// ## - `miri-ignore-leaks` for ignoring `crossbeam-epoch`'s not yet reclaimed memory.
/// ## - `miri-permissive-provenance` to avoid provenance-related warnings for `tagptr`
/// ## crate.
/// ## - `miri-disable-isolation` to use the wall-clock time for the test duration,
/// ## instead of Miri's emulated virtual clock, which may advance significantly
/// ## slower.
/// $ MIRIFLAGS='-Zmiri-tree-borrows -Zmiri-ignore-leaks -Zmiri-permissive-provenance -Zmiri-disable-isolation' \
/// cargo +nightly miri test stress_test_timer_wheel_panic -F sync -- \
/// --ignored --no-capture
/// ```
#[test]
#[ignore]
fn stress_test_timer_wheel_panic() {
// If Miri is used, extend the duration significantly.
const DURATION_MINUTES: u64 = if cfg!(miri) { 20 } else { 1 };
let test_duration = Duration::from_secs(DURATION_MINUTES * 60);
let panics = Arc::new(AtomicUsize::new(0));
let cache: Cache<u64, HandleResult<u64>> = Cache::builder()
.name("stress_test_cache")
.expire_after(CustomExpiry::default())
.time_to_idle(Duration::from_secs(240))
.max_capacity(10000)
.build();
let cache = Arc::new(cache);
let start = Instant::now();
// More aggressive thread count for stress testing
const NUM_INSERT_THREADS: i32 = if cfg!(miri) { 6 } else { 8 };
const NUM_GET_THREADS: i32 = if cfg!(miri) { 4 } else { 8 };
// Insert threads
let insert_handles: Vec<_> = (0..NUM_INSERT_THREADS)
.map(|tid| {
let cache = Arc::clone(&cache);
let panics = Arc::clone(&panics);
let duration = test_duration;
thread::spawn(move || {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut ops = 0u64;
const REPORT_INTERVAL: u64 = if cfg!(miri) { 5 } else { 100_000 };
'l: loop {
for key in 0..200u64 {
let key = key + (tid as u64 * 10000);
cache.insert(key, Err("error".into()));
cache.insert(key, Ok(ops));
if ops % 3 == 0 {
cache.insert(key, Err("retry".into()));
}
if ops % 7 == 0 {
cache.invalidate(&key);
}
ops += 1;
if ops % REPORT_INTERVAL == 0 {
println!("[Insert {}] running: {} ops", tid, ops);
}
if start.elapsed() >= duration {
break 'l;
}
}
}
println!("[Insert {}] done: {} ops", tid, ops);
}))
.unwrap_or_else(|e| {
panics.fetch_add(1, Ordering::Relaxed);
eprintln!("[Insert {}] PANICKED: {:?}", tid, e);
});
})
})
.collect();
// Get threads
let get_handles: Vec<_> = (0..NUM_GET_THREADS)
.map(|tid| {
let cache = Arc::clone(&cache);
let panics = Arc::clone(&panics);
let duration = test_duration;
thread::spawn(move || {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut ops = 0u64;
const REPORT_INTERVAL: u64 = if cfg!(miri) { 50 } else { 100_000 };
'l: loop {
for key in 0..200u64 {
let key = key + ((ops % NUM_GET_THREADS as u64) * 10000);
let _ = cache.get(&key);
ops += 1;
if ops % REPORT_INTERVAL == 0 {
println!("[Get {}] running: {} ops", tid, ops);
}
if start.elapsed() >= duration {
break 'l;
}
}
}
println!("[Get {}] done: {} ops", tid, ops);
}))
.unwrap_or_else(|e| {
panics.fetch_add(1, Ordering::Relaxed);
eprintln!("[Get {}] PANICKED: {:?}", tid, e);
});
})
})
.collect();
let hk_handles = if cfg!(miri) {
None
} else {
let handles = (0..2)
.map(|tid| {
let cache = Arc::clone(&cache);
let panics = Arc::clone(&panics);
let duration = test_duration;
thread::spawn(move || {
let mut ops = 0u64;
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
while start.elapsed() < duration {
cache.run_pending_tasks();
thread::sleep(Duration::from_millis(25));
ops += 1;
if ops % 50 == 0 {
println!("[HK {}] running: {} ops", tid, ops);
}
}
}))
.unwrap_or_else(|e| {
panics.fetch_add(1, Ordering::Relaxed);
eprintln!("[HK {}] PANICKED: {:?}", tid, e);
});
})
})
.collect::<Vec<_>>();
Some(handles)
};
// Wait for all threads
for h in insert_handles {
let _ = h.join();
}
for h in get_handles {
let _ = h.join();
}
if let Some(hk_handles) = hk_handles {
for h in hk_handles {
let _ = h.join();
}
}
let total_panics = panics.load(Ordering::Relaxed);
assert_eq!(
total_panics, 0,
"Timer wheel panic detected! {} threads panicked during stress test.",
total_panics
);
}
|