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
chore: merge main into litellm_gcs_native_cache
Yujong Lee4e2047e9c5ca
diff --cc litellm-rust/Cargo.lockindex 2f1e78a6577,1a4eb51af08..b13bce2ed67--- a/litellm-rust/Cargo.lock+++ b/litellm-rust/Cargo.lock@@@ -2540,21 -2596,21 +2596,36 @@@ dependencies ="url",]+ [[package]]+ name = "litellm-cache-disk"+ version = "0.1.0"+ dependencies = [+ "litellm-cache",+ "py_literal",+ "rand 0.8.7",+ "rstest",+ "rusqlite",+ "serde-pickle",+ "serde_json",+ "tempfile",+ "tokio",+ ]++[[package]]+name = "litellm-cache-gcs"+version = "0.1.0"+dependencies = [+ "futures-util",+ "litellm-auth-gcp",+ "litellm-auth-types",+ "litellm-cache",+ "percent-encoding",+ "reqwest 0.12.28",+ "serde_json",+ "tokio",+ "wiremock",+]+[[package]]name = "litellm-cache-memory"version = "0.1.0"@@@ -2758,7 -2814,7 +2829,8 @@@ dependencies ="litellm-auth-gcp","litellm-cache","litellm-cache-azure-blob",+ "litellm-cache-disk",+ "litellm-cache-gcs","litellm-cache-memory","litellm-cache-redis","litellm-cache-response",diff --cc litellm-rust/Cargo.tomlindex d313c004972,fabec9bcd6c..3ab1e592c6a--- a/litellm-rust/Cargo.toml+++ b/litellm-rust/Cargo.toml@@@ -32,7 -32,7 +32,8 @@@ litellm-cache = { path = "crates/cachelitellm-cache-azure-blob = { path = "crates/cache-azure-blob" }litellm-cache-memory = { path = "crates/cache-memory" }litellm-cache-redis = { path = "crates/cache-redis" }+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" }litellm-token-counter-fast = { path = "crates/token-counter-fast" }diff --cc litellm-rust/crates/python-bridge/Cargo.tomlindex 6bdfe2ac09d,f5d08850b39..4a9ea633ac5--- 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 = trulitellm-cache-azure-blob.workspace = truelitellm-cache-memory.workspace = truelitellm-cache-redis.workspace = true+litellm-cache-gcs.workspace = true+ litellm-cache-disk.workspace = truelitellm-cache-response.workspace = trueserde.workspace = truelitellm-auth.workspace = truediff --cc litellm-rust/crates/python-bridge/src/cache/config.rsindex 15fa8938c9c,927017e2e60..6c180708335--- a/litellm-rust/crates/python-bridge/src/cache/config.rs+++ b/litellm-rust/crates/python-bridge/src/cache/config.rs@@@ -101,7 -98,7 +105,8 @@@ const REDIS_PY_DEFAULT_MAX_CONNECTIONSpub(super) enum CacheBackendConfig {Memory(MemoryCacheConfig),Redis(Box<RedisCacheConfig>),+ Gcs(GcsCacheConfig),+ Disk(DiskCacheConfig),AzureBlob(AzureBlobCacheConfig),}@@@ -117,7 -114,7 +122,8 @@@ pub(super) enum UnsupportedCacheConfigRedisCredentials,RedisConnection,RedisOption,+ GcsBucket,+ DiskStore,}impl UnsupportedCacheConfig {@@@ -128,7 -125,7 +134,8 @@@Self::RedisCredentials => "native Redis credentials require Python",Self::RedisConnection => "native Redis connection type is not implemented",Self::RedisOption => "native Redis configuration requires Python",+ Self::GcsBucket => "native GCS cache requires a configured bucket name",+ Self::DiskStore => "native disk cache requires the built-in diskcache store",}}}@@@ -171,13 -168,13 +178,20 @@@ impl NativeCacheConfig}))),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,+ 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,@@@ -188,8 -185,8 +202,7 @@@CacheType::RedisSemantic| CacheType::ValkeySemantic| CacheType::S3- | CacheType::Disk- | CacheType::QdrantSemantic- | CacheType::Gcs,+ | CacheType::QdrantSemantic,)| None => Ok(CacheConfigProjection::Unsupported(UnsupportedCacheConfig::Backend,@@@ -201,7 -198,8 +214,9 @@@let default_ttl = match &self.backend {CacheBackendConfig::Memory(config) => Some(config.default_ttl),CacheBackendConfig::Redis(config) => Some(config.default_ttl),- CacheBackendConfig::AzureBlob(_) | CacheBackendConfig::Gcs(_) => 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");@@@ -228,31 -226,17 +243,42 @@@CacheBackendConfig::Redis(config) => (service.namespace()!= config.namespace.as_deref()).then_some("facade and native backend namespaces must match"),+ 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")+ }+ 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))@@@ -293,23 -277,21 +319,38 @@@ fn project_memory(backend: &Bound<'_, P})}+#[inline(never)]+fn project_gcs(+ backend: &Bound<'_, PyAny>,+) -> PyResult<Result<GcsCacheConfig, UnsupportedCacheConfig>> {+ let bucket_name = match backend.getattr("bucket_name")?.extract::<Option<String>>() {+ Ok(Some(bucket_name)) if !bucket_name.is_empty() => bucket_name,+ _ => return Ok(Err(UnsupportedCacheConfig::GcsBucket)),+ };+ Ok(Ok(GcsCacheConfig {+ bucket_name,+ key_prefix: backend.getattr("key_prefix")?.extract::<String>()?,+ path_service_account: backend+ .getattr("path_service_account")?+ .extract::<Option<String>>()?,+ }))+}++ #[inline(never)]+ fn project_disk(+ backend: &Bound<'_, PyAny>,+ ) -> PyResult<Result<DiskCacheConfig, UnsupportedCacheConfig>> {+ let store = backend.getattr("disk_cache")?;+ if !instance_class_is(&store, "diskcache.core", "Cache")?+ || !instance_class_is(&store.getattr("_disk")?, "diskcache.core", "Disk")?+ {+ return Ok(Err(UnsupportedCacheConfig::DiskStore));+ }+ Ok(Ok(DiskCacheConfig {+ directory: PathBuf::from(store.getattr("directory")?.extract::<String>()?),+ }))+ }+#[inline(never)]fn project_redis(backend: &Bound<'_, PyAny>,@@@ -697,8 -679,8 +738,8 @@@ mod testsuse litellm_cache_redis::{RedisNode, RedisTopology};use super::{- CacheBackendConfig, CacheConfigProjection, CertificateRequirement, GcsCacheConfig,- NativeCacheConfig, RedisProtocol, UnsupportedCacheConfig,+ CacheBackendConfig, CacheConfigProjection, CachePolicy, CertificateRequirement,- DiskCacheConfig, NativeCacheConfig, RedisProtocol,++ DiskCacheConfig, GcsCacheConfig, NativeCacheConfig, RedisProtocol, UnsupportedCacheConfig,};use crate::cache::native::NativeResponseCache;diff --cc litellm-rust/crates/python-bridge/src/cache/facade.rsindex facb529c8a9,ee6423daf6e..0fa4511b1c1--- a/litellm-rust/crates/python-bridge/src/cache/facade.rs+++ b/litellm-rust/crates/python-bridge/src/cache/facade.rs@@@ -295,7 -320,7 +320,8 @@@ impl FacadeGuard"RedisClusterCache","redis",),+ ("gcs", _) => ("litellm.caching.gcs_cache", "GCSCache", "gcs"),+ ("disk", _) => ("litellm.caching.disk_cache", "DiskCache", "disk"),("azure-blob", _) => ("litellm.caching.azure_blob_cache","AzureBlobCache",@@@ -344,11 -369,11 +370,14 @@@"max_size_per_item","redis_kwargs","redis_flush_size",+ "bucket_name",+ "key_prefix",+ "path_service_account",],)?,+ 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.rsindex c148791a9b2,6e12e12040b..64ac3696e80--- a/litellm-rust/crates/python-bridge/src/cache/handle.rs+++ b/litellm-rust/crates/python-bridge/src/cache/handle.rs@@@ -66,31 -64,18 +66,43 @@@ impl CacheTestHandle})}+ #[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> {+ 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.rsindex cdf843110fd,80789cc279a..b10f9e2a443--- a/litellm-rust/crates/python-bridge/src/cache/native.rs+++ b/litellm-rust/crates/python-bridge/src/cache/native.rs@@@ -2,7 -2,7 +2,8 @@@ use std::{path::Path, sync::Arc, time::use litellm_cache::{CacheCodec, CacheConnectionResult, Error};use litellm_cache_azure_blob::AzureBlobCache;+ use litellm_cache_disk::DiskCache;+use litellm_cache_gcs::{GcsCache, GcsConfig, StaticTokenSource};use litellm_cache_memory::InMemoryCache;use litellm_cache_redis::{RedisCache, RedisTopology};use litellm_cache_response::{@@@ -17,7 -17,7 +18,8 @@@ pub(super) enum NativeResponseCachecache: Arc<ResponseCache<RedisCache<ResponseCacheCodec>>>,buffer: Option<Arc<WriteBuffer>>,},+ Gcs(Arc<ResponseCache<GcsCache<ResponseCacheCodec>>>),+ Disk(Arc<ResponseCache<DiskCache<ResponseCacheCodec>>>),AzureBlob(Arc<ResponseCache<AzureBlobCache<ResponseCacheCodec>>>),}@@@ -49,19 -49,11 +51,23 @@@ impl NativeResponseCachebuffer: None,})}+ 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 fn gcs(config: GcsConfig, token: Option<String>) -> Result<Self, Error> {+ let backend = match token {+ Some(token) => GcsCache::with_token_source(+ config,+ ResponseCacheCodec,+ Arc::new(StaticTokenSource(token)),+ )?,+ None => GcsCache::new(config, ResponseCacheCodec)?,+ };+ Ok(Self::Gcs(Arc::new(ResponseCache::new(Arc::new(backend)))))+ }+pub async fn azure_blob(account_url: &str, container: &str) -> Result<Self, Error> {let backend = AzureBlobCache::connect(account_url,@@@ -81,7 -73,7 +87,7 @@@cache.backend().account_url(),cache.backend().container_name(),)),- Self::Memory(_) | Self::Redis { .. } | Self::Gcs(_) => None,- Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) => None,++ Self::Memory(_) | Self::Redis { .. } | Self::Disk(_) | Self::Gcs(_) => None,}}}@@@ -91,7 -83,7 +97,8 @@@ impl NativeResponseCachematch self {Self::Memory(_) => "memory",Self::Redis { .. } => "redis",+ Self::Gcs(_) => "gcs",+ Self::Disk(_) => "disk",Self::AzureBlob(_) => "azure-blob",}}@@@ -100,22 -92,21 +107,23 @@@match self {Self::Memory(cache) => cache.default_ttl(),Self::Redis { cache, .. } => cache.default_ttl(),+ Self::Gcs(cache) => cache.default_ttl(),+ Self::Disk(cache) => cache.default_ttl(),Self::AzureBlob(cache) => cache.default_ttl(),}}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::Gcs(_) => None,}}pub fn topology(&self) -> Option<&RedisTopology> {match self {- Self::Memory(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,- Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) => None,++ Self::Memory(_) | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,Self::Redis { cache, .. } => Some(cache.backend().topology()),}}@@@ -123,14 -114,14 +131,14 @@@pub fn capacity(&self) -> Option<usize> {match self {Self::Memory(cache) => Some(cache.backend().max_size_in_memory()),- Self::Redis { .. } | Self::AzureBlob(_) | Self::Gcs(_) => None,- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) => None,++ Self::Redis { .. } | 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::AzureBlob(_) | Self::Gcs(_) => None,- Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) => None,++ Self::Redis { .. } | Self::Disk(_) | Self::AzureBlob(_) | Self::Gcs(_) => None,}}@@@ -144,6 -135,13 +152,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::AzureBlob(_) | Self::Gcs(_) => None,+ }+ }+pub fn lookup(&self,request: &ResponseCacheRequest,@@@ -152,7 -150,7 +167,8 @@@match self {Self::Memory(cache) => cache.lookup(request, now),Self::Redis { 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),}}@@@ -166,7 -164,7 +182,8 @@@match self {Self::Memory(cache) => cache.store(request, response, now),Self::Redis { 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),}}@@@ -179,7 -177,7 +196,8 @@@match self {Self::Memory(cache) => cache.lookup_batch(requests, now),Self::Redis { 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),}}@@@ -192,7 -190,7 +210,8 @@@match self {Self::Memory(cache) => cache.async_lookup(request, now).await,Self::Redis { 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,}}@@@ -213,7 -211,7 +232,8 @@@cache,buffer: Some(buffer),} => buffer.async_store(cache, 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,}}@@@ -226,7 -224,7 +246,8 @@@match self {Self::Memory(cache) => cache.async_lookup_batch(requests, now).await,Self::Redis { 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,}}@@@ -239,7 -237,7 +260,8 @@@match self {Self::Memory(cache) => cache.async_store_batch(entries, now).await,Self::Redis { 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,}}@@@ -253,7 -251,7 +275,8 @@@}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,}}@@@ -262,7 -260,7 +285,8 @@@match self {Self::Memory(cache) => cache.test_connection().await,Self::Redis { 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 tests/test_litellm_rust/test_cache.pyindex fb2e9daa5cb,8cddc868073..ba95b21d530--- a/tests/test_litellm_rust/test_cache.py+++ b/tests/test_litellm_rust/test_cache.py@@@ -20,7 -22,7 +22,8 @@@ from azure.storage.blob import Containeimport litellmfrom litellm.caching.azure_blob_cache import AzureBlobCachefrom litellm.caching.caching import Cache, disable_cache, enable_cache, update_cache+from litellm.caching.gcs_cache import GCSCache+ from litellm.caching.disk_cache import DiskCachefrom litellm.caching.in_memory_cache import InMemoryCachefrom litellm.caching.redis_cluster_cache import RedisClusterCachefrom litellm.rust_bridge import _native@@@ -531,224 -522,114 +534,330 @@@ async def test_redis_facade_buffers_natassert client.get("second") is not Noneawait 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],+ }+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: