Skip to content

fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings - #46936

Merged
mateo-berri merged 8 commits into
mainfrom
litellm_bedrock_nova_sonic_realtime_replay_guard
Oct 17, 2026
Merged

mateo-berri merged 8 commits into
mainfrom
litellm_bedrock_nova_sonic_realtime_replay_guard

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Bedrock realtime acked malformed settings, like a voice object, then broke
  • A fallback after the stream took input silently started a new session
  • A refused stream lost an input-first opening message

How it solves it:

  • A malformed setting gets an error, or is dropped under drop_params
  • The opening message is replayed until Bedrock accepts the stream
  • After that, any retry or fallback is refused

Breaking change. Without drop_params, a Nova Sonic session.update with any malformed setting, like list instructions or an object audio format, now gets an error and applies nothing, where base acked it. drop_params: true drops the field. With a fallback set, a mid-call Bedrock failure now closes 1011 instead of silently opening a new session

User Flow

Before: bad settings are acked and then kill the call

  1. They open wss://litellm-domain/v1/realtime?model=nova-sonic and get session.created
  2. They send session.update with "voice": {"id": "voice_123"} and get session.updated
  3. Their first question gets "Received invalid id: '{'id': 'voice_123'}'" and a 1011 close
  4. With a fallback set, a mid-call Bedrock error silently starts a fresh session

After: bad settings are refused up front

  1. They open wss://litellm-domain/v1/realtime?model=nova-sonic and get session.created
  2. The same update gets an invalid_type error on session.voice, or is dropped under drop_params
  3. The whole update is refused, so their first question gets a spoken answer with the session defaults
  4. With a fallback set, that error arrives as an error event and a 1011 close
Design decisions

The voice object 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 the drop_params convention, 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 same invalid_type error without drop_params and is dropped with it. A dropped field falls back to the session default, the same as leaving it out. Without drop_params one 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 inside tools, which is a separate follow-up. An OpenAI voice name such as alloy, 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 gets invalid_value on session.voice the same way. A Nova Sonic voice name like tiffany still passes through, and so does any other name, since Bedrock's voice list changes per model

The first message that makes Bedrock events, a session.update or 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 second session.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 own session.created and 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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-sonic and OpenAI gpt-realtime-2.1, Before at the merge base ee4860dd84 and After at d847b20eee

Case Before After
SDK, voice object acked, 1011 close invalid_type, answered
voice object acked, 1011 close invalid_type, answered
instructions object acked, pirate answer invalid_type, default answer
drop_params, both objects acked, 1011 close acked, dropped, answered
string settings (control) pirate answer pirate answer
input, then update (control) update refused, two answers update refused, two answers
text, bad chunk, Bedrock fallback silent second session error, 1011 close
audio, bad chunk, Bedrock fallback silent second session error, 1011 close
text, bad chunk, OpenAI fallback silent OpenAI session error, 1011 close
refused stream, fallback question lost question answered
string modalities error, 1011 close invalid_type, answered
string input rate, then audio acked, 1011 close invalid_type, socket open
tools object acked, ignored invalid_type, answered
OpenAI voice name acked, 1011 close invalid_value, answered
output format object acked, ignored invalid_type, answered
refused stream, OpenAI fallback question lost question answered
refused stream, spoken question question lost question answered
Shared 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

model_list:
  - model_name: nova-sonic-qa
    litellm_params:
      model: bedrock/amazon.nova-2-5-sonic
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
  - model_name: nova-sonic-qa-drop-params
    litellm_params:
      model: bedrock/amazon.nova-2-5-sonic
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
      drop_params: true
  - model_name: nova-a
    litellm_params:
      model: bedrock/amazon.nova-2-5-sonic
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
  - model_name: nova-b
    litellm_params:
      model: bedrock/amazon.nova-2-5-sonic
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
  - model_name: nova-x
    litellm_params:
      model: bedrock/amazon.nova-2-5-sonic
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
  - model_name: nova-unavailable
    litellm_params:
      model: bedrock/amazon.nova-sonic-not-enabled-v9:0
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
  - model_name: nova-unavailable-x
    litellm_params:
      model: bedrock/amazon.nova-sonic-not-enabled-v9:0
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
  - model_name: nova-retry
    litellm_params:
      model: bedrock/amazon.nova-2-5-sonic
      aws_region_name: us-east-1
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
  - model_name: gpt-rt
    litellm_params:
      model: openai/gpt-realtime-2.1
      api_key: os.environ/OPENAI_API_KEY

router_settings:
  num_retries: 2
  fallbacks: [{"nova-a": ["nova-b"]}, {"nova-x": ["gpt-rt"]}, {"nova-unavailable": ["nova-b"]}, {"nova-unavailable-x": ["gpt-rt"]}]
  model_group_retry_policy: {"nova-retry": {"BadRequestErrorRetries": 1}}

Proxy: python litellm/proxy/proxy_cli.py --config config.yaml --port <port> --num_workers 2 with LITELLM_MASTER_KEY (exported as MK for the clients), the Bedrock AWS keys and OPENAI_API_KEY in the env

sdk_client.py

import asyncio
import json
import os
import sys
import time

from openai import AsyncOpenAI

PORT, MODEL = sys.argv[1], sys.argv[2]
SESSION = json.loads(os.environ.get("SESSION", '{"voice": {"id": "voice_123"}}'))
START = time.monotonic()


def stamp(*parts):
    print(f"{time.monotonic() - START:6.1f}s", *parts, flush=True)


