Skip to content

fix(memory): skip stored events that are not a SessionMessage on restore - #749

Open
abhiramshaji-cyber wants to merge 3 commits into
aws:mainfrom
abhiramshaji-cyber:fix/strands-skip-non-session-conversational
Open

abhiramshaji-cyber wants to merge 3 commits into
aws:mainfrom
abhiramshaji-cyber:fix/strands-skip-non-session-conversational

Conversation

@abhiramshaji-cyber

@abhiramshaji-cyber abhiramshaji-cyber commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #743

A Strands agent restored from AgentCore Memory came back with no history at all when one stored event was not a SessionMessage, and now only that one event is skipped.

What this code is for

AgentCoreMemorySessionManager.list_messages reads the session's events from AgentCore Memory and hands them to AgentCoreMemoryConverter.events_to_messages, which turns each conversational or blob payload back into a Strands SessionMessage. RepositorySessionManager.initialize calls this when an agent starts, so it decides which history the agent starts with.

Before this PR

A developer runs a Strands agent with AgentCoreMemorySessionManager, and the same session also holds one plain text conversational event, for example one written by MemoryClient.save_conversation or the AgentCoreMemoryStore sender.

  1. The agent starts and initialize calls list_messages.
  2. list_messages passes every event to events_to_messages (session_manager.py L804).
  3. The conversational branch runs SessionMessage.from_dict(json.loads(conv["content"]["text"])) with no try around it (bedrock_converter.py L79 to L84):
    if "conversational" in payload_item:
        conv = payload_item["conversational"]
        session_msg = SessionMessage.from_dict(json.loads(conv["content"]["text"]))
  4. "I prefer window seats" raises JSONDecodeError. 3 and null parse, then from_dict calls env.items() and raises AttributeError. {"note": "x"} raises TypeError for the missing message and message_id.
  5. The except Exception in list_messages (L812 to L814) logs Failed to list messages from AgentCore Memory and returns [].
  6. The agent starts with 0 messages, even though every other event in the session was valid.

The blob branch below it only catches json.JSONDecodeError, ValueError, so a blob pair whose first entry is a number, or JSON that is not an object, empties the history the same way.

After this PR

Same developer, same session.

  1. Same as above through step 2.
  2. Both branches pass their text to one new parser, _parse_session_message. It returns None when the text is not JSON, is JSON but not an object, is missing SessionMessage fields, has bad base64 bytes, or has a message (or redact_message) that is not a Strands message: a role of user or assistant and a content list of objects whose text, if present, is a string.
  3. On None, events_to_messages logs Skipping a payload that is not a SessionMessage in event <eventId> and moves on to the next payload.
  4. Every valid event is restored as before. In the repro from Strands session manager restores an empty history when the session has one plain text conversational event #743, list_messages now returns 2 messages for each of "I prefer window seats", 3, null and {"note": "x"}, where main returned 0.

The diagram

flowchart LR

classDef box fill:#eef1ff,stroke:#4c5bd4,color:#111827
classDef bad fill:#ffd6d6,stroke:#cc0000,color:#111827,stroke-width:3px
classDef good fill:#c8f0c8,stroke:#008800,color:#111827,stroke-width:3px

subgraph BEFORE["BEFORE: one odd event, 0 messages restored"]
direction TB
  B1["agent starts, initialize"] --> B2["list_messages"]
  B2 --> B3["events_to_messages"]
  B3 --> B4{"json.loads then SessionMessage.from_dict"}
  B4 -->|"plain text, 3, null, other JSON"| B5["raises, list_messages returns empty list"]
  B4 -->|"stored SessionMessage"| B6["message restored"]
end

subgraph AFTER["AFTER: odd event skipped, every other message restored"]
direction TB
  A1["agent starts, initialize"] --> A2["list_messages"]
  A2 --> A3["events_to_messages"]
  A3 --> A4{"THE CHANGE: _parse_session_message"}
  A4 -->|"plain text, 3, null, other JSON"| A5["returns None, payload logged and skipped"]
  A4 -->|"stored SessionMessage"| A6["message restored, same as before"]
