diff --git a/src/google/adk/sessions/database_session_service.py b/src/google/adk/sessions/database_session_service.py index 331683af92..d1dce82ae8 100644 --- a/src/google/adk/sessions/database_session_service.py +++ b/src/google/adk/sessions/database_session_service.py @@ -531,11 +531,14 @@ async def get_session( stmt = stmt.order_by(schema.StorageEvent.timestamp.desc()) - if config and config.num_recent_events: + if config and config.num_recent_events is not None: stmt = stmt.limit(config.num_recent_events) - result = await sql_session.execute(stmt) - storage_events = result.scalars().all() + if config and config.num_recent_events == 0: + storage_events = [] + else: + result = await sql_session.execute(stmt) + storage_events = result.scalars().all() # Fetch states from storage storage_app_state = await sql_session.get( diff --git a/tests/unittests/sessions/test_session_service.py b/tests/unittests/sessions/test_session_service.py index 02f5159a45..3d2117e805 100644 --- a/tests/unittests/sessions/test_session_service.py +++ b/tests/unittests/sessions/test_session_service.py @@ -1067,6 +1067,21 @@ async def test_get_session_with_config(session_service): assert len(events) == num_recent_events assert events[0].timestamp == num_test_events - num_recent_events + 1 + # num_recent_events=0 should return no events (boundary case). + config = GetSessionConfig(num_recent_events=0) + session = await session_service.get_session( + app_name=app_name, user_id=user_id, session_id=session.id, config=config + ) + assert session.events == [] + + # num_recent_events=2 should return the 2 most recent events. + config = GetSessionConfig(num_recent_events=2) + session = await session_service.get_session( + app_name=app_name, user_id=user_id, session_id=session.id, config=config + ) + assert len(session.events) == 2 + assert session.events[0].timestamp == num_test_events - 2 + 1 + # Only expect events after timestamp 4.0 (inclusive), i.e., 2 events. after_timestamp = 4.0 config = GetSessionConfig(after_timestamp=after_timestamp)