async def main():
    client = AsyncOpenAI(base_url=f"http://127.0.0.1:{PORT}/v1", api_key=os.environ["MK"])
    async with client.realtime.connect(model=MODEL) as conn:
        await conn.session.update(session=SESSION)
        await conn.conversation.item.create(
            item={"type": "message", "role": "user", "content": [{"type": "input_text", "text": "In one short sentence, who are you?"}]}
        )
        await conn.response.create()
        transcript = []
        async for event in conn:
            if event.type == "error":
                stamp("error", json.dumps({k: getattr(event.error, k, None) for k in ("code", "param", "message")}))
            elif event.type in ("session.created", "session.updated", "response.done"):
                stamp(event.type)
            elif event.type in ("response.text.delta", "response.output_text.delta") or event.type.endswith("audio_transcript.delta"):
                transcript.append(event.delta)
            if event.type == "response.done":
                break
        stamp("assistant said:", "".join(transcript).strip())


try:
    asyncio.run(main())
except Exception as exc:
    stamp("client raised", type(exc).__name__, str(exc)[:220])

realtime_client.py

import asyncio
import json
import os
import sys
import time

import websockets

PORT, MODEL, SCENARIO = sys.argv[1], sys.argv[2], sys.argv[3]
IDLE_SECONDS = float(os.environ.get("IDLE_SECONDS", "150"))
URL = f"ws://127.0.0.1:{PORT}/v1/realtime?model={MODEL}"
USER_TEXT = {
    "type": "conversation.item.create",
    "item": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "In one short sentence, who are you?"}]},
}
BAD_AUDIO = {"type": "input_audio_buffer.append", "audio": "@@@not-base64@@@"}
SILENCE = {"type": "input_audio_buffer.append", "audio": "AAAA" * 256}
START = time.monotonic()
SEEN = {"session.created": 0}


def show(event):
    t = f"{time.monotonic() - START:6.1f}s"
    kind = event.get("type")
    SEEN["session.created"] += kind == "session.created"
    if kind == "error":
        print(t, "error", json.dumps({k: event["error"].get(k) for k in ("code", "param", "message")}))
    elif kind in ("session.created", "session.updated"):
        session = event.get("session", {})
        print(t, kind, json.dumps({k: session.get(k) for k in ("instructions", "voice")}))
    elif kind == "response.done":
        print(t, kind, event.get("response", {}).get("status"))
    elif not kind.endswith(".delta"):
        print(t, kind)


async def read_until(ws, stop_types, timeout):
    text = []
    while True:
        event = json.loads(await asyncio.wait_for(ws.recv(), timeout))
        show(event)
        if event.get("type", "").endswith("transcript.delta") or event.get("type") == "response.text.delta":
            text.append(event.get("delta", ""))
        if event.get("type") in stop_types:
            return event, "".join(text)


async def ask(ws):
    await ws.send(json.dumps(USER_TEXT))
    await ws.send(json.dumps({"type": "response.create"}))
    try:
        _, text = await read_until(ws, {"response.done"}, float(os.environ.get("ANSWER_SECONDS", "60")))
    except asyncio.TimeoutError:
        print("no answer within the wait")
        return
    print("assistant said:", text.strip())


async def main():
    headers = {"Authorization": f"Bearer {os.environ['MK']}"}
    async with websockets.connect(URL, additional_headers=headers, max_size=None) as ws:
        await read_until(ws, {"session.created"}, 30)
        if SCENARIO == "object-settings":
            session = json.loads(os.environ.get("SESSION", '{"instructions": {"role": "pirate"}, "voice": {"id": "voice_123"}}'))
            await ws.send(json.dumps({"type": "session.update", "session": session}))
            await read_until(ws, {"session.updated", "error"}, 30)
            await ask(ws)
            return
        if SCENARIO == "input-then-update":
            await ask(ws)
            await ws.send(json.dumps({"type": "session.update", "session": json.loads(os.environ["SESSION"])}))
            await read_until(ws, {"session.updated", "error"}, 30)
            await ask(ws)
            return
        if SCENARIO == "settings-then-audio":
            await ws.send(json.dumps({"type": "session.update", "session": json.loads(os.environ["SESSION"])}))
            await read_until(ws, {"session.updated", "error"}, 30)
            for _ in range(5):
                await ws.send(json.dumps(SILENCE))
        elif SCENARIO == "audio-then-bad-audio":
            for _ in range(20):
                await ws.send(json.dumps(SILENCE))
            await asyncio.sleep(1.5)
            await ws.send(json.dumps(BAD_AUDIO))
        elif SCENARIO == "audio-question":
            await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": open("question_16k.b64").read()}))
            for _ in range(120):
                await ws.send(json.dumps(SILENCE))
                await asyncio.sleep(0.024)
            try:
                _, text = await read_until(ws, {"response.done"}, float(os.environ.get("ANSWER_SECONDS", "60")))
                print("assistant said:", text.strip())
            except asyncio.TimeoutError:
                print("no answer within the wait")
        else:
            await ask(ws)
        if SCENARIO == "text-then-bad-audio":
            await ws.send(json.dumps(BAD_AUDIO))
        deadline = time.monotonic() + IDLE_SECONDS
        try:
            while time.monotonic() < deadline:
                event = json.loads(await asyncio.wait_for(ws.recv(), deadline - time.monotonic()))
                show(event)
        except asyncio.TimeoutError:
            print("no more events within the idle window")
        except websockets.ConnectionClosed as closed:
            print(f"{time.monotonic() - START:6.1f}s websocket closed", closed.rcvd.code if closed.rcvd else None, closed.rcvd.reason if closed.rcvd else None)
        print("session.created events seen:", SEEN["session.created"])


try:
    asyncio.run(main())
except websockets.ConnectionClosed as closed:
    print(f"{time.monotonic() - START:6.1f}s websocket closed", closed.rcvd.code if closed.rcvd else None, (closed.rcvd.reason if closed.rcvd else "")[:160])

Before (ee4860d)

SDK, voice object

  1. Run the client
