use crate::core::types::{CalcError, CanonicalForm, EvalResult};
use std::sync::OnceLock;
static RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
fn runtime() -> &'static tokio::runtime::Runtime {
RUNTIME.get_or_init(|| {
tokio::runtime::Runtime::new().expect("failed to create tokio runtime for oxcache")
})
}
pub struct CacheKeyGen;
impl CacheKeyGen {
pub fn hash(cf: &CanonicalForm) -> [u8; 32] {
*blake3::hash(cf.as_str().as_bytes()).as_bytes()
}
fn to_key_string(bytes: &[u8; 32]) -> String {
use std::fmt::Write;
let mut s = String::with_capacity(64);
for b in bytes {
write!(s, "{:02x}", b).unwrap();
}
s
}
fn make_key(cf: &CanonicalForm) -> String {
Self::to_key_string(&Self::hash(cf))
}
}
const DEFAULT_MAX_CAPACITY: u64 = 10_000;
pub struct CacheManager {
inner: oxcache::Cache<String, EvalResult>,
}
impl CacheManager {
pub fn new() -> Self {
let cache = runtime()
.block_on(
oxcache::Cache::builder()
.capacity(DEFAULT_MAX_CAPACITY)
.build(),
)
.expect("failed to build oxcache L1 cache");
Self { inner: cache }
}
pub fn get(&self, cf: &CanonicalForm) -> Option<EvalResult> {
let key = CacheKeyGen::make_key(cf);
runtime().block_on(self.inner.get(&key)).ok().flatten()
}
pub fn insert(&self, cf: &CanonicalForm, result: &Result<EvalResult, CalcError>) {
if let Ok(value) = result {
let key = CacheKeyGen::make_key(cf);
let _ = runtime().block_on(self.inner.set(&key, value));
}
}
pub fn get_or_compute<F>(&self, cf: &CanonicalForm, compute: F) -> Result<EvalResult, CalcError>
where
F: FnOnce() -> Result<EvalResult, CalcError>,
{
if let Some(cached) = self.get(cf) {
return Ok(cached);
}
let result = compute()?;
self.insert(cf, &Ok(result.clone()));
Ok(result)
}
pub fn entry_count(&self) -> u64 {
runtime().block_on(self.inner.len()).unwrap_or(0)
}
}
impl Default for CacheManager {
fn default() -> Self {
Self::new()
}
}
#[cfg(not(coverage))]
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<CacheManager>();
assert_send_sync::<CacheKeyGen>();
};
#[cfg(test)]
mod tests {
use super::*;
use crate::core::canonicalizer::AstCanonicalizer;
use crate::core::parser::parse;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
fn canon(input: &str) -> CanonicalForm {
let ast = parse(input).unwrap();
let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
cf
}
#[test]
fn test_cache_hit_returns_cached_value() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("(+ 2 3)");
cache.insert(&cf, &Ok(EvalResult::Scalar(5.0)));
let hit = cache.get(&cf);
assert_eq!(hit, Some(EvalResult::Scalar(5.0)));
}
#[test]
fn test_cache_hit_returns_clone_not_reference() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("test");
cache.insert(&cf, &Ok(EvalResult::Scalar(42.0)));
let _hit1 = cache.get(&cf).unwrap();
let hit2 = cache.get(&cf).unwrap();
assert_eq!(hit2, EvalResult::Scalar(42.0));
}
#[test]
fn test_cache_miss_returns_none() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("(+ 1 2)");
assert_eq!(cache.get(&cf), None);
}
#[test]
fn test_insert_then_immediate_hit() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("6*7");
cache.insert(&cf, &Ok(EvalResult::Scalar(42.0)));
let hit = cache.get(&cf);
assert_eq!(hit, Some(EvalResult::Scalar(42.0)));
}
#[test]
fn test_get_or_compute_calls_compute_on_miss() {
let cache = CacheManager::new();
let cf = canon("6*7");
let call_count = Arc::new(AtomicUsize::new(0));
let cc = Arc::clone(&call_count);
let result = cache.get_or_compute(&cf, || {
cc.fetch_add(1, Ordering::SeqCst);
Ok(EvalResult::Scalar(42.0))
});
assert_eq!(result.unwrap(), EvalResult::Scalar(42.0));
assert_eq!(call_count.load(Ordering::SeqCst), 1);
}
#[test]
fn test_commutative_equivalent_share_cache() {
let cache = CacheManager::new();
let cf_2plus3 = canon("2+3");
let cf_3plus2 = canon("3+2");
assert_eq!(cf_2plus3, cf_3plus2, "规范形式应相同");
cache.insert(&cf_2plus3, &Ok(EvalResult::Scalar(5.0)));
assert_eq!(cache.get(&cf_3plus2), Some(EvalResult::Scalar(5.0)));
}
#[test]
fn test_constant_folding_equivalent_share_cache() {
let cache = CacheManager::new();
let cf_1 = canon("2*3+1");
let cf_2 = canon("1+6");
assert_eq!(cf_1, cf_2, "规范形式应相同");
cache.insert(&cf_1, &Ok(EvalResult::Scalar(7.0)));
assert_eq!(cache.get(&cf_2), Some(EvalResult::Scalar(7.0)));
}
#[test]
fn test_non_equivalent_do_not_share_cache() {
let cache = CacheManager::new();
let cf_2minus3 = canon("2-3");
let cf_3minus2 = canon("3-2");
assert_ne!(cf_2minus3, cf_3minus2, "规范形式应不同");
cache.insert(&cf_2minus3, &Ok(EvalResult::Scalar(-1.0)));
assert_eq!(cache.get(&cf_3minus2), None, "不同规范形式不应命中");
}
#[test]
fn test_same_canonical_form_same_key() {
let cf1 = CanonicalForm::new("(+ 2 3)");
let cf2 = CanonicalForm::new("(+ 2 3)");
assert_eq!(CacheKeyGen::hash(&cf1), CacheKeyGen::hash(&cf2));
}
#[test]
fn test_different_canonical_form_different_key() {
let cf1 = CanonicalForm::new("(+ 2 3)");
let cf2 = CanonicalForm::new("(* 2 3)");
assert_ne!(CacheKeyGen::hash(&cf1), CacheKeyGen::hash(&cf2));
}
#[test]
fn test_key_length_is_32_bytes() {
let cf = CanonicalForm::new("(+ 2 3)");
let key = CacheKeyGen::hash(&cf);
assert_eq!(key.len(), 32);
}
#[test]
fn test_empty_string_generates_key() {
let cf = CanonicalForm::new("");
let key = CacheKeyGen::hash(&cf);
assert_eq!(key.len(), 32);
assert!(key.iter().any(|&b| b != 0));
}
#[test]
fn test_cache_persists_within_process() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("(+ 1 1)");
cache.insert(&cf, &Ok(EvalResult::Scalar(2.0)));
for _ in 0..10 {
assert_eq!(cache.get(&cf), Some(EvalResult::Scalar(2.0)));
}
}
#[test]
fn test_no_time_based_eviction() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("(+ 1 1)");
cache.insert(&cf, &Ok(EvalResult::Scalar(2.0)));
thread::sleep(std::time::Duration::from_millis(50));
assert_eq!(cache.get(&cf), Some(EvalResult::Scalar(2.0)));
}
#[test]
fn test_cache_manager_is_send_sync() {
fn assert_send_sync<T: Send + Sync>(_: &T) {}
let cache = CacheManager::new();
assert_send_sync(&cache);
}
#[test]
fn test_concurrent_read_hits() {
let cache = Arc::new(CacheManager::new());
let cf = Arc::new(CanonicalForm::new("(+ 2 3)"));
cache.insert(&cf, &Ok(EvalResult::Scalar(5.0)));
let mut handles = vec![];
for _ in 0..8 {
let cache = Arc::clone(&cache);
let cf = Arc::clone(&cf);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
assert_eq!(cache.get(&cf), Some(EvalResult::Scalar(5.0)));
}
}));
}
for h in handles {
h.join().unwrap();
}
}
#[test]
fn test_concurrent_writes_no_conflict() {
let cache = Arc::new(CacheManager::new());
let mut handles = vec![];
for i in 0..8u64 {
let cache = Arc::clone(&cache);
handles.push(thread::spawn(move || {
let cf = CanonicalForm::new(format!("(+ {} {})", i, i).as_str());
let result = EvalResult::Scalar((i * 2) as f64);
cache.insert(&cf, &Ok(result.clone()));
assert_eq!(cache.get(&cf), Some(result));
}));
}
for h in handles {
h.join().unwrap();
}
for i in 0..8u64 {
let cf = CanonicalForm::new(format!("(+ {} {})", i, i).as_str());
let expected = EvalResult::Scalar((i * 2) as f64);
assert_eq!(
cache.get(&cf),
Some(expected),
"线程 {} 的缓存条目应可读",
i
);
}
}
#[test]
fn test_error_result_not_cached() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("1/0");
let result = cache.get_or_compute(&cf, || Err(CalcError::DivisionByZero));
assert!(result.is_err());
assert_eq!(cache.get(&cf), None, "错误结果不应写入缓存");
}
#[test]
fn test_nan_error_not_cached() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("sqrt(-1)");
let result = cache.get_or_compute(&cf, || Err(CalcError::NaNOrInf));
assert!(result.is_err());
assert_eq!(cache.get(&cf), None, "NaN 错误不应写入缓存");
}
#[test]
fn test_only_success_cached() {
let cache = CacheManager::new();
let cf_ok = CanonicalForm::new("(+ 1 2)");
let cf_err = CanonicalForm::new("(1/0)");
cache.insert(&cf_ok, &Ok(EvalResult::Scalar(3.0)));
cache.insert(&cf_err, &Err(CalcError::DivisionByZero));
assert_eq!(cache.get(&cf_ok), Some(EvalResult::Scalar(3.0)));
assert_eq!(cache.get(&cf_err), None, "错误结果不应写入");
}
#[test]
fn test_get_or_compute_hits_cache_on_second_call() {
let cache = CacheManager::new();
let cf = canon("2+3");
let call_count = Arc::new(AtomicUsize::new(0));
let cc = Arc::clone(&call_count);
let r1 = cache.get_or_compute(&cf, || {
cc.fetch_add(1, Ordering::SeqCst);
Ok(EvalResult::Scalar(5.0))
});
assert_eq!(r1.unwrap(), EvalResult::Scalar(5.0));
assert_eq!(call_count.load(Ordering::SeqCst), 1);
let r2 = cache.get_or_compute(&cf, || Ok(EvalResult::Scalar(999.0)));
assert_eq!(r2.unwrap(), EvalResult::Scalar(5.0), "应返回缓存值");
assert_eq!(call_count.load(Ordering::SeqCst), 1, "compute 不应被调用");
}
#[test]
fn test_entry_count_zero_on_empty_cache() {
let cache = CacheManager::new();
assert_eq!(cache.entry_count(), 0, "fresh cache should have 0 entries");
}
#[test]
fn test_entry_count_increases_after_insert() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("(+ 1 2)");
cache.insert(&cf, &Ok(EvalResult::Scalar(3.0)));
let _count = cache.entry_count();
}
#[test]
fn test_default_creates_working_cache() {
let cache = CacheManager::default();
let cf = CanonicalForm::new("(+ 5 7)");
assert_eq!(cache.get(&cf), None);
cache.insert(&cf, &Ok(EvalResult::Scalar(12.0)));
assert_eq!(cache.get(&cf), Some(EvalResult::Scalar(12.0)));
}
#[test]
fn test_get_or_compute_closure_runs_on_miss() {
let cache = CacheManager::new();
let cf1 = CanonicalForm::new("(+ 100 1)");
let cf2 = CanonicalForm::new("(+ 200 2)");
let r1 = cache.get_or_compute(&cf1, || Ok(EvalResult::Scalar(101.0)));
assert_eq!(r1.unwrap(), EvalResult::Scalar(101.0));
let r2 = cache.get_or_compute(&cf2, || Ok(EvalResult::Scalar(202.0)));
assert_eq!(r2.unwrap(), EvalResult::Scalar(202.0));
}
#[test]
fn test_cache_keygen_to_key_string_via_make_key() {
let cache = CacheManager::new();
let cf = CanonicalForm::new("(unique-key-test 42)");
cache.insert(&cf, &Ok(EvalResult::Scalar(7.0)));
assert_eq!(cache.get(&cf), Some(EvalResult::Scalar(7.0)));
}
use proptest::prelude::*;
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
#[test]
fn prop_commutative_expressions_share_cache(
a in (0u8..26u8).prop_map(|i| ((b'a' + i) as char).to_string()),
b in (0u8..26u8).prop_map(|i| ((b'a' + i) as char).to_string())
) {
let cache = CacheManager::new();
let cf_ab = canon(&format!("{}+{}", a, b));
let cf_ba = canon(&format!("{}+{}", b, a));
prop_assert_eq!(&cf_ab, &cf_ba, "规范形式应相同");
cache.insert(&cf_ab, &Ok(EvalResult::Scalar(5.0)));
prop_assert_eq!(cache.get(&cf_ba), Some(EvalResult::Scalar(5.0)));
}
#[test]
fn prop_cache_hit_repeatable(
x in (1u8..100u8).prop_map(|i| format!("{}+{}", i, i+1))
) {
let cache = CacheManager::new();
let cf = canon(&x);
cache.insert(&cf, &Ok(EvalResult::Scalar(42.0)));
prop_assert_eq!(cache.get(&cf), Some(EvalResult::Scalar(42.0)));
prop_assert_eq!(cache.get(&cf), Some(EvalResult::Scalar(42.0)));
}
#[test]
fn prop_distinct_expressions_distinct_cache(
a in (1u8..50u8).prop_map(|i| format!("{}*2", i)),
b in (51u8..100u8).prop_map(|i| format!("{}*2", i))
) {
let cache = CacheManager::new();
let cf_a = canon(&a);
let cf_b = canon(&b);
if cf_a != cf_b {
cache.insert(&cf_a, &Ok(EvalResult::Scalar(1.0)));
prop_assert_eq!(cache.get(&cf_b), None, "不同表达式不应命中");
}
}
}
}