Skip to content

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]

Merge remote-tracking branch 'origin/main' into litellm_rust_cache_s3

Yujong Lee911e320b9520
diff --cc litellm-rust/Cargo.toml
index 5800c1c611b,fabec9bcd6c..a3889a009ec
--- a/litellm-rust/Cargo.toml
+++ b/litellm-rust/Cargo.toml
@@@ -32,7 -32,7 +32,8 @@@ litellm-cache = { path = "crates/cache
litellm-cache-azure-blob = { path = "crates/cache-azure-blob" }
litellm-cache-memory = { path = "crates/cache-memory" }
litellm-cache-redis = { path = "crates/cache-redis" }
+litellm-cache-s3 = { path = "crates/cache-s3" }
+ litellm-cache-disk = { path = "crates/cache-disk" }
litellm-cache-response = { path = "crates/cache-response" }
litellm-token-counter = { path = "crates/token-counter" }
litellm-token-counter-fast = { path = "crates/token-counter-fast" }
diff --cc litellm-rust/crates/python-bridge/Cargo.toml
index cbf9eac0caf,f5d08850b39..094137bed99
--- a/litellm-rust/crates/python-bridge/Cargo.toml
+++ b/litellm-rust/crates/python-bridge/Cargo.toml
@@@ -24,7 -24,7 +24,8 @@@ litellm-cache.workspace = tru
litellm-cache-azure-blob.workspace = true
litellm-cache-memory.workspace = true
litellm-cache-redis.workspace = true
+litellm-cache-s3.workspace = true
+ litellm-cache-disk.workspace = true
litellm-cache-response.workspace = true
serde.workspace = true
litellm-auth.workspace = true
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index 554db7adf81,927017e2e60..58e4f57b227
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -1,13 -1,11 +1,13 @@@
- use std::time::Duration;
+ use std::{path::PathBuf, 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, PyDict, PyList, PyString},
+ types::{PyAny, PyBool, PyDict, PyList, PyString},
};
use super::{native::NativeResponseCache, request::duration};
@@@ -96,7 -98,7 +100,8 @@@ const REDIS_PY_DEFAULT_MAX_CONNECTIONS
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ S3(Box<S3CacheConfig>),
+ Disk(DiskCacheConfig),
AzureBlob(AzureBlobCacheConfig),
}
@@@ -112,9 -114,7 +117,10 @@@ pub(super) enum UnsupportedCacheConfig
RedisCredentials,
RedisConnection,
RedisOption,
+ S3Client,
+ S3Credentials,
+ S3Option,
+ DiskStore,
}
impl UnsupportedCacheConfig {
@@@ -125,9 -125,7 +131,10 @@@
Self::RedisCredentials => "native Redis credentials require Python",
Self::RedisConnection => "native Redis connection type is not implemented",
Self::RedisOption => "native Redis configuration requires Python",
+ Self::S3Client => "native S3 client type is not implemented",
+ Self::S3Credentials => "native S3 credentials require Python",
+ Self::S3Option => "native S3 configuration requires Python",
+ Self::DiskStore => "native disk cache requires the built-in diskcache store",
}
}
}
@@@ -170,13 -168,13 +177,20 @@@ impl NativeCacheConfig
}))),
Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
},
+ Some(CacheType::S3) => match project_s3(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::S3(Box::new(backend)),
+ }))),
+ Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
+ },
+ Some(CacheType::Disk) => match project_disk(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::Disk(backend),
+ }))),
+ Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
+ },
Some(CacheType::AzureBlob) => project_azure_blob(&backend).map(|backend| {
CacheConfigProjection::Native(Box::new(Self {
policy,
@@@ -186,7 -184,7 +200,6 @@@
Some(
CacheType::RedisSemantic
| CacheType::ValkeySemantic
- | CacheType::Disk
- | CacheType::S3
| CacheType::QdrantSemantic
| CacheType::Gcs,
)
@@@ -200,7 -198,7 +213,8 @@@
let default_ttl = match &self.backend {
CacheBackendConfig::Memory(config) => Some(config.default_ttl),
CacheBackendConfig::Redis(config) => Some(config.default_ttl),
+ CacheBackendConfig::S3(_) => None,
+ CacheBackendConfig::Disk(_) => None,
CacheBackendConfig::AzureBlob(_) => None,
};
if service.default_ttl() != default_ttl {
@@@ -228,30 -226,17 +242,41 @@@
CacheBackendConfig::Redis(config) => (service.namespace()
!= config.namespace.as_deref())
.then_some("facade and native backend namespaces must match"),
+ CacheBackendConfig::S3(_) if service.kind() != "s3" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::S3(config) if service.bucket() != Some(config.bucket.as_str()) => {
+ Some("facade and native backend buckets must match")
+ }
+ CacheBackendConfig::S3(config)
+ if service.key_prefix() != Some(config.key_prefix.as_str()) =>
+ {
+ Some("facade and native backend key prefixes must match")
+ }
+ CacheBackendConfig::S3(config) if service.region() != Some(config.region.as_str()) => {
+ Some("facade and native backend regions must match")
+ }
+ CacheBackendConfig::S3(config)
+ if service.endpoint()
+ != config
+ .endpoint
+ .as_ref()
+ .map(|endpoint| endpoint.url.as_str()) =>
+ {
+ Some("facade and native backend endpoints must match")
+ }
+ CacheBackendConfig::S3(_) => None,
+ CacheBackendConfig::Disk(_) if service.kind() != "disk" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::Disk(config) => {
+ let Some(directory) = service.directory() else {
+ return Some("facade and native backend types must match");
+ };
+ let native = std::fs::canonicalize(directory).ok();
+ let facade = std::fs::canonicalize(&config.directory).ok();
+ (native != facade).then_some("facade and native backend directories must match")
+ }
CacheBackendConfig::AzureBlob(config) => match service.azure_blob_identity() {
None => Some("facade and native backend types must match"),
Some((account_url, container))
@@@ -772,16 -676,13 +812,16 @@@ mod tests
use pyo3::{prelude::*, types::PyDict};
- use litellm_cache_redis::{RedisNode, RedisTopology};
+ use litellm_auth_aws::AwsAuthConfig;
+ use litellm_cache_s3::{S3CacheConfig, S3Endpoint};
+ use litellm_host_python::run_sync_value;
use super::{
- CacheBackendConfig, CacheConfigProjection, CertificateRequirement, NativeCacheConfig,
- RedisProtocol,
+ CacheBackendConfig, CacheConfigProjection, CachePolicy, CertificateRequirement,
+ DiskCacheConfig, NativeCacheConfig, RedisProtocol,
};
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(
@@@ -914,190 -815,86 +954,269 @@@
assert_eq!(reason.message(), "native Redis credentials require Python");
});
}
+ #[test]
+ fn projects_builtin_disk_configuration_and_rejects_custom_stores() {
+ Python::initialize();
+ Python::attach(|py| {
+ let root =
+ std::env::temp_dir().join(format!("litellm-disk-config-{}", std::process::id()));
+ let directory = root.to_string_lossy();
+ let disk_facade = facade(
+ py,
+ &format!(
+ "Cache = type('Cache', (), {{'__module__': 'diskcache.core'}})\n\
+ Disk = type('Disk', (), {{'__module__': 'diskcache.core'}})\n\
+ store = Cache()\n\
+ store._disk = Disk()\n\
+ store.directory = {directory:?}\n\
+ backend = SimpleNamespace(disk_cache=store)\n\
+ facade = SimpleNamespace(type='disk', mode='default-on', ttl=None, namespace=None, supported_call_types=None, redis_flush_size=None, semantic_cache_scope='key', cache=backend)"
+ ),
+ );
+ let CacheConfigProjection::Native(config) =
+ NativeCacheConfig::project(&disk_facade).unwrap()
+ else {
+ panic!("disk cache should be supported");
+ };
+ let CacheBackendConfig::Disk(disk) = config.backend else {
+ panic!("expected disk configuration");
+ };
+ assert_eq!(disk.directory, root);
+ let matching = NativeResponseCache::disk(&directory).unwrap();
+ assert_eq!(
+ (NativeCacheConfig {
+ policy: config.policy,
+ backend: CacheBackendConfig::Disk(disk),
+ })
+ .service_mismatch(&matching),
+ None
+ );
+ let other = NativeResponseCache::disk(&root.join("other").to_string_lossy()).unwrap();
+ let mismatch = NativeCacheConfig {
+ policy: CachePolicy {
+ mode: "default-on".into(),
+ ttl: None,
+ namespace: None,
+ supported_call_types: None,
+ redis_flush_size: None,
+ semantic_cache_scope: "key".into(),
+ },
+ backend: CacheBackendConfig::Disk(DiskCacheConfig {
+ directory: root.clone(),
+ }),
+ };
+ assert_eq!(
+ mismatch.service_mismatch(&other),
+ Some("facade and native backend directories must match")
+ );
+
+ let custom = facade(
+ py,
+ &format!(
+ "CustomCache = type('CustomCache', (), {{'__module__': 'mypkg'}})\n\
+ CustomDisk = type('CustomDisk', (), {{'__module__': 'mypkg'}})\n\
+ store = CustomCache()\n\
+ store._disk = CustomDisk()\n\
+ store.directory = {directory:?}\n\
+ backend = SimpleNamespace(disk_cache=store)\n\
+ facade = SimpleNamespace(type='disk', mode='default-on', ttl=None, namespace=None, supported_call_types=None, redis_flush_size=None, semantic_cache_scope='key', cache=backend)"
+ ),
+ );
+ let CacheConfigProjection::Unsupported(reason) =
+ NativeCacheConfig::project(&custom).unwrap()
+ else {
+ panic!("custom disk store must stay on Python");
+ };
+ assert_eq!(
+ reason.message(),
+ "native disk cache requires the built-in diskcache store"
+ );
+ });
+ }
+ 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();
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index 81f3a1f66d4,ee6423daf6e..e3e04b9ddf6
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -34,10 -34,11 +34,14 @@@ struct RedisPoolGuard
attributes: RedisPoolAttributes,
}
+struct S3ClientGuard {
+ reference: Py<PyAny>,
+}
+
+ struct DiskStoreGuard {
+ reference: Py<PyAny>,
+ directory: String,
+ }
-
struct AzureBlobClientGuard {
sync_client: Py<PyAny>,
async_client: Py<PyAny>,
@@@ -221,22 -223,26 +226,41 @@@ impl RedisPoolGuard
}
}
+impl S3ClientGuard {
+ fn capture(backend: &Bound<'_, PyAny>) -> PyResult<Self> {
+ Ok(Self {
+ reference: backend.getattr("s3_client")?.unbind(),
+ })
+ }
+
+ fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {
+ Ok(self.reference.bind(py).is(&backend.getattr("s3_client")?))
+ }
+
+ fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {
+ visit.call(&self.reference)
+ }
+}
+
+ impl DiskStoreGuard {
+ fn capture(backend: &Bound<'_, PyAny>) -> PyResult<Self> {
+ let store = backend.getattr("disk_cache")?;
+ Ok(Self {
+ reference: store.clone().unbind(),
+ directory: store.getattr("directory")?.extract()?,
+ })
+ }
+
+ fn matches(&self, py: Python<'_>, backend: &Bound<'_, PyAny>) -> PyResult<bool> {
+ let store = backend.getattr("disk_cache")?;
+ Ok(self.reference.bind(py).is(&store)
+ && self.directory == store.getattr("directory")?.extract::<String>()?)
+ }
+
+ fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> {
+ visit.call(&self.reference)
+ }
+ }
-
impl AzureBlobClientGuard {
fn capture(backend: &Bound<'_, PyAny>) -> PyResult<Self> {
let sync_client = backend.getattr("container_client")?;
@@@ -316,7 -320,7 +340,8 @@@ impl FacadeGuard
"RedisClusterCache",
"redis",
),
+ ("s3", _) => ("litellm.caching.s3_cache", "S3Cache", "s3"),
+ ("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),
("azure-blob", _) => (
"litellm.caching.azure_blob_cache",
"AzureBlobCache",
@@@ -365,10 -369,11 +390,13 @@@
"max_size_per_item",
"redis_kwargs",
"redis_flush_size",
+ "bucket_name",
+ "key_prefix",
],
)?,
+ disk_store: (kind == "disk")
+ .then(|| DiskStoreGuard::capture(&backend))
+ .transpose()?,
connection: ConnectionGuard::capture(kind, cluster, &backend)?,
})
}
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index 98a869372b3,6e12e12040b..76a7a1d041a
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -66,40 -64,18 +66,52 @@@ impl CacheTestHandle
})
}
+ #[staticmethod]
+ #[allow(clippy::too_many_arguments)]
+ #[pyo3(signature = (bucket, *, region, endpoint_url=None, key_prefix="", access_key_id=None, secret_access_key=None, session_token=None))]
+ fn s3(
+ py: Python<'_>,
+ bucket: String,
+ region: String,
+ endpoint_url: Option<String>,
+ key_prefix: &str,
+ access_key_id: Option<String>,
+ secret_access_key: Option<String>,
+ session_token: Option<String>,
+ ) -> PyResult<Self> {
+ let config = S3CacheConfig {
+ bucket,
+ key_prefix: key_prefix.to_string(),
+ region: region.clone(),
+ endpoint: endpoint_url.map(|url| S3Endpoint { url }),
+ auth: AwsAuthConfig {
+ access_key_id,
+ secret_access_key,
+ session_token,
+ region_name: Some(region),
+ ..Default::default()
+ },
+ };
+ let service = run_sync_value(py, async move { Ok(NativeResponseCache::s3(config).await) })?;
+ Ok(Self {
+ service,
+ guard: None,
+ pid: std::process::id(),
+ })
+ }
+
+ #[staticmethod]
+ #[pyo3(signature = (directory))]
+ fn disk(py: Python<'_>, directory: String) -> PyResult<Self> {
+ let service =
+ release_gil(py, move || NativeResponseCache::disk(&directory)).map_err(cache_error)?;
+ Ok(Self {
+ service,
+ guard: None,
+ pid: std::process::id(),
+ })
+ }
+
#[staticmethod]
#[pyo3(signature = (account_url, container))]
fn azure_blob(py: Python<'_>, account_url: String, container: String) -> PyResult<Self> {
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index ff3deb43a47,80789cc279a..c56c5f8d87f
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -17,7 -17,7 +18,8 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ S3(Arc<ResponseCache<S3Cache<ResponseCacheCodec>>>),
+ Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),
AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
@@@ -49,14 -49,10 +51,18 @@@ impl NativeResponseCache
buffer: None,
})
}
+ pub async fn s3(config: S3CacheConfig) -> Self {
+ let runtime = tokio::runtime::Handle::current();
+ Self::S3(Arc::new(ResponseCache::new(Arc::new(S3Cache::new(
+ config,
+ ResponseCacheCodec,
+ runtime,
+ )))))
+ }
+ pub fn disk(directory: &str) -> Result<Self, Error> {
+ let cache = DiskCache::open(directory, ResponseCacheCodec)?;
+ Ok(Self::Disk(Arc::new(ResponseCache::new(Arc::new(cache)))))
+ }
pub async fn azure_blob(account_url: &str, container: &str) -> Result<Self, Error> {
let backend = AzureBlobCache::connect(
@@@ -77,7 -73,7 +83,7 @@@
cache.backend().account_url(),
cache.backend().container_name(),
)),
- Self::Memory(_) | Self::Redis { .. } | Self::S3(_) => None,
- Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::S3(_) | Self::Disk(_) => None,
}
}
}
@@@ -87,7 -83,7 +93,8 @@@ impl NativeResponseCache
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::S3(_) => "s3",
+ Self::Disk(_) => "disk",
Self::AzureBlob(_) => "azure-blob",
}
}
@@@ -96,66 -92,36 +103,67 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::S3(cache) => cache.default_ttl(),
+ Self::Disk(cache) => cache.default_ttl(),
Self::AzureBlob(cache) => cache.default_ttl(),
}
}
+ pub fn bucket(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => Some(cache.backend().bucket()),
+ _ => None,
+ }
+ }
+
+ pub fn key_prefix(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => Some(cache.backend().key_prefix()),
+ _ => None,
+ }
+ }
+
+ pub fn region(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => Some(cache.backend().region()),
+ _ => None,
+ }
+ }
+
+ pub fn endpoint(&self) -> Option<&str> {
+ match self {
+ Self::S3(cache) => cache.backend().endpoint(),
+ _ => None,
+ }
+ }
+
pub fn namespace(&self) -> Option<&str> {
match self {
- Self::Memory(_) | Self::AzureBlob(_) => None,
+ Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
+ Self::S3(_) => None,
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::AzureBlob(_) => None,
+ Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => 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()),
- Self::Redis { .. } | Self::S3(_) | Self::AzureBlob(_) => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::S3(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
}
}
pub fn max_entry_bytes(&self) -> Option<usize> {
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
- Self::Redis { .. } | Self::S3(_) | Self::AzureBlob(_) => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) => None,
++ Self::Redis { .. } | Self::S3(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
}
}
@@@ -169,6 -135,13 +177,13 @@@
}
}
+ pub fn directory(&self) -> Option<&Path> {
+ match self {
+ Self::Disk(cache) => Some(cache.backend().directory()),
- Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::S3(_) | Self::AzureBlob(_) => None,
+ }
+ }
+
pub fn lookup(
&self,
request: &ResponseCacheRequest,
@@@ -177,7 -150,7 +192,8 @@@
match self {
Self::Memory(cache) => cache.lookup(request, now),
Self::Redis { cache, .. } => cache.lookup(request, now),
+ Self::S3(cache) => cache.lookup(request, now),
+ Self::Disk(cache) => cache.lookup(request, now),
Self::AzureBlob(cache) => cache.lookup(request, now),
}
}
@@@ -191,7 -164,7 +207,8 @@@
match self {
Self::Memory(cache) => cache.store(request, response, now),
Self::Redis { cache, .. } => cache.store(request, response, now),
+ Self::S3(cache) => cache.store(request, response, now),
+ Self::Disk(cache) => cache.store(request, response, now),
Self::AzureBlob(cache) => cache.store(request, response, now),
}
}
@@@ -204,7 -177,7 +221,8 @@@
match self {
Self::Memory(cache) => cache.lookup_batch(requests, now),
Self::Redis { cache, .. } => cache.lookup_batch(requests, now),
+ Self::S3(cache) => cache.lookup_batch(requests, now),
+ Self::Disk(cache) => cache.lookup_batch(requests, now),
Self::AzureBlob(cache) => cache.lookup_batch(requests, now),
}
}
@@@ -217,7 -190,7 +235,8 @@@
match self {
Self::Memory(cache) => cache.async_lookup(request, now).await,
Self::Redis { cache, .. } => cache.async_lookup(request, now).await,
+ Self::S3(cache) => cache.async_lookup(request, now).await,
+ Self::Disk(cache) => cache.async_lookup(request, now).await,
Self::AzureBlob(cache) => cache.async_lookup(request, now).await,
}
}
@@@ -238,7 -211,7 +257,8 @@@
cache,
buffer: Some(buffer),
} => buffer.async_store(cache, request, response, now).await,
+ Self::S3(cache) => cache.async_store(request, response, now).await,
+ Self::Disk(cache) => cache.async_store(request, response, now).await,
Self::AzureBlob(cache) => cache.async_store(request, response, now).await,
}
}
@@@ -251,7 -224,7 +271,8 @@@
match self {
Self::Memory(cache) => cache.async_lookup_batch(requests, now).await,
Self::Redis { cache, .. } => cache.async_lookup_batch(requests, now).await,
+ Self::S3(cache) => cache.async_lookup_batch(requests, now).await,
+ Self::Disk(cache) => cache.async_lookup_batch(requests, now).await,
Self::AzureBlob(cache) => cache.async_lookup_batch(requests, now).await,
}
}
@@@ -264,7 -237,7 +285,8 @@@
match self {
Self::Memory(cache) => cache.async_store_batch(entries, now).await,
Self::Redis { cache, .. } => cache.async_store_batch(entries, now).await,
+ Self::S3(cache) => cache.async_store_batch(entries, now).await,
+ Self::Disk(cache) => cache.async_store_batch(entries, now).await,
Self::AzureBlob(cache) => cache.async_store_batch(entries, now).await,
}
}
@@@ -278,7 -251,7 +300,8 @@@
}
cache.async_flush().await
}
+ Self::S3(cache) => cache.async_flush().await,
+ Self::Disk(cache) => cache.async_flush().await,
Self::AzureBlob(cache) => cache.async_flush().await,
}
}
@@@ -287,7 -260,7 +310,8 @@@
match self {
Self::Memory(cache) => cache.test_connection().await,
Self::Redis { cache, .. } => cache.test_connection().await,
+ Self::S3(cache) => cache.test_connection().await,
+ Self::Disk(cache) => cache.test_connection().await,
Self::AzureBlob(cache) => cache.test_connection().await,
}
}
diff --cc litellm/rust_bridge/_native.pyi
index 3f747dadc56,05a6df6d5af..057a83611fa
--- a/litellm/rust_bridge/_native.pyi
+++ b/litellm/rust_bridge/_native.pyi
@@@ -93,99 -93,6 +93,101 @@@ class ResponsesWebSocketConnection
def recv_text(self) -> Future[str | None]: ...
def close(self) -> Future[None]: ...
+@final
+class _CacheTestBinding:
+ @property
+ def kind(self) -> str: ...
+ def lookup(
+ self,
+ request: object,
+ *,
+ callback_kwargs: Mapping[str, object] | Sequence[object] | None = None,
+ ) -> object: ...
+ def store(
+ self,
+ request: object,
+ response: object,
+ *,
+ callback_kwargs: Mapping[str, object] | None = None,
+ ) -> None: ...
+ def lookup_batch(
+ self,
+ requests: Sequence[object],
+ *,
+ callback_kwargs: Sequence[object] | None = None,
+ ) -> object: ...
+ def async_lookup(
+ self,
+ request: object,
+ *,
+ callback_kwargs: Mapping[str, object] | None = None,
+ ) -> Future[object]: ...
+ def async_store(
+ self,
+ request: object,
+ response: object,
+ *,
+ callback_kwargs: Mapping[str, object] | None = None,
+ ) -> Future[None]: ...
+ def async_lookup_batch(
+ self,
+ requests: Sequence[object],
+ *,
+ callback_kwargs: Sequence[object] | None = None,
+ ) -> Future[object]: ...
+ def async_store_batch(
+ self,
+ requests: Sequence[object],
+ responses: Sequence[object],
+ *,
+ callback_result: object = None,
+ callback_kwargs: Mapping[str, object] | None = None,
+ ) -> Future[object]: ...
+ def async_flush(self) -> Future[None]: ...
+ def ping(self) -> Future[object]: ...
+
+@final
+class _CacheTestHandle:
+ def __new__(cls, _uninstantiable: Never, /) -> Never: ...
+ @staticmethod
+ def memory(
+ *,
+ capacity: int = 200,
+ ttl_seconds: float = 600.0,
+ max_entry_bytes: int = 1048576,
+ ) -> _CacheTestHandle: ...
+ @staticmethod
+ def redis(
+ url: str,
+ *,
+ ttl_seconds: float = 60.0,
+ namespace: str | None = None,
+ startup_nodes: Sequence[tuple[str, int]] | None = None,
+ ) -> _CacheTestHandle: ...
+ @staticmethod
++ def disk(directory: str) -> _CacheTestHandle: ...
++ @staticmethod
+ def azure_blob(account_url: str, container: str) -> _CacheTestHandle: ...
+ @staticmethod
+ def s3(
+ bucket: str,
+ *,
+ region: str,
+ endpoint_url: str | None = None,
+ key_prefix: str = "",
+ access_key_id: str | None = None,
+ secret_access_key: str | None = None,
+ session_token: str | None = None,
+ ) -> _CacheTestHandle: ...
+ @property
+ def backend(self) -> str: ...
+ def _bind_facade(self, facade: object) -> None: ...
+
+@final
+class _CacheTestResolver:
+ def __new__(cls, namespace: object) -> _CacheTestResolver: ...
+ def resolve(self) -> _CacheTestBinding: ...
+
@final
class TokenCounter:
def __new__(cls, tokenizer_json: str) -> TokenCounter: ...
diff --cc tests/test_litellm_rust/test_cache.py
index 04bca2d5dd3,8cddc868073..ae0a88f7fdf
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@@ -8,14 -8,12 +8,16 @@@ import tim
import uuid
import weakref
from collections.abc import Generator
+from datetime import datetime
+ from pathlib import Path
from types import SimpleNamespace
from typing import Final, Protocol, cast
+from unittest.mock import Mock
from urllib.parse import urlparse
+import boto3
+import botocore.config
+ import diskcache
import fakeredis
import pytest
import redis
@@@ -24,9 -22,9 +26,10 @@@ from azure.storage.blob import Containe
import litellm
from litellm.caching.azure_blob_cache import AzureBlobCache
from litellm.caching.caching import Cache, disable_cache, enable_cache, update_cache
+ from litellm.caching.disk_cache import DiskCache
from litellm.caching.in_memory_cache import InMemoryCache
- from litellm.caching.s3_cache import S3Cache
from litellm.caching.redis_cluster_cache import RedisClusterCache
++from litellm.caching.s3_cache import S3Cache
from litellm.rust_bridge import _native
from litellm.types.caching import LiteLLMCacheType
from tests.test_litellm_rust.support.isolation import rebound
@@@ -417,15 -414,15 +420,20 @@@ def test_azure_blob_facade_serves_nativ
assert handle.backend == "azure-blob"
account_url: Final = backend.container_client.url.removesuffix(f"/{backend.container_client.container_name}")
with pytest.raises(TypeError, match="containers must match"):
-- _native._CacheTestHandle.azure_blob(account_url, f"{backend.container_client.container_name}-other")._bind_facade(
-- azure_blob_facade
-- )
++ _native._CacheTestHandle.azure_blob(
++ account_url, f"{backend.container_client.container_name}-other"
++ )._bind_facade(azure_blob_facade)
handle._bind_facade(azure_blob_facade)
resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=azure_blob_facade))
native: Final = resolver.resolve()
assert native.kind == "native"
-- response: Final = {"choices": [{"text": "caf\u00e9 \u2603"}], "usage": {"total_tokens": 3}, "flag": True, "empty": None}
++ response: Final = {
++ "choices": [{"text": "caf\u00e9 \u2603"}],
++ "usage": {"total_tokens": 3},
++ "flag": True,
++ "empty": None,
++ }
native.store({**request("sync"), "ttl_seconds": 0.001}, response)
native.store(request("sync"), {"choices": [{"text": "second"}]})
time.sleep(0.01)
@@@ -480,7 -477,7 +488,9 @@@ async def test_azure_blob_native_async_
await binding.async_store({**request("async"), "ttl_seconds": 0.001}, {"value": 2})
time.sleep(0.01)
assert await binding.async_lookup(request("async")) == {"value": 2}
-- assert await backend.async_get_cache("async") == json.loads(backend.container_client.download_blob("async").readall())
++ assert await backend.async_get_cache("async") == json.loads(
++ backend.container_client.download_blob("async").readall()
++ )
assert cast(CacheLookup, azure_blob_facade).get_cache(cache_key="async") == {"value": 2}
await binding.async_store_batch([request("first"), request("second")], [{"value": 3}, {"value": 4}])
@@@ -525,185 -522,114 +535,293 @@@ async def test_redis_facade_buffers_nat
assert client.get("second") is not None
await facade.cache.disconnect()
client.close()
+
+
+ async def test_disk_reads_python_entries_and_python_reads_native_entries(tmp_path: Path) -> None:
+ disk_cache: Final = DiskCache(disk_cache_dir=str(tmp_path))
+ response: Final = {"choices": [{"text": "cached"}], "usage": {"total_tokens": 3}}
+ disk_cache.disk_cache.set(
+ "sync",
+ {"timestamp": time.time(), "response": json.dumps(response)},
+ )
+ disk_cache.disk_cache.set("async", json.dumps({"timestamp": time.time(), "response": response}))
+ disk_cache.disk_cache.set("raw", json.dumps(response))
+ disk_cache.disk_cache.set("invalid", "not a cache entry")
+ disk_cache.disk_cache.set(
+ "large",
+ {"timestamp": time.time(), "response": {"text": "x" * 70_000}},
+ )
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))
+ ).resolve()
+
+ assert binding.lookup(request("sync")) == response
+ assert await binding.async_lookup(request("async")) == response
+ assert binding.lookup(request("raw")) == response
+ assert await binding.async_lookup(request("invalid")) is None
+ assert binding.lookup(request("large")) == {"text": "x" * 70_000}
+
+ await binding.async_store({**request("native"), "ttl_seconds": 12.0}, response)
+ stored_response: Final = disk_cache.get_cache("native")
+ assert isinstance(stored_response, dict)
+ assert stored_response["response"] == response
+ stored, expire_time = disk_cache.disk_cache.get("native", expire_time=True)
+ assert stored is not None
+ assert time.time() < expire_time <= time.time() + 12.0
+ await binding.async_store(request("no-ttl"), response)
+ _, no_expiry = disk_cache.disk_cache.get("no-ttl", expire_time=True)
+ assert no_expiry is None
+
+
+ async def test_disk_entries_survive_a_fresh_handle_and_expire_on_time(tmp_path: Path) -> None:
+ first: Final = _native._CacheTestResolver(
+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))
+ ).resolve()
+ await first.async_store(request("persistent"), {"value": "persistent"})
+ await first.async_store({**request("expiring"), "ttl_seconds": 0.3}, {"value": "expiring"})
+ fresh: Final = _native._CacheTestResolver(
+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))
+ ).resolve()
+ assert fresh.lookup(request("persistent")) == {"value": "persistent"}
+ assert fresh.lookup(request("expiring")) == {"value": "expiring"}
+ await asyncio.sleep(0.4)
+ assert fresh.lookup(request("expiring")) is None
+ assert fresh.lookup(request("persistent")) == {"value": "persistent"}
+
+
+ def test_disk_facade_registers_and_store_changes_fall_back(tmp_path: Path) -> None:
+ facade: Final = Cache(type=LiteLLMCacheType.DISK, disk_cache_dir=str(tmp_path))
+ with pytest.raises(TypeError, match="directories must match"):
+ _native._CacheTestHandle.disk(str(tmp_path / "other"))._bind_facade(facade)
+ handle: Final = _native._CacheTestHandle.disk(str(tmp_path))
+ handle._bind_facade(facade)
+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))
+ binding: Final = resolver.resolve()
+ assert binding.kind == "native"
+ binding.store(request("native"), {"value": "native"})
+ assert facade.get_cache(cache_key="native") == {"value": "native"}
+
+ with rebound(facade.cache, "disk_cache", diskcache.Cache(str(tmp_path))):
+ assert resolver.resolve().kind == "python_callback"
+ assert resolver.resolve().kind == "native"
+
+ class CustomDiskCache(DiskCache):
+ pass
+
+ with rebound(facade, "cache", CustomDiskCache(disk_cache_dir=str(tmp_path))):
+ assert resolver.resolve().kind == "python_callback"
+
+ class CustomStore(diskcache.Cache):
+ pass
+
+ custom_facade: Final = Cache(type=LiteLLMCacheType.DISK, disk_cache_dir=str(tmp_path))
+ custom_facade.cache.disk_cache = CustomStore(str(tmp_path))
+ with pytest.raises(TypeError, match="built-in diskcache store"):
+ _native._CacheTestHandle.disk(str(tmp_path))._bind_facade(custom_facade)
+
+
+ async def test_disk_native_batch_lookup_and_store_report_partial_hits(tmp_path: Path) -> None:
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(cache=_native._CacheTestHandle.disk(str(tmp_path)))
+ ).resolve()
+ requests: Final = [request("hit"), request("miss"), request("disabled")]
+ requests[2]["controls"] = {
+ "supported_call_type": True,
+ "configured": True,
+ "native_backend": True,
+ "default_on": True,
+ "caching": False,
+ "no_cache": False,
+ "no_store": False,
+ "use_cache": False,
+ }
+ await binding.async_store_batch(requests, [{"value": 1}, {"value": 2}, {"value": 3}])
+
+ partial: Final = await binding.async_lookup_batch(requests)
+
+ assert partial == {
+ "values": [{"value": 1}, {"value": 2}, None],
+ "missing_indices": [2],
+ }
+
+
+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"
+
+ handler: Final = Mock()
+ facade.cache.s3_client.meta.events.register("before-call.s3.*", handler)
+ binding.store(request("native"), {"answer": 1})
+ assert binding.lookup(request("native")) == {"answer": 1}
+ assert handler.call_count == 0
+ 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:
@@@ -757,7 -683,7 +875,9 @@@
await binding.async_flush()
-- remaining: Final = tuple(sorted(key for node in client.get_primaries() for key in client.keys("parity:*", target_nodes=node)))
++ 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")