$ SESSION='{"voice": {"id": "voice_123"}}' python sdk_client.py 34299 nova-sonic-qa
  1. Observed
   1.0s session.created
   1.0s session.updated
   1.0s error {"code": null, "param": null, "message": "ValidationException: RequestId=f95124a8-09f2-475c-a35e-fbc959da3b3e : Received invalid id: '{'id': 'voice_123'}'. Please check AWS documentation for valid voiceIds."}
   1.0s client raised ConnectionClosedError received 1011 (internal error) ValidationException: RequestId=f95124a8-09f2-475c-a35e-fbc959da3b3e : Received invalid id: '{'id': 'voice_123'}'. Please ch; then sent 1011 (internal error) ValidationException: RequestId=f
Cases 2 to 17, steps and output

voice object

  1. Run the client
$ SESSION='{"voice": {"id": "voice_123"}}' python realtime_client.py 34299 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.4s session.updated {"instructions": null, "voice": null}
   0.5s error {"code": null, "param": null, "message": "ValidationException: RequestId=8cfaf593-6fb2-4106-97d9-485ff37cee4c : Received invalid id: '{'id': 'voice_123'}'. Please check AWS documentation for valid voiceIds."}
   0.5s websocket closed 1011 ValidationException: RequestId=8cfaf593-6fb2-4106-97d9-485ff37cee4c : Received invalid id: '{'id': 'voice_123'}'. Please ch

instructions object

  1. Run the client
$ SESSION='{"instructions": {"role": "pirate"}}' python realtime_client.py 34299 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.4s session.updated {"instructions": null, "voice": null}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.3s response.output_item.added
   1.3s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I be a pirate and an AI model here to help ye.

drop_params, both objects

  1. Run the client
$ SESSION='{"instructions": {"role": "pirate"}, "voice": {"id": "voice_123"}}' python realtime_client.py 34299 nova-sonic-qa-drop-params object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.4s session.updated {"instructions": null, "voice": null}
   0.4s error {"code": null, "param": null, "message": "ValidationException: RequestId=16b32892-8e19-4adb-9140-8c9996e9091b : Received invalid id: '{'id': 'voice_123'}'. Please check AWS documentation for valid voiceIds."}
   0.4s websocket closed 1011 ValidationException: RequestId=16b32892-8e19-4adb-9140-8c9996e9091b : Received invalid id: '{'id': 'voice_123'}'. Please ch

string settings (control)

  1. Run the client
$ SESSION='{"instructions": "Answer as a pirate.", "voice": "matthew"}' python realtime_client.py 34299 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.4s session.updated {"instructions": null, "voice": null}
   0.7s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.2s response.created
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.2s response.text.done
   1.2s response.content_part.done
   1.2s response.output_item.done
   1.4s response.output_item.added
   1.4s response.content_part.added
   2.2s response.audio.done
   2.2s response.content_part.done
   2.2s response.output_item.done
   2.2s response.done completed
assistant said: I be a salty pirate and an AI model built to help you with this here conversation.

input, then update (control)

  1. Run the client
$ SESSION='{"instructions": "Answer as a pirate."}' python realtime_client.py 34299 nova-sonic-qa input-then-update
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.5s input_audio_buffer.speech_started
   0.9s input_audio_buffer.speech_stopped
   0.9s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.
   1.8s error {"code": "session_update_not_applied", "param": "session", "message": "Bedrock Nova Sonic cannot change tools, instructions, voice, output audio format, temperature or max output tokens after the session has started, so this session.update was not applied"}
   2.0s input_audio_buffer.speech_started
   2.3s input_audio_buffer.speech_stopped
   2.3s conversation.item.input_audio_transcription.completed
   2.5s response.created
   2.5s response.output_item.added
   2.5s response.content_part.added
   2.5s response.text.done
   2.5s response.content_part.done
   2.5s response.output_item.done
   2.6s response.output_item.added
   2.6s response.content_part.added
   3.2s response.audio.done
   3.2s response.content_part.done
   3.2s response.output_item.done
   3.2s response.done completed
assistant said: I am an AI model built to help with this conversation.

text, bad chunk, Bedrock fallback

  1. Run the client
$ IDLE_SECONDS=20 python realtime_client.py 34299 nova-a text-then-bad-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.5s input_audio_buffer.speech_started
   0.9s input_audio_buffer.speech_stopped
   0.9s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.
   2.1s session.created {"instructions": null, "voice": null}
no more events within the idle window
session.created events seen: 2

audio, bad chunk, Bedrock fallback

  1. Run the client
$ IDLE_SECONDS=20 python realtime_client.py 34299 nova-a audio-then-bad-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   1.8s session.created {"instructions": null, "voice": null}
no more events within the idle window
session.created events seen: 2

text, bad chunk, OpenAI fallback

  1. Run the client
$ IDLE_SECONDS=20 python realtime_client.py 34299 nova-x text-then-bad-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.5s input_audio_buffer.speech_started
   0.9s input_audio_buffer.speech_stopped
   0.9s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.
   2.2s session.created {"instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you\u2019re asked about them.", "voice": null}
no more events within the idle window
session.created events seen: 2

refused stream, fallback

  1. Run the client
$ IDLE_SECONDS=10 ANSWER_SECONDS=30 python realtime_client.py 34299 nova-unavailable idle
  1. Observed
   0.2s session.created {"instructions": null, "voice": null}
   0.5s session.created {"instructions": null, "voice": null}
no answer within the wait
no more events within the idle window
session.created events seen: 2

string modalities

  1. Run the client
$ SESSION='{"modalities": "text"}' IDLE_SECONDS=8 python realtime_client.py 34299 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   1.3s error {"code": null, "param": null, "message": "Bedrock realtime session already committed to a provider stream; it cannot be replayed. The committed stream failed with: 1 validation error for nullable[list[str]]\n  Input should be a valid list [type=list_type, input_value='text', input_type=str]\n    For further information visit https://errors.pydantic.dev/2.13/v/list_type"}
   1.3s websocket closed 1011 Bedrock realtime session already committed to a provider stream; it cannot be replayed. The committed stream failed with: 1