end

B1 ~~~ A1

class B1,B2,B3,B6 box
class A1,A2,A3,A6 box
class B4,B5 bad
class A4,A5 good

linkStyle 3 stroke:#cc0000,stroke-width:5px
linkStyle 8 stroke:#008800,stroke-width:5px

style BEFORE fill:#fff5f5,stroke:#cc0000,color:#111827
style AFTER fill:#f3fff3,stroke:#008800,color:#111827
Loading

The change

In bedrock_converter.py, _parse_session_message wraps json.loads and SessionMessage.from_dict in except (TypeError, ValueError, RecursionError) (JSONDecodeError and the base64 binascii.Error are both ValueError; RecursionError covers deeply nested JSON that still fits the 100000 character payload limit), rejects JSON that is not an object before from_dict sees it, and checks the message shape with _is_message. That check is what keeps a payload like {"message": {"role": "user", "content": "hi"}, "message_id": 0} from reaching _filter_empty_text and raising AttributeError there. This is the fix.

The conversational and blob branches now share that parser, so the blob branch gets the same coverage, and its outer json.loads also catches TypeError and RecursionError. Both error log lines, the skip line and the blob parse error, name the eventId instead of printing the payload, so user text does not end up in error logs. A dict blob now reaches the blob parse except, so that line matters too (thanks @kimnamu for catching it on #743).

Tests: @kimnamu's parametrized test from #743, extended to 15 shapes, each run once as a conversational payload and once as a blob payload, plus one for a blob pair whose first entry is a number. 29 of the 31 fail on main, all pass here. One more test feeds a dict blob and a non JSON string blob and checks neither value shows up in the error log. tests/bedrock_agentcore/memory 827 passed, full tests 3858 passed on 9259dcb, ruff check and ruff format --check clean.

Thanks a lot to @kimnamu for reproducing this on main, finding the 3, null and {"note": "x"} shapes my first suggested except tuple missed, and writing the test this builds on.

What changes for a user

  • A session with one plain text or foreign JSON event now restores every valid message instead of none.
  • Messages written by the session manager itself restore exactly as before, including redact_message and base64 encoded bytes.
  • The skip is per payload, matching how the blob branch and OpenAIConverseConverter.events_to_messages already behave. If you would rather filter these earlier in list_messages, or raise instead, I'm happy to change it.
  • A stored message whose role is not user or assistant is now skipped. Strands only writes those two roles, so nothing the session manager wrote is affected.

AgentCoreMemoryConverter.events_to_messages parsed every conversational
payload as a SessionMessage with no guard, so one plain text event, or any
JSON that is not a SessionMessage, raised inside list_messages and the
restored agent started with an empty history. The blob branch had the same
gap for non string entries and non object JSON.

Both branches now go through one parser that returns None for anything
that is not a SessionMessage with a Strands Message shape, and that one
payload is skipped and logged while the rest of the history is restored.

Thanks to @kimnamu for reproducing this on main, finding the 3, null and
{"note": "x"} shapes the first suggested fix missed, and writing the
parametrized test this change extends.

Fixes aws#743
@abhiramshaji-cyber

Copy link
Copy Markdown
Contributor Author

Small update after kimnamu's testing on #743: the blob parse error now logs only the event id instead of the whole payload_item, since dict blobs reach that except now (8da4271). A new test feeds a dict blob and a non JSON string blob and checks neither value lands in the log. I also merged in the latest main, and memory tests and ruff pass locally. Happy to change anything!

This branch is waiting to be deployed

1 waiting deployment
manual-approval — 8da42717 Waiting Nov 20, 2026 by abhiramshaji-cyber via Test (runtime) #1732
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/m PR size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant