mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-03 01:38:46 +00:00
* refactor(rust): align the cache crates with Python and activate every backend The cache port had drifted: lifecycle and Redis-only operations sat on `BaseCache`, counters were pinned to `f64`, each semantic backend defined its own embedder and prompt handling, and only the in-memory backend could be selected natively. - Split `disconnect` and `test_connection` out of `BaseCache` into optional capabilities, implemented only where the Python class defines them, and give every Redis-only operation its own capability trait. - Decouple counters from the stored value type, so one backend can serve both responses and counters as Python's `RedisCache` does. - Share one `Embedder` and prompt contract in `litellm_cache::semantic`, and make the Redis and Valkey semantic backends generic over their codec. - Port the Python operations that were missing: `async_refresh_ttl`, `async_rpush_and_trim`, `async_set_cache_pipeline_with_ttls`, the DualCache pipeline, sadd, bulk delete and TTL reads, and the semantic-similarity write-back. - Take the HTTP client from the host pool in the GCS, S3 and Azure backends. - Activate all nine backends through the Rust catalog, whose rules all stay `PYTHON_ONLY`, and route the `Cache` facade's storage calls to the native runtime when one is selected. - Give every crate the same layout, move all tests to `tests/` on rstest, and add the shared `litellm-cache-testing` contract suite. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: freeze native cache request kwargs and batch entries for type discipline Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: declare semantic lookup methods in the native stub Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(rust): align the cache crates with Python and activate every backend The cache port had drifted: lifecycle and Redis-only operations sat on `BaseCache`, counters were pinned to `f64`, each semantic backend defined its own embedder and prompt handling, and only the in-memory backend could be selected natively. - Split `disconnect` and `test_connection` out of `BaseCache` into optional capabilities, implemented only where the Python class defines them, and give every Redis-only operation its own capability trait. - Decouple counters from the stored value type, so one backend can serve both responses and counters as Python's `RedisCache` does. - Share one `Embedder` and prompt contract in `litellm_cache::semantic`, and make the Redis and Valkey semantic backends generic over their codec. - Port the Python operations that were missing: `async_refresh_ttl`, `async_rpush_and_trim`, `async_set_cache_pipeline_with_ttls`, the DualCache pipeline, sadd, bulk delete and TTL reads, and the semantic-similarity write-back. - Take the HTTP client from the host pool in the GCS, S3 and Azure backends. - Activate all nine backends through the Rust catalog, whose rules all stay `PYTHON_ONLY`, and route the `Cache` facade's storage calls to the native runtime when one is selected. - Give every crate the same layout, move all tests to `tests/` on rstest, and add the shared `litellm-cache-testing` contract suite. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: freeze native cache request kwargs and batch entries for type discipline Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: declare semantic lookup methods in the native stub Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(rust): opt the native Messages and tokenizer suites into Rust explicitly #42517 made the Messages, token counter and tokenizer routes Python-only, so tests/test_litellm_rust silently exercised the Python path or failed outright. Each suite now prepends a RUST_OPT_IN rule for its route, keeping native coverage without changing the shipped default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(rust): pop one at a time in the Redis 6 lpop pipeline and drop explanatory comments Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
105 lines
3.5 KiB
Rust
105 lines
3.5 KiB
Rust
use litellm_cache::{CacheCodec, ClaimCache, Error, ExactCacheContext};
|
|
use redis::Commands;
|
|
|
|
use crate::{cache::RedisCache, connection::ConnectionRef};
|
|
|
|
const CLAIM_SCRIPT: &str = concat!(
|
|
"local current = redis.call('GET', KEYS[1]); ",
|
|
"if ARGV[1] == '' then if current ~= false and current ~= '' then return 0; end; ",
|
|
"elseif current ~= ARGV[1] then return 0; end; ",
|
|
"if ARGV[3] ~= '' then redis.call('SET', KEYS[1], ARGV[3], 'EX', ARGV[2]); ",
|
|
"elseif ARGV[4] == '1' then redis.call('EXPIRE', KEYS[1], ARGV[2]); end; return 1"
|
|
);
|
|
const CLAIM_ATTEMPTS: usize = 8;
|
|
|
|
fn stored_bytes(value: redis::Value) -> Result<Option<Vec<u8>>, Error> {
|
|
match value {
|
|
redis::Value::Nil => Ok(None),
|
|
redis::Value::BulkString(bytes) => Ok(Some(bytes)),
|
|
redis::Value::SimpleString(text) => Ok(Some(text.into_bytes())),
|
|
_ => Err(Error::InvalidEntry),
|
|
}
|
|
}
|
|
|
|
/// Eligibility is decided on decoded values, so a pin written by another encoder (Python's
|
|
/// `json.dumps` spacing or key order) still matches. The write is a compare-and-set on the
|
|
/// bytes that decision was made on, retried when another claimant wins the race.
|
|
fn claim<S: CacheCodec>(
|
|
connection: &mut ConnectionRef<'_>,
|
|
codec: &S,
|
|
key: &str,
|
|
candidate: S::Value,
|
|
eligible: &[S::Value],
|
|
ttl: u64,
|
|
) -> Result<S::Value, Error>
|
|
where
|
|
S::Value: PartialEq,
|
|
{
|
|
let payload = codec.encode(&candidate)?;
|
|
if payload.is_empty() {
|
|
return Err(Error::InvalidEntry);
|
|
}
|
|
for _ in 0..CLAIM_ATTEMPTS {
|
|
let current = stored_bytes(
|
|
connection
|
|
.get::<_, redis::Value>(key)
|
|
.map_err(|_| Error::Unavailable)?,
|
|
)?
|
|
.filter(|bytes| !bytes.is_empty());
|
|
let existing = current
|
|
.as_deref()
|
|
.and_then(|bytes| codec.decode(bytes).ok())
|
|
.filter(|existing| eligible.is_empty() || eligible.contains(existing));
|
|
let refresh = existing
|
|
.as_ref()
|
|
.is_some_and(|existing| !eligible.is_empty() || *existing == candidate);
|
|
let write: &[u8] = if existing.is_some() { b"" } else { &payload };
|
|
let applied = redis::cmd("EVAL")
|
|
.arg(CLAIM_SCRIPT)
|
|
.arg(1)
|
|
.arg(key)
|
|
.arg(current.as_deref().unwrap_or_default())
|
|
.arg(ttl)
|
|
.arg(write)
|
|
.arg(u8::from(refresh))
|
|
.query::<bool>(connection)
|
|
.map_err(|_| Error::Unavailable)?;
|
|
if applied {
|
|
return Ok(existing.unwrap_or(candidate));
|
|
}
|
|
}
|
|
Err(Error::Unavailable)
|
|
}
|
|
|
|
impl<S, C> ClaimCache for RedisCache<S, C>
|
|
where
|
|
S: CacheCodec + Clone + 'static,
|
|
S::Value: PartialEq,
|
|
C: redis::ConnectionLike + Send + 'static,
|
|
{
|
|
fn claim_cache(
|
|
&self,
|
|
key: &str,
|
|
candidate: S::Value,
|
|
eligible: &[S::Value],
|
|
context: ExactCacheContext,
|
|
) -> Result<S::Value, Error> {
|
|
let key = self.namespaced_key(key);
|
|
let ttl = self.ttl_or_default(context.ttl);
|
|
self.execute(|connection| claim(connection, &self.codec, &key, candidate, eligible, ttl))
|
|
}
|
|
|
|
async fn async_claim_cache(
|
|
&self,
|
|
key: &str,
|
|
candidate: S::Value,
|
|
eligible: Vec<S::Value>,
|
|
context: ExactCacheContext,
|
|
) -> Result<S::Value, Error> {
|
|
let key = self.namespaced_key(key);
|
|
let ttl = self.ttl_or_default(context.ttl);
|
|
let codec = self.codec.clone();
|
|
self.run(move |connection| claim(connection, &codec, &key, candidate, &eligible, ttl))
|
|
.await
|
|
}
|
|
}
|