string input rate, then audio

  1. Run the client
$ SESSION='{"input_sample_rate_hertz": "16000"}' IDLE_SECONDS=8 python realtime_client.py 34299 nova-sonic-qa settings-then-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.3s session.updated {"instructions": null, "voice": null}
   0.5s error {"code": null, "param": null, "message": "ValidationException: Unable to parse input chunk. Please check input format contains correct format."}
   0.5s websocket closed 1011 ValidationException: Unable to parse input chunk. Please check input format contains correct format.
session.created events seen: 1

tools object

  1. Run the client
$ SESSION='{"tools": {"type": "function", "name": "lookup"}}' python realtime_client.py 34299 nova-sonic-qa object-settings
  1. Observed
   0.9s session.created {"instructions": null, "voice": null}
   1.3s session.updated {"instructions": null, "voice": null}
   1.8s input_audio_buffer.speech_started
   2.4s input_audio_buffer.speech_stopped
   2.4s conversation.item.input_audio_transcription.completed
   2.6s response.created
   2.6s response.output_item.added
   2.6s response.content_part.added
   2.6s response.text.done
   2.6s response.content_part.done
   2.6s response.output_item.done
   2.9s response.output_item.added
   2.9s response.content_part.added
   3.2s response.audio.done
   3.2s response.content_part.done
   3.2s response.output_item.done
   3.2s response.done completed
assistant said: I am an AI model built to help with this conversation.

OpenAI voice name

  1. Run the client
$ SESSION='{"voice": "alloy"}' python realtime_client.py 34299 nova-sonic-qa object-settings
  1. Observed
   0.7s session.created {"instructions": null, "voice": null}
   1.0s session.updated {"instructions": null, "voice": null}
   1.1s error {"code": null, "param": null, "message": "ValidationException: RequestId=46110d9d-ac35-4928-bf37-44db798c954e : Received invalid id: 'alloy'. Please check AWS documentation for valid voiceIds."}
   1.1s websocket closed 1011 ValidationException: RequestId=46110d9d-ac35-4928-bf37-44db798c954e : Received invalid id: 'alloy'. Please check AWS docume

output format object

  1. Run the client
$ SESSION='{"output_audio_format": {"type": "audio/pcmu"}}' python realtime_client.py 34299 nova-sonic-qa object-settings
  1. Observed
   0.7s session.created {"instructions": null, "voice": null}
   0.9s session.updated {"instructions": null, "voice": null}
   1.2s input_audio_buffer.speech_started
   1.6s input_audio_buffer.speech_stopped
   1.6s conversation.item.input_audio_transcription.completed
   1.7s response.created
   1.7s response.output_item.added
   1.7s response.content_part.added
   1.7s response.text.done
   1.7s response.content_part.done
   1.7s response.output_item.done
   1.9s response.output_item.added
   1.9s response.content_part.added
   2.5s response.audio.done
   2.5s response.content_part.done
   2.5s response.output_item.done
   2.5s response.done completed
assistant said: I am an AI model built to help with this conversation.

refused stream, OpenAI fallback

  1. Run the client
$ IDLE_SECONDS=10 ANSWER_SECONDS=30 python realtime_client.py 34299 nova-unavailable-x idle
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.8s session.created {"instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you\u2019re asked about them.", "voice": null}
no answer within the wait
no more events within the idle window
session.created events seen: 2

refused stream, spoken question

  1. Run the client
$ IDLE_SECONDS=3 ANSWER_SECONDS=30 python realtime_client.py 34299 nova-unavailable audio-question
  1. Observed
   0.2s session.created {"instructions": null, "voice": null}
   3.1s session.created {"instructions": null, "voice": null}
no answer within the wait
no more events within the idle window
session.created events seen: 2

After (d847b20)

SDK, voice object

  1. Run the client
$ SESSION='{"voice": {"id": "voice_123"}}' python sdk_client.py 51321 nova-sonic-qa
  1. Observed
   0.7s session.created
   0.7s error {"code": "invalid_type", "param": "session.voice", "message": "Invalid type for 'session.voice': Bedrock Nova Sonic needs a string there. Set drop_params to drop it instead"}
   2.2s response.done
   2.2s assistant said: I am an AI model built to help with this conversation.
Cases 2 to 17, steps and output

voice object

  1. Run the client
$ SESSION='{"voice": {"id": "voice_123"}}' python realtime_client.py 51321 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.1s error {"code": "invalid_type", "param": "session.voice", "message": "Invalid type for 'session.voice': Bedrock Nova Sonic needs a string there. Set drop_params to drop it instead"}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.3s response.output_item.added
   1.3s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.

instructions object

  1. Run the client
$ SESSION='{"instructions": {"role": "pirate"}}' python realtime_client.py 51321 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.1s error {"code": "invalid_type", "param": "session.instructions", "message": "Invalid type for 'session.instructions': Bedrock Nova Sonic needs a string there. Set drop_params to drop it instead"}
   0.6s input_audio_buffer.speech_started
   0.9s conversation.item.input_audio_transcription.completed
   0.9s input_audio_buffer.speech_stopped
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.

drop_params, both objects

  1. Run the client
$ SESSION='{"instructions": {"role": "pirate"}, "voice": {"id": "voice_123"}}' python realtime_client.py 51321 nova-sonic-qa-drop-params object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.4s session.updated {"instructions": null, "voice": null}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.2s response.created
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.2s response.text.done
   1.2s response.content_part.done
   1.2s response.output_item.done
   1.3s response.output_item.added
   1.3s response.content_part.added
   1.9s response.audio.done
   1.9s response.content_part.done
   1.9s response.output_item.done
   1.9s response.done completed
assistant said: I am an AI model built to help with this conversation.

string settings (control)

  1. Run the client
