25 KiB
Exception mapping: plan to align the Rust path with the five-stage design
Scope: branch litellm_ocr_rust_parity_gaps. The types and the trait are generic, but only the OCR route is moved in this work. Chat, messages, responses and audio transcription are a later change (section 4.5) and nothing here depends on them. Nothing in this plan has been built or run. The target design is the five-stage chain (capture, normalize, classify, construct, finalize) where each stage has one owner and the pyo3 layer owns none of them
1. What this branch changed
fd18a6c9d70,75cbb689b8a: tests only- Failing contract tests for the OCR Rust path gaps
- A differential parity sweep in
tests/test_litellm_rust/ocr/test_parity.pywithsupport/parity.py(Outcome,Divergence,assert_parity)
9a0c45f6e3e:core/src/litellm_core_utils/secret_redaction.rs, a port of the Python redaction patterns0eb60785854: the mapping itselfcore/src/litellm_core_utils/exception_mapping_utils.rs(1021 lines, one file):ProviderException,ExceptionContext,PublicFailure,exception_type, withmap_openai_exception,map_vertex_exception,map_cohere_exceptionandmap_exception_by_statusas hand-written functions, plus 13 rstest groupspython-bridge/src/failures.rs:provider_exception(parses aRustUpstreamErrorback into aProviderException),exception_context(readslitellm.*globals and kwargs),public_exception(serde dict tolitellm.rust_bridge.failures.public_exception),map_upstream_failurepython-bridge/src/routes/ocr/host.rs:map_failuretriesmap_upstream_failurefirst, then falls back to the Pythonroute_host.map_failurelitellm/rust_bridge/failures.py: PydanticPublicFailurewithextra="forbid"and the constructorpublic_exception. The oldmap_failurethat callslitellm.exception_typeis still therelitellm/rust_bridge/dispatch.py:finalize_failure,_finalized,_afinalizedwrap the native call inrunandarun
2. Where the branch stands against each stage
| Stage | State on the branch | Gap |
|---|---|---|
| 1. Capture | ocr::Error carries Provider{status, body, headers}, Transport, validation, auth and file variants |
None in core. The bridge turns it into a PyErr too early (routes/ocr/errors.rs::to_pyerr) |
| 2. Normalize | OcrConfigKind::get_error_class(message, status, headers) exists but returns ocr::Error. The real normalization happens in the bridge: provider_exception rebuilds ProviderException from RustUpstreamError.args and a headers attribute set with setattr |
Wrong owner and a lossy round trip through a Python exception |
| 3. Classify | exception_type(&ExceptionContext, &ProviderException) in core |
Only Provider and Transport::Http errors reach it. Everything else (ValueError with a patched status_code, FileNotFoundError, OSError, RuntimeError) goes to the Python litellm.exception_type, which is Python-path-only code. RequestFormat is classified in Python through the ocr_request_format_error attribute. Provider dispatch is on strings ("mistral" | "azure_ai", "vertex_ai", "cohere") |
| 4. Construct | failures.public_exception |
Matches the design. The payload shape does not: flat response and request fields that both have Omitted, an upstream_content override applied with setattr after construction, stdout carried as a string, no provider_specific_fields |
| 5. Finalize | dispatch.finalize_failure, tested for sync and async |
Done. Only str(error) coverage is missing |
| Driver | machine_failed keeps the interrupted host PyErr apart from the native error, then calls H::native_error and map_failure(&PyErr) |
map_failure(py, &error).unwrap_or(error) at driver.rs:390 swallows a mapper failure |
Two things the design text does not say but the code shows:
- Only OCR runs on the
RouteHostdriver. Chat, messages, responses and audio transcription userun_sync/run_asyncwith*_error_to_pyerr. Step 5 of the design is therefore larger than moving a call site. See 4.5 runtime._raise_upstreamand themap_failurefunctions inchat_completions/route_host.py,messages/route_host.pyandresponses/route_host.pyare dead stand-ins- No Rust code calls those three
map_failurefunctions. Onlyroutes/ocr/host.rsimports aroute_host.map_failure catalog.RULESenables only OCR and bedrock transcription. Transcription errors go throughcore_error_to_pyerrand never raiseRustUpstreamError. OCR'sRustUpstreamErroris mapped inside the driver. The only way one reaches_raise_upstreamtoday is theunwrap_or(error)swallow in the driver
- No Rust code calls those three
- OCR invents an HTTP response for timeouts:
ocr/client.rs::transport_errorreturnsTransport::Http{status: 408, body: "OCR request timed out"}andocr/document.rs:207does the same for document downloads. The Python path has no response at all there, it maps an httpx exception. The sweep does not cover transport failures yet RequestFormatmaps tolitellm.UnsupportedParamsError, which is not in the design'sPublicFailurelist. It fits as one moreStatusclass (it subclassesBadRequestError), so no new kind is needed
3. Target shapes
Core (core-utils/src/exception_mapping_utils/)
original.rsenum OriginalException { Http{status, body, headers}, Connection{message}, Timeout{message}, Response{message}, Local{class: LocalClass, message, status: Option<u16>} }enum LocalClass { ValueError, FileNotFound, OsError }ProviderException,status_code_is_synthesizedand the status 0 sentinel are deleted
public.rsstruct PublicFailure { kind, message, model, llm_provider, litellm_debug_info, litellm_response_headers, provider_specific_fields, print_banner }enum PublicKind { Status{class: StatusClass, response: Option<ResponseArg>}, Timeout{status: Option<u16>, response: Option<ResponseArg>}, ApiConnection{request: RequestStub}, Api{status: u16, request: RequestStub}, Passthrough{class: LocalClass, message} }StatusClassis today's simple kinds minusApiConnection, plusUnsupportedParamsResponseArgstaysUpstream | Stub, withoutOmitted.Optionsays whether the constructor gets oneupstream_contentgoes away: the vertex case becomesStatus{response: Some(Upstream{status: <python status>, body, headers})}, decided in the rule, so Python never patcheserror.responseafter constructionstdout: Stringbecomesprint_banner: bool. The banner text moves tolitellm/rust_bridge/failures.py, because printing is part of stage 4 and the text today lives in Python-path-only code
mod.rs:ExceptionContext, the message prefixes (exception_provider,python_capitalize,extra_information), redaction oferror_str, the timeout marker check, and the dispatchmatch provider: Provider.ExceptionContext.custom_llm_providerbecomes core's provider enum plus the raw string for messages, so dispatch never compares stringsstatus.rs: the fallback table, today'smap_exception_by_statusrules.rs:struct Rule { when: When, kind, message: MessageTemplate, response: ResponseChoice, debug: bool }and the one interpreterfn apply(rules: &[Rule], mapping: &Mapping) -> Option<PublicFailure>, first match winsopenai.rs,vertex_ai.rs,cohere.rs: one ordered&[Rule]each- Dead branches: drop every branch that only matches a string the Python SDKs produce, for example the
BadRequestError.__init__() missing 1 required positional argument: 'param'check inmap. Each removal is aDivergencerow in the sweep if the sweep can reach it, and a line in the PR body either way
Provider config (stage 2)
OcrConfigKind::error_class(&ocr::Error) -> OriginalExceptionreplacesget_error_classProvider{..}->Httpwith headersTransport::Http->Httpwithout headersTransport::Network->Timeoutwhen the reqwest error was a timeout, elseConnection.transport::Error::Network(String)loses that bit today, so addtransport::Error::Timeout(String)and set it infrom_reqwest_before_dispatchandFrom<reqwest::Error>- Delete the invented 408 in
ocr/client.rs::transport_errorandocr/document.rs. Both returntransport::Error::Timeout.Transport::Connect(refused, DNS) ->Connection - The message text cannot match: Python embeds httpx's exception text and Rust has reqwest's. Parity is on class,
status_code, the absence of a response, and the litellm-owned prefix of the message. The httpx part of the message is one recordedDivergenceonmessagefor the transport rows only - Invalid and oversized responses (
InvalidResponse,ResponseField,EmptyContent,TooLarge,NumericRange) -> a new variantOriginalException::Response{message}. The Python path raises inside response transformation andexception_typeturns that into whatever the sweep shows (expectedAPIConnectionError). This replaces open question 1 FileReadwithNotFound->Local{FileNotFound, "File not found: <path>", None}. OtherFileRead->Local{OsError, <io message>, None}is_request()errors, auth errors and the other value-error cases fromcore_error_to_pyerr->Local{ValueError, message, Some(400)}RequestFormatneeds its own arm, because its public class isUnsupportedParamsand its message includes the rejectedreq_formatvalue. Carry the value in the error (RequestFormat{value: String}) so the message is built in core- Response errors (
TooLarge,ResponseField, ...) areRuntimeErrortoday.LocalClasshas noRuntimeError. Open question 1 below
Bridge (python-bridge) and driver (host-python)
RouteHostlosesnative_errorandmap_failure(&PyErr)and gainsfn classify(&self, py, error: <Route as Route>::Error) -> PyResult<PublicFailure>- The OCR impl builds
ExceptionContextwithfailures::exception_context, callsconfig.error_class(&error), thenexception_type
- The OCR impl builds
struct BridgeFailure(PublicFailure)withimpl From<BridgeFailure> for PyErrinpython-bridge/src/failures.rs. It is the only caller ofpublic_exception. If the Python constructor itself fails (import error, Pydantic validation), that error is what theFromimpl returnshost-pythonmust not depend onpython-bridge, so the driver cannot nameBridgeFailure. The trait method returnsPyResult<PyErr>built through theFromimpl inside the route'sclassify, or the trait gets an associatedtype Failure: Into<PyErr>. Recommendation: the associated type, because it keeps thePublicFailurevalue visible to the driver's fake route in tests
- Driver:
machine_failedcallsclassifyexactly once, only whenself.interruptedisNone.failure()loses theFailureOrigin::Call => map_failure(...).unwrap_or(error)arm. Aclassifyerror is raised with the classifier error as the exception and the native error's message attached through__context__(aRuntimeErrorholdingerror.to_string()), so nothing is swallowed - Deleted:
RustUpstreamError(class,.pyientry,bindings.native_exception_typessecond slot),provider_exception,map_upstream_failure,routes/ocr/errors.rs(to_pyerr,upstream_error,attach_status),litellm/rust_bridge/ocr/route_host.map_failure, and at the endfailures.map_failurewith itsExceptionMapperprotocol - Kept:
create_exception!forRustBridgeDeclinedonly - Not used, per the design:
import_exception!, lazyPyErrArguments,#[pyclass(extends=PyException)], a#[pyclass]mirror ofPublicFailure
Shared Python (litellm/rust_bridge/failures.py)
- The Pydantic models mirror the new
PublicKind.extra="forbid"stays _simple's eleven near-identical arms collapse into aMapping[StatusClass, type[Exception]]lookup plus one call, because everyStatusclass now takes the same keyword argumentsPassthroughbuilds the builtin (ValueError,FileNotFoundError,OSError) and setsstatus_codewhen presentpublic_exceptionprints the banner whenprint_banneris true, setslitellm_response_headersandprovider_specific_fields
4. Steps, each with its unit tests
The parity sweep must be green after every step except for recorded divergences. Every step lands with the tests listed under it. Rust tests use rstest tables and assert the whole PublicFailure value with assert_eq!, never a single field, so a mutation in any field fails a test
4.1 OriginalException and error_class in core
- Sweep first: add a transport axis to
test_parity.pybefore touching the code, so the 408 shows up as a red row. Cases: read timeout, connection refused, body that is not JSON, JSON missing required fields, body over the size limit, each for sync and async and per provider. The local server in the sweep's support code needs a "sleep past the timeout" handler, a closed port, and a large-body handler - Code: add
original.rs,transport::Error::Timeout, remove both invented 408s,OcrConfigKind::error_class.exception_typetakes&OriginalException. Keep a privateFrom<ProviderException>shim only inside this step if needed to keep the diff reviewable, and delete it before the step's commit - Tests (Rust, permanent)
error_class: one case perocr::Errorvariant group listed in section 3, per provider config where the config overrides anything. TheFileReadcases assert the exact message, including the path- A test that iterates every
ocr::Errorvariant thatis_request()and assertsLocal{ValueError, _, Some(400)}, so a new request variant cannot be forgotten transport: a timeout reqwest error becomesTimeout, a connect error before dispatch staysConnectocr/client.rs: replacerequest_timeout_has_an_http_408_statuswith a test that a timed-out request and a timed-out document download both yieldtransport::Error::Timeoutand that noHttpvariant is ever produced without a real responseexception_typeonResponse{..}: whole-value case per provider familyexception_typeonConnectionandTimeoutinputs: replaces today'ssynthesized_status_is_a_connection_error
4.2 classify on the trait, one From impl, OCR moved over
- Code: trait change in
host-python/src/adapter.rs, driver change indriver.rs,BridgeFailure, OCRclassify, deleteroutes/ocr/errors.rsand theRustUpstreamErrorre-parsing - Dead stand-ins go in this step, because fixing the
unwrap_or(error)swallow removes the last way aRustUpstreamErrorcan escape- Delete
runtime._raise_upstream, theexcept upstreamarms inattemptandaattempt, and the second slot ofbindings.native_exception_types - Delete
map_failurefromchat_completions/route_host.py,messages/route_host.pyandresponses/route_host.py, with their tests undertests/test_litellm/rust_bridge/<route>/ chat_completions_error_to_pyerrstill namesRustUpstreamError. Chat has no rule incatalog.RULES, so map those two arms toPyRuntimeErrorfor now and let 4.5 replace the functiontest_runtime.py: drop the_raise_upstreamcases, keep and extend the declined-falls-back cases
- Delete
- Tests (
host-pythondriver, existing fake route with itslog)- A native error reaches
classifyexactly once and theFailedevent carries the classified error - A host-raised error during an op skips
classifyand is emitted unchanged (self.interruptedpath) - A cancellation is returned as is, with no
classifycall and noFailedevent - A
classifythat returnsErrsurfaces that error, and the native error's text is reachable from__context__. This is the regression test forunwrap_or(error) - Failures in
beginandafter_successstay unmapped (already covered, keep)
- A native error reaches
- Tests (
python-bridge)exception_context: readssuppress_debug_infoandredact_messages_in_exceptionsfromlitellm, readsvertex_project,vertex_locationand the four metadata keys, toleratesmetadata=Noneand a non-mappingmetadata, stringifies non-string values the way Python'sstr()doesBridgeFailure -> PyErr: a valid payload yields the litellm class. A payload the Python side rejects yields the Pydantic error, not a panic and not a silent fallback
4.3 Reshape PublicFailure, the constructor, and add the golden fixtures
- Code:
public.rs, the Pydantic models, the collapsed constructor, banner text moved to Python,provider_specific_fields - Tests
- Rust: a test builds one
PublicFailureper kind (Statusonce perStatusClass,Timeoutwith and without status,ApiConnection,Api,Passthroughonce perLocalClass), serializes them and compares againsttests/test_litellm/rust_bridge/fixtures/public_failures/*.json. An env switch regenerates the files. The comparison is what runs in CI - Python, permanent, in
tests/test_litellm/rust_bridge/test_failures.py: parametrized over the fixture files. For each one assert the exact class,isinstanceof the matchingopenai.*type,status_code,message,llm_provider,model, response body and headers,litellm_response_headers,provider_specific_fields, and that the banner is written to stdout only whenprint_banneris true - Python: an unknown field and an unknown
StatusClassare both rejected. A test asserts everyStatusClassliteral has a constructor entry and a fixture, so adding a class on one side fails on the other - Delete the three
map_failuretests at the top oftest_failures.pyin step 4.4, not here
- Rust: a test builds one
4.4 Cover Local, then delete the Python fallback
- Code: classifier handles
Local.ValueErrorwith status 400 follows what the Pythonexception_typedoes with it today for OCR (the sweep is the oracle for whether that isBadRequestError,APIConnectionErroror a passthrough, per provider).FileNotFoundandOsErrorbecomePassthrough.RequestFormatbecomesStatus{UnsupportedParams}. Then deleteocr/route_host.map_failure, the Python call inhost.rsandfailures.map_failurewith itsExceptionMapperprotocol. After this step nothing underlitellm/rust_bridge/importslitellm.exception_type. Add a test intests/test_litellm/rust_bridge/that fails if any module there references it, since that is the invariant the step exists for - Tests
- Rust: one table row per
LocalClassx status x provider family, whole-value assertions - Rust:
RequestFormat{value}message equals the Python text, includingreprquoting of the value. Cover a string with a quote in it - Sweep: extend
test_parity.pywith a validation axis, written before the port so the rows decide the table above. Cases: badreq_format, empty file, missing file, unreadable file, missing document URL, invalid MIME type, invalid data URI, Cohere with a PDF, Reducto with a plain URL, invalidpages, invalid provider, missing Azure AI credentials, missing Document Intelligence credentials, missing Reducto key. Each for sync and async. Every row asserts no request reached the local server tests/test_litellm/rust_bridge/ocr/test_route_host.py: drop themap_failurecases with the function
- Rust: one table row per
4.5 Chat, messages, responses, audio transcription (later, not part of the OCR work)
- These routes are not on the driver. They also have decline semantics that OCR does not: an error before dispatch must stay
RustBridgeDeclinedsoruntime.attemptcan fall back to Python - Code
- Per route in core:
fn disposition(&Error) -> Dispositionwithenum Disposition { Declined, Failed(OriginalException) }. This moves the pre-dispatch list out ofchat_completions_error_to_pyerrinto core, where it can be tested without Python - Per route provider config:
error_class - Bridge: build
ExceptionContextat entry while attached, beforerun_sync/run_asyncdetach. Themap_errclosure becomesDeclined -> RustBridgeDeclined,Failed(original) -> BridgeFailure(exception_type(&context, &original)).into() RustUpstreamErroritself is deleted here, with its.pyientry
- Per route in core:
- Tests
- Rust core:
dispositiontable per route, one row per error variant. Assert that every variant is covered by matching exhaustively in the test helper, so a new variant fails to compile until it has a row - Rust core:
error_classper provider config - Python
test_runtime.py: a declined call still falls back, a classified litellm exception passes throughattemptuntouched (no wrapping, no prefix), sync and async - Sweep: add
tests/test_litellm_rust/chat/andmessages/parity files using the samesupport/parity.py - Proxy and Router: one smoke sweep per route, same shape as 4.7
- Rust core:
4.6 Split the classifier into rule tables
- Done last on purpose: by then the sweep and the whole-value tests pin the behavior, so the split is a pure refactor
- Code:
rules.rs,status.rs,openai.rs,vertex_ai.rs,cohere.rs. Existing test cases move next to their rule file unchanged - Tests
- One case per rule, named after the rule
- One case per pair of rules that can both match, asserting the earlier one wins (for example a 400 whose body has both a context-window marker and a content-policy marker)
- Separate test modules for
status.rs(every mapped status plus one unmapped),extra_information(each optional context field present and absent), redaction (message redacted, markers still matched on the redacted string), andprint_banneragainstsuppress_debug_info - Run
cargo mutants -p litellm-core-utils --file 'src/exception_mapping_utils/**'and hold the 90% kill rate. Survivors become table rows
4.7 Router and proxy smoke sweep
tests/test_litellm_rust/ocr/test_router_and_proxy.pyhas five hand-written tests today and they pass. Shrink it to one parametrized sweep:(upstream status, body, headers) -> (proxy HTTP status, error JSON type and code, retried or not, deployment cooled down or not), run against both backends throughsupport/parity.py- Keep one success row. Add one row each from the transport and validation axes, so the Router's retry and cooldown decisions are checked for a
Timeout, anAPIConnectionErrorand aPassthrough - Router and proxy only consume the exception, so nothing beyond this smoke sweep belongs here. A failure in it is fixed in the classifier or the constructor, never in the Router
- Can be done at any point. Doing it right after 4.1 gives the later steps a cheaper end-to-end signal
4.8 Known gaps in the exception_type port
All three are unreachable for today's OCR models, so they cannot be Divergence rows (assert_parity fails a registered divergence that does not diverge). They are recorded as a KNOWN_GAPS doc comment at the top of exception_mapping_utils/mod.rs and in the PR body. Each has a trigger that says when it stops being acceptable
- The Vertex partner URL for "claude" models in
extra_information. Trigger: a Vertex route whose models include Anthropic partner models. Thenapi_basegets the branch and a table row - A stripped model name that happens to resolve in
get_llm_provider, which changes the provider Python reports. Trigger: a route whose model names overlap the model cost map. Needs the provider resolution port, not a classifier change - Python tracebacks embedded in fallback messages (
traceback.format_exc()in theAPIConnectionErrorfallback). Rust cannot reproduce this and should not. Permanent, deliberate divergence. If a sweep row ever reaches it, register aDivergenceonmessageand compare the prefix before the traceback
5. Test ownership summary
| Contract | Owner | Location | Lifetime |
|---|---|---|---|
Error -> OriginalException |
core provider config | core/src/<route>/provider_config.rs tests |
permanent |
Error -> Declined | Failed |
core route | core/src/<route>/error.rs tests |
permanent |
(OriginalException, ExceptionContext) -> PublicFailure |
core classifier | next to each rule file | permanent |
PublicFailure JSON shape |
core + shared Python | golden fixtures, written by Rust, read by test_failures.py |
permanent |
| classify once, host errors skip, cancellation, classifier failure surfaces | host-python driver |
driver.rs tests with the fake route |
permanent |
litellm.* globals and kwargs -> ExceptionContext |
python-bridge |
failures.rs tests |
permanent |
num_retries, timeout, str(error) |
Python dispatch | test_dispatch.py |
permanent |
| Python path vs Rust path | nobody, it is an oracle | tests/test_litellm_rust/ |
deleted with the Python path |
6. Open questions
- Polling errors (
PollTimeout,PollLocation,PollOrigin,OperationStatus) areRuntimeErrortoday. They likely fitTimeoutandResponse, but the Python polling code decides. Add sweep rows for Document Intelligence polling before choosing - The mapped error's
__context__is theRustUpstreamErrortoday. After 4.2 there is no nativePyErr. If the sweep compares__context__or__cause__, record one divergence. Otherwise nothing to do ExceptionContextneeds core's provider enum. OCR has its ownOcrProvider, and chat has another. If there is no shared enum yet, 4.1 uses a smallenum ExceptionFamily { OpenAiCompatible, VertexAi, Cohere, Other }derived by each route, and the shared provider enum is a separate change