@@ -846,8 +846,8 @@ def _flush_agent_states_only(self) -> list[dict[str, Any]]:
846846 """Flush only buffered agent states to AgentCore Memory.
847847
848848 Call this method to send any remaining agent state when batch_size > 1.
849- This is called when the agent state buffer reaches batch_size.
850- All agent states are batched into a single create_event () call .
849+ Agent states are grouped by agent_id and sent as separate events so that
850+ each event carries the correct agentId metadata for read_agent () lookups .
851851
852852 Returns:
853853 list[dict[str, Any]]: List of created event responses from AgentCore Memory.
@@ -863,28 +863,31 @@ def _flush_agent_states_only(self) -> list[dict[str, Any]]:
863863
864864 results = []
865865 try :
866- # Convert all agent states to payload format
867- agent_state_payloads = []
866+ # Group agent states by agent_id
867+ agent_groups : dict [ str , list [ dict ]] = {}
868868 for _session_id , session_agent in agent_states_to_send :
869- agent_state_payloads .append ({"blob" : json .dumps (session_agent .to_dict ())})
869+ agent_id = session_agent .agent_id
870+ if agent_id not in agent_groups :
871+ agent_groups [agent_id ] = []
872+ agent_groups [agent_id ].append ({"blob" : json .dumps (session_agent .to_dict ())})
870873
871- # Send all agent states in a single batched create_event call
872- event = self . memory_client . gmdp_client . create_event (
873- memoryId = self .config . memory_id ,
874- actorId = self .config .actor_id ,
875- sessionId = self .config .session_id ,
876- payload = agent_state_payloads ,
877- eventTimestamp = self . _get_monotonic_timestamp () ,
878- metadata = {
879- STATE_TYPE_KEY : { "stringValue" : StateType . AGENT . value },
880- },
881- )
882- results . append ( event )
883- logger . debug (
884- "Flushed %d agent states in batched event: %s" , len ( agent_states_to_send ), event . get ( "eventId" )
885- )
874+ # Send one event per agent_id with correct metadata
875+ for agent_id , payloads in agent_groups . items ():
876+ event = self .memory_client . gmdp_client . create_event (
877+ memoryId = self .config .memory_id ,
878+ actorId = self .config .actor_id ,
879+ sessionId = self . config . session_id ,
880+ payload = payloads ,
881+ eventTimestamp = self . _get_monotonic_timestamp (),
882+ metadata = {
883+ STATE_TYPE_KEY : { "stringValue" : StateType . AGENT . value },
884+ AGENT_ID_KEY : { "stringValue" : agent_id },
885+ },
886+ )
887+ results . append ( event )
888+ logger . debug ( "Flushed %d agent states for agent %s: %s" , len ( payloads ), agent_id , event . get ( "eventId" ) )
886889
887- # Clear agent state buffer only after success
890+ # Clear agent state buffer only after ALL events succeed
888891 with self ._agent_state_lock :
889892 self ._agent_state_buffer .clear ()
890893
0 commit comments