$ SESSION='{"instructions": "Answer as a pirate.", "voice": "matthew"}' python realtime_client.py 51321 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.4s session.updated {"instructions": null, "voice": null}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.2s response.created
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.2s response.text.done
   1.2s response.content_part.done
   1.2s response.output_item.done
   1.3s response.output_item.added
   1.3s response.content_part.added
   2.3s response.audio.done
   2.3s response.content_part.done
   2.3s response.output_item.done
   2.3s response.done completed
assistant said: I be a salty pirate and an AI model built to help you with this here conversation.

input, then update (control)

  1. Run the client
$ SESSION='{"instructions": "Answer as a pirate."}' python realtime_client.py 51321 nova-sonic-qa input-then-update
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.3s response.output_item.added
   1.3s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.
   1.8s error {"code": "session_update_not_applied", "param": "session", "message": "Bedrock Nova Sonic cannot change tools, instructions, voice, output audio format, temperature or max output tokens after the session has started, so this session.update was not applied"}
   2.0s input_audio_buffer.speech_started
   2.3s input_audio_buffer.speech_stopped
   2.3s conversation.item.input_audio_transcription.completed
   2.5s response.created
   2.5s response.output_item.added
   2.5s response.content_part.added
   2.5s response.text.done
   2.5s response.content_part.done
   2.5s response.output_item.done
   2.6s response.output_item.added
   2.6s response.content_part.added
   3.2s response.audio.done
   3.2s response.content_part.done
   3.2s response.output_item.done
   3.2s response.done completed
assistant said: I am an AI model built to help with this conversation.

text, bad chunk, Bedrock fallback

  1. Run the client
$ IDLE_SECONDS=20 python realtime_client.py 51321 nova-a text-then-bad-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.6s input_audio_buffer.speech_started
   1.0s conversation.item.input_audio_transcription.completed
   1.0s input_audio_buffer.speech_stopped
   1.2s response.created
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.2s response.text.done
   1.2s response.content_part.done
   1.2s response.output_item.done
   1.3s response.output_item.added
   1.3s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.
   2.0s error {"code": null, "param": null, "message": "ValidationException: Unable to parse input chunk. Please check input format contains correct format."}
   2.0s websocket closed 1011 ValidationException: Unable to parse input chunk. Please check input format contains correct format.
session.created events seen: 1

audio, bad chunk, Bedrock fallback

  1. Run the client
$ IDLE_SECONDS=20 python realtime_client.py 51321 nova-a audio-then-bad-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   1.8s error {"code": null, "param": null, "message": "ValidationException: Unable to parse input chunk. Please check input format contains correct format."}
   1.8s websocket closed 1011 ValidationException: Unable to parse input chunk. Please check input format contains correct format.
session.created events seen: 1

text, bad chunk, OpenAI fallback

  1. Run the client
$ IDLE_SECONDS=20 python realtime_client.py 51321 nova-x text-then-bad-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.
   2.0s error {"code": null, "param": null, "message": "ValidationException: Unable to parse input chunk. Please check input format contains correct format."}
   2.0s websocket closed 1011 ValidationException: Unable to parse input chunk. Please check input format contains correct format.
session.created events seen: 1

refused stream, fallback

  1. Run the client
$ IDLE_SECONDS=10 ANSWER_SECONDS=30 python realtime_client.py 51321 nova-unavailable idle
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.9s input_audio_buffer.speech_started
   1.3s input_audio_buffer.speech_stopped
   1.3s conversation.item.input_audio_transcription.completed
   1.4s response.created
   1.4s response.output_item.added
   1.4s response.content_part.added
   1.4s response.text.done
   1.4s response.content_part.done
   1.4s response.output_item.done
   1.6s response.output_item.added
   1.6s response.content_part.added
   2.1s response.audio.done
   2.1s response.content_part.done
   2.1s response.output_item.done
   2.1s response.done completed
assistant said: I am an AI model built to help with this conversation.
no more events within the idle window
session.created events seen: 1

string modalities

  1. Run the client
$ SESSION='{"modalities": "text"}' IDLE_SECONDS=8 python realtime_client.py 51321 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.1s error {"code": "invalid_type", "param": "session.modalities", "message": "Invalid type for 'session.modalities': Bedrock Nova Sonic needs a list of strings there. Set drop_params to drop it instead"}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.

string input rate, then audio

  1. Run the client
$ SESSION='{"input_sample_rate_hertz": "16000"}' IDLE_SECONDS=8 python realtime_client.py 51321 nova-sonic-qa settings-then-audio
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.1s error {"code": "invalid_type", "param": "session.input_sample_rate_hertz", "message": "Invalid type for 'session.input_sample_rate_hertz': Bedrock Nova Sonic needs a number there. Set drop_params to drop it instead"}
no more events within the idle window
session.created events seen: 1

tools object

  1. Run the client
$ SESSION='{"tools": {"type": "function", "name": "lookup"}}' python realtime_client.py 51321 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.1s error {"code": "invalid_type", "param": "session.tools", "message": "Invalid type for 'session.tools': Bedrock Nova Sonic needs a list there. Set drop_params to drop it instead"}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.1s response.created
   1.1s response.output_item.added
   1.1s response.content_part.added
   1.1s response.text.done
   1.1s response.content_part.done
   1.1s response.output_item.done
   1.2s response.output_item.added
   1.3s response.content_part.added
   1.8s response.audio.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.8s response.done completed
assistant said: I am an AI model built to help with this conversation.

OpenAI voice name

  1. Run the client
