Skip to content

Streaming responses silently turn unserialisable events into JSON strings of their Python repr #659

Open

Description

@surecloud-jleite

Describe the bug

When an entrypoint generator yields an object that json.dumps cannot serialise, BedrockAgentCoreApp._safe_serialize_to_json_string (runtime/app.py line 898 in 1.22.0) tries convert_complex_objects and then falls back to json.dumps(str(obj)). convert_complex_objects (runtime/utils.py) handles Pydantic models, dataclasses, dicts, lists, tuples and sets but not bytes, so any event that contains binary data anywhere in its tree reaches the third fallback. The SSE data: line then carries a JSON string holding the Python repr of the dictionary, for example "{'result': {'type': 'agent_result', 'message': {... b'rsn_...'}}}", rather than a JSON object or an error.

The client cannot tell this apart from a legitimate string event, and it cannot recover the original payload from the repr. In our case a supervisor agent consuming a sub-agent's stream did event.get("error") on what was now a str and failed with AttributeError: 'str' object has no attribute 'get', turning every affected turn into a user-facing failure. Nothing was logged on the producing side, because the fallback succeeds.

To Reproduce

  1. Write a streaming entrypoint whose generator yields a dictionary containing a bytes value somewhere inside it. A real-world source is the AgentResult.to_dict() from Strands when the model returns a reasoningContent.redactedContent block, which OpenAI GPT-5.6 Luna on Bedrock does after tool calls. Any other bytes value in a yielded event, such as image or document source.bytes from a tool result, takes the same path.
  2. Invoke the runtime and read the SSE stream.
  3. Observe that the event arrives as data: "{'result': ...}" (a JSON string) instead of data: {"result": ...}.

Expected behavior

One of:

  • binary values are converted to something JSON can carry (for example base64), or
  • the event is replaced by an explicit error event, as _stream_with_error_handling already does for exceptions, and a warning is logged.

Either way the consumer should never receive a Python repr as the payload.

Additional context

