Repository navigation
fix(guardrails): accept Gemini tools in generic_guardrail_api, add opt-in forward_messages_as_sent, name the error type on fail-open - #46338
Conversation
…generic_guardrail_api, name the error type on fail-open GuardrailToolParam required a type key, so Gemini native tools (function_declarations, googleSearch) failed validation inside the hook and either returned a 500 or skipped the scan when fail_on_error was false. The type key is now optional and left out of the forwarded tool when absent, so an echoing guardrail server cannot write type: null into the provider request. structured_messages was re-validated against the chat completion message types, which silently emptied tool_result, tool_use, image and document content blocks to content: [] and dropped undeclared keys before the guardrail saw them. The request model now forwards rows as opaque mappings, which also retires the write-back shim that restored the original rows for echoed-back entries. The fail-open critical log line now carries error_type so a timeout, a refused connection and an upstream HTTP status can be told apart without the traceback.
aiohttp raises ServerDisconnectedError when a kept-alive connection is closed by the peer before a response arrives, which is what a load balancer idle timeout shorter than AIOHTTP_KEEPALIVE_TIMEOUT produces. The transport mapped it to httpx.ReadError, which the handler's connection-error retry does not cover, so the request failed instead of being resent on a fresh connection. It now maps to httpx.RemoteProtocolError, the error httpx itself raises for the same condition, so the existing retry fires.
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
This remap is global, so every AsyncHTTPHandler POST would replay after any server disconnect, including mid-request ones. Was that intended outside guardrails? |
|
#46336 stops POST resends after a disconnect, since they can double-bill. The 20s keepalive change should cover load-balancer cuts, so can you drop this remap? |
…streamed resend readable The connection-error retry closed its fresh client before a streamed body was read, so an aiohttp disconnect now billed a second upstream request and still failed. It also skipped masking on a status error from the resend, resent PATCH and DELETE as POST, dropped multipart files and ignored the handler's ssl_verify. The retry now resends the request the first attempt built, on a client with the handler's TLS settings, closes that client when a streamed body is closed, and masks a status error the same way the first attempt does.
… fail-open error_type
|
bugbot run |
[Medium impact] Guardrail API now accepts more message and tool formats. The new unit tests must meet the repository's dependency-injection and FindingsSummaryThe PR accepts Gemini tools without Two repository requirements remain unmet in the new unit tests. They replace internal attributes instead of injecting dependencies and omit required The earlier, unnumbered socket-test thread was resolved.
Reviews (7) · Last reviewed commit: "test(guardrails): pick the closed guardr..." · Reviewed by Greptile |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…onse A load balancer that closes an idle keepalive connection made the guardrail POST fail with "Server disconnected", because #46336 only resends POST on ConnectError. AsyncHTTPHandler.post now takes a keyword-only idempotent flag, defaulting to False, that gives a RemoteProtocolError the same single fresh-client resend PUT and DELETE get. Only GenericGuardrailAPI.apply_guardrail opts in, since a guardrail check is a pure verdict over the request. Every other POST keeps the #46336 rule The fail-open log line now puts error_type at the end so the pre-PR text stays contiguous for existing alert matchers test_rows_reach_the_guardrail_verbatim now reads the body off a real local guardrail server instead of mock call args
|
bugbot run |
|
@greptileai re review |
…ket tests to integration A ServerDisconnectedError raised while reading a response body now stays httpx.ReadError, as it was before this PR. Only a disconnect before any response maps to RemoteProtocolError, which is the case the resend rule is about. Stream readers that end on ReadError, like the SAP stream iterator, keep their old behavior The loopback-server disconnect, TLS and guardrail resend tests move to tests/integration/sdk/test_disconnect_resend_wire.py, since tests/unit is in-process only. Unit keeps in-process MockTransport checks for the idempotent POST resend, masking on the resend, streamed and buffered client closing, the guardrail resend, and the guardrail receiving rows verbatim
|
bugbot run |
|
@greptileai re review |
… on texts An idempotent POST now resends once on any network error after connect (ReadError, WriteError, RemoteProtocolError), so a guardrail behind a load balancer that answers a stale keepalive with a TCP reset rides it out too. That makes the aiohttp ServerDisconnectedError remap unnecessary, so it goes back to ReadError. This stops PUT and DELETE from stacking litellm's resend on top of aiohttp's own idempotent retry (4 sends instead of 2) and stops Vigil Guard from replaying its analyze POST on a disconnect Every resend now runs inside the method's own error mapping, so a timeout on the resend is a litellm.Timeout like the first attempt and a status error is masked once by the caller A guardrail server that parses rows with its own message types and echoes them back without the keys those types lack (annotations, tool_calls[].index) is read as an echo again, so its texts redaction reaches the LLM. A row only counts as an echo when no value changed and every key the chat completion types declare is kept The wire tests for the PUT/DELETE resend, its masking and its TLS settings now run on the httpx transport, where litellm's resend is the only retry, and the POST and guardrail tests cover both transports and both cut styles
|
bugbot run |
|
@greptileai re review |
…fail-open error type and idle cut resend Integration tests against an owned proxy and scripted peers. Gemini native tools reach the guardrail and Gemini as sent, the guardrail sees chat rows and an Anthropic image block as sent, an echoing guardrail leaves a /v1/messages request unchanged, the fail-open log line names ConnectError, Timeout or HTTPStatusError, and a guardrail check cut on an idle pooled connection is resent once on each worker. Each fails at the merge base and passes at the head
|
@litereview code-review |
Review not startedLiteLLM team members: sign in to LiteReview with your work Google account and connect GitHub, then post your review request again. Everyone else: comment |
…t of this PR The resend on a dropped or hung generic guardrail call, and the shared AsyncHTTPHandler retry rework behind it, move to a follow-up PR that adds a per-guardrail num_retries setting. This PR keeps the request and response shape fixes and the error_type on the fail-open log line
… port allocator Reading a port back from a port-0 bind trips TQ012, so the fail-open connect error case now takes its unused port from allocate_port
|
@greptileai re review |
|
bugbot run |
|
@litereview guide |
|
|
||
| endpoint: Final = AsyncHTTPHandler(transport=httpx.MockTransport(answer)) | ||
| try: | ||
| with patch.object(generic_guardrail, "async_handler", endpoint): |
There was a problem hiding this comment.
Tests replace internal attributes
The new tests replace async_handler and post through patch.object. The repository requires dependency injection instead. Pass the test client into the guardrail before merging
Context Used: AGENTS.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| ): | ||
| """A server that parses rows with its own message types echoes them back without | ||
| the keys those types lack, and its texts redaction must still reach the LLM.""" | ||
| original_rows = [ |
There was a problem hiding this comment.
The new tests assign original_rows, assistant_row, and other locals without Final. The repository requires every variable to carry Final. Annotate these new assignments before merging
Context Used: AGENTS.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 707e8a2. Configure here.
📝 guideScope: full · Full PR review. Today, a caller whose key runs a The walkthrough follows that Gemini request:
What the fix changes for the caller:
Tests added: 5 integration tests with 7 cases in Black box coverage: Yay. Each of the four behaviors that changed has its own integration test that runs the proxy against local stand-ins for the guardrail and the provider. I found no defects. Checks and execution details
View review · Reviewed |
…ward_messages_as_sent generic_guardrail_api keeps main's OpenAI-format rows and echo comparison by default. Setting forward_messages_as_sent: true on the guardrail sends rows as the client sent them and treats an echo that only drops undeclared keys as unchanged
|
Automatic reviews are disabled for this repository. |
…t-in forward_messages_as_sent, name the error type on fail-open (#46338) * fix(guardrails): accept Gemini tools and Anthropic content blocks in generic_guardrail_api, name the error type on fail-open GuardrailToolParam required a type key, so Gemini native tools (function_declarations, googleSearch) failed validation inside the hook and either returned a 500 or skipped the scan when fail_on_error was false. The type key is now optional and left out of the forwarded tool when absent, so an echoing guardrail server cannot write type: null into the provider request. structured_messages was re-validated against the chat completion message types, which silently emptied tool_result, tool_use, image and document content blocks to content: [] and dropped undeclared keys before the guardrail saw them. The request model now forwards rows as opaque mappings, which also retires the write-back shim that restored the original rows for echoed-back entries. The fail-open critical log line now carries error_type so a timeout, a refused connection and an upstream HTTP status can be told apart without the traceback. * fix(httpx): retry aiohttp server disconnects the way httpx does aiohttp raises ServerDisconnectedError when a kept-alive connection is closed by the peer before a response arrives, which is what a load balancer idle timeout shorter than AIOHTTP_KEEPALIVE_TIMEOUT produces. The transport mapped it to httpx.ReadError, which the handler's connection-error retry does not cover, so the request failed instead of being resent on a fresh connection. It now maps to httpx.RemoteProtocolError, the error httpx itself raises for the same condition, so the existing retry fires. * test(httpx): build the stub server reply in one bytes literal * fix(httpx): resend a dropped connection's request as sent and keep a streamed resend readable The connection-error retry closed its fresh client before a streamed body was read, so an aiohttp disconnect now billed a second upstream request and still failed. It also skipped masking on a status error from the resend, resent PATCH and DELETE as POST, dropped multipart files and ignored the handler's ssl_verify. The retry now resends the request the first attempt built, on a client with the handler's TLS settings, closes that client when a streamed body is closed, and masks a status error the same way the first attempt does. * fix(guardrails): log HTTPStatusError, not the masking wrapper, as the fail-open error_type * fix(guardrails): resend a generic guardrail check cut before any response A load balancer that closes an idle keepalive connection made the guardrail POST fail with "Server disconnected", because #46336 only resends POST on ConnectError. AsyncHTTPHandler.post now takes a keyword-only idempotent flag, defaulting to False, that gives a RemoteProtocolError the same single fresh-client resend PUT and DELETE get. Only GenericGuardrailAPI.apply_guardrail opts in, since a guardrail check is a pure verdict over the request. Every other POST keeps the The fail-open log line now puts error_type at the end so the pre-PR text stays contiguous for existing alert matchers test_rows_reach_the_guardrail_verbatim now reads the body off a real local guardrail server instead of mock call args * fix(http): keep a mid-body server disconnect a ReadError and move socket tests to integration A ServerDisconnectedError raised while reading a response body now stays httpx.ReadError, as it was before this PR. Only a disconnect before any response maps to RemoteProtocolError, which is the case the resend rule is about. Stream readers that end on ReadError, like the SAP stream iterator, keep their old behavior The loopback-server disconnect, TLS and guardrail resend tests move to tests/integration/sdk/test_disconnect_resend_wire.py, since tests/unit is in-process only. Unit keeps in-process MockTransport checks for the idempotent POST resend, masking on the resend, streamed and buffered client closing, the guardrail resend, and the guardrail receiving rows verbatim * fix(guardrails): resend a reset guardrail check and keep typed echoes on texts An idempotent POST now resends once on any network error after connect (ReadError, WriteError, RemoteProtocolError), so a guardrail behind a load balancer that answers a stale keepalive with a TCP reset rides it out too. That makes the aiohttp ServerDisconnectedError remap unnecessary, so it goes back to ReadError. This stops PUT and DELETE from stacking litellm's resend on top of aiohttp's own idempotent retry (4 sends instead of 2) and stops Vigil Guard from replaying its analyze POST on a disconnect Every resend now runs inside the method's own error mapping, so a timeout on the resend is a litellm.Timeout like the first attempt and a status error is masked once by the caller A guardrail server that parses rows with its own message types and echoes them back without the keys those types lack (annotations, tool_calls[].index) is read as an echo again, so its texts redaction reaches the LLM. A row only counts as an echo when no value changed and every key the chat completion types declare is kept The wire tests for the PUT/DELETE resend, its masking and its TLS settings now run on the httpx transport, where litellm's resend is the only retry, and the POST and guardrail tests cover both transports and both cut styles * test(guardrails): black box wire tests for generic guardrail shapes, fail-open error type and idle cut resend Integration tests against an owned proxy and scripted peers. Gemini native tools reach the guardrail and Gemini as sent, the guardrail sees chat rows and an Anthropic image block as sent, an echoing guardrail leaves a /v1/messages request unchanged, the fail-open log line names ConnectError, Timeout or HTTPStatusError, and a guardrail check cut on an idle pooled connection is resent once on each worker. Each fails at the merge base and passes at the head * fix(guardrails): check echoed rows without recursion and keep pytest.raises to one statement * refactor(guardrails): move the dropped-connection guardrail resend out of this PR The resend on a dropped or hung generic guardrail call, and the shared AsyncHTTPHandler retry rework behind it, move to a follow-up PR that adds a per-guardrail num_retries setting. This PR keeps the request and response shape fixes and the error_type on the fail-open log line * test(guardrails): pick the closed guardrail port from the integration port allocator Reading a port back from a port-0 bind trips TQ012, so the fail-open connect error case now takes its unused port from allocate_port * feat(guardrails): forward structured_messages as sent only behind forward_messages_as_sent generic_guardrail_api keeps main's OpenAI-format rows and echo comparison by default. Setting forward_messages_as_sent: true on the guardrail sends rows as the client sent them and treats an echo that only drops undeclared keys as unchanged --------- Co-authored-by: yuneng-jiang <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit 0dac61a)
TLDR
Problem this solves:
typekey, so the guardrail tool model rejects themHow it solves it:
GuardrailToolParam.typeis optional and left off the wire when absentforward_messages_as_sent, off by defaultstructured_messagesand write-back stay byte for byte what main doeserror_type=, e.g.HTTPStatusErrorThe Gemini tools fix and
error_type=apply to every guardrail, flag or not. The retry on a dropped or hung guardrail call moved to a follow-up PR that adds a per-guardrailnum_retriessettingFound by a customer evaluating 1.105.0rc1. Each claim was re-verified against current main before the change
Docs PR: BerriAI/litellm-docs#2417
User Flow
Before: a developer whose key runs a
generic_guardrail_apiguardrail onpre_callcannot call Gemini with native tools, and the guardrail never sees what the other providers were sent"model": "gemini-3.8-flash"and"tools": [{"function_declarations": [...]}]Generic Guardrail API failed: 1 validation error for GuardrailToolParam type Field requiredclaude-sonnet-5-5request with a native image block or anameon a row reaches the guardrail as{"role": "user", "content": []}withnamegonedocumentblock, through a guardrail that echoes rows back, reaches Claude without the documentfail_on_error: falsefails open and logs the same line for a timeout and a refused connectionAfter: Gemini tools pass and the fail-open line says what failed, and an admin who opts in gets every row as sent
"model": "gemini-3.8-flash"and"tools": [{"function_declarations": [...]}]typekey addedforward_messages_as_sent: trueunder the guardrail'slitellm_params(or flips the new toggle on the Add Guardrail form), and the Claude request now reaches the guardrail with the image block andnameintacterror_type=ConnectError,TimeoutorHTTPStatusErrorWithout the setting, steps 3 and 4 behave exactly as Before
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Three proxies ran one after the other with no DB, each started with
litellm --config <config> --port <port> --detailed_debug. Before is the merge base on port 48310, After (flag off) is the PR tip on port 48311 with the same config, and After (flag on) is the PR tip on port 48318 withforward_messages_as_sent: trueadded tostub-guardandguard-echo. Every call hits the real provider (Gemini, Anthropic, OpenAI). The guardrails point at a small local stub guardrail server that writes each request body it receives as one JSON line to a log file and answers{"action": "NONE"}. The stub on 48317 also echoestoolsandstructured_messagesback, the one on 48314 sleeps 10s, the one on 48315 answers 503, and nothing listens on 48313Models are the newest in
model_prices_and_context_window.jsonfor each familyThe flag-on config differs in two lines only
Payloads (
PNGis a 16x16 red square,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAFklEQVR4nGO4IydHEmIY1TCqYfhqAACaMxgQdGu1YAAAAABJRU5ErkJggg==)PROXYis http://localhost:48310 for Before, http://localhost:48311 for After with the flag off and http://localhost:48318 for After with the flag on. The stub on port N logs tostub_N.jsonl, androws_N.txtisjq -c '[.path, .body.structured_messages]' stub_N.jsonl. Long response bodies are trimmed, the PNG base64 is shown as<png>, and the call and trace ids are cut from the fail-open linesBefore (8227f9b)
Gemini native tools
curl -s -w '\nHTTP %{http_code}\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d @gemini_tools.jsonSame call with
-d @gemini_search.jsonstub_48312.jsonlandstub_48317.jsonlare both empty, so nothing was scanned and Gemini was never calledRows forwarded to the guardrail
curl ... $PROXY/v1/chat/completions ... -d @claude_rows.jsonreturns 200 from Claudetail -n 1 stub_48312.jsonl | jq -c .body.structured_messagesshowsnameandtool_calls[].indexstrippedcurl ... $PROXY/v1/chat/completions ... -d @claude_image.jsonis refused by the chat completions message check that runs after the guardrail (same everywhere below, chat completions does not take Anthropic image blocks)tail -n 1 stub_48312.jsonl | jq -c .body.structured_messagesshows the guardrail was handed an empty row instead of the image blockAnthropic /v1/messages with an echoing guardrail
curl -s -w '\nHTTP %{http_code}\n' $PROXY/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d @claude_blocks.jsonreturns 200, but Claude never saw the trip notes (459 input tokens)The request LiteLLM sent to Anthropic (
grep -A 4 'POST Request Sent' proxy.log) lost thedocumentblock and split the tool_result and the follow-up text into two user turns, because the guardrail's echo of the rows was written backFail-open log line
for g in guard-closed-port guard-slow guard-503; do echo "--- $g"; curl -s -o /dev/null -w 'HTTP %{http_code} in %{time_total}s\n' $PROXY/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "{\"model\": \"gpt-5.6\", \"messages\": [{\"role\": \"user\", \"content\": \"Say ok.\"}], \"guardrails\": [\"$g\"]}"; donegrep -o 'Generic Guardrail API error (fail-open).*' proxy.loggives the same line for all three, with nothing saying what failedAfter (7e567b3)
Gemini native tools
Same
-d @gemini_tools.jsoncall against the flag-off proxy now returns 200 from Gemini (the flag-on proxy returns the same)Same call with
-d @gemini_search.jsonreturns 200tail -n 1 stub_48312.jsonl | jq -c .body.toolsand the same onstub_48317.jsonlshow the tools exactly as sent, with notypekey addedRows forwarded to the guardrail
With the flag off, the same
-d @claude_rows.jsonand-d @claude_image.jsoncalls return the same 200 and 500 as BeforeWith the flag off, every row both stubs received matches Before byte for byte. After has two extra lines on top for the Gemini calls, which Before rejected before calling the guardrail, so they are skipped
With the flag on,
-d @claude_rows.jsonreturns 200 andtail -n 1 stub_48312.jsonl | jq -c .body.structured_messageskeepsnameandtool_calls[].indexWith the flag on,
-d @claude_image.jsonstill gets the same 500, and the guardrail now gets the image block itselfcurl -s $PROXY/guardrails/ui/provider_specific_params -H "Authorization: Bearer $LITELLM_MASTER_KEY" | jq -c '.generic_guardrail_api.optional_params.fields | {fail_on_error: (.fail_on_error | {type, default_value}), forward_messages_as_sent: (.forward_messages_as_sent | {type, default_value})}'shows the Add Guardrail form gets the toggle next tofail_on_error, off by defaultAnthropic /v1/messages with an echoing guardrail
With the flag off, the same
-d @claude_blocks.jsoncall returns the same answer as Before from 459 input tokens, and the request sent to Anthropic is identical to Before, document block missingWith the flag on, the same call returns 200 and Claude read the trip notes (514 input tokens)
With the flag on, the request LiteLLM sent to Anthropic (
grep -A 4 'POST Request Sent' proxy.log) matches what the client sent, with thedocumentblock kept and the tool_result and text in one user turnFail-open log line
Same
for g in guard-closed-port guard-slow guard-503loop as Before, on the flag-off proxygrep -o 'Generic Guardrail API error (fail-open).*' proxy.lognow ends each line witherror_type=, with the 503 reported as httpx'sHTTPStatusErrorrather than LiteLLM's internal masking wrapper. The flag-on proxy logs the same three linesType
🐛 Bug Fix
🆕 New Feature
Caveats (if any)
Medium
documentblockLow
forward_messages_as_sentmeans off, through the existing blank-value handling on guardrail paramsfunction_declarationstool and sends'tools': []documentblock never reaches the guardrail'sstructured_messagesimage_urlpartFinal Attestation