The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge remote-tracking branch 'origin/main' into litellm_rust_cache_s3
Yujong Lee3ebbb2af5b33
diff --cc litellm-rust/Cargo.lockindex e2337f41ebc,ea4f3d848c4..d1ca1831717--- a/litellm-rust/Cargo.lock+++ b/litellm-rust/Cargo.lock@@@ -1008,16 -927,12 +1008,22 @@@ dependencies ="libc",]+[[package]]+name = "crc-fast"+version = "1.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5"+dependencies = [+ "digest 0.10.7",+ "spin",+]++ [[package]]+ name = "crc16"+ version = "0.4.0"+ source = "registry+https://github.com/rust-lang/crates.io-index"+ checksum = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"+[[package]]name = "crc32fast"version = "1.5.1"diff --cc litellm-rust/crates/python-bridge/src/cache/config.rsindex 003a2687e88,5fe36f6c1fa..70d6f7c1841--- a/litellm-rust/crates/python-bridge/src/cache/config.rs+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs@@@ -1,12 -1,11 +1,13 @@@use std::time::Duration;+use litellm_auth_aws::AwsAuthConfig;use litellm_cache::CacheType;+ use litellm_cache_redis::{RedisNode, RedisTopology};+use litellm_cache_s3::{S3CacheConfig, S3Endpoint};use pyo3::{- exceptions::{PyTypeError, PyValueError},+ exceptions::{PyAttributeError, PyTypeError, PyValueError},prelude::*,- types::{PyAny, PyBool, PyDict, PyString},- types::{PyAny, PyDict, PyList, PyString},++ types::{PyAny, PyBool, PyDict, PyList, PyString},};use super::{native::NativeResponseCache, request::duration};@@@ -339,77 -311,128 +351,199 @@@ fn project_redis}))}+#[inline(never)]+fn project_s3(+ backend: &Bound<'_, PyAny>,+) -> PyResult<Result<S3CacheConfig, UnsupportedCacheConfig>> {+ let client = backend.getattr("s3_client")?;+ if !instance_class_is(&client, "botocore.client", "S3")? {+ return Ok(Err(UnsupportedCacheConfig::S3Client));+ }+ let meta = client.getattr("meta")?;+ let Some(region) = optional_string(meta.getattr("region_name")?)? else {+ return Ok(Err(UnsupportedCacheConfig::S3Option));+ };+ let Some(endpoint_url) = optional_string(meta.getattr("endpoint_url")?)? else {+ return Ok(Err(UnsupportedCacheConfig::S3Option));+ };+ let client_config = meta.getattr("config")?;+ for name in ["s3", "proxies", "client_cert"] {+ if optional_attribute(&client_config, name)?.is_some_and(|value| !value.is_none()) {+ return Ok(Err(UnsupportedCacheConfig::S3Option));+ }+ }+ let signature = match optional_attribute(&client_config, "signature_version")? {+ Some(value) => value.extract::<Option<String>>()?,+ None => None,+ };+ if signature.as_deref() != Some("s3v4") {+ return Ok(Err(UnsupportedCacheConfig::S3Option));+ }+ let insecure = endpoint_url.starts_with("http://");+ let verify = optional_attribute_chain(&client, &["_endpoint", "http_session", "_verify"])?;+ let verified = verify+ .and_then(|value| value.cast::<PyBool>().ok().map(|value| value.is_true()))+ .unwrap_or(false);+ if !verified && !insecure {+ return Ok(Err(UnsupportedCacheConfig::S3Option));+ }+ let credentials = optional_attribute_chain(&client, &["_request_signer", "_credentials"])?+ .ok_or(UnsupportedCacheConfig::S3Credentials);+ let credentials = match credentials {+ Ok(credentials) if !credentials.is_none() => credentials,+ _ => return Ok(Err(UnsupportedCacheConfig::S3Credentials)),+ };+ let auth = if credentials.getattr("method")?.extract::<String>()?.as_str() == "explicit" {+ AwsAuthConfig {+ access_key_id: credentials+ .getattr("access_key")?+ .extract::<Option<String>>()?,+ secret_access_key: credentials+ .getattr("secret_key")?+ .extract::<Option<String>>()?,+ session_token: credentials.getattr("token")?.extract::<Option<String>>()?,+ region_name: Some(region.clone()),+ ..Default::default()+ }+ } else {+ AwsAuthConfig {+ region_name: Some(region.clone()),+ ..Default::default()+ }+ };+ let default_endpoint = endpoint_url == format!("https://s3.{region}.amazonaws.com")+ || (region == "us-east-1" && endpoint_url == "https://s3.amazonaws.com");+ Ok(Ok(S3CacheConfig {+ bucket: backend.getattr("bucket_name")?.extract::<String>()?,+ key_prefix: backend.getattr("key_prefix")?.extract::<String>()?,+ region,+ endpoint: (!default_endpoint).then_some(S3Endpoint { url: endpoint_url }),+ auth,+ }))+}++ #[inline(never)]+ fn project_standalone_client<'py>(+ client: &Bound<'py, PyAny>,+ ) -> PyResult<Result<RedisClientProjection<'py>, UnsupportedCacheConfig>> {+ let pool = client.getattr("connection_pool")?;+ if !instance_class_is(&pool, "redis.connection", "ConnectionPool")? {+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));+ }+ let resolved = pool.getattr("connection_kwargs")?.cast_into::<PyDict>()?;+ if has_value(&resolved, "redis_connect_func")? {+ return Ok(Err(UnsupportedCacheConfig::RedisCredentials));+ }+ let connection_class = resolved+ .get_item("connection_class")?+ .unwrap_or(pool.getattr("connection_class")?);+ let tls = if class_is(&connection_class, "redis.connection", "Connection")? {+ None+ } else if class_is(&connection_class, "redis.connection", "SSLConnection")? {+ Some(project_tls(&resolved)?)+ } else {+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));+ };+ Ok(Ok(RedisClientProjection {+ topology: RedisTopology::Standalone,+ host: required_string(&resolved, "host")?,+ port: port(required_i64(&resolved, "port")?)?,+ pool_size: pool.getattr("max_connections")?.extract::<usize>()?,+ resolved,+ tls,+ }))+ }++ #[inline(never)]+ fn project_cluster_client<'py>(+ source: &Bound<'py, PyDict>,+ client: &Bound<'py, PyAny>,+ ) -> PyResult<Result<RedisClientProjection<'py>, UnsupportedCacheConfig>> {+ let Some(startup_nodes) = startup_nodes(source)? else {+ return Ok(Err(UnsupportedCacheConfig::RedisTopology));+ };+ if !instance_class_is(client, "redis.cluster", "RedisCluster")? {+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));+ }+ let nodes = client.getattr("nodes_manager")?;+ if !class_is(+ &nodes.getattr("connection_pool_class")?,+ "redis.connection",+ "ConnectionPool",+ )? {+ return Ok(Err(UnsupportedCacheConfig::RedisConnection));+ }+ let resolved = nodes.getattr("connection_kwargs")?.cast_into::<PyDict>()?;+ if let Some(connect) = resolved.get_item("redis_connect_func")?+ && !connect.is_none()+ {+ let own_hook = connect+ .getattr("__self__")+ .is_ok_and(|owner| owner.is(client))+ && connect+ .getattr("__func__")+ .and_then(|function| Ok(function.is(&client.get_type().getattr("on_connect")?)))+ .unwrap_or(false);+ if !own_hook {+ return Ok(Err(UnsupportedCacheConfig::RedisCredentials));+ }+ }+ let tls = if optional_bool(&resolved, "ssl")?.unwrap_or(false) {+ Some(project_tls(&resolved)?)+ } else {+ None+ };+ let first = &startup_nodes[0];+ Ok(Ok(RedisClientProjection {+ host: first.host.clone(),+ port: first.port,+ pool_size: optional_i64(&resolved, "max_connections")?+ .map(|value| {+ usize::try_from(value).map_err(|_| PyValueError::new_err("invalid Redis pool size"))+ })+ .transpose()?+ .unwrap_or(REDIS_PY_DEFAULT_MAX_CONNECTIONS),+ topology: RedisTopology::Cluster { startup_nodes },+ resolved,+ tls,+ }))+ }++ #[inline(never)]+ fn startup_nodes(source: &Bound<'_, PyDict>) -> PyResult<Option<Vec<RedisNode>>> {+ let Some(nodes) = source.get_item("startup_nodes")? else {+ return Ok(None);+ };+ let Ok(nodes) = nodes.cast_into::<PyList>() else {+ return Ok(None);+ };+ if nodes.is_empty() {+ return Ok(None);+ }+ let mut parsed = Vec::with_capacity(nodes.len());+ for node in nodes.iter() {+ let Ok(node) = node.cast_into::<PyDict>() else {+ return Ok(None);+ };+ if node.len() != 2 || !has_value(&node, "host")? || !has_value(&node, "port")? {+ return Ok(None);+ }+ let (Ok(host), Ok(port)) = (+ required_string(&node, "host"),+ required_i64(&node, "port").and_then(port),+ ) else {+ return Ok(None);+ };+ parsed.push(RedisNode { host, port });+ }+ Ok(Some(parsed))+ }++ #[inline(never)]+ fn port(value: i64) -> PyResult<u16> {+ u16::try_from(value).map_err(|_| PyValueError::new_err("invalid Redis port"))+ }+#[inline(never)]fn project_tls(values: &Bound<'_, PyDict>) -> PyResult<RedisTlsConfig> {Ok(RedisTlsConfig {@@@ -614,6 -608,19 +748,20 @@@ mod testsRedisProtocol,};use crate::cache::native::NativeResponseCache;++ use litellm_cache_redis::{RedisNode, RedisTopology};++ fn cluster_facade<'py>(py: Python<'py>, startup_nodes: &str, hook: &str) -> Bound<'py, PyAny> {+ facade(+ py,+ &format!(+ "RedisCluster = type('RedisCluster', (), {{'__module__': 'redis.cluster', 'on_connect': lambda self, connection: None}})\n\+ client = RedisCluster()\n\+ client.nodes_manager = SimpleNamespace(connection_pool_class=ConnectionPool, connection_kwargs={{'password': 'secret', 'redis_connect_func': {hook}, 'protocol': 3, 'ssl': True, 'ssl_cert_reqs': 'none'}})\n\+ backend = SimpleNamespace(default_ttl=120, namespace='team', redis_flush_size=100, redis_kwargs={{'startup_nodes': {startup_nodes}, 'password': 'secret'}}, redis_client=client)\n\+ facade = SimpleNamespace(type='redis', mode='default-on', ttl=None, namespace='team', supported_call_types=None, redis_flush_size=100, semantic_cache_scope='key', cache=backend)"+ ),+ )+ }fn facade<'py>(py: Python<'py>, body: &str) -> Bound<'py, PyAny> {let locals = PyDict::new(py);@@@ -734,186 -741,86 +882,269 @@@});}+ fn s3_facade<'py>(py: Python<'py>, body: &str) -> Bound<'py, PyAny> {+ let locals = PyDict::new(py);+ py.run(+ &CString::new(format!(+ "from types import SimpleNamespace\n\+ S3Client = type('S3', (), {{'__module__': 'botocore.client'}})\n\+ client = S3Client()\n\+ client.meta = SimpleNamespace(region_name='us-east-1', endpoint_url='https://example.test', config=SimpleNamespace(s3=None, proxies=None, client_cert=None, signature_version='s3v4'))\n\+ client._endpoint = SimpleNamespace(http_session=SimpleNamespace(_verify=True))\n\+ client._request_signer = SimpleNamespace(_credentials=SimpleNamespace(method='explicit', access_key='key', secret_key='secret', token='token'))\n\+ backend = SimpleNamespace(bucket_name='bucket', key_prefix='team/', s3_client=client)\n\+ facade = SimpleNamespace(type='s3', mode='default-on', ttl=None, namespace=None, supported_call_types=[], redis_flush_size=None, semantic_cache_scope='key', cache=backend)\n\+ {body}"+ ))+ .unwrap(),+ None,+ Some(&locals),+ )+ .unwrap();+ locals.get_item("facade").unwrap().unwrap()+ }++ #[test]+ fn projects_s3_configuration_with_explicit_credentials_and_custom_endpoint() {+ Python::initialize();+ Python::attach(|py| {+ let facade = s3_facade(py, "");+ let CacheConfigProjection::Native(config) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("S3 cache should be supported");+ };+ let CacheBackendConfig::S3(s3) = config.backend else {+ panic!("expected S3 configuration");+ };+ assert_eq!(s3.bucket, "bucket");+ assert_eq!(s3.key_prefix, "team/");+ assert_eq!(s3.region, "us-east-1");+ assert_eq!(+ s3.endpoint.map(|endpoint| endpoint.url).as_deref(),+ Some("https://example.test")+ );+ assert_eq!(s3.auth.access_key_id.as_deref(), Some("key"));+ assert_eq!(s3.auth.secret_access_key.as_deref(), Some("secret"));+ assert_eq!(s3.auth.session_token.as_deref(), Some("token"));+ assert_eq!(s3.auth.region_name.as_deref(), Some("us-east-1"));+ });+ }++ #[test]+ fn default_s3_endpoint_projects_no_custom_endpoint() {+ Python::initialize();+ Python::attach(|py| {+ let facade = s3_facade(+ py,+ "facade.cache.s3_client.meta.endpoint_url = 'https://s3.us-east-1.amazonaws.com'",+ );+ let CacheConfigProjection::Native(config) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("S3 cache should be supported");+ };+ let CacheBackendConfig::S3(s3) = config.backend else {+ panic!("expected S3 configuration");+ };+ assert!(s3.endpoint.is_none());+ });+ }++ #[test]+ fn non_sigv4_proxies_and_disabled_verification_stay_on_python() {+ Python::initialize();+ Python::attach(|py| {+ for (body, message) in [+ (+ "facade.cache.s3_client.meta.config.signature_version = 's3'",+ "native S3 configuration requires Python",+ ),+ (+ "facade.cache.s3_client.meta.config.proxies = {'https': 'proxy'}",+ "native S3 configuration requires Python",+ ),+ (+ "facade.cache.s3_client._endpoint.http_session._verify = False",+ "native S3 configuration requires Python",+ ),+ (+ "del facade.cache.s3_client._endpoint.http_session._verify",+ "native S3 configuration requires Python",+ ),+ ] {+ let facade = s3_facade(py, body);+ let CacheConfigProjection::Unsupported(reason) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("{body} must stay on Python");+ };+ assert_eq!(reason.message(), message);+ }+ let facade = s3_facade(py, "facade.cache.s3_client = SimpleNamespace()");+ let CacheConfigProjection::Unsupported(reason) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("non-botocore client must stay on Python");+ };+ assert_eq!(reason.message(), "native S3 client type is not implemented");+ let facade = s3_facade(+ py,+ "facade.cache.s3_client._request_signer._credentials = None",+ );+ let CacheConfigProjection::Unsupported(reason) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("missing credentials must stay on Python");+ };+ assert_eq!(reason.message(), "native S3 credentials require Python");+ });+ }++ #[test]+ fn non_explicit_s3_credentials_use_the_default_chain() {+ Python::initialize();+ Python::attach(|py| {+ let facade = s3_facade(+ py,+ "facade.cache.s3_client._request_signer._credentials = SimpleNamespace(method='sso', access_key=None, secret_key=None, token=None)",+ );+ let CacheConfigProjection::Native(config) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("default-chain credentials should be supported");+ };+ let CacheBackendConfig::S3(s3) = config.backend else {+ panic!("expected S3 configuration");+ };+ assert_eq!(s3.auth.access_key_id, None);+ assert_eq!(s3.auth.secret_access_key, None);+ assert_eq!(s3.auth.region_name.as_deref(), Some("us-east-1"));+ });+ }++ fn s3_service(py: Python<'_>, region: &str, endpoint: Option<&str>) -> NativeResponseCache {+ let config = S3CacheConfig {+ bucket: "bucket".to_string(),+ key_prefix: "team/".to_string(),+ region: region.to_string(),+ endpoint: endpoint.map(|url| S3Endpoint {+ url: url.to_string(),+ }),+ auth: AwsAuthConfig::default(),+ };+ run_sync_value(py, async move { Ok(NativeResponseCache::s3(config).await) }).unwrap()+ }++ #[test]+ fn s3_binding_rejects_region_and_endpoint_mismatches() {+ Python::initialize();+ Python::attach(|py| {+ let facade = s3_facade(py, "");+ let CacheConfigProjection::Native(config) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("S3 cache should be supported");+ };+ assert_eq!(+ config.service_mismatch(&s3_service(py, "us-east-1", Some("https://example.test"))),+ None+ );+ assert_eq!(+ config.service_mismatch(&s3_service(py, "us-west-2", Some("https://example.test"))),+ Some("facade and native backend regions must match")+ );+ assert_eq!(+ config.service_mismatch(&s3_service(py, "us-east-1", Some("https://other.test"))),+ Some("facade and native backend endpoints must match")+ );+ assert_eq!(+ config.service_mismatch(&s3_service(py, "us-east-1", None)),+ Some("facade and native backend endpoints must match")+ );+ });+ }+++ #[test]+ fn projects_cluster_startup_nodes_as_redis_topology() {+ Python::initialize();+ Python::attach(|py| {+ let facade = cluster_facade(+ py,+ "[{'host': 'node-a', 'port': 7000}, {'host': 'node-b', 'port': 7001}]",+ "client.on_connect",+ );+ let CacheConfigProjection::Native(config) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("cluster startup nodes should project natively");+ };+ let CacheBackendConfig::Redis(redis) = &config.backend else {+ panic!("expected Redis configuration");+ };+ let expected = RedisTopology::Cluster {+ startup_nodes: vec![+ RedisNode {+ host: "node-a".into(),+ port: 7000,+ },+ RedisNode {+ host: "node-b".into(),+ port: 7001,+ },+ ],+ };+ assert_eq!(redis.topology, expected);+ assert_eq!(redis.connection.host, "node-a");+ assert_eq!(redis.connection.port, 7000);+ assert_eq!(redis.connection.password.as_deref(), Some("secret"));+ assert_eq!(redis.connection.protocol, RedisProtocol::Resp3);+ assert_eq!(+ redis+ .connection+ .tls+ .as_ref()+ .unwrap()+ .certificate_requirement,+ CertificateRequirement::None+ );+ });+ }++ #[test]+ fn malformed_startup_nodes_and_foreign_connect_hooks_stay_on_python() {+ Python::initialize();+ Python::attach(|py| {+ for (startup_nodes, hook, message) in [+ (+ "[{'host': 'node-a', 'port': 7000, 'server_type': 'primary'}]",+ "client.on_connect",+ "native Redis topology is not implemented",+ ),+ (+ "[{'host': 'node-a', 'port': 'seven'}]",+ "client.on_connect",+ "native Redis topology is not implemented",+ ),+ (+ "[]",+ "client.on_connect",+ "native Redis topology is not implemented",+ ),+ (+ "[{'host': 'node-a', 'port': 7000}]",+ "lambda connection: None",+ "native Redis credentials require Python",+ ),+ ] {+ let facade = cluster_facade(py, startup_nodes, hook);+ let CacheConfigProjection::Unsupported(reason) =+ NativeCacheConfig::project(&facade).unwrap()+ else {+ panic!("{startup_nodes} with {hook} must stay on Python");+ };+ assert_eq!(reason.message(), message, "{startup_nodes} with {hook}");+ }+ });+ }}diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rsindex 0f7b9778d3e,a9ce2ae7756..955367d969e--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs@@@ -29,13 -30,28 +30,31 @@@ struct RedisPoolGuardreference: Py<PyAny>,connection_class: Py<PyAny>,connection_kwargs: Py<PyAny>,- max_connections: usize,+ max_connections: Option<usize>,+ attributes: RedisPoolAttributes,}+struct S3ClientGuard {+ reference: Py<PyAny>,+}++ struct RedisPoolAttributes {+ pool: &'static str,+ connection_class: &'static str,+ max_connections: Option<&'static str>,+ }++ const STANDALONE_POOL: RedisPoolAttributes = RedisPoolAttributes {+ pool: "connection_pool",+ connection_class: "connection_class",+ max_connections: Some("max_connections"),+ };++ const CLUSTER_POOL: RedisPoolAttributes = RedisPoolAttributes {+ pool: "nodes_manager",+ connection_class: "connection_pool_class",+ max_connections: None,+ };-pub(super) struct FacadeGuard {outer: ObjectGuard,backend: ObjectGuard,@@@ -210,10 -218,15 +238,16 @@@ impl FacadeGuard"only exact built-in Cache facades can be registered",));}- let (module, name, cache_kind) = match kind {- "memory" => ("litellm.caching.in_memory_cache", "InMemoryCache", "local"),- "redis" => ("litellm.caching.redis_cache", "RedisCache", "redis"),- "s3" => ("litellm.caching.s3_cache", "S3Cache", "s3"),+ let cluster = matches!(service.topology(), Some(RedisTopology::Cluster { .. }));+ let (module, name, cache_kind) = match (kind, cluster) {+ ("memory", _) => ("litellm.caching.in_memory_cache", "InMemoryCache", "local"),+ ("redis", false) => ("litellm.caching.redis_cache", "RedisCache", "redis"),+ ("redis", true) => (+ "litellm.caching.redis_cluster_cache",+ "RedisClusterCache",+ "redis",+ ),++ ("s3", _) => ("litellm.caching.s3_cache", "S3Cache", "s3"),_ => unreachable!(),};let backend = facade.getattr("cache")?;@@@ -257,16 -270,13 +291,18 @@@"max_size_per_item","redis_kwargs","redis_flush_size",+ "bucket_name",+ "key_prefix",],)?,- redis_pool: (kind == "redis")- .then(|| RedisPoolGuard::capture(&backend))- .transpose()?,+ redis_pool: match (kind, cluster) {+ ("redis", false) => Some(RedisPoolGuard::capture(&backend, STANDALONE_POOL)?),+ ("redis", true) => Some(RedisPoolGuard::capture(&backend, CLUSTER_POOL)?),+ _ => None,+ },+ s3_client: (kind == "s3")+ .then(|| S3ClientGuard::capture(&backend))+ .transpose()?,})}diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rsindex 0d5a2ac9d8c,2ee2b0c2c8c..b922f89d7c4--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs@@@ -1,6 -1,5 +1,7 @@@+use litellm_auth_aws::AwsAuthConfig;+ use litellm_cache_redis::{RedisNode, RedisTopology};-use litellm_host_python::release_gil;+use litellm_cache_s3::{S3CacheConfig, S3Endpoint};+use litellm_host_python::{release_gil, run_sync_value};use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*};use super::{cache_error, facade::FacadeGuard, native::NativeResponseCache, request::duration};diff --cc litellm-rust/crates/python-bridge/src/cache/native.rsindex a6eef420ace,b23038dee65..78be6a243d7--- a/litellm-rust/crates/python-bridge/src/cache/native.rs+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs@@@ -109,6 -69,13 +111,14 @@@ impl NativeResponseCache}}+ pub fn topology(&self) -> Option<&RedisTopology> {+ match self {+ Self::Memory(_) => None,+ Self::Redis { cache, .. } => Some(cache.backend().topology()),++ Self::S3(_) => None,+ }+ }+pub fn capacity(&self) -> Option<usize> {match self {Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),diff --cc tests/test_litellm_rust/test_cache.pyindex f18454ea8d1,3903ef65daa..f786384633d--- a/tests/test_litellm_rust/test_cache.py+++ b/tests/test_litellm_rust/test_cache.py@@@ -20,7 -18,7 +21,8 @@@ import rediimport litellmfrom litellm.caching.caching import Cache, disable_cache, enable_cache, update_cachefrom litellm.caching.in_memory_cache import InMemoryCache+from litellm.caching.s3_cache import S3Cache+ from litellm.caching.redis_cluster_cache import RedisClusterCachefrom litellm.rust_bridge import _nativefrom litellm.types.caching import LiteLLMCacheTypefrom tests.test_litellm_rust.support.isolation import rebound@@@ -400,178 -405,62 +410,239 @@@ async def test_redis_facade_buffers_natclient.close()+def s3_stub() -> Generator[S3Stub]:+ stub: Final = S3Stub()+ try:+ yield stub+ finally:+ stub.close()+++def python_s3(url: str) -> S3Cache:+ return S3Cache(+ s3_bucket_name="cache-bucket",+ s3_region_name="us-east-1",+ s3_endpoint_url=url,+ s3_aws_access_key_id="key",+ s3_aws_secret_access_key="secret",+ s3_path="team",+ )+++async def test_s3_reads_python_entries_and_writes_with_python_metadata(s3_stub: S3Stub) -> None:+ python_cache: Final = python_s3(s3_stub.url)+ response: Final = {"choices": [{"text": "cached"}], "usage": {"total_tokens": 3}}+ python_cache.set_cache("sync:key", {"timestamp": time.time(), "response": response}, ttl=90)+ python_cache.set_cache("plain", {"timestamp": time.time(), "response": response})+ s3_stub.put_object("team/malformed", b"not a cache entry")+ s3_stub.put_object(+ "team/expired",+ json.dumps({"timestamp": time.time(), "response": response}).encode(),+ {"expires": "Thu, 01 Jan 1970 00:00:00 GMT"},+ )+ binding: Final = _native._CacheTestResolver(+ SimpleNamespace(+ cache=_native._CacheTestHandle.s3(+ "cache-bucket",+ region="us-east-1",+ endpoint_url=s3_stub.url,+ key_prefix="team/",+ access_key_id="key",+ secret_access_key="secret",+ )+ )+ ).resolve()++ assert binding.lookup(request("sync:key")) == response+ assert await binding.async_lookup(request("plain")) == response+ assert binding.lookup(request("malformed")) is None+ assert binding.lookup(request("expired")) is None+ assert binding.lookup(request("absent")) is None++ binding.store({**request("native:key"), "ttl_seconds": 90.0}, response)+ await binding.async_store(request("no_ttl"), response)+ stored: Final = s3_stub.objects["team/native/key"]+ assert stored.headers["content-type"] == "application/json"+ assert stored.headers["content-language"] == "en"+ assert stored.headers["content-disposition"] == 'inline; filename="team/native/key.json"'+ assert stored.headers["cache-control"] == "immutable, max-age=90, s-maxage=90"+ expires: Final = cast(datetime, s3_stub.expires("team/native/key"))+ remaining: Final = (expires - datetime.now(expires.tzinfo)).total_seconds()+ assert 60 < remaining <= 91+ no_ttl: Final = s3_stub.objects["team/no_ttl"]+ assert no_ttl.headers["cache-control"] == "immutable, max-age=31536000, s-maxage=31536000"+ assert "expires" not in no_ttl.headers+ assert python_cache.get_cache("native:key")["response"] == response++ partial: Final = await binding.async_lookup_batch([request("native:key"), request("absent"), request("malformed")])+ assert partial == {"values": [response, None, None], "missing_indices": [1, 2]}+++def test_s3_facade_binds_only_exact_configuration_and_falls_back_on_mutation(s3_stub: S3Stub) -> None:+ facade: Final = Cache(+ type=LiteLLMCacheType.S3,+ s3_bucket_name="cache-bucket",+ s3_region_name="us-east-1",+ s3_endpoint_url=s3_stub.url,+ s3_aws_access_key_id="key",+ s3_aws_secret_access_key="secret",+ s3_path="team",+ )+ handle: Final = _native._CacheTestHandle.s3(+ "cache-bucket",+ region="us-east-1",+ endpoint_url=s3_stub.url,+ key_prefix="team/",+ access_key_id="key",+ secret_access_key="secret",+ )+ with pytest.raises(TypeError, match="buckets must match"):+ _native._CacheTestHandle.s3("other", region="us-east-1", endpoint_url=s3_stub.url)._bind_facade(facade)+ with pytest.raises(TypeError, match="key prefixes must match"):+ _native._CacheTestHandle.s3(+ "cache-bucket", region="us-east-1", endpoint_url=s3_stub.url, key_prefix="other/"+ )._bind_facade(facade)+ handle._bind_facade(facade)+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))+ binding: Final = resolver.resolve()+ assert binding.kind == "native"++ calls: Final = []+ facade.cache.s3_client.meta.events.register("before-call.s3.*", lambda **_kwargs: calls.append(1))+ binding.store(request("native"), {"answer": 1})+ assert binding.lookup(request("native")) == {"answer": 1}+ assert calls == []+ assert "team/native" in s3_stub.objects++ with rebound(facade.cache, "bucket_name", "other"):+ assert resolver.resolve().kind == "python_callback"+ other_client: Final = boto3.client(+ "s3",+ region_name="us-east-1",+ endpoint_url=s3_stub.url,+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ )+ with rebound(facade.cache, "s3_client", other_client):+ assert resolver.resolve().kind == "python_callback"++ class CustomS3Cache(S3Cache):+ pass++ subclassed: Final = Cache(+ type=LiteLLMCacheType.S3,+ s3_bucket_name="cache-bucket",+ s3_region_name="us-east-1",+ s3_endpoint_url=s3_stub.url,+ s3_aws_access_key_id="key",+ s3_aws_secret_access_key="secret",+ s3_path="team",+ )+ subclassed.cache = CustomS3Cache(+ s3_bucket_name="cache-bucket",+ s3_region_name="us-east-1",+ s3_endpoint_url=s3_stub.url,+ s3_aws_access_key_id="key",+ s3_aws_secret_access_key="secret",+ s3_path="team",+ )+ with pytest.raises(TypeError):+ handle._bind_facade(subclassed)+ assert _native._CacheTestResolver(SimpleNamespace(cache=subclassed)).resolve().kind == "python_callback"+++def test_s3_facade_rejects_configurations_that_require_python(s3_stub: S3Stub) -> None:+ handle: Final = _native._CacheTestHandle.s3(+ "cache-bucket",+ region="us-east-1",+ endpoint_url=s3_stub.url,+ key_prefix="team/",+ access_key_id="key",+ secret_access_key="secret",+ )+ unverified: Final = Cache(+ type=LiteLLMCacheType.S3,+ s3_bucket_name="cache-bucket",+ s3_region_name="us-east-1",+ s3_endpoint_url="https://s3.example.test",+ s3_aws_access_key_id="key",+ s3_aws_secret_access_key="secret",+ s3_path="team",+ s3_verify=False,+ )+ with pytest.raises(TypeError, match="requires Python"):+ handle._bind_facade(unverified)+ proxied: Final = Cache(+ type=LiteLLMCacheType.S3,+ s3_bucket_name="cache-bucket",+ s3_region_name="us-east-1",+ s3_endpoint_url=s3_stub.url,+ s3_aws_access_key_id="key",+ s3_aws_secret_access_key="secret",+ s3_path="team",+ s3_config=botocore.config.Config(proxies={"https": "http://proxy.test"}),+ )+ with pytest.raises(TypeError, match="requires Python"):+ handle._bind_facade(proxied)+++++ async def test_redis_cluster_facade_serves_multi_slot_batches_and_scoped_flush_natively(+ cluster_nodes: tuple[tuple[str, int], ...],+ ) -> None:+ startup_nodes: Final = [{"host": host, "port": port} for host, port in cluster_nodes]+ url: Final = f"redis://{cluster_nodes[0][0]}:{cluster_nodes[0][1]}"+ with rebound(litellm, "default_redis_ttl", 60):+ facade: Final = Cache(type=LiteLLMCacheType.REDIS, redis_startup_nodes=startup_nodes, namespace="parity")+ assert type(facade.cache) is RedisClusterCache+ with pytest.raises(TypeError, match="types must match"):+ _native._CacheTestHandle.redis(url, namespace="parity")._bind_facade(facade)+ _native._CacheTestHandle.redis(url, namespace="parity", startup_nodes=list(cluster_nodes))._bind_facade(facade)+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))+ assert resolver.resolve().kind == "native"++ manager: Final = facade.cache.redis_client.nodes_manager+ with rebound(manager, "connection_kwargs", {**manager.connection_kwargs, "db": 1}):+ assert resolver.resolve().kind == "python_callback"+ with rebound(facade.cache, "redis_kwargs", {**facade.cache.redis_kwargs, "startup_nodes": startup_nodes[:1]}):+ assert resolver.resolve().kind == "python_callback"+ binding: Final = resolver.resolve()+ assert binding.kind == "native"++ client: Final = redis.RedisCluster(startup_nodes=[redis.cluster.ClusterNode(*node) for node in cluster_nodes])+ keys: Final = tuple(f"slot-{index}" for index in range(12))+ slots: Final = {client.keyslot(f"parity:{key}") for key in keys}+ assert len(slots) > 1, slots+ requests: Final = [request(key) for key in keys]+ values: Final = [{"index": index} for index in range(len(keys))]+ await binding.async_store_batch(requests, values)+ client.set("parity:slot-3", "not a cache entry")+ client.set("parity:slot-7", json.dumps({"timestamp": time.time(), "response": {"index": 7, "python": True}}))++ batch: Final = await binding.async_lookup_batch(requests)+ assert batch == {+ "values": [+ None if index == 3 else {"index": 7, "python": True} if index == 7 else value+ for index, value in enumerate(values)+ ],+ "missing_indices": [3],+ }+ assert facade.cache.get_cache("parity:slot-0")["response"] == {"index": 0}+ assert (await facade.cache.async_get_cache("parity:slot-11"))["response"] == {"index": 11}+ assert facade.cache.redis_client.mget_nonatomic([f"parity:{key}" for key in keys[:2]]) == [+ client.get("parity:slot-0"),+ client.get("parity:slot-1"),+ ]++ await binding.async_store({**request("pinned"), "ttl_seconds": 12.0}, {"pinned": True})+ assert 0 < client.ttl("parity:pinned") <= 12+ client.set("unscoped", "stays")++ await binding.async_flush()++ remaining: Final = tuple(sorted(key for node in client.get_primaries() for key in client.keys("parity:*", target_nodes=node)))+ assert remaining == (), remaining+ assert client.get("unscoped") == b"stays"+ client.delete("unscoped")+ client.close()+ facade.cache.redis_client.close()