$ SESSION='{"voice": "alloy"}' python realtime_client.py 51321 nova-sonic-qa object-settings
  1. Observed
   0.8s session.created {"instructions": null, "voice": null}
   0.8s error {"code": "invalid_value", "param": "session.voice", "message": "Invalid value for 'session.voice': 'alloy' is not a Bedrock Nova Sonic voice. Set drop_params to drop it instead"}
   1.3s input_audio_buffer.speech_started
   1.6s input_audio_buffer.speech_stopped
   1.6s conversation.item.input_audio_transcription.completed
   1.8s response.created
   1.8s response.output_item.added
   1.8s response.content_part.added
   1.8s response.text.done
   1.8s response.content_part.done
   1.8s response.output_item.done
   1.9s response.output_item.added
   1.9s response.content_part.added
   2.5s response.audio.done
   2.5s response.content_part.done
   2.5s response.output_item.done
   2.5s response.done completed
assistant said: I am an AI model built to help with this conversation.

output format object

  1. Run the client
$ SESSION='{"output_audio_format": {"type": "audio/pcmu"}}' python realtime_client.py 51321 nova-sonic-qa object-settings
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   0.1s error {"code": "invalid_type", "param": "session.output_audio_format", "message": "Invalid type for 'session.output_audio_format': Bedrock Nova Sonic needs a string there. Set drop_params to drop it instead"}
   0.6s input_audio_buffer.speech_started
   1.0s input_audio_buffer.speech_stopped
   1.0s conversation.item.input_audio_transcription.completed
   1.2s response.created
   1.2s response.output_item.added
   1.2s response.content_part.added
   1.2s response.text.done
   1.2s response.content_part.done
   1.2s response.output_item.done
   1.3s response.output_item.added
   1.3s response.content_part.added
   1.9s response.audio.done
   1.9s response.content_part.done
   1.9s response.output_item.done
   1.9s response.done completed
assistant said: I am an AI model built to help with this conversation.

refused stream, OpenAI fallback

  1. Run the client
$ IDLE_SECONDS=10 ANSWER_SECONDS=30 python realtime_client.py 51321 nova-unavailable-x idle
  1. Observed
   0.7s session.created {"instructions": null, "voice": null}
   1.2s session.created {"instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you\u2019re asked about them.", "voice": null}
   1.2s conversation.item.added
   1.2s conversation.item.done
   1.2s response.created
   1.5s response.output_item.added
   1.5s conversation.item.added
   1.5s response.content_part.added
   2.6s response.output_audio.done
   2.6s response.output_audio_transcript.done
   2.6s response.content_part.done
   2.6s conversation.item.done
   2.6s response.output_item.done
   2.6s response.done completed
assistant said: I’m ChatGPT, a friendly AI voice here to help you think, create, and chat.
   2.6s rate_limits.updated
no more events within the idle window
session.created events seen: 2

refused stream, spoken question

  1. Run the client
$ IDLE_SECONDS=3 ANSWER_SECONDS=30 python realtime_client.py 51321 nova-unavailable audio-question
  1. Observed
   0.1s session.created {"instructions": null, "voice": null}
   3.1s input_audio_buffer.speech_started
   3.1s input_audio_buffer.speech_stopped
   3.1s conversation.item.input_audio_transcription.completed
   3.1s response.created
   3.1s response.output_item.added
   3.1s response.content_part.added
   3.1s response.text.done
   3.1s response.content_part.done
   3.1s response.output_item.done
   3.1s response.output_item.added
   3.1s response.content_part.added
   3.1s response.audio.done
   3.1s response.content_part.done
   3.1s response.output_item.done
   3.1s response.done completed
assistant said: I am an AI model built to help with this conversation.
no more events within the idle window
session.created events seen: 1

Surprises

  • A dropped Bedrock connection closes 1000, no error. Left alone
/live-pr-risk at d847b20

87 cells ran on base ee4860dd84 and head d847b20eee in parallel, each with 2 uvicorn workers, its own Postgres database, and real Bedrock amazon.nova-2-5-sonic and amazon.nova-2-sonic-v1:0, OpenAI gpt-realtime-2.1 and Gemini gemini-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 ran

Breaking

B1. Without drop_params, base acked a non-string instructions (list or int), an object, int or list input_audio_format, a string tools and a non-numeric sample rate, and the session went on. Head answers invalid_type and applies nothing from that update. With drop_params head drops the field and answers like base. Approved by @mateo-berri as the standing drop_params rule 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 note

Cell Sent Base Head
S02 object input_audio_format acked, answered invalid_type, answered
S04 list instructions pirate answer invalid_type, plain answer
S05 int instructions acked invalid_type

B2. 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_params an OpenAI voice name drops to matthew, where base sent it and closed 1011

Regression 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

Dependent Status
Bedrock session.update checks live
Replay to Bedrock, OpenAI, Gemini live
Guardrail on the replay live
Committed refusal on fallback live
Same-deployment retry unit only
OpenAI, Gemini direct live
Dashboard Playground payload live payload
Azure, xAI, Vertex, Meta fallback untested
/v1/live/sessions unit only
Spend logging live

Not 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_params from a user agent or router defaults. Python 3.10 and 3.11

Found and left alone, both sides: Bedrock realtime client frames skip realtime guardrails (O11), and a direct Gemini session drops a session.update sent after session.created (C05). Each has its own follow-up

Audit round 1 of 3

Node ids are relative to tests/integration/providers/. The file test_bedrock_nova_sonic_realtime_tool_calls.py is written as nova::, and test_realtime_unguarded_voice_turns.py is written as voice::. Head results cover two runs with the same seeds