Activity

  1. added
    bug
    on Sep 4, 2026
  2. kimnamu commented on Sep 22, 2026

    @kimnamu

    Thanks for the careful report, and for tracing the SSE payload all the way down to the third fallback in _safe_serialize_to_json_string; that made this quick to confirm.

    Reproduced on main (889615f, v1.23.1) with the Starlette TestClient. runtime/utils.py and runtime/app.py are unchanged between v1.22.0 and main, so the released versions behave the same. The cause is that convert_complex_objects (src/bedrock_agentcore/runtime/utils.py:7-35) has no branch for bytes, so the second attempt's json.dumps raises TypeError and app.py:919 json.dumps(str(obj)) succeeds without logging. Adding a bytes branch next to the existing set branch (base64, the same choice strands-agents/harness-sdk#4313 made for AgentResult.to_dict()) turns the event back into a JSON object, and the existing runtime tests stay green.

    main 889615f with the branch below
    SSE data: line "{'result': {... b'rsn_abc'}}}" (JSON string of the repr) {"result": {... "redactedContent": "cnNuX2FiYw=="}}
    Consumer side json.loads(...) str, then AttributeError: 'str' object has no attribute 'get' dict
    Producer side log nothing (third fallback succeeds) nothing needed (second attempt succeeds)
    runtime/test_utils.py + runtime/test_app.py 165 passed 166 passed (incl. new regression test)

    Repro (repro.py, no AWS credentials needed):

    import json
    from starlette.testclient import TestClient
    from bedrock_agentcore import BedrockAgentCoreApp
    
    app = BedrockAgentCoreApp()
    
    @app.entrypoint
    def handler(payload):
        yield {"result": {"message": {"content": [{"reasoningContent": {"redactedContent": b"rsn_abc"}}]}}}
    
    client = TestClient(app)
    with client.stream("POST", "/invocations", json={}) as r:
        raw = b"".join(r.iter_bytes()).decode()
    
    print("raw SSE:", raw.strip())
    data = json.loads(raw.split("data: ", 1)[1])
    print("type after json.loads:", type(data).__name__)
    try:
        print("event.get('error') ->", data.get("error"))
    except AttributeError as e:
        print("AttributeError:", e)

    Output on main:

    raw SSE: data: "{'result': {'message': {'content': [{'reasoningContent': {'redactedContent': b'rsn_abc'}}]}}}"
    type after json.loads: str
    AttributeError: 'str' object has no attribute 'get'
    

    Minimal fix, mirroring the sibling branches in convert_complex_objects:

    --- a/src/bedrock_agentcore/runtime/utils.py
    +++ b/src/bedrock_agentcore/runtime/utils.py
    @@ -1,5 +1,6 @@
     """Bedrock AgentCore runtime utilities for object conversion and serialization."""
     
    +import base64
     from dataclasses import asdict, is_dataclass
     from typing import Any
     
    @@ -30,6 +31,10 @@ def convert_complex_objects(obj: Any, _depth: int = 0) -> Any:
         elif isinstance(obj, set):
             return [convert_complex_objects(item, _depth + 1) for item in obj]
     
    +    # Handle binary data (e.g. Converse reasoningContent.redactedContent, image/document source.bytes)
    +    elif isinstance(obj, (bytes, bytearray)):
    +        return base64.b64encode(obj).decode("ascii")
    +
         # Return primitives as-is
         else:
             return obj

    Same script after the patch:

    raw SSE: data: {"result": {"message": {"content": [{"reasoningContent": {"redactedContent": "cnNuX2FiYw=="}}]}}}
    type after json.loads: dict
    event.get('error') -> None
    
    Regression test (red on main, green with the branch), ruff, and notes on the alternatives

    Added next to test_sets in tests/bedrock_agentcore/runtime/test_utils.py (plus import json at the top):

        def test_bytes_are_base64_encoded(self):
            """Bytes nested in an event must become a JSON-carriable string, not fall through to repr."""
            result = convert_complex_objects({"reasoningContent": {"redactedContent": b"rsn_abc"}})
    
            assert result == {"reasoningContent": {"redactedContent": "cnNuX2FiYw=="}}
            json.dumps(result)
            assert convert_complex_objects(bytearray(b"\x00\xff")) == "AP8="
    # main
    E       AssertionError: assert {'reasoningCo...: b'rsn_abc'}} == {'reasoningCo...nNuX2FiYw=='}}
    1 failed, 17 deselected
    
    # with the branch (test_utils.py + test_app.py)
    166 passed
    All checks passed!            (ruff check src tests)
    274 files already formatted   (ruff format --check src tests)
    

    Notes, in case they help with the decision:

    • The issue lists two acceptable outcomes. Base64 is the smaller change, and it also covers the non-streaming Response path at app.py:600, which goes through the same helper. The other route, dropping the json.dumps(str(obj)) attempt so the existing warning plus {"error": "Serialization failed"} fallback fires, would also change the datetime/Decimal/frozenset results that test_safe_serialize_fallback_to_string currently expects as str(obj).
    • Encoding shape: this uses a plain base64 string. Strands' session encoder (strands/types/session.py) wraps it as {"__bytes_encoded__": true, "data": ...} so consumers can decode it back; if that shape is preferred here, it is a one-line change in the same branch.
    • Strands side: fix(agent): make AgentResult.to_dict JSON-serializable with bytes strands-agents/harness-sdk#4313 (merged 2026-09-14) makes AgentResult.to_dict() encode bytes itself, so the redactedContent trigger goes away once agents pick up that release. Other bytes in a yielded event, such as image or document source.bytes in a tool result, still reach this fallback, so the SDK-side branch seems useful regardless.

    If a PR is welcome for this despite the current external-PR policy, I can open one with the diff and test above; otherwise please feel free to take it as-is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions