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 branch 'main' into litellm_rust_cache_s3

Yujong Lee0c5bbf8c378e
diff --cc litellm-rust/Cargo.toml
index a3889a009ec,3ab1e592c6a..ddd37680313
--- 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-gcs = { path = "crates/cache-gcs" }
litellm-cache-disk = { path = "crates/cache-disk" }
litellm-cache-response = { path = "crates/cache-response" }
litellm-token-counter = { path = "crates/token-counter" }
diff --cc litellm-rust/crates/python-bridge/Cargo.toml
index 094137bed99,4a9ea633ac5..9191e61a25c
--- 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-gcs.workspace = true
litellm-cache-disk.workspace = true
litellm-cache-response.workspace = true
serde.workspace = true
diff --cc litellm-rust/crates/python-bridge/src/cache/config.rs
index 58e4f57b227,6c180708335..7316b3e259c
--- a/litellm-rust/crates/python-bridge/src/cache/config.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs
@@@ -100,7 -105,7 +107,8 @@@ const REDIS_PY_DEFAULT_MAX_CONNECTIONS
pub(super) enum CacheBackendConfig {
Memory(MemoryCacheConfig),
Redis(Box<RedisCacheConfig>),
+ S3(Box<S3CacheConfig>),
+ Gcs(GcsCacheConfig),
Disk(DiskCacheConfig),
AzureBlob(AzureBlobCacheConfig),
}
@@@ -117,9 -122,7 +125,10 @@@ pub(super) enum UnsupportedCacheConfig
RedisCredentials,
RedisConnection,
RedisOption,
+ S3Client,
+ S3Credentials,
+ S3Option,
+ GcsBucket,
DiskStore,
}
@@@ -131,9 -134,7 +140,10 @@@ impl UnsupportedCacheConfig
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::GcsBucket => "native GCS cache requires a configured bucket name",
Self::DiskStore => "native disk cache requires the built-in diskcache store",
}
}
@@@ -177,13 -178,13 +187,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::Gcs) => match project_gcs(&backend)? {
+ Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
+ policy,
+ backend: CacheBackendConfig::Gcs(backend),
+ }))),
+ Err(reason) => Ok(CacheConfigProjection::Unsupported(reason)),
+ },
Some(CacheType::Disk) => match project_disk(&backend)? {
Ok(backend) => Ok(CacheConfigProjection::Native(Box::new(Self {
policy,
@@@ -198,10 -199,10 +215,7 @@@
}))
}),
Some(
-- CacheType::RedisSemantic
-- | CacheType::ValkeySemantic
- | CacheType::QdrantSemantic
- | CacheType::Gcs,
- | CacheType::S3
- | CacheType::QdrantSemantic,
++ CacheType::RedisSemantic | CacheType::ValkeySemantic | CacheType::QdrantSemantic,
)
| None => Ok(CacheConfigProjection::Unsupported(
UnsupportedCacheConfig::Backend,
@@@ -213,9 -214,9 +227,10 @@@
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,
+ CacheBackendConfig::Disk(_)
+ | CacheBackendConfig::AzureBlob(_)
+ | CacheBackendConfig::Gcs(_) => None,
};
if service.default_ttl() != default_ttl {
return Some("facade and native backend default TTLs must match");
@@@ -242,30 -243,31 +257,55 @@@
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::Gcs(_) if service.kind() != "gcs" => {
+ Some("facade and native backend types must match")
+ }
+ CacheBackendConfig::Gcs(config)
+ if service
+ .gcs_backend()
+ .is_none_or(|backend| backend.bucket_name() != config.bucket_name) =>
+ {
+ Some("facade and native backend buckets must match")
+ }
+ CacheBackendConfig::Gcs(config)
+ if service
+ .gcs_backend()
+ .is_none_or(|backend| backend.key_prefix() != config.key_prefix) =>
+ {
+ Some("facade and native backend key prefixes must match")
+ }
+ CacheBackendConfig::Gcs(config)
+ if service.gcs_backend().is_none_or(|backend| {
+ backend.path_service_account() != config.path_service_account.as_deref()
+ }) =>
+ {
+ Some("facade and native backend credentials must match")
+ }
+ CacheBackendConfig::Gcs(_) => None,
CacheBackendConfig::Disk(_) if service.kind() != "disk" => {
Some("facade and native backend types must match")
}
@@@ -818,10 -739,9 +875,10 @@@ mod tests
use super::{
CacheBackendConfig, CacheConfigProjection, CachePolicy, CertificateRequirement,
- DiskCacheConfig, NativeCacheConfig, RedisProtocol,
+ DiskCacheConfig, GcsCacheConfig, NativeCacheConfig, RedisProtocol, UnsupportedCacheConfig,
};
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(
diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rs
index e3e04b9ddf6,0fa4511b1c1..e89d0fc9715
--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs
@@@ -340,7 -320,7 +340,8 @@@ impl FacadeGuard
"RedisClusterCache",
"redis",
),
+ ("s3", _) => ("litellm.caching.s3_cache", "S3Cache", "s3"),
+ ("gcs", _) => ("litellm.caching.gcs_cache", "GCSCache", "gcs"),
("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),
("azure-blob", _) => (
"litellm.caching.azure_blob_cache",
diff --cc litellm-rust/crates/python-bridge/src/cache/handle.rs
index 76a7a1d041a,64ac3696e80..d6e622a5c49
--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs
@@@ -66,40 -66,31 +68,65 @@@ 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 = (bucket_name, *, gcs_path=None, path_service_account=None, endpoint=None, token=None))]
+ fn gcs(
+ py: Python<'_>,
+ bucket_name: String,
+ gcs_path: Option<String>,
+ path_service_account: Option<String>,
+ endpoint: Option<String>,
+ token: Option<String>,
+ ) -> PyResult<Self> {
+ let config = GcsConfig {
+ bucket_name,
+ gcs_path,
+ path_service_account,
+ endpoint: endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()),
+ };
+ let service = release_gil(py, move || NativeResponseCache::gcs(config, token))
+ .map_err(cache_error)?;
+ Ok(Self {
+ service,
+ guard: None,
+ pid: std::process::id(),
+ })
+ }
+
#[staticmethod]
#[pyo3(signature = (directory))]
fn disk(py: Python<'_>, directory: String) -> PyResult<Self> {
diff --cc litellm-rust/crates/python-bridge/src/cache/native.rs
index c56c5f8d87f,b10f9e2a443..39496890009
--- a/litellm-rust/crates/python-bridge/src/cache/native.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs
@@@ -18,7 -18,7 +19,8 @@@ pub(super) enum NativeResponseCache
cache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,
buffer: Option<Arc<WriteBuffer>>,
},
+ S3(Arc<ResponseCache<S3Cache<ResponseCacheCodec>>>),
+ Gcs(Arc<ResponseCache<GcsCache<ResponseCacheCodec>>>),
Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),
AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),
}
@@@ -83,7 -87,7 +97,9 @@@ impl NativeResponseCache
cache.backend().account_url(),
cache.backend().container_name(),
)),
- Self::Memory(_) | Self::Redis { .. } | Self::S3(_) | Self::Disk(_) => None,
- Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) | Self::Gcs(_) => None,
++ Self::Memory(_) | Self::Redis { .. } | Self::S3(_) | Self::Disk(_) | Self::Gcs(_) => {
++ None
++ }
}
}
}
@@@ -93,7 -97,7 +109,8 @@@ impl NativeResponseCache
match self {
Self::Memory(_) => "memory",
Self::Redis { .. } => "redis",
+ Self::S3(_) => "s3",
+ Self::Gcs(_) => "gcs",
Self::Disk(_) => "disk",
Self::AzureBlob(_) => "azure-blob",
}
@@@ -103,7 -107,7 +120,8 @@@
match self {
Self::Memory(cache) => cache.default_ttl(),
Self::Redis { cache, .. } => cache.default_ttl(),
+ Self::S3(cache) => cache.default_ttl(),
+ Self::Gcs(cache) => cache.default_ttl(),
Self::Disk(cache) => cache.default_ttl(),
Self::AzureBlob(cache) => cache.default_ttl(),
}
@@@ -141,29 -117,28 +159,37 @@@
match self {
Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
Self::Redis { cache, .. } => cache.backend().namespace(),
- Self::S3(_) => None,
- Self::Gcs(_) => None,
++ Self::S3(_) | Self::Gcs(_) => None,
}
}
pub fn topology(&self) -> Option<&RedisTopology> {
match self {
- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
+ Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => 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::Disk(_) | Self::AzureBlob(_) => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Redis { .. }
++ | Self::S3(_)
++ | Self::Disk(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
}
}
pub fn max_entry_bytes(&self) -> Option<usize> {
match self {
Self::Memory(cache) => cache.backend().max_entry_bytes(),
- Self::Redis { .. } | Self::S3(_) | Self::Disk(_) | Self::AzureBlob(_) => None,
- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Redis { .. }
++ | Self::S3(_)
++ | Self::Disk(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
}
}
@@@ -180,7 -155,7 +206,11 @@@
pub fn directory(&self) -> Option<&Path> {
match self {
Self::Disk(cache) => Some(cache.backend().directory()),
- Self::Memory(_) | Self::Redis { .. } | Self::S3(_) | Self::AzureBlob(_) => None,
- Self::Memory(_) | Self::Redis { .. } | Self::AzureBlob(_) | Self::Gcs(_) => None,
++ Self::Memory(_)
++ | Self::Redis { .. }
++ | Self::S3(_)
++ | Self::AzureBlob(_)
++ | Self::Gcs(_) => None,
}
}
@@@ -192,7 -167,7 +222,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::Gcs(cache) => cache.lookup(request, now),
Self::Disk(cache) => cache.lookup(request, now),
Self::AzureBlob(cache) => cache.lookup(request, now),
}
@@@ -207,7 -182,7 +238,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::Gcs(cache) => cache.store(request, response, now),
Self::Disk(cache) => cache.store(request, response, now),
Self::AzureBlob(cache) => cache.store(request, response, now),
}
@@@ -221,7 -196,7 +253,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::Gcs(cache) => cache.lookup_batch(requests, now),
Self::Disk(cache) => cache.lookup_batch(requests, now),
Self::AzureBlob(cache) => cache.lookup_batch(requests, now),
}
@@@ -235,7 -210,7 +268,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::Gcs(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,
}
@@@ -257,7 -232,7 +291,8 @@@
cache,
buffer: Some(buffer),
} => buffer.async_store(cache, request, response, now).await,
+ Self::S3(cache) => cache.async_store(request, response, now).await,
+ Self::Gcs(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,
}
@@@ -271,7 -246,7 +306,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::Gcs(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,
}
@@@ -285,7 -260,7 +321,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::Gcs(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,
}
@@@ -300,7 -275,7 +337,8 @@@
}
cache.async_flush().await
}
+ Self::S3(cache) => cache.async_flush().await,
+ Self::Gcs(cache) => cache.async_flush().await,
Self::Disk(cache) => cache.async_flush().await,
Self::AzureBlob(cache) => cache.async_flush().await,
}
@@@ -310,7 -285,7 +348,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::Gcs(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 057a83611fa,05a6df6d5af..90d876b71e6
--- a/litellm/rust_bridge/_native.pyi
+++ b/litellm/rust_bridge/_native.pyi
@@@ -93,101 -93,6 +93,110 @@@ 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 gcs(
++ bucket_name: str,
++ *,
++ gcs_path: str | None = None,
++ path_service_account: str | None = None,
++ endpoint: str | None = None,
++ token: str | None = None,
++ ) -> _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 ae0a88f7fdf,ba95b21d530..e0d92a2e957
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@@ -26,14 -22,14 +26,16 @@@ 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.gcs_cache import GCSCache
from litellm.caching.disk_cache import DiskCache
++from litellm.caching.gcs_cache import GCSCache
from litellm.caching.in_memory_cache import InMemoryCache
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.fake_gcs import FakeGcs
from tests.test_litellm_rust.support.isolation import rebound
+from tests.test_litellm_rust.support.s3_stub import S3Stub
pytestmark: Final = pytest.mark.requires_rust_extension
@@@ -645,183 -642,222 +657,400 @@@ async def test_disk_native_batch_lookup
}
+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_gcs_reads_python_entries_and_writes_python_compatible_objects(
+ fake_gcs: FakeGcs, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.delenv("GCS_PATH_SERVICE_ACCOUNT", raising=False)
+ monkeypatch.delenv("GCS_BUCKET_NAME", raising=False)
+ response: Final = {"choices": [{"text": "cached"}], "usage": {"total_tokens": 3}, "flag": True, "empty": None}
+ fake_gcs.put(
+ "bucket",
+ "cache/sync",
+ json.dumps({"timestamp": time.time(), "response": json.dumps(response)}).encode(),
+ )
+ fake_gcs.put("bucket", "cache/async", json.dumps({"timestamp": time.time(), "response": response}).encode())
+ fake_gcs.put("bucket", "cache/raw", json.dumps(response).encode())
+ fake_gcs.put("bucket", "cache/invalid", b"not a cache entry")
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).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("missing")) is None
+
+ await binding.async_store({**request("native"), "ttl_seconds": 12.0}, response)
+ stored: Final = fake_gcs.objects[("bucket", "cache/native")]
+ stored_value: Final = cast(dict[str, object], json.loads(stored))
+ assert stored_value["response"] == response
+ assert isinstance(stored_value["timestamp"], float)
+ upload: Final = next(item for item in fake_gcs.requests if item.method == "POST")
+ assert upload.path == "/upload/storage/v1/b/bucket/o"
+ assert upload.query == "uploadType=media&name=cache%2Fnative"
+ assert upload.headers["Authorization"] == f"Bearer {fake_gcs.token}"
+ assert upload.headers["Content-Type"] == "application/json"
+ upload_text: Final = f"{upload.path}?{upload.query}{upload.headers}"
+ assert "ttl" not in upload_text.lower()
+ assert "expiry" not in upload_text.lower()
+ download: Final = next(item for item in fake_gcs.requests if item.path.endswith("/cache%2Fsync"))
+ assert download.path == "/storage/v1/b/bucket/o/cache%2Fsync"
+ assert download.query == "alt=media"
+
+ binding.store(request("sync2"), response)
+ assert binding.lookup(request("sync2")) == response
+ assert GCSCache(bucket_name="bucket", gcs_path="cache").key_prefix == "cache/"
+ assert GCSCache(bucket_name="bucket", gcs_path="cache/").key_prefix == "cache/"
+ assert GCSCache(bucket_name="bucket").key_prefix == ""
+
+
+ async def test_gcs_batch_lookup_preserves_order_and_treats_malformed_entries_as_misses(fake_gcs: FakeGcs) -> None:
+ fake_gcs.put("bucket", "cache/hit", json.dumps({"timestamp": time.time(), "response": {"value": 1}}).encode())
+ fake_gcs.put("bucket", "cache/invalid", b"not a cache entry")
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).resolve()
+ requests: Final = [request("hit"), request("missing"), request("invalid")]
+ expected: Final = {"values": [{"value": 1}, None, None], "missing_indices": [1, 2]}
+
+ assert await binding.async_lookup_batch(requests) == expected
+ assert binding.lookup_batch(requests) == expected
+ await binding.async_store_batch([request("first"), request("second")], [{"value": 1}, {"value": 2}])
+ assert ("bucket", "cache/first") in fake_gcs.objects
+ assert ("bucket", "cache/second") in fake_gcs.objects
+
+
+ async def test_gcs_facade_binds_only_exact_matching_configuration(
+ fake_gcs: FakeGcs, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.delenv("GCS_PATH_SERVICE_ACCOUNT", raising=False)
+ monkeypatch.delenv("GCS_BUCKET_NAME", raising=False)
+ monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", "/nonexistent")
+ facade: Final = Cache(type=LiteLLMCacheType.GCS, gcs_bucket_name="bucket", gcs_path="cache/")
+ assert type(facade.cache) is GCSCache
+
+ mismatched_bucket: Final = _native._CacheTestHandle.gcs(
+ "other",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ with pytest.raises(TypeError, match="buckets must match"):
+ mismatched_bucket._bind_facade(facade)
+ mismatched_prefix: Final = _native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="x",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ with pytest.raises(TypeError, match="key prefixes must match"):
+ mismatched_prefix._bind_facade(facade)
+ mismatched_credentials: Final = _native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ path_service_account="sa.json",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ with pytest.raises(TypeError, match="credentials must match"):
+ mismatched_credentials._bind_facade(facade)
+ with pytest.raises(TypeError, match="types must match"):
+ _native._CacheTestHandle.memory()._bind_facade(facade)
+
+ matching: Final = _native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ matching._bind_facade(facade)
+ resolver: Final = _native._CacheTestResolver(SimpleNamespace(cache=facade))
+ binding: Final = resolver.resolve()
+ assert binding.kind == "native"
+ await binding.async_store(request("native"), {"value": "native"})
+ assert await binding.async_lookup(request("native")) == {"value": "native"}
+ assert cast(CacheLookup, facade).get_cache(cache_key="native") is None
+
+ with rebound(facade.cache, "bucket_name", "other"):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(facade.cache, "key_prefix", "x/"):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(facade.cache, "path_service_account", "sa.json"):
+ assert resolver.resolve().kind == "python_callback"
++
+ def no_get_cache(*args: object, **kwargs: object) -> None:
+ return None
+
+ with rebound(facade.cache, "get_cache", no_get_cache):
+ assert resolver.resolve().kind == "python_callback"
+ with rebound(facade, "ttl", 12):
+ assert resolver.resolve().kind == "python_callback"
+
+ class CustomGcs(GCSCache):
+ pass
+
+ with rebound(facade, "cache", CustomGcs(bucket_name="bucket", gcs_path="cache/")):
+ assert resolver.resolve().kind == "python_callback"
+ custom_facade: Final = Cache(type=LiteLLMCacheType.GCS, gcs_bucket_name="bucket", gcs_path="cache/")
+ with rebound(custom_facade, "cache", CustomGcs(bucket_name="bucket", gcs_path="cache/")):
+ with pytest.raises(TypeError, match="types must match"):
+ matching._bind_facade(custom_facade)
+
+ missing_bucket: Final = Cache(type=LiteLLMCacheType.GCS)
+ with pytest.raises(TypeError, match="requires a configured bucket name"):
+ matching._bind_facade(missing_bucket)
+
+
+ async def test_gcs_flush_is_a_no_op_and_ping_is_not_implemented(
+ fake_gcs: FakeGcs, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.delenv("GCS_PATH_SERVICE_ACCOUNT", raising=False)
+ monkeypatch.delenv("GCS_BUCKET_NAME", raising=False)
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).resolve()
+ await binding.async_store(request("key"), {"value": "stored"})
+ await binding.async_flush()
+ assert ("bucket", "cache/key") in fake_gcs.objects
+ assert await binding.async_lookup(request("key")) == {"value": "stored"}
+ with pytest.raises(NotImplementedError):
+ await binding.ping()
+
+ facade: Final = Cache(type=LiteLLMCacheType.GCS, gcs_bucket_name="bucket", gcs_path="cache/")
+ with pytest.raises(AttributeError):
+ await facade.ping()
+ assert cast(CacheLookup, facade.cache).flush_cache() is None
+
+
+ async def test_gcs_unauthorized_and_server_errors_surface_as_runtime_errors(fake_gcs: FakeGcs) -> None:
+ wrong_token: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token="wrong-token",
+ )
+ )
+ ).resolve()
+ with pytest.raises(RuntimeError):
+ wrong_token.lookup(request("missing"))
+ assert not fake_gcs.objects
+
+ binding: Final = _native._CacheTestResolver(
+ SimpleNamespace(
+ cache=_native._CacheTestHandle.gcs(
+ "bucket",
+ gcs_path="cache",
+ endpoint=fake_gcs.url,
+ token=fake_gcs.token,
+ )
+ )
+ ).resolve()
+ with pytest.raises(RuntimeError):
+ binding.lookup(request("server-error"))
+ assert binding.lookup(request("missing")) is None
+
+
async def test_redis_cluster_facade_serves_multi_slot_batches_and_scoped_flush_natively(
cluster_nodes: tuple[tuple[str, int], ...],
) -> None: