Skip to content

Strands session manager restores an empty history when the session has one plain text conversational event #743

Open

Description

@abhiramshaji-cyber

Hi team, hope you're doing well!

Describe the bug

One conversational event whose text isn't a serialized SessionMessage makes AgentCoreMemorySessionManager.list_messages return [], so a restored Strands agent starts with no history at all.

For context, AgentCoreMemoryConverter.events_to_messages is what turns the events stored in AgentCore Memory back into Strands SessionMessages when an agent is restored, so it decides what history the agent wakes up with.

To Reproduce

  1. A session's (memory_id, actor_id, session_id) stream holds the session manager's own events plus one conversational event with plain text, like {"conversational": {"role": "USER", "content": {"text": "I prefer window seats"}}}.
  2. The agent is restored: initialize calls RepositorySessionManager.initialize, which calls list_messages (session_manager.py L1020 to L1027).
  3. list_messages passes every listed event to the converter (session_manager.py L795 to L814).
  4. The conversational branch calls SessionMessage.from_dict(json.loads(conv["content"]["text"])) with no try around it (bedrock_converter.py L79 to L84), so the plain text raises JSONDecodeError.
  5. list_messages catches it, logs Failed to list messages from AgentCore Memory: Expecting value: line 1 column 1 (char 0) and returns [].
  6. The agent starts with an empty history, even though every other event in the session was valid.

Expected behavior

The one event that isn't a SessionMessage gets skipped (with a log line), and the rest of the history is restored. That's how the blob branch right below already behaves (bedrock_converter.py L85 to L97), and the OpenAI converter does the same per event for conversational payloads (converters/openai.py L163 to L169). Both of those handle it really nicely, which is part of why this one stood out to me.

Minimal repro

Mocked MemoryClient, no AWS needed. Tested on main at fda8209 (1.26.0) with strands-agents 1.56.0:

import json
from unittest.mock import patch

from strands.types.session import SessionMessage

from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig
from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager


def stored(role, text, index):
    msg = SessionMessage(message={"role": role, "content": [{"text": text}]}, message_id=index)
    return {"payload": [{"conversational": {"role": role.upper(), "content": {"text": json.dumps(msg.to_dict())}}}]}


def plain(role, text):
    return {"payload": [{"conversational": {"role": role, "content": {"text": text}}}]}


config = AgentCoreMemoryConfig(memory_id="mem", session_id="sess", actor_id="actor")
with patch("bedrock_agentcore.memory.integrations.strands.session_manager.MemoryClient") as client, patch("boto3.Session"):
    client.return_value.list_events.return_value = []
    manager = AgentCoreMemorySessionManager(config)

history = [stored("assistant", "hi there", 1), stored("user", "hello", 0)]

manager.memory_client.list_events.return_value = history
print("session manager events only:", len(manager.list_messages("sess", "agent")))

manager.memory_client.list_events.return_value = [plain("USER", "I prefer window seats")] + history
print("plus one plain text event:", len(manager.list_messages("sess", "agent")))

Output:

session manager events only: 2
Failed to list messages from AgentCore Memory: Expecting value: line 1 column 1 (char 0)
plus one plain text event: 0
flowchart TD
    A["initialize"] --> B["RepositorySessionManager.initialize"]
    B --> C["list_messages"]
    C --> D["events_to_messages"]
    D --> E{"conversational text is a SessionMessage?"}
    E -- yes --> F["message restored"]
    E -- no --> G["JSONDecodeError"]
    G --> H["list_messages catches it and returns an empty list"]
    H --> I["agent restored with no history"]
Loading

Environment

  • bedrock-agentcore: main at fda8209 (1.26.0)
  • strands-agents: 1.56.0
  • Python 3.10, macOS

Additional context

Where plain text conversational events can come from: a few writers in this SDK put them into the same kind of stream, like the AgentCoreMemoryStore sender (memorystore/sender.py L218 to L242, and the MemoryStore README describes that stream as shared), MemoryClient.save_conversation and MemorySession.add_turns. To be fair, I didn't find a doc example that uses the session manager and MemoryStore on the same session, so this may be a less common setup. It still felt worth raising since one event wipes everything, and the docstring example on events_to_messages itself is a plain text event (bedrock_converter.py L54 to L71).

Related but I think different: #564 (eventual consistency), #346 and #347 (pagination), #723 (OpenAI converter tool results).

Suggested fix: wrap the conversational branch in a try / except (json.JSONDecodeError, KeyError, ValueError), like the blob branch's except (json.JSONDecodeError, ValueError), log it and continue, so one odd event is skipped instead of taking the whole history with it.

Does that sound like the right approach to you, or would you rather filter these events earlier in list_messages (or raise instead of returning [])? I saw the repo isn't taking external PRs right now, but if a PR would ever help, I'd be happy to send one. Thanks so much for all the work on this SDK!

Activity

  1. added
    bug
    on Nov 17, 2026
  2. kimnamu commented on Nov 19, 2026

    @kimnamu

    Appreciate the no-AWS repro. It runs unchanged on main (c629a24, 1.26.1) and still prints plus one plain text event: 0.

    The suggested except (json.JSONDecodeError, KeyError, ValueError) skips the sentence, but a reply like 3 or null is valid JSON, reaches SessionMessage.from_dict (it calls env.items()) and raises AttributeError. A JSON object such as {"note": "x"} raises TypeError for the missing message and message_id. Both land in the except Exception in list_messages (L812-L814), so the history comes back empty. The OpenAI converter returns nothing for these inputs without raising; its isinstance(openai_msg, dict) check (openai.py L180) is what stops 3 and null. Adding the two types closes it:

    --- a/src/bedrock_agentcore/memory/integrations/strands/bedrock_converter.py
    +++ b/src/bedrock_agentcore/memory/integrations/strands/bedrock_converter.py
    @@ -78,7 +78,11 @@ class AgentCoreMemoryConverter:
                 for payload_item in event.get("payload", []):
                     if "conversational" in payload_item:
                         conv = payload_item["conversational"]
    -                    session_msg = SessionMessage.from_dict(json.loads(conv["content"]["text"]))
    +                    try:
    +                        session_msg = SessionMessage.from_dict(json.loads(conv["content"]["text"]))
    +                    except (json.JSONDecodeError, KeyError, ValueError, TypeError, AttributeError):
    +                        logger.error("This is not a SessionMessage but just a conversational message. Ignoring")
    +                        continue
                         session_msg.message = AgentCoreMemoryConverter._filter_empty_text(session_msg.message)
                         if session_msg.message.get("content"):
                             messages.append(session_msg)
    --- a/tests/bedrock_agentcore/memory/integrations/strands/test_bedrock_converter.py
    +++ b/tests/bedrock_agentcore/memory/integrations/strands/test_bedrock_converter.py
    @@ -3,6 +3,7 @@
     import json
     from unittest.mock import patch
     
    +import pytest
     from strands.types.session import SessionMessage
     
     from bedrock_agentcore.memory.integrations.strands.bedrock_converter import AgentCoreMemoryConverter
    @@ -343,6 +344,19 @@ class TestAgentCoreMemoryConverter:
             assert result[0].message["content"][0]["text"] == "First"
             assert result[1].message["content"][0]["text"] == "Second"
     
    +    @pytest.mark.parametrize("text", ["I prefer window seats", "3", '{"note": "x"}'])
    +    @patch("bedrock_agentcore.memory.integrations.strands.bedrock_converter.logger")
    +    def test_events_to_messages_plain_text_conversational_does_not_break_batch(self, mock_logger, text):
    +        """A conversational payload that is not a SessionMessage is skipped, not fatal."""
    +        msg = SessionMessage(message_id=1, message={"role": "user", "content": [{"text": "msg1"}]})
    +        valid = {"conversational": {"content": {"text": json.dumps(msg.to_dict())}, "role": "USER"}}
    +        plain = {"conversational": {"content": {"text": text}, "role": "USER"}}
    +
    +        result = AgentCoreMemoryConverter.events_to_messages([{"payload": [plain, valid]}])
    +
    +        assert [m.message["content"][0]["text"] for m in result] == ["msg1"]
    +        mock_logger.error.assert_called()
    +
         @patch("bedrock_agentcore.memory.integrations.strands.bedrock_converter.logger")
         def test_events_to_messages_malformed_payload_does_not_break_batch(self, mock_logger):
             """Test a malformed blob payload between two valid conversational payloads in a single event."""

    The test fails 3/3 on main, 2/3 with the narrower tuple, and passes with the patch. tests/bedrock_agentcore/memory: 798 passed, ruff clean. Per-event skip versus filtering in list_messages is the team's call; if they want a PR, it's yours, and the test is there to reuse.

  3. abhiramshaji-cyber commented on Nov 20, 2026

    @abhiramshaji-cyber
    ContributorAuthor

    Hey @kimnamu, hope you're doing well, and thank you so much for this! Running the repro on main at c629a24 and tracing 3, null and {"note": "x"} through from_dict showed exactly where my suggested tuple fell short, and I really appreciate you writing the diff and the test too.

    Since the issue was still open, I went ahead and opened #749 so the team has something concrete to look at. It adopts your wider handling and reuses your parametrized test with credit to you in the commit and the PR. I extended the test a bit to cover a few more stored shapes and the blob branch, since it had the same gap.

    Does that look right to you? And to the maintainers, I kept it as a per payload skip like the blob branch and the OpenAI converter already do, but if you'd rather filter earlier in list_messages or raise instead, I'm glad to change it. Happy to hear what everyone thinks.

  4. kimnamu commented on Nov 20, 2026

    @kimnamu

    Extending the test into the blob branch found a gap I hadn't looked at, so thank you for that. #749 looks right to me. At its head (9259dcb) the new cases fail 29/31 on main and pass on the branch, memory tests pass (826), ruff is clean, and 13 message shapes written through message_to_payload (tool use, media bytes, redactedContent, a >100k blob, with and without redact_message) restore identically to main.

    One thing in the diff: the outer blob except now also catches dict blobs (the shape in create_blob_event's docstring example), but that line still logs payload_item, so the blob content lands in the ERROR log. Logging the event id like your new line avoids that; strands tests still pass (441):

    logger.error("Failed to parse blob content in event %s", event.get("eventId"))

    Separately, with converter=OpenAIConverseConverter, list_messages still comes back empty for a dict blob, [3, 4] and the deep-nesting text, on main and on #749. That seems fine as a follow-up.

  5. abhiramshaji-cyber commented on Nov 20, 2026

    @abhiramshaji-cyber
    ContributorAuthor

    Hey @kimnamu, thank you so much for testing #749 this thoroughly! Checking 13 real message shapes through message_to_payload against main is exactly the kind of check I was hoping someone would do, and it's really reassuring.

    Great catch on the blob log line too. You're right that the outer except now sees dict blobs, so logging payload_item would put their content in the ERROR log. I switched it to log only the event id like you suggested and pushed that to #749 in 8da4271, with a test that checks neither a dict blob nor a non JSON string blob shows up in the log.

    On the OpenAIConverseConverter point, I reproduced it on current main: a dict blob and [3, 4] both raise TypeError out of events_to_messages, and the deeply nested text raises RecursionError, so list_messages drops the whole history, valid messages included. Since #749 doesn't touch that converter, it behaves the same there. I agree it fits better as its own follow up, so I opened #751 for it. That converter's blob except also logs the whole payload_item, so I noted that there too.

    Does that sound good to you? And maintainers, if you'd rather have both converters handled in one PR, I'm happy to fold it in instead.

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