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]

fix(python-bridge): propagate cancellation from semantic embedding awaits

Yujong Lee7282494c30e0
diff --git a/litellm-rust/crates/python-bridge/src/cache/semantic.rs b/litellm-rust/crates/python-bridge/src/cache/semantic.rs
index eb38b8b9c67..f0f75de1edf 100644
--- a/litellm-rust/crates/python-bridge/src/cache/semantic.rs
+++ b/litellm-rust/crates/python-bridge/src/cache/semantic.rs
@@ -3,7 +3,11 @@ use std::collections::VecDeque;
use litellm_cache::Error;
use litellm_cache_redis_semantic::prompt_from_context;
use litellm_host_python::{Execution, ExecutionBody, ExecutionStep, run_async};
-use pyo3::{PyTraverseError, PyVisit, exceptions::PyRuntimeError, prelude::*};
+use pyo3::{
+ PyTraverseError, PyVisit,
+ exceptions::{PyException, PyRuntimeError},
+ prelude::*,
+};
use serde_json::Value;
use super::{
@@ -120,9 +124,16 @@ impl ExecutionBody for SemanticBody {
"semantic execution expected an embedding result",
)
})?;
- let seed = result
- .and_then(|value| PythonEmbedder::extract(value.into_bound(py)))
- .map_err(|_| Error::Unavailable);
+ let seed = match result {
+ Ok(value) => PythonEmbedder::extract(value.into_bound(py))
+ .map_err(|_| Error::Unavailable),
+ Err(error) => {
+ if !error.is_instance_of::<PyException>(py) {
+ return Err(error);
+ }
+ Err(Error::Unavailable)
+ }
+ };
return self.backend_step(py, seed);
}
Phase::AwaitingBackend => {
diff --git a/tests/test_litellm_rust/test_cache.py b/tests/test_litellm_rust/test_cache.py
index 3f5449a1aa9..8a8c83cd82b 100644
--- a/tests/test_litellm_rust/test_cache.py
+++ b/tests/test_litellm_rust/test_cache.py
@@ -736,6 +736,8 @@ class DeterministicEmbedding(litellm.CustomLLM):
def __init__(self) -> None:
self.calls: list[dict[str, object]] = []
self.async_calls: list[dict[str, object]] = []
+ self.entered = asyncio.Event()
+ self.gate: asyncio.Event | None = None
def _respond(
self,
@@ -790,6 +792,9 @@ class DeterministicEmbedding(litellm.CustomLLM):
}
)
SEMANTIC_CONTEXT.set("written-in-aembedding")
+ self.entered.set()
+ if self.gate is not None:
+ await self.gate.wait()
return self._respond(model, input, model_response)
@@ -1036,6 +1041,36 @@ async def test_native_semantic_async_embedding_runs_inline_in_the_callers_task(
], semantic_embedding.async_calls
+async def test_native_semantic_cancellation_during_embedding_skips_the_backend(
+ redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding
+) -> None:
+ url, index = redis_stack
+ facade: Final = semantic_facade(url, index)
+ binding: Final = _CacheTestResolver(SimpleNamespace(cache=facade)).resolve()
+ assert binding.kind == "native"
+ semantic_embedding.gate = asyncio.Event()
+
+ async def lookup() -> object:
+ return await binding.async_lookup(
+ semantic_request("cancel", "cancelled prompt")
+ )
+
+ task: Final = asyncio.create_task(lookup())
+ await semantic_embedding.entered.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ semantic_embedding.gate.set()
+
+ assert len(semantic_embedding.async_calls) == 1
+ assert (
+ await cast(RedisSemanticCache, facade.cache).async_get_cache( # pyright: ignore[reportUnknownMemberType] # **kwargs stays unknown on the backend class
+ "cancel", messages=semantic_messages("cancelled prompt")
+ )
+ is None
+ )
+
+
def test_redis_semantic_similarity_tag_and_threshold_boundaries(
redis_stack: tuple[str, str], semantic_embedding: DeterministicEmbedding
) -> None: