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]

test(ocr): trace callback lifecycle parity (#40063)

yujonglee8da735410c79
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/hooks.rs b/litellm-rust/crates/ai-gateway/src/ocr/hooks.rs
index 446b323db3a..ed41f1ff9e7 100644
--- a/litellm-rust/crates/ai-gateway/src/ocr/hooks.rs
+++ b/litellm-rust/crates/ai-gateway/src/ocr/hooks.rs
@@ -265,6 +265,12 @@ impl CallLifecycleHooks<PreparedOcrRequest, PreparedOcrRequest, Value> for OcrLi
Box::pin(async move { Ok(request) })
}
+ #[tracing::instrument(
+ name = "success_callback",
+ target = "litellm::function_trace",
+ level = "trace",
+ skip_all
+ )]
fn async_log_success_event<'a>(
&'a self,
context: &'a CallLifecycleContext,
@@ -288,6 +294,12 @@ impl CallLifecycleHooks<PreparedOcrRequest, PreparedOcrRequest, Value> for OcrLi
})
}
+ #[tracing::instrument(
+ name = "failure_callback",
+ target = "litellm::function_trace",
+ level = "trace",
+ skip_all
+ )]
fn async_log_failure_event<'a>(
&'a self,
context: &'a CallLifecycleContext,
diff --git a/litellm-rust/crates/ai-gateway/tests/ocr_lifecycle.rs b/litellm-rust/crates/ai-gateway/tests/ocr_lifecycle.rs
index c3a89f4394d..60e90ed2a7c 100644
--- a/litellm-rust/crates/ai-gateway/tests/ocr_lifecycle.rs
+++ b/litellm-rust/crates/ai-gateway/tests/ocr_lifecycle.rs
@@ -11,9 +11,13 @@ use litellm_ai_gateway::integrations::custom_logger::{
use litellm_ai_gateway::integrations::types::RequestMetadata;
use litellm_ai_gateway::ocr::{OcrRequest, ocr};
use litellm_core::error::Error;
+#[cfg(feature = "trace-parity")]
+use litellm_core::observability::FunctionTrace;
use serde_json::{Map, Value, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
+#[cfg(feature = "trace-parity")]
+use tracing::instrument::WithSubscriber;
async fn read_http_headers(socket: &mut TcpStream) -> String {
let mut request = Vec::new();
@@ -320,14 +324,17 @@ async fn ocr_lifecycle_runs_pre_during_and_success_hooks() {
GuardrailEventHook::PreCall,
GuardrailEventHook::DuringCall,
]));
- let response = ocr(OcrRequest {
+ #[cfg(feature = "trace-parity")]
+ let trace = FunctionTrace::default();
+ let api_base = format!("http://{addr}");
+ let call = ocr(OcrRequest {
model: "mistral-ocr-latest",
document: json!({
"type": "document_url",
"document_url": "https://example.com/doc.pdf"
}),
api_key: Some("sk-test"),
- api_base: Some(&format!("http://{addr}")),
+ api_base: Some(&api_base),
custom_llm_provider: Some("mistral"),
extra_headers: None,
optional_params: Map::new(),
@@ -339,9 +346,10 @@ async fn ocr_lifecycle_runs_pre_during_and_success_hooks() {
..Default::default()
},
litellm_call_id: Some("ocr-call-1"),
- })
- .await
- .expect("ocr request succeeds");
+ });
+ #[cfg(feature = "trace-parity")]
+ let call = call.with_subscriber(trace.dispatcher());
+ let response = call.await.expect("ocr request succeeds");
assert_eq!(response["pages"][0]["markdown"], "ok");
assert_eq!(
@@ -359,6 +367,16 @@ async fn ocr_lifecycle_runs_pre_during_and_success_hooks() {
error_kind: None,
}]
);
+ #[cfg(feature = "trace-parity")]
+ assert_eq!(
+ trace
+ .events()
+ .iter()
+ .filter(|event| event.function.ends_with("_callback"))
+ .map(|event| event.function)
+ .collect::<Vec<_>>(),
+ vec!["success_callback"]
+ );
let request = server.await.expect("server task completes");
assert!(request.contains(r#""guarded_pre":true"#), "{request}");
@@ -388,14 +406,17 @@ async fn ocr_lifecycle_runs_failure_hook_on_provider_error() {
});
let logger = Arc::new(RecordingOcrLogger::default());
- let err = ocr(OcrRequest {
+ #[cfg(feature = "trace-parity")]
+ let trace = FunctionTrace::default();
+ let api_base = format!("http://{addr}");
+ let call = ocr(OcrRequest {
model: "mistral-ocr-latest",
document: json!({
"type": "document_url",
"document_url": "https://example.com/doc.pdf"
}),
api_key: Some("sk-test"),
- api_base: Some(&format!("http://{addr}")),
+ api_base: Some(&api_base),
custom_llm_provider: Some("mistral"),
extra_headers: None,
optional_params: Map::new(),
@@ -404,9 +425,10 @@ async fn ocr_lifecycle_runs_failure_hook_on_provider_error() {
guardrails: Vec::new(),
request_metadata: RequestMetadata::default(),
litellm_call_id: Some("ocr-call-2"),
- })
- .await
- .expect_err("provider error propagates");
+ });
+ #[cfg(feature = "trace-parity")]
+ let call = call.with_subscriber(trace.dispatcher());
+ let err = call.await.expect_err("provider error propagates");
assert!(matches!(err, Error::Http { status: 500, .. }));
server.await.expect("server task completes");
@@ -421,6 +443,16 @@ async fn ocr_lifecycle_runs_failure_hook_on_provider_error() {
error_kind: Some("HttpError".to_string()),
}]
);
+ #[cfg(feature = "trace-parity")]
+ assert_eq!(
+ trace
+ .events()
+ .iter()
+ .filter(|event| event.function.ends_with("_callback"))
+ .map(|event| event.function)
+ .collect::<Vec<_>>(),
+ vec!["failure_callback"]
+ );
}
#[tokio::test]
diff --git a/litellm-rust/crates/python-bridge/src/function_trace.rs b/litellm-rust/crates/python-bridge/src/function_trace.rs
index ea7d9f4993e..bc3c962f7a3 100644
--- a/litellm-rust/crates/python-bridge/src/function_trace.rs
+++ b/litellm-rust/crates/python-bridge/src/function_trace.rs
@@ -1,3 +1,4 @@
+use std::fmt::Display;
use std::future::Future;
use litellm_core::observability::{FunctionTrace, FunctionTraceEvent};
@@ -6,17 +7,32 @@ use tracing::instrument::WithSubscriber;
#[derive(Serialize)]
pub(crate) struct TracedResponse<T> {
- response: T,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ response: Option<T>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ error: Option<String>,
trace: Vec<FunctionTraceEvent>,
}
pub(crate) async fn capture<T, E>(
future: impl Future<Output = Result<T, E>>,
-) -> Result<TracedResponse<T>, E> {
+) -> Result<TracedResponse<T>, E>
+where
+ E: Display,
+{
let trace = FunctionTrace::default();
- let response = future.with_subscriber(trace.dispatcher()).await?;
- Ok(TracedResponse {
- response,
- trace: trace.events(),
+ let result = future.with_subscriber(trace.dispatcher()).await;
+ let events = trace.events();
+ Ok(match result {
+ Ok(response) => TracedResponse {
+ response: Some(response),
+ error: None,
+ trace: events,
+ },
+ Err(error) => TracedResponse {
+ response: None,
+ error: Some(error.to_string()),
+ trace: events,
+ },
})
}
diff --git a/litellm-rust/crates/python-bridge/src/routes/definition.rs b/litellm-rust/crates/python-bridge/src/routes/definition.rs
index 3285da14d5f..bc51647cbad 100644
--- a/litellm-rust/crates/python-bridge/src/routes/definition.rs
+++ b/litellm-rust/crates/python-bridge/src/routes/definition.rs
@@ -486,10 +486,11 @@ asyncio.run(exercise())
let code = CString::new(
r#"
result = routes.echo("traced")
-assert result == {
- "response": "traced",
- "trace": [{"function": "execute_echo", "depth": 0}],
-}
+assert result["response"] == "traced", result
+assert [event["function"] for event in result["trace"]] == ["execute_echo"], result
+failure = routes.echo("error")
+assert failure["error"] == "invalid request: synthetic error", failure
+assert [event["function"] for event in failure["trace"]] == ["execute_echo"], failure
"#,
)
.expect("Python source should not contain null bytes");
diff --git a/tests/rust-python-harness/shared/tracing/native.py b/tests/rust-python-harness/shared/tracing/native.py
index 4f988f65294..688995cbc4b 100644
--- a/tests/rust-python-harness/shared/tracing/native.py
+++ b/tests/rust-python-harness/shared/tracing/native.py
@@ -19,7 +19,8 @@ class _TraceEventPayload(BaseModel):
class TraceResponsePayload(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
- response: object
+ response: object = None
+ error: str | None = None
trace: tuple[_TraceEventPayload, ...] | list[_TraceEventPayload]
diff --git a/tests/rust-python-harness/strategies/trace_parity/models.py b/tests/rust-python-harness/strategies/trace_parity/models.py
index da560f99730..04659b25382 100644
--- a/tests/rust-python-harness/strategies/trace_parity/models.py
+++ b/tests/rust-python-harness/strategies/trace_parity/models.py
@@ -16,6 +16,7 @@ TraceFailureSource = Literal["python", "rust", "harness"]
class RouteFixture:
kwargs: dict[str, object]
provider_responses: tuple[RecordedHttpResponse, ...]
+ expected_failure: bool = False
@dataclass(frozen=True, slots=True)
diff --git a/tests/rust-python-harness/strategies/trace_parity/sdk/execution.py b/tests/rust-python-harness/strategies/trace_parity/sdk/execution.py
index f8d7c55d4e2..eb6c9233565 100644
--- a/tests/rust-python-harness/strategies/trace_parity/sdk/execution.py
+++ b/tests/rust-python-harness/strategies/trace_parity/sdk/execution.py
@@ -2,15 +2,16 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable
+from dataclasses import dataclass
from pathlib import Path
from typing import Final, Protocol, cast
from ....shared.parity.replay import replay_server
from ....shared.reporting.models import Surface
-from ....shared.tracing.native import native_trace_events
+from ....shared.tracing.native import TraceResponsePayload, native_trace_events
from ....shared.tracing.profiler import FunctionTraceEvent, profile_python
from ....shared.tracing.steps import Engine, pipeline_projection
-from ..models import RouteSpec, TraceExecutionFailure, TraceMode, TraceScenario
+from ..models import RouteFixture, RouteSpec, TraceExecutionFailure, TraceMode, TraceScenario
from ..reporting import TraceComparisonArtifact
@@ -18,9 +19,22 @@ class SdkCall(Protocol):
def __call__(self, **kwargs: object) -> object: ...
+@dataclass(frozen=True, slots=True)
+class _CollectedTrace:
+ events: tuple[FunctionTraceEvent, ...]
+ error: str | None = None
+
+
def _invoke(function: SdkCall, kwargs: dict[str, object], *, asynchronous: bool) -> object:
async def invoke_async() -> object:
- return await cast(Awaitable[object], function(**kwargs))
+ try:
+ return await cast(Awaitable[object], function(**kwargs))
+ finally:
+ await asyncio.sleep(0)
+ from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
+
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10)
+ await GLOBAL_LOGGING_WORKER.stop()
if asynchronous:
return asyncio.run(invoke_async())
@@ -48,16 +62,30 @@ def _entrypoint(spec: RouteSpec, engine: Engine, *, asynchronous: bool) -> SdkCa
return cast(SdkCall, getattr(owner, spec.python_entrypoints[int(asynchronous)]))
+def _python_invocation_error(function: SdkCall, kwargs: dict[str, object], *, asynchronous: bool) -> str | None:
+ try:
+ _invoke(function, kwargs, asynchronous=asynchronous)
+ except Exception as error:
+ return f"{type(error).__name__}: {error}"
+ return None
+
+
def _collect(
- function: SdkCall, kwargs: dict[str, object], engine: Engine, *, asynchronous: bool
-) -> tuple[FunctionTraceEvent, ...]:
+ function: SdkCall,
+ fixture: RouteFixture,
+ engine: Engine,
+ *,
+ asynchronous: bool,
+) -> _CollectedTrace:
+ kwargs: Final = fixture.kwargs
if engine == "rust":
- return native_trace_events(_invoke(function, kwargs, asynchronous=asynchronous))
+ payload: Final = TraceResponsePayload.model_validate(_invoke(function, kwargs, asynchronous=asynchronous))
+ return _CollectedTrace(native_trace_events(payload), payload.error)
import litellm
with profile_python(Path(litellm.__file__).parent, threads=True) as profiler:
- _invoke(function, kwargs, asynchronous=asynchronous)
- return tuple(profiler.events)
+ error: Final = _python_invocation_error(function, kwargs, asynchronous=asynchronous)
+ return _CollectedTrace(tuple(profiler.events), error)
def collect_trace(
@@ -68,22 +96,30 @@ def collect_trace(
return function
try:
with replay_server() as provider:
- fixture: Final = spec.fixture(engine, provider.url)
- for response in fixture.provider_responses:
+ base_fixture: Final = spec.fixture(engine, provider.url)
+ for response in base_fixture.provider_responses:
provider.enqueue_response(response)
- kwargs: Final = {
- **fixture.kwargs,
- "api_key": "test-key",
- "api_base": provider.url,
- **({"timeout_seconds": 5} if engine == "rust" else {"timeout": 5}),
- }
- events: Final = _collect(function, kwargs, engine, asynchronous=asynchronous)
+ fixture: Final = RouteFixture(
+ kwargs={
+ **base_fixture.kwargs,
+ "api_key": "test-key",
+ "api_base": provider.url,
+ **({"timeout_seconds": 5} if engine == "rust" else {"timeout": 5}),
+ },
+ provider_responses=base_fixture.provider_responses,
+ expected_failure=base_fixture.expected_failure,
+ )
+ collected: Final = _collect(function, fixture, engine, asynchronous=asynchronous)
provider.take_requests(len(fixture.provider_responses))
except Exception as error:
return TraceExecutionFailure(engine, f"{type(error).__name__}: {error}")
- if not events:
+ if fixture.expected_failure and collected.error is None:
+ return TraceExecutionFailure(engine, "call succeeded but the scenario expects failure")
+ if not fixture.expected_failure and collected.error is not None:
+ return TraceExecutionFailure(engine, collected.error)
+ if not collected.events:
return TraceExecutionFailure(engine, "trace is empty")
- return events
+ return collected.events
def _failure_message(result: tuple[FunctionTraceEvent, ...] | TraceExecutionFailure) -> str | None:
diff --git a/tests/rust-python-harness/strategies/trace_parity/sdk/ocr/case.py b/tests/rust-python-harness/strategies/trace_parity/sdk/ocr/case.py
index fe214f45339..2a4a1b3a152 100644
--- a/tests/rust-python-harness/strategies/trace_parity/sdk/ocr/case.py
+++ b/tests/rust-python-harness/strategies/trace_parity/sdk/ocr/case.py
@@ -19,6 +19,20 @@ COMMON_MAPPINGS: Final = (
mapping(rust_span="http_request", python_frame=r"AsyncHTTPHandler\.post$|HTTPHandler\.post$"),
)
+SUCCESS_CALLBACK_SYNC_MAPPING: Final = mapping(
+ rust_span="success_callback",
+ python_frame=r"BoundedLoggingThreadPoolExecutor\.submit$",
+)
+SUCCESS_CALLBACK_ASYNC_MAPPING: Final = mapping(
+ rust_span="success_callback",
+ python_frame=r"Logging\.async_success_handler$",
+)
+FAILURE_CALLBACK_MAPPING: Final = mapping(
+ rust_span="failure_callback",
+ python_frame=r"Logging\.(?:async_)?failure_handler$",
+)
+IGNORED_SUCCESS_CALLBACK_MAPPING: Final = mapping(rust_span="success_callback")
+
SYNC_MAPPINGS: Final = (
*COMMON_MAPPINGS,
mapping(rust_span="execute_ocr_provider_call", python_frame=r"BaseLLMHTTPHandler\.ocr$"),
@@ -39,6 +53,21 @@ ASYNC_MAPPINGS: Final = (
),
)
+CALLBACK_SUCCESS_SYNC_MAPPINGS: Final = (*SYNC_MAPPINGS, SUCCESS_CALLBACK_SYNC_MAPPING)
+CALLBACK_SUCCESS_ASYNC_MAPPINGS: Final = (*ASYNC_MAPPINGS, SUCCESS_CALLBACK_ASYNC_MAPPING)
+CALLBACK_FAILURE_SYNC_MAPPINGS: Final = (
+ *COMMON_MAPPINGS,
+ mapping(rust_span="execute_ocr_provider_call", python_frame=r"BaseLLMHTTPHandler\.ocr$"),
+ FAILURE_CALLBACK_MAPPING,
+)
+CALLBACK_FAILURE_ASYNC_MAPPINGS: Final = (
+ *COMMON_MAPPINGS,
+ mapping(span="python_ocr_wrapper", python_frame=r"BaseLLMHTTPHandler\.ocr$"),
+ mapping(rust_span="execute_ocr_provider_call", python_frame=r"BaseLLMHTTPHandler\.async_ocr$"),
+ FAILURE_CALLBACK_MAPPING,
+)
+
+
AZURE_COMMON_MAPPINGS: Final = (
*COMMON_MAPPINGS[:7],
mapping(
@@ -99,6 +128,34 @@ def _mistral_fixture(engine: Engine, _base_url: str) -> RouteFixture:
return _fixture(engine, "mistral/mistral-ocr-latest")
+def _callback_fixture(engine: Engine, *, failure: bool) -> RouteFixture:
+ fixture: Final = _fixture(engine, "mistral/mistral-ocr-latest")
+ provider_responses: Final = (
+ (
+ RecordedHttpResponse.from_bytes(
+ 400,
+ (HttpHeader(name="content-type", value="application/json"),),
+ b'{"message":"trace callback provider failure"}',
+ ),
+ )
+ if failure
+ else fixture.provider_responses
+ )
+ return RouteFixture(
+ kwargs=fixture.kwargs,
+ provider_responses=provider_responses,
+ expected_failure=failure,
+ )
+
+
+def _mistral_callback_success_fixture(engine: Engine, _base_url: str) -> RouteFixture:
+ return _callback_fixture(engine, failure=False)
+
+
+def _mistral_callback_failure_fixture(engine: Engine, _base_url: str) -> RouteFixture:
+ return _callback_fixture(engine, failure=True)
+
+
def _azure_fixture(engine: Engine, _base_url: str) -> RouteFixture:
return _fixture(
engine,
@@ -304,36 +361,50 @@ TRACE_SUITE: Final = TraceSuite(
name="mistral",
fixture=_mistral_fixture,
mappings=COMMON_MAPPINGS,
- sync_mappings=SYNC_MAPPINGS,
- async_mappings=ASYNC_MAPPINGS,
+ sync_mappings=(*SYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
+ async_mappings=(*ASYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
+ ),
+ TraceScenario(
+ name="mistral-callback-success",
+ fixture=_mistral_callback_success_fixture,
+ mappings=COMMON_MAPPINGS,
+ sync_mappings=CALLBACK_SUCCESS_SYNC_MAPPINGS,
+ async_mappings=CALLBACK_SUCCESS_ASYNC_MAPPINGS,
+ ),
+ TraceScenario(
+ name="mistral-callback-failure",
+ fixture=_mistral_callback_failure_fixture,
+ mappings=(*COMMON_MAPPINGS, FAILURE_CALLBACK_MAPPING),
+ sync_mappings=CALLBACK_FAILURE_SYNC_MAPPINGS,
+ async_mappings=CALLBACK_FAILURE_ASYNC_MAPPINGS,
),
TraceScenario(
name="azure-ai",
fixture=_azure_fixture,
mappings=AZURE_COMMON_MAPPINGS,
- sync_mappings=AZURE_SYNC_MAPPINGS,
- async_mappings=AZURE_ASYNC_MAPPINGS,
+ sync_mappings=(*AZURE_SYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
+ async_mappings=(*AZURE_ASYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
),
TraceScenario(
name="azure-document-intelligence",
fixture=_azure_document_intelligence_fixture,
mappings=DOCUMENT_INTELLIGENCE_COMMON_MAPPINGS,
- sync_mappings=DOCUMENT_INTELLIGENCE_SYNC_MAPPINGS,
- async_mappings=DOCUMENT_INTELLIGENCE_ASYNC_MAPPINGS,
+ sync_mappings=(*DOCUMENT_INTELLIGENCE_SYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
+ async_mappings=(*DOCUMENT_INTELLIGENCE_ASYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
),
TraceScenario(
name="vertex-ai",
fixture=_vertex_fixture,
mappings=VERTEX_COMMON_MAPPINGS,
- sync_mappings=VERTEX_SYNC_MAPPINGS,
- async_mappings=VERTEX_ASYNC_MAPPINGS,
+ sync_mappings=(*VERTEX_SYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
+ async_mappings=(*VERTEX_ASYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
),
TraceScenario(
name="vertex-deepseek",
fixture=_vertex_deepseek_fixture,
mappings=DEEPSEEK_COMMON_MAPPINGS,
- sync_mappings=DEEPSEEK_SYNC_MAPPINGS,
- async_mappings=DEEPSEEK_ASYNC_MAPPINGS,
+ sync_mappings=(*DEEPSEEK_SYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
+ async_mappings=(*DEEPSEEK_ASYNC_MAPPINGS, IGNORED_SUCCESS_CALLBACK_MAPPING),
),
),
)