diff --git a/src/google/adk/sessions/in_memory_session_service.py b/src/google/adk/sessions/in_memory_session_service.py index d2775cefa4..e7613e8f50 100644 --- a/src/google/adk/sessions/in_memory_session_service.py +++ b/src/google/adk/sessions/in_memory_session_service.py @@ -114,6 +114,7 @@ def _create_session_impl( state: Optional[dict[str, Any]] = None, session_id: Optional[str] = None, ) -> Session: + session_id = session_id.strip() if session_id else None if session_id and self._get_session_impl( app_name=app_name, user_id=user_id, session_id=session_id ): @@ -129,11 +130,7 @@ def _create_session_impl( user_state_delta ) - session_id = ( - session_id.strip() - if session_id and session_id.strip() - else platform_uuid.new_uuid() - ) + session_id = session_id or platform_uuid.new_uuid() session = Session( app_name=app_name, user_id=user_id, diff --git a/tests/unittests/sessions/test_session_service.py b/tests/unittests/sessions/test_session_service.py index 95b9a3f552..9148eab8e0 100644 --- a/tests/unittests/sessions/test_session_service.py +++ b/tests/unittests/sessions/test_session_service.py @@ -1196,6 +1196,50 @@ async def test_create_session_with_existing_id_raises_error(session_service): ) +@pytest.mark.asyncio +async def test_create_session_with_padded_duplicate_id_raises_error(): + """Tests that InMemorySessionService checks the duplicate id after + stripping it, so a whitespace-padded id maps to the same session as its + trimmed form instead of silently overwriting it.""" + service = InMemorySessionService() + app_name = 'my_app' + user_id = 'test_user' + session_id = 'existing_session' + + await service.create_session( + app_name=app_name, + user_id=user_id, + session_id=session_id, + state={'keep': 'original'}, + ) + + with pytest.raises(AlreadyExistsError): + await service.create_session( + app_name=app_name, + user_id=user_id, + session_id=f' {session_id} ', + state={'keep': 'clobbered'}, + ) + + session = await service.get_session( + app_name=app_name, user_id=user_id, session_id=session_id + ) + assert session.state['keep'] == 'original' + + +@pytest.mark.asyncio +async def test_create_session_with_blank_id_generates_one(): + """Tests that a whitespace-only session id is treated the same as no id + at all, rather than being stored verbatim.""" + service = InMemorySessionService() + + session = await service.create_session( + app_name='my_app', user_id='test_user', session_id=' ' + ) + + assert session.id.strip() + + @pytest.mark.asyncio async def test_append_event_bytes(session_service): app_name = 'my_app'