id contract cell base head result last ran
R1 refused text opening, Bedrock fallback nova::test_refused_opening_is_replayed_on_the_bedrock_fallback[text-first] red green x2 PASS d847b20
R2 refused session.update, Bedrock fallback nova::...[session-update-first] green green x2 PASS d847b20
R3 refused text opening, OpenAI fallback nova::test_refused_text_opening_is_replayed_on_the_openai_fallback red green x2 PASS d847b20
R4 committed stream fails, no second provider nova::test_committed_session_failure_closes_the_socket_without_another_provider_stream red green x2 PASS d847b20
R5 OpenAI frames unchanged voice::test_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_frames[/v1/realtime] ctl green PASS d847b20
R6 OpenAI SDK frames unchanged voice::test_openai_sdk_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_frames[async] ctl green PASS d847b20
R7 Azure frames unchanged voice::test_azure_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_frames ctl green PASS d847b20
R8 xAI frames unchanged voice::test_xai_push_to_talk_turn_reaches_the_upstream_as_the_clients_own_frames ctl green PASS d847b20
R9 Vertex live frames unchanged voice::test_vertex_live_voice_turn_sends_the_upstream_only_the_setup_and_the_audio ctl green PASS d847b20
R10 Bedrock tool calls still flow 9 existing nova:: cells green green x2 PASS d847b20
R11 voice object refused, never sent nova::test_voice_object_is_refused_and_never_reaches_bedrock red green x2 FAIL, approved d847b20
L1 real refusal, OpenAI fallback live/.../L1_*.txt no answer answered PASS d847b20
L2 real mid-call failure after commit live/.../L2_*.txt silent failover error, 1011 PASS d847b20
L3 OpenAI voice name with instructions live/.../L3_*.txt ack, then 1011 invalid_value FAIL, approved d847b20
U1 type and voice predicates test_bedrock_realtime_transformation.py n/a green unit evidence d847b20
U2 handler replay and rejection test_bedrock_realtime_handler.py n/a green unit evidence d847b20
U3 shared opening-message pop test_realtime_streaming.py n/a green unit evidence d847b20

The 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_response and test_malformed_tool_content[empty|missing|not-json|five-kb]. The nested cell's green comes from the *-nested lanes after its stale tail was fixed. The other 8 are green in base, head-1 and head-2

Base reds, all as the inventory expected. In R1 the client got a second session.created from the fallback attempt. In R3 the lane timed out with only session.created, because the OpenAI upstream never received the opening conversation.item.create. In R4 the client got a second session.created from a fallback that opened a new provider session. In R11 the voice object got session.updated and no invalid_type error. On the head, the proxy log head-1/gw1/owned-proxy-4720d5f88faa474cb65f39a71b496d30.log holds the guard refusal "already committed to a provider stream; it cannot be replayed. The committed stream failed with: ModelStreamErrorException" for R4

Live rows, real vendors (AWS Bedrock Nova Sonic amazon.nova-2-5-sonic and a deliberately unknown id amazon.nova-sonic-not-enabled-v9:0, then OpenAI gpt-realtime-2.1 as the fallback target).

L1 base got two session.created and 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 OpenAI

L2 base answered on Bedrock. After the bad audio chunk it then failed over to OpenAI, and the client saw a second session.created that carried OpenAI's default instructions. L2 head answered on Bedrock. After the bad chunk the client got error "ValidationException: Unable to parse input chunk ..." and a 1011 close, with one session.created

L3 sends {"voice": "alloy", "instructions": "Always start your answer with the word Ahoy."}. L3 base acked it with session.updated, then real Bedrock answered "ValidationException ... Received invalid id: 'alloy'", and the socket closed with 1011. L3 head answered error with code invalid_value on param session.voice and sent no session.updated. The session stayed open and answered the next question on Bedrock's defaults. The instructions were not applied, since the whole update was refused

R11 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 standing drop_params rule of 2026-10-02, where an unsupported or malformed value drops under drop_params and answers 400 without it, like o-series temperature

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • No live run of a same-deployment retry, which no live 400 triggers. A unit test covers it

Low

  • Malformed tools entries, like ["lookup"], still pass or drop silently, as before, a separate follow-up
  • An unknown voice, like nova or alloy, is acked, then closes 1011, as before
  • GA session.audio.output.voice is still ignored, as before, a separate follow-up
  • A refused fallback logs a failure on the fallback deployment, without a cooldown
  • A refused stream after an input pause sends a second session.created, as before
  • Handler unit tests monkeypatch provider singletons

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
Bugbot summary

[!NOTE]
High Risk
Changes Bedrock realtime session validation (breaking without drop_params), websocket replay/commit semantics, and blocks all fallback retries after a committed stream—core proxy realtime routing behavior.

Overview
Breaking: Nova Sonic session.update with malformed settings (wrong types, object voice, OpenAI voice names like alloy) now returns invalid_type / invalid_value errors instead of session.updated, unless drop_params drops the bad fields. After Bedrock has accepted a stream, retries and cross-provider fallbacks on the same websocket are refused with 400 / 1011 instead of silently starting a second session.

Bedrock realtime now treats the first client message that opens the provider stream (session update or user input) as a pending opening message stored on the websocket scope until await_output() succeeds, then marks the session committed. Fallbacks and RealTimeStreaming replay that message once so refused or input-first starts are not lost.

Handler flow splits session ack from stream readiness (_send_opening_message), renames the scope key to BEDROCK_REALTIME_PENDING_OPENING_MESSAGE_SCOPE_KEY, and tightens BedrockRealtimeConfig validation across instructions, voice, tools, modalities, audio formats, and sample rates. Integration/unit tests cover Bedrock→Bedrock/OpenAI replay and mid-call failure without a second upstream connection.

Reviewed by Cursor Bugbot for commit fe90289. Bugbot is set up for automated code reviews on this repo. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@codspeed

codspeed Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_bedrock_nova_sonic_realtime_replay_guard (fe90289) with main (9aab6ec)

Open in CodSpeed

@litereview

litereview Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

I traced the new session.update checks from _forward_client_to_bedrock through session_update_rejection and _apply_locked_settings, with and without drop_params. I also traced the opening-message scope key from _send_opening_message to a Bedrock fallback (_pending_opening_message) and to a non-Bedrock fallback (RealTimeStreaming._receive_client_message), plus the commit guard in _arealtime. The PR title carries ! and explains the breaking change and how to migrate.

Checks and execution details
  • Passed · real-testing-evidence (required): litellm/llms/bedrock/realtime/transformation.py and handler.py change how OpenAI session.update translates to Bedrock, so this rule applies.

