Repository navigation
fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings - #46936
Conversation
…d reject non-string instructions and voice
…sonic_realtime_replay_guard
…sonic_realtime_replay_guard
|
@litereview code-review |
Merging this PR will not alter performance
|
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. I traced the new Checks and execution details
Manual E2E evidence (in the PR description):
Integration tests (executed):
The title
Paths traced:
Boundary cases checked:
Unit tests run: No unresolved defects remain to reconcile. View review · Reviewed |
[Critical impact] The PR appears safe to merge, with the previous notice finding addressed and no new actionable issues found SummaryThis PR rejects malformed Nova Sonic settings, keeps the opening message until Bedrock accepts the stream, and blocks later retries or fallbacks on a committed session Since the previous review, it adds integration tests for refused openings, cross-provider replay, committed-stream failures, and malformed voices. The earlier breaking-change notice finding is addressed. No new actionable issues were found
Reviews (6) · Last reviewed commit: "test(bedrock): cover realtime replay, re..." · Reviewed by Greptile |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…ts the stream and refuse any fallback after commit Also rejects a malformed modalities, input_sample_rate_hertz or tools setting with invalid_type, dropped under drop_params.
|
@litereview code-review |
|
|
||
| For PROXY use only. | ||
| """ | ||
| raise_if_session_committed(websocket.scope) |
There was a problem hiding this comment.
Medium · Realtime commit guard breaks the xAI realtime unit tests in CI
tests/unit/llms/xai/test_xai_key_fallback.pycallsrealtime_main._arealtime(..., websocket=object())in three tests. These tests check xAI key resolution, and theobject()websocket has noscopeattribute.- This PR adds
raise_if_session_committed(websocket.scope)as the first line of_arealtime. That line runs before provider dispatch. - The guard raises
AttributeError: 'object' object has no attribute 'scope'beforexai_realtime.async_realtimeruns, so all three tests fail. - CI runs these tests through
tests/unit/llms/xaiin.github/workflows/test-unit.yml, so the unit job would go red on this PR.
Production is unaffected because a Starlette WebSocket always has scope. The smallest fix is to give those test websockets a scope dict (for example, a SimpleNamespace(scope={})). Another option is to read the scope defensively with getattr(websocket, "scope", {}).
Evidence
.venv/bin/python -m pytest tests/unit/llms/xai/test_xai_key_fallback.py at head: 3 failed, 17 passed. Failed: test_realtime_config_uses_xai_key_through_provider_resolution, test_realtime_config_uses_xai_key_when_provider_does_not_resolve_key, test_realtime_config_uses_generic_key_when_provider_does_not_resolve_key. Error: AttributeError: 'object' object has no attribute 'scope' at litellm/realtime_api/main.py:454
With line 454 replaced by pass (and nothing else changed): 20 passed. Restoring the line brings the 3 failures back.
tests/unit/llms/xai/test_xai_key_fallback.py:203,231,261 pass websocket=object()
.github/workflows/test-unit.yml:359 includes tests/unit/llms/xai
Latest summary by code-review · View this review · Reviewed 69961190e731
…ject OpenAI voices and non-string audio formats
|
@litereview code-review |
…and reject any-case OpenAI and empty Bedrock voices
|
@litereview code-review |
…hrough a real proxy Fix the scripted Bedrock peer's port import and the nested tool call cell's stale expected events, so the Nova Sonic integration file collects again
|
@litereview code-review |
|
bugbot run |
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 fe90289. Configure here.
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Judge (gpt-6-luna): low, probability of high 0.22 (high at or above 0.75)
Pushes do not re-run this check. Comment |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at fe90289
…in (#47090) * fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings (#46936) * fix(bedrock): block realtime replay after input starts the session and reject non-string instructions and voice * test(bedrock): name the malformed realtime setting test for its string cases * fix(bedrock): replay the opening realtime message until Bedrock accepts the stream and refuse any fallback after commit Also rejects a malformed modalities, input_sample_rate_hertz or tools setting with invalid_type, dropped under drop_params. * fix(bedrock): replay a refused opening message on any fallback and reject OpenAI voices and non-string audio formats * fix(realtime): read the client scope only when the websocket has one and reject any-case OpenAI and empty Bedrock voices * test(bedrock): cover realtime replay, refusal and committed failure through a real proxy Fix the scripted Bedrock peer's port import and the nested tool call cell's stale expected events, so the Nova Sonic integration file collects again (cherry picked from commit 3ef0b35) * test(integration): write worker configs beside test-supplied configs (#47066) Under worker isolation the harness rewrote every proxy config into the owned proxy's directory, so modules a test placed next to its own config (custom_auth) no longer resolved and the proxy died at boot. The copy now lands next to a test-supplied config, while configs inside the checkout still go to the worker directory so nothing is written into the repo tree (cherry picked from commit e754857) * test(e2e): keep the prompt-caching affinity test on the live provider (#47072) With E2E_PROVIDER_CACHE=1 the test's Anthropic deployment went through the shared response cache. Each call's recording expires on its own, so a run could replay the cache-writing call while a follow-up went live against a cold provider cache, recording creation instead of a read. That recording then replayed as a failure for 24 hours. Mark the test provider_live, as PROVIDER_CACHE.md requires for prompt-caching tests (cherry picked from commit 6b45a19) * test(integration): send post-kill requests on a fresh connection in two worker-kill tests (#47080) kill() returns once the killed worker's main thread is a zombie, but its other threads can still be exiting and holding its sockets open. A keep-alive connection pooled to that worker still looks healthy, so the next request goes out on it and the closing socket answers with a reset. The old reap wait used to hide this. A new connection can only be accepted by a live worker, so the surviving-worker assertions now run on a fresh client (cherry picked from commit c32eea6) * fix(caching): keep prompt cache usage on streamed cache hits (#47073) * fix(caching): keep prompt cache usage on streamed cache hits A stream=true request served from the response cache rebuilt its usage from the prompt, completion and total counts only, so prompt_tokens_details and the cache read and creation counts were dropped on the replayed stream. /v1/messages clients routed to Bedrock Converse saw input_tokens equal to the whole prompt and no cache tokens on a hit. Both replays now build the usage through one helper that also restores prompt_tokens_details and the integer cache read and creation counts, skipping cached values that do not validate. * fix(caching): coerce replayed token counts the way the live usage does The replay accepted only exact ints for the token counts, so an integral float or numeric string in a cached entry became 0 where the previous replay kept it. Counts now go through pydantic int coercion and fall back only when they do not validate. (cherry picked from commit d346d76) * fix(logging): keep the async request's logging payload when the sync success thread runs late (#47019) * fix(logging): keep the async request's logging payload when sync callbacks run late Treat the "cache" success callback as internal when deciding whether to start the sync success thread for async requests. It has no branch in the sync handler, so with `cache: true` that thread did nothing except rebuild and overwrite model_call_details["standard_logging_object"]. When the sync handler does run for an async request (a real sync-only logger is configured), it now builds its own payload and hands it only to its own callbacks. The async handler keeps sole ownership of the shared payload, so edits made by async logging hooks (for example the v3 rate limiter's mirrored x-ratelimit headers that Prometheus reads) are no longer discarded. Sync requests keep their existing behavior. * fix(logging): keep sync cache hits logged and isolate the async-request payload build The sync completion cache-hit path reused handle_sync_success_callbacks_for_async_calls, so treating "cache" as internal silently dropped sync callbacks on sync cache hits. It now submits the sync handler through its own method, as it effectively always did. For async requests the sync handler builds its payload from a copy of the call details, so message redaction cannot rewrite the shared standard_logging_object, and when it builds no payload its callbacks keep the shared one instead of getting None. * test(caching): lock sync cache-hit logging for completion, embedding and text_completion * test(logging): keep sync hook edits off a caller-supplied payload for async requests * fix(logging): give sync hooks a copy of the async payload when the thread builds none * test(logging): check every legacy sync logger gets the thread's own payload * test(logging): cover traceloop and supabase sync logging for async requests (cherry picked from commit a4e0570) * fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI (#47037) * fix(test-harness): preserve sibling auth modules in isolated worker configs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect servers in MCP connect-flow descriptions Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect ptu_hours in daily activity metrics after #43043 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): kill every serving worker once the SCIM push blocks on the row lock * fix(cost): price exact cost-map names before price-free capability rule matches * test(streaming): price a priced alias stream at its deployment model and keep the unpriceable case unmapped Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): price an explicit base_model under its own provider after candidate reordering Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): retain priced generalized candidates and skip explicit-pricing lookups Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(cost): assert custom pricing makes no remote model-info requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(cost): keep the per-candidate pricing provider final Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(router): pin a Bedrock application profile prompt for the one-hour ttl its base model sends Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): assert the Nova Sonic tool-call argument delta carries the full arguments * fix(cost): sort cost candidates from the static cost map and rules, without provider lookups * test(integration): bill route-priced Bedrock chat streams and responses, and pin application profiles for an hour on messages and cache hits --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Yuneng Jiang <yuneng@berri.ai> (cherry picked from commit 4a58784) * test(e2e): warm the memory test up with two batches before the measured one (#47087) * test(e2e): warm the memory test up with two batches before the measured one On a cold worker the second batch of failing requests can still raise the allocator's high-water mark by about 50 MB while the live Python heap stays flat, so the 48 MB budget failed about 1 in 10 Buildkite runs without a leak. The test now runs two warmup batches, measures the third against the same budget, and records every batch's settled growth per worker as an rss_batch_growth JUnit property for later calibration * test(e2e): record each memory batch's growth as soon as it settles A failure in a later batch no longer drops the growth already measured, and the worker keys are no longer sorted, which raised on a mix of named and unnamed hosts * test(e2e): silence the xunit2 record_property warning on the memory test (cherry picked from commit 1fd7f81) * test: import pytest and Final for the backported #47073 test on rc On main these imports came from an earlier commit that is not on rc/1.107.0, so the picked test failed collection with NameError --------- Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
voiceobject, then brokeHow it solves it:
drop_paramsBreaking change. Without
drop_params, a Nova Sonicsession.updatewith any malformed setting, like listinstructionsor an object audio format, now gets an error and applies nothing, where base acked it.drop_params: truedrops the field. With a fallback set, a mid-call Bedrock failure now closes 1011 instead of silently opening a new sessionUser Flow
Before: bad settings are acked and then kill the call
wss://litellm-domain/v1/realtime?model=nova-sonicand getsession.createdsession.updatewith"voice": {"id": "voice_123"}and getsession.updatedAfter: bad settings are refused up front
wss://litellm-domain/v1/realtime?model=nova-sonicand getsession.createdinvalid_typeerror onsession.voice, or is dropped underdrop_paramserrorevent and a 1011 closeDesign decisions
The
voiceobject is OpenAI's custom voice shape ({"id": "voice_..."}), and those ids name voices on an OpenAI account that Nova Sonic cannot play. Unwrapping the id was rejected because Bedrock would still refuse it, only later and after an ack. A silent drop was rejected because the realtime config follows thedrop_paramsconvention, so every malformed setting Nova Sonic reads (instructions,voice,tools,modalities,temperature,max_response_output_tokens, both sample rates and both audio formats) gets the sameinvalid_typeerror withoutdrop_paramsand is dropped with it. A dropped field falls back to the session default, the same as leaving it out. Withoutdrop_paramsone malformed field refuses the whole update, the way a 400 refuses a whole request, so its valid fields are not applied either. The check covers each setting's type, not each entry insidetools, which is a separate follow-up. An OpenAI voice name such asalloy, in any case, or an empty name is a string, but Nova Sonic has no such voice and closed the call 1011 on the first question, so it getsinvalid_valueonsession.voicethe same way. A Nova Sonic voice name liketiffanystill passes through, and so does any other name, since Bedrock's voice list changes per modelThe first message that makes Bedrock events, a
session.updateor user input, is kept on the client websocket until Bedrock accepts the stream it opened. A retry or fallback before that point sends it again on the new stream without a secondsession.created, since the model never saw it. The same replay happens when the fallback is an OpenAI or other non-Bedrock deployment, which sends its ownsession.createdand then reads the kept message before the client's next one (case 16). A spoken opening question is kept the same way (case 17). Once Bedrock accepts the stream the session is committed, and every later attempt on that websocket gets a 400 naming the failure that ended the committed stream. Replaying the whole conversation was rejected because Nova Sonic cannot be told what it already said. Committing when the message is sent was the earlier version of this PR, and it lost an input-first message when Bedrock refused the stream (case 10)The refusal runs at the start of every realtime attempt, not only inside the Bedrock handler, because a fallback to an OpenAI deployment never enters Bedrock code (case 9). It only fires on a websocket a Bedrock stream already committed, so a realtime request that never touched Bedrock sees no change
Relevant issues
Follow-up to #46214
Affected release
The input-first replay is a regression from #46214 in rc/1.107.0. The rest is older
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
Last updated: fe90289. QA and /live-pr-risk ran on d847b20, the last commit with a product diff
Both legs ran one config with 2 uvicorn workers against real Bedrock
amazon.nova-2-5-sonicand OpenAIgpt-realtime-2.1, Before at the merge baseee4860dd84and After atd847b20eeeShared setup (config, OpenAI SDK 2.33.0 client, websockets client)
Cases 7 to 9 break a live Bedrock stream with a bad audio chunk on a model with a fallback, and case 10 uses a model id Bedrock refuses, so the router falls back before the stream starts
Proxy:
python litellm/proxy/proxy_cli.py --config config.yaml --port <port> --num_workers 2withLITELLM_MASTER_KEY(exported asMKfor the clients), the Bedrock AWS keys andOPENAI_API_KEYin the envsdk_client.pyrealtime_client.pyBefore (ee4860d)
SDK, voice object
Cases 2 to 17, steps and output
voice object
instructions object
drop_params, both objects
string settings (control)
input, then update (control)
text, bad chunk, Bedrock fallback
audio, bad chunk, Bedrock fallback
text, bad chunk, OpenAI fallback
refused stream, fallback
string modalities
string input rate, then audio
tools object
OpenAI voice name
output format object
refused stream, OpenAI fallback
refused stream, spoken question
After (d847b20)
SDK, voice object
Cases 2 to 17, steps and output
voice object
instructions object
drop_params, both objects
string settings (control)
input, then update (control)
text, bad chunk, Bedrock fallback
audio, bad chunk, Bedrock fallback
text, bad chunk, OpenAI fallback
refused stream, fallback
string modalities
string input rate, then audio
tools object
OpenAI voice name
output format object
refused stream, OpenAI fallback
refused stream, spoken question
Surprises
/live-pr-risk at d847b20
87 cells ran on base
ee4860dd84and headd847b20eeein parallel, each with 2 uvicorn workers, its own Postgres database, and real Bedrockamazon.nova-2-5-sonicandamazon.nova-2-sonic-v1:0, OpenAIgpt-realtime-2.1and Geminigemini-3.8-live. A pass-through logged every event the proxy sent upstream. The head merged with current main matched head on every cell it ranBreaking
B1. Without
drop_params, base acked a non-stringinstructions(list or int), an object, int or listinput_audio_format, a stringtoolsand a non-numeric sample rate, and the session went on. Head answersinvalid_typeand applies nothing from that update. Withdrop_paramshead drops the field and answers like base. Approved by @mateo-berri as the standingdrop_paramsrule he set on 2026-10-02 for #40775, an error without it and a drop with it. It is now named in the Breaking change noteinput_audio_formatinvalid_type, answeredinstructionsinvalid_type, plain answerinstructionsinvalid_typeB2. With a fallback set, a Bedrock stream that already answered and then failed opened a new, silent session on base, and the socket stayed open. Head sends the Bedrock error and closes 1011 (O12 Bedrock to Bedrock, O13 Bedrock to OpenAI, O15 audio first). This is the behavior the PR exists to ship, and it is now named in the Breaking change note
Backward incompatible
Every realtime attempt, for every provider, now refuses a websocket that a Bedrock stream already committed, with a 400. A websocket that never touched Bedrock sees no change (C01 to C05). The shared realtime reader for OpenAI, Azure, xAI, Gemini, Vertex and Meta now reads a kept opening message first, so guardrails run on the replay (O09 blocked it, like a direct OpenAI call in O10). The scope key from #46214 is renamed, and nothing else uses the old name. Under
drop_paramsan OpenAI voice name drops tomatthew, where base sent it and closed 1011Regression risk
A 2-hop fallback whose first hop is a non-Bedrock deployment that reads the kept message and then fails would give the second hop the client's next frame. The router only falls back before streaming starts, so this is hard to reach, and base drops the opening message on every refused fallback anyway. Azure, xAI, Vertex and Meta as fallback targets share the replay code that ran live for OpenAI and Gemini
Dependency graph
session.updatechecks/v1/live/sessionsNot verified
A same-deployment retry after a commit, since the router never retries the 400s a live run can trigger. Azure, xAI, Vertex and Meta fallbacks, with no deployments in the rig. A Playground click-through, where its exact payload ran instead.
drop_paramsfrom a user agent or router defaults. Python 3.10 and 3.11Found and left alone, both sides: Bedrock realtime client frames skip realtime guardrails (O11), and a direct Gemini session drops a
session.updatesent aftersession.created(C05). Each has its own follow-upAudit round 1 of 3
Node ids are relative to
tests/integration/providers/. The filetest_bedrock_nova_sonic_realtime_tool_calls.pyis written asnova::, andtest_realtime_unguarded_voice_turns.pyis written asvoice::. Head results cover two runs with the same seedsnova::test_refused_opening_is_replayed_on_the_bedrock_fallback[text-first]nova::...[session-update-first]nova::test_refused_text_opening_is_replayed_on_the_openai_fallbacknova::test_committed_session_failure_closes_the_socket_without_another_provider_streamvoice::test_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_frames[/v1/realtime]voice::test_openai_sdk_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_frames[async]voice::test_azure_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_framesvoice::test_xai_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_framesvoice::test_vertex_live_voice_turn_sends_the_upstream_only_the_setup_and_the_audionova::cellsnova::test_voice_object_is_refused_and_never_reaches_bedrocklive/.../L1_*.txtlive/.../L2_*.txtlive/.../L3_*.txttest_bedrock_realtime_transformation.pytest_bedrock_realtime_handler.pytest_realtime_streaming.pyThe 9 existing R10 cells are
test_nested_tool_call_before_assistant_block,test_flat_tool_shape,test_tool_result_round_trip,test_two_tool_calls_one_turn,test_tool_call_inside_active_assistant_responseandtest_malformed_tool_content[empty|missing|not-json|five-kb]. The nested cell's green comes from the*-nestedlanes after its stale tail was fixed. The other 8 are green in base, head-1 and head-2Base reds, all as the inventory expected. In R1 the client got a second
session.createdfrom the fallback attempt. In R3 the lane timed out with onlysession.created, because the OpenAI upstream never received the openingconversation.item.create. In R4 the client got a secondsession.createdfrom a fallback that opened a new provider session. In R11 the voice object gotsession.updatedand noinvalid_typeerror. On the head, the proxy loghead-1/gw1/owned-proxy-4720d5f88faa474cb65f39a71b496d30.logholds the guard refusal "already committed to a provider stream; it cannot be replayed. The committed stream failed with: ModelStreamErrorException" for R4Live rows, real vendors (AWS Bedrock Nova Sonic
amazon.nova-2-5-sonicand a deliberately unknown idamazon.nova-sonic-not-enabled-v9:0, then OpenAIgpt-realtime-2.1as the fallback target).L1 base got two
session.createdand no answer in 45 s. L1 head got the answer from the OpenAI fallback ("I'm ChatGPT, a friendly AI voice ..."), so the opening text reached OpenAIL2 base answered on Bedrock. After the bad audio chunk it then failed over to OpenAI, and the client saw a second
session.createdthat carried OpenAI's default instructions. L2 head answered on Bedrock. After the bad chunk the client goterror"ValidationException: Unable to parse input chunk ..." and a 1011 close, with onesession.createdL3 sends
{"voice": "alloy", "instructions": "Always start your answer with the word Ahoy."}. L3 base acked it withsession.updated, then real Bedrock answered "ValidationException ... Received invalid id: 'alloy'", and the socket closed with 1011. L3 head answerederrorwith codeinvalid_valueon paramsession.voiceand sent nosession.updated. The session stayed open and answered the next question on Bedrock's defaults. The instructions were not applied, since the whole update was refusedR11 and L3 are behavior changes. Without
drop_params, a malformed or OpenAI-only session setting now gets an error frame, and the whole session.update is refused, where base acked it. With base, Bedrock either got a stringified value or killed the session with 1011, as L3 shows. Shipping it is approved by @mateo-berri's standingdrop_paramsrule of 2026-10-02, where an unsupported or malformed value drops underdrop_paramsand answers 400 without it, like o-seriestemperatureType
🐛 Bug Fix
✅ Test
Caveats (if any)
Medium
Low
toolsentries, like["lookup"], still pass or drop silently, as before, a separate follow-upnovaoralloy, is acked, then closes 1011, as beforesession.audio.output.voiceis still ignored, as before, a separate follow-upsession.created, as beforeFinal Attestation
Bugbot summary