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
refactor(rust-bridge): return an unstarted Execution from native entrypoints and drive it in Python (#46299)
yujonglee8302f006ddf5
diff --git a/litellm-rust/crates/coroutine/AGENTS.md b/litellm-rust/crates/coroutine/AGENTS.mdindex 403d53a0a6d..0c3c737b0ef 100644--- a/litellm-rust/crates/coroutine/AGENTS.md+++ b/litellm-rust/crates/coroutine/AGENTS.md@@ -3,7 +3,7 @@Core must pause mid-call to ask the host for things it cannot do itself (Python callbacks, secret and token reads, `before_send` rewrites, stream demand), then continue where it stopped. Any change to this crate must keep every requirement below. The alternatives section says which one each rejected design breaks- R1 Core never calls the host: it names an op and waits for the answer, so it stays free of PyO3 and of any other host runtime-- R2 Async host work is awaited by the host's own driver in the caller's asyncio task (`litellm/rust_bridge/lifecycle.py`), so `contextvars` writes reach the caller. A Rust-side `into_future` would run it in a copied context+- R2 Async host work is awaited by the host's own driver in the caller's asyncio task (`litellm/rust_bridge/execution.py`), so `contextvars` writes reach the caller. A Rust-side `into_future` would run it in a copied context- R3 The body awaits real I/O (HTTP, `spawn_blocking`, timers) between yields, so `resume` is itself a future driven by the caller's runtime- R4 Route code stays straight-line async (`host.route(OcrOp::ReadDocument).await?`) instead of hand-written states- R5 Each op fixes its answer type at compile time: a host cannot answer `ReadDocument` with a token, and core never matches a result variant it did not ask fordiff --git a/litellm-rust/crates/host-python/AGENTS.md b/litellm-rust/crates/host-python/AGENTS.mdindex e511cc74a78..02b8d4f2dcb 100644--- a/litellm-rust/crates/host-python/AGENTS.md+++ b/litellm-rust/crates/host-python/AGENTS.md@@ -6,7 +6,7 @@ This crate owns CPython execution mechanics for generic `litellm-host` machines`src/native.rs` belongs here: it runs a generic machine through the Python runtime and owns its pending execution and abort handle. Keep provider selection, request projection and public exception policy out of it. A rename to `machine_runner.rs` is optional and must not change behavior-The execution handle receives its Python lifecycle binding from its consumer through `PythonLifecycle` rather than import a fixed `litellm.rust_bridge` module. Generic suspension and execution state validation belong here. Public stream wrappers and `_hidden_params` conventions belong to the consumer+`run_call` returns the unstarted `Execution` and never names a Python stream class or driver. The consumer drives it from Python and supplies the step classes through `StepTypes` rather than have this crate import a fixed `litellm.rust_bridge` module. Generic suspension and execution state validation belong here. Public stream wrappers and `_hidden_params` conventions belong to the consumerCreating a resolved asyncio Future from an already constructed Python value belongs here, alongside runtime waiting, interpreter detachment and panic containment. Choosing which callable exceptions become a public `RuntimeError` belongs to the consumer. `python-bridge::callable::wrap_failure` owns that policy@@ -38,7 +38,7 @@ Terminal notifications share the selected response or exception. An ordinary not- Keep diagnostic counters in the consumer. Wrapper invocations do not measure every interpreter release- Release exclusive class borrows/locks before Python calls or decrements that can invoke finalizers. Expose retained Python edges to GC without calling Python during traversal- Keep coroutine driving in the shared Python driver and the native handle- - Shared driver implementation: `litellm/rust_bridge/lifecycle.py`, handle: `src/handle.rs`, call driver: `src/driver.rs`, native-backed behavior tests: `tests/lifecycle.py`. The consumer supplies the lifecycle binding+ - Shared driver implementation: `litellm/rust_bridge/execution.py`, handle: `src/handle.rs`, call driver: `src/driver.rs`, native-backed behavior tests: `tests/lifecycle.py`. The consumer supplies the lifecycle binding- Every lifecycle suspension is awaited inline in the caller's task. `into_future` creates a separate task and cannot satisfy this contract- References: [ownership](https://pyo3.rs/v0.29.2/types.html), [conversions](https://pyo3.rs/v0.29.2/conversions/traits.html), [pythonize errors](https://docs.rs/pythonize/0.29.0/src/pythonize/error.rs.html)- [GC](https://pyo3.rs/v0.29.2/class/protocols.html#garbage-collector-integration), [re-entry](https://pyo3.rs/v0.29.2/class/call.html), [parallelism](https://pyo3.rs/v0.29.2/parallelism.html), [async delivery source](https://docs.rs/pyo3-async-runtimes/0.29.0/src/pyo3_async_runtimes/generic.rs.html)diff --git a/litellm-rust/crates/host-python/src/driver.rs b/litellm-rust/crates/host-python/src/driver.rsindex fed4cc1eeea..f8e35aa09ba 100644--- a/litellm-rust/crates/host-python/src/driver.rs+++ b/litellm-rust/crates/host-python/src/driver.rs@@ -19,7 +19,7 @@ use litellm_host::{use crate::PythonHostCalls;use crate::caller::{Answer, PythonCaller, Yielded};-use crate::handle::{Execution, ExecutionBody, ExecutionStep, PythonLifecycle, Suspension};+use crate::handle::{Execution, ExecutionBody, ExecutionStep, StepTypes};use crate::hooks::{HookStep, PythonCallEvent, PythonCallHooks};use crate::native::{NativeMachine, NativePoll};use crate::{Error, InvokeError, PythonBinding};@@ -37,15 +37,15 @@ type Body = Coroutine<Yielded, PyResult<Py<PyAny>>>;pub struct CallOptions {pub asynchronous: bool,- pub lifecycle: PythonLifecycle,+ pub steps: StepTypes,pub observers: Option<ObservationSender>,}impl CallOptions {- pub fn new(asynchronous: bool, lifecycle: PythonLifecycle) -> Self {+ pub fn new(asynchronous: bool, steps: StepTypes) -> Self {Self {asynchronous,- lifecycle,+ steps,observers: None,}}@@ -633,25 +633,10 @@ where.run()}});- let mut driver = CallDriver {+ let driver = CallDriver {body: Mutex::new(body),reply: None,parts,};- if options.asynchronous {- return Execution::new(driver, options.lifecycle)- .into_coroutine(py)- .map(Bound::unbind);- }- match driver.resume(None)? {- ExecutionStep::Return(value) => Ok(value),- ExecutionStep::Suspended(Suspension::StreamOpen(head)) => {- Execution::suspended(driver, options.lifecycle)- .into_sync_stream(py, head)- .map(Bound::unbind)- }- ExecutionStep::Suspended(Suspension::Await(_) | Suspension::StreamChunk(_)) => {- Err(Error::SyncCallSuspended.into())- }- }+ Py::new(py, Execution::new(driver, options.steps)).map(Py::into_any)}diff --git a/litellm-rust/crates/host-python/src/error.rs b/litellm-rust/crates/host-python/src/error.rsindex b22959432c1..b06a4a2fd41 100644--- a/litellm-rust/crates/host-python/src/error.rs+++ b/litellm-rust/crates/host-python/src/error.rs@@ -20,8 +20,6 @@ pub enum Error {ExecutionClosedWhileRunning,#[error("native execution closed")]NativeExecutionClosed,- #[error("sync call suspended")]- SyncCallSuspended,#[error("synchronous native routes cannot run from a Tokio context; use the async route")]SyncInsideTokio,#[error("the context body produced no value")]@@ -42,7 +40,6 @@ impl From<Error> for PyErr {| Error::ExecutionOutOfOrder| Error::ExecutionClosedWhileRunning| Error::NativeExecutionClosed- | Error::SyncCallSuspended| Error::SyncInsideTokio| Error::ContextBodyProducedNothing => PyRuntimeError::new_err(error.to_string()),}diff --git a/litellm-rust/crates/host-python/src/handle.rs b/litellm-rust/crates/host-python/src/handle.rsindex 39a36b72a20..2361128bf43 100644--- a/litellm-rust/crates/host-python/src/handle.rs+++ b/litellm-rust/crates/host-python/src/handle.rs@@ -5,7 +5,7 @@ use pyo3::exceptions::PyBaseException;use pyo3::gc::{PyTraverseError, PyVisit};use pyo3::prelude::*;-pub type PythonLifecycle = for<'py> fn(Python<'py>) -> PyResult<Bound<'py, PyModule>>;+pub type StepTypes = for<'py> fn(Python<'py>) -> PyResult<Bound<'py, PyModule>>;/// What a suspended execution waits on: an awaitable the caller awaits, or a stream/// boundary the caller's stream reads past.@@ -42,38 +42,14 @@ enum ExecutionState {#[pyclass]pub struct Execution {state: ExecutionState,- lifecycle: PythonLifecycle,+ steps: StepTypes,}impl Execution {- pub fn new(body: impl ExecutionBody + 'static, lifecycle: PythonLifecycle) -> Self {+ pub fn new(body: impl ExecutionBody + 'static, steps: StepTypes) -> Self {Self {state: ExecutionState::Created(Box::new(body)),- lifecycle,- }- }-- pub fn into_coroutine(self, py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {- let binding = (self.lifecycle)(py)?;- let execution = Py::new(py, self)?;- binding.getattr("drive")?.call1((execution,))- }-- pub(crate) fn into_sync_stream(- self,- py: Python<'_>,- head: Py<PyAny>,- ) -> PyResult<Bound<'_, PyAny>> {- (self.lifecycle)(py)?- .getattr("SyncStream")?- .call1((Py::new(py, self)?, head))- }-- /// An execution already started elsewhere and now waiting for its next input.- pub fn suspended(body: impl ExecutionBody + 'static, lifecycle: PythonLifecycle) -> Self {- Self {- state: ExecutionState::Suspended(Box::new(body)),- lifecycle,+ steps,}}@@ -105,7 +81,7 @@ impl Execution {Resume::Send(value) => started.then_some(Ok(value)),Resume::Throw(error) => Some(Err(error)),};- let lifecycle = slf.borrow().lifecycle;+ let steps = slf.borrow().steps;let outcome = catch_unwind(AssertUnwindSafe(|| {let step = body.resume(result)?;let (tag, value, suspended) = match step {@@ -118,7 +94,7 @@ impl Execution {}ExecutionStep::Return(value) => ("Complete", value, false),};- let step = lifecycle(py)?.getattr(tag)?.call1((value,))?.unbind();+ let step = steps(py)?.getattr(tag)?.call1((value,))?.unbind();Ok((step, suspended))})).map_err(panic_to_pyerr)diff --git a/litellm-rust/crates/host-python/src/lib.rs b/litellm-rust/crates/host-python/src/lib.rsindex 580e6674b95..8e37ab02669 100644--- a/litellm-rust/crates/host-python/src/lib.rs+++ b/litellm-rust/crates/host-python/src/lib.rs@@ -28,7 +28,7 @@ pub use error::{Error, InvokeError};pub use file_reader::{FileContent, PythonFileReader, py_bytes};pub use fork_gate::RuntimeAlreadyStarted;pub use gil::{PythonContext, attach_blocking, release_count, release_gil};-pub use handle::{Execution, ExecutionBody, ExecutionStep, PythonLifecycle, Suspension};+pub use handle::{Execution, ExecutionBody, ExecutionStep, StepTypes, Suspension};pub use hooks::{HookChain, HookResume, HookStep, PythonCallEvent, PythonCallHooks, PythonRuntime};pub use marshal::{Pythonized, from_py, from_py_argument, json_loads, json_object_field, panic_to_pyerr, to_py,diff --git a/litellm-rust/crates/host-python/tests/driver.rs b/litellm-rust/crates/host-python/tests/driver.rsindex 522e4b4ae8c..157cfc92148 100644--- a/litellm-rust/crates/host-python/tests/driver.rs+++ b/litellm-rust/crates/host-python/tests/driver.rs@@ -23,15 +23,15 @@ use pyo3::{use rstest::rstest;use support::{HookScript, Interpreter, Log, MachineFactory, OpScript, Synthetic, binding, call_options,- failing_machine, hooks, interpreter, lifecycle_binding, open_stream, read_all, run_composed,- run_scripted, settled, success_machine,+ failing_machine, handed, hooks, interpreter, lifecycle_module, open_stream, read_all,+ run_composed, run_scripted, settled, success_machine,};fn observed(capacity: usize) -> (CallOptions, impl FnMut() -> Vec<CallEvent>) {let (sender, mut receiver) = observation_channel(NonZeroUsize::new(capacity).unwrap());let options = CallOptions {asynchronous: false,- lifecycle: lifecycle_binding,+ steps: lifecycle_module,observers: Some(sender),};(options, move || {@@ -83,13 +83,17 @@ fn composed_hooks_share_prepared_arguments_and_one_execution(.with(hooks(&log, HookScript::ObserveArguments)).with(hooks(&log, HookScript::RewriteArguments)).with(hooks(&log, HookScript::ReplaceResponse));- let result = run_call(+ let result = handed(py,- move |_, _, request| Ok(success_machine()(request)),- binding(&log, OpScript::Answer),- chain,- PyDict::new(py).unbind(),- call_options(asynchronous),+ run_call(+ py,+ move |_, _, request| Ok(success_machine()(request)),+ binding(&log, OpScript::Answer),+ chain,+ PyDict::new(py).unbind(),+ call_options(asynchronous),+ ),+ asynchronous,);if asynchronous {assert!(log.entries().is_empty());@@ -148,7 +152,7 @@ fn observation_delivery_preserves_callback_order_and_response(std::convert::identity,CallOptions {asynchronous,- lifecycle: lifecycle_binding,+ steps: lifecycle_module,observers: Some(sender.clone()),},);@@ -389,7 +393,7 @@ fn a_stream_carries_its_head_before_the_first_chunk(call_options(asynchronous),);let hidden: std::collections::HashMap<String, std::collections::HashMap<String, String>> =- stream.getattr("head").unwrap().extract().unwrap();+ stream.getattr("_hidden_params").unwrap().extract().unwrap();assert_eq!(hidden["additional_headers"],std::collections::HashMap::from([("request-id".to_string(), "req_1".to_string())])@@ -563,23 +567,27 @@ fn resource_setup_uses_prepared_arguments_and_failures_are_terminal(let setup_error = error.clone_ref(py);let arguments = PyDict::new(py);arguments.set_item("api_key", "original").unwrap();- let result = run_call(+ let result = handed(py,- move |py, prepared, request| {- let source: String = prepared.get_item("prepared")?.unwrap().extract()?;- let key: String = prepared.get_item("api_key")?.unwrap().extract()?;- setup_log.push(format!("setup:{source}:{key}"));- if fail_setup {- return Err(PyErr::from_value(setup_error.into_bound(py).into_any()));- }- Ok(success_machine()(request))- },- binding(&log, OpScript::Answer),- HookChain::new()- .with(hooks(&log, HookScript::RewriteArguments))- .with(ArgumentPolicy::Inherit),- arguments.clone().unbind(),- call_options(asynchronous),+ run_call(+ py,+ move |py, prepared, request| {+ let source: String = prepared.get_item("prepared")?.unwrap().extract()?;+ let key: String = prepared.get_item("api_key")?.unwrap().extract()?;+ setup_log.push(format!("setup:{source}:{key}"));+ if fail_setup {+ return Err(PyErr::from_value(setup_error.into_bound(py).into_any()));+ }+ Ok(success_machine()(request))+ },+ binding(&log, OpScript::Answer),+ HookChain::new()+ .with(hooks(&log, HookScript::RewriteArguments))+ .with(ArgumentPolicy::Inherit),+ arguments.clone().unbind(),+ call_options(asynchronous),+ ),+ asynchronous,);if asynchronous {assert!(log.entries().is_empty());@@ -630,16 +638,20 @@ fn closing_an_unstarted_call_never_initializes_resources(Python::attach(|py| {let log = Log::default();let setup_log = log.clone();- let pending = run_call(+ let pending = handed(py,- move |_, _, request| {- setup_log.push("setup");- Ok(success_machine()(request))- },- binding(&log, OpScript::Answer),- hooks(&log, HookScript::Plain),- PyDict::new(py).unbind(),- call_options(true),+ run_call(+ py,+ move |_, _, request| {+ setup_log.push("setup");+ Ok(success_machine()(request))+ },+ binding(&log, OpScript::Answer),+ hooks(&log, HookScript::Plain),+ PyDict::new(py).unbind(),+ call_options(true),+ ),+ true,).unwrap();assert!(log.entries().is_empty());diff --git a/litellm-rust/crates/host-python/tests/handle.rs b/litellm-rust/crates/host-python/tests/handle.rsindex 916850f4b84..fe900f2c1ec 100644--- a/litellm-rust/crates/host-python/tests/handle.rs+++ b/litellm-rust/crates/host-python/tests/handle.rs@@ -13,8 +13,8 @@ use pyo3::{};use rstest::rstest;use support::{- Interpreter, Log, OpScript, binding, call_options, install_lifecycle_module, interpreter,- lifecycle_binding, success_machine,+ Interpreter, Log, OpScript, binding, call_options, handed, install_lifecycle_module,+ interpreter, lifecycle_module, success_machine,};struct RetainingHost {@@ -39,7 +39,7 @@ fn retaining_coroutine(py: Python<'_>, retained: Py<PyAny>) -> PyResult<Py<ExecuRetainingHost {retained: Some(retained),},- lifecycle_binding,+ lifecycle_module,),)}@@ -63,7 +63,7 @@ impl ExecutionBody for AwaitBody {#[pyfunction]fn await_execution(awaitable: Py<PyAny>) -> Execution {- Execution::new(AwaitBody(Some(awaitable)), lifecycle_binding)+ Execution::new(AwaitBody(Some(awaitable)), lifecycle_module)}struct CallingBody(Py<PyAny>);@@ -80,7 +80,7 @@ impl ExecutionBody for CallingBody {#[pyfunction]fn calling_execution(callback: Py<PyAny>) -> Execution {- Execution::new(CallingBody(callback), lifecycle_binding)+ Execution::new(CallingBody(callback), lifecycle_module)}struct ErrorBody(Option<Py<PyBaseException>>);@@ -101,7 +101,7 @@ impl ExecutionBody for ErrorBody {#[pyfunction]fn error_execution(error: Bound<'_, PyBaseException>) -> Execution {- Execution::new(ErrorBody(Some(error.unbind())), lifecycle_binding)+ Execution::new(ErrorBody(Some(error.unbind())), lifecycle_module)}/// Where a paused call keeps the test's object: in its hooks, or selected as the call's@@ -173,17 +173,21 @@ fn paused_call(holder: Holder,) -> PyResult<Py<PyAny>> {let machine = success_machine();- run_call(+ handed(py,- move |_, _, request| Ok(machine(request)),- binding(&Log::default(), OpScript::Answer),- PausingHooks {- retained: Some(retained),- pause: Some(pause),- holder,- },- PyDict::new(py).unbind(),- call_options(true),+ run_call(+ py,+ move |_, _, request| Ok(machine(request)),+ binding(&Log::default(), OpScript::Answer),+ PausingHooks {+ retained: Some(retained),+ pause: Some(pause),+ holder,+ },+ PyDict::new(py).unbind(),+ call_options(true),+ ),+ true,)}diff --git a/litellm-rust/crates/host-python/tests/hook_chain.rs b/litellm-rust/crates/host-python/tests/hook_chain.rsindex faae56e6daf..4b520ca2665 100644--- a/litellm-rust/crates/host-python/tests/hook_chain.rs+++ b/litellm-rust/crates/host-python/tests/hook_chain.rs@@ -519,12 +519,10 @@ impl litellm_host_python::ExecutionBody for Preparing {}fn lifecycle(py: Python<'_>) -> PyResult<Bound<'_, PyModule>> {- let source = std::ffi::CString::new(concat!(- include_str!("../../../../litellm/rust_bridge/lifecycle.py"),- "\n_drive = drive\n\n\nasync def drive(execution):\n return await _drive(execution, Stream)\n",- ))- .unwrap();- PyModule::from_code(py, &source, c"lifecycle.py", c"hook_chain_test_lifecycle")+ let source =+ std::ffi::CString::new(include_str!("../../../../litellm/rust_bridge/execution.py"))+ .unwrap();+ PyModule::from_code(py, &source, c"execution.py", c"hook_chain_test_lifecycle")}#[rstest]@@ -560,9 +558,16 @@ second = Hooks('b', invoke)},lifecycle,);- locals- .set_item("call", execution.into_coroutine(py).unwrap())+ let module = lifecycle(py).unwrap();+ let call = module+ .getattr("drive")+ .unwrap()+ .call1((+ Py::new(py, execution).unwrap(),+ module.getattr("AsyncStream").unwrap(),+ )).unwrap();+ locals.set_item("call", call).unwrap();py.run(c"async def exercise():diff --git a/litellm-rust/crates/host-python/tests/support/mod.rs b/litellm-rust/crates/host-python/tests/support/mod.rsindex be93fb822a8..ef09135698e 100644--- a/litellm-rust/crates/host-python/tests/support/mod.rs+++ b/litellm-rust/crates/host-python/tests/support/mod.rs@@ -41,24 +41,43 @@ pub fn interpreter() -> Interpreter {Interpreter(guard)}-pub fn lifecycle_binding(py: Python<'_>) -> PyResult<Bound<'_, PyModule>> {+pub fn lifecycle_module(py: Python<'_>) -> PyResult<Bound<'_, PyModule>> {py.import("host_test_lifecycle")}+/// Hands a call's execution to its caller the way the product entrypoints do: an async call+/// gets the coroutine from `drive`, a sync call the value or stream `run` settles to.+pub fn handed(+ py: Python<'_>,+ execution: PyResult<Py<PyAny>>,+ asynchronous: bool,+) -> PyResult<Py<PyAny>> {+ let execution = execution?;+ let module = lifecycle_module(py)?;+ let handed = if asynchronous {+ module.getattr("drive")?.call1((execution,))?+ } else {+ module+ .getattr("run")?+ .call1((execution, module.getattr("SyncStream")?))?+ };+ Ok(handed.unbind())+}+pub fn call_options(asynchronous: bool) -> CallOptions {- CallOptions::new(asynchronous, lifecycle_binding)+ CallOptions::new(asynchronous, lifecycle_module)}pub fn install_lifecycle_module(py: Python<'_>) -> Bound<'_, PyModule> {let source = std::ffi::CString::new(concat!(- include_str!("../../../../../litellm/rust_bridge/lifecycle.py"),- "\n_drive = drive\n\n\nasync def drive(execution):\n return await _drive(execution, Stream)\n",+ include_str!("../../../../../litellm/rust_bridge/execution.py"),+ "\n_drive = drive\n\n\nasync def drive(execution):\n return await _drive(execution, AsyncStream)\n",)).unwrap();PyModule::from_code(py,&source,- pyo3::ffi::c_str!("lifecycle.py"),+ pyo3::ffi::c_str!("execution.py"),pyo3::ffi::c_str!("host_test_lifecycle"),).unwrap()@@ -512,13 +531,17 @@ pub fn run_composed<L: PythonCallHooks + 'static>(let log = binding.log.clone();let arguments = PyDict::new(py);arguments.set_item("model", "m").unwrap();- let result = run_call(+ let result = handed(py,- move |_, _, request| Ok(machine(request)),- binding,- compose(hooks),- arguments.unbind(),- options,+ run_call(+ py,+ move |_, _, request| Ok(machine(request)),+ binding,+ compose(hooks),+ arguments.unbind(),+ options,+ ),+ asynchronous,);(settled(py, result, asynchronous), log.entries())}@@ -615,13 +638,17 @@ pub fn open_stream(options: CallOptions,) -> Bound<'_, PyAny> {let asynchronous = options.asynchronous;- let handed = run_call(+ let handed = handed(py,- |_, _, request| Ok(streaming_machine()(request)),- StreamingBinding,- hooks,- PyDict::new(py).unbind(),- options,+ run_call(+ py,+ |_, _, request| Ok(streaming_machine()(request)),+ StreamingBinding,+ hooks,+ PyDict::new(py).unbind(),+ options,+ ),+ asynchronous,).unwrap();if asynchronous {@@ -632,7 +659,7 @@ pub fn open_stream(}}-/// Drives a `Stream` (async) or `SyncStream` to completion from a sync test.+/// Drives an `AsyncStream` or `SyncStream` to completion from a sync test.pub fn read_all(py: Python<'_>, stream: &Bound<'_, PyAny>, asynchronous: bool) -> Vec<String> {if !asynchronous {return streamdiff --git a/litellm-rust/crates/python-bridge/AGENTS.md b/litellm-rust/crates/python-bridge/AGENTS.mdindex 28ea62468f9..c435ba37e78 100644--- a/litellm-rust/crates/python-bridge/AGENTS.md+++ b/litellm-rust/crates/python-bridge/AGENTS.md@@ -48,7 +48,7 @@ Each step needs focused regression tests in the owning crate and Python integrat- Preserve provider-specific upload/submission/poll observation and encoding boundaries. Signed/build-captured bytes must not be silently reserialized- Conversion errors and every failure after the call starts are terminal- Disabled/unavailable native execution may select legacy once. Callback exceptions never authorize fallback or replay-- Use one ordinary inline `async def` driver in `litellm/rust_bridge/lifecycle.py`, with the native handle and call driver in `litellm-host-python`+- Use one ordinary inline `async def` driver in `litellm/rust_bridge/execution.py`, with the native handle and call driver in `litellm-host-python`- Contract: generator-style `send` (`send(None)` starts), `throw`, idempotent `close`. Explicitly tagged `Await`/`Complete` preserve awaitable final values- Validate Created/Running/Suspended/Closed protocol states. The machine yields ops, the driver emits one terminal event, the adapter chooses dispatch policy- Defer effectful setup/context reads/timestamps until start. Unstarted-handle destruction releases inputs independently of Python `finally`diff --git a/litellm-rust/crates/python-bridge/src/lib.rs b/litellm-rust/crates/python-bridge/src/lib.rsindex 9fed9422240..12827b76ff3 100644--- a/litellm-rust/crates/python-bridge/src/lib.rs+++ b/litellm-rust/crates/python-bridge/src/lib.rs@@ -6,7 +6,6 @@ mod diagnostics;mod errors;mod execution;mod http;-mod lifecycle;mod logger;mod marshal;mod preflight;diff --git a/litellm-rust/crates/python-bridge/src/lifecycle.rs b/litellm-rust/crates/python-bridge/src/lifecycle.rsdeleted file mode 100644index b69976278d4..00000000000--- a/litellm-rust/crates/python-bridge/src/lifecycle.rs+++ /dev/null@@ -1,10 +0,0 @@-use litellm_host_python::CallOptions;-use pyo3::prelude::*;--pub(crate) fn binding(py: Python<'_>) -> PyResult<Bound<'_, PyModule>> {- py.import("litellm.rust_bridge.streams")-}--pub(crate) fn call_options(asynchronous: bool) -> CallOptions {- CallOptions::new(asynchronous, binding)-}diff --git a/litellm-rust/crates/python-bridge/src/routes/mod.rs b/litellm-rust/crates/python-bridge/src/routes/mod.rsindex 31885694b82..444ef4f01b7 100644--- a/litellm-rust/crates/python-bridge/src/routes/mod.rs+++ b/litellm-rust/crates/python-bridge/src/routes/mod.rs@@ -11,10 +11,10 @@ pub(crate) mod traces;use litellm_callbacks_legacy_python::{LegacyLogging, LoggingOperation, PublicCall};use litellm_host::{call::HostedCompletion, machine::Machine, protocol::Protocol};-use litellm_host_python::{Error as HostError, present};use litellm_host_python::{- HookChain, PythonBinding, PythonCallHooks, PythonHostCalls, effective_py_args,+ CallOptions, HookChain, PythonBinding, PythonCallHooks, PythonHostCalls, effective_py_args,};+use litellm_host_python::{Error as HostError, present};use pyo3::{gc::{PyTraverseError, PyVisit},prelude::*,@@ -129,6 +129,10 @@ fn call_hooks())}+fn execution_steps(py: Python<'_>) -> PyResult<Bound<'_, PyModule>> {+ py.import("litellm.rust_bridge.execution")+}+fn run_public_call<H, M>(py: Python<'_>,arguments: Py<PyDict>,@@ -159,7 +163,7 @@ where.with(hooks).with(crate::preflight::SdkPolicy),arguments,- crate::lifecycle::call_options(asynchronous),+ CallOptions::new(asynchronous, execution_steps),)}diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.pyindex 6027f3774fd..461ac5d947f 100644--- a/litellm/caching/redis_cache.py+++ b/litellm/caching/redis_cache.py@@ -102,8 +102,7 @@ _GENERIC_CALLER_MODULES: Final = frozenset("litellm.caching.redis_batch","litellm.caching.dual_cache","litellm.caching.caching",- "litellm.rust_bridge.lifecycle",- "litellm.rust_bridge.streams",+ "litellm.rust_bridge.execution","contextlib",})diff --git a/litellm/rust_bridge/AGENTS.md b/litellm/rust_bridge/AGENTS.mdindex 9845ba9f18e..607bb257a0e 100644--- a/litellm/rust_bridge/AGENTS.md+++ b/litellm/rust_bridge/AGENTS.md@@ -4,7 +4,7 @@ This package owns native rollout and fallback selection, Python public API compa`host/` holds the Python modules Rust imports by name to read Python-owned state (provider resolution, model capabilities, settings, caches, diagnostics, legacy callbacks, the secret manager, transport and timeout conversions). Its AGENTS.md states that contract-`lifecycle.py` owns generic inline execution and stream iteration. `streams.py` supplies the product binding and public stream wrappers through the bridge rather than let the generic Rust host import this package by name. Keep one driver implementing generator-style `send` (`send(None)` starts), `throw` and idempotent `close`. Do not create a second implementation+`execution.py` owns generic inline execution and stream iteration, plus the step classes Rust constructs. Native entrypoints return an unstarted `Execution`, and `execution.synchronous` or `execution.asynchronous` hands it to the public caller through `run` or `drive` with the one stream pair, so Rust never names a Python driver or stream class. Keep one driver implementing generator-style `send` (`send(None)` starts), `throw` and idempotent `close`. Do not create a second implementationGeneric execution steps and inline suspension handling must not depend on LiteLLM response metadata. Public stream construction, `_hidden_params` and header compatibility remain product responsibilities. Keep generic stream heads opaque and preserve public header behavior in the product wrappersdiff --git a/litellm/rust_bridge/_native.pyi b/litellm/rust_bridge/_native.pyiindex d196ceddacf..7364a1d72f2 100644--- a/litellm/rust_bridge/_native.pyi+++ b/litellm/rust_bridge/_native.pyi@@ -1,15 +1,12 @@from asyncio import Future-from collections.abc import AsyncIterator, Coroutine, Iterator, Mapping, Sequence+from collections.abc import Mapping, Sequencefrom typing import Never, finalimport httpxfrom pydantic import JsonValue-from litellm.llms.base_llm.ocr.transformation import OCRResponse+from litellm.rust_bridge.execution import Executionfrom litellm.rust_bridge.public_call import NativeCall-from litellm.types.llms.anthropic_messages.anthropic_response import AnthropicMessagesResponse-from litellm.types.llms.openai import ResponsesAPIResponse-from litellm.types.utils import EmbeddingResponse, ModelResponseclass RustBridgeDeclined(Exception): ...class RustUpstreamError(Exception): ...@@ -17,6 +14,7 @@ class ForkedAfterNativeRuntimeStarted(RuntimeError): ...class ProcessReservedForForking(RuntimeError): ...def trace_encode_error(message: str) -> bytes: ...+@finalclass NativeClickHouseSpendConfig:def __new__(cls, database: str, url: str, retention_days: int) -> NativeClickHouseSpendConfig: ...@@ -45,18 +43,18 @@ class NativeDiagnosticProcessor:def ocr(call: NativeCall,-) -> OCRResponse: ...+) -> Execution: ...def aocr(call: NativeCall,-) -> Coroutine[object, object, OCRResponse]: ...+) -> Execution: ...def ocr_health_check_document(model: str, custom_llm_provider: str | None) -> dict[str, object]: ...def ocr_passthrough_response(model: str, endpoint: str, body: bytes) -> dict[str, object] | None: ...def embedding(call: NativeCall,-) -> EmbeddingResponse: ...+) -> Execution: ...def aembedding(call: NativeCall,-) -> Coroutine[object, object, EmbeddingResponse]: ...+) -> Execution: ...def transcription(call: NativeCall,) -> dict[str, object]: ...@@ -65,22 +63,22 @@ def atranscription() -> Future[dict[str, object]]: ...def completion(call: NativeCall,-) -> ModelResponse: ...+) -> Execution: ...def acompletion(call: NativeCall,-) -> Coroutine[object, object, ModelResponse]: ...+) -> Execution: ...def responses(call: NativeCall,-) -> ResponsesAPIResponse: ...+) -> Execution: ...def aresponses(call: NativeCall,-) -> Coroutine[object, object, ResponsesAPIResponse]: ...+) -> Execution: ...def messages(call: NativeCall,-) -> AnthropicMessagesResponse | Iterator[bytes]: ...+) -> Execution: ...def amessages(call: NativeCall,-) -> Coroutine[object, object, AnthropicMessagesResponse | AsyncIterator[bytes]]: ...+) -> Execution: ...@finalclass ResponsesWebSocketConnection:diff --git a/litellm/rust_bridge/chat_completions/entrypoints.py b/litellm/rust_bridge/chat_completions/entrypoints.pyindex 6bfcffa2c21..8f6a3033103 100644--- a/litellm/rust_bridge/chat_completions/entrypoints.py+++ b/litellm/rust_bridge/chat_completions/entrypoints.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom collections.abc import Awaitablefrom typing import Final, Protocol, cast # noqa: TID251 # validates dynamically loaded native callables+from litellm.rust_bridge import executionfrom litellm.rust_bridge.bindings import NativeBindingfrom litellm.rust_bridge.public_call import NativeCallfrom litellm.types.utils import ModelResponse@@ -25,13 +26,15 @@ class NativeAcompletion(Protocol):def _completion_binding(value: object) -> NativeCompletion | None:if not callable(value):return None- return cast("NativeCompletion", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.synchronous(value)+ return cast("NativeCompletion", native) # cast-ok: the execution adapter returns the route's resultdef _acompletion_binding(value: object) -> NativeAcompletion | None:if not callable(value):return None- return cast("NativeAcompletion", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.asynchronous(value)+ return cast("NativeAcompletion", native) # cast-ok: the execution adapter returns the route's resultNATIVE_COMPLETION: Final = NativeBinding("completion", validate=_completion_binding)diff --git a/litellm/rust_bridge/embeddings/entrypoints.py b/litellm/rust_bridge/embeddings/entrypoints.pyindex 2fed4eb512b..8b027a6bd6a 100644--- a/litellm/rust_bridge/embeddings/entrypoints.py+++ b/litellm/rust_bridge/embeddings/entrypoints.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom collections.abc import Awaitablefrom typing import Final, Protocol, cast # noqa: TID251 # validates dynamically loaded native callables+from litellm.rust_bridge import executionfrom litellm.rust_bridge.bindings import NativeBindingfrom litellm.rust_bridge.public_call import NativeCallfrom litellm.types.utils import EmbeddingResponse@@ -25,13 +26,15 @@ class NativeAembedding(Protocol):def _embedding_binding(value: object) -> NativeEmbedding | None:if not callable(value):return None- return cast("NativeEmbedding", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.synchronous(value)+ return cast("NativeEmbedding", native) # cast-ok: the execution adapter returns the route's resultdef _aembedding_binding(value: object) -> NativeAembedding | None:if not callable(value):return None- return cast("NativeAembedding", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.asynchronous(value)+ return cast("NativeAembedding", native) # cast-ok: the execution adapter returns the route's resultNATIVE_EMBEDDING: Final = NativeBinding("embedding", validate=_embedding_binding)diff --git a/litellm/rust_bridge/lifecycle.py b/litellm/rust_bridge/execution.pysimilarity index 63%rename from litellm/rust_bridge/lifecycle.pyrename to litellm/rust_bridge/execution.pyindex 15e889c868c..430de8d1ad6 100644--- a/litellm/rust_bridge/lifecycle.py+++ b/litellm/rust_bridge/execution.py@@ -1,9 +1,11 @@from __future__ import annotations-from collections.abc import AsyncIterator, Awaitable, Callable, Iterator+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mappingfrom contextlib import ExitStackfrom dataclasses import dataclass-from typing import Final, Protocol+from typing import Final, Protocol, TypeVar, cast # noqa: TID251 # trusts the native stub at the binding boundary++_Call: Final = TypeVar("_Call")@dataclass(frozen=True, slots=True)@@ -42,6 +44,10 @@ class Execution(Protocol):_REOPENED: Final = "execution opened a stream twice"+def _headers(head: object) -> Mapping[str, object]:+ return cast("Mapping[str, object]", head) # cast-ok: encode_stream_head always builds a str-keyed dict++class StreamClosed(Exception):"""Tells a streaming execution that its caller stopped reading."""@@ -65,29 +71,53 @@ def _settled(step: Step) -> Settled:return step+def _hand_off(+ execution: Execution, step: Settled, open_stream: Callable[[Execution, object], object], cleanup: ExitStack+) -> object:+ match step:+ case Complete(value):+ return value+ case StreamOpen(head):+ stream: Final = open_stream(execution, head)+ cleanup.pop_all()+ return stream+ case StreamChunk():+ raise RuntimeError("execution yielded a chunk before opening a stream")++async def drive(execution: Execution, open_stream: Callable[[Execution, object], object]) -> object:with ExitStack() as cleanup:cleanup.callback(execution.close)- match await _settle(execution, execution.send(None)):- case Complete(value):- return value- case StreamOpen(head):- stream: Final = open_stream(execution, head)- cleanup.pop_all()- return stream- case StreamChunk():- raise RuntimeError("execution yielded a chunk before opening a stream")---class Stream(AsyncIterator[object]):+ return _hand_off(execution, await _settle(execution, execution.send(None)), open_stream, cleanup)+++def run(execution: Execution, open_stream: Callable[[Execution, object], object]) -> object:+ with ExitStack() as cleanup:+ cleanup.callback(execution.close)+ return _hand_off(execution, _settled(execution.send(None)), open_stream, cleanup)+++def synchronous(native: Callable[[_Call], object]) -> Callable[[_Call], object]:+ return lambda call: run(_execution(native(call)), SyncStream)+++def asynchronous(native: Callable[[_Call], object]) -> Callable[[_Call], Awaitable[object]]:+ return lambda call: drive(_execution(native(call)), AsyncStream)+++def _execution(value: object) -> Execution:+ return cast("Execution", value) # cast-ok: native entrypoints return Execution per _native.pyi+++class AsyncStream(AsyncIterator[object]):"""A streamed native call: each read resumes the execution until its next chunk."""- def __init__(self, execution: Execution, head: object = None) -> None:+ def __init__(self, execution: Execution, head: object) -> None:self._execution: Final = executionself._done = False- self.head: Final = head+ self._hidden_params: dict[str, object] = dict(_headers(head)) # mutable-ok: header writers mutate it- def __aiter__(self) -> Stream:+ def __aiter__(self) -> AsyncStream:return selfasync def __anext__(self) -> object:@@ -122,12 +152,12 @@ class Stream(AsyncIterator[object]):class SyncStream(Iterator[object]):- """The sync form of `Stream`; its execution never suspends on an awaitable."""+ """The sync form of `AsyncStream`; its execution never suspends on an awaitable."""- def __init__(self, execution: Execution, head: object = None) -> None:+ def __init__(self, execution: Execution, head: object) -> None:self._execution: Final = executionself._done = False- self.head: Final = head+ self._hidden_params: dict[str, object] = dict(_headers(head)) # mutable-ok: header writers mutate itdef __iter__(self) -> SyncStream:return selfdiff --git a/litellm/rust_bridge/messages/entrypoints.py b/litellm/rust_bridge/messages/entrypoints.pyindex c49877bf174..756d62b747a 100644--- a/litellm/rust_bridge/messages/entrypoints.py+++ b/litellm/rust_bridge/messages/entrypoints.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom collections.abc import AsyncIterator, Awaitable, Iteratorfrom typing import Final, Protocol, cast # noqa: TID251 # validates dynamically loaded native callables+from litellm.rust_bridge import executionfrom litellm.rust_bridge.bindings import NativeBindingfrom litellm.rust_bridge.public_call import NativeCallfrom litellm.types.llms.anthropic_messages.anthropic_response import AnthropicMessagesResponse@@ -25,13 +26,15 @@ class NativeAmessages(Protocol):def _messages_binding(value: object) -> NativeMessages | None:if not callable(value):return None- return cast("NativeMessages", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.synchronous(value)+ return cast("NativeMessages", native) # cast-ok: the execution adapter returns the route's resultdef _amessages_binding(value: object) -> NativeAmessages | None:if not callable(value):return None- return cast("NativeAmessages", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.asynchronous(value)+ return cast("NativeAmessages", native) # cast-ok: the execution adapter returns the route's resultNATIVE_MESSAGES: Final = NativeBinding("messages", validate=_messages_binding)diff --git a/litellm/rust_bridge/ocr/entrypoints.py b/litellm/rust_bridge/ocr/entrypoints.pyindex 2796f0148e3..09a98d8dbfc 100644--- a/litellm/rust_bridge/ocr/entrypoints.py+++ b/litellm/rust_bridge/ocr/entrypoints.py@@ -4,6 +4,7 @@ from collections.abc import Awaitable, Mappingfrom typing import Final, Protocol, cast # noqa: TID251 # validates dynamically loaded native callablesfrom litellm.llms.base_llm.ocr.transformation import DocumentType, OCRResponse+from litellm.rust_bridge import executionfrom litellm.rust_bridge.bindings import NativeBindingfrom litellm.rust_bridge.public_call import NativeCall@@ -25,13 +26,15 @@ class NativeAocr(Protocol):def _ocr_binding(value: object) -> NativeOcr | None:if not callable(value):return None- return cast("NativeOcr", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.synchronous(value)+ return cast("NativeOcr", native) # cast-ok: the execution adapter returns the route's resultdef _aocr_binding(value: object) -> NativeAocr | None:if not callable(value):return None- return cast("NativeAocr", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.asynchronous(value)+ return cast("NativeAocr", native) # cast-ok: the execution adapter returns the route's resultclass NativeOcrHealthCheckDocument(Protocol):diff --git a/litellm/rust_bridge/responses/entrypoints.py b/litellm/rust_bridge/responses/entrypoints.pyindex e0bb973075c..909d00d8131 100644--- a/litellm/rust_bridge/responses/entrypoints.py+++ b/litellm/rust_bridge/responses/entrypoints.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom collections.abc import Awaitablefrom typing import Final, Protocol, cast # noqa: TID251 # validates dynamically loaded native callables+from litellm.rust_bridge import executionfrom litellm.rust_bridge.bindings import NativeBindingfrom litellm.rust_bridge.public_call import NativeCallfrom litellm.types.llms.openai import ResponsesAPIResponse@@ -25,13 +26,15 @@ class NativeAresponses(Protocol):def _responses_binding(value: object) -> NativeResponses | None:if not callable(value):return None- return cast("NativeResponses", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.synchronous(value)+ return cast("NativeResponses", native) # cast-ok: the execution adapter returns the route's resultdef _aresponses_binding(value: object) -> NativeAresponses | None:if not callable(value):return None- return cast("NativeAresponses", value) # cast-ok: callable validated at the native binding boundary+ native: Final = execution.asynchronous(value)+ return cast("NativeAresponses", native) # cast-ok: the execution adapter returns the route's resultNATIVE_RESPONSES: Final = NativeBinding("responses", validate=_responses_binding)diff --git a/litellm/rust_bridge/streams.py b/litellm/rust_bridge/streams.pydeleted file mode 100644index 4f8f935d3da..00000000000--- a/litellm/rust_bridge/streams.py+++ /dev/null@@ -1,56 +0,0 @@-from __future__ import annotations--from collections.abc import AsyncIterator, Iterator, Mapping-from typing import Final--from pydantic import TypeAdapter--from litellm.rust_bridge import lifecycle-from litellm.rust_bridge.lifecycle import Execution--Await: Final = lifecycle.Await-Complete: Final = lifecycle.Complete-StreamOpen: Final = lifecycle.StreamOpen-StreamChunk: Final = lifecycle.StreamChunk--_HEADERS: Final = TypeAdapter(Mapping[str, object])---async def drive(execution: Execution) -> object:- return await lifecycle.drive(execution, Stream)---class Stream(AsyncIterator[object]):- def __init__(self, execution: Execution, hidden_params: object = None) -> None:- self._stream: Final = lifecycle.Stream(execution, hidden_params)- self._hidden_params: dict[str, object] = dict(_headers(hidden_params)) # mutable-ok: header writers mutate it-- def __aiter__(self) -> Stream:- return self-- async def __anext__(self) -> object:- return await self._stream.__anext__()-- async def aclose(self) -> None:- await self._stream.aclose()---class SyncStream(Iterator[object]):- def __init__(self, execution: Execution, hidden_params: object = None) -> None:- self._stream: Final = lifecycle.SyncStream(execution, hidden_params)- self._hidden_params: dict[str, object] = dict(_headers(hidden_params)) # mutable-ok: header writers mutate it-- def __iter__(self) -> SyncStream:- return self-- def __next__(self) -> object:- return next(self._stream)-- def close(self) -> None:- self._stream.close()---def _headers(value: object) -> Mapping[str, object]:- if value is None:- return {}- return _HEADERS.validate_python(value)diff --git a/tests/test_litellm_rust/chat_completions/test_lifecycle.py b/tests/test_litellm_rust/chat_completions/test_lifecycle.pyindex f335d6fa509..96427f701f7 100644--- a/tests/test_litellm_rust/chat_completions/test_lifecycle.py+++ b/tests/test_litellm_rust/chat_completions/test_lifecycle.py@@ -4,7 +4,7 @@ from typing import Finalimport pytestimport litellm-from litellm.rust_bridge import _native+from litellm.rust_bridge import _native, executionfrom litellm.rust_bridge.public_call import NativeCallfrom tests.test_litellm_rust.chat_completions.data import REQUESTfrom tests.test_litellm_rust.support.callback_recorder import RecordingLogger@@ -29,7 +29,7 @@ async def test_unstarted_call_has_no_provider_or_callback_effects("callbacks": [recorder],}- pending: Final = _native.acompletion(NativeCall(args=(), kwargs=kwargs, base={}))+ pending: Final = execution.asynchronous(_native.acompletion)(NativeCall(args=(), kwargs=kwargs, base={}))assert asyncio.iscoroutine(pending)pending.close()diff --git a/tests/test_litellm_rust/ocr/test_lifecycle.py b/tests/test_litellm_rust/ocr/test_lifecycle.pyindex c262454a678..c35f6836144 100644--- a/tests/test_litellm_rust/ocr/test_lifecycle.py+++ b/tests/test_litellm_rust/ocr/test_lifecycle.py@@ -288,9 +288,9 @@ def test_unstarted_native_coroutine_releases_input_without_reading_file(server:def create():file: Final = File()kwargs: Final = {"model": "mistral/mistral-ocr-latest", "document": {"type": "file", "file": file}}- coroutine: Final = _native.aocr(_public_request("aocr", (), kwargs))- file.owner = coroutine- coroutine.close()+ execution: Final = _native.aocr(_public_request("aocr", (), kwargs))+ file.owner = execution+ execution.close()return weakref.ref(file)reference: Final = create()diff --git a/tests/test_litellm_rust/responses/test_lifecycle.py b/tests/test_litellm_rust/responses/test_lifecycle.pyindex a8a4ce18f09..3387ce89505 100644--- a/tests/test_litellm_rust/responses/test_lifecycle.py+++ b/tests/test_litellm_rust/responses/test_lifecycle.py@@ -4,7 +4,7 @@ from typing import Finalimport pytestimport litellm-from litellm.rust_bridge import _native+from litellm.rust_bridge import _native, executionfrom litellm.rust_bridge.public_call import NativeCallfrom tests.test_litellm_rust.responses.data import REQUESTfrom tests.test_litellm_rust.support.callback_recorder import RecordingLogger@@ -38,7 +38,7 @@ async def test_unstarted_call_has_no_provider_or_callback_effects("extra_headers": None,}- pending: Final = _native.aresponses(NativeCall(args=(), kwargs=kwargs, base=base))+ pending: Final = execution.asynchronous(_native.aresponses)(NativeCall(args=(), kwargs=kwargs, base=base))assert asyncio.iscoroutine(pending)pending.close()diff --git a/tests/unit/caching/test_redis_cache.py b/tests/unit/caching/test_redis_cache.pyindex d27645d19fa..377527497cc 100644--- a/tests/unit/caching/test_redis_cache.py+++ b/tests/unit/caching/test_redis_cache.py@@ -1653,18 +1653,18 @@ def drive():return _settle()-def test_call_stack_info_skips_native_lifecycle_frames():- """The Rust execution awaits the response-cache coroutine from ``lifecycle._settle`` inside+def test_call_stack_info_skips_native_execution_frames():+ """The Rust execution awaits the response-cache coroutine from ``execution._settle`` inside``drive``; those frames forward every native suspension, so the chain names the code thatstarted the native call instead of ``_settle <- drive``."""- lifecycle_globals = {"__name__": "litellm.rust_bridge.lifecycle", "_native_probe": _native_probe}- native_settle = types.FunctionType(_settle.__code__, lifecycle_globals, "_settle")- native_drive = types.FunctionType(drive.__code__, {**lifecycle_globals, "_settle": native_settle}, "drive")+ execution_globals = {"__name__": "litellm.rust_bridge.execution", "_native_probe": _native_probe}+ native_settle = types.FunctionType(_settle.__code__, execution_globals, "_settle")+ native_drive = types.FunctionType(drive.__code__, {**execution_globals, "_settle": native_settle}, "drive")def anthropic_messages():return native_drive()- assert anthropic_messages() == "anthropic_messages <- test_call_stack_info_skips_native_lifecycle_frames"+ assert anthropic_messages() == "anthropic_messages <- test_call_stack_info_skips_native_execution_frames"class _FormatCountingStr(str):diff --git a/tests/unit/rust_bridge/test_bindings.py b/tests/unit/rust_bridge/test_bindings.pyindex 044ed92bad7..39a157220dc 100644--- a/tests/unit/rust_bridge/test_bindings.py+++ b/tests/unit/rust_bridge/test_bindings.py@@ -1,13 +1,18 @@+import asyncio+from collections.abc import Coroutine+from dataclasses import dataclassfrom types import SimpleNamespace-from typing import Final+from typing import Final, cast # noqa: TID251 # narrows the async binding's untyped coroutineimport pytestfrom litellm.rust_bridge import bindingsfrom litellm.rust_bridge.chat_completions import entrypoints as chat_completionsfrom litellm.rust_bridge.embeddings import entrypoints as embeddings+from litellm.rust_bridge.execution import Complete, Stepfrom litellm.rust_bridge.messages import entrypoints as messagesfrom litellm.rust_bridge.ocr import entrypoints as ocr+from litellm.rust_bridge.public_call import NativeCallfrom litellm.rust_bridge.responses import entrypoints as responsesfrom litellm.rust_bridge.transcription import native as transcription@@ -41,36 +46,100 @@ def test_binding_validates_native_attribute(assert binding.load() == expected-ROUTE_BINDINGS: Final = (- ("completion", chat_completions.NATIVE_COMPLETION),- ("acompletion", chat_completions.NATIVE_ACOMPLETION),- ("embedding", embeddings.NATIVE_EMBEDDING),- ("aembedding", embeddings.NATIVE_AEMBEDDING),- ("messages", messages.NATIVE_MESSAGES),- ("amessages", messages.NATIVE_AMESSAGES),- ("responses", responses.NATIVE_RESPONSES),- ("aresponses", responses.NATIVE_ARESPONSES),- ("ocr", ocr.NATIVE_OCR),- ("aocr", ocr.NATIVE_AOCR),+EXECUTION_BINDINGS: Final = (+ ("completion", chat_completions.NATIVE_COMPLETION, False),+ ("acompletion", chat_completions.NATIVE_ACOMPLETION, True),+ ("embedding", embeddings.NATIVE_EMBEDDING, False),+ ("aembedding", embeddings.NATIVE_AEMBEDDING, True),+ ("messages", messages.NATIVE_MESSAGES, False),+ ("amessages", messages.NATIVE_AMESSAGES, True),+ ("responses", responses.NATIVE_RESPONSES, False),+ ("aresponses", responses.NATIVE_ARESPONSES, True),+ ("ocr", ocr.NATIVE_OCR, False),+ ("aocr", ocr.NATIVE_AOCR, True),+)++TRANSCRIPTION_BINDINGS: Final = (("transcription", transcription.NATIVE_TRANSCRIPTION),("atranscription", transcription.NATIVE_ATRANSCRIPTION),)+ROUTE_BINDINGS: Final = tuple((attribute, binding) for attribute, binding, _ in EXECUTION_BINDINGS) + (+ TRANSCRIPTION_BINDINGS+)+@pytest.mark.parametrize(("attribute", "route_binding"), ROUTE_BINDINGS, ids=[attribute for attribute, _ in ROUTE_BINDINGS])-def test_route_bindings_only_accept_callable_native_attributes(+def test_route_bindings_reject_non_callable_native_attributes(monkeypatch: pytest.MonkeyPatch, attribute: str, route_binding: bindings.NativeBinding[object]) -> None:- def native_route() -> None:- pass-monkeypatch.setattr(bindings, "get_native_bridge", lambda: SimpleNamespace(**{attribute: "not callable"}))route_binding.reset()assert route_binding.load() is None+ route_binding.reset()+++ ("attribute", "route_binding"), TRANSCRIPTION_BINDINGS, ids=[attribute for attribute, _ in TRANSCRIPTION_BINDINGS]+)+def test_transcription_bindings_expose_the_native_callable_itself(+ monkeypatch: pytest.MonkeyPatch, attribute: str, route_binding: bindings.NativeBinding[object]+) -> None:+ def native_route() -> None:+ passmonkeypatch.setattr(bindings, "get_native_bridge", lambda: SimpleNamespace(**{attribute: native_route}))route_binding.reset()assert route_binding.load() is native_routeroute_binding.reset()+++@dataclass(frozen=True, slots=True)+class _EchoingExecution:+ """Completes on its first resume with the value it was resumed with."""++ def send(self, value: object) -> Step:+ return Complete(("completed with", value))++ def throw(self, error: BaseException) -> Step:+ raise error++ def close(self) -> None:+ pass+++ ("attribute", "route_binding", "asynchronous"),+ EXECUTION_BINDINGS,+ ids=[attribute for attribute, _, _ in EXECUTION_BINDINGS],+)+def test_execution_bindings_start_the_native_execution_and_return_its_result(+ monkeypatch: pytest.MonkeyPatch,+ attribute: str,+ route_binding: bindings.NativeBinding[object],+ asynchronous: bool,+) -> None:+ call: Final = NativeCall(args=(), kwargs={}, base={})+ received: list[NativeCall] = []++ def native_route(incoming: NativeCall) -> _EchoingExecution:+ received.append(incoming)+ return _EchoingExecution()++ monkeypatch.setattr(bindings, "get_native_bridge", lambda: SimpleNamespace(**{attribute: native_route}))+ route_binding.reset()+ bound: Final = route_binding.load()+ assert callable(bound)++ outcome: Final = bound(call)+ result: Final = (+ asyncio.run(cast("Coroutine[None, None, object]", outcome)) # cast-ok: async bindings return a coroutine+ if asynchronous+ else outcome+ )+ route_binding.reset()++ assert received == [call]+ assert result == ("completed with", None)diff --git a/tests/unit/rust_bridge/test_execution.py b/tests/unit/rust_bridge/test_execution.pynew file mode 100644index 00000000000..5746bf510e2--- /dev/null+++ b/tests/unit/rust_bridge/test_execution.py@@ -0,0 +1,192 @@+from __future__ import annotations++import asyncio+from collections.abc import Sequence+from typing import Final++import pytest++from litellm.rust_bridge.execution import (+ AsyncStream,+ Await,+ Complete,+ Execution,+ Step,+ StreamChunk,+ StreamClosed,+ StreamOpen,+ SyncStream,+ drive,+ run,+)+++class ScriptedExecution:+ """Plays scripted steps and records how it was resumed and whether it was closed."""++ def __init__(self, steps: Sequence[Step | BaseException]) -> None:+ self._steps: Final = list(steps)+ self.resumed: list[tuple[str, object]] = []+ self.closed = False++ def send(self, value: object) -> Step:+ self.resumed.append(("value", value))+ return self._next()++ def throw(self, error: BaseException) -> Step:+ self.resumed.append(("error", type(error)))+ return self._next()++ def _next(self) -> Step:+ step: Final = self._steps.pop(0)+ if isinstance(step, BaseException):+ raise step+ return step++ def close(self) -> None:+ self.closed = True+++async def ready(value: object) -> object:+ return value+++async def failing() -> object:+ raise ValueError("boom")+++async def exiting() -> object:+ raise GeneratorExit+++def test_drive_resumes_each_await_with_its_result_or_error_and_returns_the_completed_value() -> None:+ execution: Final = ScriptedExecution([Await(ready(1)), Await(failing()), Complete("done")])++ assert asyncio.run(drive(execution, AsyncStream)) == "done"++ assert execution.resumed == [("value", None), ("value", 1), ("error", ValueError)]+ assert execution.closed++[email protected]("factory_fails", (False, True))+def test_stream_handoff_preserves_head_identity_and_closes_on_construction_failure(factory_fails: bool) -> None:+ head: Final = object()+ stream: Final = object()+ execution: Final = ScriptedExecution([StreamOpen(head)])+ failure: Final = ValueError("stream construction failed")++ def construct(owner: Execution, received: object) -> object:+ assert owner is execution+ assert received is head+ if factory_fails:+ raise failure+ return stream++ if factory_fails:+ with pytest.raises(ValueError, match="stream construction failed") as caught:+ asyncio.run(drive(execution, construct))+ assert caught.value is failure+ assert execution.closed+ else:+ assert asyncio.run(drive(execution, construct)) is stream+ assert not execution.closed+ execution.close()+++def test_drive_rejects_a_chunk_before_the_stream_opens_and_closes_the_execution() -> None:+ execution: Final = ScriptedExecution([StreamChunk("chunk")])++ with pytest.raises(RuntimeError, match="chunk before opening a stream"):+ asyncio.run(drive(execution, AsyncStream))++ assert execution.closed++[email protected]("asynchronous", (False, True))+def test_stream_read_rejects_a_second_open_and_closes_the_execution(asynchronous: bool) -> None:+ execution: Final = ScriptedExecution([StreamChunk("first"), StreamOpen("head")])++ async def read() -> tuple[object, ...]:+ stream: Final = AsyncStream(execution, {})+ return (await anext(stream), await anext(stream))++ def read_sync() -> tuple[object, ...]:+ stream: Final = SyncStream(execution, {})+ return (next(stream), next(stream))++ with pytest.raises(RuntimeError, match="opened a stream twice"):+ asyncio.run(read()) if asynchronous else read_sync()++ assert execution.closed+++def test_drive_propagates_generator_exit_without_resuming_the_execution() -> None:+ execution: Final = ScriptedExecution([Await(exiting())])++ with pytest.raises(GeneratorExit):+ asyncio.run(drive(execution, AsyncStream))++ assert execution.resumed == [("value", None)]+ assert execution.closed+++def test_run_rejects_a_sync_call_that_suspends_and_closes_the_execution() -> None:+ pending: Final = ready(1)+ execution: Final = ScriptedExecution([Await(pending)])++ with pytest.raises(RuntimeError, match="sync call suspended"):+ run(execution, SyncStream)++ pending.close()+ assert execution.closed++[email protected]("asynchronous", (False, True))+def test_closing_a_stream_tells_the_execution_once_and_closes_it(asynchronous: bool) -> None:+ execution: Final = ScriptedExecution([StreamChunk("first"), Complete(None)])++ async def read_then_close() -> object:+ stream: Final = AsyncStream(execution, {})+ first: Final = await anext(stream)+ await stream.aclose()+ await stream.aclose()+ return first++ def read_then_close_sync() -> object:+ stream: Final = SyncStream(execution, {})+ first: Final = next(stream)+ stream.close()+ stream.close()+ return first++ assert (asyncio.run(read_then_close()) if asynchronous else read_then_close_sync()) == "first"++ assert execution.resumed == [("value", None), ("error", StreamClosed)]+ assert execution.closed++[email protected]("asynchronous", (False, True))+def test_stream_read_failure_closes_the_execution_and_ends_the_stream(asynchronous: bool) -> None:+ failure: Final = ValueError("read failed")+ execution: Final = ScriptedExecution([failure])++ async def read_twice() -> None:+ stream: Final = AsyncStream(execution, {})+ with pytest.raises(ValueError, match="read failed") as caught:+ await anext(stream)+ assert caught.value is failure+ with pytest.raises(StopAsyncIteration):+ await anext(stream)++ def read_twice_sync() -> None:+ stream: Final = SyncStream(execution, {})+ with pytest.raises(ValueError, match="read failed") as caught:+ next(stream)+ assert caught.value is failure+ with pytest.raises(StopIteration):+ next(stream)++ asyncio.run(read_twice()) if asynchronous else read_twice_sync()++ assert execution.resumed == [("value", None)]+ assert execution.closeddiff --git a/tests/unit/rust_bridge/test_lifecycle.py b/tests/unit/rust_bridge/test_lifecycle.pydeleted file mode 100644index 41f71c3332f..00000000000--- a/tests/unit/rust_bridge/test_lifecycle.py+++ /dev/null@@ -1,108 +0,0 @@-from __future__ import annotations--import asyncio-from collections.abc import Sequence-from typing import Final--import pytest--from litellm.rust_bridge.lifecycle import (- Await,- Complete,- Execution,- Step,- Stream,- StreamChunk,- StreamOpen,- SyncStream,- drive,-)---class ScriptedExecution:- """Plays scripted steps and records how it was resumed and whether it was closed."""-- def __init__(self, steps: Sequence[Step]) -> None:- self._steps: Final = list(steps)- self.resumed: list[tuple[str, object]] = []- self.closed = False-- def send(self, value: object) -> Step:- self.resumed.append(("value", value))- return self._steps.pop(0)-- def throw(self, error: BaseException) -> Step:- self.resumed.append(("error", type(error)))- return self._steps.pop(0)-- def close(self) -> None:- self.closed = True---async def ready(value: object) -> object:- return value---async def failing() -> object:- raise ValueError("boom")---def test_drive_resumes_each_await_with_its_result_or_error_and_returns_the_completed_value() -> None:- execution: Final = ScriptedExecution([Await(ready(1)), Await(failing()), Complete("done")])-- assert asyncio.run(drive(execution, Stream)) == "done"-- assert execution.resumed == [("value", None), ("value", 1), ("error", ValueError)]- assert execution.closed--[email protected]("factory_fails", (False, True))-def test_stream_handoff_preserves_head_identity_and_closes_on_construction_failure(factory_fails: bool) -> None:- head: Final = object()- stream: Final = object()- execution: Final = ScriptedExecution([StreamOpen(head)])- failure: Final = ValueError("stream construction failed")-- def construct(owner: Execution, received: object) -> object:- assert owner is execution- assert received is head- if factory_fails:- raise failure- return stream-- if factory_fails:- with pytest.raises(ValueError, match="stream construction failed") as caught:- asyncio.run(drive(execution, construct))- assert caught.value is failure- assert execution.closed- else:- assert asyncio.run(drive(execution, construct)) is stream- assert not execution.closed- execution.close()---def test_drive_rejects_a_chunk_before_the_stream_opens_and_closes_the_execution() -> None:- execution: Final = ScriptedExecution([StreamChunk("chunk")])-- with pytest.raises(RuntimeError, match="chunk before opening a stream"):- asyncio.run(drive(execution, Stream))-- assert execution.closed--[email protected]("asynchronous", (False, True))-def test_stream_read_rejects_a_second_open_and_closes_the_execution(asynchronous: bool) -> None:- execution: Final = ScriptedExecution([StreamChunk("first"), StreamOpen("head")])-- async def read() -> tuple[object, ...]:- stream: Final = Stream(execution)- return (await anext(stream), await anext(stream))-- def read_sync() -> tuple[object, ...]:- stream: Final = SyncStream(execution)- return (next(stream), next(stream))-- with pytest.raises(RuntimeError, match="opened a stream twice"):- asyncio.run(read()) if asynchronous else read_sync()-- assert execution.closeddiff --git a/tests/unit/rust_bridge/test_runtime.py b/tests/unit/rust_bridge/test_runtime.pyindex 86cc9eda5cc..95fa3e2cc7b 100644--- a/tests/unit/rust_bridge/test_runtime.py+++ b/tests/unit/rust_bridge/test_runtime.py@@ -12,8 +12,7 @@ from litellm.router_utils.add_retry_fallback_headers import get_hidden_params_difrom litellm.rust_bridge import bindings, configuration, runtimefrom litellm.rust_bridge.catalog import Route, RouteContext, RouteRulefrom litellm.rust_bridge.configuration import Rollout-from litellm.rust_bridge.lifecycle import Complete, StreamChunk-from litellm.rust_bridge.streams import Stream, SyncStream+from litellm.rust_bridge.execution import AsyncStream, Complete, StreamChunk, SyncStreamclass RustBridgeDeclined(Exception):@@ -296,7 +295,7 @@ async def test_native_stream_marker_reaches_caller_without_wrapping_or_consuming) -> None:chunks: Final = (b"event: message_start\n\n", b"event: message_stop\n\n")execution: Final = ScriptedStreamExecution(chunks)- stream: Final[Stream | SyncStream] = Stream(execution) if asynchronous else SyncStream(execution)+ stream: Final[AsyncStream | SyncStream] = AsyncStream(execution, {}) if asynchronous else SyncStream(execution, {})bound: Final[bindings.NativeBinding[Callable[[], object]]] = bindings.NativeBinding("messages", validate=lambda _: None)@@ -321,7 +320,7 @@ async def test_native_stream_marker_reaches_caller_without_wrapping_or_consumingassert result is streamassert get_hidden_params_dict(result) == {"additional_headers": {"x-litellm-rust": "true"}}assert not execution.closed- delivered: Final = tuple([chunk async for chunk in result]) if isinstance(result, Stream) else tuple(result)+ delivered: Final = tuple([chunk async for chunk in result]) if isinstance(result, AsyncStream) else tuple(result)assert delivered == chunksassert execution.closed