Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions src/google/adk/sessions/in_memory_session_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
):
Expand All @@ -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,
Expand Down
44 changes: 44 additions & 0 deletions tests/unittests/sessions/test_session_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down