Manual E2E evidence (in the PR description):

  • The runs used real Bedrock amazon.nova-2-5-sonic and real OpenAI gpt-realtime-2.1, going through wss://.../v1/realtime on a 2-worker proxy. Each case lists its config, client scripts, commands and observed frames, for base ee4860dd84 and head d847b20eee.
  • The GitHub compare API shows that d847b20eee...fe902891d9 touches only tests/integration/_support/bedrock_realtime_peer.py and the integration test file. The live evidence therefore covers the reviewed product code.
  • The live cases cover:
    • a voice object (raw websocket and SDK)
    • an instructions object
    • drop_params with both objects
    • string modalities
    • a string input sample rate
    • a tools object
    • the OpenAI voice name alloy
    • an output format object
    • refused-stream replay to a Bedrock fallback, to an OpenAI fallback, and with a spoken question
    • committed-stream failure with Bedrock and OpenAI fallbacks
  • The string controls show that valid settings still apply.

Integration tests (executed):

  • Command: INTEGRATION_WORKERS=2 python tests/integration/run.py providers tests/integration/providers/test_bedrock_nova_sonic_realtime_tool_calls.py, with local Postgres and Redis and prisma generate.
  • Result: 14 passed.
  • The new cells cover:
    • replay on the Bedrock fallback, session-update-first and text-first
    • replay on the OpenAI fallback
    • a committed failure that leaves no second provider stream and closes 1011
    • a voice object that is refused and never reaches the peer
  • These tests use a scripted peer, so the live manual evidence above is what passes this gate.
  • Passed · compatibility-notice (required): Two real incompatibilities exist:
  1. Without drop_params, a Nova Sonic session.update with a malformed setting used to get session.updated. For example, list instructions, an object input_audio_format, or a string tools. Now it gets invalid_type and nothing from the update applies. OpenAI voice names such as alloy now get invalid_value.
  2. With a fallback configured, a committed Bedrock stream that fails used to open a new provider session silently. Now it sends error and closes 1011. Later _arealtime attempts on that websocket get a 400.

The title fix(bedrock)!: carries the breaking marker. The description's Breaking change paragraph gives both impacts and the drop_params: true migration.

  • Passed · behavioral-coverage (required): I read tests/integration/AGENTS.md and tests/integration/README.md.

Paths traced:

  • _forward_client_to_bedrock: session_update_rejection, then _reject_session_update or transform_realtime_request, then _send_opening_message (sets the scope key, sends, await_output, pops the key, sets committed), then _ack_session_update.
  • Bedrock fallback: _pending_opening_message raises when committed. Otherwise _run_session skips session.created and replays through _client_messages.
  • Non-Bedrock fallback: RealTimeStreaming._receive_client_message pops the kept message.
  • _arealtime calls raise_if_session_committed(client_websocket_scope(websocket)).

Boundary cases checked:

  • With drop_params, each malformed field falls back to its base value. The isinstance checks in _apply_locked_settings and transform_session_update_event handle tools, instructions, voice, the formats and the input rate.
  • A rejected opening update is never sent to Bedrock and is never stored as pending.
  • A client frame sent while await_output blocks stays in the socket buffer, so a fallback reads it next.
  • A websocket without scope gets None from the guard, so it is a no-op there.

Unit tests run: pytest tests/unit/llms/bedrock/realtime tests/unit/litellm_core_utils/test_realtime_streaming.py tests/unit/llms/xai/test_xai_key_fallback.py tests/unit/realtime_api gave 392 passed.

No unresolved defects remain to reconcile.


View review · Reviewed fe902891d977

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Critical impact] The PR appears safe to merge, with the previous notice finding addressed and no new actionable issues found

Summary

This 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

  • A refused Bedrock stream leaves its opening message ready for another attempt.
  • Nova Sonic session updates reject malformed settings before applying them.
  • A failed committed Bedrock session cannot start another provider session.

Reviews (6) · Last reviewed commit: "test(bedrock): cover realtime replay, re..." · Reviewed by Greptile

@codecov

codecov Bot commented Oct 16, 2026

Copy link
Copy Markdown

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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

Comment thread litellm/realtime_api/main.py Outdated

For PROXY use only.
"""
raise_if_session_committed(websocket.scope)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium · Realtime commit guard breaks the xAI realtime unit tests in CI

  1. tests/unit/llms/xai/test_xai_key_fallback.py calls realtime_main._arealtime(..., websocket=object()) in three tests. These tests check xAI key resolution, and the object() websocket has no scope attribute.
  2. This PR adds raise_if_session_committed(websocket.scope) as the first line of _arealtime. That line runs before provider dispatch.
  3. The guard raises AttributeError: 'object' object has no attribute 'scope' before xai_realtime.async_realtime runs, so all three tests fail.
  4. CI runs these tests through tests/unit/llms/xai in .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

@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

…ject OpenAI voices and non-string audio formats
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

…and reject any-case OpenAI and empty Bedrock voices
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri mateo-berri changed the title fix(bedrock): block realtime replay after an input-first start and reject non-string instructions and voice fix(bedrock)!: block realtime replay after an input-first start and reject non-string instructions and voice Oct 16, 2026
@mateo-berri mateo-berri changed the title fix(bedrock)!: block realtime replay after an input-first start and reject non-string instructions and voice fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings Oct 16, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

litellm-stampbot Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at fe90289.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.22 (high at or above 0.75)

  • risk: low (probability of high 0.22)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 17, 2026

@kerry-berri kerry-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low risk by rule and by judgement at fe90289

@mateo-berri
mateo-berri merged commit 3ef0b35 into main Oct 17, 2026
93 checks passed
@mateo-berri
mateo-berri deleted the litellm_bedrock_nova_sonic_realtime_replay_guard branch October 17, 2026 00:29
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants